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