10 "github.com/go-playground/validator/v10"
26 type contextKey string
28 var contextKeyReq = contextKey("req")
30 type requestCtx struct {
36 var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
37 var frogblastVersion = []byte{0, 0, 0, 0xb9} // version ID used by the Frogblast 1.2.4 client
39 var heildrun = []byte{0, 0x97}
41 var obsessionVersion = []byte{0xbe, 0x00} // version ID used by the Obsession client
45 Accounts map[string]*Account
47 Clients map[uint16]*ClientConn
48 fileTransfers map[[4]byte]*FileTransfer
52 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(":%v", s.Port),
97 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
100 var wg sync.WaitGroup
104 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
109 s.Logger.Fatal(s.Serve(ctx, ln))
114 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
120 s.Logger.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.Errorw("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.Errorw("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.Errorw("error accepting connection", "err", err)
197 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
198 remoteAddr: conn.RemoteAddr().String(),
202 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
205 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
207 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
209 s.Logger.Errorw("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 string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
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 server.Config.FileRoot = filepath.Join(configDir, "Files")
272 *server.NextGuestID = 1
274 if server.Config.EnableTrackerRegistration {
276 "Tracker registration enabled",
277 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
278 "trackers", server.Config.Trackers,
283 tr := &TrackerRegistration{
284 UserCount: server.userCount(),
285 PassID: server.TrackerPassID[:],
286 Name: server.Config.Name,
287 Description: server.Config.Description,
289 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
290 for _, t := range server.Config.Trackers {
291 if err := register(t, tr); err != nil {
292 server.Logger.Errorw("unable to register with tracker %v", "error", err)
294 server.Logger.Debugw("Sent Tracker registration", "addr", t)
297 time.Sleep(trackerUpdateFrequency * time.Second)
302 // Start Client Keepalive go routine
303 go server.keepaliveHandler()
308 func (s *Server) userCount() int {
312 return len(s.Clients)
315 func (s *Server) keepaliveHandler() {
317 time.Sleep(idleCheckInterval * time.Second)
320 for _, c := range s.Clients {
321 c.IdleTime += idleCheckInterval
322 if c.IdleTime > userIdleSeconds && !c.Idle {
325 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
326 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
327 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
330 tranNotifyChangeUser,
331 NewField(fieldUserID, *c.ID),
332 NewField(fieldUserFlags, c.Flags),
333 NewField(fieldUserName, c.UserName),
334 NewField(fieldUserIconID, c.Icon),
342 func (s *Server) writeBanList() error {
344 defer s.banListMU.Unlock()
346 out, err := yaml.Marshal(s.banList)
350 err = ioutil.WriteFile(
351 filepath.Join(s.ConfigDir, "Banlist.yaml"),
358 func (s *Server) writeThreadedNews() error {
359 s.threadedNewsMux.Lock()
360 defer s.threadedNewsMux.Unlock()
362 out, err := yaml.Marshal(s.ThreadedNews)
366 err = s.FS.WriteFile(
367 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
374 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
378 clientConn := &ClientConn{
387 transfers: map[int]map[[4]byte]*FileTransfer{},
389 RemoteAddr: remoteAddr,
391 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
402 binary.BigEndian.PutUint16(*clientConn.ID, ID)
403 s.Clients[ID] = clientConn
408 // NewUser creates a new user account entry in the server map and config file
409 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
416 Password: hashAndSalt([]byte(password)),
419 out, err := yaml.Marshal(&account)
423 s.Accounts[login] = &account
425 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
428 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
432 // update renames the user login
433 if login != newLogin {
434 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
438 s.Accounts[newLogin] = s.Accounts[login]
439 delete(s.Accounts, login)
442 account := s.Accounts[newLogin]
443 account.Access = access
445 account.Password = password
447 out, err := yaml.Marshal(&account)
452 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
459 // DeleteUser deletes the user account
460 func (s *Server) DeleteUser(login string) error {
464 delete(s.Accounts, login)
466 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
469 func (s *Server) connectedUsers() []Field {
473 var connectedUsers []Field
474 for _, c := range sortedClients(s.Clients) {
482 Name: string(c.UserName),
484 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
486 return connectedUsers
489 func (s *Server) loadBanList(path string) error {
490 fh, err := os.Open(path)
494 decoder := yaml.NewDecoder(fh)
496 return decoder.Decode(s.banList)
499 // loadThreadedNews loads the threaded news data from disk
500 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
501 fh, err := os.Open(threadedNewsPath)
505 decoder := yaml.NewDecoder(fh)
507 return decoder.Decode(s.ThreadedNews)
510 // loadAccounts loads account data from disk
511 func (s *Server) loadAccounts(userDir string) error {
512 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
517 if len(matches) == 0 {
518 return errors.New("no user accounts found in " + userDir)
521 for _, file := range matches {
522 fh, err := s.FS.Open(file)
528 decoder := yaml.NewDecoder(fh)
529 if err := decoder.Decode(&account); err != nil {
533 s.Accounts[account.Login] = &account
538 func (s *Server) loadConfig(path string) error {
539 fh, err := s.FS.Open(path)
544 decoder := yaml.NewDecoder(fh)
545 err = decoder.Decode(s.Config)
550 validate := validator.New()
551 err = validate.Struct(s.Config)
558 // handleNewConnection takes a new net.Conn and performs the initial login sequence
559 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
560 defer dontPanic(s.Logger)
562 if err := Handshake(rwc); err != nil {
566 // Create a new scanner for parsing incoming bytes into transaction tokens
567 scanner := bufio.NewScanner(rwc)
568 scanner.Split(transactionScanner)
572 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
573 // scanner re-uses the buffer for subsequent scans.
574 buf := make([]byte, len(scanner.Bytes()))
575 copy(buf, scanner.Bytes())
577 var clientLogin Transaction
578 if _, err := clientLogin.Write(buf); err != nil {
582 c := s.NewClientConn(rwc, remoteAddr)
584 // check if remoteAddr is present in the ban list
585 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
588 s.outbox <- *NewTransaction(
591 NewField(fieldData, []byte("You are permanently banned on this server")),
592 NewField(fieldChatOptions, []byte{0, 0}),
594 time.Sleep(1 * time.Second)
596 } else if time.Now().Before(*banUntil) {
597 s.outbox <- *NewTransaction(
600 NewField(fieldData, []byte("You are temporarily banned on this server")),
601 NewField(fieldChatOptions, []byte{0, 0}),
603 time.Sleep(1 * time.Second)
610 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
611 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
612 c.Version = clientLogin.GetField(fieldVersion).Data
615 for _, char := range encodedLogin {
616 login += string(rune(255 - uint(char)))
622 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
624 // If authentication fails, send error reply and close connection
625 if !c.Authenticate(login, encodedPassword) {
626 t := c.NewErrReply(&clientLogin, "Incorrect login.")
627 b, err := t.MarshalBinary()
631 if _, err := rwc.Write(b); err != nil {
635 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
640 if clientLogin.GetField(fieldUserIconID).Data != nil {
641 c.Icon = clientLogin.GetField(fieldUserIconID).Data
644 c.Account = c.Server.Accounts[login]
646 if clientLogin.GetField(fieldUserName).Data != nil {
647 if c.Authorize(accessAnyName) {
648 c.UserName = clientLogin.GetField(fieldUserName).Data
650 c.UserName = []byte(c.Account.Name)
654 if c.Authorize(accessDisconUser) {
655 c.Flags = []byte{0, 2}
658 s.outbox <- c.NewReply(&clientLogin,
659 NewField(fieldVersion, []byte{0x00, 0xbe}),
660 NewField(fieldCommunityBannerID, []byte{0, 0}),
661 NewField(fieldServerName, []byte(s.Config.Name)),
664 // Send user access privs so client UI knows how to behave
665 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:]))
667 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
668 // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send
669 // tranShowAgreement but with the NoServerAgreement field set to 1.
670 if c.Authorize(accessNoAgreement) {
671 // If client version is nil, then the client uses the 1.2.3 login behavior
672 if c.Version != nil {
673 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1}))
676 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
679 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
680 // TODO: figure out a generalized solution that doesn't require playing whack-a-mole for specific client versions
681 if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) || bytes.Equal(c.Version, frogblastVersion) || bytes.Equal(c.Version, obsessionVersion) || bytes.Equal(c.Version, heildrun) {
683 c.logger = c.logger.With("name", string(c.UserName))
684 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }()))
686 for _, t := range c.notifyOthers(
688 tranNotifyChangeUser, nil,
689 NewField(fieldUserName, c.UserName),
690 NewField(fieldUserID, *c.ID),
691 NewField(fieldUserIconID, c.Icon),
692 NewField(fieldUserFlags, c.Flags),
699 c.Server.Stats.ConnectionCounter += 1
700 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
701 c.Server.Stats.ConnectionPeak = len(s.Clients)
704 // Scan for new transactions and handle them as they come in.
706 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
707 // scanner re-uses the buffer for subsequent scans.
708 buf := make([]byte, len(scanner.Bytes()))
709 copy(buf, scanner.Bytes())
712 if _, err := t.Write(buf); err != nil {
716 if err := c.handleTransaction(t); err != nil {
717 c.logger.Errorw("Error handling transaction", "err", err)
723 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
724 s.PrivateChatsMu.Lock()
725 defer s.PrivateChatsMu.Unlock()
727 randID := make([]byte, 4)
729 data := binary.BigEndian.Uint32(randID[:])
731 s.PrivateChats[data] = &PrivateChat{
732 ClientConn: make(map[uint16]*ClientConn),
734 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
739 const dlFldrActionSendFile = 1
740 const dlFldrActionResumeFile = 2
741 const dlFldrActionNextFile = 3
743 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
744 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
745 defer dontPanic(s.Logger)
747 txBuf := make([]byte, 16)
748 if _, err := io.ReadFull(rwc, txBuf); err != nil {
753 if _, err := t.Write(txBuf); err != nil {
759 delete(s.fileTransfers, t.ReferenceNumber)
762 // Wait a few seconds before closing the connection: this is a workaround for problems
763 // observed with Windows clients where the client must initiate close of the TCP connection before
764 // the server does. This is gross and seems unnecessary. TODO: Revisit?
765 time.Sleep(3 * time.Second)
769 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
772 return errors.New("invalid transaction ID")
776 fileTransfer.ClientConn.transfersMU.Lock()
777 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
778 fileTransfer.ClientConn.transfersMU.Unlock()
781 rLogger := s.Logger.With(
782 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
783 "login", fileTransfer.ClientConn.Account.Login,
784 "name", string(fileTransfer.ClientConn.UserName),
787 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
792 switch fileTransfer.Type {
794 if err := s.bannerDownload(rwc); err != nil {
798 s.Stats.DownloadCounter += 1
799 s.Stats.DownloadsInProgress += 1
801 s.Stats.DownloadsInProgress -= 1
805 if fileTransfer.fileResumeData != nil {
806 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
809 fw, err := newFileWrapper(s.FS, fullPath, 0)
814 rLogger.Infow("File download started", "filePath", fullPath)
816 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
817 if fileTransfer.options == nil {
818 // Start by sending flat file object to client
819 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
824 file, err := fw.dataForkReader()
829 br := bufio.NewReader(file)
830 if _, err := br.Discard(int(dataOffset)); err != nil {
834 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
838 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
839 if fileTransfer.fileResumeData == nil {
840 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
846 rFile, err := fw.rsrcForkFile()
851 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
856 s.Stats.UploadCounter += 1
857 s.Stats.UploadsInProgress += 1
858 defer func() { s.Stats.UploadsInProgress -= 1 }()
862 // A file upload has three possible cases:
863 // 1) Upload a new file
864 // 2) Resume a partially transferred file
865 // 3) Replace a fully uploaded file
866 // We have to infer which case applies by inspecting what is already on the filesystem
868 // 1) Check for existing file:
869 _, err = os.Stat(fullPath)
871 return errors.New("existing file found at " + fullPath)
873 if errors.Is(err, fs.ErrNotExist) {
874 // If not found, open or create a new .incomplete file
875 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
881 f, err := newFileWrapper(s.FS, fullPath, 0)
886 rLogger.Infow("File upload started", "dstFile", fullPath)
888 rForkWriter := io.Discard
889 iForkWriter := io.Discard
890 if s.Config.PreserveResourceForks {
891 rForkWriter, err = f.rsrcForkWriter()
896 iForkWriter, err = f.infoForkWriter()
902 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
906 if err := file.Close(); err != nil {
910 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
914 rLogger.Infow("File upload complete", "dstFile", fullPath)
917 s.Stats.DownloadCounter += 1
918 s.Stats.DownloadsInProgress += 1
919 defer func() { s.Stats.DownloadsInProgress -= 1 }()
921 // Folder Download flow:
922 // 1. Get filePath from the transfer
923 // 2. Iterate over files
924 // 3. For each fileWrapper:
925 // Send fileWrapper header to client
926 // The client can reply in 3 ways:
928 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
929 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
931 // 2. If download of a fileWrapper is to be resumed:
933 // []byte{0x00, 0x02} // download folder action
934 // [2]byte // Resume data size
935 // []byte fileWrapper resume data (see myField_FileResumeData)
937 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
939 // When download is requested (case 2 or 3), server replies with:
940 // [4]byte - fileWrapper size
941 // []byte - Flattened File Object
943 // After every fileWrapper download, client could request next fileWrapper with:
944 // []byte{0x00, 0x03}
946 // This notifies the server to send the next item header
948 basePathLen := len(fullPath)
950 rLogger.Infow("Start folder download", "path", fullPath)
952 nextAction := make([]byte, 2)
953 if _, err := io.ReadFull(rwc, nextAction); err != nil {
958 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
959 s.Stats.DownloadCounter += 1
967 if strings.HasPrefix(info.Name(), ".") {
971 hlFile, err := newFileWrapper(s.FS, path, 0)
976 subPath := path[basePathLen+1:]
977 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
983 fileHeader := NewFileHeader(subPath, info.IsDir())
985 // Send the fileWrapper header to client
986 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
987 s.Logger.Errorf("error sending file header: %v", err)
991 // Read the client's Next Action request
992 if _, err := io.ReadFull(rwc, nextAction); err != nil {
996 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
1000 switch nextAction[1] {
1001 case dlFldrActionResumeFile:
1002 // get size of resumeData
1003 resumeDataByteLen := make([]byte, 2)
1004 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
1008 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
1009 resumeDataBytes := make([]byte, resumeDataLen)
1010 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
1014 var frd FileResumeData
1015 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1018 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1019 case dlFldrActionNextFile:
1020 // client asked to skip this file
1028 rLogger.Infow("File download started",
1029 "fileName", info.Name(),
1030 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1033 // Send file size to client
1034 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1039 // Send ffo bytes to client
1040 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1045 file, err := s.FS.Open(path)
1050 // wr := bufio.NewWriterSize(rwc, 1460)
1051 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1055 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1056 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1061 rFile, err := hlFile.rsrcForkFile()
1066 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1071 // Read the client's Next Action request. This is always 3, I think?
1072 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1084 s.Stats.UploadCounter += 1
1085 s.Stats.UploadsInProgress += 1
1086 defer func() { s.Stats.UploadsInProgress -= 1 }()
1088 "Folder upload started",
1089 "dstPath", fullPath,
1090 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1091 "FolderItemCount", fileTransfer.FolderItemCount,
1094 // Check if the target folder exists. If not, create it.
1095 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1096 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1101 // Begin the folder upload flow by sending the "next file action" to client
1102 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1106 fileSize := make([]byte, 4)
1108 for i := 0; i < fileTransfer.ItemCount(); i++ {
1109 s.Stats.UploadCounter += 1
1112 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1115 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1118 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1122 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1124 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1129 "Folder upload continued",
1130 "FormattedPath", fu.FormattedPath(),
1131 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1132 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1135 if fu.IsFolder == [2]byte{0, 1} {
1136 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1137 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1142 // Tell client to send next file
1143 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1147 nextAction := dlFldrActionSendFile
1149 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1150 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1151 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1155 nextAction = dlFldrActionNextFile
1158 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1159 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1160 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1164 nextAction = dlFldrActionResumeFile
1167 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1172 case dlFldrActionNextFile:
1174 case dlFldrActionResumeFile:
1175 offset := make([]byte, 4)
1176 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1178 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1183 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1185 b, _ := fileResumeData.BinaryMarshal()
1187 bs := make([]byte, 2)
1188 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1190 if _, err := rwc.Write(append(bs, b...)); err != nil {
1194 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1198 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1202 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1207 case dlFldrActionSendFile:
1208 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1212 filePath := filepath.Join(fullPath, fu.FormattedPath())
1214 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1219 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1221 incWriter, err := hlFile.incFileWriter()
1226 rForkWriter := io.Discard
1227 iForkWriter := io.Discard
1228 if s.Config.PreserveResourceForks {
1229 iForkWriter, err = hlFile.infoForkWriter()
1234 rForkWriter, err = hlFile.rsrcForkWriter()
1239 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1243 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1248 // Tell client to send next fileWrapper
1249 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1254 rLogger.Infof("Folder upload complete")