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))
110 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
118 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
120 conn, err := ln.Accept()
126 defer func() { _ = conn.Close() }()
128 err = s.handleFileTransfer(
129 context.WithValue(ctx, contextKeyReq, requestCtx{
130 remoteAddr: conn.RemoteAddr().String(),
136 s.Logger.Errorw("file transfer error", "reason", err)
142 func (s *Server) sendTransaction(t Transaction) error {
143 clientID, err := byteToInt(*t.clientID)
149 client := s.Clients[uint16(clientID)]
152 return fmt.Errorf("invalid client id %v", *t.clientID)
155 b, err := t.MarshalBinary()
160 _, err = client.Connection.Write(b)
168 func (s *Server) processOutbox() {
172 if err := s.sendTransaction(t); err != nil {
173 s.Logger.Errorw("error sending transaction", "err", err)
179 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
183 conn, err := ln.Accept()
185 s.Logger.Errorw("error accepting connection", "err", err)
187 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
188 remoteAddr: conn.RemoteAddr().String(),
192 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
195 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
197 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
199 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
207 agreementFile = "Agreement.txt"
210 // NewServer constructs a new Server from a config dir
211 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, fs FileStore) (*Server, error) {
214 Accounts: make(map[string]*Account),
216 Clients: make(map[uint16]*ClientConn),
217 fileTransfers: make(map[[4]byte]*FileTransfer),
218 PrivateChats: make(map[uint32]*PrivateChat),
219 ConfigDir: configDir,
221 NextGuestID: new(uint16),
222 outbox: make(chan Transaction),
223 Stats: &Stats{Since: time.Now()},
224 ThreadedNews: &ThreadedNews{},
226 banList: make(map[string]*time.Time),
231 // generate a new random passID for tracker registration
232 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
236 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
241 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
245 // try to load the ban list, but ignore errors as this file may not be present or may be empty
246 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
248 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
252 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
256 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
260 server.Config.FileRoot = filepath.Join(configDir, "Files")
262 *server.NextGuestID = 1
264 if server.Config.EnableTrackerRegistration {
266 "Tracker registration enabled",
267 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
268 "trackers", server.Config.Trackers,
273 tr := &TrackerRegistration{
274 UserCount: server.userCount(),
275 PassID: server.TrackerPassID[:],
276 Name: server.Config.Name,
277 Description: server.Config.Description,
279 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
280 for _, t := range server.Config.Trackers {
281 if err := register(t, tr); err != nil {
282 server.Logger.Errorw("unable to register with tracker %v", "error", err)
284 server.Logger.Debugw("Sent Tracker registration", "addr", t)
287 time.Sleep(trackerUpdateFrequency * time.Second)
292 // Start Client Keepalive go routine
293 go server.keepaliveHandler()
298 func (s *Server) userCount() int {
302 return len(s.Clients)
305 func (s *Server) keepaliveHandler() {
307 time.Sleep(idleCheckInterval * time.Second)
310 for _, c := range s.Clients {
311 c.IdleTime += idleCheckInterval
312 if c.IdleTime > userIdleSeconds && !c.Idle {
315 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
316 flagBitmap.SetBit(flagBitmap, UserFlagAway, 1)
317 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
320 TranNotifyChangeUser,
321 NewField(FieldUserID, *c.ID),
322 NewField(FieldUserFlags, c.Flags),
323 NewField(FieldUserName, c.UserName),
324 NewField(FieldUserIconID, c.Icon),
332 func (s *Server) writeBanList() error {
334 defer s.banListMU.Unlock()
336 out, err := yaml.Marshal(s.banList)
341 filepath.Join(s.ConfigDir, "Banlist.yaml"),
348 func (s *Server) writeThreadedNews() error {
349 s.threadedNewsMux.Lock()
350 defer s.threadedNewsMux.Unlock()
352 out, err := yaml.Marshal(s.ThreadedNews)
356 err = s.FS.WriteFile(
357 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
364 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
368 clientConn := &ClientConn{
377 transfers: map[int]map[[4]byte]*FileTransfer{},
378 RemoteAddr: remoteAddr,
380 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
391 binary.BigEndian.PutUint16(*clientConn.ID, ID)
392 s.Clients[ID] = clientConn
397 // NewUser creates a new user account entry in the server map and config file
398 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
405 Password: hashAndSalt([]byte(password)),
408 out, err := yaml.Marshal(&account)
412 s.Accounts[login] = &account
414 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
417 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
421 // update renames the user login
422 if login != newLogin {
423 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
427 s.Accounts[newLogin] = s.Accounts[login]
428 delete(s.Accounts, login)
431 account := s.Accounts[newLogin]
432 account.Access = access
434 account.Password = password
436 out, err := yaml.Marshal(&account)
441 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
448 // DeleteUser deletes the user account
449 func (s *Server) DeleteUser(login string) error {
453 delete(s.Accounts, login)
455 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
458 func (s *Server) connectedUsers() []Field {
462 var connectedUsers []Field
463 for _, c := range sortedClients(s.Clients) {
468 Name: string(c.UserName),
470 connectedUsers = append(connectedUsers, NewField(FieldUsernameWithInfo, user.Payload()))
472 return connectedUsers
475 func (s *Server) loadBanList(path string) error {
476 fh, err := os.Open(path)
480 decoder := yaml.NewDecoder(fh)
482 return decoder.Decode(s.banList)
485 // loadThreadedNews loads the threaded news data from disk
486 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
487 fh, err := os.Open(threadedNewsPath)
491 decoder := yaml.NewDecoder(fh)
493 return decoder.Decode(s.ThreadedNews)
496 // loadAccounts loads account data from disk
497 func (s *Server) loadAccounts(userDir string) error {
498 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
503 if len(matches) == 0 {
504 return errors.New("no user accounts found in " + userDir)
507 for _, file := range matches {
508 fh, err := s.FS.Open(file)
514 decoder := yaml.NewDecoder(fh)
515 if err := decoder.Decode(&account); err != nil {
519 s.Accounts[account.Login] = &account
524 func (s *Server) loadConfig(path string) error {
525 fh, err := s.FS.Open(path)
530 decoder := yaml.NewDecoder(fh)
531 err = decoder.Decode(s.Config)
536 validate := validator.New()
537 err = validate.Struct(s.Config)
544 // handleNewConnection takes a new net.Conn and performs the initial login sequence
545 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
546 defer dontPanic(s.Logger)
548 if err := Handshake(rwc); err != nil {
552 // Create a new scanner for parsing incoming bytes into transaction tokens
553 scanner := bufio.NewScanner(rwc)
554 scanner.Split(transactionScanner)
558 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
559 // scanner re-uses the buffer for subsequent scans.
560 buf := make([]byte, len(scanner.Bytes()))
561 copy(buf, scanner.Bytes())
563 var clientLogin Transaction
564 if _, err := clientLogin.Write(buf); err != nil {
568 // check if remoteAddr is present in the ban list
569 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
575 NewField(FieldData, []byte("You are permanently banned on this server")),
576 NewField(FieldChatOptions, []byte{0, 0}),
579 b, err := t.MarshalBinary()
584 _, err = rwc.Write(b)
589 time.Sleep(1 * time.Second)
594 if time.Now().Before(*banUntil) {
598 NewField(FieldData, []byte("You are temporarily banned on this server")),
599 NewField(FieldChatOptions, []byte{0, 0}),
601 b, err := t.MarshalBinary()
606 _, err = rwc.Write(b)
611 time.Sleep(1 * time.Second)
616 c := s.NewClientConn(rwc, remoteAddr)
619 encodedLogin := clientLogin.GetField(FieldUserLogin).Data
620 encodedPassword := clientLogin.GetField(FieldUserPassword).Data
621 c.Version = clientLogin.GetField(FieldVersion).Data
624 for _, char := range encodedLogin {
625 login += string(rune(255 - uint(char)))
631 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
633 // If authentication fails, send error reply and close connection
634 if !c.Authenticate(login, encodedPassword) {
635 t := c.NewErrReply(&clientLogin, "Incorrect login.")
636 b, err := t.MarshalBinary()
640 if _, err := rwc.Write(b); err != nil {
644 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
649 if clientLogin.GetField(FieldUserIconID).Data != nil {
650 c.Icon = clientLogin.GetField(FieldUserIconID).Data
653 c.Account = c.Server.Accounts[login]
655 if clientLogin.GetField(FieldUserName).Data != nil {
656 if c.Authorize(accessAnyName) {
657 c.UserName = clientLogin.GetField(FieldUserName).Data
659 c.UserName = []byte(c.Account.Name)
663 if c.Authorize(accessDisconUser) {
664 c.Flags = []byte{0, 2}
667 s.outbox <- c.NewReply(&clientLogin,
668 NewField(FieldVersion, []byte{0x00, 0xbe}),
669 NewField(FieldCommunityBannerID, []byte{0, 0}),
670 NewField(FieldServerName, []byte(s.Config.Name)),
673 // Send user access privs so client UI knows how to behave
674 c.Server.outbox <- *NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:]))
676 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
677 // client versions. For 1.2.3 client, we do not send TranShowAgreement. For other client versions, we send
678 // TranShowAgreement but with the NoServerAgreement field set to 1.
679 if c.Authorize(accessNoAgreement) {
680 // If client version is nil, then the client uses the 1.2.3 login behavior
681 if c.Version != nil {
682 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1}))
685 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement))
688 // If the client has provided a username as part of the login, we can infer that it is using the 1.2.3 login
689 // flow and not the 1.5+ flow.
690 if len(c.UserName) != 0 {
691 // Add the client username to the logger. For 1.5+ clients, we don't have this information yet as it comes as
692 // part of TranAgreed
693 c.logger = c.logger.With("name", string(c.UserName))
695 c.logger.Infow("Login successful", "clientVersion", "Not sent (probably 1.2.3)")
697 // Notify other clients on the server that the new user has logged in. For 1.5+ clients we don't have this
698 // information yet, so we do it in TranAgreed instead
699 for _, t := range c.notifyOthers(
701 TranNotifyChangeUser, nil,
702 NewField(FieldUserName, c.UserName),
703 NewField(FieldUserID, *c.ID),
704 NewField(FieldUserIconID, c.Icon),
705 NewField(FieldUserFlags, c.Flags),
712 c.Server.Stats.ConnectionCounter += 1
713 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
714 c.Server.Stats.ConnectionPeak = len(s.Clients)
717 // Scan for new transactions and handle them as they come in.
719 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
720 // scanner re-uses the buffer for subsequent scans.
721 buf := make([]byte, len(scanner.Bytes()))
722 copy(buf, scanner.Bytes())
725 if _, err := t.Write(buf); err != nil {
729 if err := c.handleTransaction(t); err != nil {
730 c.logger.Errorw("Error handling transaction", "err", err)
736 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
737 s.PrivateChatsMu.Lock()
738 defer s.PrivateChatsMu.Unlock()
740 randID := make([]byte, 4)
742 data := binary.BigEndian.Uint32(randID)
744 s.PrivateChats[data] = &PrivateChat{
745 ClientConn: make(map[uint16]*ClientConn),
747 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
752 const dlFldrActionSendFile = 1
753 const dlFldrActionResumeFile = 2
754 const dlFldrActionNextFile = 3
756 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
757 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
758 defer dontPanic(s.Logger)
760 txBuf := make([]byte, 16)
761 if _, err := io.ReadFull(rwc, txBuf); err != nil {
766 if _, err := t.Write(txBuf); err != nil {
772 delete(s.fileTransfers, t.ReferenceNumber)
775 // Wait a few seconds before closing the connection: this is a workaround for problems
776 // observed with Windows clients where the client must initiate close of the TCP connection before
777 // the server does. This is gross and seems unnecessary. TODO: Revisit?
778 time.Sleep(3 * time.Second)
782 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
785 return errors.New("invalid transaction ID")
789 fileTransfer.ClientConn.transfersMU.Lock()
790 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
791 fileTransfer.ClientConn.transfersMU.Unlock()
794 rLogger := s.Logger.With(
795 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
796 "login", fileTransfer.ClientConn.Account.Login,
797 "name", string(fileTransfer.ClientConn.UserName),
800 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
805 switch fileTransfer.Type {
807 if err := s.bannerDownload(rwc); err != nil {
811 s.Stats.DownloadCounter += 1
812 s.Stats.DownloadsInProgress += 1
814 s.Stats.DownloadsInProgress -= 1
818 if fileTransfer.fileResumeData != nil {
819 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
822 fw, err := newFileWrapper(s.FS, fullPath, 0)
827 rLogger.Infow("File download started", "filePath", fullPath)
829 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
830 if fileTransfer.options == nil {
831 // Start by sending flat file object to client
832 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
837 file, err := fw.dataForkReader()
842 br := bufio.NewReader(file)
843 if _, err := br.Discard(int(dataOffset)); err != nil {
847 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
851 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
852 if fileTransfer.fileResumeData == nil {
853 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
859 rFile, err := fw.rsrcForkFile()
864 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
869 s.Stats.UploadCounter += 1
870 s.Stats.UploadsInProgress += 1
871 defer func() { s.Stats.UploadsInProgress -= 1 }()
875 // A file upload has three possible cases:
876 // 1) Upload a new file
877 // 2) Resume a partially transferred file
878 // 3) Replace a fully uploaded file
879 // We have to infer which case applies by inspecting what is already on the filesystem
881 // 1) Check for existing file:
882 _, err = os.Stat(fullPath)
884 return errors.New("existing file found at " + fullPath)
886 if errors.Is(err, fs.ErrNotExist) {
887 // If not found, open or create a new .incomplete file
888 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
894 f, err := newFileWrapper(s.FS, fullPath, 0)
899 rLogger.Infow("File upload started", "dstFile", fullPath)
901 rForkWriter := io.Discard
902 iForkWriter := io.Discard
903 if s.Config.PreserveResourceForks {
904 rForkWriter, err = f.rsrcForkWriter()
909 iForkWriter, err = f.infoForkWriter()
915 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
919 if err := file.Close(); err != nil {
923 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
927 rLogger.Infow("File upload complete", "dstFile", fullPath)
930 s.Stats.DownloadCounter += 1
931 s.Stats.DownloadsInProgress += 1
932 defer func() { s.Stats.DownloadsInProgress -= 1 }()
934 // Folder Download flow:
935 // 1. Get filePath from the transfer
936 // 2. Iterate over files
937 // 3. For each fileWrapper:
938 // Send fileWrapper header to client
939 // The client can reply in 3 ways:
941 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
942 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
944 // 2. If download of a fileWrapper is to be resumed:
946 // []byte{0x00, 0x02} // download folder action
947 // [2]byte // Resume data size
948 // []byte fileWrapper resume data (see myField_FileResumeData)
950 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
952 // When download is requested (case 2 or 3), server replies with:
953 // [4]byte - fileWrapper size
954 // []byte - Flattened File Object
956 // After every fileWrapper download, client could request next fileWrapper with:
957 // []byte{0x00, 0x03}
959 // This notifies the server to send the next item header
961 basePathLen := len(fullPath)
963 rLogger.Infow("Start folder download", "path", fullPath)
965 nextAction := make([]byte, 2)
966 if _, err := io.ReadFull(rwc, nextAction); err != nil {
971 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
972 s.Stats.DownloadCounter += 1
980 if strings.HasPrefix(info.Name(), ".") {
984 hlFile, err := newFileWrapper(s.FS, path, 0)
989 subPath := path[basePathLen+1:]
990 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
996 fileHeader := NewFileHeader(subPath, info.IsDir())
998 // Send the fileWrapper header to client
999 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
1000 s.Logger.Errorf("error sending file header: %v", err)
1004 // Read the client's Next Action request
1005 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1009 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
1011 var dataOffset int64
1013 switch nextAction[1] {
1014 case dlFldrActionResumeFile:
1015 // get size of resumeData
1016 resumeDataByteLen := make([]byte, 2)
1017 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
1021 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
1022 resumeDataBytes := make([]byte, resumeDataLen)
1023 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1027 var frd FileResumeData
1028 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1031 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1032 case dlFldrActionNextFile:
1033 // client asked to skip this file
1041 rLogger.Infow("File download started",
1042 "fileName", info.Name(),
1043 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1046 // Send file size to client
1047 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1052 // Send ffo bytes to client
1053 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1058 file, err := s.FS.Open(path)
1063 // wr := bufio.NewWriterSize(rwc, 1460)
1064 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1068 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1069 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1074 rFile, err := hlFile.rsrcForkFile()
1079 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1084 // Read the client's Next Action request. This is always 3, I think?
1085 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1097 s.Stats.UploadCounter += 1
1098 s.Stats.UploadsInProgress += 1
1099 defer func() { s.Stats.UploadsInProgress -= 1 }()
1101 "Folder upload started",
1102 "dstPath", fullPath,
1103 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1104 "FolderItemCount", fileTransfer.FolderItemCount,
1107 // Check if the target folder exists. If not, create it.
1108 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1109 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1114 // Begin the folder upload flow by sending the "next file action" to client
1115 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1119 fileSize := make([]byte, 4)
1121 for i := 0; i < fileTransfer.ItemCount(); i++ {
1122 s.Stats.UploadCounter += 1
1125 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1128 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1131 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1135 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1137 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1142 "Folder upload continued",
1143 "FormattedPath", fu.FormattedPath(),
1144 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1145 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1148 if fu.IsFolder == [2]byte{0, 1} {
1149 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1150 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1155 // Tell client to send next file
1156 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1160 nextAction := dlFldrActionSendFile
1162 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1163 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1164 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1168 nextAction = dlFldrActionNextFile
1171 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1172 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1173 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1177 nextAction = dlFldrActionResumeFile
1180 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1185 case dlFldrActionNextFile:
1187 case dlFldrActionResumeFile:
1188 offset := make([]byte, 4)
1189 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1191 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1196 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1198 b, _ := fileResumeData.BinaryMarshal()
1200 bs := make([]byte, 2)
1201 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1203 if _, err := rwc.Write(append(bs, b...)); err != nil {
1207 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1211 if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil {
1215 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1220 case dlFldrActionSendFile:
1221 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1225 filePath := filepath.Join(fullPath, fu.FormattedPath())
1227 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1232 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1234 incWriter, err := hlFile.incFileWriter()
1239 rForkWriter := io.Discard
1240 iForkWriter := io.Discard
1241 if s.Config.PreserveResourceForks {
1242 iForkWriter, err = hlFile.infoForkWriter()
1247 rForkWriter, err = hlFile.rsrcForkWriter()
1252 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1256 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1261 // Tell client to send next fileWrapper
1262 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1267 rLogger.Infof("Folder upload complete")