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