10 "github.com/go-playground/validator/v10"
26 type contextKey string
28 var contextKeyReq = contextKey("req")
30 type requestCtx struct {
36 var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
37 var frogblastVersion = []byte{0, 0, 0, 0xb9} // version ID used by the Frogblast 1.2.4 client
41 Accounts map[string]*Account
43 Clients map[uint16]*ClientConn
44 fileTransfers map[[4]byte]*FileTransfer
48 Logger *zap.SugaredLogger
50 PrivateChatsMu sync.Mutex
51 PrivateChats map[uint32]*PrivateChat
59 FS FileStore // Storage backend to use for File storage
61 outbox chan Transaction
64 threadedNewsMux sync.Mutex
65 ThreadedNews *ThreadedNews
67 flatNewsMux sync.Mutex
71 banList map[string]*time.Time
74 func (s *Server) CurrentStats() Stats {
76 defer s.StatsMu.Unlock()
79 stats.CurrentlyConnected = len(s.Clients)
84 type PrivateChat struct {
86 ClientConn map[uint16]*ClientConn
89 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
90 s.Logger.Infow("Hotline server started",
92 "API port", fmt.Sprintf(":%v", s.Port),
93 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
100 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
105 s.Logger.Fatal(s.Serve(ctx, ln))
110 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
116 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
124 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
126 conn, err := ln.Accept()
132 defer func() { _ = conn.Close() }()
134 err = s.handleFileTransfer(
135 context.WithValue(ctx, contextKeyReq, requestCtx{
136 remoteAddr: conn.RemoteAddr().String(),
142 s.Logger.Errorw("file transfer error", "reason", err)
148 func (s *Server) sendTransaction(t Transaction) error {
149 clientID, err := byteToInt(*t.clientID)
155 client := s.Clients[uint16(clientID)]
157 return fmt.Errorf("invalid client id %v", *t.clientID)
162 b, err := t.MarshalBinary()
167 if _, err := client.Connection.Write(b); err != nil {
174 func (s *Server) processOutbox() {
178 if err := s.sendTransaction(t); err != nil {
179 s.Logger.Errorw("error sending transaction", "err", err)
185 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
189 conn, err := ln.Accept()
191 s.Logger.Errorw("error accepting connection", "err", err)
193 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
194 remoteAddr: conn.RemoteAddr().String(),
198 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
201 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
203 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
205 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
213 agreementFile = "Agreement.txt"
216 // NewServer constructs a new Server from a config dir
217 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
220 Accounts: make(map[string]*Account),
222 Clients: make(map[uint16]*ClientConn),
223 fileTransfers: make(map[[4]byte]*FileTransfer),
224 PrivateChats: make(map[uint32]*PrivateChat),
225 ConfigDir: configDir,
227 NextGuestID: new(uint16),
228 outbox: make(chan Transaction),
229 Stats: &Stats{Since: time.Now()},
230 ThreadedNews: &ThreadedNews{},
232 banList: make(map[string]*time.Time),
237 // generate a new random passID for tracker registration
238 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
242 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
247 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
251 // try to load the ban list, but ignore errors as this file may not be present or may be empty
252 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
254 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
258 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
262 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
266 server.Config.FileRoot = filepath.Join(configDir, "Files")
268 *server.NextGuestID = 1
270 if server.Config.EnableTrackerRegistration {
272 "Tracker registration enabled",
273 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
274 "trackers", server.Config.Trackers,
279 tr := &TrackerRegistration{
280 UserCount: server.userCount(),
281 PassID: server.TrackerPassID[:],
282 Name: server.Config.Name,
283 Description: server.Config.Description,
285 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
286 for _, t := range server.Config.Trackers {
287 if err := register(t, tr); err != nil {
288 server.Logger.Errorw("unable to register with tracker %v", "error", err)
290 server.Logger.Debugw("Sent Tracker registration", "addr", t)
293 time.Sleep(trackerUpdateFrequency * time.Second)
298 // Start Client Keepalive go routine
299 go server.keepaliveHandler()
304 func (s *Server) userCount() int {
308 return len(s.Clients)
311 func (s *Server) keepaliveHandler() {
313 time.Sleep(idleCheckInterval * time.Second)
316 for _, c := range s.Clients {
317 c.IdleTime += idleCheckInterval
318 if c.IdleTime > userIdleSeconds && !c.Idle {
321 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
322 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
323 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
326 tranNotifyChangeUser,
327 NewField(fieldUserID, *c.ID),
328 NewField(fieldUserFlags, c.Flags),
329 NewField(fieldUserName, c.UserName),
330 NewField(fieldUserIconID, c.Icon),
338 func (s *Server) writeBanList() error {
340 defer s.banListMU.Unlock()
342 out, err := yaml.Marshal(s.banList)
346 err = ioutil.WriteFile(
347 filepath.Join(s.ConfigDir, "Banlist.yaml"),
354 func (s *Server) writeThreadedNews() error {
355 s.threadedNewsMux.Lock()
356 defer s.threadedNewsMux.Unlock()
358 out, err := yaml.Marshal(s.ThreadedNews)
362 err = s.FS.WriteFile(
363 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
370 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
374 clientConn := &ClientConn{
383 transfers: map[int]map[[4]byte]*FileTransfer{},
385 RemoteAddr: remoteAddr,
387 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
398 binary.BigEndian.PutUint16(*clientConn.ID, ID)
399 s.Clients[ID] = clientConn
404 // NewUser creates a new user account entry in the server map and config file
405 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
412 Password: hashAndSalt([]byte(password)),
415 out, err := yaml.Marshal(&account)
419 s.Accounts[login] = &account
421 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
424 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
428 // update renames the user login
429 if login != newLogin {
430 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
434 s.Accounts[newLogin] = s.Accounts[login]
435 delete(s.Accounts, login)
438 account := s.Accounts[newLogin]
439 account.Access = access
441 account.Password = password
443 out, err := yaml.Marshal(&account)
448 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
455 // DeleteUser deletes the user account
456 func (s *Server) DeleteUser(login string) error {
460 delete(s.Accounts, login)
462 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
465 func (s *Server) connectedUsers() []Field {
469 var connectedUsers []Field
470 for _, c := range sortedClients(s.Clients) {
478 Name: string(c.UserName),
480 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
482 return connectedUsers
485 func (s *Server) loadBanList(path string) error {
486 fh, err := os.Open(path)
490 decoder := yaml.NewDecoder(fh)
492 return decoder.Decode(s.banList)
495 // loadThreadedNews loads the threaded news data from disk
496 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
497 fh, err := os.Open(threadedNewsPath)
501 decoder := yaml.NewDecoder(fh)
503 return decoder.Decode(s.ThreadedNews)
506 // loadAccounts loads account data from disk
507 func (s *Server) loadAccounts(userDir string) error {
508 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
513 if len(matches) == 0 {
514 return errors.New("no user accounts found in " + userDir)
517 for _, file := range matches {
518 fh, err := s.FS.Open(file)
524 decoder := yaml.NewDecoder(fh)
525 if err := decoder.Decode(&account); err != nil {
529 s.Accounts[account.Login] = &account
534 func (s *Server) loadConfig(path string) error {
535 fh, err := s.FS.Open(path)
540 decoder := yaml.NewDecoder(fh)
541 err = decoder.Decode(s.Config)
546 validate := validator.New()
547 err = validate.Struct(s.Config)
554 // handleNewConnection takes a new net.Conn and performs the initial login sequence
555 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
556 defer dontPanic(s.Logger)
558 if err := Handshake(rwc); err != nil {
562 // Create a new scanner for parsing incoming bytes into transaction tokens
563 scanner := bufio.NewScanner(rwc)
564 scanner.Split(transactionScanner)
568 var clientLogin Transaction
569 if _, err := clientLogin.Write(scanner.Bytes()); err != nil {
573 c := s.NewClientConn(rwc, remoteAddr)
575 // check if remoteAddr is present in the ban list
576 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
579 s.outbox <- *NewTransaction(
582 NewField(fieldData, []byte("You are permanently banned on this server")),
583 NewField(fieldChatOptions, []byte{0, 0}),
585 time.Sleep(1 * time.Second)
587 } else if time.Now().Before(*banUntil) {
588 s.outbox <- *NewTransaction(
591 NewField(fieldData, []byte("You are temporarily banned on this server")),
592 NewField(fieldChatOptions, []byte{0, 0}),
594 time.Sleep(1 * time.Second)
601 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
602 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
603 c.Version = clientLogin.GetField(fieldVersion).Data
606 for _, char := range encodedLogin {
607 login += string(rune(255 - uint(char)))
613 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
615 // If authentication fails, send error reply and close connection
616 if !c.Authenticate(login, encodedPassword) {
617 t := c.NewErrReply(&clientLogin, "Incorrect login.")
618 b, err := t.MarshalBinary()
622 if _, err := rwc.Write(b); err != nil {
626 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
631 if clientLogin.GetField(fieldUserIconID).Data != nil {
632 c.Icon = clientLogin.GetField(fieldUserIconID).Data
635 c.Account = c.Server.Accounts[login]
637 if clientLogin.GetField(fieldUserName).Data != nil {
638 if c.Authorize(accessAnyName) {
639 c.UserName = clientLogin.GetField(fieldUserName).Data
641 c.UserName = []byte(c.Account.Name)
645 if c.Authorize(accessDisconUser) {
646 c.Flags = []byte{0, 2}
649 s.outbox <- c.NewReply(&clientLogin,
650 NewField(fieldVersion, []byte{0x00, 0xbe}),
651 NewField(fieldCommunityBannerID, []byte{0, 0}),
652 NewField(fieldServerName, []byte(s.Config.Name)),
655 // Send user access privs so client UI knows how to behave
656 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:]))
658 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
659 // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send
660 // tranShowAgreement but with the NoServerAgreement field set to 1.
661 if c.Authorize(accessNoAgreement) {
662 // If client version is nil, then the client uses the 1.2.3 login behavior
663 if c.Version != nil {
664 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1}))
667 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
670 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
671 if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) || bytes.Equal(c.Version, frogblastVersion) {
673 c.logger = c.logger.With("name", string(c.UserName))
674 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }()))
676 for _, t := range c.notifyOthers(
678 tranNotifyChangeUser, nil,
679 NewField(fieldUserName, c.UserName),
680 NewField(fieldUserID, *c.ID),
681 NewField(fieldUserIconID, c.Icon),
682 NewField(fieldUserFlags, c.Flags),
689 c.Server.Stats.ConnectionCounter += 1
690 if len(s.Clients) > c.Server.Stats.ConnectionPeak {
691 c.Server.Stats.ConnectionPeak = len(s.Clients)
694 // Scan for new transactions and handle them as they come in.
696 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
697 // scanner re-uses the buffer for subsequent scans.
698 buf := make([]byte, len(scanner.Bytes()))
699 copy(buf, scanner.Bytes())
702 if _, err := t.Write(buf); err != nil {
706 if err := c.handleTransaction(t); err != nil {
707 c.logger.Errorw("Error handling transaction", "err", err)
713 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
714 s.PrivateChatsMu.Lock()
715 defer s.PrivateChatsMu.Unlock()
717 randID := make([]byte, 4)
719 data := binary.BigEndian.Uint32(randID[:])
721 s.PrivateChats[data] = &PrivateChat{
722 ClientConn: make(map[uint16]*ClientConn),
724 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
729 const dlFldrActionSendFile = 1
730 const dlFldrActionResumeFile = 2
731 const dlFldrActionNextFile = 3
733 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
734 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
735 defer dontPanic(s.Logger)
737 txBuf := make([]byte, 16)
738 if _, err := io.ReadFull(rwc, txBuf); err != nil {
743 if _, err := t.Write(txBuf); err != nil {
749 delete(s.fileTransfers, t.ReferenceNumber)
755 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
758 return errors.New("invalid transaction ID")
762 fileTransfer.ClientConn.transfersMU.Lock()
763 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
764 fileTransfer.ClientConn.transfersMU.Unlock()
767 rLogger := s.Logger.With(
768 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
769 "login", fileTransfer.ClientConn.Account.Login,
770 "name", string(fileTransfer.ClientConn.UserName),
773 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
778 switch fileTransfer.Type {
780 if err := s.bannerDownload(rwc); err != nil {
784 s.Stats.DownloadCounter += 1
785 s.Stats.DownloadsInProgress += 1
786 defer func() { s.Stats.DownloadsInProgress -= 1 }()
789 if fileTransfer.fileResumeData != nil {
790 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
793 fw, err := newFileWrapper(s.FS, fullPath, 0)
798 rLogger.Infow("File download started", "filePath", fullPath)
800 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
801 if fileTransfer.options == nil {
802 // Start by sending flat file object to client
803 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
808 file, err := fw.dataForkReader()
813 br := bufio.NewReader(file)
814 if _, err := br.Discard(int(dataOffset)); err != nil {
818 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
822 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
823 if fileTransfer.fileResumeData == nil {
824 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
830 rFile, err := fw.rsrcForkFile()
835 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
840 s.Stats.UploadCounter += 1
841 s.Stats.UploadsInProgress += 1
842 defer func() { s.Stats.UploadsInProgress -= 1 }()
846 // A file upload has three possible cases:
847 // 1) Upload a new file
848 // 2) Resume a partially transferred file
849 // 3) Replace a fully uploaded file
850 // We have to infer which case applies by inspecting what is already on the filesystem
852 // 1) Check for existing file:
853 _, err = os.Stat(fullPath)
855 return errors.New("existing file found at " + fullPath)
857 if errors.Is(err, fs.ErrNotExist) {
858 // If not found, open or create a new .incomplete file
859 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
865 f, err := newFileWrapper(s.FS, fullPath, 0)
870 rLogger.Infow("File upload started", "dstFile", fullPath)
872 rForkWriter := io.Discard
873 iForkWriter := io.Discard
874 if s.Config.PreserveResourceForks {
875 rForkWriter, err = f.rsrcForkWriter()
880 iForkWriter, err = f.infoForkWriter()
886 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
890 if err := file.Close(); err != nil {
894 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
898 rLogger.Infow("File upload complete", "dstFile", fullPath)
901 s.Stats.DownloadCounter += 1
902 s.Stats.DownloadsInProgress += 1
903 defer func() { s.Stats.DownloadsInProgress -= 1 }()
905 // Folder Download flow:
906 // 1. Get filePath from the transfer
907 // 2. Iterate over files
908 // 3. For each fileWrapper:
909 // Send fileWrapper header to client
910 // The client can reply in 3 ways:
912 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
913 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
915 // 2. If download of a fileWrapper is to be resumed:
917 // []byte{0x00, 0x02} // download folder action
918 // [2]byte // Resume data size
919 // []byte fileWrapper resume data (see myField_FileResumeData)
921 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
923 // When download is requested (case 2 or 3), server replies with:
924 // [4]byte - fileWrapper size
925 // []byte - Flattened File Object
927 // After every fileWrapper download, client could request next fileWrapper with:
928 // []byte{0x00, 0x03}
930 // This notifies the server to send the next item header
932 basePathLen := len(fullPath)
934 rLogger.Infow("Start folder download", "path", fullPath)
936 nextAction := make([]byte, 2)
937 if _, err := io.ReadFull(rwc, nextAction); err != nil {
942 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
943 s.Stats.DownloadCounter += 1
951 if strings.HasPrefix(info.Name(), ".") {
955 hlFile, err := newFileWrapper(s.FS, path, 0)
960 subPath := path[basePathLen+1:]
961 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
967 fileHeader := NewFileHeader(subPath, info.IsDir())
969 // Send the fileWrapper header to client
970 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
971 s.Logger.Errorf("error sending file header: %v", err)
975 // Read the client's Next Action request
976 if _, err := io.ReadFull(rwc, nextAction); err != nil {
980 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
984 switch nextAction[1] {
985 case dlFldrActionResumeFile:
986 // get size of resumeData
987 resumeDataByteLen := make([]byte, 2)
988 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
992 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
993 resumeDataBytes := make([]byte, resumeDataLen)
994 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
998 var frd FileResumeData
999 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
1002 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1003 case dlFldrActionNextFile:
1004 // client asked to skip this file
1012 rLogger.Infow("File download started",
1013 "fileName", info.Name(),
1014 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1017 // Send file size to client
1018 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1023 // Send ffo bytes to client
1024 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1029 file, err := s.FS.Open(path)
1034 // wr := bufio.NewWriterSize(rwc, 1460)
1035 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1039 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1040 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1045 rFile, err := hlFile.rsrcForkFile()
1050 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1055 // Read the client's Next Action request. This is always 3, I think?
1056 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1068 s.Stats.UploadCounter += 1
1069 s.Stats.UploadsInProgress += 1
1070 defer func() { s.Stats.UploadsInProgress -= 1 }()
1072 "Folder upload started",
1073 "dstPath", fullPath,
1074 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1075 "FolderItemCount", fileTransfer.FolderItemCount,
1078 // Check if the target folder exists. If not, create it.
1079 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1080 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1085 // Begin the folder upload flow by sending the "next file action" to client
1086 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1090 fileSize := make([]byte, 4)
1092 for i := 0; i < fileTransfer.ItemCount(); i++ {
1093 s.Stats.UploadCounter += 1
1096 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1099 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1102 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1106 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1108 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1113 "Folder upload continued",
1114 "FormattedPath", fu.FormattedPath(),
1115 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1116 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1119 if fu.IsFolder == [2]byte{0, 1} {
1120 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1121 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1126 // Tell client to send next file
1127 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1131 nextAction := dlFldrActionSendFile
1133 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1134 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1135 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1139 nextAction = dlFldrActionNextFile
1142 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1143 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1144 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1148 nextAction = dlFldrActionResumeFile
1151 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1156 case dlFldrActionNextFile:
1158 case dlFldrActionResumeFile:
1159 offset := make([]byte, 4)
1160 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1162 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1167 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1169 b, _ := fileResumeData.BinaryMarshal()
1171 bs := make([]byte, 2)
1172 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1174 if _, err := rwc.Write(append(bs, b...)); err != nil {
1178 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1182 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1186 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1191 case dlFldrActionSendFile:
1192 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1196 filePath := filepath.Join(fullPath, fu.FormattedPath())
1198 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1203 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1205 incWriter, err := hlFile.incFileWriter()
1210 rForkWriter := io.Discard
1211 iForkWriter := io.Discard
1212 if s.Config.PreserveResourceForks {
1213 iForkWriter, err = hlFile.infoForkWriter()
1218 rForkWriter, err = hlFile.rsrcForkWriter()
1223 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1227 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1232 // Tell client to send next fileWrapper
1233 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1238 rLogger.Infof("Folder upload complete")