9 "github.com/go-playground/validator/v10"
24 type contextKey string
26 var contextKeyReq = contextKey("req")
28 type requestCtx struct {
36 Accounts map[string]*Account
38 Clients map[uint16]*ClientConn
39 fileTransfers map[[4]byte]*FileTransfer
43 Logger *zap.SugaredLogger
45 PrivateChatsMu sync.Mutex
46 PrivateChats map[uint32]*PrivateChat
54 FS FileStore // Storage backend to use for File storage
56 outbox chan Transaction
59 threadedNewsMux sync.Mutex
60 ThreadedNews *ThreadedNews
62 flatNewsMux sync.Mutex
66 banList map[string]*time.Time
69 func (s *Server) CurrentStats() Stats {
71 defer s.StatsMu.Unlock()
74 stats.CurrentlyConnected = len(s.Clients)
79 type PrivateChat struct {
81 ClientConn map[uint16]*ClientConn
84 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
85 s.Logger.Infow("Hotline server started",
87 "API port", fmt.Sprintf(":%v", s.Port),
88 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
95 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
100 s.Logger.Fatal(s.Serve(ctx, ln))
105 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
111 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
119 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
121 conn, err := ln.Accept()
127 defer func() { _ = conn.Close() }()
129 err = s.handleFileTransfer(
130 context.WithValue(ctx, contextKeyReq, requestCtx{
131 remoteAddr: conn.RemoteAddr().String(),
137 s.Logger.Errorw("file transfer error", "reason", err)
143 func (s *Server) sendTransaction(t Transaction) error {
144 clientID, err := byteToInt(*t.clientID)
150 client := s.Clients[uint16(clientID)]
153 return fmt.Errorf("invalid client id %v", *t.clientID)
156 b, err := t.MarshalBinary()
161 _, err = client.Connection.Write(b)
169 func (s *Server) processOutbox() {
173 if err := s.sendTransaction(t); err != nil {
174 s.Logger.Errorw("error sending transaction", "err", err)
180 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
184 conn, err := ln.Accept()
186 s.Logger.Errorw("error accepting connection", "err", err)
188 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
189 remoteAddr: conn.RemoteAddr().String(),
193 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
196 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
198 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
200 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
208 agreementFile = "Agreement.txt"
211 // NewServer constructs a new Server from a config dir
212 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
215 Accounts: make(map[string]*Account),
217 Clients: make(map[uint16]*ClientConn),
218 fileTransfers: make(map[[4]byte]*FileTransfer),
219 PrivateChats: make(map[uint32]*PrivateChat),
220 ConfigDir: configDir,
222 NextGuestID: new(uint16),
223 outbox: make(chan Transaction),
224 Stats: &Stats{Since: time.Now()},
225 ThreadedNews: &ThreadedNews{},
227 banList: make(map[string]*time.Time),
232 // generate a new random passID for tracker registration
233 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
237 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
242 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
246 // try to load the ban list, but ignore errors as this file may not be present or may be empty
247 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
249 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
253 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
257 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
261 server.Config.FileRoot = filepath.Join(configDir, "Files")
263 *server.NextGuestID = 1
265 if server.Config.EnableTrackerRegistration {
267 "Tracker registration enabled",
268 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
269 "trackers", server.Config.Trackers,
274 tr := &TrackerRegistration{
275 UserCount: server.userCount(),
276 PassID: server.TrackerPassID[:],
277 Name: server.Config.Name,
278 Description: server.Config.Description,
280 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
281 for _, t := range server.Config.Trackers {
282 if err := register(t, tr); err != nil {
283 server.Logger.Errorw("unable to register with tracker %v", "error", err)
285 server.Logger.Debugw("Sent Tracker registration", "addr", t)
288 time.Sleep(trackerUpdateFrequency * time.Second)
293 // Start Client Keepalive go routine
294 go server.keepaliveHandler()
299 func (s *Server) userCount() int {
303 return len(s.Clients)
306 func (s *Server) keepaliveHandler() {
308 time.Sleep(idleCheckInterval * time.Second)
311 for _, c := range s.Clients {
312 c.IdleTime += idleCheckInterval
313 if c.IdleTime > userIdleSeconds && !c.Idle {
316 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
317 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
318 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
321 TranNotifyChangeUser,
322 NewField(FieldUserID, *c.ID),
323 NewField(FieldUserFlags, c.Flags),
324 NewField(FieldUserName, c.UserName),
325 NewField(FieldUserIconID, c.Icon),
333 func (s *Server) writeBanList() error {
335 defer s.banListMU.Unlock()
337 out, err := yaml.Marshal(s.banList)
342 filepath.Join(s.ConfigDir, "Banlist.yaml"),
349 func (s *Server) writeThreadedNews() error {
350 s.threadedNewsMux.Lock()
351 defer s.threadedNewsMux.Unlock()
353 out, err := yaml.Marshal(s.ThreadedNews)
357 err = s.FS.WriteFile(
358 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
365 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
369 clientConn := &ClientConn{
378 transfers: map[int]map[[4]byte]*FileTransfer{},
379 RemoteAddr: remoteAddr,
381 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
392 binary.BigEndian.PutUint16(*clientConn.ID, ID)
393 s.Clients[ID] = clientConn
398 // NewUser creates a new user account entry in the server map and config file
399 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
406 Password: hashAndSalt([]byte(password)),
409 out, err := yaml.Marshal(&account)
413 s.Accounts[login] = &account
415 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
418 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
422 // update renames the user login
423 if login != newLogin {
424 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
428 s.Accounts[newLogin] = s.Accounts[login]
429 delete(s.Accounts, login)
432 account := s.Accounts[newLogin]
433 account.Access = access
435 account.Password = password
437 out, err := yaml.Marshal(&account)
442 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
449 // DeleteUser deletes the user account
450 func (s *Server) DeleteUser(login string) error {
454 delete(s.Accounts, login)
456 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
459 func (s *Server) connectedUsers() []Field {
463 var connectedUsers []Field
464 for _, c := range sortedClients(s.Clients) {
469 Name: string(c.UserName),
471 connectedUsers = append(connectedUsers, NewField(FieldUsernameWithInfo, user.Payload()))
473 return connectedUsers
476 func (s *Server) loadBanList(path string) error {
477 fh, err := os.Open(path)
481 decoder := yaml.NewDecoder(fh)
483 return decoder.Decode(s.banList)
486 // loadThreadedNews loads the threaded news data from disk
487 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
488 fh, err := os.Open(threadedNewsPath)
492 decoder := yaml.NewDecoder(fh)
494 return decoder.Decode(s.ThreadedNews)
497 // loadAccounts loads account data from disk
498 func (s *Server) loadAccounts(userDir string) error {
499 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
504 if len(matches) == 0 {
505 return errors.New("no user accounts found in " + userDir)
508 for _, file := range matches {
509 fh, err := s.FS.Open(file)
515 decoder := yaml.NewDecoder(fh)
516 if err := decoder.Decode(&account); err != nil {
520 s.Accounts[account.Login] = &account
525 func (s *Server) loadConfig(path string) error {
526 fh, err := s.FS.Open(path)
531 decoder := yaml.NewDecoder(fh)
532 err = decoder.Decode(s.Config)
537 validate := validator.New()
538 err = validate.Struct(s.Config)
545 // handleNewConnection takes a new net.Conn and performs the initial login sequence
546 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
547 defer dontPanic(s.Logger)
549 if err := Handshake(rwc); err != nil {
553 // Create a new scanner for parsing incoming bytes into transaction tokens
554 scanner := bufio.NewScanner(rwc)
555 scanner.Split(transactionScanner)
559 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
560 // scanner re-uses the buffer for subsequent scans.
561 buf := make([]byte, len(scanner.Bytes()))
562 copy(buf, scanner.Bytes())
564 var clientLogin Transaction
565 if _, err := clientLogin.Write(buf); err != nil {
569 // check if remoteAddr is present in the ban list
570 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
576 NewField(FieldData, []byte("You are permanently banned on this server")),
577 NewField(FieldChatOptions, []byte{0, 0}),
580 b, err := t.MarshalBinary()
585 _, err = rwc.Write(b)
590 time.Sleep(1 * time.Second)
595 if time.Now().Before(*banUntil) {
599 NewField(FieldData, []byte("You are temporarily banned on this server")),
600 NewField(FieldChatOptions, []byte{0, 0}),
602 b, err := t.MarshalBinary()
607 _, err = rwc.Write(b)
612 time.Sleep(1 * time.Second)
617 c := s.NewClientConn(rwc, remoteAddr)
620 encodedLogin := clientLogin.GetField(FieldUserLogin).Data
621 encodedPassword := clientLogin.GetField(FieldUserPassword).Data
622 c.Version = clientLogin.GetField(FieldVersion).Data
625 for _, char := range encodedLogin {
626 login += string(rune(255 - uint(char)))
632 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
634 // If authentication fails, send error reply and close connection
635 if !c.Authenticate(login, encodedPassword) {
636 t := c.NewErrReply(&clientLogin, "Incorrect login.")
637 b, err := t.MarshalBinary()
641 if _, err := rwc.Write(b); err != nil {
645 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
650 if clientLogin.GetField(FieldUserIconID).Data != nil {
651 c.Icon = clientLogin.GetField(FieldUserIconID).Data
654 c.Account = c.Server.Accounts[login]
656 if clientLogin.GetField(FieldUserName).Data != nil {
657 if c.Authorize(accessAnyName) {
658 c.UserName = clientLogin.GetField(FieldUserName).Data
660 c.UserName = []byte(c.Account.Name)
664 if c.Authorize(accessDisconUser) {
665 c.Flags = []byte{0, 2}
668 s.outbox <- c.NewReply(&clientLogin,
669 NewField(FieldVersion, []byte{0x00, 0xbe}),
670 NewField(FieldCommunityBannerID, []byte{0, 0}),
671 NewField(FieldServerName, []byte(s.Config.Name)),
674 // Send user access privs so client UI knows how to behave
675 c.Server.outbox <- *NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:]))
677 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
678 // client versions. For 1.2.3 client, we do not send TranShowAgreement. For other client versions, we send
679 // TranShowAgreement but with the NoServerAgreement field set to 1.
680 if c.Authorize(accessNoAgreement) {
681 // If client version is nil, then the client uses the 1.2.3 login behavior
682 if c.Version != nil {
683 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1}))
686 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement))
689 // If the client has provided a username as part of the login, we can infer that it is using the 1.2.3 login
690 // flow and not the 1.5+ flow.
691 if len(c.UserName) != 0 {
692 // Add the client username to the logger. For 1.5+ clients, we don't have this information yet as it comes as
693 // part of TranAgreed
694 c.logger = c.logger.With("name", string(c.UserName))
696 c.logger.Infow("Login successful", "clientVersion", "Not sent (probably 1.2.3)")
698 // Notify other clients on the server that the new user has logged in. For 1.5+ clients we don't have this
699 // information yet, so we do it in TranAgreed instead
700 for _, t := range c.notifyOthers(
702 TranNotifyChangeUser, nil,
703 NewField(FieldUserName, c.UserName),
704 NewField(FieldUserID, *c.ID),
705 NewField(FieldUserIconID, c.Icon),
706 NewField(FieldUserFlags, c.Flags),
713 c.Server.Stats.ConnectionCounter += 1
714 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
715 c.Server.Stats.ConnectionPeak = len(s.Clients)
718 // Scan for new transactions and handle them as they come in.
720 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
721 // scanner re-uses the buffer for subsequent scans.
722 buf := make([]byte, len(scanner.Bytes()))
723 copy(buf, scanner.Bytes())
726 if _, err := t.Write(buf); err != nil {
730 if err := c.handleTransaction(t); err != nil {
731 c.logger.Errorw("Error handling transaction", "err", err)
737 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
738 s.PrivateChatsMu.Lock()
739 defer s.PrivateChatsMu.Unlock()
741 randID := make([]byte, 4)
743 data := binary.BigEndian.Uint32(randID[:])
745 s.PrivateChats[data] = &PrivateChat{
746 ClientConn: make(map[uint16]*ClientConn),
748 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
753 const dlFldrActionSendFile = 1
754 const dlFldrActionResumeFile = 2
755 const dlFldrActionNextFile = 3
757 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
758 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
759 defer dontPanic(s.Logger)
761 txBuf := make([]byte, 16)
762 if _, err := io.ReadFull(rwc, txBuf); err != nil {
767 if _, err := t.Write(txBuf); err != nil {
773 delete(s.fileTransfers, t.ReferenceNumber)
776 // Wait a few seconds before closing the connection: this is a workaround for problems
777 // observed with Windows clients where the client must initiate close of the TCP connection before
778 // the server does. This is gross and seems unnecessary. TODO: Revisit?
779 time.Sleep(3 * time.Second)
783 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
786 return errors.New("invalid transaction ID")
790 fileTransfer.ClientConn.transfersMU.Lock()
791 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
792 fileTransfer.ClientConn.transfersMU.Unlock()
795 rLogger := s.Logger.With(
796 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
797 "login", fileTransfer.ClientConn.Account.Login,
798 "name", string(fileTransfer.ClientConn.UserName),
801 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
806 switch fileTransfer.Type {
808 if err := s.bannerDownload(rwc); err != nil {
812 s.Stats.DownloadCounter += 1
813 s.Stats.DownloadsInProgress += 1
815 s.Stats.DownloadsInProgress -= 1
819 if fileTransfer.fileResumeData != nil {
820 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
823 fw, err := newFileWrapper(s.FS, fullPath, 0)
828 rLogger.Infow("File download started", "filePath", fullPath)
830 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
831 if fileTransfer.options == nil {
832 // Start by sending flat file object to client
833 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
838 file, err := fw.dataForkReader()
843 br := bufio.NewReader(file)
844 if _, err := br.Discard(int(dataOffset)); err != nil {
848 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
852 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
853 if fileTransfer.fileResumeData == nil {
854 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
860 rFile, err := fw.rsrcForkFile()
865 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
870 s.Stats.UploadCounter += 1
871 s.Stats.UploadsInProgress += 1
872 defer func() { s.Stats.UploadsInProgress -= 1 }()
876 // A file upload has three possible cases:
877 // 1) Upload a new file
878 // 2) Resume a partially transferred file
879 // 3) Replace a fully uploaded file
880 // We have to infer which case applies by inspecting what is already on the filesystem
882 // 1) Check for existing file:
883 _, err = os.Stat(fullPath)
885 return errors.New("existing file found at " + fullPath)
887 if errors.Is(err, fs.ErrNotExist) {
888 // If not found, open or create a new .incomplete file
889 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
895 f, err := newFileWrapper(s.FS, fullPath, 0)
900 rLogger.Infow("File upload started", "dstFile", fullPath)
902 rForkWriter := io.Discard
903 iForkWriter := io.Discard
904 if s.Config.PreserveResourceForks {
905 rForkWriter, err = f.rsrcForkWriter()
910 iForkWriter, err = f.infoForkWriter()
916 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
920 if err := file.Close(); err != nil {
924 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
928 rLogger.Infow("File upload complete", "dstFile", fullPath)
931 s.Stats.DownloadCounter += 1
932 s.Stats.DownloadsInProgress += 1
933 defer func() { s.Stats.DownloadsInProgress -= 1 }()
935 // Folder Download flow:
936 // 1. Get filePath from the transfer
937 // 2. Iterate over files
938 // 3. For each fileWrapper:
939 // Send fileWrapper header to client
940 // The client can reply in 3 ways:
942 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
943 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
945 // 2. If download of a fileWrapper is to be resumed:
947 // []byte{0x00, 0x02} // download folder action
948 // [2]byte // Resume data size
949 // []byte fileWrapper resume data (see myField_FileResumeData)
951 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
953 // When download is requested (case 2 or 3), server replies with:
954 // [4]byte - fileWrapper size
955 // []byte - Flattened File Object
957 // After every fileWrapper download, client could request next fileWrapper with:
958 // []byte{0x00, 0x03}
960 // This notifies the server to send the next item header
962 basePathLen := len(fullPath)
964 rLogger.Infow("Start folder download", "path", fullPath)
966 nextAction := make([]byte, 2)
967 if _, err := io.ReadFull(rwc, nextAction); err != nil {
972 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
973 s.Stats.DownloadCounter += 1
981 if strings.HasPrefix(info.Name(), ".") {
985 hlFile, err := newFileWrapper(s.FS, path, 0)
990 subPath := path[basePathLen+1:]
991 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
997 fileHeader := NewFileHeader(subPath, info.IsDir())
999 // Send the fileWrapper header to client
1000 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
1001 s.Logger.Errorf("error sending file header: %v", err)
1005 // Read the client's Next Action request
1006 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1010 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
1012 var dataOffset int64
1014 switch nextAction[1] {
1015 case dlFldrActionResumeFile:
1016 // get size of resumeData
1017 resumeDataByteLen := make([]byte, 2)
1018 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
1022 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
1023 resumeDataBytes := make([]byte, resumeDataLen)
1024 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1028 var frd FileResumeData
1029 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1032 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1033 case dlFldrActionNextFile:
1034 // client asked to skip this file
1042 rLogger.Infow("File download started",
1043 "fileName", info.Name(),
1044 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1047 // Send file size to client
1048 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1053 // Send ffo bytes to client
1054 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1059 file, err := s.FS.Open(path)
1064 // wr := bufio.NewWriterSize(rwc, 1460)
1065 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1069 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1070 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1075 rFile, err := hlFile.rsrcForkFile()
1080 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1085 // Read the client's Next Action request. This is always 3, I think?
1086 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1098 s.Stats.UploadCounter += 1
1099 s.Stats.UploadsInProgress += 1
1100 defer func() { s.Stats.UploadsInProgress -= 1 }()
1102 "Folder upload started",
1103 "dstPath", fullPath,
1104 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1105 "FolderItemCount", fileTransfer.FolderItemCount,
1108 // Check if the target folder exists. If not, create it.
1109 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1110 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1115 // Begin the folder upload flow by sending the "next file action" to client
1116 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1120 fileSize := make([]byte, 4)
1122 for i := 0; i < fileTransfer.ItemCount(); i++ {
1123 s.Stats.UploadCounter += 1
1126 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1129 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1132 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1136 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1138 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1143 "Folder upload continued",
1144 "FormattedPath", fu.FormattedPath(),
1145 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1146 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1149 if fu.IsFolder == [2]byte{0, 1} {
1150 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1151 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1156 // Tell client to send next file
1157 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1161 nextAction := dlFldrActionSendFile
1163 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1164 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1165 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1169 nextAction = dlFldrActionNextFile
1172 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1173 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1174 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1178 nextAction = dlFldrActionResumeFile
1181 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1186 case dlFldrActionNextFile:
1188 case dlFldrActionResumeFile:
1189 offset := make([]byte, 4)
1190 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1192 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1197 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1199 b, _ := fileResumeData.BinaryMarshal()
1201 bs := make([]byte, 2)
1202 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1204 if _, err := rwc.Write(append(bs, b...)); err != nil {
1208 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1212 if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil {
1216 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1221 case dlFldrActionSendFile:
1222 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1226 filePath := filepath.Join(fullPath, fu.FormattedPath())
1228 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1233 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1235 incWriter, err := hlFile.incFileWriter()
1240 rForkWriter := io.Discard
1241 iForkWriter := io.Discard
1242 if s.Config.PreserveResourceForks {
1243 iForkWriter, err = hlFile.infoForkWriter()
1248 rForkWriter, err = hlFile.rsrcForkWriter()
1253 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1257 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1262 // Tell client to send next fileWrapper
1263 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1268 rLogger.Infof("Folder upload complete")