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