Skip to content

Commit 1a3c278

Browse files
authored
Merge pull request #6 from numbleroot/refactoring
First refactoring efforts.
2 parents 2def2af + 481d3c3 commit 1a3c278

File tree

13 files changed

+269
-481
lines changed

13 files changed

+269
-481
lines changed

auth/authenticator.go

Lines changed: 0 additions & 22 deletions
This file was deleted.

auth/file.go

Lines changed: 17 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,17 @@ import (
66
"os"
77
"sort"
88
"strings"
9-
"sync"
109

1110
"github.com/numbleroot/pluto/config"
1211
)
1312

1413
// Structs
1514

16-
// FileAuthenticator contains file based authentication
15+
// File contains file based authentication
1716
// information including the in-memory map of username to
1817
// password mapping.
19-
type FileAuthenticator struct {
20-
lock *sync.RWMutex
21-
File string
22-
Separator string
23-
Users []User
18+
type File struct {
19+
Users []User
2420
}
2521

2622
// User holds name and password from one line from users file.
@@ -30,49 +26,37 @@ type User struct {
3026
Password string
3127
}
3228

33-
// UsersByName defines a list type of users to search efficiently.
34-
type UsersByName []User
35-
3629
// Functions
3730

38-
// Make list of users searchable efficiently.
39-
func (u UsersByName) Len() int { return len(u) }
40-
func (u UsersByName) Swap(i, j int) { u[i], u[j] = u[j], u[i] }
41-
func (u UsersByName) Less(i, j int) bool { return u[i].Name < u[j].Name }
42-
43-
// NewFileAuthenticator takes in a file name and a separator,
31+
// NewFile takes in a file name and a separator,
4432
// reads in specified file and parses it line by line as
4533
// username - password elements separated by the separator.
4634
// At the end, the returned struct contains the information
4735
// and an in-memory map of username mapped to password.
48-
func NewFileAuthenticator(file string, sep string) (*FileAuthenticator, error) {
49-
50-
i := 1
51-
var err error
52-
var handle *os.File
53-
var nextUser User
36+
func NewFile(file string, sep string) (*File, error) {
5437

5538
// Reserve space for the ordered users list in memory.
5639
users := make([]User, 0, 50)
5740

5841
// Open file with authentication information.
59-
handle, err = os.Open(file)
42+
handle, err := os.Open(file)
6043
if err != nil {
61-
return nil, fmt.Errorf("[auth.NewFileAuthenticator] Could not open supplied authentication file: %s\n", err.Error())
44+
return nil, fmt.Errorf("[auth.NewFile] Could not open supplied authentication file: %v", err)
6245
}
6346
defer handle.Close()
6447

6548
// Create a new scanner on top of file handle.
6649
scanner := bufio.NewScanner(handle)
6750

51+
i := 1
6852
// As long as there are lines left, scan them into memory.
6953
for scanner.Scan() {
7054

7155
// Split read line based on separator defined in config file.
7256
userData := strings.Split(scanner.Text(), sep)
7357

7458
// Create new user struct.
75-
nextUser = User{
59+
nextUser := User{
7660
ID: i,
7761
Name: userData[0],
7862
Password: userData[1],
@@ -87,23 +71,22 @@ func NewFileAuthenticator(file string, sep string) (*FileAuthenticator, error) {
8771

8872
// If the scanner ended with an error, report it.
8973
if err := scanner.Err(); err != nil {
90-
return nil, fmt.Errorf("[auth.NewFileAuthenticator] Experienced error while scanning authentication file: %s\n", err.Error())
74+
return nil, fmt.Errorf("[auth.NewFile] Experienced error while scanning authentication file: %v", err)
9175
}
9276

9377
// Sort users list to search it efficiently later on.
94-
sort.Sort(UsersByName(users))
78+
sort.Slice(users, func(i, j int) bool {
79+
return users[i].Name < users[j].Name
80+
})
9581

96-
return &FileAuthenticator{
97-
lock: new(sync.RWMutex),
98-
File: file,
99-
Separator: sep,
100-
Users: users,
82+
return &File{
83+
Users: users,
10184
}, nil
10285
}
10386

10487
// GetWorkerForUser returns the name of the worker node
10588
// that is responsible for handling the user's mailbox.
106-
func (f *FileAuthenticator) GetWorkerForUser(workers map[string]config.Worker, id int) (string, error) {
89+
func (f *File) GetWorkerForUser(workers map[string]config.Worker, id int) (string, error) {
10790

10891
for name, worker := range workers {
10992

@@ -122,12 +105,7 @@ func (f *FileAuthenticator) GetWorkerForUser(workers map[string]config.Worker, i
122105
// process by taking supplied credentials and attempting
123106
// to find a matching entry the in-memory list taken from
124107
// the authentication file.
125-
func (f *FileAuthenticator) AuthenticatePlain(username string, password string, clientAddr string) (int, string, error) {
126-
127-
// This routine has to be safe for concurrent usage,
128-
// therefore lock the struct on entry.
129-
f.lock.RLock()
130-
defer f.lock.RUnlock()
108+
func (f *File) AuthenticatePlain(username string, password string, clientAddr string) (int, string, error) {
131109

132110
// Search in user list for user matching supplied name.
133111
i := sort.Search(len(f.Users), func(i int) bool {

comm/receiver.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -507,8 +507,10 @@ func (recv *Receiver) ApplyStoredMsgs() {
507507
// Calculate size of needed buffer.
508508
bufferSize := logSize - curOffset
509509

510-
// Account for case when offset reached end of log file.
511-
if logSize == curOffset {
510+
// Account for case when offset reached end of log file
511+
// or accidentally the current offset is bigger than the
512+
// log file's size.
513+
if logSize <= curOffset {
512514

513515
// Reset position to beginning of file.
514516
_, err = recv.updLog.Seek(0, os.SEEK_SET)
@@ -562,7 +564,6 @@ func (recv *Receiver) ApplyStoredMsgs() {
562564
// If not, set indicator to false.
563565
if (msg.VClock[msg.Sender] != recv.vclock[msg.Sender]) &&
564566
(msg.VClock[msg.Sender] != (recv.vclock[msg.Sender] + 1)) {
565-
log.Printf("[comm.ApplyStoredMsgs] %s: not applying message because leap in causality and messages missing.\n", recv.name)
566567
applyMsg = false
567568
}
568569

@@ -574,7 +575,6 @@ func (recv *Receiver) ApplyStoredMsgs() {
574575
// and check if they do not exceed the locally stored
575576
// values for these nodes.
576577
if value > recv.vclock[node] {
577-
log.Printf("[comm.ApplyStoredMsgs] %s: not applying message because other elements exceeded.\n", recv.name)
578578
applyMsg = false
579579
break
580580
}
@@ -597,8 +597,6 @@ func (recv *Receiver) ApplyStoredMsgs() {
597597

598598
// Wait for done signal from node.
599599
<-recv.doneCRDTUpdChan
600-
} else {
601-
log.Printf("[comm.ApplyStoredMsgs] %s: message was a duplicate, already seen.\n", recv.name)
602600
}
603601

604602
for node, value := range msg.VClock {

crypto/config.go

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@ import (
1616
// will be used when verifying certificates.
1717
func NewPublicTLSConfig(certPath string, keyPath string) (*tls.Config, error) {
1818

19-
var err error
20-
2119
// Define very strict defaults for public TLS usage.
2220
// Good parts of them were taken from the excellent post:
2321
// "Achieving a Perfect SSL Labs Score with Go":
@@ -38,10 +36,11 @@ func NewPublicTLSConfig(certPath string, keyPath string) (*tls.Config, error) {
3836

3937
// Put certificate specified via arguments as the
4038
// only certificate into config.
41-
config.Certificates[0], err = tls.LoadX509KeyPair(certPath, keyPath)
39+
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
4240
if err != nil {
43-
return nil, fmt.Errorf("[crypto.NewPublicTLSConfig] Failed to load TLS cert and key: %s\n", err.Error())
41+
return nil, fmt.Errorf("[crypto.NewPublicTLSConfig] Failed to load TLS cert and key: %v", err)
4442
}
43+
config.Certificates[0] = cert
4544

4645
// Build Common Name (CN) and Subject Alternate
4746
// Name (SAN) from supplied certificate.
@@ -56,8 +55,6 @@ func NewPublicTLSConfig(certPath string, keyPath string) (*tls.Config, error) {
5655
// and requires all nodes to verify each other by TLS means.
5756
func NewInternalTLSConfig(certPath string, keyPath string, rootCertPath string) (*tls.Config, error) {
5857

59-
var err error
60-
6158
// Define very strict defaults for internal TLS usage.
6259
// Good parts of them were taken from the excellent post:
6360
// "Achieving a Perfect SSL Labs Score with Go":
@@ -84,25 +81,26 @@ func NewInternalTLSConfig(certPath string, keyPath string, rootCertPath string)
8481
// via path in arguments.
8582
rootCert, err := ioutil.ReadFile(rootCertPath)
8683
if err != nil {
87-
return nil, fmt.Errorf("[crypto.NewInternalTLSConfig] Reading root certificate into memory failed with: %s\n", err.Error())
84+
return nil, fmt.Errorf("[crypto.NewInternalTLSConfig] Reading root certificate into memory failed with: %v", err)
8885
}
8986

9087
// Append root certificate to root CA pool.
9188
if ok := config.RootCAs.AppendCertsFromPEM(rootCert); !ok {
92-
return nil, fmt.Errorf("[crypto.NewInternalTLSConfig] Failed to append root certificate to root CA pool: %s\n", err.Error())
89+
return nil, fmt.Errorf("[crypto.NewInternalTLSConfig] Failed to append root certificate to root CA pool: %v", err)
9390
}
9491

9592
// Append root certificate to client CA pool.
9693
if ok := config.ClientCAs.AppendCertsFromPEM(rootCert); !ok {
97-
return nil, fmt.Errorf("[crypto.NewInternalTLSConfig] Failed to append root certificate to client CA pool: %s\n", err.Error())
94+
return nil, fmt.Errorf("[crypto.NewInternalTLSConfig] Failed to append root certificate to client CA pool: %v", err)
9895
}
9996

10097
// Put certificate specified via arguments as the
10198
// only certificate into config.
102-
config.Certificates[0], err = tls.LoadX509KeyPair(certPath, keyPath)
99+
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
103100
if err != nil {
104-
return nil, fmt.Errorf("[crypto.NewInternalTLSConfig] Failed to load TLS cert and key: %s\n", err.Error())
101+
return nil, fmt.Errorf("[crypto.NewInternalTLSConfig] Failed to load TLS cert and key: %v", err)
105102
}
103+
config.Certificates[0] = cert
106104

107105
// Build Common Name (CN) and Subject Alternate
108106
// Name (SAN) from supplied certificate.
Lines changed: 5 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
package imap_test
1+
package main
22

33
import (
44
"bufio"
55
"fmt"
66
"log"
7-
"os"
87
"testing"
98

109
"crypto/tls"
@@ -67,35 +66,12 @@ var loginTests = []struct {
6766

6867
// Functions
6968

70-
func TestMain(m *testing.M) {
71-
72-
var err error
73-
74-
// Create needed test environment.
75-
testEnv, err = utils.CreateTestEnv("../test-config.toml")
76-
if err != nil {
77-
log.Fatal(err)
78-
}
79-
80-
// Run all nodes in background.
81-
utils.RunAllNodes(testEnv, "worker-1")
82-
83-
// Run all tests of this package.
84-
success := m.Run()
85-
86-
// Tear down test setup.
87-
utils.TearDownNormalSetup(testEnv)
88-
89-
// Return with test return value.
90-
os.Exit(success)
91-
}
92-
9369
// TestCapability executes a black-box table test on the
9470
// implemented Capability() function.
9571
func TestCapability(t *testing.T) {
9672

9773
// Connect to IMAP distributor.
98-
conn, err := tls.Dial("tcp", (testEnv.Config.Distributor.PublicIP + ":" + testEnv.Config.Distributor.Port), testEnv.TLSConfig)
74+
conn, err := tls.Dial("tcp", testEnv.Addr, testEnv.TLSConfig)
9975
if err != nil {
10076
t.Fatalf("[imap.TestCapability] Error during connection attempt to IMAP distributor: %s\n", err.Error())
10177
}
@@ -159,7 +135,7 @@ func TestLogout(t *testing.T) {
159135
var answer string
160136

161137
// Connect to IMAP distributor.
162-
conn, err := tls.Dial("tcp", (testEnv.Config.Distributor.PublicIP + ":" + testEnv.Config.Distributor.Port), testEnv.TLSConfig)
138+
conn, err := tls.Dial("tcp", testEnv.Addr, testEnv.TLSConfig)
163139
if err != nil {
164140
t.Fatalf("[imap.TestLogout] Error during connection attempt to IMAP distributor: %s\n", err.Error())
165141
}
@@ -218,7 +194,7 @@ func TestLogout(t *testing.T) {
218194
func TestStartTLS(t *testing.T) {
219195

220196
// Connect to IMAP server.
221-
conn, err := tls.Dial("tcp", (testEnv.Config.Distributor.PublicIP + ":" + testEnv.Config.Distributor.Port), testEnv.TLSConfig)
197+
conn, err := tls.Dial("tcp", testEnv.Addr, testEnv.TLSConfig)
222198
if err != nil {
223199
t.Fatalf("[imap.TestStartTLS] Error during connection attempt to IMAP server: %s\n", err.Error())
224200
}
@@ -263,7 +239,7 @@ func TestStartTLS(t *testing.T) {
263239
func TestLogin(t *testing.T) {
264240

265241
// Connect to IMAP distributor.
266-
conn, err := tls.Dial("tcp", (testEnv.Config.Distributor.PublicIP + ":" + testEnv.Config.Distributor.Port), testEnv.TLSConfig)
242+
conn, err := tls.Dial("tcp", testEnv.Addr, testEnv.TLSConfig)
267243
if err != nil {
268244
t.Fatalf("[imap.TestLogin] Error during connection attempt to IMAP distributor: %s\n", err.Error())
269245
}

0 commit comments

Comments
 (0)