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