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