10 "github.com/go-playground/validator/v10"
12 "golang.org/x/text/encoding/charmap"
27 type contextKey string
29 var contextKeyReq = contextKey("req")
31 type requestCtx struct {
35 // Converts bytes from Mac Roman encoding to UTF-8
36 var txtDecoder = charmap.Macintosh.NewDecoder()
38 // Converts bytes from UTF-8 to Mac Roman encoding
39 var txtEncoder = charmap.Macintosh.NewEncoder()
44 Accounts map[string]*Account
46 Clients map[uint16]*ClientConn
47 fileTransfers map[[4]byte]*FileTransfer
51 Logger *zap.SugaredLogger
54 PrivateChatsMu sync.Mutex
55 PrivateChats map[uint32]*PrivateChat
63 FS FileStore // Storage backend to use for File storage
65 outbox chan Transaction
68 threadedNewsMux sync.Mutex
69 ThreadedNews *ThreadedNews
71 flatNewsMux sync.Mutex
75 banList map[string]*time.Time
78 func (s *Server) CurrentStats() Stats {
80 defer s.StatsMu.Unlock()
83 stats.CurrentlyConnected = len(s.Clients)
88 type PrivateChat struct {
90 ClientConn map[uint16]*ClientConn
93 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
94 s.Logger.Infow("Hotline server started",
96 "API port", fmt.Sprintf("%s:%v", s.NetInterface, s.Port),
97 "Transfer port", fmt.Sprintf("%s:%v", s.NetInterface, s.Port+1),
100 var wg sync.WaitGroup
104 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port))
109 s.Logger.Fatal(s.Serve(ctx, ln))
114 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port+1))
119 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
127 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
129 conn, err := ln.Accept()
135 defer func() { _ = conn.Close() }()
137 err = s.handleFileTransfer(
138 context.WithValue(ctx, contextKeyReq, requestCtx{
139 remoteAddr: conn.RemoteAddr().String(),
145 s.Logger.Errorw("file transfer error", "reason", err)
151 func (s *Server) sendTransaction(t Transaction) error {
152 clientID, err := byteToInt(*t.clientID)
158 client := s.Clients[uint16(clientID)]
161 return fmt.Errorf("invalid client id %v", *t.clientID)
164 b, err := t.MarshalBinary()
169 _, err = client.Connection.Write(b)
177 func (s *Server) processOutbox() {
181 if err := s.sendTransaction(t); err != nil {
182 s.Logger.Errorw("error sending transaction", "err", err)
188 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
192 conn, err := ln.Accept()
194 s.Logger.Errorw("error accepting connection", "err", err)
196 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
197 remoteAddr: conn.RemoteAddr().String(),
201 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
204 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
206 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
208 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
216 agreementFile = "Agreement.txt"
219 // NewServer constructs a new Server from a config dir
220 func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger, fs FileStore) (*Server, error) {
222 NetInterface: netInterface,
224 Accounts: make(map[string]*Account),
226 Clients: make(map[uint16]*ClientConn),
227 fileTransfers: make(map[[4]byte]*FileTransfer),
228 PrivateChats: make(map[uint32]*PrivateChat),
229 ConfigDir: configDir,
231 NextGuestID: new(uint16),
232 outbox: make(chan Transaction),
233 Stats: &Stats{Since: time.Now()},
234 ThreadedNews: &ThreadedNews{},
236 banList: make(map[string]*time.Time),
241 // generate a new random passID for tracker registration
242 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
246 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
251 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
255 // try to load the ban list, but ignore errors as this file may not be present or may be empty
256 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
258 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
262 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
266 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
270 // If the FileRoot is an absolute path, use it, otherwise treat as a relative path to the config dir.
271 if !filepath.IsAbs(server.Config.FileRoot) {
272 server.Config.FileRoot = filepath.Join(configDir, server.Config.FileRoot)
275 server.banner, err = os.ReadFile(filepath.Join(server.ConfigDir, server.Config.BannerFile))
277 return nil, fmt.Errorf("error opening banner: %w", err)
280 *server.NextGuestID = 1
282 if server.Config.EnableTrackerRegistration {
284 "Tracker registration enabled",
285 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
286 "trackers", server.Config.Trackers,
291 tr := &TrackerRegistration{
292 UserCount: server.userCount(),
293 PassID: server.TrackerPassID,
294 Name: server.Config.Name,
295 Description: server.Config.Description,
297 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
298 for _, t := range server.Config.Trackers {
299 if err := register(t, tr); err != nil {
300 server.Logger.Errorw("unable to register with tracker %v", "error", err)
302 server.Logger.Debugw("Sent Tracker registration", "addr", t)
305 time.Sleep(trackerUpdateFrequency * time.Second)
310 // Start Client Keepalive go routine
311 go server.keepaliveHandler()
316 func (s *Server) userCount() int {
320 return len(s.Clients)
323 func (s *Server) keepaliveHandler() {
325 time.Sleep(idleCheckInterval * time.Second)
328 for _, c := range s.Clients {
329 c.IdleTime += idleCheckInterval
330 if c.IdleTime > userIdleSeconds && !c.Idle {
333 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
334 flagBitmap.SetBit(flagBitmap, UserFlagAway, 1)
335 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
338 TranNotifyChangeUser,
339 NewField(FieldUserID, *c.ID),
340 NewField(FieldUserFlags, c.Flags),
341 NewField(FieldUserName, c.UserName),
342 NewField(FieldUserIconID, c.Icon),
350 func (s *Server) writeBanList() error {
352 defer s.banListMU.Unlock()
354 out, err := yaml.Marshal(s.banList)
359 filepath.Join(s.ConfigDir, "Banlist.yaml"),
366 func (s *Server) writeThreadedNews() error {
367 s.threadedNewsMux.Lock()
368 defer s.threadedNewsMux.Unlock()
370 out, err := yaml.Marshal(s.ThreadedNews)
374 err = s.FS.WriteFile(
375 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
382 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
386 clientConn := &ClientConn{
395 RemoteAddr: remoteAddr,
396 transfers: map[int]map[[4]byte]*FileTransfer{
408 binary.BigEndian.PutUint16(*clientConn.ID, ID)
409 s.Clients[ID] = clientConn
414 // NewUser creates a new user account entry in the server map and config file
415 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
422 Password: hashAndSalt([]byte(password)),
425 out, err := yaml.Marshal(&account)
430 // Create account file, returning an error if one already exists.
431 file, err := os.OpenFile(
432 filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"),
433 os.O_CREATE|os.O_EXCL|os.O_WRONLY,
441 _, err = file.Write(out)
443 return fmt.Errorf("error writing account file: %w", err)
446 s.Accounts[login] = &account
451 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
455 // update renames the user login
456 if login != newLogin {
457 err := os.Rename(filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"), filepath.Join(s.ConfigDir, "Users", path.Join("/", newLogin)+".yaml"))
459 return fmt.Errorf("unable to rename account: %w", err)
461 s.Accounts[newLogin] = s.Accounts[login]
462 s.Accounts[newLogin].Login = newLogin
463 delete(s.Accounts, login)
466 account := s.Accounts[newLogin]
467 account.Access = access
469 account.Password = password
471 out, err := yaml.Marshal(&account)
476 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
483 // DeleteUser deletes the user account
484 func (s *Server) DeleteUser(login string) error {
488 err := s.FS.Remove(filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"))
493 delete(s.Accounts, login)
498 func (s *Server) connectedUsers() []Field {
502 var connectedUsers []Field
503 for _, c := range sortedClients(s.Clients) {
504 b, err := io.ReadAll(&User{
508 Name: string(c.UserName),
513 connectedUsers = append(connectedUsers, NewField(FieldUsernameWithInfo, b))
515 return connectedUsers
518 func (s *Server) loadBanList(path string) error {
519 fh, err := os.Open(path)
523 decoder := yaml.NewDecoder(fh)
525 return decoder.Decode(s.banList)
528 // loadThreadedNews loads the threaded news data from disk
529 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
530 fh, err := os.Open(threadedNewsPath)
534 decoder := yaml.NewDecoder(fh)
536 return decoder.Decode(s.ThreadedNews)
539 // loadAccounts loads account data from disk
540 func (s *Server) loadAccounts(userDir string) error {
541 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
546 if len(matches) == 0 {
547 return errors.New("no user accounts found in " + userDir)
550 for _, file := range matches {
551 fh, err := s.FS.Open(file)
557 decoder := yaml.NewDecoder(fh)
558 if err = decoder.Decode(&account); err != nil {
559 return fmt.Errorf("error loading account %s: %w", file, err)
562 s.Accounts[account.Login] = &account
567 func (s *Server) loadConfig(path string) error {
568 fh, err := s.FS.Open(path)
573 decoder := yaml.NewDecoder(fh)
574 err = decoder.Decode(s.Config)
579 validate := validator.New()
580 err = validate.Struct(s.Config)
587 // handleNewConnection takes a new net.Conn and performs the initial login sequence
588 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
589 defer dontPanic(s.Logger)
591 if err := Handshake(rwc); err != nil {
595 // Create a new scanner for parsing incoming bytes into transaction tokens
596 scanner := bufio.NewScanner(rwc)
597 scanner.Split(transactionScanner)
601 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
602 // scanner re-uses the buffer for subsequent scans.
603 buf := make([]byte, len(scanner.Bytes()))
604 copy(buf, scanner.Bytes())
606 var clientLogin Transaction
607 if _, err := clientLogin.Write(buf); err != nil {
611 // check if remoteAddr is present in the ban list
612 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
618 NewField(FieldData, []byte("You are permanently banned on this server")),
619 NewField(FieldChatOptions, []byte{0, 0}),
622 b, err := t.MarshalBinary()
627 _, err = rwc.Write(b)
632 time.Sleep(1 * time.Second)
637 if time.Now().Before(*banUntil) {
641 NewField(FieldData, []byte("You are temporarily banned on this server")),
642 NewField(FieldChatOptions, []byte{0, 0}),
644 b, err := t.MarshalBinary()
649 _, err = rwc.Write(b)
654 time.Sleep(1 * time.Second)
659 c := s.NewClientConn(rwc, remoteAddr)
662 encodedLogin := clientLogin.GetField(FieldUserLogin).Data
663 encodedPassword := clientLogin.GetField(FieldUserPassword).Data
664 c.Version = clientLogin.GetField(FieldVersion).Data
667 for _, char := range encodedLogin {
668 login += string(rune(255 - uint(char)))
674 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
676 // If authentication fails, send error reply and close connection
677 if !c.Authenticate(login, encodedPassword) {
678 t := c.NewErrReply(&clientLogin, "Incorrect login.")
679 b, err := t.MarshalBinary()
683 if _, err := rwc.Write(b); err != nil {
687 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
692 if clientLogin.GetField(FieldUserIconID).Data != nil {
693 c.Icon = clientLogin.GetField(FieldUserIconID).Data
696 c.Account = c.Server.Accounts[login]
698 if clientLogin.GetField(FieldUserName).Data != nil {
699 if c.Authorize(accessAnyName) {
700 c.UserName = clientLogin.GetField(FieldUserName).Data
702 c.UserName = []byte(c.Account.Name)
706 if c.Authorize(accessDisconUser) {
707 c.Flags = []byte{0, 2}
710 s.outbox <- c.NewReply(&clientLogin,
711 NewField(FieldVersion, []byte{0x00, 0xbe}),
712 NewField(FieldCommunityBannerID, []byte{0, 0}),
713 NewField(FieldServerName, []byte(s.Config.Name)),
716 // Send user access privs so client UI knows how to behave
717 c.Server.outbox <- *NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:]))
719 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
720 // client versions. For 1.2.3 client, we do not send TranShowAgreement. For other client versions, we send
721 // TranShowAgreement but with the NoServerAgreement field set to 1.
722 if c.Authorize(accessNoAgreement) {
723 // If client version is nil, then the client uses the 1.2.3 login behavior
724 if c.Version != nil {
725 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1}))
728 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement))
731 // If the client has provided a username as part of the login, we can infer that it is using the 1.2.3 login
732 // flow and not the 1.5+ flow.
733 if len(c.UserName) != 0 {
734 // Add the client username to the logger. For 1.5+ clients, we don't have this information yet as it comes as
735 // part of TranAgreed
736 c.logger = c.logger.With("name", string(c.UserName))
738 c.logger.Infow("Login successful", "clientVersion", "Not sent (probably 1.2.3)")
740 // Notify other clients on the server that the new user has logged in. For 1.5+ clients we don't have this
741 // information yet, so we do it in TranAgreed instead
742 for _, t := range c.notifyOthers(
744 TranNotifyChangeUser, nil,
745 NewField(FieldUserName, c.UserName),
746 NewField(FieldUserID, *c.ID),
747 NewField(FieldUserIconID, c.Icon),
748 NewField(FieldUserFlags, c.Flags),
755 c.Server.Stats.ConnectionCounter += 1
756 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
757 c.Server.Stats.ConnectionPeak = len(s.Clients)
760 // Scan for new transactions and handle them as they come in.
762 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
763 // scanner re-uses the buffer for subsequent scans.
764 buf := make([]byte, len(scanner.Bytes()))
765 copy(buf, scanner.Bytes())
768 if _, err := t.Write(buf); err != nil {
772 if err := c.handleTransaction(t); err != nil {
773 c.logger.Errorw("Error handling transaction", "err", err)
779 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
780 s.PrivateChatsMu.Lock()
781 defer s.PrivateChatsMu.Unlock()
783 randID := make([]byte, 4)
785 data := binary.BigEndian.Uint32(randID)
787 s.PrivateChats[data] = &PrivateChat{
788 ClientConn: make(map[uint16]*ClientConn),
790 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
795 const dlFldrActionSendFile = 1
796 const dlFldrActionResumeFile = 2
797 const dlFldrActionNextFile = 3
799 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
800 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
801 defer dontPanic(s.Logger)
803 txBuf := make([]byte, 16)
804 if _, err := io.ReadFull(rwc, txBuf); err != nil {
809 if _, err := t.Write(txBuf); err != nil {
815 delete(s.fileTransfers, t.ReferenceNumber)
818 // Wait a few seconds before closing the connection: this is a workaround for problems
819 // observed with Windows clients where the client must initiate close of the TCP connection before
820 // the server does. This is gross and seems unnecessary. TODO: Revisit?
821 time.Sleep(3 * time.Second)
825 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
828 return errors.New("invalid transaction ID")
832 fileTransfer.ClientConn.transfersMU.Lock()
833 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
834 fileTransfer.ClientConn.transfersMU.Unlock()
837 rLogger := s.Logger.With(
838 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
839 "login", fileTransfer.ClientConn.Account.Login,
840 "name", string(fileTransfer.ClientConn.UserName),
843 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
848 switch fileTransfer.Type {
850 if _, err := io.Copy(rwc, bytes.NewBuffer(s.banner)); err != nil {
851 return fmt.Errorf("error sending banner: %w", err)
854 s.Stats.DownloadCounter += 1
855 s.Stats.DownloadsInProgress += 1
857 s.Stats.DownloadsInProgress -= 1
861 if fileTransfer.fileResumeData != nil {
862 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
865 fw, err := newFileWrapper(s.FS, fullPath, 0)
870 rLogger.Infow("File download started", "filePath", fullPath)
872 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
873 if fileTransfer.options == nil {
874 _, err = io.Copy(rwc, fw.ffo)
880 file, err := fw.dataForkReader()
885 br := bufio.NewReader(file)
886 if _, err := br.Discard(int(dataOffset)); err != nil {
890 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
894 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
895 if fileTransfer.fileResumeData == nil {
896 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
902 rFile, err := fw.rsrcForkFile()
907 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
912 s.Stats.UploadCounter += 1
913 s.Stats.UploadsInProgress += 1
914 defer func() { s.Stats.UploadsInProgress -= 1 }()
918 // A file upload has three possible cases:
919 // 1) Upload a new file
920 // 2) Resume a partially transferred file
921 // 3) Replace a fully uploaded file
922 // We have to infer which case applies by inspecting what is already on the filesystem
924 // 1) Check for existing file:
925 _, err = os.Stat(fullPath)
927 return errors.New("existing file found at " + fullPath)
929 if errors.Is(err, fs.ErrNotExist) {
930 // If not found, open or create a new .incomplete file
931 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
937 f, err := newFileWrapper(s.FS, fullPath, 0)
942 rLogger.Infow("File upload started", "dstFile", fullPath)
944 rForkWriter := io.Discard
945 iForkWriter := io.Discard
946 if s.Config.PreserveResourceForks {
947 rForkWriter, err = f.rsrcForkWriter()
952 iForkWriter, err = f.infoForkWriter()
958 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
962 if err := file.Close(); err != nil {
966 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
970 rLogger.Infow("File upload complete", "dstFile", fullPath)
973 s.Stats.DownloadCounter += 1
974 s.Stats.DownloadsInProgress += 1
975 defer func() { s.Stats.DownloadsInProgress -= 1 }()
977 // Folder Download flow:
978 // 1. Get filePath from the transfer
979 // 2. Iterate over files
980 // 3. For each fileWrapper:
981 // Send fileWrapper header to client
982 // The client can reply in 3 ways:
984 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
985 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
987 // 2. If download of a fileWrapper is to be resumed:
989 // []byte{0x00, 0x02} // download folder action
990 // [2]byte // Resume data size
991 // []byte fileWrapper resume data (see myField_FileResumeData)
993 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
995 // When download is requested (case 2 or 3), server replies with:
996 // [4]byte - fileWrapper size
997 // []byte - Flattened File Object
999 // After every fileWrapper download, client could request next fileWrapper with:
1000 // []byte{0x00, 0x03}
1002 // This notifies the server to send the next item header
1004 basePathLen := len(fullPath)
1006 rLogger.Infow("Start folder download", "path", fullPath)
1008 nextAction := make([]byte, 2)
1009 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1014 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
1015 s.Stats.DownloadCounter += 1
1023 if strings.HasPrefix(info.Name(), ".") {
1027 hlFile, err := newFileWrapper(s.FS, path, 0)
1032 subPath := path[basePathLen+1:]
1033 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
1039 fileHeader := NewFileHeader(subPath, info.IsDir())
1040 if _, err := io.Copy(rwc, &fileHeader); err != nil {
1041 return fmt.Errorf("error sending file header: %w", err)
1044 // Read the client's Next Action request
1045 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1049 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
1051 var dataOffset int64
1053 switch nextAction[1] {
1054 case dlFldrActionResumeFile:
1055 // get size of resumeData
1056 resumeDataByteLen := make([]byte, 2)
1057 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
1061 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
1062 resumeDataBytes := make([]byte, resumeDataLen)
1063 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1067 var frd FileResumeData
1068 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1071 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1072 case dlFldrActionNextFile:
1073 // client asked to skip this file
1081 rLogger.Infow("File download started",
1082 "fileName", info.Name(),
1083 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1086 // Send file size to client
1087 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1092 // Send ffo bytes to client
1093 _, err = io.Copy(rwc, hlFile.ffo)
1098 file, err := s.FS.Open(path)
1103 // wr := bufio.NewWriterSize(rwc, 1460)
1104 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1108 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1109 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1114 rFile, err := hlFile.rsrcForkFile()
1119 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1124 // Read the client's Next Action request. This is always 3, I think?
1125 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1137 s.Stats.UploadCounter += 1
1138 s.Stats.UploadsInProgress += 1
1139 defer func() { s.Stats.UploadsInProgress -= 1 }()
1141 "Folder upload started",
1142 "dstPath", fullPath,
1143 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1144 "FolderItemCount", fileTransfer.FolderItemCount,
1147 // Check if the target folder exists. If not, create it.
1148 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1149 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1154 // Begin the folder upload flow by sending the "next file action" to client
1155 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1159 fileSize := make([]byte, 4)
1161 for i := 0; i < fileTransfer.ItemCount(); i++ {
1162 s.Stats.UploadCounter += 1
1165 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1168 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1171 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1175 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1177 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1182 "Folder upload continued",
1183 "FormattedPath", fu.FormattedPath(),
1184 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1185 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1188 if fu.IsFolder == [2]byte{0, 1} {
1189 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1190 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1195 // Tell client to send next file
1196 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1200 nextAction := dlFldrActionSendFile
1202 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1203 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1204 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1208 nextAction = dlFldrActionNextFile
1211 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1212 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1213 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1217 nextAction = dlFldrActionResumeFile
1220 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1225 case dlFldrActionNextFile:
1227 case dlFldrActionResumeFile:
1228 offset := make([]byte, 4)
1229 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1231 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1236 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1238 b, _ := fileResumeData.BinaryMarshal()
1240 bs := make([]byte, 2)
1241 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1243 if _, err := rwc.Write(append(bs, b...)); err != nil {
1247 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1251 if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil {
1255 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1260 case dlFldrActionSendFile:
1261 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1265 filePath := filepath.Join(fullPath, fu.FormattedPath())
1267 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1272 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1274 incWriter, err := hlFile.incFileWriter()
1279 rForkWriter := io.Discard
1280 iForkWriter := io.Discard
1281 if s.Config.PreserveResourceForks {
1282 iForkWriter, err = hlFile.infoForkWriter()
1287 rForkWriter, err = hlFile.rsrcForkWriter()
1292 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1296 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1301 // Tell client to send next fileWrapper
1302 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1307 rLogger.Infof("Folder upload complete")