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