X-Git-Url: https://git.r.bdr.sh/rbdr/mobius/blobdiff_plain/0ed5132769e88cb385b5240986b706430f0ccd72..a2ef262a164fc735b9b8471ac0c8001eea2b9bf6:/hotline/server.go diff --git a/hotline/server.go b/hotline/server.go index 448aab1..0ee2dd7 100644 --- a/hotline/server.go +++ b/hotline/server.go @@ -4,6 +4,7 @@ import ( "bufio" "bytes" "context" + "crypto/rand" "encoding/binary" "errors" "fmt" @@ -11,17 +12,15 @@ import ( "golang.org/x/text/encoding/charmap" "gopkg.in/yaml.v3" "io" - "io/fs" "log" "log/slog" - "math/big" - "math/rand" "net" "os" "path" "path/filepath" "strings" "sync" + "sync/atomic" "time" ) @@ -40,11 +39,12 @@ var txtDecoder = charmap.Macintosh.NewDecoder() var txtEncoder = charmap.Macintosh.NewEncoder() type Server struct { - NetInterface string - Port int - Accounts map[string]*Account - Agreement []byte - Clients map[uint16]*ClientConn + NetInterface string + Port int + Accounts map[string]*Account + Agreement []byte + + Clients map[[2]byte]*ClientConn fileTransfers map[[4]byte]*FileTransfer Config *Config @@ -53,12 +53,12 @@ type Server struct { banner []byte PrivateChatsMu sync.Mutex - PrivateChats map[uint32]*PrivateChat + PrivateChats map[[4]byte]*PrivateChat - NextGuestID *uint16 + nextClientID atomic.Uint32 TrackerPassID [4]byte - StatsMu sync.Mutex + statsMu sync.Mutex Stats *Stats FS FileStore // Storage backend to use for File storage @@ -77,8 +77,8 @@ type Server struct { } func (s *Server) CurrentStats() Stats { - s.StatsMu.Lock() - defer s.StatsMu.Unlock() + s.statsMu.Lock() + defer s.statsMu.Unlock() stats := s.Stats stats.CurrentlyConnected = len(s.Clients) @@ -88,10 +88,10 @@ func (s *Server) CurrentStats() Stats { type PrivateChat struct { Subject string - ClientConn map[uint16]*ClientConn + ClientConn map[[2]byte]*ClientConn } -func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error { +func (s *Server) ListenAndServe(ctx context.Context) error { var wg sync.WaitGroup wg.Add(1) @@ -130,9 +130,7 @@ func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error defer func() { _ = conn.Close() }() err = s.handleFileTransfer( - context.WithValue(ctx, contextKeyReq, requestCtx{ - remoteAddr: conn.RemoteAddr().String(), - }), + context.WithValue(ctx, contextKeyReq, requestCtx{remoteAddr: conn.RemoteAddr().String()}), conn, ) @@ -144,21 +142,17 @@ func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error } func (s *Server) sendTransaction(t Transaction) error { - clientID, err := byteToInt(*t.clientID) - if err != nil { - return fmt.Errorf("invalid client ID: %v", err) - } - s.mux.Lock() - client, ok := s.Clients[uint16(clientID)] + client, ok := s.Clients[t.clientID] s.mux.Unlock() + if !ok || client == nil { - return fmt.Errorf("invalid client id %v", *t.clientID) + return nil } - _, err = io.Copy(client.Connection, &t) + _, err := io.Copy(client.Connection, &t) if err != nil { - return fmt.Errorf("failed to send transaction to client %v: %v", clientID, err) + return fmt.Errorf("failed to send transaction to client %v: %v", t.clientID, err) } return nil @@ -207,18 +201,18 @@ const ( ) // NewServer constructs a new Server from a config dir +// TODO: move config file reads out of this function func NewServer(configDir, netInterface string, netPort int, logger *slog.Logger, fs FileStore) (*Server, error) { server := Server{ NetInterface: netInterface, Port: netPort, Accounts: make(map[string]*Account), Config: new(Config), - Clients: make(map[uint16]*ClientConn), + Clients: make(map[[2]byte]*ClientConn), fileTransfers: make(map[[4]byte]*FileTransfer), - PrivateChats: make(map[uint32]*PrivateChat), + PrivateChats: make(map[[4]byte]*PrivateChat), ConfigDir: configDir, Logger: logger, - NextGuestID: new(uint16), outbox: make(chan Transaction), Stats: &Stats{Since: time.Now()}, ThreadedNews: &ThreadedNews{}, @@ -243,14 +237,18 @@ func NewServer(configDir, netInterface string, netPort int, logger *slog.Logger, } // try to load the ban list, but ignore errors as this file may not be present or may be empty - _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml")) + //_ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml")) - if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil { + _ = loadFromYAMLFile(filepath.Join(configDir, "Banlist.yaml"), &server.banList) + + err = loadFromYAMLFile(filepath.Join(configDir, "ThreadedNews.yaml"), &server.ThreadedNews) + if err != nil { return nil, fmt.Errorf("error loading threaded news: %w", err) } - if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil { - return nil, err + err = server.loadConfig(filepath.Join(configDir, "config.yaml")) + if err != nil { + return nil, fmt.Errorf("error loading config: %w", err) } if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil { @@ -267,8 +265,6 @@ func NewServer(configDir, netInterface string, netPort int, logger *slog.Logger, return nil, fmt.Errorf("error opening banner: %w", err) } - *server.NextGuestID = 1 - if server.Config.EnableTrackerRegistration { server.Logger.Info( "Tracker registration enabled", @@ -286,7 +282,7 @@ func NewServer(configDir, netInterface string, netPort int, logger *slog.Logger, } binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port)) for _, t := range server.Config.Trackers { - if err := register(t, tr); err != nil { + if err := register(&RealDialer{}, t, tr); err != nil { server.Logger.Error("unable to register with tracker %v", "error", err) } server.Logger.Debug("Sent Tracker registration", "addr", t) @@ -320,14 +316,13 @@ func (s *Server) keepaliveHandler() { if c.IdleTime > userIdleSeconds && !c.Idle { c.Idle = true - flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags))) - flagBitmap.SetBit(flagBitmap, UserFlagAway, 1) - binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64())) - + c.flagsMU.Lock() + c.Flags.Set(UserFlagAway, 1) + c.flagsMU.Unlock() c.sendAll( TranNotifyChangeUser, - NewField(FieldUserID, *c.ID), - NewField(FieldUserFlags, c.Flags), + NewField(FieldUserID, c.ID[:]), + NewField(FieldUserFlags, c.Flags[:]), NewField(FieldUserName, c.UserName), NewField(FieldUserIconID, c.Icon), ) @@ -374,14 +369,9 @@ func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *Clie defer s.mux.Unlock() clientConn := &ClientConn{ - ID: &[]byte{0, 0}, - Icon: []byte{0, 0}, - Flags: []byte{0, 0}, - UserName: []byte{}, + Icon: []byte{0, 0}, // TODO: make array type Connection: conn, Server: s, - Version: []byte{}, - AutoReply: []byte{}, RemoteAddr: remoteAddr, transfers: map[int]map[[4]byte]*FileTransfer{ FileDownload: {}, @@ -392,11 +382,10 @@ func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *Clie }, } - *s.NextGuestID++ - ID := *s.NextGuestID + s.nextClientID.Add(1) - binary.BigEndian.PutUint16(*clientConn.ID, ID) - s.Clients[ID] = clientConn + binary.BigEndian.PutUint16(clientConn.ID[:], uint16(s.nextClientID.Load())) + s.Clients[clientConn.ID] = clientConn return clientConn } @@ -406,34 +395,29 @@ func (s *Server) NewUser(login, name, password string, access accessBitmap) erro s.mux.Lock() defer s.mux.Unlock() - account := Account{ - Login: login, - Name: name, - Password: hashAndSalt([]byte(password)), - Access: access, - } - out, err := yaml.Marshal(&account) - if err != nil { - return err - } + account := NewAccount(login, name, password, access) // Create account file, returning an error if one already exists. file, err := os.OpenFile( filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"), - os.O_CREATE|os.O_EXCL|os.O_WRONLY, - 0644, + os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644, ) if err != nil { - return err + return fmt.Errorf("error creating account file: %w", err) } defer file.Close() - _, err = file.Write(out) + b, err := yaml.Marshal(account) + if err != nil { + return err + } + + _, err = file.Write(b) if err != nil { return fmt.Errorf("error writing account file: %w", err) } - s.Accounts[login] = &account + s.Accounts[login] = account return nil } @@ -442,11 +426,14 @@ func (s *Server) UpdateUser(login, newLogin, name, password string, access acces s.mux.Lock() defer s.mux.Unlock() - // update renames the user login + // If the login has changed, rename the account file. if login != newLogin { - err := os.Rename(filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"), filepath.Join(s.ConfigDir, "Users", path.Join("/", newLogin)+".yaml")) + err := os.Rename( + filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"), + filepath.Join(s.ConfigDir, "Users", path.Join("/", newLogin)+".yaml"), + ) if err != nil { - return fmt.Errorf("unable to rename account: %w", err) + return fmt.Errorf("error renaming account file: %w", err) } s.Accounts[newLogin] = s.Accounts[login] s.Accounts[newLogin].Login = newLogin @@ -464,7 +451,7 @@ func (s *Server) UpdateUser(login, newLogin, name, password string, access acces } if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil { - return err + return fmt.Errorf("error writing account file: %w", err) } return nil @@ -486,15 +473,15 @@ func (s *Server) DeleteUser(login string) error { } func (s *Server) connectedUsers() []Field { - s.mux.Lock() - defer s.mux.Unlock() + //s.mux.Lock() + //defer s.mux.Unlock() var connectedUsers []Field for _, c := range sortedClients(s.Clients) { b, err := io.ReadAll(&User{ - ID: *c.ID, + ID: c.ID, Icon: c.Icon, - Flags: c.Flags, + Flags: c.Flags[:], Name: string(c.UserName), }) if err != nil { @@ -505,25 +492,16 @@ func (s *Server) connectedUsers() []Field { return connectedUsers } -func (s *Server) loadBanList(path string) error { +// loadFromYAMLFile loads data from a YAML file into the provided data structure. +func loadFromYAMLFile(path string, data interface{}) error { fh, err := os.Open(path) if err != nil { return err } - decoder := yaml.NewDecoder(fh) + defer fh.Close() - return decoder.Decode(s.banList) -} - -// loadThreadedNews loads the threaded news data from disk -func (s *Server) loadThreadedNews(threadedNewsPath string) error { - fh, err := os.Open(threadedNewsPath) - if err != nil { - return err - } decoder := yaml.NewDecoder(fh) - - return decoder.Decode(s.ThreadedNews) + return decoder.Decode(data) } // loadAccounts loads account data from disk @@ -534,18 +512,12 @@ func (s *Server) loadAccounts(userDir string) error { } if len(matches) == 0 { - return errors.New("no user accounts found in " + userDir) + return fmt.Errorf("no accounts found in directory: %s", userDir) } for _, file := range matches { - fh, err := s.FS.Open(file) - if err != nil { - return err - } - - account := Account{} - decoder := yaml.NewDecoder(fh) - if err = decoder.Decode(&account); err != nil { + var account Account + if err = loadFromYAMLFile(file, &account); err != nil { return fmt.Errorf("error loading account %s: %w", file, err) } @@ -574,12 +546,41 @@ func (s *Server) loadConfig(path string) error { return nil } +func sendBanMessage(rwc io.Writer, message string) { + t := NewTransaction( + TranServerMsg, + [2]byte{0, 0}, + NewField(FieldData, []byte(message)), + NewField(FieldChatOptions, []byte{0, 0}), + ) + _, _ = io.Copy(rwc, &t) + time.Sleep(1 * time.Second) +} + // handleNewConnection takes a new net.Conn and performs the initial login sequence func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error { defer dontPanic(s.Logger) - if err := Handshake(rwc); err != nil { - return err + // Check if remoteAddr is present in the ban list + ipAddr := strings.Split(remoteAddr, ":")[0] + if banUntil, ok := s.banList[ipAddr]; ok { + // permaban + if banUntil == nil { + sendBanMessage(rwc, "You are permanently banned on this server") + s.Logger.Debug("Disconnecting permanently banned IP", "remoteAddr", ipAddr) + return nil + } + + // temporary ban + if time.Now().Before(*banUntil) { + sendBanMessage(rwc, "You are temporarily banned on this server") + s.Logger.Debug("Disconnecting temporarily banned IP", "remoteAddr", ipAddr) + return nil + } + } + + if err := performHandshake(rwc); err != nil { + return fmt.Errorf("error performing handshake: %w", err) } // Create a new scanner for parsing incoming bytes into transaction tokens @@ -595,59 +596,16 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser var clientLogin Transaction if _, err := clientLogin.Write(buf); err != nil { - return err - } - - // check if remoteAddr is present in the ban list - if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok { - // permaban - if banUntil == nil { - t := NewTransaction( - TranServerMsg, - &[]byte{0, 0}, - NewField(FieldData, []byte("You are permanently banned on this server")), - NewField(FieldChatOptions, []byte{0, 0}), - ) - - _, err := io.Copy(rwc, t) - if err != nil { - return err - } - - time.Sleep(1 * time.Second) - return nil - } - - // temporary ban - if time.Now().Before(*banUntil) { - t := NewTransaction( - TranServerMsg, - &[]byte{0, 0}, - NewField(FieldData, []byte("You are temporarily banned on this server")), - NewField(FieldChatOptions, []byte{0, 0}), - ) - - _, err := io.Copy(rwc, t) - if err != nil { - return err - } - - time.Sleep(1 * time.Second) - return nil - } + return fmt.Errorf("error writing login transaction: %w", err) } c := s.NewClientConn(rwc, remoteAddr) defer c.Disconnect() - encodedLogin := clientLogin.GetField(FieldUserLogin).Data encodedPassword := clientLogin.GetField(FieldUserPassword).Data c.Version = clientLogin.GetField(FieldVersion).Data - var login string - for _, char := range encodedLogin { - login += string(rune(255 - uint(char))) - } + login := string(encodeString(clientLogin.GetField(FieldUserLogin).Data)) if login == "" { login = GuestAccount } @@ -656,7 +614,7 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser // If authentication fails, send error reply and close connection if !c.Authenticate(login, encodedPassword) { - t := c.NewErrReply(&clientLogin, "Incorrect login.") + t := c.NewErrReply(&clientLogin, "Incorrect login.")[0] _, err := io.Copy(rwc, &t) if err != nil { @@ -672,7 +630,9 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser c.Icon = clientLogin.GetField(FieldUserIconID).Data } + c.Lock() c.Account = c.Server.Accounts[login] + c.Unlock() if clientLogin.GetField(FieldUserName).Data != nil { if c.Authorize(accessAnyName) { @@ -683,7 +643,7 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser } if c.Authorize(accessDisconUser) { - c.Flags = []byte{0, 2} + c.Flags.Set(UserFlagAdmin, 1) } s.outbox <- c.NewReply(&clientLogin, @@ -693,7 +653,7 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser ) // Send user access privs so client UI knows how to behave - c.Server.outbox <- *NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:])) + c.Server.outbox <- NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:])) // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between // client versions. For 1.2.3 client, we do not send TranShowAgreement. For other client versions, we send @@ -701,10 +661,10 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser if c.Authorize(accessNoAgreement) { // If client version is nil, then the client uses the 1.2.3 login behavior if c.Version != nil { - c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1})) + c.Server.outbox <- NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1})) } } else { - c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement)) + c.Server.outbox <- NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement)) } // If the client has provided a username as part of the login, we can infer that it is using the 1.2.3 login @@ -713,33 +673,33 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser // Add the client username to the logger. For 1.5+ clients, we don't have this information yet as it comes as // part of TranAgreed c.logger = c.logger.With("Name", string(c.UserName)) - c.logger.Info("Login successful", "clientVersion", "Not sent (probably 1.2.3)") // Notify other clients on the server that the new user has logged in. For 1.5+ clients we don't have this // information yet, so we do it in TranAgreed instead for _, t := range c.notifyOthers( - *NewTransaction( - TranNotifyChangeUser, nil, + NewTransaction( + TranNotifyChangeUser, [2]byte{0, 0}, NewField(FieldUserName, c.UserName), - NewField(FieldUserID, *c.ID), + NewField(FieldUserID, c.ID[:]), NewField(FieldUserIconID, c.Icon), - NewField(FieldUserFlags, c.Flags), + NewField(FieldUserFlags, c.Flags[:]), ), ) { c.Server.outbox <- t } } + c.Server.mux.Lock() c.Server.Stats.ConnectionCounter += 1 if len(s.Clients) > c.Server.Stats.ConnectionPeak { c.Server.Stats.ConnectionPeak = len(s.Clients) } + c.Server.mux.Unlock() // Scan for new transactions and handle them as they come in. for scanner.Scan() { - // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the - // scanner re-uses the buffer for subsequent scans. + // Copy the scanner bytes to a new slice to it to avoid a data race when the scanner re-uses the buffer. buf := make([]byte, len(scanner.Bytes())) copy(buf, scanner.Bytes()) @@ -748,25 +708,22 @@ func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser return err } - if err := c.handleTransaction(t); err != nil { - c.logger.Error("Error handling transaction", "err", err) - } + c.handleTransaction(t) } return nil } -func (s *Server) NewPrivateChat(cc *ClientConn) []byte { +func (s *Server) NewPrivateChat(cc *ClientConn) [4]byte { s.PrivateChatsMu.Lock() defer s.PrivateChatsMu.Unlock() - randID := make([]byte, 4) - rand.Read(randID) - data := binary.BigEndian.Uint32(randID) + var randID [4]byte + _, _ = rand.Read(randID[:]) - s.PrivateChats[data] = &PrivateChat{ - ClientConn: make(map[uint16]*ClientConn), + s.PrivateChats[randID] = &PrivateChat{ + ClientConn: make(map[[2]byte]*ClientConn), } - s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc + s.PrivateChats[randID].ClientConn[cc.ID] = cc return randID } @@ -779,14 +736,10 @@ const dlFldrActionNextFile = 3 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error { defer dontPanic(s.Logger) - txBuf := make([]byte, 16) - if _, err := io.ReadFull(rwc, txBuf); err != nil { - return err - } - + // The first 16 bytes contain the file transfer. var t transfer - if _, err := t.Write(txBuf); err != nil { - return err + if _, err := io.CopyN(&t, rwc, 16); err != nil { + return fmt.Errorf("error reading file transfer: %w", err) } defer func() { @@ -836,55 +789,9 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro s.Stats.DownloadsInProgress -= 1 }() - var dataOffset int64 - if fileTransfer.fileResumeData != nil { - dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:])) - } - - fw, err := newFileWrapper(s.FS, fullPath, 0) - if err != nil { - return err - } - - rLogger.Info("File download started", "filePath", fullPath) - - // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client - if fileTransfer.options == nil { - _, err = io.Copy(rwc, fw.ffo) - if err != nil { - return err - } - } - - file, err := fw.dataForkReader() + err = DownloadHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, true) if err != nil { - return err - } - - br := bufio.NewReader(file) - if _, err := br.Discard(int(dataOffset)); err != nil { - return err - } - - if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil { - return err - } - - // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data - if fileTransfer.fileResumeData == nil { - err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader()) - if err != nil { - return err - } - } - - rFile, err := fw.rsrcForkFile() - if err != nil { - return nil - } - - if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil { - return err + return fmt.Errorf("file download error: %w", err) } case FileUpload: @@ -892,224 +799,19 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro s.Stats.UploadsInProgress += 1 defer func() { s.Stats.UploadsInProgress -= 1 }() - var file *os.File - - // A file upload has three possible cases: - // 1) Upload a new file - // 2) Resume a partially transferred file - // 3) Replace a fully uploaded file - // We have to infer which case applies by inspecting what is already on the filesystem - - // 1) Check for existing file: - _, err = os.Stat(fullPath) - if err == nil { - return errors.New("existing file found at " + fullPath) - } - if errors.Is(err, fs.ErrNotExist) { - // If not found, open or create a new .incomplete file - file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) - if err != nil { - return err - } - } - - f, err := newFileWrapper(s.FS, fullPath, 0) + err = UploadHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks) if err != nil { - return err - } - - rLogger.Info("File upload started", "dstFile", fullPath) - - rForkWriter := io.Discard - iForkWriter := io.Discard - if s.Config.PreserveResourceForks { - rForkWriter, err = f.rsrcForkWriter() - if err != nil { - return err - } - - iForkWriter, err = f.infoForkWriter() - if err != nil { - return err - } + return fmt.Errorf("file upload error: %w", err) } - if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil { - s.Logger.Error(err.Error()) - } - - if err := file.Close(); err != nil { - return err - } - - if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil { - return err - } - - rLogger.Info("File upload complete", "dstFile", fullPath) - case FolderDownload: s.Stats.DownloadCounter += 1 s.Stats.DownloadsInProgress += 1 defer func() { s.Stats.DownloadsInProgress -= 1 }() - // Folder Download flow: - // 1. Get filePath from the transfer - // 2. Iterate over files - // 3. For each fileWrapper: - // Send fileWrapper header to client - // The client can reply in 3 ways: - // - // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed: - // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper - // - // 2. If download of a fileWrapper is to be resumed: - // client sends: - // []byte{0x00, 0x02} // download folder action - // [2]byte // Resume data size - // []byte fileWrapper resume data (see myField_FileResumeData) - // - // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01} - // - // When download is requested (case 2 or 3), server replies with: - // [4]byte - fileWrapper size - // []byte - Flattened File Object - // - // After every fileWrapper download, client could request next fileWrapper with: - // []byte{0x00, 0x03} - // - // This notifies the server to send the next item header - - basePathLen := len(fullPath) - - rLogger.Info("Start folder download", "path", fullPath) - - nextAction := make([]byte, 2) - if _, err := io.ReadFull(rwc, nextAction); err != nil { - return err - } - - i := 0 - err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error { - s.Stats.DownloadCounter += 1 - i += 1 - - if err != nil { - return err - } - - // skip dot files - if strings.HasPrefix(info.Name(), ".") { - return nil - } - - hlFile, err := newFileWrapper(s.FS, path, 0) - if err != nil { - return err - } - - subPath := path[basePathLen+1:] - rLogger.Debug("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir()) - - if i == 1 { - return nil - } - - fileHeader := NewFileHeader(subPath, info.IsDir()) - if _, err := io.Copy(rwc, &fileHeader); err != nil { - return fmt.Errorf("error sending file header: %w", err) - } - - // Read the client's Next Action request - if _, err := io.ReadFull(rwc, nextAction); err != nil { - return err - } - - rLogger.Debug("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2])) - - var dataOffset int64 - - switch nextAction[1] { - case dlFldrActionResumeFile: - // get size of resumeData - resumeDataByteLen := make([]byte, 2) - if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil { - return err - } - - resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen) - resumeDataBytes := make([]byte, resumeDataLen) - if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil { - return err - } - - var frd FileResumeData - 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 - } - - rLogger.Info("File download started", - "fileName", info.Name(), - "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)), - ) - - // Send file size to client - if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil { - s.Logger.Error(err.Error()) - return err - } - - // Send ffo bytes to client - _, err = io.Copy(rwc, hlFile.ffo) - if err != nil { - return err - } - - file, err := s.FS.Open(path) - if err != nil { - return err - } - - // wr := bufio.NewWriterSize(rwc, 1460) - if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil { - return err - } - - if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 { - err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader()) - if err != nil { - return err - } - - rFile, err := hlFile.rsrcForkFile() - if err != nil { - return err - } - - if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil { - return err - } - } - - // Read the client's Next Action request. This is always 3, I think? - if _, err := io.ReadFull(rwc, nextAction); err != nil { - return err - } - - return nil - }) - + err = DownloadFolderHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks) if err != nil { - return err + return fmt.Errorf("file upload error: %w", err) } case FolderUpload: @@ -1123,168 +825,10 @@ func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) erro "FolderItemCount", fileTransfer.FolderItemCount, ) - // Check if the target folder exists. If not, create it. - if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) { - if err := s.FS.Mkdir(fullPath, 0777); err != nil { - return err - } - } - - // Begin the folder upload flow by sending the "next file action" to client - if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { - return err - } - - fileSize := make([]byte, 4) - - for i := 0; i < fileTransfer.ItemCount(); i++ { - s.Stats.UploadCounter += 1 - - var fu folderUpload - if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil { - return err - } - if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil { - return err - } - if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil { - return err - } - - fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes - - if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil { - return err - } - - rLogger.Info( - "Folder upload continued", - "FormattedPath", fu.FormattedPath(), - "IsFolder", fmt.Sprintf("%x", fu.IsFolder), - "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]), - ) - - if fu.IsFolder == [2]byte{0, 1} { - if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) { - if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil { - return err - } - } - - // Tell client to send next file - if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { - return err - } - } else { - nextAction := dlFldrActionSendFile - - // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip. - _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath())) - if err != nil && !errors.Is(err, fs.ErrNotExist) { - return err - } - if err == nil { - nextAction = dlFldrActionNextFile - } - - // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload. - incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix)) - if err != nil && !errors.Is(err, fs.ErrNotExist) { - return err - } - if err == nil { - nextAction = dlFldrActionResumeFile - } - - if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil { - return err - } - - switch nextAction { - case dlFldrActionNextFile: - continue - case dlFldrActionResumeFile: - offset := make([]byte, 4) - binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size())) - - file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return err - } - - fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)}) - - b, _ := fileResumeData.BinaryMarshal() - - bs := make([]byte, 2) - binary.BigEndian.PutUint16(bs, uint16(len(b))) - - if _, err := rwc.Write(append(bs, b...)); err != nil { - return err - } - - if _, err := io.ReadFull(rwc, fileSize); err != nil { - return err - } - - if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil { - s.Logger.Error(err.Error()) - } - - err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath()) - if err != nil { - return err - } - - case dlFldrActionSendFile: - if _, err := io.ReadFull(rwc, fileSize); err != nil { - return err - } - - filePath := filepath.Join(fullPath, fu.FormattedPath()) - - hlFile, err := newFileWrapper(s.FS, filePath, 0) - if err != nil { - return err - } - - rLogger.Info("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize)) - - incWriter, err := hlFile.incFileWriter() - if err != nil { - return err - } - - rForkWriter := io.Discard - iForkWriter := io.Discard - if s.Config.PreserveResourceForks { - iForkWriter, err = hlFile.infoForkWriter() - if err != nil { - return err - } - - rForkWriter, err = hlFile.rsrcForkWriter() - if err != nil { - return err - } - } - if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil { - return err - } - - if err := os.Rename(filePath+".incomplete", filePath); err != nil { - return err - } - } - - // Tell client to send next fileWrapper - if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil { - return err - } - } + err = UploadFolderHandler(rwc, fullPath, fileTransfer, s.FS, rLogger, s.Config.PreserveResourceForks) + if err != nil { + return fmt.Errorf("file upload error: %w", err) } - rLogger.Info("Folder upload complete") } - return nil }