10 "github.com/go-playground/validator/v10"
27 type contextKey string
29 var contextKeyReq = contextKey("req")
31 type requestCtx struct {
38 userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
39 idleCheckInterval = 10 // time in seconds to check for idle users
40 trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
43 var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
47 Accounts map[string]*Account
49 Clients map[uint16]*ClientConn
50 fileTransfers map[[4]byte]*FileTransfer
54 Logger *zap.SugaredLogger
55 PrivateChats map[uint32]*PrivateChat
60 FS FileStore // Storage backend to use for File storage
62 outbox chan Transaction
65 threadedNewsMux sync.Mutex
66 ThreadedNews *ThreadedNews
68 flatNewsMux sync.Mutex
72 banList map[string]*time.Time
75 type PrivateChat struct {
77 ClientConn map[uint16]*ClientConn
80 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
81 s.Logger.Infow("Hotline server started",
83 "API port", fmt.Sprintf(":%v", s.Port),
84 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
91 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
96 s.Logger.Fatal(s.Serve(ctx, ln))
101 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
107 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
115 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
117 conn, err := ln.Accept()
123 defer func() { _ = conn.Close() }()
125 err = s.handleFileTransfer(
126 context.WithValue(ctx, contextKeyReq, requestCtx{
127 remoteAddr: conn.RemoteAddr().String(),
133 s.Logger.Errorw("file transfer error", "reason", err)
139 func (s *Server) sendTransaction(t Transaction) error {
140 clientID, err := byteToInt(*t.clientID)
146 client := s.Clients[uint16(clientID)]
148 return fmt.Errorf("invalid client id %v", *t.clientID)
153 b, err := t.MarshalBinary()
158 if _, err := client.Connection.Write(b); err != nil {
165 func (s *Server) processOutbox() {
169 if err := s.sendTransaction(t); err != nil {
170 s.Logger.Errorw("error sending transaction", "err", err)
176 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
180 conn, err := ln.Accept()
182 s.Logger.Errorw("error accepting connection", "err", err)
184 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
185 remoteAddr: conn.RemoteAddr().String(),
189 s.Logger.Infow("Connection established", "RemoteAddr", conn.RemoteAddr())
192 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
194 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
196 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
204 agreementFile = "Agreement.txt"
207 // NewServer constructs a new Server from a config dir
208 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
211 Accounts: make(map[string]*Account),
213 Clients: make(map[uint16]*ClientConn),
214 fileTransfers: make(map[[4]byte]*FileTransfer),
215 PrivateChats: make(map[uint32]*PrivateChat),
216 ConfigDir: configDir,
218 NextGuestID: new(uint16),
219 outbox: make(chan Transaction),
220 Stats: &Stats{StartTime: time.Now()},
221 ThreadedNews: &ThreadedNews{},
223 banList: make(map[string]*time.Time),
228 // generate a new random passID for tracker registration
229 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
233 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
238 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
242 // try to load the ban list, but ignore errors as this file may not be present or may be empty
243 _ = server.loadBanList(filepath.Join(configDir, "Banlist.yaml"))
245 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
249 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
253 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
257 server.Config.FileRoot = filepath.Join(configDir, "Files")
259 *server.NextGuestID = 1
261 if server.Config.EnableTrackerRegistration {
263 "Tracker registration enabled",
264 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
265 "trackers", server.Config.Trackers,
270 tr := &TrackerRegistration{
271 UserCount: server.userCount(),
272 PassID: server.TrackerPassID[:],
273 Name: server.Config.Name,
274 Description: server.Config.Description,
276 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
277 for _, t := range server.Config.Trackers {
278 if err := register(t, tr); err != nil {
279 server.Logger.Errorw("unable to register with tracker %v", "error", err)
281 server.Logger.Infow("Sent Tracker registration", "data", tr)
284 time.Sleep(trackerUpdateFrequency * time.Second)
289 // Start Client Keepalive go routine
290 go server.keepaliveHandler()
295 func (s *Server) userCount() int {
299 return len(s.Clients)
302 func (s *Server) keepaliveHandler() {
304 time.Sleep(idleCheckInterval * time.Second)
307 for _, c := range s.Clients {
308 c.IdleTime += idleCheckInterval
309 if c.IdleTime > userIdleSeconds && !c.Idle {
312 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
313 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
314 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
317 tranNotifyChangeUser,
318 NewField(fieldUserID, *c.ID),
319 NewField(fieldUserFlags, c.Flags),
320 NewField(fieldUserName, c.UserName),
321 NewField(fieldUserIconID, c.Icon),
329 func (s *Server) writeBanList() error {
331 defer s.banListMU.Unlock()
333 out, err := yaml.Marshal(s.banList)
337 err = ioutil.WriteFile(
338 filepath.Join(s.ConfigDir, "Banlist.yaml"),
345 func (s *Server) writeThreadedNews() error {
346 s.threadedNewsMux.Lock()
347 defer s.threadedNewsMux.Unlock()
349 out, err := yaml.Marshal(s.ThreadedNews)
353 err = s.FS.WriteFile(
354 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
361 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
365 clientConn := &ClientConn{
374 transfers: map[int]map[[4]byte]*FileTransfer{},
376 RemoteAddr: remoteAddr,
378 clientConn.transfers = map[int]map[[4]byte]*FileTransfer{
389 binary.BigEndian.PutUint16(*clientConn.ID, ID)
390 s.Clients[ID] = clientConn
395 // NewUser creates a new user account entry in the server map and config file
396 func (s *Server) NewUser(login, name, password string, access accessBitmap) error {
403 Password: hashAndSalt([]byte(password)),
406 out, err := yaml.Marshal(&account)
410 s.Accounts[login] = &account
412 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
415 func (s *Server) UpdateUser(login, newLogin, name, password string, access accessBitmap) error {
419 // update renames the user login
420 if login != newLogin {
421 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
425 s.Accounts[newLogin] = s.Accounts[login]
426 delete(s.Accounts, login)
429 account := s.Accounts[newLogin]
430 account.Access = access
432 account.Password = password
434 out, err := yaml.Marshal(&account)
439 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
446 // DeleteUser deletes the user account
447 func (s *Server) DeleteUser(login string) error {
451 delete(s.Accounts, login)
453 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
456 func (s *Server) connectedUsers() []Field {
460 var connectedUsers []Field
461 for _, c := range sortedClients(s.Clients) {
469 Name: string(c.UserName),
471 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
473 return connectedUsers
476 func (s *Server) loadBanList(path string) error {
477 fh, err := os.Open(path)
481 decoder := yaml.NewDecoder(fh)
483 return decoder.Decode(s.banList)
486 // loadThreadedNews loads the threaded news data from disk
487 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
488 fh, err := os.Open(threadedNewsPath)
492 decoder := yaml.NewDecoder(fh)
494 return decoder.Decode(s.ThreadedNews)
497 // loadAccounts loads account data from disk
498 func (s *Server) loadAccounts(userDir string) error {
499 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
504 if len(matches) == 0 {
505 return errors.New("no user accounts found in " + userDir)
508 for _, file := range matches {
509 fh, err := s.FS.Open(file)
515 decoder := yaml.NewDecoder(fh)
516 if err := decoder.Decode(&account); err != nil {
520 s.Accounts[account.Login] = &account
525 func (s *Server) loadConfig(path string) error {
526 fh, err := s.FS.Open(path)
531 decoder := yaml.NewDecoder(fh)
532 err = decoder.Decode(s.Config)
537 validate := validator.New()
538 err = validate.Struct(s.Config)
545 // dontPanic logs panics instead of crashing
546 func dontPanic(logger *zap.SugaredLogger) {
547 if r := recover(); r != nil {
548 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
549 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
553 // handleNewConnection takes a new net.Conn and performs the initial login sequence
554 func (s *Server) handleNewConnection(ctx context.Context, rwc io.ReadWriteCloser, remoteAddr string) error {
555 defer dontPanic(s.Logger)
557 if err := Handshake(rwc); err != nil {
561 // Create a new scanner for parsing incoming bytes into transaction tokens
562 scanner := bufio.NewScanner(rwc)
563 scanner.Split(transactionScanner)
567 clientLogin, _, err := ReadTransaction(scanner.Bytes())
572 c := s.NewClientConn(rwc, remoteAddr)
574 // check if remoteAddr is present in the ban list
575 if banUntil, ok := s.banList[strings.Split(remoteAddr, ":")[0]]; ok {
578 s.outbox <- *NewTransaction(
581 NewField(fieldData, []byte("You are permanently banned on this server")),
582 NewField(fieldChatOptions, []byte{0, 0}),
584 time.Sleep(1 * time.Second)
586 } else if time.Now().Before(*banUntil) {
587 s.outbox <- *NewTransaction(
590 NewField(fieldData, []byte("You are temporarily banned on this server")),
591 NewField(fieldChatOptions, []byte{0, 0}),
593 time.Sleep(1 * time.Second)
600 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
601 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
602 c.Version = clientLogin.GetField(fieldVersion).Data
605 for _, char := range encodedLogin {
606 login += string(rune(255 - uint(char)))
612 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
614 // If authentication fails, send error reply and close connection
615 if !c.Authenticate(login, encodedPassword) {
616 t := c.NewErrReply(clientLogin, "Incorrect login.")
617 b, err := t.MarshalBinary()
621 if _, err := rwc.Write(b); err != nil {
625 c.logger.Infow("Login failed", "clientVersion", fmt.Sprintf("%x", c.Version))
630 if clientLogin.GetField(fieldUserIconID).Data != nil {
631 c.Icon = clientLogin.GetField(fieldUserIconID).Data
634 c.Account = c.Server.Accounts[login]
636 if clientLogin.GetField(fieldUserName).Data != nil {
637 if c.Authorize(accessAnyName) {
638 c.UserName = clientLogin.GetField(fieldUserName).Data
640 c.UserName = []byte(c.Account.Name)
644 if c.Authorize(accessDisconUser) {
645 c.Flags = []byte{0, 2}
648 s.outbox <- c.NewReply(clientLogin,
649 NewField(fieldVersion, []byte{0x00, 0xbe}),
650 NewField(fieldCommunityBannerID, []byte{0, 0}),
651 NewField(fieldServerName, []byte(s.Config.Name)),
654 // Send user access privs so client UI knows how to behave
655 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, c.Account.Access[:]))
657 // Accounts with accessNoAgreement do not receive the server agreement on login. The behavior is different between
658 // client versions. For 1.2.3 client, we do not send tranShowAgreement. For other client versions, we send
659 // tranShowAgreement but with the NoServerAgreement field set to 1.
660 if c.Authorize(accessNoAgreement) {
661 // If client version is nil, then the client uses the 1.2.3 login behavior
662 if c.Version != nil {
663 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldNoServerAgreement, []byte{1}))
666 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
669 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
670 if c.Version == nil || bytes.Equal(c.Version, nostalgiaVersion) {
672 c.logger = c.logger.With("name", string(c.UserName))
673 c.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(c.Version); return i }()))
675 for _, t := range c.notifyOthers(
677 tranNotifyChangeUser, nil,
678 NewField(fieldUserName, c.UserName),
679 NewField(fieldUserID, *c.ID),
680 NewField(fieldUserIconID, c.Icon),
681 NewField(fieldUserFlags, c.Flags),
688 c.Server.Stats.LoginCount += 1
690 // Scan for new transactions and handle them as they come in.
692 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
693 // scanner re-uses the buffer for subsequent scans.
694 buf := make([]byte, len(scanner.Bytes()))
695 copy(buf, scanner.Bytes())
697 t, _, err := ReadTransaction(buf)
701 if err := c.handleTransaction(*t); err != nil {
702 c.logger.Errorw("Error handling transaction", "err", err)
708 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
712 randID := make([]byte, 4)
714 data := binary.BigEndian.Uint32(randID[:])
716 s.PrivateChats[data] = &PrivateChat{
718 ClientConn: make(map[uint16]*ClientConn),
720 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
725 const dlFldrActionSendFile = 1
726 const dlFldrActionResumeFile = 2
727 const dlFldrActionNextFile = 3
729 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
730 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
731 defer dontPanic(s.Logger)
733 txBuf := make([]byte, 16)
734 if _, err := io.ReadFull(rwc, txBuf); err != nil {
739 if _, err := t.Write(txBuf); err != nil {
745 delete(s.fileTransfers, t.ReferenceNumber)
751 fileTransfer, ok := s.fileTransfers[t.ReferenceNumber]
754 return errors.New("invalid transaction ID")
758 fileTransfer.ClientConn.transfersMU.Lock()
759 delete(fileTransfer.ClientConn.transfers[fileTransfer.Type], t.ReferenceNumber)
760 fileTransfer.ClientConn.transfersMU.Unlock()
763 rLogger := s.Logger.With(
764 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
765 "login", fileTransfer.ClientConn.Account.Login,
766 "name", string(fileTransfer.ClientConn.UserName),
769 fullPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
774 switch fileTransfer.Type {
776 if err := s.bannerDownload(rwc); err != nil {
781 s.Stats.DownloadCounter += 1
784 if fileTransfer.fileResumeData != nil {
785 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
788 fw, err := newFileWrapper(s.FS, fullPath, 0)
793 rLogger.Infow("File download started", "filePath", fullPath)
795 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
796 if fileTransfer.options == nil {
797 // Start by sending flat file object to client
798 if _, err := rwc.Write(fw.ffo.BinaryMarshal()); err != nil {
803 file, err := fw.dataForkReader()
808 br := bufio.NewReader(file)
809 if _, err := br.Discard(int(dataOffset)); err != nil {
813 if _, err = io.Copy(rwc, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
817 // if the client requested to resume transfer, do not send the resource fork header, or it will be appended into the fileWrapper data
818 if fileTransfer.fileResumeData == nil {
819 err = binary.Write(rwc, binary.BigEndian, fw.rsrcForkHeader())
825 rFile, err := fw.rsrcForkFile()
830 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
835 s.Stats.UploadCounter += 1
839 // A file upload has three possible cases:
840 // 1) Upload a new file
841 // 2) Resume a partially transferred file
842 // 3) Replace a fully uploaded file
843 // We have to infer which case applies by inspecting what is already on the filesystem
845 // 1) Check for existing file:
846 _, err = os.Stat(fullPath)
848 return errors.New("existing file found at " + fullPath)
850 if errors.Is(err, fs.ErrNotExist) {
851 // If not found, open or create a new .incomplete file
852 file, err = os.OpenFile(fullPath+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
858 f, err := newFileWrapper(s.FS, fullPath, 0)
863 rLogger.Infow("File upload started", "dstFile", fullPath)
865 rForkWriter := io.Discard
866 iForkWriter := io.Discard
867 if s.Config.PreserveResourceForks {
868 rForkWriter, err = f.rsrcForkWriter()
873 iForkWriter, err = f.infoForkWriter()
879 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
883 if err := file.Close(); err != nil {
887 if err := s.FS.Rename(fullPath+".incomplete", fullPath); err != nil {
891 rLogger.Infow("File upload complete", "dstFile", fullPath)
893 // Folder Download flow:
894 // 1. Get filePath from the transfer
895 // 2. Iterate over files
896 // 3. For each fileWrapper:
897 // Send fileWrapper header to client
898 // The client can reply in 3 ways:
900 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
901 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
903 // 2. If download of a fileWrapper is to be resumed:
905 // []byte{0x00, 0x02} // download folder action
906 // [2]byte // Resume data size
907 // []byte fileWrapper resume data (see myField_FileResumeData)
909 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
911 // When download is requested (case 2 or 3), server replies with:
912 // [4]byte - fileWrapper size
913 // []byte - Flattened File Object
915 // After every fileWrapper download, client could request next fileWrapper with:
916 // []byte{0x00, 0x03}
918 // This notifies the server to send the next item header
920 basePathLen := len(fullPath)
922 rLogger.Infow("Start folder download", "path", fullPath)
924 nextAction := make([]byte, 2)
925 if _, err := io.ReadFull(rwc, nextAction); err != nil {
930 err = filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
931 s.Stats.DownloadCounter += 1
939 if strings.HasPrefix(info.Name(), ".") {
943 hlFile, err := newFileWrapper(s.FS, path, 0)
948 subPath := path[basePathLen+1:]
949 rLogger.Debugw("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
955 fileHeader := NewFileHeader(subPath, info.IsDir())
957 // Send the fileWrapper header to client
958 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
959 s.Logger.Errorf("error sending file header: %v", err)
963 // Read the client's Next Action request
964 if _, err := io.ReadFull(rwc, nextAction); err != nil {
968 rLogger.Debugw("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
972 switch nextAction[1] {
973 case dlFldrActionResumeFile:
974 // get size of resumeData
975 resumeDataByteLen := make([]byte, 2)
976 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
980 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
981 resumeDataBytes := make([]byte, resumeDataLen)
982 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
986 var frd FileResumeData
987 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
990 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
991 case dlFldrActionNextFile:
992 // client asked to skip this file
1000 rLogger.Infow("File download started",
1001 "fileName", info.Name(),
1002 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
1005 // Send file size to client
1006 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
1011 // Send ffo bytes to client
1012 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
1017 file, err := s.FS.Open(path)
1022 // wr := bufio.NewWriterSize(rwc, 1460)
1023 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
1027 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
1028 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
1033 rFile, err := hlFile.rsrcForkFile()
1038 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
1043 // Read the client's Next Action request. This is always 3, I think?
1044 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1057 "Folder upload started",
1058 "dstPath", fullPath,
1059 "TransferSize", binary.BigEndian.Uint32(fileTransfer.TransferSize),
1060 "FolderItemCount", fileTransfer.FolderItemCount,
1063 // Check if the target folder exists. If not, create it.
1064 if _, err := s.FS.Stat(fullPath); os.IsNotExist(err) {
1065 if err := s.FS.Mkdir(fullPath, 0777); err != nil {
1070 // Begin the folder upload flow by sending the "next file action" to client
1071 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1075 fileSize := make([]byte, 4)
1077 for i := 0; i < fileTransfer.ItemCount(); i++ {
1078 s.Stats.UploadCounter += 1
1081 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1084 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1087 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1091 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1093 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1098 "Folder upload continued",
1099 "FormattedPath", fu.FormattedPath(),
1100 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1101 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1104 if fu.IsFolder == [2]byte{0, 1} {
1105 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
1106 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
1111 // Tell client to send next file
1112 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1116 nextAction := dlFldrActionSendFile
1118 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1119 _, err = os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
1120 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1124 nextAction = dlFldrActionNextFile
1127 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1128 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+incompleteFileSuffix))
1129 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1133 nextAction = dlFldrActionResumeFile
1136 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1141 case dlFldrActionNextFile:
1143 case dlFldrActionResumeFile:
1144 offset := make([]byte, 4)
1145 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1147 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1152 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1154 b, _ := fileResumeData.BinaryMarshal()
1156 bs := make([]byte, 2)
1157 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1159 if _, err := rwc.Write(append(bs, b...)); err != nil {
1163 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1167 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard, fileTransfer.bytesSentCounter); err != nil {
1171 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
1176 case dlFldrActionSendFile:
1177 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1181 filePath := filepath.Join(fullPath, fu.FormattedPath())
1183 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1188 rLogger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1190 incWriter, err := hlFile.incFileWriter()
1195 rForkWriter := io.Discard
1196 iForkWriter := io.Discard
1197 if s.Config.PreserveResourceForks {
1198 iForkWriter, err = hlFile.infoForkWriter()
1203 rForkWriter, err = hlFile.rsrcForkWriter()
1208 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
1212 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1217 // Tell client to send next fileWrapper
1218 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1223 rLogger.Infof("Folder upload complete")