]> git.r.bdr.sh - rbdr/mobius/blobdiff - hotline/server.go
Misc cleanup
[rbdr/mobius] / hotline / server.go
index e51f673bf1c5c57446008fbb65be1a63fd83c500..1da2859ba479773c65d3176ab3c87f41e34459b3 100644 (file)
@@ -1,7 +1,6 @@
 package hotline
 
 import (
-       "bytes"
        "context"
        "encoding/binary"
        "errors"
@@ -9,7 +8,6 @@ import (
        "go.uber.org/zap"
        "io"
        "io/ioutil"
-       "log"
        "math/big"
        "math/rand"
        "net"
@@ -22,7 +20,6 @@ import (
        "sync"
        "time"
 
-       "golang.org/x/crypto/bcrypt"
        "gopkg.in/yaml.v2"
 )
 
@@ -33,7 +30,6 @@ const (
 )
 
 type Server struct {
-       Interface     string
        Port          int
        Accounts      map[string]*Account
        Agreement     []byte
@@ -52,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
 
@@ -113,15 +109,19 @@ 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)
+       userName := string(client.UserName)
        login := client.Account.Login
 
        handler := TransactionHandlers[requestNum]
 
+       b, err := t.MarshalBinary()
+       if err != nil {
+               return err
+       }
        var n int
-       if n, err = client.Connection.Write(t.Payload()); err != nil {
+       if n, err = client.Connection.Write(b); err != nil {
                return err
        }
        s.Logger.Debugw("Sent Transaction",
@@ -167,9 +167,7 @@ func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln ne
 }
 
 const (
-       agreementFile    = "Agreement.txt"
-       messageBoardFile = "MessageBoard.txt"
-       threadedNewsFile = "ThreadedNews.yaml"
+       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)))
@@ -290,7 +288,7 @@ func (s *Server) keepaliveHandler() {
                                        tranNotifyChangeUser,
                                        NewField(fieldUserID, *c.ID),
                                        NewField(fieldUserFlags, *c.Flags),
-                                       NewField(fieldUserName, *c.UserName),
+                                       NewField(fieldUserName, c.UserName),
                                        NewField(fieldUserIconID, *c.Icon),
                                )
                        }
@@ -323,19 +321,17 @@ func (s *Server) NewClientConn(conn net.Conn) *ClientConn {
                ID:         &[]byte{0, 0},
                Icon:       &[]byte{0, 0},
                Flags:      &[]byte{0, 0},
-               UserName:   &[]byte{},
+               UserName:   []byte{},
                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
 
@@ -377,12 +373,15 @@ 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,
                        Flags: *c.Flags,
-                       Name:  string(*c.UserName),
+                       Name:  string(c.UserName),
                }
                connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
        }
@@ -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
        }
