10 "github.com/go-playground/validator/v10"
26 type contextKey string
28 var contextKeyReq = contextKey("req")
30 type requestCtx struct {
36 var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
37 var frogblastVersion = []byte{0, 0, 0, 0xb9} // version ID used by the Frogblast 1.2.4 client
39 var obsessionVersion = []byte{0xbe, 0x00} // version ID used by the Obsession client
43 Accounts map[string]*Account
45 Clients map[uint16]*ClientConn
46 fileTransfers map[[4]byte]*FileTransfer
50 Logger *zap.SugaredLogger
52 PrivateChatsMu sync.Mutex
53 PrivateChats map[uint32]*PrivateChat
61 FS FileStore // Storage backend to use for File storage
63 outbox chan Transaction
66 threadedNewsMux sync.Mutex
67 ThreadedNews *ThreadedNews
69 flatNewsMux sync.Mutex
73 banList map[string]*time.Time
76 func (s *Server) CurrentStats() Stats {
78 defer s.StatsMu.Unlock()
81 stats.CurrentlyConnected = len(s.Clients)
86 type PrivateChat struct {
88 ClientConn map[uint16]*ClientConn
91 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
92 s.Logger.Infow("Hotline server started",
94 "API port", fmt.Sprintf(":%v", s.Port),
95 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
102 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
107 s.Logger.Fatal(s.Serve(ctx, ln))
112 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
118 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
126 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
128 conn, err := ln.Accept()
134 defer func() { _ = conn.Close() }()
136 err = s.handleFileTransfer(
137 context.WithValue(ctx, contextKeyReq, requestCtx{
138 remoteAddr: conn.RemoteAddr().String(),
144 s.Logger.Errorw("file transfer error", "reason", err)
150 func (s *Server) sendTransaction(t Transaction) error {
151 clientID, err := byteToInt(*t.clientID)
157 client := s.Clients[uint16(clientID)]
160 return fmt.Errorf("invalid client id %v", *t.clientID)
163 b, err := t.MarshalBinary()
168 _, err = client.Connection.Write(b)
176 func (s *Server) processOutbox() {
180 if err := s.sendTransaction(t); err != nil {
181 s.Logger.Errorw("error sending transaction", "err", err)
187 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
191 conn, err := ln.Accept()
193 s.Logger.Errorw("error accepting connection", "err", err)
195 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
196 remoteAddr: conn.RemoteAddr().String(),
200 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
203 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
205 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
207 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
215 agreementFile = "Agreement.txt"
218 // NewServer constructs a new Server from a config dir
219 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
222 Accounts: make(map[string]*Account),
224 Clients: make(map[uint16]*ClientConn),
225 fileTransfers: make(map[[4]byte]*FileTransfer),
226 PrivateChats: make(map[uint32]*PrivateChat),
227 ConfigDir: configDir,
229 NextGuestID: new(uint16),
230 outbox: make(chan Transaction),
231 Stats: &Stats{Since: time.Now()},
232 ThreadedNews: &ThreadedNews{},
234 banList: make(map[string]*time.Time),
239 // generate a new random passID for tracker registration
240 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
244 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
249 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
253 // try to load the ban list, but ignore errors as this file may not be present or may be empty
254 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
256 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
260 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
264 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
268 server.Config.FileRoot = filepath.Join(configDir, "Files")
270 *server.NextGuestID = 1
272 if server.Config.EnableTrackerRegistration {
274 "Tracker registration enabled",
275 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
276 "trackers", server.Config.Trackers,
281 tr := &TrackerRegistration{
282 UserCount: server.userCount(),
283 PassID: server.TrackerPassID[:],
284 Name: server.Config.Name,
285 Description: server.Config.Description,
287 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
288 for _, t := range server.Config.Trackers {
289 if err := register(t, tr); err != nil {
290 server.Logger.Errorw("unable to register with tracker %v", "error", err)
292 server.Logger.Debugw("Sent Tracker registration", "addr", t)
295 time.Sleep(trackerUpdateFrequency * time.Second)
300 // Start Client Keepalive go routine
301 go server.keepaliveHandler()
306 func (s *Server) userCount() int {
310 return len(s.Clients)
313 func (s *Server) keepaliveHandler() {
315 time.Sleep(idleCheckInterval * time.Second)
318 for _, c := range s.Clients {
319 c.IdleTime += idleCheckInterval
320 if c.IdleTime > userIdleSeconds && !c.Idle {
323 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
324 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
325 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
328 tranNotifyChangeUser,
329 NewField(fieldUserID, *c.ID),
330 NewField(fieldUserFlags, c.Flags),
331 NewField(fieldUserName, c.UserName),
332 NewField(fieldUserIconID, c.Icon),
340 func (s *Server) writeBanList() error {
342 defer s.banListMU.Unlock()
344 out, err := yaml.Marshal(s.banList)
348 err = ioutil.WriteFile(
349 filepath.Join(s.ConfigDir, "Banlist.yaml"),
356 func (s *Server) writeThreadedNews() error {
357 s.threadedNewsMux.Lock()
358 defer s.threadedNewsMux.Unlock()
360 out, err := yaml.Marshal(s.ThreadedNews)
364 err = s.FS.WriteFile(
365 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
372 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
376 clientConn := &ClientConn{
385 transfers: map[int]map[[4]byte]*FileTransfer{},
387 RemoteAddr: remoteAddr,
389 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
400 binary.BigEndian.PutUint16(*clientConn.ID, ID)
401 s.Clients[ID] = clientConn
406 // NewUser creates a new user account entry in the server map and config file
407 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
414 Password: hashAndSalt([]byte(password)),
417 out, err := yaml.Marshal(&account)
421 s.Accounts[login] = &account
423 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
426 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
430 // update renames the user login
431 if login != newLogin {
432 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
436 s.Accounts[newLogin] = s.Accounts[login]
437 delete(s.Accounts, login)
440 account := s.Accounts[newLogin]
441 account.Access = access
443 account.Password = password
445 out, err := yaml.Marshal(&account)
450 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
457 // DeleteUser deletes the user account
458 func (s *Server) DeleteUser(login string) error {
462 delete(s.Accounts, login)
464 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
467 func (s *Server) connectedUsers() []Field {
471 var connectedUsers []Field
472 for _, c := range sortedClients(s.Clients) {
480 Name: string(c.UserName),
482 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
484 return connectedUsers
487 func (s *Server) loadBanList(path string) error {
488 fh, err := os.Open(path)
492 decoder := yaml.NewDecoder(fh)
494 return decoder.Decode(s.banList)
497 // loadThreadedNews loads the threaded news data from disk
498 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
499 fh, err := os.Open(threadedNewsPath)
503 decoder := yaml.NewDecoder(fh)
505 return decoder.Decode(s.ThreadedNews)
508 // loadAccounts loads account data from disk
509 func (s *Server) loadAccounts(userDir string) error {
510 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
515 if len(matches) == 0 {
516 return errors.New("no user accounts found in " + userDir)
519 for _, file := range matches {
520 fh, err := s.FS.Open(file)
526 decoder := yaml.NewDecoder(fh)
527 if err := decoder.Decode(&account); err != nil {
531 s.Accounts[account.Login] = &account
536 func (s *Server) loadConfig(path string) error {
537 fh, err := s.FS.Open(path)
542 decoder := yaml.NewDecoder(fh)
543 err = decoder.Decode(s.Config)
548 validate := validator.New()
549 err = validate.Struct(s.Config)
556 // handleNewConnection takes a new net.Conn and performs the initial login sequence
557 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
558 defer dontPanic(s.Logger)
560 if err := Handshake(rwc); err != nil {
564 // Create a new scanner for parsing incoming bytes into transaction tokens
565 scanner := bufio.NewScanner(rwc)
566 scanner.Split(transactionScanner)
570 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
571 // scanner re-uses the buffer for subsequent scans.
572 buf := make([]byte, len(scanner.Bytes()))
573 copy(buf, scanner.Bytes())
575 var clientLogin Transaction
576 if _, err := clientLogin.Write(buf); err != nil {
580 c := s.NewClientConn(rwc, remoteAddr)
582 // check if remoteAddr is present in the ban list
583 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
586 s.outbox <- *NewTransaction(
589 NewField(fieldData, []byte("You are permanently banned on this server")),
590 NewField(fieldChatOptions, []byte{0, 0}),
592 time.Sleep(1 * time.Second)
594 } else if time.Now().Before(*banUntil) {
595 s.outbox <- *NewTransaction(
598 NewField(fieldData, []byte("You are temporarily banned on this server")),
599 NewField(fieldChatOptions, []byte{0, 0}),
601 time.Sleep(1 * time.Second)
608 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
609 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
610 c.Version = clientLogin.GetField(fieldVersion).Data
613 for _, char := range encodedLogin {
614 login += string(rune(255 - uint(char)))
620 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
622 // If authentication fails, send error reply and close connection
623 if !c.Authenticate(login, encodedPassword) {
624 t := c.NewErrReply(&clientLogin, "Incorrect login.")
625 b, err := t.MarshalBinary()
629 if _, err := rwc.Write(b); err != nil {
633 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
638 if clientLogin.GetField(fieldUserIconID).Data != nil {
639 c.Icon = clientLogin.GetField(fieldUserIconID).Data
642 c.Account = c.Server.Accounts[login]
644 if clientLogin.GetField(fieldUserName).Data != nil {
645 if c.Authorize(accessAnyName) {
646 c.UserName = clientLogin.GetField(fieldUserName).Data
648 c.UserName = []byte(c.Account.Name)
652 if c.Authorize(accessDisconUser) {
653 c.Flags = []byte{0, 2}
656 s.outbox <- c.NewReply(&clientLogin,
657 NewField(fieldVersion, []byte{0x00, 0xbe}),
658 NewField(fieldCommunityBannerID, []byte{0, 0}),
659 NewField(fieldServerName, []byte(s.Config.Name)),
662 // Send user access privs so client UI knows how to behave
663 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:]))
665 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
666 // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send
667 // tranShowAgreement but with the NoServerAgreement field set to 1.
668 if c.Authorize(accessNoAgreement) {
669 // If client version is nil, then the client uses the 1.2.3 login behavior
670 if c.Version != nil {
671 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1}))
674 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
677 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
678 // TODO: figure out a generalized solution that doesn't require playing whack-a-mole for specific client versions
679 if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) || bytes.Equal(c.Version, frogblastVersion) || bytes.Equal(c.Version, obsessionVersion) {
681 c.logger = c.logger.With("name", string(c.UserName))
682 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }()))
684 for _, t := range c.notifyOthers(
686 tranNotifyChangeUser, nil,
687 NewField(fieldUserName, c.UserName),
688 NewField(fieldUserID, *c.ID),
689 NewField(fieldUserIconID, c.Icon),
690 NewField(fieldUserFlags, c.Flags),
697 c.Server.Stats.ConnectionCounter += 1
698 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
699 c.Server.Stats.ConnectionPeak = len(s.Clients)
702 // Scan for new transactions and handle them as they come in.
704 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
705 // scanner re-uses the buffer for subsequent scans.
706 buf := make([]byte, len(scanner.Bytes()))
707 copy(buf, scanner.Bytes())
710 if _, err := t.Write(buf); err != nil {
714 if err := c.handleTransaction(t); err != nil {
715 c.logger.Errorw("Error handling transaction", "err", err)
721 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
722 s.PrivateChatsMu.Lock()
723 defer s.PrivateChatsMu.Unlock()
725 randID := make([]byte, 4)
727 data := binary.BigEndian.Uint32(randID[:])
729 s.PrivateChats[data] = &PrivateChat{
730 ClientConn: make(map[uint16]*ClientConn),
732 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
737 const dlFldrActionSendFile = 1
738 const dlFldrActionResumeFile = 2
739 const dlFldrActionNextFile = 3
741 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
742 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
743 defer dontPanic(s.Logger)
745 txBuf := make([]byte, 16)
746 if _, err := io.ReadFull(rwc, txBuf); err != nil {
751 if _, err := t.Write(txBuf); err != nil {
757 delete(s.fileTransfers, t.ReferenceNumber)
760 // Wait a few seconds before closing the connection: this is a workaround for problems
761 // observed with Windows clients where the client must initiate close of the TCP connection before
762 // the server does. This is gross and seems unnecessary. TODO: Revisit?
763 time.Sleep(3 * time.Second)
767 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
770 return errors.New("invalid transaction ID")
774 fileTransfer.ClientConn.transfersMU.Lock()
775 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
776 fileTransfer.ClientConn.transfersMU.Unlock()
779 rLogger := s.Logger.With(
780 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
781 "login", fileTransfer.ClientConn.Account.Login,
782 "name", string(fileTransfer.ClientConn.UserName),
785 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
790 switch fileTransfer.Type {
792 if err := s.bannerDownload(rwc); err != nil {
796 s.Stats.DownloadCounter += 1
797 s.Stats.DownloadsInProgress += 1
799 s.Stats.DownloadsInProgress -= 1
803 if fileTransfer.fileResumeData != nil {
804 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
807 fw, err := newFileWrapper(s.FS, fullPath, 0)
812 rLogger.Infow("File download started", "filePath", fullPath)
814 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
815 if fileTransfer.options == nil {
816 // Start by sending flat file object to client
817 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
822 file, err := fw.dataForkReader()
827 br := bufio.NewReader(file)
828 if _, err := br.Discard(int(dataOffset)); err != nil {
832 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
836 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
837 if fileTransfer.fileResumeData == nil {
838 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
844 rFile, err := fw.rsrcForkFile()
849 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
854 s.Stats.UploadCounter += 1
855 s.Stats.UploadsInProgress += 1
856 defer func() { s.Stats.UploadsInProgress -= 1 }()
860 // A file upload has three possible cases:
861 // 1) Upload a new file
862 // 2) Resume a partially transferred file
863 // 3) Replace a fully uploaded file
864 // We have to infer which case applies by inspecting what is already on the filesystem
866 // 1) Check for existing file:
867 _, err = os.Stat(fullPath)
869 return errors.New("existing file found at " + fullPath)
871 if errors.Is(err, fs.ErrNotExist) {
872 // If not found, open or create a new .incomplete file
873 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
879 f, err := newFileWrapper(s.FS, fullPath, 0)
884 rLogger.Infow("File upload started", "dstFile", fullPath)
886 rForkWriter := io.Discard
887 iForkWriter := io.Discard
888 if s.Config.PreserveResourceForks {
889 rForkWriter, err = f.rsrcForkWriter()
894 iForkWriter, err = f.infoForkWriter()
900 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
904 if err := file.Close(); err != nil {
908 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
912 rLogger.Infow("File upload complete", "dstFile", fullPath)
915 s.Stats.DownloadCounter += 1
916 s.Stats.DownloadsInProgress += 1
917 defer func() { s.Stats.DownloadsInProgress -= 1 }()
919 // Folder Download flow:
920 // 1. Get filePath from the transfer
921 // 2. Iterate over files
922 // 3. For each fileWrapper:
923 // Send fileWrapper header to client
924 // The client can reply in 3 ways:
926 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
927 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
929 // 2. If download of a fileWrapper is to be resumed:
931 // []byte{0x00, 0x02} // download folder action
932 // [2]byte // Resume data size
933 // []byte fileWrapper resume data (see myField_FileResumeData)
935 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
937 // When download is requested (case 2 or 3), server replies with:
938 // [4]byte - fileWrapper size
939 // []byte - Flattened File Object
941 // After every fileWrapper download, client could request next fileWrapper with:
942 // []byte{0x00, 0x03}
944 // This notifies the server to send the next item header
946 basePathLen := len(fullPath)
948 rLogger.Infow("Start folder download", "path", fullPath)
950 nextAction := make([]byte, 2)
951 if _, err := io.ReadFull(rwc, nextAction); err != nil {
956 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
957 s.Stats.DownloadCounter += 1
965 if strings.HasPrefix(info.Name(), ".") {
969 hlFile, err := newFileWrapper(s.FS, path, 0)
974 subPath := path[basePathLen+1:]
975 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
981 fileHeader := NewFileHeader(subPath, info.IsDir())
983 // Send the fileWrapper header to client
984 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
985 s.Logger.Errorf("error sending file header: %v", err)
989 // Read the client's Next Action request
990 if _, err := io.ReadFull(rwc, nextAction); err != nil {
994 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
998 switch nextAction[1] {
999 case dlFldrActionResumeFile:
1000 // get size of resumeData
1001 resumeDataByteLen := make([]byte, 2)
1002 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
1006 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
1007 resumeDataBytes := make([]byte, resumeDataLen)
1008 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1012 var frd FileResumeData
1013 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1016 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1017 case dlFldrActionNextFile:
1018 // client asked to skip this file
1026 rLogger.Infow("File download started",
1027 "fileName", info.Name(),
1028 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1031 // Send file size to client
1032 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1037 // Send ffo bytes to client
1038 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1043 file, err := s.FS.Open(path)
1048 // wr := bufio.NewWriterSize(rwc, 1460)
1049 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1053 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1054 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1059 rFile, err := hlFile.rsrcForkFile()
1064 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1069 // Read the client's Next Action request. This is always 3, I think?
1070 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1082 s.Stats.UploadCounter += 1
1083 s.Stats.UploadsInProgress += 1
1084 defer func() { s.Stats.UploadsInProgress -= 1 }()
1086 "Folder upload started",
1087 "dstPath", fullPath,
1088 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1089 "FolderItemCount", fileTransfer.FolderItemCount,
1092 // Check if the target folder exists. If not, create it.
1093 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1094 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1099 // Begin the folder upload flow by sending the "next file action" to client
1100 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1104 fileSize := make([]byte, 4)
1106 for i := 0; i < fileTransfer.ItemCount(); i++ {
1107 s.Stats.UploadCounter += 1
1110 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1113 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1116 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1120 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1122 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1127 "Folder upload continued",
1128 "FormattedPath", fu.FormattedPath(),
1129 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1130 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1133 if fu.IsFolder == [2]byte{0, 1} {
1134 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1135 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1140 // Tell client to send next file
1141 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1145 nextAction := dlFldrActionSendFile
1147 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1148 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1149 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1153 nextAction = dlFldrActionNextFile
1156 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1157 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1158 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1162 nextAction = dlFldrActionResumeFile
1165 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1170 case dlFldrActionNextFile:
1172 case dlFldrActionResumeFile:
1173 offset := make([]byte, 4)
1174 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1176 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1181 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1183 b, _ := fileResumeData.BinaryMarshal()
1185 bs := make([]byte, 2)
1186 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1188 if _, err := rwc.Write(append(bs, b...)); err != nil {
1192 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1196 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1200 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1205 case dlFldrActionSendFile:
1206 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1210 filePath := filepath.Join(fullPath, fu.FormattedPath())
1212 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1217 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1219 incWriter, err := hlFile.incFileWriter()
1224 rForkWriter := io.Discard
1225 iForkWriter := io.Discard
1226 if s.Config.PreserveResourceForks {
1227 iForkWriter, err = hlFile.infoForkWriter()
1232 rForkWriter, err = hlFile.rsrcForkWriter()
1237 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1241 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1246 // Tell client to send next fileWrapper
1247 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1252 rLogger.Infof("Folder upload complete")