9 "github.com/go-playground/validator/v10"
24 type contextKey string
26 var contextKeyReq = contextKey("req")
28 type requestCtx struct {
34 Accounts map[string]*Account
36 Clients map[uint16]*ClientConn
37 fileTransfers map[[4]byte]*FileTransfer
41 Logger *zap.SugaredLogger
43 PrivateChatsMu sync.Mutex
44 PrivateChats map[uint32]*PrivateChat
52 FS FileStore // Storage backend to use for File storage
54 outbox chan Transaction
57 threadedNewsMux sync.Mutex
58 ThreadedNews *ThreadedNews
60 flatNewsMux sync.Mutex
64 banList map[string]*time.Time
67 func (s *Server) CurrentStats() Stats {
69 defer s.StatsMu.Unlock()
72 stats.CurrentlyConnected = len(s.Clients)
77 type PrivateChat struct {
79 ClientConn map[uint16]*ClientConn
82 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
83 s.Logger.Infow("Hotline server started",
85 "API port", fmt.Sprintf(":%v", s.Port),
86 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
93 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
98 s.Logger.Fatal(s.Serve(ctx, ln))
103 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
108 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
116 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
118 conn, err := ln.Accept()
124 defer func() { _ = conn.Close() }()
126 err = s.handleFileTransfer(
127 context.WithValue(ctx, contextKeyReq, requestCtx{
128 remoteAddr: conn.RemoteAddr().String(),
134 s.Logger.Errorw("file transfer error", "reason", err)
140 func (s *Server) sendTransaction(t Transaction) error {
141 clientID, err := byteToInt(*t.clientID)
147 client := s.Clients[uint16(clientID)]
150 return fmt.Errorf("invalid client id %v", *t.clientID)
153 b, err := t.MarshalBinary()
158 _, err = client.Connection.Write(b)
166 func (s *Server) processOutbox() {
170 if err := s.sendTransaction(t); err != nil {
171 s.Logger.Errorw("error sending transaction", "err", err)
177 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
181 conn, err := ln.Accept()
183 s.Logger.Errorw("error accepting connection", "err", err)
185 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
186 remoteAddr: conn.RemoteAddr().String(),
190 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
193 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
195 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
197 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
205 agreementFile = "Agreement.txt"
208 // NewServer constructs a new Server from a config dir
209 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, fs FileStore) (*Server, error) {
212 Accounts: make(map[string]*Account),
214 Clients: make(map[uint16]*ClientConn),
215 fileTransfers: make(map[[4]byte]*FileTransfer),
216 PrivateChats: make(map[uint32]*PrivateChat),
217 ConfigDir: configDir,
219 NextGuestID: new(uint16),
220 outbox: make(chan Transaction),
221 Stats: &Stats{Since: time.Now()},
222 ThreadedNews: &ThreadedNews{},
224 banList: make(map[string]*time.Time),
229 // generate a new random passID for tracker registration
230 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
234 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
239 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
243 // try to load the ban list, but ignore errors as this file may not be present or may be empty
244 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
246 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
250 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
254 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
258 server.Config.FileRoot = filepath.Join(configDir, "Files")
260 *server.NextGuestID = 1
262 if server.Config.EnableTrackerRegistration {
264 "Tracker registration enabled",
265 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
266 "trackers", server.Config.Trackers,
271 tr := &TrackerRegistration{
272 UserCount: server.userCount(),
273 PassID: server.TrackerPassID[:],
274 Name: server.Config.Name,
275 Description: server.Config.Description,
277 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
278 for _, t := range server.Config.Trackers {
279 if err := register(t, tr); err != nil {
280 server.Logger.Errorw("unable to register with tracker %v", "error", err)
282 server.Logger.Debugw("Sent Tracker registration", "addr", t)
285 time.Sleep(trackerUpdateFrequency * time.Second)
290 // Start Client Keepalive go routine
291 go server.keepaliveHandler()
296 func (s *Server) userCount() int {
300 return len(s.Clients)
303 func (s *Server) keepaliveHandler() {
305 time.Sleep(idleCheckInterval * time.Second)
308 for _, c := range s.Clients {
309 c.IdleTime += idleCheckInterval
310 if c.IdleTime > userIdleSeconds && !c.Idle {
313 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
314 flagBitmap.SetBit(flagBitmap, UserFlagAway, 1)
315 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
318 TranNotifyChangeUser,
319 NewField(FieldUserID, *c.ID),
320 NewField(FieldUserFlags, c.Flags),
321 NewField(FieldUserName, c.UserName),
322 NewField(FieldUserIconID, c.Icon),
330 func (s *Server) writeBanList() error {
332 defer s.banListMU.Unlock()
334 out, err := yaml.Marshal(s.banList)
339 filepath.Join(s.ConfigDir, "Banlist.yaml"),
346 func (s *Server) writeThreadedNews() error {
347 s.threadedNewsMux.Lock()
348 defer s.threadedNewsMux.Unlock()
350 out, err := yaml.Marshal(s.ThreadedNews)
354 err = s.FS.WriteFile(
355 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
362 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
366 clientConn := &ClientConn{
375 transfers: map[int]map[[4]byte]*FileTransfer{},
376 RemoteAddr: remoteAddr,
378 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
389 binary.BigEndian.PutUint16(*clientConn.ID, ID)
390 s.Clients[ID] = clientConn
395 // NewUser creates a new user account entry in the server map and config file
396 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
403 Password: hashAndSalt([]byte(password)),
406 out, err := yaml.Marshal(&account)
410 s.Accounts[login] = &account
412 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
415 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
419 // update renames the user login
420 if login != newLogin {
421 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
425 s.Accounts[newLogin] = s.Accounts[login]
426 delete(s.Accounts, login)
429 account := s.Accounts[newLogin]
430 account.Access = access
432 account.Password = password
434 out, err := yaml.Marshal(&account)
439 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
446 // DeleteUser deletes the user account
447 func (s *Server) DeleteUser(login string) error {
451 delete(s.Accounts, login)
453 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
456 func (s *Server) connectedUsers() []Field {
460 var connectedUsers []Field
461 for _, c := range sortedClients(s.Clients) {
466 Name: string(c.UserName),
468 connectedUsers = append(connectedUsers, NewField(FieldUsernameWithInfo, user.Payload()))
470 return connectedUsers
473 func (s *Server) loadBanList(path string) error {
474 fh, err := os.Open(path)
478 decoder := yaml.NewDecoder(fh)
480 return decoder.Decode(s.banList)
483 // loadThreadedNews loads the threaded news data from disk
484 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
485 fh, err := os.Open(threadedNewsPath)
489 decoder := yaml.NewDecoder(fh)
491 return decoder.Decode(s.ThreadedNews)
494 // loadAccounts loads account data from disk
495 func (s *Server) loadAccounts(userDir string) error {
496 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
501 if len(matches) == 0 {
502 return errors.New("no user accounts found in " + userDir)
505 for _, file := range matches {
506 fh, err := s.FS.Open(file)
512 decoder := yaml.NewDecoder(fh)
513 if err := decoder.Decode(&account); err != nil {
517 s.Accounts[account.Login] = &account
522 func (s *Server) loadConfig(path string) error {
523 fh, err := s.FS.Open(path)
528 decoder := yaml.NewDecoder(fh)
529 err = decoder.Decode(s.Config)
534 validate := validator.New()
535 err = validate.Struct(s.Config)
542 // handleNewConnection takes a new net.Conn and performs the initial login sequence
543 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
544 defer dontPanic(s.Logger)
546 if err := Handshake(rwc); err != nil {
550 // Create a new scanner for parsing incoming bytes into transaction tokens
551 scanner := bufio.NewScanner(rwc)
552 scanner.Split(transactionScanner)
556 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
557 // scanner re-uses the buffer for subsequent scans.
558 buf := make([]byte, len(scanner.Bytes()))
559 copy(buf, scanner.Bytes())
561 var clientLogin Transaction
562 if _, err := clientLogin.Write(buf); err != nil {
566 // check if remoteAddr is present in the ban list
567 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
573 NewField(FieldData, []byte("You are permanently banned on this server")),
574 NewField(FieldChatOptions, []byte{0, 0}),
577 b, err := t.MarshalBinary()
582 _, err = rwc.Write(b)
587 time.Sleep(1 * time.Second)
592 if time.Now().Before(*banUntil) {
596 NewField(FieldData, []byte("You are temporarily banned on this server")),
597 NewField(FieldChatOptions, []byte{0, 0}),
599 b, err := t.MarshalBinary()
604 _, err = rwc.Write(b)
609 time.Sleep(1 * time.Second)
614 c := s.NewClientConn(rwc, remoteAddr)
617 encodedLogin := clientLogin.GetField(FieldUserLogin).Data
618 encodedPassword := clientLogin.GetField(FieldUserPassword).Data
619 c.Version = clientLogin.GetField(FieldVersion).Data
622 for _, char := range encodedLogin {
623 login += string(rune(255 - uint(char)))
629 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
631 // If authentication fails, send error reply and close connection
632 if !c.Authenticate(login, encodedPassword) {
633 t := c.NewErrReply(&clientLogin, "Incorrect login.")
634 b, err := t.MarshalBinary()
638 if _, err := rwc.Write(b); err != nil {
642 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
647 if clientLogin.GetField(FieldUserIconID).Data != nil {
648 c.Icon = clientLogin.GetField(FieldUserIconID).Data
651 c.Account = c.Server.Accounts[login]
653 if clientLogin.GetField(FieldUserName).Data != nil {
654 if c.Authorize(accessAnyName) {
655 c.UserName = clientLogin.GetField(FieldUserName).Data
657 c.UserName = []byte(c.Account.Name)
661 if c.Authorize(accessDisconUser) {
662 c.Flags = []byte{0, 2}
665 s.outbox <- c.NewReply(&clientLogin,
666 NewField(FieldVersion, []byte{0x00, 0xbe}),
667 NewField(FieldCommunityBannerID, []byte{0, 0}),
668 NewField(FieldServerName, []byte(s.Config.Name)),
671 // Send user access privs so client UI knows how to behave
672 c.Server.outbox <- *NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:]))
674 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
675 // client versions. For 1.2.3 client, we do not send TranShowAgreement. For other client versions, we send
676 // TranShowAgreement but with the NoServerAgreement field set to 1.
677 if c.Authorize(accessNoAgreement) {
678 // If client version is nil, then the client uses the 1.2.3 login behavior
679 if c.Version != nil {
680 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1}))
683 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement))
686 // If the client has provided a username as part of the login, we can infer that it is using the 1.2.3 login
687 // flow and not the 1.5+ flow.
688 if len(c.UserName) != 0 {
689 // Add the client username to the logger. For 1.5+ clients, we don't have this information yet as it comes as
690 // part of TranAgreed
691 c.logger = c.logger.With("name", string(c.UserName))
693 c.logger.Infow("Login successful", "clientVersion", "Not sent (probably 1.2.3)")
695 // Notify other clients on the server that the new user has logged in. For 1.5+ clients we don't have this
696 // information yet, so we do it in TranAgreed instead
697 for _, t := range c.notifyOthers(
699 TranNotifyChangeUser, nil,
700 NewField(FieldUserName, c.UserName),
701 NewField(FieldUserID, *c.ID),
702 NewField(FieldUserIconID, c.Icon),
703 NewField(FieldUserFlags, c.Flags),
710 c.Server.Stats.ConnectionCounter += 1
711 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
712 c.Server.Stats.ConnectionPeak = len(s.Clients)
715 // Scan for new transactions and handle them as they come in.
717 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
718 // scanner re-uses the buffer for subsequent scans.
719 buf := make([]byte, len(scanner.Bytes()))
720 copy(buf, scanner.Bytes())
723 if _, err := t.Write(buf); err != nil {
727 if err := c.handleTransaction(t); err != nil {
728 c.logger.Errorw("Error handling transaction", "err", err)
734 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
735 s.PrivateChatsMu.Lock()
736 defer s.PrivateChatsMu.Unlock()
738 randID := make([]byte, 4)
740 data := binary.BigEndian.Uint32(randID)
742 s.PrivateChats[data] = &PrivateChat{
743 ClientConn: make(map[uint16]*ClientConn),
745 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
750 const dlFldrActionSendFile = 1
751 const dlFldrActionResumeFile = 2
752 const dlFldrActionNextFile = 3
754 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
755 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
756 defer dontPanic(s.Logger)
758 txBuf := make([]byte, 16)
759 if _, err := io.ReadFull(rwc, txBuf); err != nil {
764 if _, err := t.Write(txBuf); err != nil {
770 delete(s.fileTransfers, t.ReferenceNumber)
773 // Wait a few seconds before closing the connection: this is a workaround for problems
774 // observed with Windows clients where the client must initiate close of the TCP connection before
775 // the server does. This is gross and seems unnecessary. TODO: Revisit?
776 time.Sleep(3 * time.Second)
780 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
783 return errors.New("invalid transaction ID")
787 fileTransfer.ClientConn.transfersMU.Lock()
788 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
789 fileTransfer.ClientConn.transfersMU.Unlock()
792 rLogger := s.Logger.With(
793 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
794 "login", fileTransfer.ClientConn.Account.Login,
795 "name", string(fileTransfer.ClientConn.UserName),
798 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
803 switch fileTransfer.Type {
805 if err := s.bannerDownload(rwc); err != nil {
809 s.Stats.DownloadCounter += 1
810 s.Stats.DownloadsInProgress += 1
812 s.Stats.DownloadsInProgress -= 1
816 if fileTransfer.fileResumeData != nil {
817 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
820 fw, err := newFileWrapper(s.FS, fullPath, 0)
825 rLogger.Infow("File download started", "filePath", fullPath)
827 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
828 if fileTransfer.options == nil {
829 // Start by sending flat file object to client
830 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
835 file, err := fw.dataForkReader()
840 br := bufio.NewReader(file)
841 if _, err := br.Discard(int(dataOffset)); err != nil {
845 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
849 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
850 if fileTransfer.fileResumeData == nil {
851 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
857 rFile, err := fw.rsrcForkFile()
862 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
867 s.Stats.UploadCounter += 1
868 s.Stats.UploadsInProgress += 1
869 defer func() { s.Stats.UploadsInProgress -= 1 }()
873 // A file upload has three possible cases:
874 // 1) Upload a new file
875 // 2) Resume a partially transferred file
876 // 3) Replace a fully uploaded file
877 // We have to infer which case applies by inspecting what is already on the filesystem
879 // 1) Check for existing file:
880 _, err = os.Stat(fullPath)
882 return errors.New("existing file found at " + fullPath)
884 if errors.Is(err, fs.ErrNotExist) {
885 // If not found, open or create a new .incomplete file
886 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
892 f, err := newFileWrapper(s.FS, fullPath, 0)
897 rLogger.Infow("File upload started", "dstFile", fullPath)
899 rForkWriter := io.Discard
900 iForkWriter := io.Discard
901 if s.Config.PreserveResourceForks {
902 rForkWriter, err = f.rsrcForkWriter()
907 iForkWriter, err = f.infoForkWriter()
913 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
917 if err := file.Close(); err != nil {
921 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
925 rLogger.Infow("File upload complete", "dstFile", fullPath)
928 s.Stats.DownloadCounter += 1
929 s.Stats.DownloadsInProgress += 1
930 defer func() { s.Stats.DownloadsInProgress -= 1 }()
932 // Folder Download flow:
933 // 1. Get filePath from the transfer
934 // 2. Iterate over files
935 // 3. For each fileWrapper:
936 // Send fileWrapper header to client
937 // The client can reply in 3 ways:
939 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
940 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
942 // 2. If download of a fileWrapper is to be resumed:
944 // []byte{0x00, 0x02} // download folder action
945 // [2]byte // Resume data size
946 // []byte fileWrapper resume data (see myField_FileResumeData)
948 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
950 // When download is requested (case 2 or 3), server replies with:
951 // [4]byte - fileWrapper size
952 // []byte - Flattened File Object
954 // After every fileWrapper download, client could request next fileWrapper with:
955 // []byte{0x00, 0x03}
957 // This notifies the server to send the next item header
959 basePathLen := len(fullPath)
961 rLogger.Infow("Start folder download", "path", fullPath)
963 nextAction := make([]byte, 2)
964 if _, err := io.ReadFull(rwc, nextAction); err != nil {
969 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
970 s.Stats.DownloadCounter += 1
978 if strings.HasPrefix(info.Name(), ".") {
982 hlFile, err := newFileWrapper(s.FS, path, 0)
987 subPath := path[basePathLen+1:]
988 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
994 fileHeader := NewFileHeader(subPath, info.IsDir())
996 // Send the fileWrapper header to client
997 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
998 s.Logger.Errorf("error sending file header: %v", err)
1002 // Read the client's Next Action request
1003 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1007 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
1009 var dataOffset int64
1011 switch nextAction[1] {
1012 case dlFldrActionResumeFile:
1013 // get size of resumeData
1014 resumeDataByteLen := make([]byte, 2)
1015 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
1019 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
1020 resumeDataBytes := make([]byte, resumeDataLen)
1021 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1025 var frd FileResumeData
1026 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1029 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1030 case dlFldrActionNextFile:
1031 // client asked to skip this file
1039 rLogger.Infow("File download started",
1040 "fileName", info.Name(),
1041 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1044 // Send file size to client
1045 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1050 // Send ffo bytes to client
1051 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1056 file, err := s.FS.Open(path)
1061 // wr := bufio.NewWriterSize(rwc, 1460)
1062 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1066 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1067 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1072 rFile, err := hlFile.rsrcForkFile()
1077 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1082 // Read the client's Next Action request. This is always 3, I think?
1083 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1095 s.Stats.UploadCounter += 1
1096 s.Stats.UploadsInProgress += 1
1097 defer func() { s.Stats.UploadsInProgress -= 1 }()
1099 "Folder upload started",
1100 "dstPath", fullPath,
1101 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1102 "FolderItemCount", fileTransfer.FolderItemCount,
1105 // Check if the target folder exists. If not, create it.
1106 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1107 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1112 // Begin the folder upload flow by sending the "next file action" to client
1113 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1117 fileSize := make([]byte, 4)
1119 for i := 0; i < fileTransfer.ItemCount(); i++ {
1120 s.Stats.UploadCounter += 1
1123 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1126 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1129 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1133 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1135 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1140 "Folder upload continued",
1141 "FormattedPath", fu.FormattedPath(),
1142 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1143 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1146 if fu.IsFolder == [2]byte{0, 1} {
1147 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1148 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1153 // Tell client to send next file
1154 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1158 nextAction := dlFldrActionSendFile
1160 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1161 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1162 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1166 nextAction = dlFldrActionNextFile
1169 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1170 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1171 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1175 nextAction = dlFldrActionResumeFile
1178 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1183 case dlFldrActionNextFile:
1185 case dlFldrActionResumeFile:
1186 offset := make([]byte, 4)
1187 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1189 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1194 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1196 b, _ := fileResumeData.BinaryMarshal()
1198 bs := make([]byte, 2)
1199 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1201 if _, err := rwc.Write(append(bs, b...)); err != nil {
1205 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1209 if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil {
1213 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1218 case dlFldrActionSendFile:
1219 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1223 filePath := filepath.Join(fullPath, fu.FormattedPath())
1225 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1230 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1232 incWriter, err := hlFile.incFileWriter()
1237 rForkWriter := io.Discard
1238 iForkWriter := io.Discard
1239 if s.Config.PreserveResourceForks {
1240 iForkWriter, err = hlFile.infoForkWriter()
1245 rForkWriter, err = hlFile.rsrcForkWriter()
1250 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1254 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1259 // Tell client to send next fileWrapper
1260 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1265 rLogger.Infof("Folder upload complete")