10 "github.com/go-playground/validator/v10"
11 "golang.org/x/text/encoding/charmap"
28 type contextKey string
30 var contextKeyReq = contextKey("req")
32 type requestCtx struct {
36 // Converts bytes from Mac Roman encoding to UTF-8
37 var txtDecoder = charmap.Macintosh.NewDecoder()
39 // Converts bytes from UTF-8 to Mac Roman encoding
40 var txtEncoder = charmap.Macintosh.NewEncoder()
45 Accounts map[string]*Account
47 Clients map[uint16]*ClientConn
48 fileTransfers map[[4]byte]*FileTransfer
55 PrivateChatsMu sync.Mutex
56 PrivateChats map[uint32]*PrivateChat
64 FS FileStore // Storage backend to use for File storage
66 outbox chan Transaction
69 threadedNewsMux sync.Mutex
70 ThreadedNews *ThreadedNews
72 flatNewsMux sync.Mutex
76 banList map[string]*time.Time
79 func (s *Server) CurrentStats() Stats {
81 defer s.StatsMu.Unlock()
84 stats.CurrentlyConnected = len(s.Clients)
89 type PrivateChat struct {
91 ClientConn map[uint16]*ClientConn
94 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
95 s.Logger.Info("Hotline server started",
97 "API port", fmt.Sprintf("%s:%v", s.NetInterface, s.Port),
98 "Transfer port", fmt.Sprintf("%s:%v", s.NetInterface, s.Port+1),
101 var wg sync.WaitGroup
105 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port))
110 log.Fatal(s.Serve(ctx, ln))
115 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", s.NetInterface, s.Port+1))
120 log.Fatal(s.ServeFileTransfers(ctx, ln))
128 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
130 conn, err := ln.Accept()
136 defer func() { _ = conn.Close() }()
138 err = s.handleFileTransfer(
139 context.WithValue(ctx, contextKeyReq, requestCtx{
140 remoteAddr: conn.RemoteAddr().String(),
146 s.Logger.Error("file transfer error", "reason", err)
152 func (s *Server) sendTransaction(t Transaction) error {
153 clientID, err := byteToInt(*t.clientID)
159 client := s.Clients[uint16(clientID)]
162 return fmt.Errorf("invalid client id %v", *t.clientID)
165 b, err := t.MarshalBinary()
170 _, err = client.Connection.Write(b)
178 func (s *Server) processOutbox() {
182 if err := s.sendTransaction(t); err != nil {
183 s.Logger.Error("error sending transaction", "err", err)
189 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
193 conn, err := ln.Accept()
195 s.Logger.Error("error accepting connection", "err", err)
197 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
198 remoteAddr: conn.RemoteAddr().String(),
202 s.Logger.Info("Connection established", "RemoteAddr", conn.RemoteAddr())
205 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
207 s.Logger.Info("Client disconnected", "RemoteAddr", conn.RemoteAddr())
209 s.Logger.Error("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
217 agreementFile = "Agreement.txt"
220 // NewServer constructs a new Server from a config dir
221 func NewServer(configDir, netInterface string, netPort int, logger *slog.Logger, fs FileStore) (*Server, error) {
223 NetInterface: netInterface,
225 Accounts: make(map[string]*Account),
227 Clients: make(map[uint16]*ClientConn),
228 fileTransfers: make(map[[4]byte]*FileTransfer),
229 PrivateChats: make(map[uint32]*PrivateChat),
230 ConfigDir: configDir,
232 NextGuestID: new(uint16),
233 outbox: make(chan Transaction),
234 Stats: &Stats{Since: time.Now()},
235 ThreadedNews: &ThreadedNews{},
237 banList: make(map[string]*time.Time),
242 // generate a new random passID for tracker registration
243 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
247 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
252 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
256 // try to load the ban list, but ignore errors as this file may not be present or may be empty
257 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
259 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
263 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
267 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
271 // If the FileRoot is an absolute path, use it, otherwise treat as a relative path to the config dir.
272 if !filepath.IsAbs(server.Config.FileRoot) {
273 server.Config.FileRoot = filepath.Join(configDir, server.Config.FileRoot)
276 server.banner, err = os.ReadFile(filepath.Join(server.ConfigDir, server.Config.BannerFile))
278 return nil, fmt.Errorf("error opening banner: %w", err)
281 *server.NextGuestID = 1
283 if server.Config.EnableTrackerRegistration {
285 "Tracker registration enabled",
286 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
287 "trackers", server.Config.Trackers,
292 tr := &TrackerRegistration{
293 UserCount: server.userCount(),
294 PassID: server.TrackerPassID,
295 Name: server.Config.Name,
296 Description: server.Config.Description,
298 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
299 for _, t := range server.Config.Trackers {
300 if err := register(t, tr); err != nil {
301 server.Logger.Error("unable to register with tracker %v", "error", err)
303 server.Logger.Debug("Sent Tracker registration", "addr", t)
306 time.Sleep(trackerUpdateFrequency * time.Second)
311 // Start Client Keepalive go routine
312 go server.keepaliveHandler()
317 func (s *Server) userCount() int {
321 return len(s.Clients)
324 func (s *Server) keepaliveHandler() {
326 time.Sleep(idleCheckInterval * time.Second)
329 for _, c := range s.Clients {
330 c.IdleTime += idleCheckInterval
331 if c.IdleTime > userIdleSeconds && !c.Idle {
334 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
335 flagBitmap.SetBit(flagBitmap, UserFlagAway, 1)
336 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
339 TranNotifyChangeUser,
340 NewField(FieldUserID, *c.ID),
341 NewField(FieldUserFlags, c.Flags),
342 NewField(FieldUserName, c.UserName),
343 NewField(FieldUserIconID, c.Icon),
351 func (s *Server) writeBanList() error {
353 defer s.banListMU.Unlock()
355 out, err := yaml.Marshal(s.banList)
360 filepath.Join(s.ConfigDir, "Banlist.yaml"),
367 func (s *Server) writeThreadedNews() error {
368 s.threadedNewsMux.Lock()
369 defer s.threadedNewsMux.Unlock()
371 out, err := yaml.Marshal(s.ThreadedNews)
375 err = s.FS.WriteFile(
376 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
383 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
387 clientConn := &ClientConn{
396 RemoteAddr: remoteAddr,
397 transfers: map[int]map[[4]byte]*FileTransfer{
409 binary.BigEndian.PutUint16(*clientConn.ID, ID)
410 s.Clients[ID] = clientConn
415 // NewUser creates a new user account entry in the server map and config file
416 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
423 Password: hashAndSalt([]byte(password)),
426 out, err := yaml.Marshal(&account)
431 // Create account file, returning an error if one already exists.
432 file, err := os.OpenFile(
433 filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"),
434 os.O_CREATE|os.O_EXCL|os.O_WRONLY,
442 _, err = file.Write(out)
444 return fmt.Errorf("error writing account file: %w", err)
447 s.Accounts[login] = &account
452 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
456 // update renames the user login
457 if login != newLogin {
458 err := os.Rename(filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"), filepath.Join(s.ConfigDir, "Users", path.Join("/", newLogin)+".yaml"))
460 return fmt.Errorf("unable to rename account: %w", err)
462 s.Accounts[newLogin] = s.Accounts[login]
463 s.Accounts[newLogin].Login = newLogin
464 delete(s.Accounts, login)
467 account := s.Accounts[newLogin]
468 account.Access = access
470 account.Password = password
472 out, err := yaml.Marshal(&account)
477 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
484 // DeleteUser deletes the user account
485 func (s *Server) DeleteUser(login string) error {
489 err := s.FS.Remove(filepath.Join(s.ConfigDir, "Users", path.Join("/", login)+".yaml"))
494 delete(s.Accounts, login)
499 func (s *Server) connectedUsers() []Field {
503 var connectedUsers []Field
504 for _, c := range sortedClients(s.Clients) {
505 b, err := io.ReadAll(&User{
509 Name: string(c.UserName),
514 connectedUsers = append(connectedUsers, NewField(FieldUsernameWithInfo, b))
516 return connectedUsers
519 func (s *Server) loadBanList(path string) error {
520 fh, err := os.Open(path)
524 decoder := yaml.NewDecoder(fh)
526 return decoder.Decode(s.banList)
529 // loadThreadedNews loads the threaded news data from disk
530 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
531 fh, err := os.Open(threadedNewsPath)
535 decoder := yaml.NewDecoder(fh)
537 return decoder.Decode(s.ThreadedNews)
540 // loadAccounts loads account data from disk
541 func (s *Server) loadAccounts(userDir string) error {
542 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
547 if len(matches) == 0 {
548 return errors.New("no user accounts found in " + userDir)
551 for _, file := range matches {
552 fh, err := s.FS.Open(file)
558 decoder := yaml.NewDecoder(fh)
559 if err = decoder.Decode(&account); err != nil {
560 return fmt.Errorf("error loading account %s: %w", file, err)
563 s.Accounts[account.Login] = &account
568 func (s *Server) loadConfig(path string) error {
569 fh, err := s.FS.Open(path)
574 decoder := yaml.NewDecoder(fh)
575 err = decoder.Decode(s.Config)
580 validate := validator.New()
581 err = validate.Struct(s.Config)
588 // handleNewConnection takes a new net.Conn and performs the initial login sequence
589 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
590 defer dontPanic(s.Logger)
592 if err := Handshake(rwc); err != nil {
596 // Create a new scanner for parsing incoming bytes into transaction tokens
597 scanner := bufio.NewScanner(rwc)
598 scanner.Split(transactionScanner)
602 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
603 // scanner re-uses the buffer for subsequent scans.
604 buf := make([]byte, len(scanner.Bytes()))
605 copy(buf, scanner.Bytes())
607 var clientLogin Transaction
608 if _, err := clientLogin.Write(buf); err != nil {
612 // check if remoteAddr is present in the ban list
613 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
619 NewField(FieldData, []byte("You are permanently banned on this server")),
620 NewField(FieldChatOptions, []byte{0, 0}),
623 b, err := t.MarshalBinary()
628 _, err = rwc.Write(b)
633 time.Sleep(1 * time.Second)
638 if time.Now().Before(*banUntil) {
642 NewField(FieldData, []byte("You are temporarily banned on this server")),
643 NewField(FieldChatOptions, []byte{0, 0}),
645 b, err := t.MarshalBinary()
650 _, err = rwc.Write(b)
655 time.Sleep(1 * time.Second)
660 c := s.NewClientConn(rwc, remoteAddr)
663 encodedLogin := clientLogin.GetField(FieldUserLogin).Data
664 encodedPassword := clientLogin.GetField(FieldUserPassword).Data
665 c.Version = clientLogin.GetField(FieldVersion).Data
668 for _, char := range encodedLogin {
669 login += string(rune(255 - uint(char)))
675 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
677 // If authentication fails, send error reply and close connection
678 if !c.Authenticate(login, encodedPassword) {
679 t := c.NewErrReply(&clientLogin, "Incorrect login.")
680 b, err := t.MarshalBinary()
684 if _, err := rwc.Write(b); err != nil {
688 c.logger.Info("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
693 if clientLogin.GetField(FieldUserIconID).Data != nil {
694 c.Icon = clientLogin.GetField(FieldUserIconID).Data
697 c.Account = c.Server.Accounts[login]
699 if clientLogin.GetField(FieldUserName).Data != nil {
700 if c.Authorize(accessAnyName) {
701 c.UserName = clientLogin.GetField(FieldUserName).Data
703 c.UserName = []byte(c.Account.Name)
707 if c.Authorize(accessDisconUser) {
708 c.Flags = []byte{0, 2}
711 s.outbox <- c.NewReply(&clientLogin,
712 NewField(FieldVersion, []byte{0x00, 0xbe}),
713 NewField(FieldCommunityBannerID, []byte{0, 0}),
714 NewField(FieldServerName, []byte(s.Config.Name)),
717 // Send user access privs so client UI knows how to behave
718 c.Server.outbox <- *NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, c.Account.Access[:]))
720 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
721 // client versions. For 1.2.3 client, we do not send TranShowAgreement. For other client versions, we send
722 // TranShowAgreement but with the NoServerAgreement field set to 1.
723 if c.Authorize(accessNoAgreement) {
724 // If client version is nil, then the client uses the 1.2.3 login behavior
725 if c.Version != nil {
726 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldNoServerAgreement, []byte{1}))
729 c.Server.outbox <- *NewTransaction(TranShowAgreement, c.ID, NewField(FieldData, s.Agreement))
732 // If the client has provided a username as part of the login, we can infer that it is using the 1.2.3 login
733 // flow and not the 1.5+ flow.
734 if len(c.UserName) != 0 {
735 // Add the client username to the logger. For 1.5+ clients, we don't have this information yet as it comes as
736 // part of TranAgreed
737 c.logger = c.logger.With("name", string(c.UserName))
739 c.logger.Info("Login successful", "clientVersion", "Not sent (probably 1.2.3)")
741 // Notify other clients on the server that the new user has logged in. For 1.5+ clients we don't have this
742 // information yet, so we do it in TranAgreed instead
743 for _, t := range c.notifyOthers(
745 TranNotifyChangeUser, nil,
746 NewField(FieldUserName, c.UserName),
747 NewField(FieldUserID, *c.ID),
748 NewField(FieldUserIconID, c.Icon),
749 NewField(FieldUserFlags, c.Flags),
756 c.Server.Stats.ConnectionCounter += 1
757 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
758 c.Server.Stats.ConnectionPeak = len(s.Clients)
761 // Scan for new transactions and handle them as they come in.
763 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
764 // scanner re-uses the buffer for subsequent scans.
765 buf := make([]byte, len(scanner.Bytes()))
766 copy(buf, scanner.Bytes())
769 if _, err := t.Write(buf); err != nil {
773 if err := c.handleTransaction(t); err != nil {
774 c.logger.Error("Error handling transaction", "err", err)
780 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
781 s.PrivateChatsMu.Lock()
782 defer s.PrivateChatsMu.Unlock()
784 randID := make([]byte, 4)
786 data := binary.BigEndian.Uint32(randID)
788 s.PrivateChats[data] = &PrivateChat{
789 ClientConn: make(map[uint16]*ClientConn),
791 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
796 const dlFldrActionSendFile = 1
797 const dlFldrActionResumeFile = 2
798 const dlFldrActionNextFile = 3
800 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
801 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
802 defer dontPanic(s.Logger)
804 txBuf := make([]byte, 16)
805 if _, err := io.ReadFull(rwc, txBuf); err != nil {
810 if _, err := t.Write(txBuf); err != nil {
816 delete(s.fileTransfers, t.ReferenceNumber)
819 // Wait a few seconds before closing the connection: this is a workaround for problems
820 // observed with Windows clients where the client must initiate close of the TCP connection before
821 // the server does. This is gross and seems unnecessary. TODO: Revisit?
822 time.Sleep(3 * time.Second)
826 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
829 return errors.New("invalid transaction ID")
833 fileTransfer.ClientConn.transfersMU.Lock()
834 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
835 fileTransfer.ClientConn.transfersMU.Unlock()
838 rLogger := s.Logger.With(
839 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
840 "login", fileTransfer.ClientConn.Account.Login,
841 "name", string(fileTransfer.ClientConn.UserName),
844 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
849 switch fileTransfer.Type {
851 if _, err := io.Copy(rwc, bytes.NewBuffer(s.banner)); err != nil {
852 return fmt.Errorf("error sending banner: %w", err)
855 s.Stats.DownloadCounter += 1
856 s.Stats.DownloadsInProgress += 1
858 s.Stats.DownloadsInProgress -= 1
862 if fileTransfer.fileResumeData != nil {
863 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
866 fw, err := newFileWrapper(s.FS, fullPath, 0)
871 rLogger.Info("File download started", "filePath", fullPath)
873 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
874 if fileTransfer.options == nil {
875 _, err = io.Copy(rwc, fw.ffo)
881 file, err := fw.dataForkReader()
886 br := bufio.NewReader(file)
887 if _, err := br.Discard(int(dataOffset)); err != nil {
891 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
895 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
896 if fileTransfer.fileResumeData == nil {
897 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
903 rFile, err := fw.rsrcForkFile()
908 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
913 s.Stats.UploadCounter += 1
914 s.Stats.UploadsInProgress += 1
915 defer func() { s.Stats.UploadsInProgress -= 1 }()
919 // A file upload has three possible cases:
920 // 1) Upload a new file
921 // 2) Resume a partially transferred file
922 // 3) Replace a fully uploaded file
923 // We have to infer which case applies by inspecting what is already on the filesystem
925 // 1) Check for existing file:
926 _, err = os.Stat(fullPath)
928 return errors.New("existing file found at " + fullPath)
930 if errors.Is(err, fs.ErrNotExist) {
931 // If not found, open or create a new .incomplete file
932 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
938 f, err := newFileWrapper(s.FS, fullPath, 0)
943 rLogger.Info("File upload started", "dstFile", fullPath)
945 rForkWriter := io.Discard
946 iForkWriter := io.Discard
947 if s.Config.PreserveResourceForks {
948 rForkWriter, err = f.rsrcForkWriter()
953 iForkWriter, err = f.infoForkWriter()
959 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
960 s.Logger.Error(err.Error())
963 if err := file.Close(); err != nil {
967 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
971 rLogger.Info("File upload complete", "dstFile", fullPath)
974 s.Stats.DownloadCounter += 1
975 s.Stats.DownloadsInProgress += 1
976 defer func() { s.Stats.DownloadsInProgress -= 1 }()
978 // Folder Download flow:
979 // 1. Get filePath from the transfer
980 // 2. Iterate over files
981 // 3. For each fileWrapper:
982 // Send fileWrapper header to client
983 // The client can reply in 3 ways:
985 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
986 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
988 // 2. If download of a fileWrapper is to be resumed:
990 // []byte{0x00, 0x02} // download folder action
991 // [2]byte // Resume data size
992 // []byte fileWrapper resume data (see myField_FileResumeData)
994 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
996 // When download is requested (case 2 or 3), server replies with:
997 // [4]byte - fileWrapper size
998 // []byte - Flattened File Object
1000 // After every fileWrapper download, client could request next fileWrapper with:
1001 // []byte{0x00, 0x03}
1003 // This notifies the server to send the next item header
1005 basePathLen := len(fullPath)
1007 rLogger.Info("Start folder download", "path", fullPath)
1009 nextAction := make([]byte, 2)
1010 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1015 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
1016 s.Stats.DownloadCounter += 1
1024 if strings.HasPrefix(info.Name(), ".") {
1028 hlFile, err := newFileWrapper(s.FS, path, 0)
1033 subPath := path[basePathLen+1:]
1034 rLogger.Debug("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
1040 fileHeader := NewFileHeader(subPath, info.IsDir())
1041 if _, err := io.Copy(rwc, &fileHeader); err != nil {
1042 return fmt.Errorf("error sending file header: %w", err)
1045 // Read the client's Next Action request
1046 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1050 rLogger.Debug("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
1052 var dataOffset int64
1054 switch nextAction[1] {
1055 case dlFldrActionResumeFile:
1056 // get size of resumeData
1057 resumeDataByteLen := make([]byte, 2)
1058 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
1062 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
1063 resumeDataBytes := make([]byte, resumeDataLen)
1064 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1068 var frd FileResumeData
1069 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1072 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1073 case dlFldrActionNextFile:
1074 // client asked to skip this file
1082 rLogger.Info("File download started",
1083 "fileName", info.Name(),
1084 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1087 // Send file size to client
1088 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1089 s.Logger.Error(err.Error())
1093 // Send ffo bytes to client
1094 _, err = io.Copy(rwc, hlFile.ffo)
1099 file, err := s.FS.Open(path)
1104 // wr := bufio.NewWriterSize(rwc, 1460)
1105 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1109 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1110 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1115 rFile, err := hlFile.rsrcForkFile()
1120 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1125 // Read the client's Next Action request. This is always 3, I think?
1126 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1138 s.Stats.UploadCounter += 1
1139 s.Stats.UploadsInProgress += 1
1140 defer func() { s.Stats.UploadsInProgress -= 1 }()
1142 "Folder upload started",
1143 "dstPath", fullPath,
1144 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1145 "FolderItemCount", fileTransfer.FolderItemCount,
1148 // Check if the target folder exists. If not, create it.
1149 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1150 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1155 // Begin the folder upload flow by sending the "next file action" to client
1156 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1160 fileSize := make([]byte, 4)
1162 for i := 0; i < fileTransfer.ItemCount(); i++ {
1163 s.Stats.UploadCounter += 1
1166 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1169 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1172 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1176 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1178 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1183 "Folder upload continued",
1184 "FormattedPath", fu.FormattedPath(),
1185 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1186 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1189 if fu.IsFolder == [2]byte{0, 1} {
1190 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1191 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1196 // Tell client to send next file
1197 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1201 nextAction := dlFldrActionSendFile
1203 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1204 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1205 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1209 nextAction = dlFldrActionNextFile
1212 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1213 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1214 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1218 nextAction = dlFldrActionResumeFile
1221 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1226 case dlFldrActionNextFile:
1228 case dlFldrActionResumeFile:
1229 offset := make([]byte, 4)
1230 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1232 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1237 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1239 b, _ := fileResumeData.BinaryMarshal()
1241 bs := make([]byte, 2)
1242 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1244 if _, err := rwc.Write(append(bs, b...)); err != nil {
1248 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1252 if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil {
1253 s.Logger.Error(err.Error())
1256 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1261 case dlFldrActionSendFile:
1262 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1266 filePath := filepath.Join(fullPath, fu.FormattedPath())
1268 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1273 rLogger.Info("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1275 incWriter, err := hlFile.incFileWriter()
1280 rForkWriter := io.Discard
1281 iForkWriter := io.Discard
1282 if s.Config.PreserveResourceForks {
1283 iForkWriter, err = hlFile.infoForkWriter()
1288 rForkWriter, err = hlFile.rsrcForkWriter()
1293 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1297 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1302 // Tell client to send next fileWrapper
1303 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1308 rLogger.Info("Folder upload complete")