]> git.r.bdr.sh - rbdr/mobius/blame - server.go
patch: initial pre-release
[rbdr/mobius] / server.go
CommitLineData
6988a057
JH
1package hotline
2
3import (
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
29const (
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
35type 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
64type PrivateChat struct {
65 Subject string
66 ClientConn map[uint16]*ClientConn
67}
68
69func (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
84func (s *Server) APIPort() int {
85 return s.APIListener.Addr().(*net.TCPAddr).Port
86}
87
88func (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
105func (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
138func (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
169const (
170 agreementFile = "Agreement.txt"
171 messageBoardFile = "MessageBoard.txt"
172 threadedNewsFile = "ThreadedNews.yaml"
173)
174
175// NewServer constructs a new Server from a config dir
176func 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
268func (s *Server) userCount() int {
269 s.mux.Lock()
270 defer s.mux.Unlock()
271
272 return len(s.Clients)
273}
274
275func (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
302func (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
318func (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
346func (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
366func (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
375func (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
393func (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
405func (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
433func (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
448const (
449 minTransactionLen = 22 // minimum length of any transaction
450)
451
452// handleNewConnection takes a new net.Conn and performs the initial login sequence
453func (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 // Hotline 1.2.3 client does not send fieldVersion
508 // Nostalgia client sends ""
509 //if string(*c.Version) == "" {
510 // *c.UserName = clientLogin.GetField(fieldUserName).Data
511 // *c.Icon = clientLogin.GetField(fieldUserIconID).Data
512 //}
513 //
514 if clientLogin.GetField(fieldUserName).Data != nil {
515 *c.UserName = clientLogin.GetField(fieldUserName).Data
516 }
517
518 if clientLogin.GetField(fieldUserIconID).Data != nil {
519 *c.Icon = clientLogin.GetField(fieldUserIconID).Data
520 }
521
522 c.Account = c.Server.Accounts[login]
523
524 if c.Authorize(accessDisconUser) {
525 *c.Flags = []byte{0, 2}
526 }
527
528 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", conn.RemoteAddr().String())
529
530 s.outbox <- c.NewReply(clientLogin,
531 NewField(fieldVersion, []byte{0x00, 0xbe}),
532 NewField(fieldCommunityBannerID, []byte{0x00, 0x01}),
533 NewField(fieldServerName, []byte(s.Config.Name)),
534 )
535
536 // Send user access privs so client UI knows how to behave
537 c.Server.outbox <- *NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, *c.Account.Access))
538
539 // Show agreement to client
540 c.Server.outbox <- *NewTransaction(tranShowAgreement, c.ID, NewField(fieldData, s.Agreement))
541
542 // The Hotline ClientConn v1.2.3 has a different login sequence than 1.9.2
543 if string(*c.Version) == "" {
544 if _, err := c.notifyNewUserHasJoined(); err != nil {
545 return err
546 }
547 }
548
549 if _, err := c.notifyNewUserHasJoined(); err != nil {
550 return err
551 }
552 c.Server.Stats.LoginCount += 1
553
554 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
555 const maxTranSize = 1024000
556 tranBuff := make([]byte, 0)
557 tReadlen := 0
558 // Infinite loop where take action on incoming client requests until the connection is closed
559 for {
560 buf = make([]byte, readBuffSize)
561 tranBuff = tranBuff[tReadlen:]
562
563 readLen, err := c.Connection.Read(buf)
564 if err != nil {
565 return err
566 }
567 tranBuff = append(tranBuff, buf[:readLen]...)
568
569 // We may have read multiple requests worth of bytes from Connection.Read. readTransactions splits them
570 // into a slice of transactions
571 var transactions []Transaction
572 if transactions, tReadlen, err = readTransactions(tranBuff); err != nil {
573 c.Server.Logger.Errorw("Error handling transaction", "err", err)
574 }
575
576 // iterate over all of the transactions that were parsed from the byte slice and handle them
577 for _, t := range transactions {
578 if err := c.handleTransaction(&t); err != nil {
579 c.Server.Logger.Errorw("Error handling transaction", "err", err)
580 }
581 }
582 }
583}
584
585func hashAndSalt(pwd []byte) string {
586 // Use GenerateFromPassword to hash & salt pwd.
587 // MinCost is just an integer constant provided by the bcrypt
588 // package along with DefaultCost & MaxCost.
589 // The cost can be any value you want provided it isn't lower
590 // than the MinCost (4)
591 hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
592 if err != nil {
593 log.Println(err)
594 }
595 // GenerateFromPassword returns a byte slice so we need to
596 // convert the bytes to a string and return it
597 return string(hash)
598}
599
600// NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
601// in the file transfer request payload, and the file transfer server will use it to map the request
602// to a transfer
603func (s *Server) NewTransactionRef() []byte {
604 transactionRef := make([]byte, 4)
605 rand.Read(transactionRef)
606
607 return transactionRef
608}
609
610func (s *Server) NewPrivateChat(cc *ClientConn) []byte {
611 s.mux.Lock()
612 defer s.mux.Unlock()
613
614 randID := make([]byte, 4)
615 rand.Read(randID)
616 data := binary.BigEndian.Uint32(randID[:])
617
618 s.PrivateChats[data] = &PrivateChat{
619 Subject: "",
620 ClientConn: make(map[uint16]*ClientConn),
621 }
622 s.PrivateChats[data].ClientConn[cc.uint16ID()] = cc
623
624 return randID
625}
626
627const dlFldrActionSendFile = 1
628const dlFldrActionResumeFile = 2
629const dlFldrActionNextFile = 3
630
631func (s *Server) TransferFile(conn net.Conn) error {
632 defer func() { _ = conn.Close() }()
633
634 buf := make([]byte, 1024)
635 if _, err := conn.Read(buf); err != nil {
636 return err
637 }
638
639 t, err := NewReadTransfer(buf)
640 if err != nil {
641 return err
642 }
643
644 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
645 fileTransfer := s.FileTransfers[transferRefNum]
646
647 switch fileTransfer.Type {
648 case FileDownload:
649 fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+string(fileTransfer.FilePath), string(fileTransfer.FileName))
650
651 ffo, err := NewFlattenedFileObject(
652 s.Config.FileRoot+string(fileTransfer.FilePath),
653 string(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.Payload()); err != nil {
663 return err
664 }
665
666 file, err := os.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.Payload())
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 fh := NewFilePath(fileTransfer.FilePath)
770 fullFilePath := fmt.Sprintf("%v/%v", s.Config.FileRoot+fh.String(), string(fileTransfer.FileName))
771
772 basePathLen := len(fullFilePath)
773
774 readBuffer := make([]byte, 1024)
775
776 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber, "RemoteAddr", conn.RemoteAddr())
777
778 i := 0
779 _ = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, _ error) error {
780 i += 1
781 subPath := path[basePathLen-2:]
782 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
783
784 fileHeader := NewFileHeader(subPath, info.IsDir())
785
786 if i == 1 {
787 return nil
788 }
789
790 // Send the file header to client
791 if _, err := conn.Write(fileHeader.Payload()); err != nil {
792 s.Logger.Errorf("error sending file header: %v", err)
793 return err
794 }
795
796 // Read the client's Next Action request
797 //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
798 if _, err := conn.Read(readBuffer); err != nil {
799 s.Logger.Errorf("error reading next action: %v", err)
800 return err
801 }
802
803 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", readBuffer[0:2]))
804
805 if info.IsDir() {
806 return nil
807 }
808
809 splitPath := strings.Split(path, "/")
810 //strings.Join(splitPath[:len(splitPath)-1], "/")
811
812 ffo, err := NewFlattenedFileObject(strings.Join(splitPath[:len(splitPath)-1], "/"), info.Name())
813 if err != nil {
814 return err
815 }
816 s.Logger.Infow("File download started",
817 "fileName", info.Name(),
818 "transactionRef", fileTransfer.ReferenceNumber,
819 "RemoteAddr", conn.RemoteAddr().String(),
820 "TransferSize", fmt.Sprintf("%x", ffo.TransferSize()),
821 )
822
823 // Send file size to client
824 if _, err := conn.Write(ffo.TransferSize()); err != nil {
825 s.Logger.Error(err)
826 return err
827 }
828
829 // Send file bytes to client
830 if _, err := conn.Write(ffo.Payload()); err != nil {
831 s.Logger.Error(err)
832 return err
833 }
834
835 file, err := os.Open(path)
836 if err != nil {
837 return err
838 }
839
840 sendBuffer := make([]byte, 1048576)
841 totalBytesSent := len(ffo.Payload())
842
843 for {
844 bytesRead, err := file.Read(sendBuffer)
845 if err == io.EOF {
846 // Read the client's Next Action request
847 //TODO: Remove hardcoded behavior and switch behaviors based on the next action send
848 if _, err := conn.Read(readBuffer); err != nil {
849 s.Logger.Errorf("error reading next action: %v", err)
850 return err
851 }
852 break
853 }
854
855 sentBytes, readErr := conn.Write(sendBuffer[:bytesRead])
856 totalBytesSent += sentBytes
857 if readErr != nil {
858 return err
859 }
860 }
861 return nil
862 })
863
864 case FolderUpload:
865 dstPath := s.Config.FileRoot + ReadFilePath(fileTransfer.FilePath) + "/" + string(fileTransfer.FileName)
866 s.Logger.Infow(
867 "Folder upload started",
868 "transactionRef", fileTransfer.ReferenceNumber,
869 "RemoteAddr", conn.RemoteAddr().String(),
870 "dstPath", dstPath,
871 "TransferSize", fileTransfer.TransferSize,
872 "FolderItemCount", fileTransfer.FolderItemCount,
873 )
874
875 // Check if the target folder exists. If not, create it.
876 if _, err := os.Stat(dstPath); os.IsNotExist(err) {
877 s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
878 if err := os.Mkdir(dstPath, 0777); err != nil {
879 s.Logger.Error(err)
880 }
881 }
882
883 readBuffer := make([]byte, 1024)
884
885 // Begin the folder upload flow by sending the "next file action" to client
886 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
887 return err
888 }
889
890 fileSize := make([]byte, 4)
891 itemCount := binary.BigEndian.Uint16(fileTransfer.FolderItemCount)
892
893 for i := uint16(0); i < itemCount; i++ {
894 if _, err := conn.Read(readBuffer); err != nil {
895 return err
896 }
897 fu := readFolderUpload(readBuffer)
898
899 s.Logger.Infow(
900 "Folder upload continued",
901 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
902 "RemoteAddr", conn.RemoteAddr().String(),
903 "FormattedPath", fu.FormattedPath(),
904 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
905 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount),
906 )
907
908 if bytes.Equal(fu.IsFolder, []byte{0, 1}) {
909 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
910 s.Logger.Infow("Target path does not exist; Creating...", "dstPath", dstPath)
911 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
912 s.Logger.Error(err)
913 }
914 }
915
916 // Tell client to send next file
917 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
918 s.Logger.Error(err)
919 return err
920 }
921 } else {
922 // TODO: Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
923 // TODO: Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
924 // Send dlFldrAction_SendFile to client to begin transfer
925 if _, err := conn.Write([]byte{0, dlFldrActionSendFile}); err != nil {
926 return err
927 }
928
929 if _, err := conn.Read(fileSize); err != nil {
930 fmt.Println("Error reading:", err.Error()) // TODO: handle
931 }
932
933 s.Logger.Infow("Starting file transfer", "fileNum", i+1, "totalFiles", itemCount, "fileSize", fileSize)
934
935 if err := transferFile(conn, dstPath+"/"+fu.FormattedPath()); err != nil {
936 s.Logger.Error(err)
937 }
938
939 // Tell client to send next file
940 if _, err := conn.Write([]byte{0, dlFldrActionNextFile}); err != nil {
941 s.Logger.Error(err)
942 return err
943 }
944
945 // Client sends "MACR" after the file. Read and discard.
946 // TODO: This doesn't seem to be documented. What is this? Maybe resource fork?
947 if _, err := conn.Read(readBuffer); err != nil {
948 return err
949 }
950 }
951 }
952 s.Logger.Infof("Folder upload complete")
953 }
954
955 return nil
956}
957
958func transferFile(conn net.Conn, dst string) error {
959 const buffSize = 1024
960 buf := make([]byte, buffSize)
961
962 // Read first chunk of bytes from conn; this will be the Flat File Object and initial chunk of file bytes
963 if _, err := conn.Read(buf); err != nil {
964 return err
965 }
966 ffo := ReadFlattenedFileObject(buf)
967 payloadLen := len(ffo.Payload())
968 fileSize := int(binary.BigEndian.Uint32(ffo.FlatFileDataForkHeader.DataSize))
969
970 newFile, err := os.Create(dst)
971 if err != nil {
972 return err
973 }
974 defer func() { _ = newFile.Close() }()
975 if _, err := newFile.Write(buf[payloadLen:]); err != nil {
976 return err
977 }
978 receivedBytes := buffSize - payloadLen
979
980 for {
981 if (fileSize - receivedBytes) < buffSize {
982 _, err := io.CopyN(newFile, conn, int64(fileSize-receivedBytes))
983 return err
984 }
985
986 // Copy N bytes from conn to upload file
987 n, err := io.CopyN(newFile, conn, buffSize)
988 if err != nil {
989 return err
990 }
991 receivedBytes += int(n)
992 }
993}
994
995// 00 28 // DataSize
996// 00 00 // IsFolder
997// 00 02 // PathItemCount
998//
999// 00 00
1000// 09
1001// 73 75 62 66 6f 6c 64 65 72 // "subfolder"
1002//
1003// 00 00
1004// 15
1005// 73 75 62 66 6f 6c 64 65 72 2d 74 65 73 74 66 69 6c 65 2d 35 6b // "subfolder-testfile-5k"
1006func readFolderUpload(buf []byte) folderUpload {
1007 dataLen := binary.BigEndian.Uint16(buf[0:2])
1008
1009 fu := folderUpload{
1010 DataSize: buf[0:2], // Size of this structure (not including data size element itself)
1011 IsFolder: buf[2:4],
1012 PathItemCount: buf[4:6],
1013 FileNamePath: buf[6 : dataLen+2],
1014 }
1015
1016 return fu
1017}
1018
1019type folderUpload struct {
1020 DataSize []byte
1021 IsFolder []byte
1022 PathItemCount []byte
1023 FileNamePath []byte
1024}
1025
1026func (fu *folderUpload) FormattedPath() string {
1027 pathItemLen := binary.BigEndian.Uint16(fu.PathItemCount)
1028
1029 var pathSegments []string
1030 pathData := fu.FileNamePath
1031
1032 for i := uint16(0); i < pathItemLen; i++ {
1033 segLen := pathData[2]
1034 pathSegments = append(pathSegments, string(pathData[3:3+segLen]))
1035 pathData = pathData[3+segLen:]
1036 }
1037
1038 return strings.Join(pathSegments, pathSeparator)
1039}
1040
1041// sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
1042// The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
1043func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
1044 for _, c := range unsortedClients {
1045 clients = append(clients, c)
1046 }
1047 sort.Sort(byClientID(clients))
1048 return clients
1049}