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