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 // If the client has provided a username as part of the login, we can infer that it is using the 1.2.3 login
668 // flow and not the 1.5+ flow.
669 if len(c.UserName) != 0 {
670 // Add the client username to the logger. For 1.5+ clients, we don't have this information yet as it comes as
671 // part of tranAgreed
672 c.logger = c.logger.With("name", string(c.UserName))
674 c.logger.Infow("Login successful", "clientVersion", "Not sent (probably 1.2.3)")
676 // Notify other clients on the server that the new user has logged in. For 1.5+ clients we don't have this
677 // information yet, so we do it in tranAgreed instead
678 for _, t := range c.notifyOthers(
680 tranNotifyChangeUser, nil,
681 NewField(fieldUserName, c.UserName),
682 NewField(fieldUserID, *c.ID),
683 NewField(fieldUserIconID, c.Icon),
684 NewField(fieldUserFlags, c.Flags),
691 c.Server.Stats.ConnectionCounter += 1
692 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
693 c.Server.Stats.ConnectionPeak = len(s.Clients)
696 // Scan for new transactions and handle them as they come in.
698 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
699 // scanner re-uses the buffer for subsequent scans.
700 buf := make([]byte, len(scanner.Bytes()))
701 copy(buf, scanner.Bytes())
704 if _, err := t.Write(buf); err != nil {
708 if err := c.handleTransaction(t); err != nil {
709 c.logger.Errorw("Error handling transaction", "err", err)
715 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
716 s.PrivateChatsMu.Lock()
717 defer s.PrivateChatsMu.Unlock()
719 randID := make([]byte, 4)
721 data := binary.BigEndian.Uint32(randID[:])
723 s.PrivateChats[data] = &PrivateChat{
724 ClientConn: make(map[uint16]*ClientConn),
726 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
731 const dlFldrActionSendFile = 1
732 const dlFldrActionResumeFile = 2
733 const dlFldrActionNextFile = 3
735 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
736 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
737 defer dontPanic(s.Logger)
739 txBuf := make([]byte, 16)
740 if _, err := io.ReadFull(rwc, txBuf); err != nil {
745 if _, err := t.Write(txBuf); err != nil {
751 delete(s.fileTransfers, t.ReferenceNumber)
754 // Wait a few seconds before closing the connection: this is a workaround for problems
755 // observed with Windows clients where the client must initiate close of the TCP connection before
756 // the server does. This is gross and seems unnecessary. TODO: Revisit?
757 time.Sleep(3 * time.Second)
761 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
764 return errors.New("invalid transaction ID")
768 fileTransfer.ClientConn.transfersMU.Lock()
769 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
770 fileTransfer.ClientConn.transfersMU.Unlock()
773 rLogger := s.Logger.With(
774 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
775 "login", fileTransfer.ClientConn.Account.Login,
776 "name", string(fileTransfer.ClientConn.UserName),
779 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
784 switch fileTransfer.Type {
786 if err := s.bannerDownload(rwc); err != nil {
790 s.Stats.DownloadCounter += 1
791 s.Stats.DownloadsInProgress += 1
793 s.Stats.DownloadsInProgress -= 1
797 if fileTransfer.fileResumeData != nil {
798 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
801 fw, err := newFileWrapper(s.FS, fullPath, 0)
806 rLogger.Infow("File download started", "filePath", fullPath)
808 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
809 if fileTransfer.options == nil {
810 // Start by sending flat file object to client
811 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
816 file, err := fw.dataForkReader()
821 br := bufio.NewReader(file)
822 if _, err := br.Discard(int(dataOffset)); err != nil {
826 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
830 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
831 if fileTransfer.fileResumeData == nil {
832 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
838 rFile, err := fw.rsrcForkFile()
843 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
848 s.Stats.UploadCounter += 1
849 s.Stats.UploadsInProgress += 1
850 defer func() { s.Stats.UploadsInProgress -= 1 }()
854 // A file upload has three possible cases:
855 // 1) Upload a new file
856 // 2) Resume a partially transferred file
857 // 3) Replace a fully uploaded file
858 // We have to infer which case applies by inspecting what is already on the filesystem
860 // 1) Check for existing file:
861 _, err = os.Stat(fullPath)
863 return errors.New("existing file found at " + fullPath)
865 if errors.Is(err, fs.ErrNotExist) {
866 // If not found, open or create a new .incomplete file
867 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
873 f, err := newFileWrapper(s.FS, fullPath, 0)
878 rLogger.Infow("File upload started", "dstFile", fullPath)
880 rForkWriter := io.Discard
881 iForkWriter := io.Discard
882 if s.Config.PreserveResourceForks {
883 rForkWriter, err = f.rsrcForkWriter()
888 iForkWriter, err = f.infoForkWriter()
894 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
898 if err := file.Close(); err != nil {
902 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
906 rLogger.Infow("File upload complete", "dstFile", fullPath)
909 s.Stats.DownloadCounter += 1
910 s.Stats.DownloadsInProgress += 1
911 defer func() { s.Stats.DownloadsInProgress -= 1 }()
913 // Folder Download flow:
914 // 1. Get filePath from the transfer
915 // 2. Iterate over files
916 // 3. For each fileWrapper:
917 // Send fileWrapper header to client
918 // The client can reply in 3 ways:
920 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
921 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
923 // 2. If download of a fileWrapper is to be resumed:
925 // []byte{0x00, 0x02} // download folder action
926 // [2]byte // Resume data size
927 // []byte fileWrapper resume data (see myField_FileResumeData)
929 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
931 // When download is requested (case 2 or 3), server replies with:
932 // [4]byte - fileWrapper size
933 // []byte - Flattened File Object
935 // After every fileWrapper download, client could request next fileWrapper with:
936 // []byte{0x00, 0x03}
938 // This notifies the server to send the next item header
940 basePathLen := len(fullPath)
942 rLogger.Infow("Start folder download", "path", fullPath)
944 nextAction := make([]byte, 2)
945 if _, err := io.ReadFull(rwc, nextAction); err != nil {
950 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
951 s.Stats.DownloadCounter += 1
959 if strings.HasPrefix(info.Name(), ".") {
963 hlFile, err := newFileWrapper(s.FS, path, 0)
968 subPath := path[basePathLen+1:]
969 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
975 fileHeader := NewFileHeader(subPath, info.IsDir())
977 // Send the fileWrapper header to client
978 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
979 s.Logger.Errorf("error sending file header: %v", err)
983 // Read the client's Next Action request
984 if _, err := io.ReadFull(rwc, nextAction); err != nil {
988 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
992 switch nextAction[1] {
993 case dlFldrActionResumeFile:
994 // get size of resumeData
995 resumeDataByteLen := make([]byte, 2)
996 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
1000 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
1001 resumeDataBytes := make([]byte, resumeDataLen)
1002 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1006 var frd FileResumeData
1007 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1010 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1011 case dlFldrActionNextFile:
1012 // client asked to skip this file
1020 rLogger.Infow("File download started",
1021 "fileName", info.Name(),
1022 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1025 // Send file size to client
1026 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1031 // Send ffo bytes to client
1032 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1037 file, err := s.FS.Open(path)
1042 // wr := bufio.NewWriterSize(rwc, 1460)
1043 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1047 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1048 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1053 rFile, err := hlFile.rsrcForkFile()
1058 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1063 // Read the client's Next Action request. This is always 3, I think?
1064 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1076 s.Stats.UploadCounter += 1
1077 s.Stats.UploadsInProgress += 1
1078 defer func() { s.Stats.UploadsInProgress -= 1 }()
1080 "Folder upload started",
1081 "dstPath", fullPath,
1082 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1083 "FolderItemCount", fileTransfer.FolderItemCount,
1086 // Check if the target folder exists. If not, create it.
1087 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1088 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1093 // Begin the folder upload flow by sending the "next file action" to client
1094 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1098 fileSize := make([]byte, 4)
1100 for i := 0; i < fileTransfer.ItemCount(); i++ {
1101 s.Stats.UploadCounter += 1
1104 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1107 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1110 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1114 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1116 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1121 "Folder upload continued",
1122 "FormattedPath", fu.FormattedPath(),
1123 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1124 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1127 if fu.IsFolder == [2]byte{0, 1} {
1128 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1129 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1134 // Tell client to send next file
1135 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1139 nextAction := dlFldrActionSendFile
1141 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1142 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1143 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1147 nextAction = dlFldrActionNextFile
1150 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1151 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1152 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1156 nextAction = dlFldrActionResumeFile
1159 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1164 case dlFldrActionNextFile:
1166 case dlFldrActionResumeFile:
1167 offset := make([]byte, 4)
1168 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1170 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1175 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1177 b, _ := fileResumeData.BinaryMarshal()
1179 bs := make([]byte, 2)
1180 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1182 if _, err := rwc.Write(append(bs, b...)); err != nil {
1186 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1190 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1194 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1199 case dlFldrActionSendFile:
1200 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1204 filePath := filepath.Join(fullPath, fu.FormattedPath())
1206 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1211 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1213 incWriter, err := hlFile.incFileWriter()
1218 rForkWriter := io.Discard
1219 iForkWriter := io.Discard
1220 if s.Config.PreserveResourceForks {
1221 iForkWriter, err = hlFile.infoForkWriter()
1226 rForkWriter, err = hlFile.rsrcForkWriter()
1231 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1235 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1240 // Tell client to send next fileWrapper
1241 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1246 rLogger.Infof("Folder upload complete")