]> git.r.bdr.sh - rbdr/mobius/blame - hotline/server.go
Add initial support for resource and info forks
[rbdr/mobius] / hotline / server.go
CommitLineData
6988a057
JH
1package hotline
2
3import (
7cd900d6 4 "bufio"
a82b93cf 5 "bytes"
6988a057
JH
6 "context"
7 "encoding/binary"
8 "errors"
9 "fmt"
041c2df6 10 "github.com/go-playground/validator/v10"
6988a057 11 "go.uber.org/zap"
7cd900d6 12 "gopkg.in/yaml.v3"
6988a057 13 "io"
16a4ad70 14 "io/fs"
6988a057 15 "io/ioutil"
6988a057
JH
16 "math/big"
17 "math/rand"
18 "net"
19 "os"
20 "path"
21 "path/filepath"
22 "runtime/debug"
6988a057
JH
23 "strings"
24 "sync"
25 "time"
6988a057
JH
26)
27
7cd900d6
JH
28type contextKey string
29
30var contextKeyReq = contextKey("req")
31
32type requestCtx struct {
33 remoteAddr string
34 login string
35 name string
36}
37
6988a057
JH
38const (
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
a82b93cf
JH
44var nostalgiaVersion = []byte{0, 0, 2, 0x2c} // version ID used by the Nostalgia client
45
6988a057 46type Server struct {
6988a057
JH
47 Port int
48 Accounts map[string]*Account
49 Agreement []byte
50 Clients map[uint16]*ClientConn
6988a057
JH
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
40414f92 58 TrackerPassID [4]byte
6988a057
JH
59 Stats *Stats
60
7cd900d6 61 FS FileStore // Storage backend to use for File storage
6988a057
JH
62
63 outbox chan Transaction
7cd900d6 64 mux sync.Mutex
6988a057 65
6988a057 66 flatNewsMux sync.Mutex
7cd900d6 67 FlatNews []byte
6988a057
JH
68}
69
70type PrivateChat struct {
71 Subject string
72 ClientConn map[uint16]*ClientConn
73}
74
75func (s *Server) ListenAndServe(ctx context.Context, cancelRoot context.CancelFunc) error {
aeec1015
JH
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
6988a057
JH
82 var wg sync.WaitGroup
83
84 wg.Add(1)
8168522a
JH
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
7cd900d6 91 s.Logger.Fatal(s.Serve(ctx, ln))
8168522a 92 }()
6988a057
JH
93
94 wg.Add(1)
8168522a
JH
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
7cd900d6 102 s.Logger.Fatal(s.ServeFileTransfers(ctx, ln))
8168522a 103 }()
6988a057
JH
104
105 wg.Wait()
106
107 return nil
108}
109
7cd900d6 110func (s *Server) ServeFileTransfers(ctx context.Context, ln net.Listener) error {
6988a057
JH
111 for {
112 conn, err := ln.Accept()
113 if err != nil {
114 return err
115 }
116
117 go func() {
7cd900d6
JH
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 {
6988a057
JH
128 s.Logger.Errorw("file transfer error", "reason", err)
129 }
130 }()
131 }
132}
133
134func (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 {
bd1ce113 145 return fmt.Errorf("invalid client id %v", *t.clientID)
6988a057 146 }
72dd37f1 147 userName := string(client.UserName)
6988a057
JH
148 login := client.Account.Login
149
150 handler := TransactionHandlers[requestNum]
151
72dd37f1
JH
152 b, err := t.MarshalBinary()
153 if err != nil {
154 return err
155 }
6988a057 156 var n int
72dd37f1 157 if n, err = client.Connection.Write(b); err != nil {
6988a057
JH
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,
d4c152a4 166 "remoteAddr", client.RemoteAddr,
6988a057
JH
167 )
168 return nil
169}
170
7cd900d6 171func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
6988a057
JH
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() {
7cd900d6
JH
189 if err := s.handleNewConnection(ctx, conn, conn.RemoteAddr().String()); err != nil {
190 s.Logger.Infow("New client connection established", "RemoteAddr", conn.RemoteAddr())
6988a057
JH
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
201const (
c7e932c0 202 agreementFile = "Agreement.txt"
6988a057
JH
203)
204
205// NewServer constructs a new Server from a config dir
7cd900d6 206func NewServer(configDir string, netPort int, logger *zap.SugaredLogger, FS FileStore) (*Server, error) {
6988a057
JH
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{},
b196a50a 220 FS: FS,
6988a057
JH
221 }
222
8168522a 223 var err error
6988a057
JH
224
225 // generate a new random passID for tracker registration
40414f92 226 if _, err := rand.Read(server.TrackerPassID[:]); err != nil {
6988a057
JH
227 return nil, err
228 }
229
b196a50a
JH
230 server.Agreement, err = os.ReadFile(configDir + agreementFile)
231 if err != nil {
6988a057
JH
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 {
e42888eb
JH
256 server.Logger.Infow(
257 "Tracker registration enabled",
258 "frequency", fmt.Sprintf("%vs", trackerUpdateFrequency),
259 "trackers", server.Config.Trackers,
260 )
261
6988a057
JH
262 go func() {
263 for {
e42888eb 264 tr := &TrackerRegistration{
6988a057 265 UserCount: server.userCount(),
40414f92 266 PassID: server.TrackerPassID[:],
6988a057
JH
267 Name: server.Config.Name,
268 Description: server.Config.Description,
269 }
40414f92 270 binary.BigEndian.PutUint16(tr.Port[:], uint16(server.Port))
6988a057 271 for _, t := range server.Config.Trackers {
6988a057
JH
272 if err := register(t, tr); err != nil {
273 server.Logger.Errorw("unable to register with tracker %v", "error", err)
274 }
e42888eb 275 server.Logger.Infow("Sent Tracker registration", "data", tr)
6988a057
JH
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
289func (s *Server) userCount() int {
290 s.mux.Lock()
291 defer s.mux.Unlock()
292
293 return len(s.Clients)
294}
295
296func (s *Server) keepaliveHandler() {
297 for {
298 time.Sleep(idleCheckInterval * time.Second)
299 s.mux.Lock()
300
301 for _, c := range s.Clients {
61c272e1
JH
302 c.IdleTime += idleCheckInterval
303 if c.IdleTime > userIdleSeconds && !c.Idle {
6988a057
JH
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),
72dd37f1 314 NewField(fieldUserName, c.UserName),
6988a057
JH
315 NewField(fieldUserIconID, *c.Icon),
316 )
317 }
318 }
319 s.mux.Unlock()
320 }
321}
322
323func (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
d4c152a4 339func (s *Server) NewClientConn(conn net.Conn, remoteAddr string) *ClientConn {
6988a057
JH
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},
72dd37f1 347 UserName: []byte{},
6988a057
JH
348 Connection: conn,
349 Server: s,
350 Version: &[]byte{},
aebc4d36 351 AutoReply: []byte{},
6988a057 352 Transfers: make(map[int][]*FileTransfer),
bd1ce113 353 Agreed: false,
d4c152a4 354 RemoteAddr: remoteAddr,
6988a057
JH
355 }
356 *s.NextGuestID++
357 ID := *s.NextGuestID
358
6988a057
JH
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
366func (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
b196a50a 382 return s.FS.WriteFile(s.ConfigDir+"Users/"+login+".yaml", out, 0666)
6988a057
JH
383}
384
d2810ae9
JH
385func (s *Server) UpdateUser(login, newLogin, name, password string, access []byte) error {
386 s.mux.Lock()
387 defer s.mux.Unlock()
388
d2810ae9
JH
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
6988a057
JH
415// DeleteUser deletes the user account
416func (s *Server) DeleteUser(login string) error {
417 s.mux.Lock()
418 defer s.mux.Unlock()
419
420 delete(s.Accounts, login)
421
b196a50a 422 return s.FS.Remove(s.ConfigDir + "Users/" + login + ".yaml")
6988a057
JH
423}
424
425func (s *Server) connectedUsers() []Field {
426 s.mux.Lock()
427 defer s.mux.Unlock()
428
429 var connectedUsers []Field
c7e932c0 430 for _, c := range sortedClients(s.Clients) {
aebc4d36 431 if !c.Agreed {
bd1ce113
JH
432 continue
433 }
6988a057
JH
434 user := User{
435 ID: *c.ID,
436 Icon: *c.Icon,
437 Flags: *c.Flags,
72dd37f1 438 Name: string(c.UserName),
6988a057
JH
439 }
440 connectedUsers = append(connectedUsers, NewField(fieldUsernameWithInfo, user.Payload()))
441 }
442 return connectedUsers
443}
444
445// loadThreadedNews loads the threaded news data from disk
446func (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)
6988a057
JH
452
453 return decoder.Decode(s.ThreadedNews)
454}
455
456// loadAccounts loads account data from disk
457func (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 {
b196a50a 468 fh, err := s.FS.Open(file)
6988a057
JH
469 if err != nil {
470 return err
471 }
472
473 account := Account{}
474 decoder := yaml.NewDecoder(fh)
6988a057
JH
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
484func (s *Server) loadConfig(path string) error {
b196a50a 485 fh, err := s.FS.Open(path)
6988a057
JH
486 if err != nil {
487 return err
488 }
489
490 decoder := yaml.NewDecoder(fh)
6988a057
JH
491 err = decoder.Decode(s.Config)
492 if err != nil {
493 return err
494 }
041c2df6
JH
495
496 validate := validator.New()
497 err = validate.Struct(s.Config)
498 if err != nil {
499 return err
500 }
6988a057
JH
501 return nil
502}
503
504const (
505 minTransactionLen = 22 // minimum length of any transaction
506)
507
37a954c8
JH
508// dontPanic recovers and logs panics instead of crashing
509// TODO: remove this after known issues are fixed
510func 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
6988a057 517// handleNewConnection takes a new net.Conn and performs the initial login sequence
7cd900d6 518func (s *Server) handleNewConnection(ctx context.Context, conn net.Conn, remoteAddr string) error {
c4208f86
JH
519 defer dontPanic(s.Logger)
520
d4c152a4 521 if err := Handshake(conn); err != nil {
6988a057
JH
522 return err
523 }
524
525 buf := make([]byte, 1024)
c4208f86 526 // TODO: fix potential short read with io.ReadFull
6988a057
JH
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
d4c152a4 540 c := s.NewClientConn(conn, remoteAddr)
6988a057 541 defer c.Disconnect()
6988a057
JH
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) {
72dd37f1
JH
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 {
6988a057
JH
563 return err
564 }
565 return fmt.Errorf("incorrect login")
566 }
567
6988a057 568 if clientLogin.GetField(fieldUserName).Data != nil {
72dd37f1 569 c.UserName = clientLogin.GetField(fieldUserName).Data
6988a057
JH
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
d4c152a4 582 s.Logger.Infow("Client connection received", "login", login, "version", *c.Version, "RemoteAddr", remoteAddr)
6988a057
JH
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
a82b93cf
JH
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) {
bd1ce113 598 c.Agreed = true
003a743e
JH
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 )
6988a057 609 }
bd1ce113 610
6988a057
JH
611 c.Server.Stats.LoginCount += 1
612
613 const readBuffSize = 1024000 // 1KB - TODO: what should this be?
6988a057
JH
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
7cd900d6 634 // iterate over all the transactions that were parsed from the byte slice and handle them
6988a057
JH
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
6988a057 643// NewTransactionRef generates a random ID for the file transfer. The Hotline client includes this ID
7cd900d6 644// in the transfer request payload, and the file transfer server will use it to map the request
6988a057
JH
645// to a transfer
646func (s *Server) NewTransactionRef() []byte {
647 transactionRef := make([]byte, 4)
648 rand.Read(transactionRef)
649
650 return transactionRef
651}
652
653func (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
670const dlFldrActionSendFile = 1
671const dlFldrActionResumeFile = 2
672const dlFldrActionNextFile = 3
673
85767504 674// handleFileTransfer receives a client net.Conn from the file transfer server, performs the requested transfer type, then closes the connection
7cd900d6 675func (s *Server) handleFileTransfer(ctx context.Context, rwc io.ReadWriter) error {
37a954c8 676 defer dontPanic(s.Logger)
0a92e50b 677
2e7c03cf 678 txBuf := make([]byte, 16)
7cd900d6 679 if _, err := io.ReadFull(rwc, txBuf); err != nil {
6988a057
JH
680 return err
681 }
682
df2735b2 683 var t transfer
0a92e50b 684 if _, err := t.Write(txBuf); err != nil {
6988a057
JH
685 return err
686 }
687
688 transferRefNum := binary.BigEndian.Uint32(t.ReferenceNumber[:])
0a92e50b
JH
689 defer func() {
690 s.mux.Lock()
691 delete(s.FileTransfers, transferRefNum)
692 s.mux.Unlock()
693 }()
6988a057 694
0a92e50b
JH
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 }
16a4ad70 701
7cd900d6
JH
702 rLogger := s.Logger.With(
703 "remoteAddr", ctx.Value(contextKeyReq).(requestCtx).remoteAddr,
704 "xferID", transferRefNum,
705 )
706
6988a057
JH
707 switch fileTransfer.Type {
708 case FileDownload:
23411fc2
JH
709 s.Stats.DownloadCounter += 1
710
92a7e455
JH
711 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
712 if err != nil {
713 return err
714 }
6988a057 715
16a4ad70
JH
716 var dataOffset int64
717 if fileTransfer.fileResumeData != nil {
718 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.fileResumeData.ForkInfoList[0].DataSize[:]))
719 }
720
7cd900d6 721 fw, err := newFileWrapper(s.FS, fullFilePath, 0)
6988a057
JH
722 if err != nil {
723 return err
724 }
725
7cd900d6 726 rLogger.Infow("File download started", "filePath", fullFilePath, "transactionRef", fileTransfer.ReferenceNumber)
6988a057 727
7cd900d6
JH
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
d1cd6664
JH
731 if fileTransfer.options == nil {
732 // Start by sending flat file object to client
7cd900d6 733 if _, err := wr.Write(fw.ffo.BinaryMarshal()); err != nil {
d1cd6664
JH
734 return err
735 }
6988a057
JH
736 }
737
7cd900d6 738 file, err := fw.dataForkReader()
6988a057
JH
739 if err != nil {
740 return err
741 }
742
7cd900d6
JH
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())
16a4ad70
JH
754 if err != nil {
755 return err
756 }
7cd900d6 757 if err := wr.Flush(); err != nil {
6988a057
JH
758 return err
759 }
760 }
7cd900d6
JH
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
6988a057 773 case FileUpload:
23411fc2
JH
774 s.Stats.UploadCounter += 1
775
7cd900d6
JH
776 destinationFile, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
777 if err != nil {
778 return err
779 }
16a4ad70 780
5c14e4c9
JH
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
7cd900d6 787 // We have to infer which case applies by inspecting what is already on the filesystem
5c14e4c9
JH
788
789 // 1) Check for existing file:
7cd900d6 790 _, err = os.Stat(destinationFile)
5c14e4c9
JH
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 }
16a4ad70 798 if errors.Is(err, fs.ErrNotExist) {
7cd900d6 799 // If not found, open or create a new .incomplete file
5c14e4c9 800 file, err = os.OpenFile(destinationFile+incompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
16a4ad70
JH
801 if err != nil {
802 return err
803 }
6988a057 804 }
16a4ad70 805
7cd900d6
JH
806 f, err := newFileWrapper(s.FS, destinationFile, 0)
807 if err != nil {
808 return err
809 }
810
16a4ad70 811 defer func() { _ = file.Close() }()
6988a057 812
85767504 813 s.Logger.Infow("File upload started", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
6988a057 814
7cd900d6
JH
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 {
16a4ad70
JH
830 return err
831 }
832
7cd900d6 833 if err := s.FS.Rename(destinationFile+".incomplete", destinationFile); err != nil {
16a4ad70 834 return err
6988a057 835 }
85767504
JH
836
837 s.Logger.Infow("File upload complete", "transactionRef", fileTransfer.ReferenceNumber, "dstFile", destinationFile)
6988a057
JH
838 case FolderDownload:
839 // Folder Download flow:
df2735b2 840 // 1. Get filePath from the transfer
6988a057 841 // 2. Iterate over files
7cd900d6
JH
842 // 3. For each fileWrapper:
843 // Send fileWrapper header to client
6988a057
JH
844 // The client can reply in 3 ways:
845 //
7cd900d6
JH
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
6988a057 848 //
7cd900d6 849 // 2. If download of a fileWrapper is to be resumed:
6988a057
JH
850 // client sends:
851 // []byte{0x00, 0x02} // download folder action
852 // [2]byte // Resume data size
7cd900d6 853 // []byte fileWrapper resume data (see myField_FileResumeData)
6988a057 854 //
7cd900d6 855 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
6988a057
JH
856 //
857 // When download is requested (case 2 or 3), server replies with:
7cd900d6 858 // [4]byte - fileWrapper size
6988a057
JH
859 // []byte - Flattened File Object
860 //
7cd900d6 861 // After every fileWrapper download, client could request next fileWrapper with:
6988a057
JH
862 // []byte{0x00, 0x03}
863 //
864 // This notifies the server to send the next item header
865
92a7e455
JH
866 fullFilePath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
867 if err != nil {
868 return err
869 }
6988a057
JH
870
871 basePathLen := len(fullFilePath)
872
85767504 873 s.Logger.Infow("Start folder download", "path", fullFilePath, "ReferenceNumber", fileTransfer.ReferenceNumber)
6988a057 874
85767504 875 nextAction := make([]byte, 2)
7cd900d6 876 if _, err := io.ReadFull(rwc, nextAction); err != nil {
85767504
JH
877 return err
878 }
6988a057
JH
879
880 i := 0
85767504 881 err = filepath.Walk(fullFilePath+"/", func(path string, info os.FileInfo, err error) error {
23411fc2 882 s.Stats.DownloadCounter += 1
7cd900d6 883 i += 1
23411fc2 884
85767504
JH
885 if err != nil {
886 return err
887 }
7cd900d6
JH
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
85767504 899 subPath := path[basePathLen+1:]
6988a057
JH
900 s.Logger.Infow("Sending fileheader", "i", i, "path", path, "fullFilePath", fullFilePath, "subPath", subPath, "IsDir", info.IsDir())
901
6988a057
JH
902 if i == 1 {
903 return nil
904 }
905
85767504
JH
906 fileHeader := NewFileHeader(subPath, info.IsDir())
907
7cd900d6
JH
908 // Send the fileWrapper header to client
909 if _, err := rwc.Write(fileHeader.Payload()); err != nil {
6988a057
JH
910 s.Logger.Errorf("error sending file header: %v", err)
911 return err
912 }
913
914 // Read the client's Next Action request
7cd900d6 915 if _, err := io.ReadFull(rwc, nextAction); err != nil {
6988a057
JH
916 return err
917 }
918
85767504 919 s.Logger.Infow("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
6988a057 920
16a4ad70
JH
921 var dataOffset int64
922
923 switch nextAction[1] {
924 case dlFldrActionResumeFile:
16a4ad70 925 // get size of resumeData
7cd900d6
JH
926 resumeDataByteLen := make([]byte, 2)
927 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
16a4ad70
JH
928 return err
929 }
930
7cd900d6 931 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
16a4ad70 932 resumeDataBytes := make([]byte, resumeDataLen)
7cd900d6 933 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
16a4ad70
JH
934 return err
935 }
936
7cd900d6 937 var frd FileResumeData
16a4ad70
JH
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
6988a057
JH
947 if info.IsDir() {
948 return nil
949 }
950
6988a057
JH
951 s.Logger.Infow("File download started",
952 "fileName", info.Name(),
953 "transactionRef", fileTransfer.ReferenceNumber,
7cd900d6 954 "TransferSize", fmt.Sprintf("%x", hlFile.ffo.TransferSize(dataOffset)),
6988a057
JH
955 )
956
957 // Send file size to client
7cd900d6 958 if _, err := rwc.Write(hlFile.ffo.TransferSize(dataOffset)); err != nil {
6988a057
JH
959 s.Logger.Error(err)
960 return err
961 }
962
85767504 963 // Send ffo bytes to client
7cd900d6 964 if _, err := rwc.Write(hlFile.ffo.BinaryMarshal()); err != nil {
6988a057
JH
965 s.Logger.Error(err)
966 return err
967 }
968
b196a50a 969 file, err := s.FS.Open(path)
6988a057
JH
970 if err != nil {
971 return err
972 }
973
7cd900d6
JH
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())
16a4ad70 982 if err != nil {
7cd900d6 983 return err
16a4ad70 984 }
16a4ad70 985
7cd900d6
JH
986 rFile, err := hlFile.rsrcForkFile()
987 if err != nil {
988 return err
989 }
16a4ad70 990
7cd900d6
JH
991 err = sendFile(rwc, rFile, int(dataOffset))
992 if err != nil {
16a4ad70
JH
993 return err
994 }
85767504 995 }
6988a057 996
16a4ad70 997 // Read the client's Next Action request. This is always 3, I think?
7cd900d6 998 if _, err := io.ReadFull(rwc, nextAction); err != nil {
85767504 999 return err
6988a057 1000 }
85767504 1001
16a4ad70 1002 return nil
6988a057
JH
1003 })
1004
1005 case FolderUpload:
92a7e455
JH
1006 dstPath, err := readPath(s.Config.FileRoot, fileTransfer.FilePath, fileTransfer.FileName)
1007 if err != nil {
1008 return err
1009 }
7cd900d6 1010
6988a057
JH
1011 s.Logger.Infow(
1012 "Folder upload started",
1013 "transactionRef", fileTransfer.ReferenceNumber,
6988a057 1014 "dstPath", dstPath,
92a7e455 1015 "TransferSize", fmt.Sprintf("%x", fileTransfer.TransferSize),
6988a057
JH
1016 "FolderItemCount", fileTransfer.FolderItemCount,
1017 )
1018
1019 // Check if the target folder exists. If not, create it.
b196a50a
JH
1020 if _, err := s.FS.Stat(dstPath); os.IsNotExist(err) {
1021 if err := s.FS.Mkdir(dstPath, 0777); err != nil {
16a4ad70 1022 return err
6988a057
JH
1023 }
1024 }
1025
6988a057 1026 // Begin the folder upload flow by sending the "next file action" to client
7cd900d6 1027 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
6988a057
JH
1028 return err
1029 }
1030
1031 fileSize := make([]byte, 4)
16a4ad70
JH
1032
1033 for i := 0; i < fileTransfer.ItemCount(); i++ {
ba29c43b
JH
1034 s.Stats.UploadCounter += 1
1035
1036 var fu folderUpload
7cd900d6 1037 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
ba29c43b
JH
1038 return err
1039 }
7cd900d6 1040 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
ba29c43b
JH
1041 return err
1042 }
7cd900d6 1043 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
ba29c43b
JH
1044 return err
1045 }
ba29c43b 1046
7cd900d6
JH
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 {
6988a057
JH
1050 return err
1051 }
6988a057
JH
1052
1053 s.Logger.Infow(
1054 "Folder upload continued",
1055 "transactionRef", fmt.Sprintf("%x", fileTransfer.ReferenceNumber),
6988a057
JH
1056 "FormattedPath", fu.FormattedPath(),
1057 "IsFolder", fmt.Sprintf("%x", fu.IsFolder),
c5d9af5a 1058 "PathItemCount", binary.BigEndian.Uint16(fu.PathItemCount[:]),
6988a057
JH
1059 )
1060
c5d9af5a 1061 if fu.IsFolder == [2]byte{0, 1} {
6988a057 1062 if _, err := os.Stat(dstPath + "/" + fu.FormattedPath()); os.IsNotExist(err) {
6988a057 1063 if err := os.Mkdir(dstPath+"/"+fu.FormattedPath(), 0777); err != nil {
16a4ad70 1064 return err
6988a057
JH
1065 }
1066 }
1067
1068 // Tell client to send next file
7cd900d6 1069 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
6988a057
JH
1070 return err
1071 }
1072 } else {
16a4ad70
JH
1073 nextAction := dlFldrActionSendFile
1074
1075 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
7cd900d6 1076 _, err = os.Stat(dstPath + "/" + fu.FormattedPath())
16a4ad70 1077 if err != nil && !errors.Is(err, fs.ErrNotExist) {
6988a057
JH
1078 return err
1079 }
16a4ad70
JH
1080 if err == nil {
1081 nextAction = dlFldrActionNextFile
1082 }
6988a057 1083
16a4ad70 1084 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
7cd900d6 1085 incompleteFile, err := os.Stat(dstPath + "/" + fu.FormattedPath() + incompleteFileSuffix)
16a4ad70 1086 if err != nil && !errors.Is(err, fs.ErrNotExist) {
85767504 1087 return err
6988a057 1088 }
16a4ad70
JH
1089 if err == nil {
1090 nextAction = dlFldrActionResumeFile
1091 }
6988a057 1092
7cd900d6 1093 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
85767504
JH
1094 return err
1095 }
1096
16a4ad70
JH
1097 switch nextAction {
1098 case dlFldrActionNextFile:
1099 continue
1100 case dlFldrActionResumeFile:
1101 offset := make([]byte, 4)
7cd900d6 1102 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
16a4ad70
JH
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
7cd900d6 1109 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
16a4ad70
JH
1110
1111 b, _ := fileResumeData.BinaryMarshal()
1112
1113 bs := make([]byte, 2)
1114 binary.BigEndian.PutUint16(bs, uint16(len(b)))
1115
7cd900d6 1116 if _, err := rwc.Write(append(bs, b...)); err != nil {
16a4ad70
JH
1117 return err
1118 }
1119
7cd900d6 1120 if _, err := io.ReadFull(rwc, fileSize); err != nil {
16a4ad70
JH
1121 return err
1122 }
1123
7cd900d6 1124 if err := receiveFile(rwc, file, ioutil.Discard, ioutil.Discard); err != nil {
16a4ad70
JH
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:
7cd900d6 1134 if _, err := io.ReadFull(rwc, fileSize); err != nil {
16a4ad70
JH
1135 return err
1136 }
1137
1138 filePath := dstPath + "/" + fu.FormattedPath()
16a4ad70 1139
7cd900d6 1140 hlFile, err := newFileWrapper(s.FS, filePath, 0)
16a4ad70
JH
1141 if err != nil {
1142 return err
1143 }
1144
7cd900d6
JH
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 }
16a4ad70 1164 }
7cd900d6
JH
1165 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter); err != nil {
1166 return err
1167 }
1168 // _ = newFile.Close()
16a4ad70
JH
1169 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
1170 return err
1171 }
6988a057
JH
1172 }
1173
7cd900d6
JH
1174 // Tell client to send next fileWrapper
1175 if _, err := rwc.Write([]byte{0, dlFldrActionNextFile}); err != nil {
6988a057
JH
1176 return err
1177 }
6988a057
JH
1178 }
1179 }
1180 s.Logger.Infof("Folder upload complete")
1181 }
1182
1183 return nil
1184}