]> git.r.bdr.sh - rbdr/mobius/blobdiff - hotline/server.go
Refactor and cleanup
[rbdr/mobius] / hotline / server.go
index 2ee31cf610627dc66956d04f1a1f74852e9315f8..7b409d5921fae8a1fcdc55fc12d33f2ebc7625ed 100644 (file)
@@ -8,7 +8,6 @@ import (
        "go.uber.org/zap"
        "io"
        "io/ioutil"
-       "log"
        "math/big"
        "math/rand"
        "net"
@@ -21,7 +20,6 @@ import (
        "sync"
        "time"
 
-       "golang.org/x/crypto/bcrypt"
        "gopkg.in/yaml.v2"
 )
 
@@ -50,8 +48,8 @@ type Server struct {
        APIListener  net.Listener
        FileListener net.Listener
 
-       newsReader io.Reader
-       newsWriter io.WriteCloser
+       // newsReader io.Reader
+       // newsWriter io.WriteCloser
 
        outbox chan Transaction
 
@@ -111,7 +109,7 @@ func (s *Server) sendTransaction(t Transaction) error {
        client := s.Clients[uint16(clientID)]
        s.mux.Unlock()
        if client == nil {
-               return errors.New("invalid client")
+               return fmt.Errorf("invalid client id %v", *t.clientID)
        }
        userName := string(client.UserName)
        login := client.Account.Login
@@ -169,7 +167,7 @@ func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln ne
 }
 
 const (
-       agreementFile    = "Agreement.txt"
+       agreementFile = "Agreement.txt"
 )
 
 // NewServer constructs a new Server from a config dir
@@ -278,8 +276,8 @@ func (s *Server) keepaliveHandler() {
                s.mux.Lock()
 
                for _, c := range s.Clients {
-                       *c.IdleTime += idleCheckInterval
-                       if *c.IdleTime > userIdleSeconds && !c.Idle {
+                       c.IdleTime += idleCheckInterval
+                       if c.IdleTime > userIdleSeconds && !c.Idle {
                                c.Idle = true
 
                                flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
@@ -327,15 +325,13 @@ func (s *Server) NewClientConn(conn net.Conn) *ClientConn {
                Connection: conn,
                Server:     s,
                Version:    &[]byte{},
-               IdleTime:   new(int),
-               AutoReply:  &[]byte{},
+               AutoReply:  []byte{},
                Transfers:  make(map[int][]*FileTransfer),
+               Agreed:     false,
        }
        *s.NextGuestID++
        ID := *s.NextGuestID
 
-       *clientConn.IdleTime = 0
-
        binary.BigEndian.PutUint16(*clientConn.ID, ID)
        s.Clients[ID] = clientConn
 
@@ -369,7 +365,7 @@ func (s *Server) DeleteUser(login string) error {
 
        delete(s.Accounts, login)
 
-       return os.Remove(s.ConfigDir + "Users/" + login + ".yaml")
+       return FS.Remove(s.ConfigDir + "Users/" + login + ".yaml")
 }
 
 func (s *Server) connectedUsers() []Field {
@@ -377,7 +373,10 @@ func (s *Server) connectedUsers() []Field {
        defer s.mux.Unlock()
 
        var connectedUsers []Field
-       for _, c := range s.Clients {
+       for _, c := range sortedClients(s.Clients) {
+               if !c.Agreed {
+                       continue
+               }
                user := User{
                        ID:    *c.ID,
                        Icon:  *c.Icon,
@@ -413,7 +412,7 @@ func (s *Server) loadAccounts(userDir string) error {
        }
 
        for _, file := range matches {
-               fh, err := os.Open(file)
+               fh, err := FS.Open(file)
                if err != nil {
                        return err
                }
@@ -431,7 +430,7 @@ func (s *Server) loadAccounts(userDir string) error {
 }
 
 func (s *Server) loadConfig(path string) error {
-       fh, err := os.Open(path)
+       fh, err := FS.Open(path)
        if err != nil {
                return err
        }
@@ -536,9 +535,21 @@ func (s *Server) handleNewConnection(conn net.Conn) error {
        // Show agreement to client
        c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
 
-       if _, err := c.notifyNewUserHasJoined(); err != nil {
-               return err
+       // assume simplified hotline v1.2.3 login flow that does not require agreement
+       if *c.Version == nil {
+               c.Agreed = true
+
+               c.notifyOthers(
+                       *NewTransaction(
+                               tranNotifyChangeUser, nil,
+                               NewField(fieldUserName, c.UserName),
+                               NewField(fieldUserID, *c.ID),
+                               NewField(fieldUserIconID, *c.Icon),
+                               NewField(fieldUserFlags, *c.Flags),
+                       ),
+               )
        }
+
        c.Server.Stats.LoginCount += 1
 
        const readBuffSize = 1024000 // 1KB - TODO: what should this be?
@@ -571,21 +582,6 @@ func (s *Server) handleNewConnection(conn net.Conn) error {
        }
 }
 
-func hashAndSalt(pwd []byte) string {
-       // Use GenerateFromPassword to hash & salt pwd.
-       // MinCost is just an integer constant provided by the bcrypt
-       // package along with DefaultCost & MaxCost.
-       // The cost can be any value you want provided it isn't lower
-       // than the MinCost (4)
-       hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
-       if err != nil {
-               log.Println(err)
-       }
-       // GenerateFromPassword returns a byte slice so we need to
-       // convert the bytes to a string and return it
-       return string(hash)
-}
-
 // NewTransactionRef generates a random ID for the file transfer.  The Hotline client includes this ID
 // in the file transfer request payload, and the file transfer server will use it to map the request
 // to a transfer
@@ -620,13 +616,14 @@ const dlFldrActionNextFile = 3
 func (s *Server) TransferFile(conn net.Conn) error {
        defer func() { _ = conn.Close() }()
 
-       buf := make([]byte, 1024)
-       if _, err := conn.Read(buf); err != nil {
+       txBuf := make([]byte, 16)
+       _, err := conn.Read(txBuf)
+       if err != nil {
                return err
        }
 
        var t transfer
-       _, err := t.Write(buf[:16])
+       _, err = t.Write(txBuf)
        if err != nil {
                return err
        }
@@ -678,11 +675,16 @@ func (s *Server) TransferFile(conn net.Conn) error {
                        }
                }
        case FileUpload:
-               if _, err := conn.Read(buf); err != nil {
+               const buffSize = 1460
+
+               uploadBuf := make([]byte, buffSize)
+
+               _, err := conn.Read(uploadBuf)
+               if err != nil {
                        return err
                }
 
-               ffo := ReadFlattenedFileObject(buf)
+               ffo := ReadFlattenedFileObject(uploadBuf)
                payloadLen := len(ffo.BinaryMarshal())
                fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
 
@@ -702,9 +704,7 @@ func (s *Server) TransferFile(conn net.Conn) error {
 
                defer func() { _ = newFile.Close() }()
 
-               const buffSize = 1024
-
-               if _, err := newFile.Write(buf[payloadLen:]); err != nil {
+               if _, err := newFile.Write(uploadBuf[payloadLen:]); err != nil {
                        return err
                }
                receivedBytes := buffSize - payloadLen
@@ -790,7 +790,7 @@ func (s *Server) TransferFile(conn net.Conn) error {
                        }
 
                        // Read the client's Next Action request
-                       //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
+                       // TODO: Remove hardcoded behavior and switch behaviors based on the next action send
                        if _, err := conn.Read(readBuffer); err != nil {
                                return err
                        }
@@ -830,7 +830,7 @@ func (s *Server) TransferFile(conn net.Conn) error {
                                return err
                        }
 
-                       file, err := os.Open(path)
+                       file, err := FS.Open(path)
                        if err != nil {
                                return err
                        }
@@ -842,7 +842,7 @@ func (s *Server) TransferFile(conn net.Conn) error {
                                bytesRead, err := file.Read(sendBuffer)
                                if err == io.EOF {
                                        // Read the client's Next Action request
-                                       //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
+                                       // TODO: Remove hardcoded behavior and switch behaviors based on the next action send
                                        if _, err := conn.Read(readBuffer); err != nil {
                                                s.Logger.Errorf("error reading next action: %v", err)
                                                return err
@@ -993,7 +993,6 @@ func transferFile(conn net.Conn, dst string) error {
        }
 }
 
-
 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {