10 "github.com/go-playground/validator/v10"
26 type contextKey string
28 var contextKeyReq = contextKey("req")
30 type requestCtx struct {
37 userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
38 idleCheckInterval = 10 // time in seconds to check for idle users
39 trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
42 var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
46 Accounts map[string]*Account
48 Clients map[uint16]*ClientConn
49 fileTransfers map[[4]byte]*FileTransfer
53 Logger *zap.SugaredLogger
55 PrivateChatsMu sync.Mutex
56 PrivateChats map[uint32]*PrivateChat
62 FS FileStore // Storage backend to use for File storage
64 outbox chan Transaction
67 threadedNewsMux sync.Mutex
68 ThreadedNews *ThreadedNews
70 flatNewsMux sync.Mutex
74 banList map[string]*time.Time
77 type PrivateChat struct {
79 ClientConn map[uint16]*ClientConn
82 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
83 s.Logger.Infow("Hotline server started",
85 "API port", fmt.Sprintf(":%v", s.Port),
86 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
93 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
98 s.Logger.Fatal(s.Serve(ctx, ln))
103 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
109 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
117 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
119 conn, err := ln.Accept()
125 defer func() { _ = conn.Close() }()
127 err = s.handleFileTransfer(
128 context.WithValue(ctx, contextKeyReq, requestCtx{
129 remoteAddr: conn.RemoteAddr().String(),
135 s.Logger.Errorw("file transfer error", "reason", err)
141 func (s *Server) sendTransaction(t Transaction) error {
142 clientID, err := byteToInt(*t.clientID)
148 client := s.Clients[uint16(clientID)]
150 return fmt.Errorf("invalid client id %v", *t.clientID)
155 b, err := t.MarshalBinary()
160 if _, err := client.Connection.Write(b); err != nil {
167 func (s *Server) processOutbox() {
171 if err := s.sendTransaction(t); err != nil {
172 s.Logger.Errorw("error sending transaction", "err", err)
178 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
182 conn, err := ln.Accept()
184 s.Logger.Errorw("error accepting connection", "err", err)
186 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
187 remoteAddr: conn.RemoteAddr().String(),
191 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
194 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
196 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
198 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
206 agreementFile = "Agreement.txt"
209 // NewServer constructs a new Server from a config dir
210 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
213 Accounts: make(map[string]*Account),
215 Clients: make(map[uint16]*ClientConn),
216 fileTransfers: make(map[[4]byte]*FileTransfer),
217 PrivateChats: make(map[uint32]*PrivateChat),
218 ConfigDir: configDir,
220 NextGuestID: new(uint16),
221 outbox: make(chan Transaction),
222 Stats: &Stats{StartTime: time.Now()},
223 ThreadedNews: &ThreadedNews{},
225 banList: make(map[string]*time.Time),
230 // generate a new random passID for tracker registration
231 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
235 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
240 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
244 // try to load the ban list, but ignore errors as this file may not be present or may be empty
245 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
247 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
251 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
255 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
259 server.Config.FileRoot = filepath.Join(configDir, "Files")
261 *server.NextGuestID = 1
263 if server.Config.EnableTrackerRegistration {
265 "Tracker registration enabled",
266 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
267 "trackers", server.Config.Trackers,
272 tr := &TrackerRegistration{
273 UserCount: server.userCount(),
274 PassID: server.TrackerPassID[:],
275 Name: server.Config.Name,
276 Description: server.Config.Description,
278 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
279 for _, t := range server.Config.Trackers {
280 if err := register(t, tr); err != nil {
281 server.Logger.Errorw("unable to register with tracker %v", "error", err)
283 server.Logger.Debugw("Sent Tracker registration", "addr", t)
286 time.Sleep(trackerUpdateFrequency * time.Second)
291 // Start Client Keepalive go routine
292 go server.keepaliveHandler()
297 func (s *Server) userCount() int {
301 return len(s.Clients)
304 func (s *Server) keepaliveHandler() {
306 time.Sleep(idleCheckInterval * time.Second)
309 for _, c := range s.Clients {
310 c.IdleTime += idleCheckInterval
311 if c.IdleTime > userIdleSeconds && !c.Idle {
314 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
315 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
316 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
319 tranNotifyChangeUser,
320 NewField(fieldUserID, *c.ID),
321 NewField(fieldUserFlags, c.Flags),
322 NewField(fieldUserName, c.UserName),
323 NewField(fieldUserIconID, c.Icon),
331 func (s *Server) writeBanList() error {
333 defer s.banListMU.Unlock()
335 out, err := yaml.Marshal(s.banList)
339 err = ioutil.WriteFile(
340 filepath.Join(s.ConfigDir, "Banlist.yaml"),
347 func (s *Server) writeThreadedNews() error {
348 s.threadedNewsMux.Lock()
349 defer s.threadedNewsMux.Unlock()
351 out, err := yaml.Marshal(s.ThreadedNews)
355 err = s.FS.WriteFile(
356 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
363 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
367 clientConn := &ClientConn{
376 transfers: map[int]map[[4]byte]*FileTransfer{},
378 RemoteAddr: remoteAddr,
380 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
391 binary.BigEndian.PutUint16(*clientConn.ID, ID)
392 s.Clients[ID] = clientConn
397 // NewUser creates a new user account entry in the server map and config file
398 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
405 Password: hashAndSalt([]byte(password)),
408 out, err := yaml.Marshal(&account)
412 s.Accounts[login] = &account
414 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
417 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
421 // update renames the user login
422 if login != newLogin {
423 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
427 s.Accounts[newLogin] = s.Accounts[login]
428 delete(s.Accounts, login)
431 account := s.Accounts[newLogin]
432 account.Access = access
434 account.Password = password
436 out, err := yaml.Marshal(&account)
441 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
448 // DeleteUser deletes the user account
449 func (s *Server) DeleteUser(login string) error {
453 delete(s.Accounts, login)
455 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
458 func (s *Server) connectedUsers() []Field {
462 var connectedUsers []Field
463 for _, c := range sortedClients(s.Clients) {
471 Name: string(c.UserName),
473 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
475 return connectedUsers
478 func (s *Server) loadBanList(path string) error {
479 fh, err := os.Open(path)
483 decoder := yaml.NewDecoder(fh)
485 return decoder.Decode(s.banList)
488 // loadThreadedNews loads the threaded news data from disk
489 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
490 fh, err := os.Open(threadedNewsPath)
494 decoder := yaml.NewDecoder(fh)
496 return decoder.Decode(s.ThreadedNews)
499 // loadAccounts loads account data from disk
500 func (s *Server) loadAccounts(userDir string) error {
501 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
506 if len(matches) == 0 {
507 return errors.New("no user accounts found in " + userDir)
510 for _, file := range matches {
511 fh, err := s.FS.Open(file)
517 decoder := yaml.NewDecoder(fh)
518 if err := decoder.Decode(&account); err != nil {
522 s.Accounts[account.Login] = &account
527 func (s *Server) loadConfig(path string) error {
528 fh, err := s.FS.Open(path)
533 decoder := yaml.NewDecoder(fh)
534 err = decoder.Decode(s.Config)
539 validate := validator.New()
540 err = validate.Struct(s.Config)
547 // handleNewConnection takes a new net.Conn and performs the initial login sequence
548 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
549 defer dontPanic(s.Logger)
551 if err := Handshake(rwc); err != nil {
555 // Create a new scanner for parsing incoming bytes into transaction tokens
556 scanner := bufio.NewScanner(rwc)
557 scanner.Split(transactionScanner)
561 var clientLogin Transaction
562 if _, err := clientLogin.Write(scanner.Bytes()); err != nil {
566 c := s.NewClientConn(rwc, remoteAddr)
568 // check if remoteAddr is present in the ban list
569 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
572 s.outbox <- *NewTransaction(
575 NewField(fieldData, []byte("You are permanently banned on this server")),
576 NewField(fieldChatOptions, []byte{0, 0}),
578 time.Sleep(1 * time.Second)
580 } else if time.Now().Before(*banUntil) {
581 s.outbox <- *NewTransaction(
584 NewField(fieldData, []byte("You are temporarily banned on this server")),
585 NewField(fieldChatOptions, []byte{0, 0}),
587 time.Sleep(1 * time.Second)
594 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
595 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
596 c.Version = clientLogin.GetField(fieldVersion).Data
599 for _, char := range encodedLogin {
600 login += string(rune(255 - uint(char)))
606 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
608 // If authentication fails, send error reply and close connection
609 if !c.Authenticate(login, encodedPassword) {
610 t := c.NewErrReply(&clientLogin, "Incorrect login.")
611 b, err := t.MarshalBinary()
615 if _, err := rwc.Write(b); err != nil {
619 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
624 if clientLogin.GetField(fieldUserIconID).Data != nil {
625 c.Icon = clientLogin.GetField(fieldUserIconID).Data
628 c.Account = c.Server.Accounts[login]
630 if clientLogin.GetField(fieldUserName).Data != nil {
631 if c.Authorize(accessAnyName) {
632 c.UserName = clientLogin.GetField(fieldUserName).Data
634 c.UserName = []byte(c.Account.Name)
638 if c.Authorize(accessDisconUser) {
639 c.Flags = []byte{0, 2}
642 s.outbox <- c.NewReply(&clientLogin,
643 NewField(fieldVersion, []byte{0x00, 0xbe}),
644 NewField(fieldCommunityBannerID, []byte{0, 0}),
645 NewField(fieldServerName, []byte(s.Config.Name)),
648 // Send user access privs so client UI knows how to behave
649 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:]))
651 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
652 // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send
653 // tranShowAgreement but with the NoServerAgreement field set to 1.
654 if c.Authorize(accessNoAgreement) {
655 // If client version is nil, then the client uses the 1.2.3 login behavior
656 if c.Version != nil {
657 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1}))
660 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
663 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
664 if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) {
666 c.logger = c.logger.With("name", string(c.UserName))
667 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }()))
669 for _, t := range c.notifyOthers(
671 tranNotifyChangeUser, nil,
672 NewField(fieldUserName, c.UserName),
673 NewField(fieldUserID, *c.ID),
674 NewField(fieldUserIconID, c.Icon),
675 NewField(fieldUserFlags, c.Flags),
682 c.Server.Stats.LoginCount += 1
684 // Scan for new transactions and handle them as they come in.
686 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
687 // scanner re-uses the buffer for subsequent scans.
688 buf := make([]byte, len(scanner.Bytes()))
689 copy(buf, scanner.Bytes())
692 if _, err := t.Write(buf); err != nil {
696 if err := c.handleTransaction(t); err != nil {
697 c.logger.Errorw("Error handling transaction", "err", err)
703 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
704 s.PrivateChatsMu.Lock()
705 defer s.PrivateChatsMu.Unlock()
707 randID := make([]byte, 4)
709 data := binary.BigEndian.Uint32(randID[:])
711 s.PrivateChats[data] = &PrivateChat{
712 ClientConn: make(map[uint16]*ClientConn),
714 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
719 const dlFldrActionSendFile = 1
720 const dlFldrActionResumeFile = 2
721 const dlFldrActionNextFile = 3
723 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
724 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
725 defer dontPanic(s.Logger)
727 txBuf := make([]byte, 16)
728 if _, err := io.ReadFull(rwc, txBuf); err != nil {
733 if _, err := t.Write(txBuf); err != nil {
739 delete(s.fileTransfers, t.ReferenceNumber)
745 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
748 return errors.New("invalid transaction ID")
752 fileTransfer.ClientConn.transfersMU.Lock()
753 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
754 fileTransfer.ClientConn.transfersMU.Unlock()
757 rLogger := s.Logger.With(
758 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
759 "login", fileTransfer.ClientConn.Account.Login,
760 "name", string(fileTransfer.ClientConn.UserName),
763 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
768 switch fileTransfer.Type {
770 if err := s.bannerDownload(rwc); err != nil {
774 s.Stats.DownloadCounter += 1
777 if fileTransfer.fileResumeData != nil {
778 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
781 fw, err := newFileWrapper(s.FS, fullPath, 0)
786 rLogger.Infow("File download started", "filePath", fullPath)
788 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
789 if fileTransfer.options == nil {
790 // Start by sending flat file object to client
791 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
796 file, err := fw.dataForkReader()
801 br := bufio.NewReader(file)
802 if _, err := br.Discard(int(dataOffset)); err != nil {
806 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
810 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
811 if fileTransfer.fileResumeData == nil {
812 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
818 rFile, err := fw.rsrcForkFile()
823 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
828 s.Stats.UploadCounter += 1
832 // A file upload has three possible cases:
833 // 1) Upload a new file
834 // 2) Resume a partially transferred file
835 // 3) Replace a fully uploaded file
836 // We have to infer which case applies by inspecting what is already on the filesystem
838 // 1) Check for existing file:
839 _, err = os.Stat(fullPath)
841 return errors.New("existing file found at " + fullPath)
843 if errors.Is(err, fs.ErrNotExist) {
844 // If not found, open or create a new .incomplete file
845 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
851 f, err := newFileWrapper(s.FS, fullPath, 0)
856 rLogger.Infow("File upload started", "dstFile", fullPath)
858 rForkWriter := io.Discard
859 iForkWriter := io.Discard
860 if s.Config.PreserveResourceForks {
861 rForkWriter, err = f.rsrcForkWriter()
866 iForkWriter, err = f.infoForkWriter()
872 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
876 if err := file.Close(); err != nil {
880 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
884 rLogger.Infow("File upload complete", "dstFile", fullPath)
886 // Folder Download flow:
887 // 1. Get filePath from the transfer
888 // 2. Iterate over files
889 // 3. For each fileWrapper:
890 // Send fileWrapper header to client
891 // The client can reply in 3 ways:
893 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
894 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
896 // 2. If download of a fileWrapper is to be resumed:
898 // []byte{0x00, 0x02} // download folder action
899 // [2]byte // Resume data size
900 // []byte fileWrapper resume data (see myField_FileResumeData)
902 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
904 // When download is requested (case 2 or 3), server replies with:
905 // [4]byte - fileWrapper size
906 // []byte - Flattened File Object
908 // After every fileWrapper download, client could request next fileWrapper with:
909 // []byte{0x00, 0x03}
911 // This notifies the server to send the next item header
913 basePathLen := len(fullPath)
915 rLogger.Infow("Start folder download", "path", fullPath)
917 nextAction := make([]byte, 2)
918 if _, err := io.ReadFull(rwc, nextAction); err != nil {
923 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
924 s.Stats.DownloadCounter += 1
932 if strings.HasPrefix(info.Name(), ".") {
936 hlFile, err := newFileWrapper(s.FS, path, 0)
941 subPath := path[basePathLen+1:]
942 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
948 fileHeader := NewFileHeader(subPath, info.IsDir())
950 // Send the fileWrapper header to client
951 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
952 s.Logger.Errorf("error sending file header: %v", err)
956 // Read the client's Next Action request
957 if _, err := io.ReadFull(rwc, nextAction); err != nil {
961 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
965 switch nextAction[1] {
966 case dlFldrActionResumeFile:
967 // get size of resumeData
968 resumeDataByteLen := make([]byte, 2)
969 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
973 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
974 resumeDataBytes := make([]byte, resumeDataLen)
975 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
979 var frd FileResumeData
980 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
983 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
984 case dlFldrActionNextFile:
985 // client asked to skip this file
993 rLogger.Infow("File download started",
994 "fileName", info.Name(),
995 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
998 // Send file size to client
999 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1004 // Send ffo bytes to client
1005 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1010 file, err := s.FS.Open(path)
1015 // wr := bufio.NewWriterSize(rwc, 1460)
1016 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1020 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1021 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1026 rFile, err := hlFile.rsrcForkFile()
1031 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1036 // Read the client's Next Action request. This is always 3, I think?
1037 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1050 "Folder upload started",
1051 "dstPath", fullPath,
1052 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1053 "FolderItemCount", fileTransfer.FolderItemCount,
1056 // Check if the target folder exists. If not, create it.
1057 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1058 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1063 // Begin the folder upload flow by sending the "next file action" to client
1064 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1068 fileSize := make([]byte, 4)
1070 for i := 0; i < fileTransfer.ItemCount(); i++ {
1071 s.Stats.UploadCounter += 1
1074 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1077 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1080 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1084 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1086 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1091 "Folder upload continued",
1092 "FormattedPath", fu.FormattedPath(),
1093 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1094 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1097 if fu.IsFolder == [2]byte{0, 1} {
1098 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1099 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1104 // Tell client to send next file
1105 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1109 nextAction := dlFldrActionSendFile
1111 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1112 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1113 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1117 nextAction = dlFldrActionNextFile
1120 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1121 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1122 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1126 nextAction = dlFldrActionResumeFile
1129 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1134 case dlFldrActionNextFile:
1136 case dlFldrActionResumeFile:
1137 offset := make([]byte, 4)
1138 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1140 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1145 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1147 b, _ := fileResumeData.BinaryMarshal()
1149 bs := make([]byte, 2)
1150 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1152 if _, err := rwc.Write(append(bs, b...)); err != nil {
1156 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1160 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1164 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1169 case dlFldrActionSendFile:
1170 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1174 filePath := filepath.Join(fullPath, fu.FormattedPath())
1176 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1181 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1183 incWriter, err := hlFile.incFileWriter()
1188 rForkWriter := io.Discard
1189 iForkWriter := io.Discard
1190 if s.Config.PreserveResourceForks {
1191 iForkWriter, err = hlFile.infoForkWriter()
1196 rForkWriter, err = hlFile.rsrcForkWriter()
1201 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1205 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1210 // Tell client to send next fileWrapper
1211 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1216 rLogger.Infof("Folder upload complete")