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