X-Git-Url: https://git.r.bdr.sh/rbdr/mobius/blobdiff_plain/92a7e455a347e5be7fb69b6846b9f27ca698ae12..85767504e4dc622c5ff469733e49c0cebcee57f1:/hotline/server.go?ds=sidebyside diff --git a/hotline/server.go b/hotline/server.go index 2ee31cf..90b7ea0 100644 --- a/hotline/server.go +++ b/hotline/server.go @@ -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 @@ -93,7 +91,7 @@ func (s *Server) ServeFileTransfers(ln net.Listener) error { } go func() { - if err := s.TransferFile(conn); err != nil { + if err := s.handleFileTransfer(conn); err != nil { s.Logger.Errorw("file transfer error", "reason", err) } }() @@ -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 @@ -617,16 +613,22 @@ const dlFldrActionSendFile = 1 const dlFldrActionResumeFile = 2 const dlFldrActionNextFile = 3 -func (s *Server) TransferFile(conn net.Conn) error { - defer func() { _ = conn.Close() }() +// handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection +func (s *Server) handleFileTransfer(conn io.ReadWriteCloser) error { + defer func() { + if err := conn.Close(); err != nil { + s.Logger.Errorw("error closing connection", "error", err) + } + }() - 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 } @@ -650,7 +652,7 @@ func (s *Server) TransferFile(conn net.Conn) error { return err } - s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String()) + s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber) // Start by sending flat file object to client if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { @@ -678,60 +680,20 @@ func (s *Server) TransferFile(conn net.Conn) error { } } case FileUpload: - if _, err := conn.Read(buf); err != nil { - return err - } - - ffo := ReadFlattenedFileObject(buf) - payloadLen := len(ffo.BinaryMarshal()) - fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) - destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName) - s.Logger.Infow( - "File upload started", - "transactionRef", fileTransfer.ReferenceNumber, - "RemoteAddr", conn.RemoteAddr().String(), - "size", fileSize, - "dstFile", destinationFile, - ) - - newFile, err := os.Create(destinationFile) + newFile, err := FS.Create(destinationFile) if err != nil { return err } - defer func() { _ = newFile.Close() }() - const buffSize = 1024 + s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile) - if _, err := newFile.Write(buf[payloadLen:]); err != nil { - return err + if err := receiveFile(conn, newFile, nil); err != nil { + s.Logger.Errorw("file upload error", "error", err) } - receivedBytes := buffSize - payloadLen - - for { - if (fileSize - receivedBytes) < buffSize { - s.Logger.Infow( - "File upload complete", - "transactionRef", fileTransfer.ReferenceNumber, - "RemoteAddr", conn.RemoteAddr().String(), - "size", fileSize, - "dstFile", destinationFile, - ) - - if _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)); err != nil { - return fmt.Errorf("file transfer failed: %s", err) - } - return nil - } - // Copy N bytes from conn to upload file - n, err := io.CopyN(newFile, conn, buffSize) - if err != nil { - return err - } - receivedBytes += int(n) - } + s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile) case FolderDownload: // Folder Download flow: // 1. Get filePath from the transfer @@ -767,22 +729,28 @@ func (s *Server) TransferFile(conn net.Conn) error { basePathLen := len(fullFilePath) - readBuffer := make([]byte, 1024) + s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber) - s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr()) + nextAction := make([]byte, 2) + if _, err := conn.Read(nextAction); err != nil { + return err + } i := 0 - _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error { + err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } i += 1 - subPath := path[basePathLen:] + subPath := path[basePathLen+1:] s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir()) - fileHeader := NewFileHeader(subPath, info.IsDir()) - if i == 1 { return nil } + fileHeader := NewFileHeader(subPath, info.IsDir()) + // Send the file header to client if _, err := conn.Write(fileHeader.Payload()); err != nil { s.Logger.Errorf("error sending file header: %v", err) @@ -790,12 +758,14 @@ 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 - if _, err := conn.Read(readBuffer); err != nil { + if _, err := conn.Read(nextAction); err != nil { return err } + if nextAction[1] == 3 { + return nil + } - s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", readBuffer[0:2])) + s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2])) if info.IsDir() { return nil @@ -814,7 +784,6 @@ func (s *Server) TransferFile(conn net.Conn) error { s.Logger.Infow("File download started", "fileName", info.Name(), "transactionRef", fileTransfer.ReferenceNumber, - "RemoteAddr", conn.RemoteAddr().String(), "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()), ) @@ -824,39 +793,33 @@ func (s *Server) TransferFile(conn net.Conn) error { return err } - // Send file bytes to client + // Send ffo bytes to client 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.BinaryMarshal()) + // Copy N bytes from file to connection + _, err = io.CopyN(conn, file, int64(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize[:]))) + if err != nil { + return err + } + file.Close() - 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 - if _, err := conn.Read(readBuffer); err != nil { - s.Logger.Errorf("error reading next action: %v", err) - return err - } - break - } + // TODO: optionally send resource fork header and resource fork data - sentBytes, readErr := conn.Write(sendBuffer[:bytesRead]) - totalBytesSent += sentBytes - if readErr != nil { - return err - } + // Read the client's Next Action request + if _, err := conn.Read(nextAction); err != nil { + return err } - return nil + // TODO: switch behavior based on possible next action + + return err }) case FolderUpload: @@ -867,7 +830,6 @@ func (s *Server) TransferFile(conn net.Conn) error { s.Logger.Infow( "Folder upload started", "transactionRef", fileTransfer.ReferenceNumber, - "RemoteAddr", conn.RemoteAddr().String(), "dstPath", dstPath, "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize), "FolderItemCount", fileTransfer.FolderItemCount, @@ -881,8 +843,6 @@ func (s *Server) TransferFile(conn net.Conn) error { } } - readBuffer := make([]byte, 1024) - // Begin the folder upload flow by sending the "next file action" to client if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { return err @@ -891,8 +851,10 @@ func (s *Server) TransferFile(conn net.Conn) error { fileSize := make([]byte, 4) itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount) + readBuffer := make([]byte, 1024) for i := uint16(0); i < itemCount; i++ { - if _, err := conn.Read(readBuffer); err != nil { + _, err := conn.Read(readBuffer) + if err != nil { return err } fu := readFolderUpload(readBuffer) @@ -900,7 +862,6 @@ func (s *Server) TransferFile(conn net.Conn) error { s.Logger.Infow( "Folder upload continued", "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber), - "RemoteAddr", conn.RemoteAddr().String(), "FormattedPath", fu.FormattedPath(), "IsFolder", fmt.Sprintf("%x", fu.IsFolder), "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]), @@ -928,14 +889,21 @@ func (s *Server) TransferFile(conn net.Conn) error { } if _, err := conn.Read(fileSize); err != nil { - fmt.Println("Error reading:", err.Error()) // TODO: handle + return err } - s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize) + filePath := dstPath + "/" + fu.FormattedPath() + s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "totalFiles", itemCount, "fileSize", binary.BigEndian.Uint32(fileSize)) - if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil { + newFile, err := FS.Create(filePath) + if err != nil { + return err + } + + if err := receiveFile(conn, newFile, ioutil.Discard); err != nil { s.Logger.Error(err) } + _ = newFile.Close() // Tell client to send next file if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { @@ -943,11 +911,6 @@ func (s *Server) TransferFile(conn net.Conn) error { return err } - // Client sends "MACR" after the file. Read and discard. - // TODO: This doesn't seem to be documented. What is this? Maybe resource fork? - if _, err := conn.Read(readBuffer); err != nil { - return err - } } } s.Logger.Infof("Folder upload complete") @@ -956,44 +919,6 @@ func (s *Server) TransferFile(conn net.Conn) error { return nil } -func transferFile(conn net.Conn, dst string) error { - const buffSize = 1024 - buf := make([]byte, buffSize) - - // Read first chunk of bytes from conn; this will be the Flat File Object and initial chunk of file bytes - if _, err := conn.Read(buf); err != nil { - return err - } - ffo := ReadFlattenedFileObject(buf) - payloadLen := len(ffo.BinaryMarshal()) - fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) - - newFile, err := os.Create(dst) - if err != nil { - return err - } - defer func() { _ = newFile.Close() }() - if _, err := newFile.Write(buf[payloadLen:]); err != nil { - return err - } - receivedBytes := buffSize - payloadLen - - for { - if (fileSize - receivedBytes) < buffSize { - _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)) - return err - } - - // Copy N bytes from conn to upload file - n, err := io.CopyN(newFile, conn, buffSize) - if err != nil { - return err - } - receivedBytes += int(n) - } -} - - // 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) {