]> git.r.bdr.sh - rbdr/mobius/blob - hotline/server.go
Move code to hotline dir
[rbdr/mobius] / hotline / server.go
1 package hotline
2
3 import (
4 "bytes"
5 "context"
6 "encoding/binary"
7 "errors"
8 "fmt"
9 "go.uber.org/zap"
10 "io"
11 "io/ioutil"
12 "log"
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 "golang.org/x/crypto/bcrypt"
26 "gopkg.in/yaml.v2"
27 )
28
29 const (
30 userIdleSeconds = 300 // time in seconds before an inactive user is marked idle
31 idleCheckInterval = 10 // time in seconds to check for idle users
32 trackerUpdateFrequency = 300 // time in seconds between tracker re-registration
33 )
34
35 type Server struct {
36 Interface string
37 Port int
38 Accounts map[string]*Account
39 Agreement []byte
40 Clients map[uint16]*ClientConn
41 FlatNews []byte
42 ThreadedNews *ThreadedNews
43 FileTransfers map[uint32]*FileTransfer
44 Config *Config
45 ConfigDir string
46 Logger *zap.SugaredLogger
47 PrivateChats map[uint32]*PrivateChat
48 NextGuestID *uint16
49 TrackerPassID []byte
50 Stats *Stats
51
52 APIListener net.Listener
53 FileListener net.Listener
54
55 newsReader io.Reader
56 newsWriter io.WriteCloser
57
58 outbox chan Transaction
59
60 mux sync.Mutex
61 flatNewsMux sync.Mutex
62 }
63
64 type PrivateChat struct {
65 Subject string
66 ClientConn map[uint16]*ClientConn
67 }
68
69 func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
70 s.Logger.Infow("Hotline server started", "version", VERSION)
71 var wg sync.WaitGroup
72
73 wg.Add(1)
74 go func() { s.Logger.Fatal(s.Serve(ctx, cancelRoot, s.APIListener)) }()
75
76 wg.Add(1)
77 go func() { s.Logger.Fatal(s.ServeFileTransfers(s.FileListener)) }()
78
79 wg.Wait()
80
81 return nil
82 }
83
84 func (s *Server) APIPort() int {
85 return s.APIListener.Addr().(*net.TCPAddr).Port
86 }
87
88 func (s *Server) ServeFileTransfers(ln net.Listener) error {
89 s.Logger.Infow("Hotline file transfer server started", "Addr", fmt.Sprintf(":%v", s.Port+1))
90
91 for {
92 conn, err := ln.Accept()
93 if err != nil {
94 return err
95 }
96
97 go func() {
98 if err := s.TransferFile(conn); err != nil {
99 s.Logger.Errorw("file transfer error", "reason", err)
100 }
101 }()
102 }
103 }
104
105 func (s *Server) sendTransaction(t Transaction) error {
106 requestNum := binary.BigEndian.Uint16(t.Type)
107 clientID, err := byteToInt(*t.clientID)
108 if err != nil {
109 return err
110 }
111
112 s.mux.Lock()
113 client := s.Clients[uint16(clientID)]
114 s.mux.Unlock()
115 if client == nil {
116 return errors.New("invalid client")
117 }
118 userName := string(*client.UserName)
119 login := client.Account.Login
120
121 handler := TransactionHandlers[requestNum]
122
123 var n int
124 if n, err = client.Connection.Write(t.Payload()); err != nil {
125 return err
126 }
127 s.Logger.Debugw("Sent Transaction",
128 "name", userName,
129 "login", login,
130 "IsReply", t.IsReply,
131 "type", handler.Name,
132 "sentBytes", n,
133 "remoteAddr", client.Connection.RemoteAddr(),
134 )
135 return nil
136 }
137
138 func (s *Server) Serve(ctx context.Context, cancelRoot context.CancelFunc, ln net.Listener) error {
139 s.Logger.Infow("Hotline server started", "Addr", fmt.Sprintf(":%v", s.Port))
140
141 for {
142 conn, err := ln.Accept()
143 if err != nil {
144 s.Logger.Errorw("error accepting connection", "err", err)
145 }
146
147 go func() {
148 for {
149 t := <-s.outbox
150 go func() {
151 if err := s.sendTransaction(t); err != nil {
152 s.Logger.Errorw("error sending transaction", "err", err)
153 }
154 }()
155 }
156 }()
157 go func() {
158 if err := s.handleNewConnection(conn); err != nil {
159 if err == io.EOF {
160 s.Logger.Infow("Client disconnected", "RemoteAddr", conn.RemoteAddr())
161 } else {
162 s.Logger.Errorw("error serving request", "RemoteAddr", conn.RemoteAddr(), "err", err)
163 }
164 }
165 }()
166 }
167 }
168
169 const (
170 agreementFile = "Agreement.txt"
171 messageBoardFile = "MessageBoard.txt"
172 threadedNewsFile = "ThreadedNews.yaml"
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 IdleTime: new(int),
331 AutoReply: &[]byte{},
332 Transfers: make(map[int][]*FileTransfer),
333 }
334 *s.NextGuestID++
335 ID := *s.NextGuestID
336
337 *clientConn.IdleTime = 0
338
339 binary.BigEndian.PutUint16(*clientConn.ID, ID)
340 s.Clients[ID] = clientConn
341
342 return clientConn
343 }
344
345 // NewUser creates a new user account entry in the server map and config file
346 func (s *Server) NewUser(login, name, password string, access []byte) error {
347 s.mux.Lock()
348 defer s.mux.Unlock()
349
350 account := Account{
351 Login: login,
352 Name: name,
353 Password: hashAndSalt([]byte(password)),
354 Access: &access,
355 }
356 out, err := yaml.Marshal(&account)
357 if err != nil {
358 return err
359 }
360 s.Accounts[login] = &account
361
362 return ioutil.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
363 }
364
365 // DeleteUser deletes the user account
366 func (s *Server) DeleteUser(login string) error {
367 s.mux.Lock()
368 defer s.mux.Unlock()
369
370 delete(s.Accounts, login)
371
372 return os.Remove(s.ConfigDir + "Users/" + login + ".yaml")
373 }
374
375 func (s *Server) connectedUsers() []Field {
376 s.mux.Lock()
377 defer s.mux.Unlock()
378
379 var connectedUsers []Field
380 for _, c := range s.Clients {
381 user := User{
382 ID: *c.ID,
383 Icon: *c.Icon,
384 Flags: *c.Flags,
385 Name: string(*c.UserName),
386 }
387 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
388 }
389 return connectedUsers
390 }
391
392 // loadThreadedNews loads the threaded news data from disk
393 func (s *Server) loadThreadedNews(threadedNewsPath string) error {
394 fh, err := os.Open(threadedNewsPath)
395 if err != nil {
396 return err
397 }
398 decoder := yaml.NewDecoder(fh)
399 decoder.SetStrict(true)
400
401 return decoder.Decode(s.ThreadedNews)
402 }
403
404 // loadAccounts loads account data from disk
405 func (s *Server) loadAccounts(userDir string) error {
406 matches, err := filepath.Glob(path.Join(userDir, "*.yaml"))
407 if err != nil {
408 return err
409 }
410
411 if len(matches) == 0 {
412 return errors.New("no user accounts found in " + userDir)
413 }
414
415 for _, file := range matches {
416 fh, err := os.Open(file)
417 if err != nil {
418 return err
419 }
420
421 account := Account{}
422 decoder := yaml.NewDecoder(fh)
423 decoder.SetStrict(true)
424 if err := decoder.Decode(&account); err != nil {
425 return err
426 }
427
428 s.Accounts[account.Login] = &account
429 }
430 return nil
431 }
432
433 func (s *Server) loadConfig(path string) error {
434 fh, err := os.Open(path)
435 if err != nil {
436 return err
437 }
438
439 decoder := yaml.NewDecoder(fh)
440 decoder.SetStrict(true)
441 err = decoder.Decode(s.Config)
442 if err != nil {
443 return err
444 }
445 return nil
446 }
447
448 const (
449 minTransactionLen = 22 // minimum length of any transaction
450 )
451
452 // handleNewConnection takes a new net.Conn and performs the initial login sequence
453 func (s *Server) handleNewConnection(conn net.Conn) error {
454 handshakeBuf := make([]byte, 12) // handshakes are always 12 bytes in length
455 if _, err := conn.Read(handshakeBuf); err != nil {
456 return err
457 }
458 if err := Handshake(conn, handshakeBuf[:12]); err != nil {
459 return err
460 }
461
462 buf := make([]byte, 1024)
463 readLen, err := conn.Read(buf)
464 if readLen < minTransactionLen {
465 return err
466 }
467 if err != nil {
468 return err
469 }
470
471 clientLogin, _, err := ReadTransaction(buf[:readLen])
472 if err != nil {
473 return err
474 }
475
476 c := s.NewClientConn(conn)
477 defer c.Disconnect()
478 defer func() {
479 if r := recover(); r != nil {
480 fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
481 c.Server.Logger.Errorw("PANIC", "err", r, "trace", string(debug.Stack()))
482 c.Disconnect()
483 }
484 }()
485
486 encodedLogin := clientLogin.GetField(fieldUserLogin).Data
487 encodedPassword := clientLogin.GetField(fieldUserPassword).Data
488 *c.Version = clientLogin.GetField(fieldVersion).Data
489
490 var login string
491 for _, char := range encodedLogin {
492 login += string(rune(255 - uint(char)))
493 }
494 if login == "" {
495 login = GuestAccount
496 }
497
498 // If authentication fails, send error reply and close connection
499 if !c.Authenticate(login, encodedPassword) {
500 rep := c.NewErrReply(clientLogin, "Incorrect login.")
501 if _, err := conn.Write(rep.Payload()); err != nil {
502 return err
503 }
504 return fmt.Errorf("incorrect login")
505 }
506
507 if clientLogin.GetField(fieldUserName).Data != nil {
508 *c.UserName = clientLogin.GetField(fieldUserName).Data
509 }
510
511 if clientLogin.GetField(fieldUserIconID).Data != nil {
512 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
513 }
514
515 c.Account = c.Server.Accounts[login]
516
517 if c.Authorize(accessDisconUser) {
518 *c.Flags = []byte{0, 2}
519 }
520
521 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String())
522
523 s.outbox <- c.NewReply(clientLogin,
524 NewField(fieldVersion, []byte{0x00, 0xbe}),
525 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
526 NewField(fieldServerName, []byte(s.Config.Name)),
527 )
528
529 // Send user access privs so client UI knows how to behave
530 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
531
532 // Show agreement to client
533 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
534
535 if _, err := c.notifyNewUserHasJoined(); err != nil {
536 return err
537 }
538 c.Server.Stats.LoginCount += 1
539
540 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
541 const maxTranSize = 1024000
542 tranBuff := make([]byte, 0)
543 tReadlen := 0
544 // Infinite loop where take action on incoming client requests until the connection is closed
545 for {
546 buf = make([]byte, readBuffSize)
547 tranBuff = tranBuff[tReadlen:]
548
549 readLen, err := c.Connection.Read(buf)
550 if err != nil {
551 return err
552 }
553 tranBuff = append(tranBuff, buf[:readLen]...)
554
555 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
556 // into a slice of transactions
557 var transactions []Transaction
558 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
559 c.Server.Logger.Errorw("Error handling transaction", "err", err)
560 }
561
562 // iterate over all of the transactions that were parsed from the byte slice and handle them
563 for _, t := range transactions {
564 if err := c.handleTransaction(&t); err != nil {
565 c.Server.Logger.Errorw("Error handling transaction", "err", err)
566 }
567 }
568 }
569 }
570
571 func hashAndSalt(pwd []byte) string {
572 // Use GenerateFromPassword to hash & salt pwd.
573 // MinCost is just an integer constant provided by the bcrypt
574 // package along with DefaultCost & MaxCost.
575 // The cost can be any value you want provided it isn't lower
576 // than the MinCost (4)
577 hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
578 if err != nil {
579 log.Println(err)
580 }
581 // GenerateFromPassword returns a byte slice so we need to
582 // convert the bytes to a string and return it
583 return string(hash)
584 }
585
586 // NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
587 // in the file transfer request payload, and the file transfer server will use it to map the request
588 // to a transfer
589 func (s *Server) NewTransactionRef() []byte {
590 transactionRef := make([]byte, 4)
591 rand.Read(transactionRef)
592
593 return transactionRef
594 }
595
596 func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
597 s.mux.Lock()
598 defer s.mux.Unlock()
599
600 randID := make([]byte, 4)
601 rand.Read(randID)
602 data := binary.BigEndian.Uint32(randID[:])
603
604 s.PrivateChats[data] = &PrivateChat{
605 Subject: "",
606 ClientConn: make(map[uint16]*ClientConn),
607 }
608 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
609
610 return randID
611 }
612
613 const dlFldrActionSendFile = 1
614 const dlFldrActionResumeFile = 2
615 const dlFldrActionNextFile = 3
616
617 func (s *Server) TransferFile(conn net.Conn) error {
618 defer func() { _ = conn.Close() }()
619
620 buf := make([]byte, 1024)
621 if _, err := conn.Read(buf); err != nil {
622 return err
623 }
624
625 t, err := NewReadTransfer(buf)
626 if err != nil {
627 return err
628 }
629
630 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
631 fileTransfer := s.FileTransfers[transferRefNum]
632
633 switch fileTransfer.Type {
634 case FileDownload:
635 fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+string(fileTransfer.FilePath), string(fileTransfer.FileName))
636
637 ffo, err := NewFlattenedFileObject(
638 s.Config.FileRoot+string(fileTransfer.FilePath),
639 string(fileTransfer.FileName),
640 )
641 if err != nil {
642 return err
643 }
644
645 s.Logger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr().String())
646
647 // Start by sending flat file object to client
648 if _, err := conn.Write(ffo.Payload()); err != nil {
649 return err
650 }
651
652 file, err := os.Open(fullFilePath)
653 if err != nil {
654 return err
655 }
656
657 sendBuffer := make([]byte, 1048576)
658 for {
659 var bytesRead int
660 if bytesRead, err = file.Read(sendBuffer); err == io.EOF {
661 break
662 }
663
664 fileTransfer.BytesSent += bytesRead
665
666 delete(s.FileTransfers, transferRefNum)
667
668 if _, err := conn.Write(sendBuffer[:bytesRead]); err != nil {
669 return err
670 }
671 }
672 case FileUpload:
673 if _, err := conn.Read(buf); err != nil {
674 return err
675 }
676
677 ffo := ReadFlattenedFileObject(buf)
678 payloadLen := len(ffo.Payload())
679 fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
680
681 destinationFile := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
682 s.Logger.Infow(
683 "File upload started",
684 "transactionRef", fileTransfer.ReferenceNumber,
685 "RemoteAddr", conn.RemoteAddr().String(),
686 "size", fileSize,
687 "dstFile", destinationFile,
688 )
689
690 newFile, err := os.Create(destinationFile)
691 if err != nil {
692 return err
693 }
694
695 defer func() { _ = newFile.Close() }()
696
697 const buffSize = 1024
698
699 if _, err := newFile.Write(buf[payloadLen:]); err != nil {
700 return err
701 }
702 receivedBytes := buffSize - payloadLen
703
704 for {
705 if (fileSize - receivedBytes) < buffSize {
706 s.Logger.Infow(
707 "File upload complete",
708 "transactionRef", fileTransfer.ReferenceNumber,
709 "RemoteAddr", conn.RemoteAddr().String(),
710 "size", fileSize,
711 "dstFile", destinationFile,
712 )
713
714 if _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes)); err != nil {
715 return fmt.Errorf("file transfer failed: %s", err)
716 }
717 return nil
718 }
719
720 // Copy N bytes from conn to upload file
721 n, err := io.CopyN(newFile, conn, buffSize)
722 if err != nil {
723 return err
724 }
725 receivedBytes += int(n)
726 }
727 case FolderDownload:
728 // Folder Download flow:
729 // 1. Get filePath from the Transfer
730 // 2. Iterate over files
731 // 3. For each file:
732 // Send file header to client
733 // The client can reply in 3 ways:
734 //
735 // 1. If type is an odd number (unknown type?), or file download for the current file is completed:
736 // client sends []byte{0x00, 0x03} to tell the server to continue to the next file
737 //
738 // 2. If download of a file is to be resumed:
739 // client sends:
740 // []byte{0x00, 0x02} // download folder action
741 // [2]byte // Resume data size
742 // []byte file resume data (see myField_FileResumeData)
743 //
744 // 3. Otherwise download of the file is requested and client sends []byte{0x00, 0x01}
745 //
746 // When download is requested (case 2 or 3), server replies with:
747 // [4]byte - file size
748 // []byte - Flattened File Object
749 //
750 // After every file download, client could request next file with:
751 // []byte{0x00, 0x03}
752 //
753 // This notifies the server to send the next item header
754
755 fh := NewFilePath(fileTransfer.FilePath)
756 fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+fh.String(), string(fileTransfer.FileName))
757
758 basePathLen := len(fullFilePath)
759
760 readBuffer := make([]byte, 1024)
761
762 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr())
763
764 i := 0
765 _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error {
766 i += 1
767 subPath := path[basePathLen-2:]
768 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
769
770 fileHeader := NewFileHeader(subPath, info.IsDir())
771
772 if i == 1 {
773 return nil
774 }
775
776 // Send the file header to client
777 if _, err := conn.Write(fileHeader.Payload()); err != nil {
778 s.Logger.Errorf("error sending file header: %v", err)
779 return err
780 }
781
782 // Read the client's Next Action request
783 //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
784 if _, err := conn.Read(readBuffer); err != nil {
785 s.Logger.Errorf("error reading next action: %v", err)
786 return err
787 }
788
789 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", readBuffer[0:2]))
790
791 if info.IsDir() {
792 return nil
793 }
794
795 splitPath := strings.Split(path, "/")
796 //strings.Join(splitPath[:len(splitPath)-1], "/")
797
798 ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), info.Name())
799 if err != nil {
800 return err
801 }
802 s.Logger.Infow("File download started",
803 "fileName", info.Name(),
804 "transactionRef", fileTransfer.ReferenceNumber,
805 "RemoteAddr", conn.RemoteAddr().String(),
806 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
807 )
808
809 // Send file size to client
810 if _, err := conn.Write(ffo.TransferSize()); err != nil {
811 s.Logger.Error(err)
812 return err
813 }
814
815 // Send file bytes to client
816 if _, err := conn.Write(ffo.Payload()); err != nil {
817 s.Logger.Error(err)
818 return err
819 }
820
821 file, err := os.Open(path)
822 if err != nil {
823 return err
824 }
825
826 sendBuffer := make([]byte, 1048576)
827 totalBytesSent := len(ffo.Payload())
828
829 for {
830 bytesRead, err := file.Read(sendBuffer)
831 if err == io.EOF {
832 // Read the client's Next Action request
833 //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
834 if _, err := conn.Read(readBuffer); err != nil {
835 s.Logger.Errorf("error reading next action: %v", err)
836 return err
837 }
838 break
839 }
840
841 sentBytes, readErr := conn.Write(sendBuffer[:bytesRead])
842 totalBytesSent += sentBytes
843 if readErr != nil {
844 return err
845 }
846 }
847 return nil
848 })
849
850 case FolderUpload:
851 dstPath := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
852 s.Logger.Infow(
853 "Folder upload started",
854 "transactionRef", fileTransfer.ReferenceNumber,
855 "RemoteAddr", conn.RemoteAddr().String(),
856 "dstPath", dstPath,
857 "TransferSize", fileTransfer.TransferSize,
858 "FolderItemCount", fileTransfer.FolderItemCount,
859 )
860
861 // Check if the target folder exists. If not, create it.
862 if _, err := os.Stat(dstPath); os.IsNotExist(err) {
863 s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
864 if err := os.Mkdir(dstPath, 0777); err != nil {
865 s.Logger.Error(err)
866 }
867 }
868
869 readBuffer := make([]byte, 1024)
870
871 // Begin the folder upload flow by sending the "next file action" to client
872 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
873 return err
874 }
875
876 fileSize := make([]byte, 4)
877 itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount)
878
879 for i := uint16(0); i < itemCount; i++ {
880 if _, err := conn.Read(readBuffer); err != nil {
881 return err
882 }
883 fu := readFolderUpload(readBuffer)
884
885 s.Logger.Infow(
886 "Folder upload continued",
887 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
888 "RemoteAddr", conn.RemoteAddr().String(),
889 "FormattedPath", fu.FormattedPath(),
890 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
891 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount),
892 )
893
894 if bytes.Equal(fu.IsFolder, []byte{0, 1}) {
895 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
896 s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
897 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
898 s.Logger.Error(err)
899 }
900 }
901
902 // Tell client to send next file
903 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
904 s.Logger.Error(err)
905 return err
906 }
907 } else {
908 // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
909 // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
910 // Send dlFldrAction_SendFile to client to begin transfer
911 if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil {
912 return err
913 }
914
915 if _, err := conn.Read(fileSize); err != nil {
916 fmt.Println("Error reading:", err.Error()) // TODO: handle
917 }
918
919 s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize)
920
921 if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil {
922 s.Logger.Error(err)
923 }
924
925 // Tell client to send next file
926 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
927 s.Logger.Error(err)
928 return err
929 }
930
931 // Client sends "MACR" after the file. Read and discard.
932 // TODO: This doesn't seem to be documented. What is this? Maybe resource fork?
933 if _, err := conn.Read(readBuffer); err != nil {
934 return err
935 }
936 }
937 }
938 s.Logger.Infof("Folder upload complete")
939 }
940
941 return nil
942 }
943
944 func transferFile(conn net.Conn, dst string) error {
945 const buffSize = 1024
946 buf := make([]byte, buffSize)
947
948 // Read first chunk of bytes from conn; this will be the Flat File Object and initial chunk of file bytes
949 if _, err := conn.Read(buf); err != nil {
950 return err
951 }
952 ffo := ReadFlattenedFileObject(buf)
953 payloadLen := len(ffo.Payload())
954 fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
955
956 newFile, err := os.Create(dst)
957 if err != nil {
958 return err
959 }
960 defer func() { _ = newFile.Close() }()
961 if _, err := newFile.Write(buf[payloadLen:]); err != nil {
962 return err
963 }
964 receivedBytes := buffSize - payloadLen
965
966 for {
967 if (fileSize - receivedBytes) < buffSize {
968 _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes))
969 return err
970 }
971
972 // Copy N bytes from conn to upload file
973 n, err := io.CopyN(newFile, conn, buffSize)
974 if err != nil {
975 return err
976 }
977 receivedBytes += int(n)
978 }
979 }
980
981 // 00 28 // DataSize
982 // 00 00 // IsFolder
983 // 00 02 // PathItemCount
984 //
985 // 00 00
986 // 09
987 // 73 75 62 66 6f 6c 64 65 72 // "subfolder"
988 //
989 // 00 00
990 // 15
991 // 73 75 62 66 6f 6c 64 65 72 2d 74 65 73 74 66 69 6c 65 2d 35 6b // "subfolder-testfile-5k"
992 func readFolderUpload(buf []byte) folderUpload {
993 dataLen := binary.BigEndian.Uint16(buf[0:2])
994
995 fu := folderUpload{
996 DataSize: buf[0:2], // Size of this structure (not including data size element itself)
997 IsFolder: buf[2:4],
998 PathItemCount: buf[4:6],
999 FileNamePath: buf[6 : dataLen+2],
1000 }
1001
1002 return fu
1003 }
1004
1005 type folderUpload struct {
1006 DataSize []byte
1007 IsFolder []byte
1008 PathItemCount []byte
1009 FileNamePath []byte
1010 }
1011
1012 func (fu *folderUpload) FormattedPath() string {
1013 pathItemLen := binary.BigEndian.Uint16(fu.PathItemCount)
1014
1015 var pathSegments []string
1016 pathData := fu.FileNamePath
1017
1018 for i := uint16(0); i < pathItemLen; i++ {
1019 segLen := pathData[2]
1020 pathSegments = append(pathSegments, string(pathData[3:3+segLen]))
1021 pathData = pathData[3+segLen:]
1022 }
1023
1024 return strings.Join(pathSegments, pathSeparator)
1025 }
1026
1027 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
1028 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
1029 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
1030 for _, c := range unsortedClients {
1031 clients = append(clients, c)
1032 }
1033 sort.Sort(byClientID(clients))
1034 return clients
1035 }