X-Git-Url: https://git.r.bdr.sh/rbdr/mobius/blobdiff_plain/f6d08d0ad9198b4d5a9ee5fcf108015f927fd657..40414f9295dd301f1c714bc3067392b7cc8f8427:/hotline/server.go?ds=sidebyside diff --git a/hotline/server.go b/hotline/server.go index 1429c62..d5da458 100644 --- a/hotline/server.go +++ b/hotline/server.go @@ -1,15 +1,15 @@ package hotline import ( - "bytes" "context" "encoding/binary" "errors" "fmt" + "github.com/go-playground/validator/v10" "go.uber.org/zap" "io" + "io/fs" "io/ioutil" - "log" "math/big" "math/rand" "net" @@ -22,8 +22,7 @@ import ( "sync" "time" - "golang.org/x/crypto/bcrypt" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) const ( @@ -33,7 +32,6 @@ const ( ) type Server struct { - Interface string Port int Accounts map[string]*Account Agreement []byte @@ -46,14 +44,14 @@ type Server struct { Logger *zap.SugaredLogger PrivateChats map[uint32]*PrivateChat NextGuestID *uint16 - TrackerPassID []byte + TrackerPassID [4]byte Stats *Stats APIListener net.Listener FileListener net.Listener - newsReader io.Reader - newsWriter io.WriteCloser + // newsReader io.Reader + // newsWriter io.WriteCloser outbox chan Transaction @@ -95,7 +93,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) } }() @@ -113,15 +111,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", @@ -130,7 +132,7 @@ func (s *Server) sendTransaction(t Transaction) error { "IsReply", t.IsReply, "type", handler.Name, "sentBytes", n, - "remoteAddr", client.Connection.RemoteAddr(), + "remoteAddr", client.RemoteAddr, ) return nil } @@ -155,7 +157,7 @@ func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln ne } }() go func() { - if err := s.handleNewConnection(conn); err != nil { + if err := s.handleNewConnection(conn, conn.RemoteAddr().String()); err != nil { if err == io.EOF { s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr()) } else { @@ -167,9 +169,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 @@ -187,7 +187,6 @@ func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredL outbox: make(chan Transaction), Stats: &Stats{StartTime: time.Now()}, ThreadedNews: &ThreadedNews{}, - TrackerPassID: make([]byte, 4), } ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort)) @@ -207,7 +206,7 @@ func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredL } // generate a new random passID for tracker registration - if _, err := rand.Read(server.TrackerPassID); err != nil { + if _, err := rand.Read(server.TrackerPassID[:]); err != nil { return nil, err } @@ -237,21 +236,26 @@ func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredL *server.NextGuestID = 1 if server.Config.EnableTrackerRegistration { + server.Logger.Infow( + "Tracker registration enabled", + "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency), + "trackers", server.Config.Trackers, + ) + go func() { for { - tr := TrackerRegistration{ - Port: []byte{0x15, 0x7c}, + tr := &TrackerRegistration{ UserCount: server.userCount(), - PassID: server.TrackerPassID, + PassID: server.TrackerPassID[:], Name: server.Config.Name, Description: server.Config.Description, } + binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port)) for _, t := range server.Config.Trackers { - server.Logger.Infof("Registering with tracker %v", t) - if err := register(t, tr); err != nil { server.Logger.Errorw("unable to register with tracker %v", "error", err) } + server.Logger.Infow("Sent Tracker registration", "data", tr) } time.Sleep(trackerUpdateFrequency * time.Second) @@ -278,8 +282,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 +294,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), ) } @@ -315,7 +319,7 @@ func (s *Server) writeThreadedNews() error { return err } -func (s *Server) NewClientConn(conn net.Conn) *ClientConn { +func (s *Server) NewClientConn(conn net.Conn, remoteAddr string) *ClientConn { s.mux.Lock() defer s.mux.Unlock() @@ -323,19 +327,18 @@ 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, + RemoteAddr: remoteAddr, } *s.NextGuestID++ ID := *s.NextGuestID - *clientConn.IdleTime = 0 - binary.BigEndian.PutUint16(*clientConn.ID, ID) s.Clients[ID] = clientConn @@ -359,7 +362,39 @@ func (s *Server) NewUser(login, name, password string, access []byte) error { } s.Accounts[login] = &account - return ioutil.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666) + return FS.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666) +} + +func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error { + s.mux.Lock() + defer s.mux.Unlock() + + fmt.Printf("login: %v, newLogin: %v: ", login, newLogin) + + // update renames the user login + if login != newLogin { + err := os.Rename(s.ConfigDir+"Users/"+login+".yaml", s.ConfigDir+"Users/"+newLogin+".yaml") + if err != nil { + return err + } + s.Accounts[newLogin] = s.Accounts[login] + delete(s.Accounts, login) + } + + account := s.Accounts[newLogin] + account.Access = &access + account.Name = name + account.Password = password + + out, err := yaml.Marshal(&account) + if err != nil { + return err + } + if err := os.WriteFile(s.ConfigDir+"Users/"+newLogin+".yaml", out, 0666); err != nil { + return err + } + + return nil } // DeleteUser deletes the user account @@ -369,7 +404,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,12 +412,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())) } @@ -396,7 +434,6 @@ func (s *Server) loadThreadedNews(threadedNewsPath string) error { return err } decoder := yaml.NewDecoder(fh) - decoder.SetStrict(true) return decoder.Decode(s.ThreadedNews) } @@ -413,14 +450,13 @@ 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 } account := Account{} decoder := yaml.NewDecoder(fh) - decoder.SetStrict(true) if err := decoder.Decode(&account); err != nil { return err } @@ -431,17 +467,22 @@ 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 } decoder := yaml.NewDecoder(fh) - decoder.SetStrict(true) err = decoder.Decode(s.Config) if err != nil { return err } + + validate := validator.New() + err = validate.Struct(s.Config) + if err != nil { + return err + } return nil } @@ -449,17 +490,25 @@ const ( minTransactionLen = 22 // minimum length of any transaction ) -// handleNewConnection takes a new net.Conn and performs the initial login sequence -func (s *Server) handleNewConnection(conn net.Conn) error { - handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length - if _, err := conn.Read(handshakeBuf); err != nil { - return err +// dontPanic recovers and logs panics instead of crashing +// TODO: remove this after known issues are fixed +func dontPanic(logger *zap.SugaredLogger) { + if r := recover(); r != nil { + fmt.Println("stacktrace from panic: \n" + string(debug.Stack())) + logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack())) } - if err := Handshake(conn, handshakeBuf[:12]); err != nil { +} + +// handleNewConnection takes a new net.Conn and performs the initial login sequence +func (s *Server) handleNewConnection(conn net.Conn, remoteAddr string) error { + defer dontPanic(s.Logger) + + if err := Handshake(conn); err != nil { return err } buf := make([]byte, 1024) + // TODO: fix potential short read with io.ReadFull readLen, err := conn.Read(buf) if readLen < minTransactionLen { return err @@ -473,15 +522,8 @@ func (s *Server) handleNewConnection(conn net.Conn) error { return err } - c := s.NewClientConn(conn) + c := s.NewClientConn(conn, remoteAddr) defer c.Disconnect() - defer func() { - if r := recover(); r != nil { - fmt.Println("stacktrace from panic: \n" + string(debug.Stack())) - c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack())) - c.Disconnect() - } - }() encodedLogin := clientLogin.GetField(fieldUserLogin).Data encodedPassword := clientLogin.GetField(fieldUserPassword).Data @@ -497,15 +539,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 { @@ -518,7 +564,7 @@ func (s *Server) handleNewConnection(conn net.Conn) error { *c.Flags = []byte{0, 2} } - s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String()) + s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", remoteAddr) s.outbox <- c.NewReply(clientLogin, NewField(fieldVersion, []byte{0x00, 0xbe}), @@ -532,13 +578,24 @@ 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? - 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 +625,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 @@ -614,117 +656,135 @@ 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() { - buf := make([]byte, 1024) - if _, err := conn.Read(buf); err != nil { + if err := conn.Close(); err != nil { + s.Logger.Errorw("error closing connection", "error", err) + } + }() + + defer dontPanic(s.Logger) + + txBuf := make([]byte, 16) + if _, err := io.ReadFull(conn, txBuf); err != nil { return err } var t transfer - _, err := t.Write(buf[:16]) - if err != nil { + if _, err := t.Write(txBuf); err != nil { return err } transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:]) - fileTransfer := s.FileTransfers[transferRefNum] + defer func() { + s.mux.Lock() + delete(s.FileTransfers, transferRefNum) + s.mux.Unlock() + }() + + s.mux.Lock() + fileTransfer, ok := s.FileTransfers[transferRefNum] + s.mux.Unlock() + if !ok { + return errors.New("invalid transaction ID") + } switch fileTransfer.Type { case FileDownload: - fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+string(fileTransfer.FilePath), string(fileTransfer.FileName)) - - ffo, err := NewFlattenedFileObject( - s.Config.FileRoot+string(fileTransfer.FilePath), - string(fileTransfer.FileName), - ) + fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName) if err != nil { return err } - s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String()) + var dataOffset int64 + if fileTransfer.fileResumeData != nil { + dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:])) + } - // Start by sending flat file object to client - if _, err := conn.Write(ffo.Payload()); err != nil { + ffo, err := NewFlattenedFileObject(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName, dataOffset) + if err != nil { return err } - file, err := os.Open(fullFilePath) + s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber) + + if fileTransfer.options == nil { + // Start by sending flat file object to client + if _, err := conn.Write(ffo.BinaryMarshal()); err != nil { + return err + } + } + + file, err := FS.Open(fullFilePath) if err != nil { return err } sendBuffer := make([]byte, 1048576) + var totalSent int64 for { var bytesRead int - if bytesRead, err = file.Read(sendBuffer); err == io.EOF { + if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF { + if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { + return err + } break } + if err != nil { + return err + } + totalSent += int64(bytesRead) fileTransfer.BytesSent += bytesRead - delete(s.FileTransfers, transferRefNum) - if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { return err } } case FileUpload: - if _, err := conn.Read(buf); err != nil { - return err - } + destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName) - ffo := ReadFlattenedFileObject(buf) - payloadLen := len(ffo.Payload()) - fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) + var file *os.File - 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, - ) + // A file upload has three possible cases: + // 1) Upload a new file + // 2) Resume a partially transferred file + // 3) Replace a fully uploaded file + // Unfortunately we have to infer which case applies by inspecting what is already on the file system - newFile, err := os.Create(destinationFile) - if err != nil { - return err + // 1) Check for existing file: + _, err := os.Stat(destinationFile) + if err == nil { + // If found, that means this upload is intended to replace the file + if err = os.Remove(destinationFile); err != nil { + return err + } + file, err = os.Create(destinationFile + incompleteFileSuffix) + } + if errors.Is(err, fs.ErrNotExist) { + // If not found, open or create a new incomplete file + file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) + if err != nil { + return err + } } - defer func() { _ = newFile.Close() }() + defer func() { _ = file.Close() }() - const buffSize = 1024 + s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile) - if _, err := newFile.Write(buf[payloadLen:]); err != nil { + // TODO: replace io.Discard with a real file when ready to implement storing of resource fork data + if err := receiveFile(conn, file, io.Discard); err != nil { return 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) + if err := os.Rename(destinationFile+".incomplete", destinationFile); err != nil { + return err } + + s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile) case FolderDownload: // Folder Download flow: // 1. Get filePath from the transfer @@ -742,7 +802,7 @@ func (s *Server) TransferFile(conn net.Conn) error { // [2]byte // Resume data size // []byte file resume data (see myField_FileResumeData) // - // 3. Otherwise download of the file is requested and client sends []byte{0x00, 0x01} + // 3. Otherwise, download of the file is requested and client sends []byte{0x00, 0x01} // // When download is requested (case 2 or 3), server replies with: // [4]byte - file size @@ -753,27 +813,35 @@ 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) - 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 := io.ReadFull(conn, 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) @@ -781,29 +849,51 @@ 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 { - s.Logger.Errorf("error reading next action: %v", err) + if _, err := io.ReadFull(conn, nextAction); err != nil { return err } - 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])) + + var dataOffset int64 + + switch nextAction[1] { + case dlFldrActionResumeFile: + // client asked to resume this file + var frd FileResumeData + // get size of resumeData + if _, err := io.ReadFull(conn, nextAction); err != nil { + return err + } + + resumeDataLen := binary.BigEndian.Uint16(nextAction) + resumeDataBytes := make([]byte, resumeDataLen) + if _, err := io.ReadFull(conn, resumeDataBytes); err != nil { + return err + } + + if err := frd.UnmarshalBinary(resumeDataBytes); err != nil { + return err + } + dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:])) + case dlFldrActionNextFile: + // client asked to skip this file + return nil + } if info.IsDir() { return nil } 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()), dataOffset) if err != nil { return err } s.Logger.Infow("File download started", "fileName", info.Name(), "transactionRef", fileTransfer.ReferenceNumber, - "RemoteAddr", conn.RemoteAddr().String(), "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()), ) @@ -813,72 +903,87 @@ func (s *Server) TransferFile(conn net.Conn) error { return err } - // Send file bytes to client - if _, err := conn.Write(ffo.Payload()); err != nil { + // 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 } + // // 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() sendBuffer := make([]byte, 1048576) - totalBytesSent := len(ffo.Payload()) - + var totalSent int64 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) + var bytesRead int + if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF { + if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { return err } break } + if err != nil { + panic(err) + } + totalSent += int64(bytesRead) + + fileTransfer.BytesSent += bytesRead - sentBytes, readErr := conn.Write(sendBuffer[:bytesRead]) - totalBytesSent += sentBytes - if readErr != nil { + if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil { return err } } + + // TODO: optionally send resource fork header and resource fork data + + // Read the client's Next Action request. This is always 3, I think? + if _, err := io.ReadFull(conn, nextAction); err != nil { + return err + } + return nil }) 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 { - s.Logger.Error(err) + if _, err := FS.Stat(dstPath); os.IsNotExist(err) { + if err := FS.Mkdir(dstPath, 0777); err != nil { + return err } } - 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 } 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 { + for i := 0; i < fileTransfer.ItemCount(); i++ { + // TODO: fix potential short read with io.ReadFull + _, err := conn.Read(readBuffer) + if err != nil { return err } fu := readFolderUpload(readBuffer) @@ -886,143 +991,119 @@ 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), + "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 { - s.Logger.Error(err) + return err } } // Tell client to send next file if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { - s.Logger.Error(err) return err } } else { - // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip. - // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload. - // Send dlFldrAction_SendFile to client to begin transfer - if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil { + nextAction := dlFldrActionSendFile + + // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip. + _, err := os.Stat(dstPath + "/" + fu.FormattedPath()) + if err != nil && !errors.Is(err, fs.ErrNotExist) { return err } - - if _, err := conn.Read(fileSize); err != nil { - fmt.Println("Error reading:", err.Error()) // TODO: handle + if err == nil { + nextAction = dlFldrActionNextFile } - s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize) - - if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil { - s.Logger.Error(err) - } - - // Tell client to send next file - if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { - s.Logger.Error(err) + // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload. + inccompleteFile, err := os.Stat(dstPath + "/" + fu.FormattedPath() + incompleteFileSuffix) + if err != nil && !errors.Is(err, fs.ErrNotExist) { return err } + if err == nil { + nextAction = dlFldrActionResumeFile + } + + fmt.Printf("Next Action: %v\n", nextAction) - // 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 { + if _, err := conn.Write([]byte{0, uint8(nextAction)}); err != nil { return err } - } - } - s.Logger.Infof("Folder upload complete") - } - return nil -} + switch nextAction { + case dlFldrActionNextFile: + continue + case dlFldrActionResumeFile: + offset := make([]byte, 4) + binary.BigEndian.PutUint32(offset, uint32(inccompleteFile.Size())) -func transferFile(conn net.Conn, dst string) error { - const buffSize = 1024 - buf := make([]byte, buffSize) + file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return err + } - // 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.Payload()) - fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize)) + fileResumeData := NewFileResumeData([]ForkInfoList{ + *NewForkInfoList(offset), + }) - 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 + b, _ := fileResumeData.BinaryMarshal() - for { - if (fileSize - receivedBytes) < buffSize { - _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)) - return err - } + bs := make([]byte, 2) + binary.BigEndian.PutUint16(bs, uint16(len(b))) - // Copy N bytes from conn to upload file - n, err := io.CopyN(newFile, conn, buffSize) - if err != nil { - return err - } - receivedBytes += int(n) - } -} + if _, err := conn.Write(append(bs, b...)); err != nil { + return err + } -// 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], - } + if _, err := io.ReadFull(conn, fileSize); err != nil { + return err + } - return fu -} + if err := receiveFile(conn, file, ioutil.Discard); err != nil { + s.Logger.Error(err) + } -type folderUpload struct { - DataSize []byte - IsFolder []byte - PathItemCount []byte - FileNamePath []byte -} + err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath()) + if err != nil { + return err + } -func (fu *folderUpload) FormattedPath() string { - pathItemLen := binary.BigEndian.Uint16(fu.PathItemCount) + case dlFldrActionSendFile: + if _, err := conn.Read(fileSize); err != nil { + return err + } + + filePath := dstPath + "/" + fu.FormattedPath() + s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "totalFiles", "zz", "fileSize", binary.BigEndian.Uint32(fileSize)) + + newFile, err := FS.Create(filePath + ".incomplete") + if err != nil { + return err + } - var pathSegments []string - pathData := fu.FileNamePath + if err := receiveFile(conn, newFile, ioutil.Discard); err != nil { + s.Logger.Error(err) + } + _ = newFile.Close() + if err := os.Rename(filePath+".incomplete", filePath); err != nil { + return err + } + } - for i := uint16(0); i < pathItemLen; i++ { - segLen := pathData[2] - pathSegments = append(pathSegments, string(pathData[3:3+segLen])) - pathData = pathData[3+segLen:] + // Tell client to send next file + if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil { + return err + } + } + } + s.Logger.Infof("Folder upload complete") } - return strings.Join(pathSegments, pathSeparator) + return nil } // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.