]> git.r.bdr.sh - rbdr/mobius/blob - hotline/server.go
11ec21d1b9625501cb72e6d9e2d9b5458fe813aa
[rbdr/mobius] / hotline / server.go
1 package hotline
2
3 import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/binary"
8 "errors"
9 "fmt"
10 "github.com/go-playground/validator/v10"
11 "go.uber.org/zap"
12 "gopkg.in/yaml.v3"
13 "io"
14 "io/fs"
15 "io/ioutil"
16 "math/big"
17 "math/rand"
18 "net"
19 "os"
20 "path/filepath"
21 "runtime/debug"
22 "strings"
23 "sync"
24 "time"
25 )
26
27 type contextKey string
28
29 var contextKeyReq = contextKey("req")
30
31 type requestCtx struct {
32 remoteAddr string
33 login string
34 name string
35 }
36
37 const (
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
41 )
42
43 var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
44
45 type Server struct {
46 Port int
47 Accounts map[string]*Account
48 Agreement []byte
49 Clients map[uint16]*ClientConn
50 ThreadedNews *ThreadedNews
51 FileTransfers map[uint32]*FileTransfer
52 Config *Config
53 ConfigDir string
54 Logger *zap.SugaredLogger
55 PrivateChats map[uint32]*PrivateChat
56 NextGuestID *uint16
57 TrackerPassID [4]byte
58 Stats *Stats
59
60 FS FileStore // Storage backend to use for File storage
61
62 outbox chan Transaction
63 mux sync.Mutex
64
65 flatNewsMux sync.Mutex
66 FlatNews []byte
67 }
68
69 type PrivateChat struct {
70 Subject string
71 ClientConn map[uint16]*ClientConn
72 }
73
74 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
75 s.Logger.Infow("Hotline server started",
76 "version", VERSION,
77 "API port", fmt.Sprintf(":%v", s.Port),
78 "Transfer port", fmt.Sprintf(":%v", s.Port+1),
79 )
80
81 var wg sync.WaitGroup
82
83 wg.Add(1)
84 go func() {
85 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port))
86 if err != nil {
87 s.Logger.Fatal(err)
88 }
89
90 s.Logger.Fatal(s.Serve(ctx, ln))
91 }()
92
93 wg.Add(1)
94 go func() {
95 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", "", s.Port+1))
96 if err != nil {
97 s.Logger.Fatal(err)
98
99 }
100
101 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
102 }()
103
104 wg.Wait()
105
106 return nil
107 }
108
109 func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
110 for {
111 conn, err := ln.Accept()
112 if err != nil {
113 return err
114 }
115
116 go func() {
117 defer func() { _ = conn.Close() }()
118
119 err = s.handleFileTransfer(
120 context.WithValue(ctx, contextKeyReq, requestCtx{
121 remoteAddr: conn.RemoteAddr().String(),
122 }),
123 conn,
124 )
125
126 if err != nil {
127 s.Logger.Errorw("file transfer error", "reason", err)
128 }
129 }()
130 }
131 }
132
133 func (s *Server) sendTransaction(t Transaction) error {
134 requestNum := binary.BigEndian.Uint16(t.Type)
135 clientID, err := byteToInt(*t.clientID)
136 if err != nil {
137 return err
138 }
139
140 s.mux.Lock()
141 client := s.Clients[uint16(clientID)]
142 s.mux.Unlock()
143 if client == nil {
144 return fmt.Errorf("invalid client id %v", *t.clientID)
145 }
146 userName := string(client.UserName)
147 login := client.Account.Login
148
149 handler := TransactionHandlers[requestNum]
150
151 b, err := t.MarshalBinary()
152 if err != nil {
153 return err
154 }
155 var n int
156 if n, err = client.Connection.Write(b); err != nil {
157 return err
158 }
159 s.Logger.Debugw("Sent Transaction",
160 "name", userName,
161 "login", login,
162 "IsReply", t.IsReply,
163 "type", handler.Name,
164 "sentBytes", n,
165 "remoteAddr", client.RemoteAddr,
166 )
167 return nil
168 }
169
170 func (s *Server) processOutbox() {
171 for {
172 t := <-s.outbox
173 go func() {
174 if err := s.sendTransaction(t); err != nil {
175 s.Logger.Errorw("error sending transaction", "err", err)
176 }
177 }()
178 }
179 }
180
181 func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
182 go s.processOutbox()
183
184 for {
185 conn, err := ln.Accept()
186 if err != nil {
187 s.Logger.Errorw("error accepting connection", "err", err)
188 }
189 connCtx := context.WithValue(ctx, contextKeyReq, requestCtx{
190 remoteAddr: conn.RemoteAddr().String(),
191 })
192
193 go func() {
194 if err := s.handleNewConnection(connCtx, conn, conn.RemoteAddr().String()); err != nil {
195 s.Logger.Infow("New client connection established", "RemoteAddr", conn.RemoteAddr())
196 if err == io.EOF {
197 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
198 } else {
199 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
200 }
201 }
202 }()
203 }
204 }
205
206 const (
207 agreementFile = "Agreement.txt"
208 )
209
210 // NewServer constructs a new Server from a config dir
211 func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
212 server := Server{
213 Port: netPort,
214 Accounts: make(map[string]*Account),
215 Config: new(Config),
216 Clients: make(map[uint16]*ClientConn),
217 FileTransfers: make(map[uint32]*FileTransfer),
218 PrivateChats: make(map[uint32]*PrivateChat),
219 ConfigDir: configDir,
220 Logger: logger,
221 NextGuestID: new(uint16),
222 outbox: make(chan Transaction),
223 Stats: &Stats{StartTime: time.Now()},
224 ThreadedNews: &ThreadedNews{},
225 FS: FS,
226 }
227
228 var err error
229
230 // generate a new random passID for tracker registration
231 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
232 return nil, err
233 }
234
235 server.Agreement, err = os.ReadFile(filepath.Join(configDir, agreementFile))
236 if err != nil {
237 return nil, err
238 }
239
240 if server.FlatNews, err = os.ReadFile(filepath.Join(configDir, "MessageBoard.txt")); err != nil {
241 return nil, err
242 }
243
244 if err := server.loadThreadedNews(filepath.Join(configDir, "ThreadedNews.yaml")); err != nil {
245 return nil, err
246 }
247
248 if err := server.loadConfig(filepath.Join(configDir, "config.yaml")); err != nil {
249 return nil, err
250 }
251
252 if err := server.loadAccounts(filepath.Join(configDir, "Users/")); err != nil {
253 return nil, err
254 }
255
256 server.Config.FileRoot = filepath.Join(configDir, "Files")
257
258 *server.NextGuestID = 1
259
260 if server.Config.EnableTrackerRegistration {
261 server.Logger.Infow(
262 "Tracker registration enabled",
263 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
264 "trackers", server.Config.Trackers,
265 )
266
267 go func() {
268 for {
269 tr := &TrackerRegistration{
270 UserCount: server.userCount(),
271 PassID: server.TrackerPassID[:],
272 Name: server.Config.Name,
273 Description: server.Config.Description,
274 }
275 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
276 for _, t := range server.Config.Trackers {
277 if err := register(t, tr); err != nil {
278 server.Logger.Errorw("unable to register with tracker %v", "error", err)
279 }
280 server.Logger.Infow("Sent Tracker registration", "data", tr)
281 }
282
283 time.Sleep(trackerUpdateFrequency * time.Second)
284 }
285 }()
286 }
287
288 // Start Client Keepalive go routine
289 go server.keepaliveHandler()
290
291 return &server, nil
292 }
293
294 func (s *Server) userCount() int {
295 s.mux.Lock()
296 defer s.mux.Unlock()
297
298 return len(s.Clients)
299 }
300
301 func (s *Server) keepaliveHandler() {
302 for {
303 time.Sleep(idleCheckInterval * time.Second)
304 s.mux.Lock()
305
306 for _, c := range s.Clients {
307 c.IdleTime += idleCheckInterval
308 if c.IdleTime > userIdleSeconds && !c.Idle {
309 c.Idle = true
310
311 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
312 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
313 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
314
315 c.sendAll(
316 tranNotifyChangeUser,
317 NewField(fieldUserID, *c.ID),
318 NewField(fieldUserFlags, *c.Flags),
319 NewField(fieldUserName, c.UserName),
320 NewField(fieldUserIconID, *c.Icon),
321 )
322 }
323 }
324 s.mux.Unlock()
325 }
326 }
327
328 func (s *Server) writeThreadedNews() error {
329 s.mux.Lock()
330 defer s.mux.Unlock()
331
332 out, err := yaml.Marshal(s.ThreadedNews)
333 if err != nil {
334 return err
335 }
336 err = ioutil.WriteFile(
337 filepath.Join(s.ConfigDir, "ThreadedNews.yaml"),
338 out,
339 0666,
340 )
341 return err
342 }
343
344 func (s *Server) NewClientConn(conn io.ReadWriteCloser, remoteAddr string) *ClientConn {
345 s.mux.Lock()
346 defer s.mux.Unlock()
347
348 clientConn := &ClientConn{
349 ID: &[]byte{0, 0},
350 Icon: &[]byte{0, 0},
351 Flags: &[]byte{0, 0},
352 UserName: []byte{},
353 Connection: conn,
354 Server: s,
355 Version: &[]byte{},
356 AutoReply: []byte{},
357 Transfers: make(map[int][]*FileTransfer),
358 Agreed: false,
359 RemoteAddr: remoteAddr,
360 }
361 *s.NextGuestID++
362 ID := *s.NextGuestID
363
364 binary.BigEndian.PutUint16(*clientConn.ID, ID)
365 s.Clients[ID] = clientConn
366
367 return clientConn
368 }
369
370 // NewUser creates a new user account entry in the server map and config file
371 func (s *Server) NewUser(login, name, password string, access []byte) error {
372 s.mux.Lock()
373 defer s.mux.Unlock()
374
375 account := Account{
376 Login: login,
377 Name: name,
378 Password: hashAndSalt([]byte(password)),
379 Access: &access,
380 }
381 out, err := yaml.Marshal(&account)
382 if err != nil {
383 return err
384 }
385 s.Accounts[login] = &account
386
387 return s.FS.WriteFile(filepath.Join(s.ConfigDir, "Users", login+".yaml"), out, 0666)
388 }
389
390 func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
391 s.mux.Lock()
392 defer s.mux.Unlock()
393
394 // update renames the user login
395 if login != newLogin {
396 err := os.Rename(filepath.Join(s.ConfigDir, "Users", login+".yaml"), filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"))
397 if err != nil {
398 return err
399 }
400 s.Accounts[newLogin] = s.Accounts[login]
401 delete(s.Accounts, login)
402 }
403
404 account := s.Accounts[newLogin]
405 account.Access = &access
406 account.Name = name
407 account.Password = password
408
409 out, err := yaml.Marshal(&account)
410 if err != nil {
411 return err
412 }
413
414 if err := os.WriteFile(filepath.Join(s.ConfigDir, "Users", newLogin+".yaml"), out, 0666); err != nil {
415 return err
416 }
417
418 return nil
419 }
420
421 // DeleteUser deletes the user account
422 func (s *Server) DeleteUser(login string) error {
423 s.mux.Lock()
424 defer s.mux.Unlock()
425
426 delete(s.Accounts, login)
427
428 return s.FS.Remove(filepath.Join(s.ConfigDir, "Users", login+".yaml"))
429 }
430
431 func (s *Server) connectedUsers() []Field {
432 s.mux.Lock()
433 defer s.mux.Unlock()
434
435 var connectedUsers []Field
436 for _, c := range sortedClients(s.Clients) {
437 if !c.Agreed {
438 continue
439 }
440 user := User{
441 ID: *c.ID,
442 Icon: *c.Icon,
443 Flags: *c.Flags,
444 Name: string(c.UserName),
445 }
446 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
447 }
448 return connectedUsers
449 }
450
451 // loadThreadedNews loads the threaded news data from disk
452 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
453 fh, err := os.Open(threadedNewsPath)
454 if err != nil {
455 return err
456 }
457 decoder := yaml.NewDecoder(fh)
458
459 return decoder.Decode(s.ThreadedNews)
460 }
461
462 // loadAccounts loads account data from disk
463 func (s *Server) loadAccounts(userDir string) error {
464 matches, err := filepath.Glob(filepath.Join(userDir, "*.yaml"))
465 if err != nil {
466 return err
467 }
468
469 if len(matches) == 0 {
470 return errors.New("no user accounts found in " + userDir)
471 }
472
473 for _, file := range matches {
474 fh, err := s.FS.Open(file)
475 if err != nil {
476 return err
477 }
478
479 account := Account{}
480 decoder := yaml.NewDecoder(fh)
481 if err := decoder.Decode(&account); err != nil {
482 return err
483 }
484
485 s.Accounts[account.Login] = &account
486 }
487 return nil
488 }
489
490 func (s *Server) loadConfig(path string) error {
491 fh, err := s.FS.Open(path)
492 if err != nil {
493 return err
494 }
495
496 decoder := yaml.NewDecoder(fh)
497 err = decoder.Decode(s.Config)
498 if err != nil {
499 return err
500 }
501
502 validate := validator.New()
503 err = validate.Struct(s.Config)
504 if err != nil {
505 return err
506 }
507 return nil
508 }
509
510 const (
511 minTransactionLen = 22 // minimum length of any transaction
512 )
513
514 // dontPanic recovers and logs panics instead of crashing
515 // TODO: remove this after known issues are fixed
516 func dontPanic(logger *zap.SugaredLogger) {
517 if r := recover(); r != nil {
518 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
519 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
520 }
521 }
522
523 // handleNewConnection takes a new net.Conn and performs the initial login sequence
524 func (s *Server) handleNewConnection(ctx context.Context, conn io.ReadWriteCloser, remoteAddr string) error {
525 defer dontPanic(s.Logger)
526
527 if err := Handshake(conn); err != nil {
528 return err
529 }
530
531 buf := make([]byte, 1024)
532 // TODO: fix potential short read with io.ReadFull
533 readLen, err := conn.Read(buf)
534 if readLen < minTransactionLen {
535 return err
536 }
537 if err != nil {
538 return err
539 }
540
541 clientLogin, _, err := ReadTransaction(buf[:readLen])
542 if err != nil {
543 return err
544 }
545
546 c := s.NewClientConn(conn, remoteAddr)
547 defer c.Disconnect()
548
549 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
550 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
551 *c.Version = clientLogin.GetField(fieldVersion).Data
552
553 var login string
554 for _, char := range encodedLogin {
555 login += string(rune(255 - uint(char)))
556 }
557 if login == "" {
558 login = GuestAccount
559 }
560
561 // If authentication fails, send error reply and close connection
562 if !c.Authenticate(login, encodedPassword) {
563 t := c.NewErrReply(clientLogin, "Incorrect login.")
564 b, err := t.MarshalBinary()
565 if err != nil {
566 return err
567 }
568 if _, err := conn.Write(b); err != nil {
569 return err
570 }
571 return fmt.Errorf("incorrect login")
572 }
573
574 if clientLogin.GetField(fieldUserName).Data != nil {
575 c.UserName = clientLogin.GetField(fieldUserName).Data
576 }
577
578 if clientLogin.GetField(fieldUserIconID).Data != nil {
579 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
580 }
581
582 c.Account = c.Server.Accounts[login]
583
584 if c.Authorize(accessDisconUser) {
585 *c.Flags = []byte{0, 2}
586 }
587
588 c.logger = s.Logger.With("remoteAddr", remoteAddr, "login", login)
589
590 c.logger.Infow("Client connection received", "version", fmt.Sprintf("%x", *c.Version))
591
592 s.outbox <- c.NewReply(clientLogin,
593 NewField(fieldVersion, []byte{0x00, 0xbe}),
594 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
595 NewField(fieldServerName, []byte(s.Config.Name)),
596 )
597
598 // Send user access privs so client UI knows how to behave
599 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
600
601 // Show agreement to client
602 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
603
604 // Used simplified hotline v1.2.3 login flow for clients that do not send login info in tranAgreed
605 if *c.Version == nil || bytes.Equal(*c.Version, nostalgiaVersion) {
606 c.Agreed = true
607 c.logger = c.logger.With("name", string(c.UserName))
608
609 for _, t := range c.notifyOthers(
610 *NewTransaction(
611 tranNotifyChangeUser, nil,
612 NewField(fieldUserName, c.UserName),
613 NewField(fieldUserID, *c.ID),
614 NewField(fieldUserIconID, *c.Icon),
615 NewField(fieldUserFlags, *c.Flags),
616 ),
617 ) {
618 c.Server.outbox <- t
619 }
620 }
621
622 c.Server.Stats.LoginCount += 1
623
624 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
625 tranBuff := make([]byte, 0)
626 tReadlen := 0
627 // Infinite loop where take action on incoming client requests until the connection is closed
628 for {
629 buf = make([]byte, readBuffSize)
630 tranBuff = tranBuff[tReadlen:]
631
632 readLen, err := c.Connection.Read(buf)
633 if err != nil {
634 return err
635 }
636 tranBuff = append(tranBuff, buf[:readLen]...)
637
638 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
639 // into a slice of transactions
640 var transactions []Transaction
641 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
642 c.logger.Errorw("Error handling transaction", "err", err)
643 }
644
645 // iterate over all the transactions that were parsed from the byte slice and handle them
646 for _, t := range transactions {
647 if err := c.handleTransaction(&t); err != nil {
648 c.logger.Errorw("Error handling transaction", "err", err)
649 }
650 }
651 }
652 }
653
654 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
655 // in the transfer request payload, and the file transfer server will use it to map the request
656 // to a transfer
657 func (s *Server) NewTransactionRef() []byte {
658 transactionRef := make([]byte, 4)
659 rand.Read(transactionRef)
660
661 return transactionRef
662 }
663
664 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
665 s.mux.Lock()
666 defer s.mux.Unlock()
667
668 randID := make([]byte, 4)
669 rand.Read(randID)
670 data := binary.BigEndian.Uint32(randID[:])
671
672 s.PrivateChats[data] = &PrivateChat{
673 Subject: "",
674 ClientConn: make(map[uint16]*ClientConn),
675 }
676 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
677
678 return randID
679 }
680
681 const dlFldrActionSendFile = 1
682 const dlFldrActionResumeFile = 2
683 const dlFldrActionNextFile = 3
684
685 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
686 func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
687 defer dontPanic(s.Logger)
688
689 txBuf := make([]byte, 16)
690 if _, err := io.ReadFull(rwc, txBuf); err != nil {
691 return err
692 }
693
694 var t transfer
695 if _, err := t.Write(txBuf); err != nil {
696 return err
697 }
698
699 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
700 defer func() {
701 s.mux.Lock()
702 delete(s.FileTransfers, transferRefNum)
703 s.mux.Unlock()
704 }()
705
706 s.mux.Lock()
707 fileTransfer, ok := s.FileTransfers[transferRefNum]
708 s.mux.Unlock()
709 if !ok {
710 return errors.New("invalid transaction ID")
711 }
712
713 rLogger := s.Logger.With(
714 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
715 "xferID", transferRefNum,
716 )
717
718 switch fileTransfer.Type {
719 case FileDownload:
720 s.Stats.DownloadCounter += 1
721
722 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
723 if err != nil {
724 return err
725 }
726
727 var dataOffset int64
728 if fileTransfer.fileResumeData != nil {
729 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
730 }
731
732 fw, err := newFileWrapper(s.FS, fullFilePath, 0)
733 if err != nil {
734 return err
735 }
736
737 rLogger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
738
739 wr := bufio.NewWriterSize(rwc, 1460)
740
741 // if file transfer options are included, that means this is a "quick preview" request from a 1.5+ client
742 if fileTransfer.options == nil {
743 // Start by sending flat file object to client
744 if _, err := wr.Write(fw.ffo.BinaryMarshal()); err != nil {
745 return err
746 }
747 }
748
749 file, err := fw.dataForkReader()
750 if err != nil {
751 return err
752 }
753
754 if err := sendFile(wr, file, int(dataOffset)); err != nil {
755 return err
756 }
757
758 if err := wr.Flush(); err != nil {
759 return err
760 }
761
762 // if the client requested to resume transfer, do not send the resource fork, or it will be appended into the fileWrapper data
763 if fileTransfer.fileResumeData == nil {
764 err = binary.Write(wr, binary.BigEndian, fw.rsrcForkHeader())
765 if err != nil {
766 return err
767 }
768 if err := wr.Flush(); err != nil {
769 return err
770 }
771 }
772
773 rFile, err := fw.rsrcForkFile()
774 if err != nil {
775 return nil
776 }
777
778 err = sendFile(wr, rFile, int(dataOffset))
779 if err != nil {
780 return err
781 }
782
783 if err := wr.Flush(); err != nil {
784 return err
785 }
786
787 case FileUpload:
788 s.Stats.UploadCounter += 1
789
790 destinationFile, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
791 if err != nil {
792 return err
793 }
794
795 var file *os.File
796
797 // A file upload has three possible cases:
798 // 1) Upload a new file
799 // 2) Resume a partially transferred file
800 // 3) Replace a fully uploaded file
801 // We have to infer which case applies by inspecting what is already on the filesystem
802
803 // 1) Check for existing file:
804 _, err = os.Stat(destinationFile)
805 if err == nil {
806 // If found, that means this upload is intended to replace the file
807 if err = os.Remove(destinationFile); err != nil {
808 return err
809 }
810 file, err = os.Create(destinationFile + incompleteFileSuffix)
811 }
812 if errors.Is(err, fs.ErrNotExist) {
813 // If not found, open or create a new .incomplete file
814 file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
815 if err != nil {
816 return err
817 }
818 }
819
820 f, err := newFileWrapper(s.FS, destinationFile, 0)
821 if err != nil {
822 return err
823 }
824
825 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
826
827 rForkWriter := io.Discard
828 iForkWriter := io.Discard
829 if s.Config.PreserveResourceForks {
830 rForkWriter, err = f.rsrcForkWriter()
831 if err != nil {
832 return err
833 }
834
835 iForkWriter, err = f.infoForkWriter()
836 if err != nil {
837 return err
838 }
839 }
840
841 if err := receiveFile(rwc, file, rForkWriter, iForkWriter); err != nil {
842 return err
843 }
844
845 if err := file.Close(); err != nil {
846 return err
847 }
848
849 if err := s.FS.Rename(destinationFile+".incomplete", destinationFile); err != nil {
850 return err
851 }
852
853 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
854 case FolderDownload:
855 // Folder Download flow:
856 // 1. Get filePath from the transfer
857 // 2. Iterate over files
858 // 3. For each fileWrapper:
859 // Send fileWrapper header to client
860 // The client can reply in 3 ways:
861 //
862 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
863 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
864 //
865 // 2. If download of a fileWrapper is to be resumed:
866 // client sends:
867 // []byte{0x00, 0x02} // download folder action
868 // [2]byte // Resume data size
869 // []byte fileWrapper resume data (see myField_FileResumeData)
870 //
871 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
872 //
873 // When download is requested (case 2 or 3), server replies with:
874 // [4]byte - fileWrapper size
875 // []byte - Flattened File Object
876 //
877 // After every fileWrapper download, client could request next fileWrapper with:
878 // []byte{0x00, 0x03}
879 //
880 // This notifies the server to send the next item header
881
882 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
883 if err != nil {
884 return err
885 }
886
887 basePathLen := len(fullFilePath)
888
889 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
890
891 nextAction := make([]byte, 2)
892 if _, err := io.ReadFull(rwc, nextAction); err != nil {
893 return err
894 }
895
896 i := 0
897 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
898 s.Stats.DownloadCounter += 1
899 i += 1
900
901 if err != nil {
902 return err
903 }
904
905 // skip dot files
906 if strings.HasPrefix(info.Name(), ".") {
907 return nil
908 }
909
910 hlFile, err := newFileWrapper(s.FS, path, 0)
911 if err != nil {
912 return err
913 }
914
915 subPath := path[basePathLen+1:]
916 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
917
918 if i == 1 {
919 return nil
920 }
921
922 fileHeader := NewFileHeader(subPath, info.IsDir())
923
924 // Send the fileWrapper header to client
925 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
926 s.Logger.Errorf("error sending file header: %v", err)
927 return err
928 }
929
930 // Read the client's Next Action request
931 if _, err := io.ReadFull(rwc, nextAction); err != nil {
932 return err
933 }
934
935 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
936
937 var dataOffset int64
938
939 switch nextAction[1] {
940 case dlFldrActionResumeFile:
941 // get size of resumeData
942 resumeDataByteLen := make([]byte, 2)
943 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
944 return err
945 }
946
947 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
948 resumeDataBytes := make([]byte, resumeDataLen)
949 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
950 return err
951 }
952
953 var frd FileResumeData
954 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
955 return err
956 }
957 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
958 case dlFldrActionNextFile:
959 // client asked to skip this file
960 return nil
961 }
962
963 if info.IsDir() {
964 return nil
965 }
966
967 s.Logger.Infow("File download started",
968 "fileName", info.Name(),
969 "transactionRef", fileTransfer.ReferenceNumber,
970 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
971 )
972
973 // Send file size to client
974 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
975 s.Logger.Error(err)
976 return err
977 }
978
979 // Send ffo bytes to client
980 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
981 s.Logger.Error(err)
982 return err
983 }
984
985 file, err := s.FS.Open(path)
986 if err != nil {
987 return err
988 }
989
990 // wr := bufio.NewWriterSize(rwc, 1460)
991 err = sendFile(rwc, file, int(dataOffset))
992 if err != nil {
993 return err
994 }
995
996 if nextAction[1] != 2 && hlFile.ffo.FlatFileHeader.ForkCount[1] == 3 {
997 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
998 if err != nil {
999 return err
1000 }
1001
1002 rFile, err := hlFile.rsrcForkFile()
1003 if err != nil {
1004 return err
1005 }
1006
1007 err = sendFile(rwc, rFile, int(dataOffset))
1008 if err != nil {
1009 return err
1010 }
1011 }
1012
1013 // Read the client's Next Action request. This is always 3, I think?
1014 if _, err := io.ReadFull(rwc, nextAction); err != nil {
1015 return err
1016 }
1017
1018 return nil
1019 })
1020
1021 if err != nil {
1022 return err
1023 }
1024
1025 case FolderUpload:
1026 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
1027 if err != nil {
1028 return err
1029 }
1030
1031 s.Logger.Infow(
1032 "Folder upload started",
1033 "transactionRef", fileTransfer.ReferenceNumber,
1034 "dstPath", dstPath,
1035 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
1036 "FolderItemCount", fileTransfer.FolderItemCount,
1037 )
1038
1039 // Check if the target folder exists. If not, create it.
1040 if _, err := s.FS.Stat(dstPath); os.IsNotExist(err) {
1041 if err := s.FS.Mkdir(dstPath, 0777); err != nil {
1042 return err
1043 }
1044 }
1045
1046 // Begin the folder upload flow by sending the "next file action" to client
1047 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1048 return err
1049 }
1050
1051 fileSize := make([]byte, 4)
1052
1053 for i := 0; i < fileTransfer.ItemCount(); i++ {
1054 s.Stats.UploadCounter += 1
1055
1056 var fu folderUpload
1057 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
1058 return err
1059 }
1060 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
1061 return err
1062 }
1063 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
1064 return err
1065 }
1066
1067 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes
1068
1069 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
1070 return err
1071 }
1072
1073 s.Logger.Infow(
1074 "Folder upload continued",
1075 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
1076 "FormattedPath", fu.FormattedPath(),
1077 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
1078 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
1079 )
1080
1081 if fu.IsFolder == [2]byte{0, 1} {
1082 if _, err := os.Stat(filepath.Join(dstPath, fu.FormattedPath())); os.IsNotExist(err) {
1083 if err := os.Mkdir(filepath.Join(dstPath, fu.FormattedPath()), 0777); err != nil {
1084 return err
1085 }
1086 }
1087
1088 // Tell client to send next file
1089 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1090 return err
1091 }
1092 } else {
1093 nextAction := dlFldrActionSendFile
1094
1095 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1096 _, err = os.Stat(filepath.Join(dstPath, fu.FormattedPath()))
1097 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1098 return err
1099 }
1100 if err == nil {
1101 nextAction = dlFldrActionNextFile
1102 }
1103
1104 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1105 incompleteFile, err := os.Stat(filepath.Join(dstPath, fu.FormattedPath()+incompleteFileSuffix))
1106 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1107 return err
1108 }
1109 if err == nil {
1110 nextAction = dlFldrActionResumeFile
1111 }
1112
1113 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
1114 return err
1115 }
1116
1117 switch nextAction {
1118 case dlFldrActionNextFile:
1119 continue
1120 case dlFldrActionResumeFile:
1121 offset := make([]byte, 4)
1122 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
1123
1124 file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1125 if err != nil {
1126 return err
1127 }
1128
1129 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
1130
1131 b, _ := fileResumeData.BinaryMarshal()
1132
1133 bs := make([]byte, 2)
1134 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1135
1136 if _, err := rwc.Write(append(bs, b...)); err != nil {
1137 return err
1138 }
1139
1140 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1141 return err
1142 }
1143
1144 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard); err != nil {
1145 s.Logger.Error(err)
1146 }
1147
1148 err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath())
1149 if err != nil {
1150 return err
1151 }
1152
1153 case dlFldrActionSendFile:
1154 if _, err := io.ReadFull(rwc, fileSize); err != nil {
1155 return err
1156 }
1157
1158 filePath := filepath.Join(dstPath, fu.FormattedPath())
1159
1160 hlFile, err := newFileWrapper(s.FS, filePath, 0)
1161 if err != nil {
1162 return err
1163 }
1164
1165 s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
1166
1167 incWriter, err := hlFile.incFileWriter()
1168 if err != nil {
1169 return err
1170 }
1171
1172 rForkWriter := io.Discard
1173 iForkWriter := io.Discard
1174 if s.Config.PreserveResourceForks {
1175 iForkWriter, err = hlFile.infoForkWriter()
1176 if err != nil {
1177 return err
1178 }
1179
1180 rForkWriter, err = hlFile.rsrcForkWriter()
1181 if err != nil {
1182 return err
1183 }
1184 }
1185 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter); err != nil {
1186 return err
1187 }
1188 // _ = newFile.Close()
1189 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1190 return err
1191 }
1192 }
1193
1194 // Tell client to send next fileWrapper
1195 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1196 return err
1197 }
1198 }
1199 }
1200 s.Logger.Infof("Folder upload complete")
1201 }
1202
1203 return nil
1204 }