9 "github.com/go-playground/validator/v10"
25 type contextKey string
27 var contextKeyReq = contextKey("req")
29 type requestCtx struct {
37 Accounts map[string]*Account
39 Clients map[uint16]*ClientConn
40 fileTransfers map[[4]byte]*FileTransfer
44 Logger *zap.SugaredLogger
46 PrivateChatsMu sync.Mutex
47 PrivateChats map[uint32]*PrivateChat
55 FS FileStore // Storage backend to use for File storage
57 outbox chan Transaction
60 threadedNewsMux sync.Mutex
61 ThreadedNews *ThreadedNews
63 flatNewsMux sync.Mutex
67 banList map[string]*time.Time
70 func (s *Server) CurrentStats() Stats {
72 defer s.StatsMu.Unlock()
75 stats.CurrentlyConnected = len(s.Clients)
80 type PrivateChat struct {
82 ClientConn map[uint16]*ClientConn
85 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
86 s.Logger.Infow("Hotline server started",
88 "API port", fmt.Sprintf(":%v", s.Port),
89 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
96 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
101 s.Logger.Fatal(s.Serve(ctx, ln))
106 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
112 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
120 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
122 conn, err := ln.Accept()
128 defer func() { _ = conn.Close() }()
130 err = s.handleFileTransfer(
131 context.WithValue(ctx, contextKeyReq, requestCtx{
132 remoteAddr: conn.RemoteAddr().String(),
138 s.Logger.Errorw("file transfer error", "reason", err)
144 func (s *Server) sendTransaction(t Transaction) error {
145 clientID, err := byteToInt(*t.clientID)
151 client := s.Clients[uint16(clientID)]
154 return fmt.Errorf("invalid client id %v", *t.clientID)
157 b, err := t.MarshalBinary()
162 _, err = client.Connection.Write(b)
170 func (s *Server) processOutbox() {
174 if err := s.sendTransaction(t); err != nil {
175 s.Logger.Errorw("error sending transaction", "err", err)
181 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
185 conn, err := ln.Accept()
187 s.Logger.Errorw("error accepting connection", "err", err)
189 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
190 remoteAddr: conn.RemoteAddr().String(),
194 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
197 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
199 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
201 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
209 agreementFile = "Agreement.txt"
212 // NewServer constructs a new Server from a config dir
213 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
216 Accounts: make(map[string]*Account),
218 Clients: make(map[uint16]*ClientConn),
219 fileTransfers: make(map[[4]byte]*FileTransfer),
220 PrivateChats: make(map[uint32]*PrivateChat),
221 ConfigDir: configDir,
223 NextGuestID: new(uint16),
224 outbox: make(chan Transaction),
225 Stats: &Stats{Since: time.Now()},
226 ThreadedNews: &ThreadedNews{},
228 banList: make(map[string]*time.Time),
233 // generate a new random passID for tracker registration
234 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
238 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
243 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
247 // try to load the ban list, but ignore errors as this file may not be present or may be empty
248 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
250 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
254 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
258 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
262 server.Config.FileRoot = filepath.Join(configDir, "Files")
264 *server.NextGuestID = 1
266 if server.Config.EnableTrackerRegistration {
268 "Tracker registration enabled",
269 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
270 "trackers", server.Config.Trackers,
275 tr := &TrackerRegistration{
276 UserCount: server.userCount(),
277 PassID: server.TrackerPassID[:],
278 Name: server.Config.Name,
279 Description: server.Config.Description,
281 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
282 for _, t := range server.Config.Trackers {
283 if err := register(t, tr); err != nil {
284 server.Logger.Errorw("unable to register with tracker %v", "error", err)
286 server.Logger.Debugw("Sent Tracker registration", "addr", t)
289 time.Sleep(trackerUpdateFrequency * time.Second)
294 // Start Client Keepalive go routine
295 go server.keepaliveHandler()
300 func (s *Server) userCount() int {
304 return len(s.Clients)
307 func (s *Server) keepaliveHandler() {
309 time.Sleep(idleCheckInterval * time.Second)
312 for _, c := range s.Clients {
313 c.IdleTime += idleCheckInterval
314 if c.IdleTime > userIdleSeconds && !c.Idle {
317 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
318 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
319 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
322 tranNotifyChangeUser,
323 NewField(fieldUserID, *c.ID),
324 NewField(fieldUserFlags, c.Flags),
325 NewField(fieldUserName, c.UserName),
326 NewField(fieldUserIconID, c.Icon),
334 func (s *Server) writeBanList() error {
336 defer s.banListMU.Unlock()
338 out, err := yaml.Marshal(s.banList)
342 err = ioutil.WriteFile(
343 filepath.Join(s.ConfigDir, "Banlist.yaml"),
350 func (s *Server) writeThreadedNews() error {
351 s.threadedNewsMux.Lock()
352 defer s.threadedNewsMux.Unlock()
354 out, err := yaml.Marshal(s.ThreadedNews)
358 err = s.FS.WriteFile(
359 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
366 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
370 clientConn := &ClientConn{
379 transfers: map[int]map[[4]byte]*FileTransfer{},
380 RemoteAddr: remoteAddr,
382 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
393 binary.BigEndian.PutUint16(*clientConn.ID, ID)
394 s.Clients[ID] = clientConn
399 // NewUser creates a new user account entry in the server map and config file
400 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
407 Password: hashAndSalt([]byte(password)),
410 out, err := yaml.Marshal(&account)
414 s.Accounts[login] = &account
416 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
419 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
423 // update renames the user login
424 if login != newLogin {
425 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
429 s.Accounts[newLogin] = s.Accounts[login]
430 delete(s.Accounts, login)
433 account := s.Accounts[newLogin]
434 account.Access = access
436 account.Password = password
438 out, err := yaml.Marshal(&account)
443 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
450 // DeleteUser deletes the user account
451 func (s *Server) DeleteUser(login string) error {
455 delete(s.Accounts, login)
457 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
460 func (s *Server) connectedUsers() []Field {
464 var connectedUsers []Field
465 for _, c := range sortedClients(s.Clients) {
470 Name: string(c.UserName),
472 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
474 return connectedUsers
477 func (s *Server) loadBanList(path string) error {
478 fh, err := os.Open(path)
482 decoder := yaml.NewDecoder(fh)
484 return decoder.Decode(s.banList)
487 // loadThreadedNews loads the threaded news data from disk
488 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
489 fh, err := os.Open(threadedNewsPath)
493 decoder := yaml.NewDecoder(fh)
495 return decoder.Decode(s.ThreadedNews)
498 // loadAccounts loads account data from disk
499 func (s *Server) loadAccounts(userDir string) error {
500 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
505 if len(matches) == 0 {
506 return errors.New("no user accounts found in " + userDir)
509 for _, file := range matches {
510 fh, err := s.FS.Open(file)
516 decoder := yaml.NewDecoder(fh)
517 if err := decoder.Decode(&account); err != nil {
521 s.Accounts[account.Login] = &account
526 func (s *Server) loadConfig(path string) error {
527 fh, err := s.FS.Open(path)
532 decoder := yaml.NewDecoder(fh)
533 err = decoder.Decode(s.Config)
538 validate := validator.New()
539 err = validate.Struct(s.Config)
546 // handleNewConnection takes a new net.Conn and performs the initial login sequence
547 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
548 defer dontPanic(s.Logger)
550 if err := Handshake(rwc); err != nil {
554 // Create a new scanner for parsing incoming bytes into transaction tokens
555 scanner := bufio.NewScanner(rwc)
556 scanner.Split(transactionScanner)
560 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
561 // scanner re-uses the buffer for subsequent scans.
562 buf := make([]byte, len(scanner.Bytes()))
563 copy(buf, scanner.Bytes())
565 var clientLogin Transaction
566 if _, err := clientLogin.Write(buf); err != nil {
570 c := s.NewClientConn(rwc, remoteAddr)
572 // check if remoteAddr is present in the ban list
573 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
576 s.outbox <- *NewTransaction(
579 NewField(fieldData, []byte("You are permanently banned on this server")),
580 NewField(fieldChatOptions, []byte{0, 0}),
582 time.Sleep(1 * time.Second)
584 } else if time.Now().Before(*banUntil) {
585 s.outbox <- *NewTransaction(
588 NewField(fieldData, []byte("You are temporarily banned on this server")),
589 NewField(fieldChatOptions, []byte{0, 0}),
591 time.Sleep(1 * time.Second)
598 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
599 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
600 c.Version = clientLogin.GetField(fieldVersion).Data
603 for _, char := range encodedLogin {
604 login += string(rune(255 - uint(char)))
610 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
612 // If authentication fails, send error reply and close connection
613 if !c.Authenticate(login, encodedPassword) {
614 t := c.NewErrReply(&clientLogin, "Incorrect login.")
615 b, err := t.MarshalBinary()
619 if _, err := rwc.Write(b); err != nil {
623 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
628 if clientLogin.GetField(fieldUserIconID).Data != nil {
629 c.Icon = clientLogin.GetField(fieldUserIconID).Data
632 c.Account = c.Server.Accounts[login]
634 if clientLogin.GetField(fieldUserName).Data != nil {
635 if c.Authorize(accessAnyName) {
636 c.UserName = clientLogin.GetField(fieldUserName).Data
638 c.UserName = []byte(c.Account.Name)
642 if c.Authorize(accessDisconUser) {
643 c.Flags = []byte{0, 2}
646 s.outbox <- c.NewReply(&clientLogin,
647 NewField(fieldVersion, []byte{0x00, 0xbe}),
648 NewField(fieldCommunityBannerID, []byte{0, 0}),
649 NewField(fieldServerName, []byte(s.Config.Name)),
652 // Send user access privs so client UI knows how to behave
653 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:]))
655 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
656 // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send
657 // tranShowAgreement but with the NoServerAgreement field set to 1.
658 if c.Authorize(accessNoAgreement) {
659 // If client version is nil, then the client uses the 1.2.3 login behavior
660 if c.Version != nil {
661 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1}))
664 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
667 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
668 // TODO: figure out a generalized solution that doesn't require playing whack-a-mole for specific client versions
669 c.logger = c.logger.With("name", string(c.UserName))
670 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }()))
672 for _, t := range c.notifyOthers(
674 tranNotifyChangeUser, nil,
675 NewField(fieldUserName, c.UserName),
676 NewField(fieldUserID, *c.ID),
677 NewField(fieldUserIconID, c.Icon),
678 NewField(fieldUserFlags, c.Flags),
684 c.Server.Stats.ConnectionCounter += 1
685 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
686 c.Server.Stats.ConnectionPeak = len(s.Clients)
689 // Scan for new transactions and handle them as they come in.
691 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
692 // scanner re-uses the buffer for subsequent scans.
693 buf := make([]byte, len(scanner.Bytes()))
694 copy(buf, scanner.Bytes())
697 if _, err := t.Write(buf); err != nil {
701 if err := c.handleTransaction(t); err != nil {
702 c.logger.Errorw("Error handling transaction", "err", err)
708 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
709 s.PrivateChatsMu.Lock()
710 defer s.PrivateChatsMu.Unlock()
712 randID := make([]byte, 4)
714 data := binary.BigEndian.Uint32(randID[:])
716 s.PrivateChats[data] = &PrivateChat{
717 ClientConn: make(map[uint16]*ClientConn),
719 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
724 const dlFldrActionSendFile = 1
725 const dlFldrActionResumeFile = 2
726 const dlFldrActionNextFile = 3
728 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
729 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
730 defer dontPanic(s.Logger)
732 txBuf := make([]byte, 16)
733 if _, err := io.ReadFull(rwc, txBuf); err != nil {
738 if _, err := t.Write(txBuf); err != nil {
744 delete(s.fileTransfers, t.ReferenceNumber)
747 // Wait a few seconds before closing the connection: this is a workaround for problems
748 // observed with Windows clients where the client must initiate close of the TCP connection before
749 // the server does. This is gross and seems unnecessary. TODO: Revisit?
750 time.Sleep(3 * time.Second)
754 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
757 return errors.New("invalid transaction ID")
761 fileTransfer.ClientConn.transfersMU.Lock()
762 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
763 fileTransfer.ClientConn.transfersMU.Unlock()
766 rLogger := s.Logger.With(
767 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
768 "login", fileTransfer.ClientConn.Account.Login,
769 "name", string(fileTransfer.ClientConn.UserName),
772 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
777 switch fileTransfer.Type {
779 if err := s.bannerDownload(rwc); err != nil {
783 s.Stats.DownloadCounter += 1
784 s.Stats.DownloadsInProgress += 1
786 s.Stats.DownloadsInProgress -= 1
790 if fileTransfer.fileResumeData != nil {
791 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
794 fw, err := newFileWrapper(s.FS, fullPath, 0)
799 rLogger.Infow("File download started", "filePath", fullPath)
801 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
802 if fileTransfer.options == nil {
803 // Start by sending flat file object to client
804 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
809 file, err := fw.dataForkReader()
814 br := bufio.NewReader(file)
815 if _, err := br.Discard(int(dataOffset)); err != nil {
819 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
823 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
824 if fileTransfer.fileResumeData == nil {
825 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
831 rFile, err := fw.rsrcForkFile()
836 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
841 s.Stats.UploadCounter += 1
842 s.Stats.UploadsInProgress += 1
843 defer func() { s.Stats.UploadsInProgress -= 1 }()
847 // A file upload has three possible cases:
848 // 1) Upload a new file
849 // 2) Resume a partially transferred file
850 // 3) Replace a fully uploaded file
851 // We have to infer which case applies by inspecting what is already on the filesystem
853 // 1) Check for existing file:
854 _, err = os.Stat(fullPath)
856 return errors.New("existing file found at " + fullPath)
858 if errors.Is(err, fs.ErrNotExist) {
859 // If not found, open or create a new .incomplete file
860 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
866 f, err := newFileWrapper(s.FS, fullPath, 0)
871 rLogger.Infow("File upload started", "dstFile", fullPath)
873 rForkWriter := io.Discard
874 iForkWriter := io.Discard
875 if s.Config.PreserveResourceForks {
876 rForkWriter, err = f.rsrcForkWriter()
881 iForkWriter, err = f.infoForkWriter()
887 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
891 if err := file.Close(); err != nil {
895 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
899 rLogger.Infow("File upload complete", "dstFile", fullPath)
902 s.Stats.DownloadCounter += 1
903 s.Stats.DownloadsInProgress += 1
904 defer func() { s.Stats.DownloadsInProgress -= 1 }()
906 // Folder Download flow:
907 // 1. Get filePath from the transfer
908 // 2. Iterate over files
909 // 3. For each fileWrapper:
910 // Send fileWrapper header to client
911 // The client can reply in 3 ways:
913 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
914 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
916 // 2. If download of a fileWrapper is to be resumed:
918 // []byte{0x00, 0x02} // download folder action
919 // [2]byte // Resume data size
920 // []byte fileWrapper resume data (see myField_FileResumeData)
922 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
924 // When download is requested (case 2 or 3), server replies with:
925 // [4]byte - fileWrapper size
926 // []byte - Flattened File Object
928 // After every fileWrapper download, client could request next fileWrapper with:
929 // []byte{0x00, 0x03}
931 // This notifies the server to send the next item header
933 basePathLen := len(fullPath)
935 rLogger.Infow("Start folder download", "path", fullPath)
937 nextAction := make([]byte, 2)
938 if _, err := io.ReadFull(rwc, nextAction); err != nil {
943 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
944 s.Stats.DownloadCounter += 1
952 if strings.HasPrefix(info.Name(), ".") {
956 hlFile, err := newFileWrapper(s.FS, path, 0)
961 subPath := path[basePathLen+1:]
962 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
968 fileHeader := NewFileHeader(subPath, info.IsDir())
970 // Send the fileWrapper header to client
971 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
972 s.Logger.Errorf("error sending file header: %v", err)
976 // Read the client's Next Action request
977 if _, err := io.ReadFull(rwc, nextAction); err != nil {
981 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
985 switch nextAction[1] {
986 case dlFldrActionResumeFile:
987 // get size of resumeData
988 resumeDataByteLen := make([]byte, 2)
989 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
993 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
994 resumeDataBytes := make([]byte, resumeDataLen)
995 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
999 var frd FileResumeData
1000 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1003 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1004 case dlFldrActionNextFile:
1005 // client asked to skip this file
1013 rLogger.Infow("File download started",
1014 "fileName", info.Name(),
1015 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1018 // Send file size to client
1019 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1024 // Send ffo bytes to client
1025 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1030 file, err := s.FS.Open(path)
1035 // wr := bufio.NewWriterSize(rwc, 1460)
1036 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1040 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1041 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1046 rFile, err := hlFile.rsrcForkFile()
1051 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1056 // Read the client's Next Action request. This is always 3, I think?
1057 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1069 s.Stats.UploadCounter += 1
1070 s.Stats.UploadsInProgress += 1
1071 defer func() { s.Stats.UploadsInProgress -= 1 }()
1073 "Folder upload started",
1074 "dstPath", fullPath,
1075 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1076 "FolderItemCount", fileTransfer.FolderItemCount,
1079 // Check if the target folder exists. If not, create it.
1080 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1081 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1086 // Begin the folder upload flow by sending the "next file action" to client
1087 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1091 fileSize := make([]byte, 4)
1093 for i := 0; i < fileTransfer.ItemCount(); i++ {
1094 s.Stats.UploadCounter += 1
1097 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1100 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1103 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1107 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1109 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1114 "Folder upload continued",
1115 "FormattedPath", fu.FormattedPath(),
1116 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1117 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1120 if fu.IsFolder == [2]byte{0, 1} {
1121 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1122 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1127 // Tell client to send next file
1128 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1132 nextAction := dlFldrActionSendFile
1134 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1135 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1136 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1140 nextAction = dlFldrActionNextFile
1143 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1144 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1145 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1149 nextAction = dlFldrActionResumeFile
1152 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1157 case dlFldrActionNextFile:
1159 case dlFldrActionResumeFile:
1160 offset := make([]byte, 4)
1161 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1163 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1168 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1170 b, _ := fileResumeData.BinaryMarshal()
1172 bs := make([]byte, 2)
1173 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1175 if _, err := rwc.Write(append(bs, b...)); err != nil {
1179 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1183 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1187 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1192 case dlFldrActionSendFile:
1193 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1197 filePath := filepath.Join(fullPath, fu.FormattedPath())
1199 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1204 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1206 incWriter, err := hlFile.incFileWriter()
1211 rForkWriter := io.Discard
1212 iForkWriter := io.Discard
1213 if s.Config.PreserveResourceForks {
1214 iForkWriter, err = hlFile.infoForkWriter()
1219 rForkWriter, err = hlFile.rsrcForkWriter()
1224 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1228 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1233 // Tell client to send next fileWrapper
1234 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1239 rLogger.Infof("Folder upload complete")