@@ -497,15 +496,19 @@ func (s *Server) handleNewConnection(conn net.Conn) error {
 
        // If authentication fails, send error reply and close connection
        if !c.Authenticate(login, encodedPassword) {
-               rep := c.NewErrReply(clientLogin, "Incorrect login.")
-               if _, err := conn.Write(rep.Payload()); err != nil {
+               t := c.NewErrReply(clientLogin, "Incorrect login.")
+               b, err := t.MarshalBinary()
+               if err != nil {
+                       return err
+               }
+               if _, err := conn.Write(b); err != nil {
                        return err
                }
                return fmt.Errorf("incorrect login")
        }
 
        if clientLogin.GetField(fieldUserName).Data != nil {
-               *c.UserName = clientLogin.GetField(fieldUserName).Data
+               c.UserName = clientLogin.GetField(fieldUserName).Data
        }
 
        if clientLogin.GetField(fieldUserIconID).Data != nil {
@@ -532,13 +535,17 @@ 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
+               if _, err := c.notifyNewUserHasJoined(); err != nil {
+                       return err
+               }
        }
+
        c.Server.Stats.LoginCount += 1
 
        const readBuffSize = 1024000 // 1KB - TODO: what should this be?
-       const maxTranSize = 1024000
        tranBuff := make([]byte, 0)
        tReadlen := 0
        // Infinite loop where take action on incoming client requests until the connection is closed
@@ -568,21 +575,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
@@ -622,7 +614,8 @@ func (s *Server) TransferFile(conn net.Conn) error {
                return err
        }
 
-       t, err := NewReadTransfer(buf)
+       var t transfer
+       _, err := t.Write(buf[:16])
        if err != nil {
                return err
        }
@@ -632,11 +625,15 @@ func (s *Server) TransferFile(conn net.Conn) error {
 
        switch fileTransfer.Type {
        case FileDownload:
-               fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+string(fileTransfer.FilePath), string(fileTransfer.FileName))
+               fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
+               if err != nil {
+                       return err
+               }
 
                ffo, err := NewFlattenedFileObject(
-                       s.Config.FileRoot+string(fileTransfer.FilePath),
-                       string(fileTransfer.FileName),
+                       s.Config.FileRoot,
+                       fileTransfer.FilePath,
+                       fileTransfer.FileName,
                )
                if err != nil {
                        return err
@@ -645,11 +642,11 @@ func (s *Server) TransferFile(conn net.Conn) error {
                s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String())
 
                // Start by sending flat file object to client
-               if _, err := conn.Write(ffo.Payload()); err != nil {
+               if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
                        return err
                }
 
-               file, err := os.Open(fullFilePath)
+               file, err := FS.Open(fullFilePath)
                if err != nil {
                        return err
                }
@@ -675,7 +672,7 @@ func (s *Server) TransferFile(conn net.Conn) error {
                }
 
                ffo := ReadFlattenedFileObject(buf)
-               payloadLen := len(ffo.Payload())
+               payloadLen := len(ffo.BinaryMarshal())
                fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
 
                destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
@@ -726,7 +723,7 @@ func (s *Server) TransferFile(conn net.Conn) error {
                }
        case FolderDownload:
                // Folder Download flow:
-               // 1. Get filePath from the Transfer
+               // 1. Get filePath from the transfer
                // 2. Iterate over files
                // 3. For each file:
                //       Send file header to client
@@ -752,8 +749,10 @@ func (s *Server) TransferFile(conn net.Conn) error {
                //
                // This notifies the server to send the next item header
 
-               fh := NewFilePath(fileTransfer.FilePath)
-               fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+fh.String(), string(fileTransfer.FileName))
+               fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
+               if err != nil {
+                       return err
+               }
 
                basePathLen := len(fullFilePath)
 
@@ -764,7 +763,7 @@ func (s *Server) TransferFile(conn net.Conn) error {
                i := 0
                _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error {
                        i += 1
-                       subPath := path[basePathLen-2:]
+                       subPath := path[basePathLen:]
                        s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
 
                        fileHeader := NewFileHeader(subPath, info.IsDir())
@@ -780,9 +779,8 @@ 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 {
-                               s.Logger.Errorf("error reading next action: %v", err)
                                return err
                        }
 
@@ -793,9 +791,12 @@ func (s *Server) TransferFile(conn net.Conn) error {
                        }
 
                        splitPath := strings.Split(path, "/")
-                       //strings.Join(splitPath[:len(splitPath)-1], "/")
 
-                       ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), info.Name())
+                       ffo, err := NewFlattenedFileObject(
+                               strings.Join(splitPath[:len(splitPath)-1], "/"),
+                               nil,
+                               []byte(info.Name()),
+                       )
                        if err != nil {
                                return err
                        }
@@ -813,24 +814,24 @@ func (s *Server) TransferFile(conn net.Conn) error {
                        }
 
                        // Send file bytes to client
-                       if _, err := conn.Write(ffo.Payload()); err != nil {
+                       if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
                                s.Logger.Error(err)
                                return err
                        }
 
-                       file, err := os.Open(path)
+                       file, err := FS.Open(path)
                        if err != nil {
                                return err
                        }
 
                        sendBuffer := make([]byte, 1048576)
-                       totalBytesSent := len(ffo.Payload())
+                       totalBytesSent := len(ffo.BinaryMarshal())
 
                        for {
                                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
@@ -848,20 +849,23 @@ func (s *Server) TransferFile(conn net.Conn) error {
                })
 
        case FolderUpload:
-               dstPath := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
+               dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
+               if err != nil {
+                       return err
+               }
                s.Logger.Infow(
                        "Folder upload started",
                        "transactionRef", fileTransfer.ReferenceNumber,
                        "RemoteAddr", conn.RemoteAddr().String(),
                        "dstPath", dstPath,
-                       "TransferSize", fileTransfer.TransferSize,
+                       "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
                        "FolderItemCount", fileTransfer.FolderItemCount,
                )
 
                // Check if the target folder exists.  If not, create it.
-               if _, err := os.Stat(dstPath); os.IsNotExist(err) {
-                       s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
-                       if err := os.Mkdir(dstPath, 0777); err != nil {
+               if _, err := FS.Stat(dstPath); os.IsNotExist(err) {
+                       s.Logger.Infow("Creating target path", "dstPath", dstPath)
+                       if err := FS.Mkdir(dstPath, 0777); err != nil {
                                s.Logger.Error(err)
                        }
                }
@@ -888,10 +892,10 @@ func (s *Server) TransferFile(conn net.Conn) error {
                                "RemoteAddr", conn.RemoteAddr().String(),
                                "FormattedPath", fu.FormattedPath(),
                                "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
-                               "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount),
+                               "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
                        )
 
-                       if bytes.Equal(fu.IsFolder, []byte{0, 1}) {
+                       if fu.IsFolder == [2]byte{0, 1} {
                                if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
                                        s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
                                        if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
@@ -950,7 +954,7 @@ func transferFile(conn net.Conn, dst string) error {
                return err
        }
        ffo := ReadFlattenedFileObject(buf)
-       payloadLen := len(ffo.Payload())
+       payloadLen := len(ffo.BinaryMarshal())
        fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
 
        newFile, err := os.Create(dst)
@@ -978,52 +982,6 @@ func transferFile(conn net.Conn, dst string) error {
        }
 }
 
-// 00 28 // DataSize
-// 00 00 // IsFolder
-// 00 02 // PathItemCount
-//
-// 00 00
-// 09
-// 73 75 62 66 6f 6c 64 65 72 // "subfolder"
-//
-// 00 00
-// 15
-// 73 75 62 66 6f 6c 64 65 72 2d 74 65 73 74 66 69 6c 65 2d 35 6b // "subfolder-testfile-5k"
-func readFolderUpload(buf []byte) folderUpload {
-       dataLen := binary.BigEndian.Uint16(buf[0:2])
-
-       fu := folderUpload{
-               DataSize:      buf[0:2], // Size of this structure (not including data size element itself)
-               IsFolder:      buf[2:4],
-               PathItemCount: buf[4:6],
-               FileNamePath:  buf[6 : dataLen+2],
-       }
-
-       return fu
-}
-
-type folderUpload struct {
-       DataSize      []byte
-       IsFolder      []byte
-       PathItemCount []byte
-       FileNamePath  []byte
-}
-
-func (fu *folderUpload) FormattedPath() string {
-       pathItemLen := binary.BigEndian.Uint16(fu.PathItemCount)
-
-       var pathSegments []string
-       pathData := fu.FileNamePath
-
-       for i := uint16(0); i < pathItemLen; i++ {
-               segLen := pathData[2]
-               pathSegments = append(pathSegments, string(pathData[3:3+segLen]))
-               pathData = pathData[3+segLen:]
-       }
-
-       return strings.Join(pathSegments, pathSeparator)
-}
-
 // 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) {