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