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