]> git.r.bdr.sh - rbdr/mobius/blame_incremental - hotline/file_transfer.go
Extensive refactor, quality of life enhancements
[rbdr/mobius] / hotline / file_transfer.go
... / ...
CommitLineData
1package hotline
2
3import (
4 "bufio"
5 "crypto/rand"
6 "encoding/binary"
7 "errors"
8 "fmt"
9 "io"
10 "io/fs"
11 "log/slog"
12 "math"
13 "os"
14 "path/filepath"
15 "slices"
16 "strings"
17 "sync"
18)
19
20// Folder download actions. Send by the client to indicate the next action the server should take
21// for a folder download.
22const (
23 DlFldrActionSendFile = 1
24 DlFldrActionResumeFile = 2
25 DlFldrActionNextFile = 3
26)
27
28// File transfer types
29type FileTransferType uint8
30
31const (
32 FileDownload = FileTransferType(0)
33 FileUpload = FileTransferType(1)
34 FolderDownload = FileTransferType(2)
35 FolderUpload = FileTransferType(3)
36 BannerDownload = FileTransferType(4)
37)
38
39type FileTransferID [4]byte
40
41type FileTransferMgr interface {
42 Add(ft *FileTransfer)
43 Get(id FileTransferID) *FileTransfer
44 Delete(id FileTransferID)
45}
46
47type MemFileTransferMgr struct {
48 fileTransfers map[FileTransferID]*FileTransfer
49
50 mu sync.Mutex
51}
52
53func NewMemFileTransferMgr() *MemFileTransferMgr {
54 return &MemFileTransferMgr{
55 fileTransfers: make(map[FileTransferID]*FileTransfer),
56 }
57}
58
59func (ftm *MemFileTransferMgr) Add(ft *FileTransfer) {
60 ftm.mu.Lock()
61 defer ftm.mu.Unlock()
62
63 _, _ = rand.Read(ft.RefNum[:])
64
65 ftm.fileTransfers[ft.RefNum] = ft
66
67 ft.ClientConn.ClientFileTransferMgr.Add(ft.Type, ft)
68}
69
70func (ftm *MemFileTransferMgr) Get(id FileTransferID) *FileTransfer {
71 ftm.mu.Lock()
72 defer ftm.mu.Unlock()
73
74 return ftm.fileTransfers[id]
75}
76
77func (ftm *MemFileTransferMgr) Delete(id FileTransferID) {
78 ftm.mu.Lock()
79 defer ftm.mu.Unlock()
80
81 ft := ftm.fileTransfers[id]
82
83 ft.ClientConn.ClientFileTransferMgr.Delete(ft.Type, id)
84
85 delete(ftm.fileTransfers, id)
86
87}
88
89type FileTransfer struct {
90 FileName []byte
91 FilePath []byte
92 RefNum [4]byte
93 Type FileTransferType
94 TransferSize []byte
95 FolderItemCount []byte
96 FileResumeData *FileResumeData
97 Options []byte
98 bytesSentCounter *WriteCounter
99 ClientConn *ClientConn
100}
101
102// WriteCounter counts the number of bytes written to it.
103type WriteCounter struct {
104 mux sync.Mutex
105 Total int64 // Total # of bytes written
106}
107
108// Write implements the io.Writer interface.
109//
110// Always completes and never returns an error.
111func (wc *WriteCounter) Write(p []byte) (int, error) {
112 wc.mux.Lock()
113 defer wc.mux.Unlock()
114 n := len(p)
115 wc.Total += int64(n)
116 return n, nil
117}
118
119func (cc *ClientConn) NewFileTransfer(transferType FileTransferType, fileName, filePath, size []byte) *FileTransfer {
120 ft := &FileTransfer{
121 FileName: fileName,
122 FilePath: filePath,
123 Type: transferType,
124 TransferSize: size,
125 ClientConn: cc,
126 bytesSentCounter: &WriteCounter{},
127 }
128
129 cc.Server.FileTransferMgr.Add(ft)
130
131 return ft
132}
133
134// String returns a string representation of a file transfer and its progress for display in the GetInfo window
135// Example:
136// MasterOfOrionII1.4.0. 0% 197.9M
137func (ft *FileTransfer) String() string {
138 trunc := fmt.Sprintf("%.21s", ft.FileName)
139 return fmt.Sprintf("%-21s %.3s%% %6s\n", trunc, ft.percentComplete(), ft.formattedTransferSize())
140}
141
142func (ft *FileTransfer) percentComplete() string {
143 ft.bytesSentCounter.mux.Lock()
144 defer ft.bytesSentCounter.mux.Unlock()
145 return fmt.Sprintf(
146 "%v",
147 math.RoundToEven(float64(ft.bytesSentCounter.Total)/float64(binary.BigEndian.Uint32(ft.TransferSize))*100),
148 )
149}
150
151func (ft *FileTransfer) formattedTransferSize() string {
152 sizeInKB := float32(binary.BigEndian.Uint32(ft.TransferSize)) / 1024
153 if sizeInKB >= 1024 {
154 return fmt.Sprintf("%.1fM", sizeInKB/1024)
155 } else {
156 return fmt.Sprintf("%.0fK", sizeInKB)
157 }
158}
159
160func (ft *FileTransfer) ItemCount() int {
161 return int(binary.BigEndian.Uint16(ft.FolderItemCount))
162}
163
164type folderUpload struct {
165 DataSize [2]byte
166 IsFolder [2]byte
167 PathItemCount [2]byte
168 FileNamePath []byte
169}
170
171//func (fu *folderUpload) Write(p []byte) (int, error) {
172// if len(p) < 7 {
173// return 0, errors.New("buflen too short")
174// }
175// copy(fu.DataSize[:], p[0:2])
176// copy(fu.IsFolder[:], p[2:4])
177// copy(fu.PathItemCount[:], p[4:6])
178//
179// fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes TODO: wat
180// n, err := io.ReadFull(rwc, fu.FileNamePath)
181// if err != nil {
182// return 0, err
183// }
184//
185// return n + 6, nil
186//}
187
188func (fu *folderUpload) FormattedPath() string {
189 pathItemLen := binary.BigEndian.Uint16(fu.PathItemCount[:])
190
191 var pathSegments []string
192 pathData := fu.FileNamePath
193
194 // TODO: implement scanner interface instead?
195 for i := uint16(0); i < pathItemLen; i++ {
196 segLen := pathData[2]
197 pathSegments = append(pathSegments, string(pathData[3:3+segLen]))
198 pathData = pathData[3+segLen:]
199 }
200
201 return filepath.Join(pathSegments...)
202}
203
204type FileHeader struct {
205 Size [2]byte // Total size of FileHeader payload
206 Type [2]byte // 0 for file, 1 for dir
207 FilePath []byte // encoded file path
208
209 readOffset int // Internal offset to track read progress
210}
211
212func NewFileHeader(fileName string, isDir bool) FileHeader {
213 fh := FileHeader{
214 FilePath: EncodeFilePath(fileName),
215 }
216 if isDir {
217 fh.Type = [2]byte{0x00, 0x01}
218 }
219
220 encodedPathLen := uint16(len(fh.FilePath) + len(fh.Type))
221 binary.BigEndian.PutUint16(fh.Size[:], encodedPathLen)
222
223 return fh
224}
225
226func (fh *FileHeader) Read(p []byte) (int, error) {
227 buf := slices.Concat(
228 fh.Size[:],
229 fh.Type[:],
230 fh.FilePath,
231 )
232
233 if fh.readOffset >= len(buf) {
234 return 0, io.EOF // All bytes have been read
235 }
236
237 n := copy(p, buf[fh.readOffset:])
238 fh.readOffset += n
239
240 return n, nil
241}
242
243func DownloadHandler(w io.Writer, fullPath string, fileTransfer *FileTransfer, fs FileStore, rLogger *slog.Logger, preserveForks bool) error {
244 //s.Stats.DownloadCounter += 1
245 //s.Stats.DownloadsInProgress += 1
246 //defer func() {
247 // s.Stats.DownloadsInProgress -= 1
248 //}()
249
250 var dataOffset int64
251 if fileTransfer.FileResumeData != nil {
252 dataOffset = int64(binary.BigEndian.Uint32(fileTransfer.FileResumeData.ForkInfoList[0].DataSize[:]))
253 }
254
255 fw, err := NewFileWrapper(fs, fullPath, 0)
256 if err != nil {
257 return fmt.Errorf("reading file header: %v", err)
258 }
259
260 rLogger.Info("Download file", "filePath", fullPath)
261
262 // If file transfer options are included, that means this is a "quick preview" request. In this case skip sending
263 // the flat file info and proceed directly to sending the file data.
264 if fileTransfer.Options == nil {
265 if _, err = io.Copy(w, fw.Ffo); err != nil {
266 return fmt.Errorf("send flat file object: %v", err)
267 }
268 }
269
270 file, err := fw.dataForkReader()
271 if err != nil {
272 return fmt.Errorf("open data fork reader: %v", err)
273 }
274
275 br := bufio.NewReader(file)
276 if _, err := br.Discard(int(dataOffset)); err != nil {
277 return fmt.Errorf("seek to resume offsent: %v", err)
278 }
279
280 if _, err = io.Copy(w, io.TeeReader(br, fileTransfer.bytesSentCounter)); err != nil {
281 return fmt.Errorf("send data fork: %v", err)
282 }
283
284 // If the client requested to resume transfer, do not send the resource fork header.
285 if fileTransfer.FileResumeData == nil {
286 err = binary.Write(w, binary.BigEndian, fw.rsrcForkHeader())
287 if err != nil {
288 return fmt.Errorf("send resource fork header: %v", err)
289 }
290 }
291
292 rFile, err := fw.rsrcForkFile()
293 if err != nil {
294 // return fmt.Errorf("open resource fork file: %v", err)
295 }
296
297 if _, err = io.Copy(w, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
298 // return fmt.Errorf("send resource fork data: %v", err)
299 }
300
301 return nil
302}
303
304func UploadHandler(rwc io.ReadWriter, fullPath string, fileTransfer *FileTransfer, fileStore FileStore, rLogger *slog.Logger, preserveForks bool) error {
305 var file *os.File
306
307 // A file upload has two possible cases:
308 // 1) Upload a new file
309 // 2) Resume a partially transferred file
310 // We have to infer which case applies by inspecting what is already on the filesystem
311
312 // Check for existing file. If found, do not proceed. This is an invalid scenario, as the file upload transaction
313 // handler should have returned an error to the client indicating there was an existing file present.
314 _, err := os.Stat(fullPath)
315 if err == nil {
316 return fmt.Errorf("existing file found: %s", fullPath)
317 }
318 if errors.Is(err, fs.ErrNotExist) {
319 // If not found, open or create a new .incomplete file
320 file, err = os.OpenFile(fullPath+IncompleteFileSuffix, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
321 if err != nil {
322 return err
323 }
324 }
325
326 f, err := NewFileWrapper(fileStore, fullPath, 0)
327 if err != nil {
328 return err
329 }
330
331 rLogger.Info("File upload started", "dstFile", fullPath)
332
333 rForkWriter := io.Discard
334 iForkWriter := io.Discard
335 if preserveForks {
336 rForkWriter, err = f.rsrcForkWriter()
337 if err != nil {
338 return err
339 }
340
341 iForkWriter, err = f.InfoForkWriter()
342 if err != nil {
343 return err
344 }
345 }
346
347 if err := receiveFile(rwc, file, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
348 rLogger.Error(err.Error())
349 }
350
351 if err := file.Close(); err != nil {
352 return err
353 }
354
355 if err := fileStore.Rename(fullPath+".incomplete", fullPath); err != nil {
356 return err
357 }
358
359 rLogger.Info("File upload complete", "dstFile", fullPath)
360
361 return nil
362}
363
364func DownloadFolderHandler(rwc io.ReadWriter, fullPath string, fileTransfer *FileTransfer, fileStore FileStore, rLogger *slog.Logger, preserveForks bool) error {
365 // Folder Download flow:
366 // 1. Get filePath from the transfer
367 // 2. Iterate over files
368 // 3. For each fileWrapper:
369 // Send fileWrapper header to client
370 // The client can reply in 3 ways:
371 //
372 // 1. If type is an odd number (unknown type?), or fileWrapper download for the current fileWrapper is completed:
373 // client sends []byte{0x00, 0x03} to tell the server to continue to the next fileWrapper
374 //
375 // 2. If download of a fileWrapper is to be resumed:
376 // client sends:
377 // []byte{0x00, 0x02} // download folder action
378 // [2]byte // Resume data size
379 // []byte fileWrapper resume data (see myField_FileResumeData)
380 //
381 // 3. Otherwise, download of the fileWrapper is requested and client sends []byte{0x00, 0x01}
382 //
383 // When download is requested (case 2 or 3), server replies with:
384 // [4]byte - fileWrapper size
385 // []byte - Flattened File Object
386 //
387 // After every fileWrapper download, client could request next fileWrapper with:
388 // []byte{0x00, 0x03}
389 //
390 // This notifies the server to send the next item header
391
392 basePathLen := len(fullPath)
393
394 rLogger.Info("Start folder download", "path", fullPath)
395
396 nextAction := make([]byte, 2)
397 if _, err := io.ReadFull(rwc, nextAction); err != nil {
398 return err
399 }
400
401 i := 0
402 err := filepath.Walk(fullPath+"/", func(path string, info os.FileInfo, err error) error {
403 //s.Stats.DownloadCounter += 1
404 i += 1
405
406 if err != nil {
407 return err
408 }
409
410 // skip dot files
411 if strings.HasPrefix(info.Name(), ".") {
412 return nil
413 }
414
415 hlFile, err := NewFileWrapper(fileStore, path, 0)
416 if err != nil {
417 return err
418 }
419
420 subPath := path[basePathLen+1:]
421 rLogger.Debug("Sending fileheader", "i", i, "path", path, "fullFilePath", fullPath, "subPath", subPath, "IsDir", info.IsDir())
422
423 if i == 1 {
424 return nil
425 }
426
427 fileHeader := NewFileHeader(subPath, info.IsDir())
428 if _, err := io.Copy(rwc, &fileHeader); err != nil {
429 return fmt.Errorf("error sending file header: %w", err)
430 }
431
432 // Read the client's Next Action request
433 if _, err := io.ReadFull(rwc, nextAction); err != nil {
434 return err
435 }
436
437 rLogger.Debug("Client folder download action", "action", fmt.Sprintf("%X", nextAction[0:2]))
438
439 var dataOffset int64
440
441 switch nextAction[1] {
442 case DlFldrActionResumeFile:
443 // get size of resumeData
444 resumeDataByteLen := make([]byte, 2)
445 if _, err := io.ReadFull(rwc, resumeDataByteLen); err != nil {
446 return err
447 }
448
449 resumeDataLen := binary.BigEndian.Uint16(resumeDataByteLen)
450 resumeDataBytes := make([]byte, resumeDataLen)
451 if _, err := io.ReadFull(rwc, resumeDataBytes); err != nil {
452 return err
453 }
454
455 var frd FileResumeData
456 if err := frd.UnmarshalBinary(resumeDataBytes); err != nil {
457 return err
458 }
459 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
460 case DlFldrActionNextFile:
461 // client asked to skip this file
462 return nil
463 }
464
465 if info.IsDir() {
466 return nil
467 }
468
469 rLogger.Info("File download started",
470 "fileName", info.Name(),
471 "TransferSize", fmt.Sprintf("%x", hlFile.Ffo.TransferSize(dataOffset)),
472 )
473
474 // Send file size to client
475 if _, err := rwc.Write(hlFile.Ffo.TransferSize(dataOffset)); err != nil {
476 rLogger.Error(err.Error())
477 return fmt.Errorf("error sending file size: %w", err)
478 }
479
480 // Send ffo bytes to client
481 _, err = io.Copy(rwc, hlFile.Ffo)
482 if err != nil {
483 return fmt.Errorf("error sending flat file object: %w", err)
484 }
485
486 file, err := fileStore.Open(path)
487 if err != nil {
488 return fmt.Errorf("error opening file: %w", err)
489 }
490
491 // wr := bufio.NewWriterSize(rwc, 1460)
492 if _, err = io.Copy(rwc, io.TeeReader(file, fileTransfer.bytesSentCounter)); err != nil {
493 return fmt.Errorf("error sending file: %w", err)
494 }
495
496 if nextAction[1] != 2 && hlFile.Ffo.FlatFileHeader.ForkCount[1] == 3 {
497 err = binary.Write(rwc, binary.BigEndian, hlFile.rsrcForkHeader())
498 if err != nil {
499 return fmt.Errorf("error sending resource fork header: %w", err)
500 }
501
502 rFile, err := hlFile.rsrcForkFile()
503 if err != nil {
504 return fmt.Errorf("error opening resource fork: %w", err)
505 }
506
507 if _, err = io.Copy(rwc, io.TeeReader(rFile, fileTransfer.bytesSentCounter)); err != nil {
508 return fmt.Errorf("error sending resource fork: %w", err)
509 }
510 }
511
512 // Read the client's Next Action request. This is always 3, I think?
513 if _, err := io.ReadFull(rwc, nextAction); err != nil && err != io.EOF {
514 return fmt.Errorf("error reading client next action: %w", err)
515 }
516
517 return nil
518 })
519
520 if err != nil {
521 return err
522 }
523
524 return nil
525}
526
527func UploadFolderHandler(rwc io.ReadWriter, fullPath string, fileTransfer *FileTransfer, fileStore FileStore, rLogger *slog.Logger, preserveForks bool) error {
528
529 // Check if the target folder exists. If not, create it.
530 if _, err := fileStore.Stat(fullPath); os.IsNotExist(err) {
531 if err := fileStore.Mkdir(fullPath, 0777); err != nil {
532 return err
533 }
534 }
535
536 // Begin the folder upload flow by sending the "next file action" to client
537 if _, err := rwc.Write([]byte{0, DlFldrActionNextFile}); err != nil {
538 return err
539 }
540
541 fileSize := make([]byte, 4)
542
543 for i := 0; i < fileTransfer.ItemCount(); i++ {
544 //s.Stats.UploadCounter += 1
545
546 var fu folderUpload
547 // TODO: implement io.Writer on folderUpload and replace this
548 if _, err := io.ReadFull(rwc, fu.DataSize[:]); err != nil {
549 return err
550 }
551 if _, err := io.ReadFull(rwc, fu.IsFolder[:]); err != nil {
552 return err
553 }
554 if _, err := io.ReadFull(rwc, fu.PathItemCount[:]); err != nil {
555 return err
556 }
557 fu.FileNamePath = make([]byte, binary.BigEndian.Uint16(fu.DataSize[:])-4) // -4 to subtract the path separator bytes TODO: wat
558 if _, err := io.ReadFull(rwc, fu.FileNamePath); err != nil {
559 return err
560 }
561
562 if fu.IsFolder == [2]byte{0, 1} {
563 if _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath())); os.IsNotExist(err) {
564 if err := os.Mkdir(filepath.Join(fullPath, fu.FormattedPath()), 0777); err != nil {
565 return err
566 }
567 }
568
569 // Tell client to send next file
570 if _, err := rwc.Write([]byte{0, DlFldrActionNextFile}); err != nil {
571 return err
572 }
573 } else {
574 nextAction := DlFldrActionSendFile
575
576 // Check if we have the full file already. If so, send dlFldrAction_NextFile to client to skip.
577 _, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()))
578 if err != nil && !errors.Is(err, fs.ErrNotExist) {
579 return err
580 }
581 if err == nil {
582 nextAction = DlFldrActionNextFile
583 }
584
585 // Check if we have a partial file already. If so, send dlFldrAction_ResumeFile to client to resume upload.
586 incompleteFile, err := os.Stat(filepath.Join(fullPath, fu.FormattedPath()+IncompleteFileSuffix))
587 if err != nil && !errors.Is(err, fs.ErrNotExist) {
588 return err
589 }
590 if err == nil {
591 nextAction = DlFldrActionResumeFile
592 }
593
594 if _, err := rwc.Write([]byte{0, uint8(nextAction)}); err != nil {
595 return err
596 }
597
598 switch nextAction {
599 case DlFldrActionNextFile:
600 continue
601 case DlFldrActionResumeFile:
602 offset := make([]byte, 4)
603 binary.BigEndian.PutUint32(offset, uint32(incompleteFile.Size()))
604
605 file, err := os.OpenFile(fullPath+"/"+fu.FormattedPath()+IncompleteFileSuffix, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
606 if err != nil {
607 return err
608 }
609
610 fileResumeData := NewFileResumeData([]ForkInfoList{*NewForkInfoList(offset)})
611
612 b, _ := fileResumeData.BinaryMarshal()
613
614 bs := make([]byte, 2)
615 binary.BigEndian.PutUint16(bs, uint16(len(b)))
616
617 if _, err := rwc.Write(append(bs, b...)); err != nil {
618 return err
619 }
620
621 if _, err := io.ReadFull(rwc, fileSize); err != nil {
622 return err
623 }
624
625 if err := receiveFile(rwc, file, io.Discard, io.Discard, fileTransfer.bytesSentCounter); err != nil {
626 rLogger.Error(err.Error())
627 }
628
629 err = os.Rename(fullPath+"/"+fu.FormattedPath()+".incomplete", fullPath+"/"+fu.FormattedPath())
630 if err != nil {
631 return err
632 }
633
634 case DlFldrActionSendFile:
635 if _, err := io.ReadFull(rwc, fileSize); err != nil {
636 return err
637 }
638
639 filePath := filepath.Join(fullPath, fu.FormattedPath())
640
641 hlFile, err := NewFileWrapper(fileStore, filePath, 0)
642 if err != nil {
643 return err
644 }
645
646 rLogger.Info("Starting file transfer", "path", filePath, "fileNum", i+1, "fileSize", binary.BigEndian.Uint32(fileSize))
647
648 incWriter, err := hlFile.incFileWriter()
649 if err != nil {
650 return err
651 }
652
653 rForkWriter := io.Discard
654 iForkWriter := io.Discard
655 if preserveForks {
656 iForkWriter, err = hlFile.InfoForkWriter()
657 if err != nil {
658 return err
659 }
660
661 rForkWriter, err = hlFile.rsrcForkWriter()
662 if err != nil {
663 return err
664 }
665 }
666 if err := receiveFile(rwc, incWriter, rForkWriter, iForkWriter, fileTransfer.bytesSentCounter); err != nil {
667 return err
668 }
669
670 if err := os.Rename(filePath+".incomplete", filePath); err != nil {
671 return err
672 }
673 }
674
675 // Tell client to send next fileWrapper
676 if _, err := rwc.Write([]byte{0, DlFldrActionNextFile}); err != nil {
677 return err
678 }
679 }
680 }
681 rLogger.Info("Folder upload complete")
682 return nil
683}