]> git.r.bdr.sh - rbdr/mobius/blob - hotline/server.go
d5da45808e546bfb0b440fe866978c327b6d9098
[rbdr/mobius] / hotline / server.go
1 package hotline
2
3 import (
4 "context"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "github.com/go-playground/validator/v10"
9 "go.uber.org/zap"
10 "io"
11 "io/fs"
12 "io/ioutil"
13 "math/big"
14 "math/rand"
15 "net"
16 "os"
17 "path"
18 "path/filepath"
19 "runtime/debug"
20 "sort"
21 "strings"
22 "sync"
23 "time"
24
25 "gopkg.in/yaml.v3"
26 )
27
28 const (
29 userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
30 idleCheckInterval = 10 // time in seconds to check for idle users
31 trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
32 )
33
34 type Server struct {
35 Port int
36 Accounts map[string]*Account
37 Agreement []byte
38 Clients map[uint16]*ClientConn
39 FlatNews []byte
40 ThreadedNews *ThreadedNews
41 FileTransfers map[uint32]*FileTransfer
42 Config *Config
43 ConfigDir string
44 Logger *zap.SugaredLogger
45 PrivateChats map[uint32]*PrivateChat
46 NextGuestID *uint16
47 TrackerPassID [4]byte
48 Stats *Stats
49
50 APIListener net.Listener
51 FileListener net.Listener
52
53 // newsReader io.Reader
54 // newsWriter io.WriteCloser
55
56 outbox chan Transaction
57
58 mux sync.Mutex
59 flatNewsMux sync.Mutex
60 }
61
62 type PrivateChat struct {
63 Subject string
64 ClientConn map[uint16]*ClientConn
65 }
66
67 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
68 s.Logger.Infow("Hotline server started", "version", VERSION)
69 var wg sync.WaitGroup
70
71 wg.Add(1)
72 go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }()
73
74 wg.Add(1)
75 go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }()
76
77 wg.Wait()
78
79 return nil
80 }
81
82 func (s *Server) APIPort() int {
83 return s.APIListener.Addr().(*net.TCPAddr).Port
84 }
85
86 func (s *Server) ServeFileTransfers(ln net.Listener) error {
87 s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1))
88
89 for {
90 conn, err := ln.Accept()
91 if err != nil {
92 return err
93 }
94
95 go func() {
96 if err := s.handleFileTransfer(conn); err != nil {
97 s.Logger.Errorw("file transfer error", "reason", err)
98 }
99 }()
100 }
101 }
102
103 func (s *Server) sendTransaction(t Transaction) error {
104 requestNum := binary.BigEndian.Uint16(t.Type)
105 clientID, err := byteToInt(*t.clientID)
106 if err != nil {
107 return err
108 }
109
110 s.mux.Lock()
111 client := s.Clients[uint16(clientID)]
112 s.mux.Unlock()
113 if client == nil {
114 return fmt.Errorf("invalid client id %v", *t.clientID)
115 }
116 userName := string(client.UserName)
117 login := client.Account.Login
118
119 handler := TransactionHandlers[requestNum]
120
121 b, err := t.MarshalBinary()
122 if err != nil {
123 return err
124 }
125 var n int
126 if n, err = client.Connection.Write(b); err != nil {
127 return err
128 }
129 s.Logger.Debugw("Sent Transaction",
130 "name", userName,
131 "login", login,
132 "IsReply", t.IsReply,
133 "type", handler.Name,
134 "sentBytes", n,
135 "remoteAddr", client.RemoteAddr,
136 )
137 return nil
138 }
139
140 func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error {
141 s.Logger.Infow("Hotline server started", "Addr", fmt.Sprintf(":%v", s.Port))
142
143 for {
144 conn, err := ln.Accept()
145 if err != nil {
146 s.Logger.Errorw("error accepting connection", "err", err)
147 }
148
149 go func() {
150 for {
151 t := <-s.outbox
152 go func() {
153 if err := s.sendTransaction(t); err != nil {
154 s.Logger.Errorw("error sending transaction", "err", err)
155 }
156 }()
157 }
158 }()
159 go func() {
160 if err := s.handleNewConnection(conn, conn.RemoteAddr().String()); err != nil {
161 if err == io.EOF {
162 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
163 } else {
164 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
165 }
166 }
167 }()
168 }
169 }
170
171 const (
172 agreementFile = "Agreement.txt"
173 )
174
175 // NewServer constructs a new Server from a config dir
176 func NewServer(configDir, netInterface string, netPort int, logger *zap.SugaredLogger) (*Server, error) {
177 server := Server{
178 Port: netPort,
179 Accounts: make(map[string]*Account),
180 Config: new(Config),
181 Clients: make(map[uint16]*ClientConn),
182 FileTransfers: make(map[uint32]*FileTransfer),
183 PrivateChats: make(map[uint32]*PrivateChat),
184 ConfigDir: configDir,
185 Logger: logger,
186 NextGuestID: new(uint16),
187 outbox: make(chan Transaction),
188 Stats: &Stats{StartTime: time.Now()},
189 ThreadedNews: &ThreadedNews{},
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 UserCount: server.userCount(),
249 PassID: server.TrackerPassID[:],
250 Name: server.Config.Name,
251 Description: server.Config.Description,
252 }
253 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
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
481 validate := validator.New()
482 err = validate.Struct(s.Config)
483 if err != nil {
484 return err
485 }
486 return nil
487 }
488
489 const (
490 minTransactionLen = 22 // minimum length of any transaction
491 )
492
493 // dontPanic recovers and logs panics instead of crashing
494 // TODO: remove this after known issues are fixed
495 func dontPanic(logger *zap.SugaredLogger) {
496 if r := recover(); r != nil {
497 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
498 logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
499 }
500 }
501
502 // handleNewConnection takes a new net.Conn and performs the initial login sequence
503 func (s *Server) handleNewConnection(conn net.Conn, remoteAddr string) error {
504 defer dontPanic(s.Logger)
505
506 if err := Handshake(conn); err != nil {
507 return err
508 }
509
510 buf := make([]byte, 1024)
511 // TODO: fix potential short read with io.ReadFull
512 readLen, err := conn.Read(buf)
513 if readLen < minTransactionLen {
514 return err
515 }
516 if err != nil {
517 return err
518 }
519
520 clientLogin, _, err := ReadTransaction(buf[:readLen])
521 if err != nil {
522 return err
523 }
524
525 c := s.NewClientConn(conn, remoteAddr)
526 defer c.Disconnect()
527
528 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
529 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
530 *c.Version = clientLogin.GetField(fieldVersion).Data
531
532 var login string
533 for _, char := range encodedLogin {
534 login += string(rune(255 - uint(char)))
535 }
536 if login == "" {
537 login = GuestAccount
538 }
539
540 // If authentication fails, send error reply and close connection
541 if !c.Authenticate(login, encodedPassword) {
542 t := c.NewErrReply(clientLogin, "Incorrect login.")
543 b, err := t.MarshalBinary()
544 if err != nil {
545 return err
546 }
547 if _, err := conn.Write(b); err != nil {
548 return err
549 }
550 return fmt.Errorf("incorrect login")
551 }
552
553 if clientLogin.GetField(fieldUserName).Data != nil {
554 c.UserName = clientLogin.GetField(fieldUserName).Data
555 }
556
557 if clientLogin.GetField(fieldUserIconID).Data != nil {
558 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
559 }
560
561 c.Account = c.Server.Accounts[login]
562
563 if c.Authorize(accessDisconUser) {
564 *c.Flags = []byte{0, 2}
565 }
566
567 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", remoteAddr)
568
569 s.outbox <- c.NewReply(clientLogin,
570 NewField(fieldVersion, []byte{0x00, 0xbe}),
571 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
572 NewField(fieldServerName, []byte(s.Config.Name)),
573 )
574
575 // Send user access privs so client UI knows how to behave
576 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
577
578 // Show agreement to client
579 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
580
581 // assume simplified hotline v1.2.3 login flow that does not require agreement
582 if *c.Version == nil {
583 c.Agreed = true
584
585 c.notifyOthers(
586 *NewTransaction(
587 tranNotifyChangeUser, nil,
588 NewField(fieldUserName, c.UserName),
589 NewField(fieldUserID, *c.ID),
590 NewField(fieldUserIconID, *c.Icon),
591 NewField(fieldUserFlags, *c.Flags),
592 ),
593 )
594 }
595
596 c.Server.Stats.LoginCount += 1
597
598 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
599 tranBuff := make([]byte, 0)
600 tReadlen := 0
601 // Infinite loop where take action on incoming client requests until the connection is closed
602 for {
603 buf = make([]byte, readBuffSize)
604 tranBuff = tranBuff[tReadlen:]
605
606 readLen, err := c.Connection.Read(buf)
607 if err != nil {
608 return err
609 }
610 tranBuff = append(tranBuff, buf[:readLen]...)
611
612 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
613 // into a slice of transactions
614 var transactions []Transaction
615 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
616 c.Server.Logger.Errorw("Error handling transaction", "err", err)
617 }
618
619 // iterate over all of the transactions that were parsed from the byte slice and handle them
620 for _, t := range transactions {
621 if err := c.handleTransaction(&t); err != nil {
622 c.Server.Logger.Errorw("Error handling transaction", "err", err)
623 }
624 }
625 }
626 }
627
628 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
629 // in the file transfer request payload, and the file transfer server will use it to map the request
630 // to a transfer
631 func (s *Server) NewTransactionRef() []byte {
632 transactionRef := make([]byte, 4)
633 rand.Read(transactionRef)
634
635 return transactionRef
636 }
637
638 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
639 s.mux.Lock()
640 defer s.mux.Unlock()
641
642 randID := make([]byte, 4)
643 rand.Read(randID)
644 data := binary.BigEndian.Uint32(randID[:])
645
646 s.PrivateChats[data] = &PrivateChat{
647 Subject: "",
648 ClientConn: make(map[uint16]*ClientConn),
649 }
650 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
651
652 return randID
653 }
654
655 const dlFldrActionSendFile = 1
656 const dlFldrActionResumeFile = 2
657 const dlFldrActionNextFile = 3
658
659 // handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
660 func (s *Server) handleFileTransfer(conn io.ReadWriteCloser) error {
661 defer func() {
662
663 if err := conn.Close(); err != nil {
664 s.Logger.Errorw("error closing connection", "error", err)
665 }
666 }()
667
668 defer dontPanic(s.Logger)
669
670 txBuf := make([]byte, 16)
671 if _, err := io.ReadFull(conn, txBuf); err != nil {
672 return err
673 }
674
675 var t transfer
676 if _, err := t.Write(txBuf); err != nil {
677 return err
678 }
679
680 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
681 defer func() {
682 s.mux.Lock()
683 delete(s.FileTransfers, transferRefNum)
684 s.mux.Unlock()
685 }()
686
687 s.mux.Lock()
688 fileTransfer, ok := s.FileTransfers[transferRefNum]
689 s.mux.Unlock()
690 if !ok {
691 return errors.New("invalid transaction ID")
692 }
693
694 switch fileTransfer.Type {
695 case FileDownload:
696 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
697 if err != nil {
698 return err
699 }
700
701 var dataOffset int64
702 if fileTransfer.fileResumeData != nil {
703 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
704 }
705
706 ffo, err := NewFlattenedFileObject(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName, dataOffset)
707 if err != nil {
708 return err
709 }
710
711 s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
712
713 if fileTransfer.options == nil {
714 // Start by sending flat file object to client
715 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
716 return err
717 }
718 }
719
720 file, err := FS.Open(fullFilePath)
721 if err != nil {
722 return err
723 }
724
725 sendBuffer := make([]byte, 1048576)
726 var totalSent int64
727 for {
728 var bytesRead int
729 if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF {
730 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
731 return err
732 }
733 break
734 }
735 if err != nil {
736 return err
737 }
738 totalSent += int64(bytesRead)
739
740 fileTransfer.BytesSent += bytesRead
741
742 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
743 return err
744 }
745 }
746 case FileUpload:
747 destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
748
749 var file *os.File
750
751 // A file upload has three possible cases:
752 // 1) Upload a new file
753 // 2) Resume a partially transferred file
754 // 3) Replace a fully uploaded file
755 // Unfortunately we have to infer which case applies by inspecting what is already on the file system
756
757 // 1) Check for existing file:
758 _, err := os.Stat(destinationFile)
759 if err == nil {
760 // If found, that means this upload is intended to replace the file
761 if err = os.Remove(destinationFile); err != nil {
762 return err
763 }
764 file, err = os.Create(destinationFile + incompleteFileSuffix)
765 }
766 if errors.Is(err, fs.ErrNotExist) {
767 // If not found, open or create a new incomplete file
768 file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
769 if err != nil {
770 return err
771 }
772 }
773
774 defer func() { _ = file.Close() }()
775
776 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
777
778 // TODO: replace io.Discard with a real file when ready to implement storing of resource fork data
779 if err := receiveFile(conn, file, io.Discard); err != nil {
780 return err
781 }
782
783 if err := os.Rename(destinationFile+".incomplete", destinationFile); err != nil {
784 return err
785 }
786
787 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
788 case FolderDownload:
789 // Folder Download flow:
790 // 1. Get filePath from the transfer
791 // 2. Iterate over files
792 // 3. For each file:
793 // Send file header to client
794 // The client can reply in 3 ways:
795 //
796 // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
797 // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
798 //
799 // 2. If download of a file is to be resumed:
800 // client sends:
801 // []byte{0x00, 0x02} // download folder action
802 // [2]byte // Resume data size
803 // []byte file resume data (see myField_FileResumeData)
804 //
805 // 3. Otherwise, download of the file is requested and client sends []byte{0x00, 0x01}
806 //
807 // When download is requested (case 2 or 3), server replies with:
808 // [4]byte - file size
809 // []byte - Flattened File Object
810 //
811 // After every file download, client could request next file with:
812 // []byte{0x00, 0x03}
813 //
814 // This notifies the server to send the next item header
815
816 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
817 if err != nil {
818 return err
819 }
820
821 basePathLen := len(fullFilePath)
822
823 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
824
825 nextAction := make([]byte, 2)
826 if _, err := io.ReadFull(conn, nextAction); err != nil {
827 return err
828 }
829
830 i := 0
831 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
832 if err != nil {
833 return err
834 }
835 i += 1
836 subPath := path[basePathLen+1:]
837 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
838
839 if i == 1 {
840 return nil
841 }
842
843 fileHeader := NewFileHeader(subPath, info.IsDir())
844
845 // Send the file header to client
846 if _, err := conn.Write(fileHeader.Payload()); err != nil {
847 s.Logger.Errorf("error sending file header: %v", err)
848 return err
849 }
850
851 // Read the client's Next Action request
852 if _, err := io.ReadFull(conn, nextAction); err != nil {
853 return err
854 }
855
856 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
857
858 var dataOffset int64
859
860 switch nextAction[1] {
861 case dlFldrActionResumeFile:
862 // client asked to resume this file
863 var frd FileResumeData
864 // get size of resumeData
865 if _, err := io.ReadFull(conn, nextAction); err != nil {
866 return err
867 }
868
869 resumeDataLen := binary.BigEndian.Uint16(nextAction)
870 resumeDataBytes := make([]byte, resumeDataLen)
871 if _, err := io.ReadFull(conn, resumeDataBytes); err != nil {
872 return err
873 }
874
875 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
876 return err
877 }
878 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
879 case dlFldrActionNextFile:
880 // client asked to skip this file
881 return nil
882 }
883
884 if info.IsDir() {
885 return nil
886 }
887
888 splitPath := strings.Split(path, "/")
889
890 ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), nil, []byte(info.Name()), dataOffset)
891 if err != nil {
892 return err
893 }
894 s.Logger.Infow("File download started",
895 "fileName", info.Name(),
896 "transactionRef", fileTransfer.ReferenceNumber,
897 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
898 )
899
900 // Send file size to client
901 if _, err := conn.Write(ffo.TransferSize()); err != nil {
902 s.Logger.Error(err)
903 return err
904 }
905
906 // Send ffo bytes to client
907 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
908 s.Logger.Error(err)
909 return err
910 }
911
912 file, err := FS.Open(path)
913 if err != nil {
914 return err
915 }
916
917 // // Copy N bytes from file to connection
918 // _, err = io.CopyN(conn, file, int64(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize[:])))
919 // if err != nil {
920 // return err
921 // }
922 // file.Close()
923 sendBuffer := make([]byte, 1048576)
924 var totalSent int64
925 for {
926 var bytesRead int
927 if bytesRead, err = file.ReadAt(sendBuffer, dataOffset+totalSent); err == io.EOF {
928 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
929 return err
930 }
931 break
932 }
933 if err != nil {
934 panic(err)
935 }
936 totalSent += int64(bytesRead)
937
938 fileTransfer.BytesSent += bytesRead
939
940 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
941 return err
942 }
943 }
944
945 // TODO: optionally send resource fork header and resource fork data
946
947 // Read the client's Next Action request. This is always 3, I think?
948 if _, err := io.ReadFull(conn, nextAction); err != nil {
949 return err
950 }
951
952 return nil
953 })
954
955 case FolderUpload:
956 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
957 if err != nil {
958 return err
959 }
960 s.Logger.Infow(
961 "Folder upload started",
962 "transactionRef", fileTransfer.ReferenceNumber,
963 "dstPath", dstPath,
964 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
965 "FolderItemCount", fileTransfer.FolderItemCount,
966 )
967
968 // Check if the target folder exists. If not, create it.
969 if _, err := FS.Stat(dstPath); os.IsNotExist(err) {
970 if err := FS.Mkdir(dstPath, 0777); err != nil {
971 return err
972 }
973 }
974
975 // Begin the folder upload flow by sending the "next file action" to client
976 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
977 return err
978 }
979
980 fileSize := make([]byte, 4)
981 readBuffer := make([]byte, 1024)
982
983 for i := 0; i < fileTransfer.ItemCount(); i++ {
984 // TODO: fix potential short read with io.ReadFull
985 _, err := conn.Read(readBuffer)
986 if err != nil {
987 return err
988 }
989 fu := readFolderUpload(readBuffer)
990
991 s.Logger.Infow(
992 "Folder upload continued",
993 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
994 "FormattedPath", fu.FormattedPath(),
995 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
996 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
997 )
998
999 if fu.IsFolder == [2]byte{0, 1} {
1000 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
1001 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
1002 return err
1003 }
1004 }
1005
1006 // Tell client to send next file
1007 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1008 return err
1009 }
1010 } else {
1011 nextAction := dlFldrActionSendFile
1012
1013 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
1014 _, err := os.Stat(dstPath + "/" + fu.FormattedPath())
1015 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1016 return err
1017 }
1018 if err == nil {
1019 nextAction = dlFldrActionNextFile
1020 }
1021
1022 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
1023 inccompleteFile, err := os.Stat(dstPath + "/" + fu.FormattedPath() + incompleteFileSuffix)
1024 if err != nil && !errors.Is(err, fs.ErrNotExist) {
1025 return err
1026 }
1027 if err == nil {
1028 nextAction = dlFldrActionResumeFile
1029 }
1030
1031 fmt.Printf("Next Action: %v\n", nextAction)
1032
1033 if _, err := conn.Write([]byte{0, uint8(nextAction)}); err != nil {
1034 return err
1035 }
1036
1037 switch nextAction {
1038 case dlFldrActionNextFile:
1039 continue
1040 case dlFldrActionResumeFile:
1041 offset := make([]byte, 4)
1042 binary.BigEndian.PutUint32(offset, uint32(inccompleteFile.Size()))
1043
1044 file, err := os.OpenFile(dstPath+"/"+fu.FormattedPath()+incompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
1045 if err != nil {
1046 return err
1047 }
1048
1049 fileResumeData := NewFileResumeData([]ForkInfoList{
1050 *NewForkInfoList(offset),
1051 })
1052
1053 b, _ := fileResumeData.BinaryMarshal()
1054
1055 bs := make([]byte, 2)
1056 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1057
1058 if _, err := conn.Write(append(bs, b...)); err != nil {
1059 return err
1060 }
1061
1062 if _, err := io.ReadFull(conn, fileSize); err != nil {
1063 return err
1064 }
1065
1066 if err := receiveFile(conn, file, ioutil.Discard); err != nil {
1067 s.Logger.Error(err)
1068 }
1069
1070 err = os.Rename(dstPath+"/"+fu.FormattedPath()+".incomplete", dstPath+"/"+fu.FormattedPath())
1071 if err != nil {
1072 return err
1073 }
1074
1075 case dlFldrActionSendFile:
1076 if _, err := conn.Read(fileSize); err != nil {
1077 return err
1078 }
1079
1080 filePath := dstPath + "/" + fu.FormattedPath()
1081 s.Logger.Infow("Starting file transfer", "path", filePath, "fileNum", i+1, "totalFiles", "zz", "fileSize", binary.BigEndian.Uint32(fileSize))
1082
1083 newFile, err := FS.Create(filePath + ".incomplete")
1084 if err != nil {
1085 return err
1086 }
1087
1088 if err := receiveFile(conn, newFile, ioutil.Discard); err != nil {
1089 s.Logger.Error(err)
1090 }
1091 _ = newFile.Close()
1092 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1093 return err
1094 }
1095 }
1096
1097 // Tell client to send next file
1098 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
1099 return err
1100 }
1101 }
1102 }
1103 s.Logger.Infof("Folder upload complete")
1104 }
1105
1106 return nil
1107 }
1108
1109 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
1110 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
1111 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
1112 for _, c := range unsortedClients {
1113 clients = append(clients, c)
1114 }
1115 sort.Sort(byClientID(clients))
1116 return clients
1117 }