]> git.r.bdr.sh - rbdr/mobius/blob - hotline/server.go
c5a29ba9ea19173b3499be0ab3e1ade4d7e49f95
[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/ioutil"
11 "log"
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 "golang.org/x/crypto/bcrypt"
25 "gopkg.in/yaml.v2"
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 []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.TransferFile(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.Connection.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); 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 TrackerPassID: make([]byte, 4),
191 }
192
193 ln, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
194 if err != nil {
195 return nil, err
196 }
197 server.APIListener = ln
198
199 if netPort != 0 {
200 netPort += 1
201 }
202
203 ln2, err := net.Listen("tcp", fmt.Sprintf("%s:%v", netInterface, netPort))
204 server.FileListener = ln2
205 if err != nil {
206 return nil, err
207 }
208
209 // generate a new random passID for tracker registration
210 if _, err := rand.Read(server.TrackerPassID); err != nil {
211 return nil, err
212 }
213
214 server.Logger.Debugw("Loading Agreement", "path", configDir+agreementFile)
215 if server.Agreement, err = os.ReadFile(configDir + agreementFile); err != nil {
216 return nil, err
217 }
218
219 if server.FlatNews, err = os.ReadFile(configDir + "MessageBoard.txt"); err != nil {
220 return nil, err
221 }
222
223 if err := server.loadThreadedNews(configDir + "ThreadedNews.yaml"); err != nil {
224 return nil, err
225 }
226
227 if err := server.loadConfig(configDir + "config.yaml"); err != nil {
228 return nil, err
229 }
230
231 if err := server.loadAccounts(configDir + "Users/"); err != nil {
232 return nil, err
233 }
234
235 server.Config.FileRoot = configDir + "Files/"
236
237 *server.NextGuestID = 1
238
239 if server.Config.EnableTrackerRegistration {
240 go func() {
241 for {
242 tr := TrackerRegistration{
243 Port: []byte{0x15, 0x7c},
244 UserCount: server.userCount(),
245 PassID: server.TrackerPassID,
246 Name: server.Config.Name,
247 Description: server.Config.Description,
248 }
249 for _, t := range server.Config.Trackers {
250 server.Logger.Infof("Registering with tracker %v", t)
251
252 if err := register(t, tr); err != nil {
253 server.Logger.Errorw("unable to register with tracker %v", "error", err)
254 }
255 }
256
257 time.Sleep(trackerUpdateFrequency * time.Second)
258 }
259 }()
260 }
261
262 // Start Client Keepalive go routine
263 go server.keepaliveHandler()
264
265 return &server, nil
266 }
267
268 func (s *Server) userCount() int {
269 s.mux.Lock()
270 defer s.mux.Unlock()
271
272 return len(s.Clients)
273 }
274
275 func (s *Server) keepaliveHandler() {
276 for {
277 time.Sleep(idleCheckInterval * time.Second)
278 s.mux.Lock()
279
280 for _, c := range s.Clients {
281 c.IdleTime += idleCheckInterval
282 if c.IdleTime > userIdleSeconds && !c.Idle {
283 c.Idle = true
284
285 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
286 flagBitmap.SetBit(flagBitmap, userFlagAway, 1)
287 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
288
289 c.sendAll(
290 tranNotifyChangeUser,
291 NewField(fieldUserID, *c.ID),
292 NewField(fieldUserFlags, *c.Flags),
293 NewField(fieldUserName, c.UserName),
294 NewField(fieldUserIconID, *c.Icon),
295 )
296 }
297 }
298 s.mux.Unlock()
299 }
300 }
301
302 func (s *Server) writeThreadedNews() error {
303 s.mux.Lock()
304 defer s.mux.Unlock()
305
306 out, err := yaml.Marshal(s.ThreadedNews)
307 if err != nil {
308 return err
309 }
310 err = ioutil.WriteFile(
311 s.ConfigDir+"ThreadedNews.yaml",
312 out,
313 0666,
314 )
315 return err
316 }
317
318 func (s *Server) NewClientConn(conn net.Conn) *ClientConn {
319 s.mux.Lock()
320 defer s.mux.Unlock()
321
322 clientConn := &ClientConn{
323 ID: &[]byte{0, 0},
324 Icon: &[]byte{0, 0},
325 Flags: &[]byte{0, 0},
326 UserName: []byte{},
327 Connection: conn,
328 Server: s,
329 Version: &[]byte{},
330 AutoReply: &[]byte{},
331 Transfers: make(map[int][]*FileTransfer),
332 Agreed: false,
333 }
334 *s.NextGuestID++
335 ID := *s.NextGuestID
336
337 binary.BigEndian.PutUint16(*clientConn.ID, ID)
338 s.Clients[ID] = clientConn
339
340 return clientConn
341 }
342
343 // NewUser creates a new user account entry in the server map and config file
344 func (s *Server) NewUser(login, name, password string, access []byte) error {
345 s.mux.Lock()
346 defer s.mux.Unlock()
347
348 account := Account{
349 Login: login,
350 Name: name,
351 Password: hashAndSalt([]byte(password)),
352 Access: &access,
353 }
354 out, err := yaml.Marshal(&account)
355 if err != nil {
356 return err
357 }
358 s.Accounts[login] = &account
359
360 return ioutil.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
361 }
362
363 // DeleteUser deletes the user account
364 func (s *Server) DeleteUser(login string) error {
365 s.mux.Lock()
366 defer s.mux.Unlock()
367
368 delete(s.Accounts, login)
369
370 return os.Remove(s.ConfigDir + "Users/" + login + ".yaml")
371 }
372
373 func (s *Server) connectedUsers() []Field {
374 s.mux.Lock()
375 defer s.mux.Unlock()
376
377 var connectedUsers []Field
378 for _, c := range sortedClients(s.Clients) {
379 if c.Agreed == false {
380 continue
381 }
382 user := User{
383 ID: *c.ID,
384 Icon: *c.Icon,
385 Flags: *c.Flags,
386 Name: string(c.UserName),
387 }
388 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
389 }
390 return connectedUsers
391 }
392
393 // loadThreadedNews loads the threaded news data from disk
394 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
395 fh, err := os.Open(threadedNewsPath)
396 if err != nil {
397 return err
398 }
399 decoder := yaml.NewDecoder(fh)
400 decoder.SetStrict(true)
401
402 return decoder.Decode(s.ThreadedNews)
403 }
404
405 // loadAccounts loads account data from disk
406 func (s *Server) loadAccounts(userDir string) error {
407 matches, err := filepath.Glob(path.Join(userDir, "*.yaml"))
408 if err != nil {
409 return err
410 }
411
412 if len(matches) == 0 {
413 return errors.New("no user accounts found in " + userDir)
414 }
415
416 for _, file := range matches {
417 fh, err := FS.Open(file)
418 if err != nil {
419 return err
420 }
421
422 account := Account{}
423 decoder := yaml.NewDecoder(fh)
424 decoder.SetStrict(true)
425 if err := decoder.Decode(&account); err != nil {
426 return err
427 }
428
429 s.Accounts[account.Login] = &account
430 }
431 return nil
432 }
433
434 func (s *Server) loadConfig(path string) error {
435 fh, err := FS.Open(path)
436 if err != nil {
437 return err
438 }
439
440 decoder := yaml.NewDecoder(fh)
441 decoder.SetStrict(true)
442 err = decoder.Decode(s.Config)
443 if err != nil {
444 return err
445 }
446 return nil
447 }
448
449 const (
450 minTransactionLen = 22 // minimum length of any transaction
451 )
452
453 // handleNewConnection takes a new net.Conn and performs the initial login sequence
454 func (s *Server) handleNewConnection(conn net.Conn) error {
455 handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length
456 if _, err := conn.Read(handshakeBuf); err != nil {
457 return err
458 }
459 if err := Handshake(conn, handshakeBuf[:12]); err != nil {
460 return err
461 }
462
463 buf := make([]byte, 1024)
464 readLen, err := conn.Read(buf)
465 if readLen < minTransactionLen {
466 return err
467 }
468 if err != nil {
469 return err
470 }
471
472 clientLogin, _, err := ReadTransaction(buf[:readLen])
473 if err != nil {
474 return err
475 }
476
477 c := s.NewClientConn(conn)
478 defer c.Disconnect()
479 defer func() {
480 if r := recover(); r != nil {
481 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
482 c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
483 c.Disconnect()
484 }
485 }()
486
487 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
488 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
489 *c.Version = clientLogin.GetField(fieldVersion).Data
490
491 var login string
492 for _, char := range encodedLogin {
493 login += string(rune(255 - uint(char)))
494 }
495 if login == "" {
496 login = GuestAccount
497 }
498
499 // If authentication fails, send error reply and close connection
500 if !c.Authenticate(login, encodedPassword) {
501 t := c.NewErrReply(clientLogin, "Incorrect login.")
502 b, err := t.MarshalBinary()
503 if err != nil {
504 return err
505 }
506 if _, err := conn.Write(b); err != nil {
507 return err
508 }
509 return fmt.Errorf("incorrect login")
510 }
511
512 if clientLogin.GetField(fieldUserName).Data != nil {
513 c.UserName = clientLogin.GetField(fieldUserName).Data
514 }
515
516 if clientLogin.GetField(fieldUserIconID).Data != nil {
517 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
518 }
519
520 c.Account = c.Server.Accounts[login]
521
522 if c.Authorize(accessDisconUser) {
523 *c.Flags = []byte{0, 2}
524 }
525
526 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String())
527
528 s.outbox <- c.NewReply(clientLogin,
529 NewField(fieldVersion, []byte{0x00, 0xbe}),
530 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
531 NewField(fieldServerName, []byte(s.Config.Name)),
532 )
533
534 // Send user access privs so client UI knows how to behave
535 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
536
537 // Show agreement to client
538 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
539
540 // assume simplified hotline v1.2.3 login flow that does not require agreement
541 if *c.Version == nil {
542 c.Agreed = true
543 if _, err := c.notifyNewUserHasJoined(); err != nil {
544 return err
545 }
546 }
547
548 c.Server.Stats.LoginCount += 1
549
550 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
551 tranBuff := make([]byte, 0)
552 tReadlen := 0
553 // Infinite loop where take action on incoming client requests until the connection is closed
554 for {
555 buf = make([]byte, readBuffSize)
556 tranBuff = tranBuff[tReadlen:]
557
558 readLen, err := c.Connection.Read(buf)
559 if err != nil {
560 return err
561 }
562 tranBuff = append(tranBuff, buf[:readLen]...)
563
564 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
565 // into a slice of transactions
566 var transactions []Transaction
567 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
568 c.Server.Logger.Errorw("Error handling transaction", "err", err)
569 }
570
571 // iterate over all of the transactions that were parsed from the byte slice and handle them
572 for _, t := range transactions {
573 if err := c.handleTransaction(&t); err != nil {
574 c.Server.Logger.Errorw("Error handling transaction", "err", err)
575 }
576 }
577 }
578 }
579
580 func hashAndSalt(pwd []byte) string {
581 // Use GenerateFromPassword to hash & salt pwd.
582 // MinCost is just an integer constant provided by the bcrypt
583 // package along with DefaultCost & MaxCost.
584 // The cost can be any value you want provided it isn't lower
585 // than the MinCost (4)
586 hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
587 if err != nil {
588 log.Println(err)
589 }
590 // GenerateFromPassword returns a byte slice so we need to
591 // convert the bytes to a string and return it
592 return string(hash)
593 }
594
595 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
596 // in the file transfer request payload, and the file transfer server will use it to map the request
597 // to a transfer
598 func (s *Server) NewTransactionRef() []byte {
599 transactionRef := make([]byte, 4)
600 rand.Read(transactionRef)
601
602 return transactionRef
603 }
604
605 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
606 s.mux.Lock()
607 defer s.mux.Unlock()
608
609 randID := make([]byte, 4)
610 rand.Read(randID)
611 data := binary.BigEndian.Uint32(randID[:])
612
613 s.PrivateChats[data] = &PrivateChat{
614 Subject: "",
615 ClientConn: make(map[uint16]*ClientConn),
616 }
617 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
618
619 return randID
620 }
621
622 const dlFldrActionSendFile = 1
623 const dlFldrActionResumeFile = 2
624 const dlFldrActionNextFile = 3
625
626 func (s *Server) TransferFile(conn net.Conn) error {
627 defer func() { _ = conn.Close() }()
628
629 buf := make([]byte, 1024)
630 if _, err := conn.Read(buf); err != nil {
631 return err
632 }
633
634 var t transfer
635 _, err := t.Write(buf[:16])
636 if err != nil {
637 return err
638 }
639
640 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
641 fileTransfer := s.FileTransfers[transferRefNum]
642
643 switch fileTransfer.Type {
644 case FileDownload:
645 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
646 if err != nil {
647 return err
648 }
649
650 ffo, err := NewFlattenedFileObject(
651 s.Config.FileRoot,
652 fileTransfer.FilePath,
653 fileTransfer.FileName,
654 )
655 if err != nil {
656 return err
657 }
658
659 s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String())
660
661 // Start by sending flat file object to client
662 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
663 return err
664 }
665
666 file, err := FS.Open(fullFilePath)
667 if err != nil {
668 return err
669 }
670
671 sendBuffer := make([]byte, 1048576)
672 for {
673 var bytesRead int
674 if bytesRead, err = file.Read(sendBuffer); err == io.EOF {
675 break
676 }
677
678 fileTransfer.BytesSent += bytesRead
679
680 delete(s.FileTransfers, transferRefNum)
681
682 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
683 return err
684 }
685 }
686 case FileUpload:
687 if _, err := conn.Read(buf); err != nil {
688 return err
689 }
690
691 ffo := ReadFlattenedFileObject(buf)
692 payloadLen := len(ffo.BinaryMarshal())
693 fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
694
695 destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
696 s.Logger.Infow(
697 "File upload started",
698 "transactionRef", fileTransfer.ReferenceNumber,
699 "RemoteAddr", conn.RemoteAddr().String(),
700 "size", fileSize,
701 "dstFile", destinationFile,
702 )
703
704 newFile, err := os.Create(destinationFile)
705 if err != nil {
706 return err
707 }
708
709 defer func() { _ = newFile.Close() }()
710
711 const buffSize = 1024
712
713 if _, err := newFile.Write(buf[payloadLen:]); err != nil {
714 return err
715 }
716 receivedBytes := buffSize - payloadLen
717
718 for {
719 if (fileSize - receivedBytes) < buffSize {
720 s.Logger.Infow(
721 "File upload complete",
722 "transactionRef", fileTransfer.ReferenceNumber,
723 "RemoteAddr", conn.RemoteAddr().String(),
724 "size", fileSize,
725 "dstFile", destinationFile,
726 )
727
728 if _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)); err != nil {
729 return fmt.Errorf("file transfer failed: %s", err)
730 }
731 return nil
732 }
733
734 // Copy N bytes from conn to upload file
735 n, err := io.CopyN(newFile, conn, buffSize)
736 if err != nil {
737 return err
738 }
739 receivedBytes += int(n)
740 }
741 case FolderDownload:
742 // Folder Download flow:
743 // 1. Get filePath from the transfer
744 // 2. Iterate over files
745 // 3. For each file:
746 // Send file header to client
747 // The client can reply in 3 ways:
748 //
749 // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
750 // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
751 //
752 // 2. If download of a file is to be resumed:
753 // client sends:
754 // []byte{0x00, 0x02} // download folder action
755 // [2]byte // Resume data size
756 // []byte file resume data (see myField_FileResumeData)
757 //
758 // 3. Otherwise download of the file is requested and client sends []byte{0x00, 0x01}
759 //
760 // When download is requested (case 2 or 3), server replies with:
761 // [4]byte - file size
762 // []byte - Flattened File Object
763 //
764 // After every file download, client could request next file with:
765 // []byte{0x00, 0x03}
766 //
767 // This notifies the server to send the next item header
768
769 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
770 if err != nil {
771 return err
772 }
773
774 basePathLen := len(fullFilePath)
775
776 readBuffer := make([]byte, 1024)
777
778 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr())
779
780 i := 0
781 _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error {
782 i += 1
783 subPath := path[basePathLen:]
784 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
785
786 fileHeader := NewFileHeader(subPath, info.IsDir())
787
788 if i == 1 {
789 return nil
790 }
791
792 // Send the file header to client
793 if _, err := conn.Write(fileHeader.Payload()); err != nil {
794 s.Logger.Errorf("error sending file header: %v", err)
795 return err
796 }
797
798 // Read the client's Next Action request
799 //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
800 if _, err := conn.Read(readBuffer); err != nil {
801 return err
802 }
803
804 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", readBuffer[0:2]))
805
806 if info.IsDir() {
807 return nil
808 }
809
810 splitPath := strings.Split(path, "/")
811
812 ffo, err := NewFlattenedFileObject(
813 strings.Join(splitPath[:len(splitPath)-1], "/"),
814 nil,
815 []byte(info.Name()),
816 )
817 if err != nil {
818 return err
819 }
820 s.Logger.Infow("File download started",
821 "fileName", info.Name(),
822 "transactionRef", fileTransfer.ReferenceNumber,
823 "RemoteAddr", conn.RemoteAddr().String(),
824 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
825 )
826
827 // Send file size to client
828 if _, err := conn.Write(ffo.TransferSize()); err != nil {
829 s.Logger.Error(err)
830 return err
831 }
832
833 // Send file bytes to client
834 if _, err := conn.Write(ffo.BinaryMarshal()); err != nil {
835 s.Logger.Error(err)
836 return err
837 }
838
839 file, err := FS.Open(path)
840 if err != nil {
841 return err
842 }
843
844 sendBuffer := make([]byte, 1048576)
845 totalBytesSent := len(ffo.BinaryMarshal())
846
847 for {
848 bytesRead, err := file.Read(sendBuffer)
849 if err == io.EOF {
850 // Read the client's Next Action request
851 //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
852 if _, err := conn.Read(readBuffer); err != nil {
853 s.Logger.Errorf("error reading next action: %v", err)
854 return err
855 }
856 break
857 }
858
859 sentBytes, readErr := conn.Write(sendBuffer[:bytesRead])
860 totalBytesSent += sentBytes
861 if readErr != nil {
862 return err
863 }
864 }
865 return nil
866 })
867
868 case FolderUpload:
869 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
870 if err != nil {
871 return err
872 }
873 s.Logger.Infow(
874 "Folder upload started",
875 "transactionRef", fileTransfer.ReferenceNumber,
876 "RemoteAddr", conn.RemoteAddr().String(),
877 "dstPath", dstPath,
878 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
879 "FolderItemCount", fileTransfer.FolderItemCount,
880 )
881
882 // Check if the target folder exists. If not, create it.
883 if _, err := FS.Stat(dstPath); os.IsNotExist(err) {
884 s.Logger.Infow("Creating target path", "dstPath", dstPath)
885 if err := FS.Mkdir(dstPath, 0777); err != nil {
886 s.Logger.Error(err)
887 }
888 }
889
890 readBuffer := make([]byte, 1024)
891
892 // Begin the folder upload flow by sending the "next file action" to client
893 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
894 return err
895 }
896
897 fileSize := make([]byte, 4)
898 itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount)
899
900 for i := uint16(0); i < itemCount; i++ {
901 if _, err := conn.Read(readBuffer); err != nil {
902 return err
903 }
904 fu := readFolderUpload(readBuffer)
905
906 s.Logger.Infow(
907 "Folder upload continued",
908 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
909 "RemoteAddr", conn.RemoteAddr().String(),
910 "FormattedPath", fu.FormattedPath(),
911 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
912 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
913 )
914
915 if fu.IsFolder == [2]byte{0, 1} {
916 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
917 s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
918 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
919 s.Logger.Error(err)
920 }
921 }
922
923 // Tell client to send next file
924 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
925 s.Logger.Error(err)
926 return err
927 }
928 } else {
929 // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
930 // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
931 // Send dlFldrAction_SendFile to client to begin transfer
932 if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil {
933 return err
934 }
935
936 if _, err := conn.Read(fileSize); err != nil {
937 fmt.Println("Error reading:", err.Error()) // TODO: handle
938 }
939
940 s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize)
941
942 if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil {
943 s.Logger.Error(err)
944 }
945
946 // Tell client to send next file
947 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
948 s.Logger.Error(err)
949 return err
950 }
951
952 // Client sends "MACR" after the file. Read and discard.
953 // TODO: This doesn't seem to be documented. What is this? Maybe resource fork?
954 if _, err := conn.Read(readBuffer); err != nil {
955 return err
956 }
957 }
958 }
959 s.Logger.Infof("Folder upload complete")
960 }
961
962 return nil
963 }
964
965 func transferFile(conn net.Conn, dst string) error {
966 const buffSize = 1024
967 buf := make([]byte, buffSize)
968
969 // Read first chunk of bytes from conn; this will be the Flat File Object and initial chunk of file bytes
970 if _, err := conn.Read(buf); err != nil {
971 return err
972 }
973 ffo := ReadFlattenedFileObject(buf)
974 payloadLen := len(ffo.BinaryMarshal())
975 fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
976
977 newFile, err := os.Create(dst)
978 if err != nil {
979 return err
980 }
981 defer func() { _ = newFile.Close() }()
982 if _, err := newFile.Write(buf[payloadLen:]); err != nil {
983 return err
984 }
985 receivedBytes := buffSize - payloadLen
986
987 for {
988 if (fileSize - receivedBytes) < buffSize {
989 _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes))
990 return err
991 }
992
993 // Copy N bytes from conn to upload file
994 n, err := io.CopyN(newFile, conn, buffSize)
995 if err != nil {
996 return err
997 }
998 receivedBytes += int(n)
999 }
1000 }
1001
1002 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
1003 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
1004 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
1005 for _, c := range unsortedClients {
1006 clients = append(clients, c)
1007 }
1008 sort.Sort(byClientID(clients))
1009 return clients
1010 }