9 "github.com/go-playground/validator/v10"
11 "golang.org/x/text/encoding/charmap"
26 type contextKey string
28 var contextKeyReq = contextKey("req")
30 type requestCtx struct {
34 // Converts bytes from Mac Roman encoding to UTF-8
35 var txtDecoder = charmap.Macintosh.NewDecoder()
37 // Converts bytes from UTF-8 to Mac Roman encoding
38 var txtEncoder = charmap.Macintosh.NewEncoder()
43 Accounts map[string]*Account
45 Clients map[uint16]*ClientConn
46 fileTransfers map[[4]byte]*FileTransfer
50 Logger *zap.SugaredLogger
52 PrivateChatsMu sync.Mutex
53 PrivateChats map[uint32]*PrivateChat
61 FS FileStore // Storage backend to use for File storage
63 outbox chan Transaction
66 threadedNewsMux sync.Mutex
67 ThreadedNews *ThreadedNews
69 flatNewsMux sync.Mutex
73 banList map[string]*time.Time
76 func (s *Server) CurrentStats() Stats {
78 defer s.StatsMu.Unlock()
81 stats.CurrentlyConnected = len(s.Clients)
86 type PrivateChat struct {
88 ClientConn map[uint16]*ClientConn
91 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
92 s.Logger.Infow("Hotline server started",
94 "API port", fmt.Sprintf("%s:%v", s.NetInterface, s.Port),
95 "Transfer port", fmt.Sprintf("%s:%v", s.NetInterface, s.Port+1),
102 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port))
107 s.Logger.Fatal(s.Serve(ctx, ln))
112 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port+1))
117 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
125 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
127 conn, err := ln.Accept()
133 defer func() { _ = conn.Close() }()
135 err = s.handleFileTransfer(
136 context.WithValue(ctx, contextKeyReq, requestCtx{
137 remoteAddr: conn.RemoteAddr().String(),
143 s.Logger.Errorw("file transfer error", "reason", err)
149 func (s *Server) sendTransaction(t Transaction) error {
150 clientID, err := byteToInt(*t.clientID)
156 client := s.Clients[uint16(clientID)]
159 return fmt.Errorf("invalid client id %v", *t.clientID)
162 b, err := t.MarshalBinary()
167 _, err = client.Connection.Write(b)
175 func (s *Server) processOutbox() {
179 if err := s.sendTransaction(t); err != nil {
180 s.Logger.Errorw("error sending transaction", "err", err)
186 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
190 conn, err := ln.Accept()
192 s.Logger.Errorw("error accepting connection", "err", err)
194 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
195 remoteAddr: conn.RemoteAddr().String(),
199 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
202 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
204 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
206 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
214 agreementFile = "Agreement.txt"
217 // NewServer constructs a new Server from a config dir
218 func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger, fs FileStore) (*Server, error) {
220 NetInterface: netInterface,
222 Accounts: make(map[string]*Account),
224 Clients: make(map[uint16]*ClientConn),
225 fileTransfers: make(map[[4]byte]*FileTransfer),
226 PrivateChats: make(map[uint32]*PrivateChat),
227 ConfigDir: configDir,
229 NextGuestID: new(uint16),
230 outbox: make(chan Transaction),
231 Stats: &Stats{Since: time.Now()},
232 ThreadedNews: &ThreadedNews{},
234 banList: make(map[string]*time.Time),
239 // generate a new random passID for tracker registration
240 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
244 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
249 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
253 // try to load the ban list, but ignore errors as this file may not be present or may be empty
254 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
256 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
260 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
264 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
268 // If the FileRoot is an absolute path, use it, otherwise treat as a relative path to the config dir.
269 if !filepath.IsAbs(server.Config.FileRoot) {
270 server.Config.FileRoot = filepath.Join(configDir, server.Config.FileRoot)
273 *server.NextGuestID = 1
275 if server.Config.EnableTrackerRegistration {
277 "Tracker registration enabled",
278 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
279 "trackers", server.Config.Trackers,
284 tr := &TrackerRegistration{
285 UserCount: server.userCount(),
286 PassID: server.TrackerPassID[:],
287 Name: server.Config.Name,
288 Description: server.Config.Description,
290 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
291 for _, t := range server.Config.Trackers {
292 if err := register(t, tr); err != nil {
293 server.Logger.Errorw("unable to register with tracker %v", "error", err)
295 server.Logger.Debugw("Sent Tracker registration", "addr", t)
298 time.Sleep(trackerUpdateFrequency * time.Second)
303 // Start Client Keepalive go routine
304 go server.keepaliveHandler()
309 func (s *Server) userCount() int {
313 return len(s.Clients)
316 func (s *Server) keepaliveHandler() {
318 time.Sleep(idleCheckInterval * time.Second)
321 for _, c := range s.Clients {
322 c.IdleTime += idleCheckInterval
323 if c.IdleTime > userIdleSeconds && !c.Idle {
326 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
327 flagBitmap.SetBit(flagBitmap, UserFlagAway, 1)
328 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
331 TranNotifyChangeUser,
332 NewField(FieldUserID, *c.ID),
333 NewField(FieldUserFlags, c.Flags),
334 NewField(FieldUserName, c.UserName),
335 NewField(FieldUserIconID, c.Icon),
343 func (s *Server) writeBanList() error {
345 defer s.banListMU.Unlock()
347 out, err := yaml.Marshal(s.banList)
352 filepath.Join(s.ConfigDir, "Banlist.yaml"),
359 func (s *Server) writeThreadedNews() error {
360 s.threadedNewsMux.Lock()
361 defer s.threadedNewsMux.Unlock()
363 out, err := yaml.Marshal(s.ThreadedNews)
367 err = s.FS.WriteFile(
368 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
375 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
379 clientConn := &ClientConn{
388 RemoteAddr: remoteAddr,
389 transfers: map[int]map[[4]byte]*FileTransfer{
401 binary.BigEndian.PutUint16(*clientConn.ID, ID)
402 s.Clients[ID] = clientConn
407 // NewUser creates a new user account entry in the server map and config file
408 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
415 Password: hashAndSalt([]byte(password)),
418 out, err := yaml.Marshal(&account)
423 // Create account file, returning an error if one already exists.
424 file, err := os.OpenFile(
425 filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"),
426 os.O_CREATE|os.O_EXCL|os.O_WRONLY,
434 _, err = file.Write(out)
436 return fmt.Errorf("error writing account file: %w", err)
439 s.Accounts[login] = &account
444 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
448 // update renames the user login
449 if login != newLogin {
450 err := os.Rename(filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"), filepath.Join(s.ConfigDir, "Users", path.Join("/", newLogin)+".yaml"))
452 return fmt.Errorf("unable to rename account: %w", err)
454 s.Accounts[newLogin] = s.Accounts[login]
455 s.Accounts[newLogin].Login = newLogin
456 delete(s.Accounts, login)
459 account := s.Accounts[newLogin]
460 account.Access = access
462 account.Password = password
464 out, err := yaml.Marshal(&account)
469 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
476 // DeleteUser deletes the user account
477 func (s *Server) DeleteUser(login string) error {
481 err := s.FS.Remove(filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"))
486 delete(s.Accounts, login)
491 func (s *Server) connectedUsers() []Field {
495 var connectedUsers []Field
496 for _, c := range sortedClients(s.Clients) {
501 Name: string(c.UserName),
503 connectedUsers = append(connectedUsers, NewField(FieldUsernameWithInfo, user.Payload()))
505 return connectedUsers
508 func (s *Server) loadBanList(path string) error {
509 fh, err := os.Open(path)
513 decoder := yaml.NewDecoder(fh)
515 return decoder.Decode(s.banList)
518 // loadThreadedNews loads the threaded news data from disk
519 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
520 fh, err := os.Open(threadedNewsPath)
524 decoder := yaml.NewDecoder(fh)
526 return decoder.Decode(s.ThreadedNews)
529 // loadAccounts loads account data from disk
530 func (s *Server) loadAccounts(userDir string) error {
531 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
536 if len(matches) == 0 {
537 return errors.New("no user accounts found in " + userDir)
540 for _, file := range matches {
541 fh, err := s.FS.Open(file)
547 decoder := yaml.NewDecoder(fh)
548 if err = decoder.Decode(&account); err != nil {
549 return fmt.Errorf("error loading account %s: %w", file, err)
552 s.Accounts[account.Login] = &account
557 func (s *Server) loadConfig(path string) error {
558 fh, err := s.FS.Open(path)
563 decoder := yaml.NewDecoder(fh)
564 err = decoder.Decode(s.Config)
569 validate := validator.New()
570 err = validate.Struct(s.Config)
577 // handleNewConnection takes a new net.Conn and performs the initial login sequence
578 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
579 defer dontPanic(s.Logger)
581 if err := Handshake(rwc); err != nil {
585 // Create a new scanner for parsing incoming bytes into transaction tokens
586 scanner := bufio.NewScanner(rwc)
587 scanner.Split(transactionScanner)
591 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
592 // scanner re-uses the buffer for subsequent scans.
593 buf := make([]byte, len(scanner.Bytes()))
594 copy(buf, scanner.Bytes())
596 var clientLogin Transaction
597 if _, err := clientLogin.Write(buf); err != nil {
601 // check if remoteAddr is present in the ban list
602 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
608 NewField(FieldData, []byte("You are permanently banned on this server")),
609 NewField(FieldChatOptions, []byte{0, 0}),
612 b, err := t.MarshalBinary()
617 _, err = rwc.Write(b)
622 time.Sleep(1 * time.Second)
627 if time.Now().Before(*banUntil) {
631 NewField(FieldData, []byte("You are temporarily banned on this server")),
632 NewField(FieldChatOptions, []byte{0, 0}),
634 b, err := t.MarshalBinary()
639 _, err = rwc.Write(b)
644 time.Sleep(1 * time.Second)
649 c := s.NewClientConn(rwc, remoteAddr)
652 encodedLogin := clientLogin.GetField(FieldUserLogin).Data
653 encodedPassword := clientLogin.GetField(FieldUserPassword).Data
654 c.Version = clientLogin.GetField(FieldVersion).Data
657 for _, char := range encodedLogin {
658 login += string(rune(255 - uint(char)))
664 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
666 // If authentication fails, send error reply and close connection
667 if !c.Authenticate(login, encodedPassword) {
668 t := c.NewErrReply(&clientLogin, "Incorrect login.")
669 b, err := t.MarshalBinary()
673 if _, err := rwc.Write(b); err != nil {
677 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
682 if clientLogin.GetField(FieldUserIconID).Data != nil {
683 c.Icon = clientLogin.GetField(FieldUserIconID).Data
686 c.Account = c.Server.Accounts[login]
688 if clientLogin.GetField(FieldUserName).Data != nil {
689 if c.Authorize(accessAnyName) {
690 c.UserName = clientLogin.GetField(FieldUserName).Data
692 c.UserName = []byte(c.Account.Name)
696 if c.Authorize(accessDisconUser) {
697 c.Flags = []byte{0, 2}
700 s.outbox <- c.NewReply(&clientLogin,
701 NewField(FieldVersion, []byte{0x00, 0xbe}),
702 NewField(FieldCommunityBannerID, []byte{0, 0}),
703 NewField(FieldServerName, []byte(s.Config.Name)),
706 // Send user access privs so client UI knows how to behave
707 c.Server.outbox <- *NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:]))
709 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
710 // client versions. For 1.2.3 client, we do not send TranShowAgreement. For other client versions, we send
711 // TranShowAgreement but with the NoServerAgreement field set to 1.
712 if c.Authorize(accessNoAgreement) {
713 // If client version is nil, then the client uses the 1.2.3 login behavior
714 if c.Version != nil {
715 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1}))
718 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement))
721 // If the client has provided a username as part of the login, we can infer that it is using the 1.2.3 login
722 // flow and not the 1.5+ flow.
723 if len(c.UserName) != 0 {
724 // Add the client username to the logger. For 1.5+ clients, we don't have this information yet as it comes as
725 // part of TranAgreed
726 c.logger = c.logger.With("name", string(c.UserName))
728 c.logger.Infow("Login successful", "clientVersion", "Not sent (probably 1.2.3)")
730 // Notify other clients on the server that the new user has logged in. For 1.5+ clients we don't have this
731 // information yet, so we do it in TranAgreed instead
732 for _, t := range c.notifyOthers(
734 TranNotifyChangeUser, nil,
735 NewField(FieldUserName, c.UserName),
736 NewField(FieldUserID, *c.ID),
737 NewField(FieldUserIconID, c.Icon),
738 NewField(FieldUserFlags, c.Flags),
745 c.Server.Stats.ConnectionCounter += 1
746 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
747 c.Server.Stats.ConnectionPeak = len(s.Clients)
750 // Scan for new transactions and handle them as they come in.
752 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
753 // scanner re-uses the buffer for subsequent scans.
754 buf := make([]byte, len(scanner.Bytes()))
755 copy(buf, scanner.Bytes())
758 if _, err := t.Write(buf); err != nil {
762 if err := c.handleTransaction(t); err != nil {
763 c.logger.Errorw("Error handling transaction", "err", err)
769 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
770 s.PrivateChatsMu.Lock()
771 defer s.PrivateChatsMu.Unlock()
773 randID := make([]byte, 4)
775 data := binary.BigEndian.Uint32(randID)
777 s.PrivateChats[data] = &PrivateChat{
778 ClientConn: make(map[uint16]*ClientConn),
780 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
785 const dlFldrActionSendFile = 1
786 const dlFldrActionResumeFile = 2
787 const dlFldrActionNextFile = 3
789 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
790 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
791 defer dontPanic(s.Logger)
793 txBuf := make([]byte, 16)
794 if _, err := io.ReadFull(rwc, txBuf); err != nil {
799 if _, err := t.Write(txBuf); err != nil {
805 delete(s.fileTransfers, t.ReferenceNumber)
808 // Wait a few seconds before closing the connection: this is a workaround for problems
809 // observed with Windows clients where the client must initiate close of the TCP connection before
810 // the server does. This is gross and seems unnecessary. TODO: Revisit?
811 time.Sleep(3 * time.Second)
815 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
818 return errors.New("invalid transaction ID")
822 fileTransfer.ClientConn.transfersMU.Lock()
823 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
824 fileTransfer.ClientConn.transfersMU.Unlock()
827 rLogger := s.Logger.With(
828 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
829 "login", fileTransfer.ClientConn.Account.Login,
830 "name", string(fileTransfer.ClientConn.UserName),
833 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
838 switch fileTransfer.Type {
840 if err := s.bannerDownload(rwc); err != nil {
844 s.Stats.DownloadCounter += 1
845 s.Stats.DownloadsInProgress += 1
847 s.Stats.DownloadsInProgress -= 1
851 if fileTransfer.fileResumeData != nil {
852 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
855 fw, err := newFileWrapper(s.FS, fullPath, 0)
860 rLogger.Infow("File download started", "filePath", fullPath)
862 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
863 if fileTransfer.options == nil {
864 // Start by sending flat file object to client
865 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
870 file, err := fw.dataForkReader()
875 br := bufio.NewReader(file)
876 if _, err := br.Discard(int(dataOffset)); err != nil {
880 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
884 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
885 if fileTransfer.fileResumeData == nil {
886 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
892 rFile, err := fw.rsrcForkFile()
897 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
902 s.Stats.UploadCounter += 1
903 s.Stats.UploadsInProgress += 1
904 defer func() { s.Stats.UploadsInProgress -= 1 }()
908 // A file upload has three possible cases:
909 // 1) Upload a new file
910 // 2) Resume a partially transferred file
911 // 3) Replace a fully uploaded file
912 // We have to infer which case applies by inspecting what is already on the filesystem
914 // 1) Check for existing file:
915 _, err = os.Stat(fullPath)
917 return errors.New("existing file found at " + fullPath)
919 if errors.Is(err, fs.ErrNotExist) {
920 // If not found, open or create a new .incomplete file
921 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
927 f, err := newFileWrapper(s.FS, fullPath, 0)
932 rLogger.Infow("File upload started", "dstFile", fullPath)
934 rForkWriter := io.Discard
935 iForkWriter := io.Discard
936 if s.Config.PreserveResourceForks {
937 rForkWriter, err = f.rsrcForkWriter()
942 iForkWriter, err = f.infoForkWriter()
948 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
952 if err := file.Close(); err != nil {
956 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
960 rLogger.Infow("File upload complete", "dstFile", fullPath)
963 s.Stats.DownloadCounter += 1
964 s.Stats.DownloadsInProgress += 1
965 defer func() { s.Stats.DownloadsInProgress -= 1 }()
967 // Folder Download flow:
968 // 1. Get filePath from the transfer
969 // 2. Iterate over files
970 // 3. For each fileWrapper:
971 // Send fileWrapper header to client
972 // The client can reply in 3 ways:
974 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
975 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
977 // 2. If download of a fileWrapper is to be resumed:
979 // []byte{0x00, 0x02} // download folder action
980 // [2]byte // Resume data size
981 // []byte fileWrapper resume data (see myField_FileResumeData)
983 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
985 // When download is requested (case 2 or 3), server replies with:
986 // [4]byte - fileWrapper size
987 // []byte - Flattened File Object
989 // After every fileWrapper download, client could request next fileWrapper with:
990 // []byte{0x00, 0x03}
992 // This notifies the server to send the next item header
994 basePathLen := len(fullPath)
996 rLogger.Infow("Start folder download", "path", fullPath)
998 nextAction := make([]byte, 2)
999 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1004 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
1005 s.Stats.DownloadCounter += 1
1013 if strings.HasPrefix(info.Name(), ".") {
1017 hlFile, err := newFileWrapper(s.FS, path, 0)
1022 subPath := path[basePathLen+1:]
1023 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
1029 fileHeader := NewFileHeader(subPath, info.IsDir())
1031 // Send the fileWrapper header to client
1032 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
1033 s.Logger.Errorf("error sending file header: %v", err)
1037 // Read the client's Next Action request
1038 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1042 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
1044 var dataOffset int64
1046 switch nextAction[1] {
1047 case dlFldrActionResumeFile:
1048 // get size of resumeData
1049 resumeDataByteLen := make([]byte, 2)
1050 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
1054 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
1055 resumeDataBytes := make([]byte, resumeDataLen)
1056 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1060 var frd FileResumeData
1061 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1064 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1065 case dlFldrActionNextFile:
1066 // client asked to skip this file
1074 rLogger.Infow("File download started",
1075 "fileName", info.Name(),
1076 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1079 // Send file size to client
1080 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1085 // Send ffo bytes to client
1086 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1091 file, err := s.FS.Open(path)
1096 // wr := bufio.NewWriterSize(rwc, 1460)
1097 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1101 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1102 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1107 rFile, err := hlFile.rsrcForkFile()
1112 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1117 // Read the client's Next Action request. This is always 3, I think?
1118 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1130 s.Stats.UploadCounter += 1
1131 s.Stats.UploadsInProgress += 1
1132 defer func() { s.Stats.UploadsInProgress -= 1 }()
1134 "Folder upload started",
1135 "dstPath", fullPath,
1136 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1137 "FolderItemCount", fileTransfer.FolderItemCount,
1140 // Check if the target folder exists. If not, create it.
1141 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1142 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1147 // Begin the folder upload flow by sending the "next file action" to client
1148 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1152 fileSize := make([]byte, 4)
1154 for i := 0; i < fileTransfer.ItemCount(); i++ {
1155 s.Stats.UploadCounter += 1
1158 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1161 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1164 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1168 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1170 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1175 "Folder upload continued",
1176 "FormattedPath", fu.FormattedPath(),
1177 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1178 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1181 if fu.IsFolder == [2]byte{0, 1} {
1182 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1183 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1188 // Tell client to send next file
1189 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1193 nextAction := dlFldrActionSendFile
1195 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1196 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1197 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1201 nextAction = dlFldrActionNextFile
1204 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1205 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1206 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1210 nextAction = dlFldrActionResumeFile
1213 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1218 case dlFldrActionNextFile:
1220 case dlFldrActionResumeFile:
1221 offset := make([]byte, 4)
1222 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1224 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1229 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1231 b, _ := fileResumeData.BinaryMarshal()
1233 bs := make([]byte, 2)
1234 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1236 if _, err := rwc.Write(append(bs, b...)); err != nil {
1240 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1244 if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil {
1248 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1253 case dlFldrActionSendFile:
1254 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1258 filePath := filepath.Join(fullPath, fu.FormattedPath())
1260 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1265 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1267 incWriter, err := hlFile.incFileWriter()
1272 rForkWriter := io.Discard
1273 iForkWriter := io.Discard
1274 if s.Config.PreserveResourceForks {
1275 iForkWriter, err = hlFile.infoForkWriter()
1280 rForkWriter, err = hlFile.rsrcForkWriter()
1285 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1289 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1294 // Tell client to send next fileWrapper
1295 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1300 rLogger.Infof("Folder upload complete")