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