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
41 Accounts map[string]*Account
43 Clients map[uint16]*ClientConn
44 fileTransfers map[[4]byte]*FileTransfer
48 Logger *zap.SugaredLogger
50 PrivateChatsMu sync.Mutex
51 PrivateChats map[uint32]*PrivateChat
59 FS FileStore // Storage backend to use for File storage
61 outbox chan Transaction
64 threadedNewsMux sync.Mutex
65 ThreadedNews *ThreadedNews
67 flatNewsMux sync.Mutex
71 banList map[string]*time.Time
74 func (s *Server) CurrentStats() Stats {
76 defer s.StatsMu.Unlock()
79 stats.CurrentlyConnected = len(s.Clients)
84 type PrivateChat struct {
86 ClientConn map[uint16]*ClientConn
89 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
90 s.Logger.Infow("Hotline server started",
92 "API port", fmt.Sprintf(":%v", s.Port),
93 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
100 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
105 s.Logger.Fatal(s.Serve(ctx, ln))
110 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
116 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
124 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
126 conn, err := ln.Accept()
132 defer func() { _ = conn.Close() }()
134 err = s.handleFileTransfer(
135 context.WithValue(ctx, contextKeyReq, requestCtx{
136 remoteAddr: conn.RemoteAddr().String(),
142 s.Logger.Errorw("file transfer error", "reason", err)
148 func (s *Server) sendTransaction(t Transaction) error {
149 clientID, err := byteToInt(*t.clientID)
156 client := s.Clients[uint16(clientID)]
158 return fmt.Errorf("invalid client id %v", *t.clientID)
161 b, err := t.MarshalBinary()
166 if _, err := client.Connection.Write(b); err != nil {
173 func (s *Server) processOutbox() {
177 if err := s.sendTransaction(t); err != nil {
178 s.Logger.Errorw("error sending transaction", "err", err)
184 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
188 conn, err := ln.Accept()
190 s.Logger.Errorw("error accepting connection", "err", err)
192 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
193 remoteAddr: conn.RemoteAddr().String(),
197 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
200 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
202 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
204 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
212 agreementFile = "Agreement.txt"
215 // NewServer constructs a new Server from a config dir
216 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
219 Accounts: make(map[string]*Account),
221 Clients: make(map[uint16]*ClientConn),
222 fileTransfers: make(map[[4]byte]*FileTransfer),
223 PrivateChats: make(map[uint32]*PrivateChat),
224 ConfigDir: configDir,
226 NextGuestID: new(uint16),
227 outbox: make(chan Transaction),
228 Stats: &Stats{Since: time.Now()},
229 ThreadedNews: &ThreadedNews{},
231 banList: make(map[string]*time.Time),
236 // generate a new random passID for tracker registration
237 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
241 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
246 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
250 // try to load the ban list, but ignore errors as this file may not be present or may be empty
251 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
253 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
257 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
261 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
265 server.Config.FileRoot = filepath.Join(configDir, "Files")
267 *server.NextGuestID = 1
269 if server.Config.EnableTrackerRegistration {
271 "Tracker registration enabled",
272 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
273 "trackers", server.Config.Trackers,
278 tr := &TrackerRegistration{
279 UserCount: server.userCount(),
280 PassID: server.TrackerPassID[:],
281 Name: server.Config.Name,
282 Description: server.Config.Description,
284 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
285 for _, t := range server.Config.Trackers {
286 if err := register(t, tr); err != nil {
287 server.Logger.Errorw("unable to register with tracker %v", "error", err)
289 server.Logger.Debugw("Sent Tracker registration", "addr", t)
292 time.Sleep(trackerUpdateFrequency * time.Second)
297 // Start Client Keepalive go routine
298 go server.keepaliveHandler()
303 func (s *Server) userCount() int {
307 return len(s.Clients)
310 func (s *Server) keepaliveHandler() {
312 time.Sleep(idleCheckInterval * time.Second)
315 for _, c := range s.Clients {
316 c.IdleTime += idleCheckInterval
317 if c.IdleTime > userIdleSeconds && !c.Idle {
320 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
321 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
322 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
325 tranNotifyChangeUser,
326 NewField(fieldUserID, *c.ID),
327 NewField(fieldUserFlags, c.Flags),
328 NewField(fieldUserName, c.UserName),
329 NewField(fieldUserIconID, c.Icon),
337 func (s *Server) writeBanList() error {
339 defer s.banListMU.Unlock()
341 out, err := yaml.Marshal(s.banList)
345 err = ioutil.WriteFile(
346 filepath.Join(s.ConfigDir, "Banlist.yaml"),
353 func (s *Server) writeThreadedNews() error {
354 s.threadedNewsMux.Lock()
355 defer s.threadedNewsMux.Unlock()
357 out, err := yaml.Marshal(s.ThreadedNews)
361 err = s.FS.WriteFile(
362 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
369 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
373 clientConn := &ClientConn{
382 transfers: map[int]map[[4]byte]*FileTransfer{},
384 RemoteAddr: remoteAddr,
386 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
397 binary.BigEndian.PutUint16(*clientConn.ID, ID)
398 s.Clients[ID] = clientConn
403 // NewUser creates a new user account entry in the server map and config file
404 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
411 Password: hashAndSalt([]byte(password)),
414 out, err := yaml.Marshal(&account)
418 s.Accounts[login] = &account
420 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
423 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
427 // update renames the user login
428 if login != newLogin {
429 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
433 s.Accounts[newLogin] = s.Accounts[login]
434 delete(s.Accounts, login)
437 account := s.Accounts[newLogin]
438 account.Access = access
440 account.Password = password
442 out, err := yaml.Marshal(&account)
447 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
454 // DeleteUser deletes the user account
455 func (s *Server) DeleteUser(login string) error {
459 delete(s.Accounts, login)
461 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
464 func (s *Server) connectedUsers() []Field {
468 var connectedUsers []Field
469 for _, c := range sortedClients(s.Clients) {
477 Name: string(c.UserName),
479 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
481 return connectedUsers
484 func (s *Server) loadBanList(path string) error {
485 fh, err := os.Open(path)
489 decoder := yaml.NewDecoder(fh)
491 return decoder.Decode(s.banList)
494 // loadThreadedNews loads the threaded news data from disk
495 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
496 fh, err := os.Open(threadedNewsPath)
500 decoder := yaml.NewDecoder(fh)
502 return decoder.Decode(s.ThreadedNews)
505 // loadAccounts loads account data from disk
506 func (s *Server) loadAccounts(userDir string) error {
507 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
512 if len(matches) == 0 {
513 return errors.New("no user accounts found in " + userDir)
516 for _, file := range matches {
517 fh, err := s.FS.Open(file)
523 decoder := yaml.NewDecoder(fh)
524 if err := decoder.Decode(&account); err != nil {
528 s.Accounts[account.Login] = &account
533 func (s *Server) loadConfig(path string) error {
534 fh, err := s.FS.Open(path)
539 decoder := yaml.NewDecoder(fh)
540 err = decoder.Decode(s.Config)
545 validate := validator.New()
546 err = validate.Struct(s.Config)
553 // handleNewConnection takes a new net.Conn and performs the initial login sequence
554 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
555 defer dontPanic(s.Logger)
557 if err := Handshake(rwc); err != nil {
561 // Create a new scanner for parsing incoming bytes into transaction tokens
562 scanner := bufio.NewScanner(rwc)
563 scanner.Split(transactionScanner)
567 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
568 // scanner re-uses the buffer for subsequent scans.
569 buf := make([]byte, len(scanner.Bytes()))
570 copy(buf, scanner.Bytes())
572 var clientLogin Transaction
573 if _, err := clientLogin.Write(buf); err != nil {
577 c := s.NewClientConn(rwc, remoteAddr)
579 // check if remoteAddr is present in the ban list
580 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
583 s.outbox <- *NewTransaction(
586 NewField(fieldData, []byte("You are permanently banned on this server")),
587 NewField(fieldChatOptions, []byte{0, 0}),
589 time.Sleep(1 * time.Second)
591 } else if time.Now().Before(*banUntil) {
592 s.outbox <- *NewTransaction(
595 NewField(fieldData, []byte("You are temporarily banned on this server")),
596 NewField(fieldChatOptions, []byte{0, 0}),
598 time.Sleep(1 * time.Second)
605 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
606 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
607 c.Version = clientLogin.GetField(fieldVersion).Data
610 for _, char := range encodedLogin {
611 login += string(rune(255 - uint(char)))
617 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
619 // If authentication fails, send error reply and close connection
620 if !c.Authenticate(login, encodedPassword) {
621 t := c.NewErrReply(&clientLogin, "Incorrect login.")
622 b, err := t.MarshalBinary()
626 if _, err := rwc.Write(b); err != nil {
630 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
635 if clientLogin.GetField(fieldUserIconID).Data != nil {
636 c.Icon = clientLogin.GetField(fieldUserIconID).Data
639 c.Account = c.Server.Accounts[login]
641 if clientLogin.GetField(fieldUserName).Data != nil {
642 if c.Authorize(accessAnyName) {
643 c.UserName = clientLogin.GetField(fieldUserName).Data
645 c.UserName = []byte(c.Account.Name)
649 if c.Authorize(accessDisconUser) {
650 c.Flags = []byte{0, 2}
653 s.outbox <- c.NewReply(&clientLogin,
654 NewField(fieldVersion, []byte{0x00, 0xbe}),
655 NewField(fieldCommunityBannerID, []byte{0, 0}),
656 NewField(fieldServerName, []byte(s.Config.Name)),
659 // Send user access privs so client UI knows how to behave
660 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:]))
662 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
663 // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send
664 // tranShowAgreement but with the NoServerAgreement field set to 1.
665 if c.Authorize(accessNoAgreement) {
666 // If client version is nil, then the client uses the 1.2.3 login behavior
667 if c.Version != nil {
668 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1}))
671 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
674 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
675 if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) || bytes.Equal(c.Version, frogblastVersion) {
677 c.logger = c.logger.With("name", string(c.UserName))
678 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }()))
680 for _, t := range c.notifyOthers(
682 tranNotifyChangeUser, nil,
683 NewField(fieldUserName, c.UserName),
684 NewField(fieldUserID, *c.ID),
685 NewField(fieldUserIconID, c.Icon),
686 NewField(fieldUserFlags, c.Flags),
693 c.Server.Stats.ConnectionCounter += 1
694 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
695 c.Server.Stats.ConnectionPeak = len(s.Clients)
698 // Scan for new transactions and handle them as they come in.
700 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
701 // scanner re-uses the buffer for subsequent scans.
702 buf := make([]byte, len(scanner.Bytes()))
703 copy(buf, scanner.Bytes())
706 if _, err := t.Write(buf); err != nil {
710 if err := c.handleTransaction(t); err != nil {
711 c.logger.Errorw("Error handling transaction", "err", err)
717 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
718 s.PrivateChatsMu.Lock()
719 defer s.PrivateChatsMu.Unlock()
721 randID := make([]byte, 4)
723 data := binary.BigEndian.Uint32(randID[:])
725 s.PrivateChats[data] = &PrivateChat{
726 ClientConn: make(map[uint16]*ClientConn),
728 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
733 const dlFldrActionSendFile = 1
734 const dlFldrActionResumeFile = 2
735 const dlFldrActionNextFile = 3
737 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
738 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
739 defer dontPanic(s.Logger)
741 txBuf := make([]byte, 16)
742 if _, err := io.ReadFull(rwc, txBuf); err != nil {
747 if _, err := t.Write(txBuf); err != nil {
753 delete(s.fileTransfers, t.ReferenceNumber)
756 // Wait a few seconds before closing the connection: this is a workaround for problems
757 // observed with Windows clients where the client must initiate close of the TCP connection before
758 // the server does. This is gross and seems unnecessary. TODO: Revisit?
759 time.Sleep(3 * time.Second)
763 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
766 return errors.New("invalid transaction ID")
770 fileTransfer.ClientConn.transfersMU.Lock()
771 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
772 fileTransfer.ClientConn.transfersMU.Unlock()
775 rLogger := s.Logger.With(
776 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
777 "login", fileTransfer.ClientConn.Account.Login,
778 "name", string(fileTransfer.ClientConn.UserName),
781 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
786 switch fileTransfer.Type {
788 if err := s.bannerDownload(rwc); err != nil {
792 s.Stats.DownloadCounter += 1
793 s.Stats.DownloadsInProgress += 1
795 s.Stats.DownloadsInProgress -= 1
799 if fileTransfer.fileResumeData != nil {
800 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
803 fw, err := newFileWrapper(s.FS, fullPath, 0)
808 rLogger.Infow("File download started", "filePath", fullPath)
810 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
811 if fileTransfer.options == nil {
812 // Start by sending flat file object to client
813 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
818 file, err := fw.dataForkReader()
823 br := bufio.NewReader(file)
824 if _, err := br.Discard(int(dataOffset)); err != nil {
828 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
832 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
833 if fileTransfer.fileResumeData == nil {
834 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
840 rFile, err := fw.rsrcForkFile()
845 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
850 s.Stats.UploadCounter += 1
851 s.Stats.UploadsInProgress += 1
852 defer func() { s.Stats.UploadsInProgress -= 1 }()
856 // A file upload has three possible cases:
857 // 1) Upload a new file
858 // 2) Resume a partially transferred file
859 // 3) Replace a fully uploaded file
860 // We have to infer which case applies by inspecting what is already on the filesystem
862 // 1) Check for existing file:
863 _, err = os.Stat(fullPath)
865 return errors.New("existing file found at " + fullPath)
867 if errors.Is(err, fs.ErrNotExist) {
868 // If not found, open or create a new .incomplete file
869 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
875 f, err := newFileWrapper(s.FS, fullPath, 0)
880 rLogger.Infow("File upload started", "dstFile", fullPath)
882 rForkWriter := io.Discard
883 iForkWriter := io.Discard
884 if s.Config.PreserveResourceForks {
885 rForkWriter, err = f.rsrcForkWriter()
890 iForkWriter, err = f.infoForkWriter()
896 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
900 if err := file.Close(); err != nil {
904 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
908 rLogger.Infow("File upload complete", "dstFile", fullPath)
911 s.Stats.DownloadCounter += 1
912 s.Stats.DownloadsInProgress += 1
913 defer func() { s.Stats.DownloadsInProgress -= 1 }()
915 // Folder Download flow:
916 // 1. Get filePath from the transfer
917 // 2. Iterate over files
918 // 3. For each fileWrapper:
919 // Send fileWrapper header to client
920 // The client can reply in 3 ways:
922 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
923 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
925 // 2. If download of a fileWrapper is to be resumed:
927 // []byte{0x00, 0x02} // download folder action
928 // [2]byte // Resume data size
929 // []byte fileWrapper resume data (see myField_FileResumeData)
931 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
933 // When download is requested (case 2 or 3), server replies with:
934 // [4]byte - fileWrapper size
935 // []byte - Flattened File Object
937 // After every fileWrapper download, client could request next fileWrapper with:
938 // []byte{0x00, 0x03}
940 // This notifies the server to send the next item header
942 basePathLen := len(fullPath)
944 rLogger.Infow("Start folder download", "path", fullPath)
946 nextAction := make([]byte, 2)
947 if _, err := io.ReadFull(rwc, nextAction); err != nil {
952 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
953 s.Stats.DownloadCounter += 1
961 if strings.HasPrefix(info.Name(), ".") {
965 hlFile, err := newFileWrapper(s.FS, path, 0)
970 subPath := path[basePathLen+1:]
971 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
977 fileHeader := NewFileHeader(subPath, info.IsDir())
979 // Send the fileWrapper header to client
980 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
981 s.Logger.Errorf("error sending file header: %v", err)
985 // Read the client's Next Action request
986 if _, err := io.ReadFull(rwc, nextAction); err != nil {
990 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
994 switch nextAction[1] {
995 case dlFldrActionResumeFile:
996 // get size of resumeData
997 resumeDataByteLen := make([]byte, 2)
998 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
1002 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
1003 resumeDataBytes := make([]byte, resumeDataLen)
1004 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1008 var frd FileResumeData
1009 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1012 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1013 case dlFldrActionNextFile:
1014 // client asked to skip this file
1022 rLogger.Infow("File download started",
1023 "fileName", info.Name(),
1024 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1027 // Send file size to client
1028 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1033 // Send ffo bytes to client
1034 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1039 file, err := s.FS.Open(path)
1044 // wr := bufio.NewWriterSize(rwc, 1460)
1045 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1049 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1050 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1055 rFile, err := hlFile.rsrcForkFile()
1060 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1065 // Read the client's Next Action request. This is always 3, I think?
1066 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1078 s.Stats.UploadCounter += 1
1079 s.Stats.UploadsInProgress += 1
1080 defer func() { s.Stats.UploadsInProgress -= 1 }()
1082 "Folder upload started",
1083 "dstPath", fullPath,
1084 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1085 "FolderItemCount", fileTransfer.FolderItemCount,
1088 // Check if the target folder exists. If not, create it.
1089 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1090 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1095 // Begin the folder upload flow by sending the "next file action" to client
1096 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1100 fileSize := make([]byte, 4)
1102 for i := 0; i < fileTransfer.ItemCount(); i++ {
1103 s.Stats.UploadCounter += 1
1106 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1109 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1112 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1116 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1118 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1123 "Folder upload continued",
1124 "FormattedPath", fu.FormattedPath(),
1125 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1126 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1129 if fu.IsFolder == [2]byte{0, 1} {
1130 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1131 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1136 // Tell client to send next file
1137 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1141 nextAction := dlFldrActionSendFile
1143 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1144 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1145 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1149 nextAction = dlFldrActionNextFile
1152 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1153 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1154 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1158 nextAction = dlFldrActionResumeFile
1161 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1166 case dlFldrActionNextFile:
1168 case dlFldrActionResumeFile:
1169 offset := make([]byte, 4)
1170 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1172 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1177 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1179 b, _ := fileResumeData.BinaryMarshal()
1181 bs := make([]byte, 2)
1182 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1184 if _, err := rwc.Write(append(bs, b...)); err != nil {
1188 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1192 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1196 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1201 case dlFldrActionSendFile:
1202 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1206 filePath := filepath.Join(fullPath, fu.FormattedPath())
1208 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1213 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1215 incWriter, err := hlFile.incFileWriter()
1220 rForkWriter := io.Discard
1221 iForkWriter := io.Discard
1222 if s.Config.PreserveResourceForks {
1223 iForkWriter, err = hlFile.infoForkWriter()
1228 rForkWriter, err = hlFile.rsrcForkWriter()
1233 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1237 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1242 // Tell client to send next fileWrapper
1243 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1248 rLogger.Infof("Folder upload complete")