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