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