Files

114 lines
3.6 KiB
Go
Executable File

package main
import (
"fmt"
"os"
"path/filepath"
"lanrdp/internal/protocol"
)
// fileTransferState tracks one in-progress incoming file. Only one
// transfer is ever active at a time per session — the client serializes
// drag-and-drop sends on its end, and this struct doesn't try to
// interleave multiple concurrent transfers.
type fileTransferState struct {
f *os.File
path string
expected uint64
written uint64
}
// receivedFilesDir returns (creating if needed) the folder incoming files
// are saved to: a dedicated, clearly-labeled subfolder of the current
// user's Desktop, so transfers are easy to find and never silently land
// somewhere unexpected.
func receivedFilesDir() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("resolving home directory: %w", err)
}
dir := filepath.Join(home, "Desktop", "lanrdp-received")
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", fmt.Errorf("creating %s: %w", dir, err)
}
return dir, nil
}
// sanitizeFilename strips any directory components from a client-supplied
// name so a crafted filename (e.g. "..\..\Windows\System32\x") can never
// write outside receivedFilesDir. filepath.Base collapses ".." components
// and separators, leaving only the final path element.
func sanitizeFilename(name string) string {
name = filepath.Base(name)
if name == "" || name == "." || name == ".." || name == string(filepath.Separator) {
return "upload.bin"
}
return name
}
// uniquePath returns path if nothing exists there yet, otherwise appends
// " (1)", " (2)", ... before the extension until it finds a free name —
// the same convention Windows Explorer uses for duplicate downloads —
// rather than silently overwriting an existing file.
func uniquePath(path string) string {
if _, err := os.Stat(path); os.IsNotExist(err) {
return path
}
ext := filepath.Ext(path)
base := path[:len(path)-len(ext)]
for i := 1; ; i++ {
candidate := fmt.Sprintf("%s (%d)%s", base, i, ext)
if _, err := os.Stat(candidate); os.IsNotExist(err) {
return candidate
}
}
}
func startFileTransfer(offer protocol.FileOffer) (*fileTransferState, error) {
dir, err := receivedFilesDir()
if err != nil {
return nil, err
}
path := uniquePath(filepath.Join(dir, sanitizeFilename(offer.Name)))
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0o644)
if err != nil {
return nil, fmt.Errorf("creating destination file: %w", err)
}
return &fileTransferState{f: f, path: path, expected: offer.Size}, nil
}
// maxOverage bounds how far written can exceed the declared size before
// giving up — guards against a runaway/malicious sender that never sends
// MsgFileComplete and just keeps streaming chunks indefinitely.
const maxOverage = 16 * 1024 * 1024
func (x *fileTransferState) writeChunk(data []byte) error {
n, err := x.f.Write(data)
x.written += uint64(n)
if err != nil {
return fmt.Errorf("writing file: %w", err)
}
if x.written > x.expected+maxOverage {
return fmt.Errorf("received far more data than the declared size")
}
return nil
}
// finish closes and verifies the transfer, deleting the partial file on
// any mismatch rather than leaving a possibly-truncated file behind.
func (x *fileTransferState) finish(declaredSent uint64) (ok bool, message string) {
_ = x.f.Close()
if x.written != x.expected || x.written != declaredSent {
_ = os.Remove(x.path)
return false, fmt.Sprintf("size mismatch (wrote %d bytes, expected %d)", x.written, x.expected)
}
return true, fmt.Sprintf("saved to %s (%d bytes)", x.path, x.written)
}
func (x *fileTransferState) abort() {
_ = x.f.Close()
_ = os.Remove(x.path)
}