Compare commits
118 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 80768d64d4 | |||
| e876055167 | |||
| 3d2eb97205 | |||
| da20bb4d37 | |||
| 3e4c571355 | |||
| 05dab758cf | |||
| 8cc587b79e | |||
| 896ff05250 | |||
| 29a6b5fd84 | |||
| dff15110e8 | |||
| 7d8f593844 | |||
| 348e72e706 | |||
| 58af932b30 | |||
| 5e9f594af9 | |||
| afe6f4144b | |||
| 016c4030c5 | |||
| 95be50fead | |||
| 7eeaeea84a | |||
| 4f383cc5a5 | |||
| 8ad91b8b87 | |||
| 69773bd16a | |||
| 269ce0749b | |||
| 52d5492dee | |||
| e68e33c0c5 | |||
| 3b621e591a | |||
| d3dca6c2a5 | |||
| 29f4f8cde6 | |||
| c5acd13df2 | |||
| 41485cbe22 | |||
| c6bf7bb84e | |||
| 30239c6f50 | |||
| d21f6c8be9 | |||
| 0bee82e863 | |||
| bfc2b1f6eb | |||
| 7436b3b148 | |||
| a70ce5c4af | |||
| 415adf2077 | |||
| 3b5d89fdb9 | |||
| 2e73c6dc13 | |||
| 909d84b36e | |||
| 959e5eb959 | |||
| df6d78b6ef | |||
| 6c730c9775 | |||
| a6c471a97a | |||
| ab4bb84ed6 | |||
| 7d14d2b672 | |||
| 4bba1e8c02 | |||
| 3d598040dd | |||
| 09dc449a5c | |||
| 86c1d159cb | |||
| be79c014d4 | |||
| 081973c904 | |||
| c21950493a | |||
| ce39f2a910 | |||
| 1929e7d7b3 | |||
| 1ce771b553 | |||
| 60ab410a8c | |||
| 7adb82f8ac | |||
| 62f3df94ee | |||
| 61fd410c63 | |||
| 1c3b752a8e | |||
| 1a765e595b | |||
| 94ff55f256 | |||
| ddfd0f1cc2 | |||
| e34ec3d594 | |||
| f932a48910 | |||
| 23af379bfb | |||
| 31da8bf081 | |||
| 0cbc873f5c | |||
| 925760d1bd | |||
| 83c61aadc2 | |||
| 552561146a | |||
| cdd6d1cfed | |||
| e62296d92f | |||
| 5d819f7388 | |||
| 4339d7905d | |||
| 3ffc5c5236 | |||
| 224e7e8599 | |||
| 9a214c46e2 | |||
| 9dd925a87d | |||
| 4b93082139 | |||
| 8234677276 | |||
| 262a436264 | |||
| 70e1c6788a | |||
| 30d4d6870c | |||
| 744ac8e40c | |||
| 9042dfcfa9 | |||
| e2a500e321 | |||
| a91267ca1b | |||
| cf572ece04 | |||
| f486d34b16 | |||
| e3bd7a8cdf | |||
| 266369b1f2 | |||
| a4fc16650e | |||
| eef272fa4e | |||
| 5e8d0a2dbf | |||
| 62ff1d3929 | |||
| ba0afd4152 | |||
| 3923421224 | |||
| 27e3ac11db | |||
| 9e3e0f57a0 | |||
| e5b46bb1c0 | |||
| 86247fe2b5 | |||
| 788d3c7bea | |||
| 7ecba4e0d5 | |||
| 16376bcafc | |||
| d75701270d | |||
| 990c4362af | |||
| 6b8979a040 | |||
| bcf5ffcf40 | |||
| 5049a7bbf0 | |||
| e6e8679bfc | |||
| 6831e7e6fb | |||
| e3484939b6 | |||
| 2f9a4fac78 | |||
| e1f9ba090f | |||
| f6b4d89a3c | |||
| 8f25f6a6b6 |
@@ -5,3 +5,6 @@ __pycache__/
|
||||
build-asan
|
||||
coverage.info
|
||||
build-*/
|
||||
build2/
|
||||
build3/
|
||||
build_docker2/
|
||||
|
||||
@@ -60,15 +60,153 @@ python3 -m pytest tests/ # integration tests
|
||||
|
||||
When running the CI workflow via `tea` (the task execution agent), always set a sufficient timeout (e.g., 600000ms) to allow CI to finish. After CI completes, check the results yourself — do not assume success. Use `gh run watch` or similar to monitor CI status, then inspect logs on failure.
|
||||
|
||||
## CI Troubleshooting
|
||||
|
||||
### If lint (clang-format) fails
|
||||
Run clang-format in the CI Docker image to match the exact CI version:
|
||||
```bash
|
||||
docker run --rm -v "$PWD:/workspace" -w /workspace gitea.tap-tap.win/taptap/fastsync-ci:v9 \
|
||||
sh -c 'find src/ tests/ -name "*.c" -o -name "*.h" | xargs clang-format -i'
|
||||
```
|
||||
|
||||
### If cppcheck fails
|
||||
Fix reported issues locally, then verify with:
|
||||
```bash
|
||||
docker run --rm -v "$PWD:/workspace" -w /workspace gitea.tap-tap.win/taptap/fastsync-ci:v9 \
|
||||
sh -c 'cppcheck --enable=warning,style,performance,portability --suppress=missingIncludeSystem --error-exitcode=1 --inline-suppr src/ tests/'
|
||||
```
|
||||
|
||||
### If integration tests fail
|
||||
Run locally before pushing:
|
||||
```bash
|
||||
python3 -m pytest tests/ -v --tb=short
|
||||
```
|
||||
|
||||
## Branch Strategy
|
||||
|
||||
Never push directly to `main`. All changes must be developed on a feature branch and merged via a pull request. Always create a new branch before making changes:
|
||||
Two main branches: `dev` (integration) and `main` (stable releases).
|
||||
|
||||
### Rules
|
||||
- **All PRs target `dev`** — never target `main` directly
|
||||
- **`dev` is the default branch** in Gitea repo settings
|
||||
- **`main` is protected** — only merged from `dev` via PR with 2 approvals + full CI pass
|
||||
- **Feature/bug branches** branch from `dev`, PR back to `dev`
|
||||
- **`dev` → `main` merges** happen on-demand or weekly, requiring full CI + review
|
||||
|
||||
```bash
|
||||
git checkout -b <feature-branch-name>
|
||||
# Start a new feature
|
||||
git checkout dev && git pull
|
||||
git checkout -b feat/my-feature
|
||||
# ... work, commit, push
|
||||
git push -u origin feat/my-feature
|
||||
# Create PR targeting dev
|
||||
```
|
||||
After committing changes, push the branch and create a PR:
|
||||
|
||||
### Creating the `dev` branch (one-time setup)
|
||||
```bash
|
||||
git push -u origin <feature-branch-name>
|
||||
gh pr create --fill
|
||||
git checkout main && git pull
|
||||
git checkout -b dev
|
||||
git push origin dev
|
||||
# Then in Gitea: Settings → Repository → Default Branch → dev
|
||||
```
|
||||
Wait for CI to pass on the PR before merging.
|
||||
|
||||
### Branch protection (Gitea repo settings)
|
||||
**For `dev`:**
|
||||
- ✅ Require PR for merging
|
||||
- ✅ Require 1 approval
|
||||
- ✅ Require status checks (all CI jobs must pass)
|
||||
- ✅ Delete branch after merge
|
||||
|
||||
**For `main`:**
|
||||
- ✅ Require PR from `dev` only
|
||||
- ✅ Require CI
|
||||
- ✅ Require 2 approvals
|
||||
- ✅ No direct pushes
|
||||
|
||||
## Automated Agent Workflows
|
||||
|
||||
All agents run locally via the opencode CLI. There is no CI-based agent automation — agents are invoked on-demand by the developer or by this assistant.
|
||||
|
||||
### One-command batch workflow
|
||||
|
||||
For fixing a set of issues and creating one integration PR:
|
||||
|
||||
```bash
|
||||
# 1. Run each subagent on its category
|
||||
opencode run --agent security-auditor "Fix all open security issues"
|
||||
opencode run --agent debugger "Fix all open bugs"
|
||||
opencode run --agent test-writer "Add missing test coverage"
|
||||
|
||||
# 2. The assistant handles: merging branches, fixing CI failures,
|
||||
# pushing, creating the integration PR, waiting for CI, iterating.
|
||||
# The developer only reviews the final PR.
|
||||
```
|
||||
|
||||
### Issue triage loop
|
||||
When you want to fix a batch of issues autonomously:
|
||||
|
||||
1. Tell the assistant: *"Fix all open issues and create one big PR"*
|
||||
2. The assistant delegates to subagents in parallel
|
||||
3. Merges their branches, handles CI failures iteratively
|
||||
4. Pushes and opens the final PR
|
||||
5. You review the PR once CI passes — no intermediate check-ins
|
||||
|
||||
### Scheduling
|
||||
For periodic maintenance (security audits, code quality scans), run:
|
||||
|
||||
```bash
|
||||
opencode run --agent security-auditor "Audit the codebase for vulnerabilities"
|
||||
opencode run --agent code-quality-guardian "Scan for code quality issues"
|
||||
```
|
||||
|
||||
This can be cron'd locally if desired (e.g., `crontab -e` with `opencode run`).
|
||||
|
||||
## Is opencode a good option?
|
||||
|
||||
**Yes, for FastSync's needs.** The hybrid model works well:
|
||||
- opencode's 17 specialized agents handle deep code analysis, fixes, tests, and reviews
|
||||
- The assistant orchestrates subagents, merges branches, and iterates on CI
|
||||
- You only review the final output
|
||||
|
||||
The key limitation: opencode is session-based, not a persistent daemon. But for the "fix all issues, one PR" workflow, this is fine — the assistant runs the full pipeline in one shot. Persistent webhook-driven automation isn't available for Gitea, but the one-shot batch approach is simpler and gives you full control over what gets merged.
|
||||
|
||||
### Recommendations for this project
|
||||
- **Do** use the batch pattern: delegate to subagents, let the assistant merge + iterate CI, review once
|
||||
- **Don't** try to run opencode in Gitea Actions — the CI container doesn't have your LLM keys or the interactive context agents need
|
||||
- **If** you want fully hands-off periodic scans, set up a local cron job or systemd timer that runs `opencode run` and posts results to Gitea via API
|
||||
|
||||
## Gitea API & tea CLI
|
||||
|
||||
### Check CI status via API
|
||||
```bash
|
||||
TOKEN="<token>"
|
||||
curl -s -H "Authorization: token $TOKEN" \
|
||||
"https://gitea.tap-tap.win/api/v1/repos/TapTap/FastSync/actions/runs?limit=5" \
|
||||
| python3 -c "
|
||||
import json,sys; d=json.load(sys.stdin)
|
||||
for r in d.get('workflow_runs',[]):
|
||||
path = r.get('path','')
|
||||
prn = path.split('@')[1].replace('refs/pull/','').replace('/head','') if '@' in path else ''
|
||||
print(f'PR #{prn}: sha={r[\"head_sha\"][:8]} {r[\"status\"]} {r.get(\"conclusion\",\"\")}')
|
||||
"
|
||||
```
|
||||
|
||||
### Post review comments
|
||||
```bash
|
||||
curl -s -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{"body":"MARKDOWN_REVIEW_BODY"}' \
|
||||
"https://gitea.tap-tap.win/api/v1/repos/TapTap/FastSync/issues/<PR_NUMBER>/comments"
|
||||
```
|
||||
|
||||
### Use tea for PR operations
|
||||
```bash
|
||||
tea pr list --repo TapTap/FastSync
|
||||
tea pr close <number> --repo TapTap/FastSync
|
||||
```
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
- **`__thread` on shared SSL context**: io_ssl must NOT be thread-local — worker threads inherit the SSL context from the main thread. Use regular `static SSL* io_ssl`.
|
||||
- **SSL WANT_READ/WANT_WRITE retry**: Always retry on `SSL_ERROR_WANT_READ` and `SSL_ERROR_WANT_WRITE` in `send_n_data`/`receive_n_data`. Removing these breaks TLS multithreaded transfers.
|
||||
- **clang-format version**: The CI image uses clang-format 18. Always format inside the CI Docker container for exact match.
|
||||
- **Merge order matters**: Merge the most comprehensive branch first, then smaller ones, to minimize conflicts when creating a combined branch.
|
||||
|
||||
@@ -5,17 +5,26 @@ A high-performance file synchronization system with SSH and TCP transport, TLS e
|
||||
## Technical Overview
|
||||
|
||||
1. **Dual transport**: custom TCP client-server or SSH subprocess (rsync-style `user@host:/path`)
|
||||
2. **TLS encryption**: OpenSSL-based TLS 1.2+ for encrypted TCP connections
|
||||
2. **TLS encryption**: OpenSSL-based TLS 1.2+ for encrypted TCP connections with optional CA verification
|
||||
3. **Chunked file transfer**: files grouped into configurable-size chunks (default ~10 MB)
|
||||
4. **Streaming zstd compression** (levels 1–22) using `ZSTD_compressStream2`
|
||||
5. **Multithreading**: producer-consumer pipeline with thread-safe queues (scanner → loader → sender)
|
||||
6. **Incremental sync**: skip files unchanged since last transfer (compares size + mtime)
|
||||
7. **Metadata preservation**: `mode`, `uid`, `gid`, `mtime` restored on disk when enabled
|
||||
8. **`sendfile()` zero-copy** on TCP (~2× faster on loopback)
|
||||
9. **SSH ControlMaster** for connection reuse across repeated invocations
|
||||
10. **Bandwidth limiting**: token-bucket throttling (`--bwlimit`)
|
||||
11. **`--delete`**: receiver removes files not present in sender manifest
|
||||
12. **`--exclude` / `--include`**: glob-pattern filename filtering
|
||||
7. **Batch incremental**: send incremental checks in batched groups for reduced round-trips
|
||||
8. **Metadata preservation**: `mode`, `uid`, `gid`, `mtime` restored on disk when enabled
|
||||
9. **`sendfile()` zero-copy** on TCP (~2× faster on loopback)
|
||||
10. **SSH ControlMaster** for connection reuse across repeated invocations
|
||||
11. **Bandwidth limiting**: token-bucket throttling (`--bwlimit`)
|
||||
12. **`--delete`**: receiver removes files not present in sender manifest
|
||||
13. **`--exclude` / `--include`**: glob-pattern filename filtering
|
||||
14. **Path traversal protection**: `..` sequences in file paths are rejected automatically
|
||||
15. **Connection limits**: server enforces maximum concurrent connections (default 100)
|
||||
16. **Keep-alive**: periodic `STATUS_KEEPALIVE` messages detect stalled connections
|
||||
17. **Abort handling**: `SIGINT` sends `STATUS_ABORT` for clean server-side teardown
|
||||
18. **Atomic writes**: received files are written to a temporary name then atomically renamed
|
||||
19. **Backup mode**: `--backup` preserves overwritten files with optional `--backup-dir`
|
||||
20. **Log file**: `--log-file` redirects log output to a file instead of stderr
|
||||
21. **Transfer statistics**: `--stats` prints summary of transferred bytes, files, and timing
|
||||
|
||||
## System Architecture
|
||||
|
||||
@@ -25,20 +34,33 @@ A high-performance file synchronization system with SSH and TCP transport, TLS e
|
||||
- Streaming zstd compression with configurable level
|
||||
- Chunk serialization (compact binary format) or per-file transfer
|
||||
- Incremental transfer: sends file metadata to server, skips unchanged files
|
||||
- Batch incremental: groups incremental checks to minimize round-trips
|
||||
- Manifests all sent paths when `--delete` is active
|
||||
- Sends via TCP `sendfile()` or SSH pipe
|
||||
- Optional progress display with throughput
|
||||
- Bandwidth limiting via token-bucket algorithm
|
||||
- Configurable I/O and connection timeouts (`--timeout`, `--contimeout`)
|
||||
- Quiet mode (`-q`/`--quiet`) suppresses all non-error output
|
||||
- Backup overwritten files (`--backup`) with optional directory (`--backup-dir`)
|
||||
- Transfer statistics summary (`--stats`)
|
||||
- Maximum directory depth control (`--max-depth`)
|
||||
- Log file output (`--log-file`)
|
||||
- Configurable multithreaded queue size (`--queue-size`)
|
||||
- Exclude patterns from file (`--exclude-from`)
|
||||
|
||||
### Server
|
||||
- TCP mode: listens on configurable port (default 8080); SSH mode: runs via `--stdio`
|
||||
- TLS mode: wraps TCP connections with OpenSSL
|
||||
- TLS mode: wraps TCP connections with OpenSSL with optional CA verification
|
||||
- Receives and reassembles files
|
||||
- Decompresses (streaming zstd), deserializes, restores metadata
|
||||
- Handles incremental checks: compares size + mtime against destination files
|
||||
- Handles batch incremental checks for reduced round-trips
|
||||
- Processes `STATUS_MANIFEST` for `--delete`: walks destination tree, removes extras
|
||||
- Per-connection concurrency via `fork()`
|
||||
- Per-connection concurrency via `fork()` with configurable connection limit (default 100)
|
||||
- Thread pool for parallel processing
|
||||
- Atomic writes: files written to `.tmp` path then atomically renamed on success
|
||||
- Abort handling: cleanly shuts down on `STATUS_ABORT` from client
|
||||
- Path traversal protection: rejects file paths containing `..`
|
||||
|
||||
## Protocol Details
|
||||
|
||||
@@ -52,6 +74,11 @@ A high-performance file synchronization system with SSH and TCP transport, TLS e
|
||||
| `STATUS_CHUNK` | Following data is a serialized chunk |
|
||||
| `STATUS_MANIFEST` | Following data is a file manifest (for `--delete`) |
|
||||
| `STATUS_CHECK` | Incremental check: client sends file path + size + mtime, server responds with OK (skip) or NEXT (send) |
|
||||
| `STATUS_CHECK_BATCH` | Batch incremental check: multiple file checks sent in one message |
|
||||
| `STATUS_KEEPALIVE` | Keep-alive heartbeat to detect stalled connections |
|
||||
| `STATUS_ABORT` | Abort signal: client interrupts, server cleans up and exits |
|
||||
| `STATUS_DELTA_SIGNATURE` | Delta sync: following data is a file signature (rsync-style rolling hash) |
|
||||
| `STATUS_DELTA_DATA` | Delta sync: following data is a delta patch for a file |
|
||||
|
||||
### Wire Format — Metadata
|
||||
|
||||
@@ -59,12 +86,16 @@ When `use_metadata` is enabled (`-M`), each file entry carries a 4-byte `present
|
||||
|
||||
### Transfer Flow
|
||||
```
|
||||
Config → (STATUS_NEXT | STATUS_CHUNK | STATUS_CHECK)* → [STATUS_MANIFEST] → STATUS_FINISHED → STATUS_OK
|
||||
Config → (STATUS_NEXT | STATUS_CHUNK | STATUS_CHECK | STATUS_CHECK_BATCH)* → [STATUS_MANIFEST] → STATUS_FINISHED → STATUS_OK
|
||||
```
|
||||
|
||||
Keep-alive (`STATUS_KEEPALIVE`) may be sent at any point during the transfer. The receiver resets its inactivity timer on receipt. If no data arrives within the receive timeout, the connection is aborted.
|
||||
|
||||
Abort (`STATUS_ABORT`) may be sent at any point. On receipt the server cleans up temporary files and exits the child process.
|
||||
|
||||
### Protocol Version
|
||||
|
||||
`1.1.0` — server and client must match. Mismatch results in `STATUS_ERROR`.
|
||||
`1.3.0` — server and client must match. Mismatch results in `STATUS_ERROR`.
|
||||
|
||||
## Command-Line Arguments
|
||||
|
||||
@@ -83,15 +114,26 @@ Config → (STATUS_NEXT | STATUS_CHUNK | STATUS_CHECK)* → [STATUS_MANIFEST]
|
||||
| `-n, --dry-run` | Scan and print what would be transferred |
|
||||
| `-p <port>` | SSH port (default: 22) |
|
||||
| `-v, --verbose` | Enable debug logging |
|
||||
| `-q, --quiet` | Suppress all non-error output |
|
||||
| `--silent` | Alias for `--quiet` |
|
||||
| `--progress` | Show real-time transfer speed |
|
||||
| `--delete` | Delete files on receiver not present in source |
|
||||
| `--exclude <pattern>` | Exclude files matching glob pattern (repeatable) |
|
||||
| `--exclude-from <file>` | Read exclude patterns from a file (one per line) |
|
||||
| `--include <pattern>` | Only transfer files matching glob pattern (repeatable, whitelist) |
|
||||
| `--max-size <n>` | Skip files larger than n bytes |
|
||||
| `--min-size <n>` | Skip files smaller than n bytes |
|
||||
| `--incremental` | Skip files unchanged since last transfer (size + mtime). Auto-enables `--preserve`. Incompatible with `-s`. |
|
||||
| `--bwlimit <KB/s>` | Bandwidth limit in kilobytes per second |
|
||||
| `--chunk-size <n>` | Chunk size in bytes (default: 10485760) |
|
||||
| `--timeout <sec>` | I/O timeout in seconds (default: 30) |
|
||||
| `--contimeout <sec>` | Connection timeout in seconds (default: 10) |
|
||||
| `--backup` | Backup existing destination files before overwriting |
|
||||
| `--backup-dir <dir>` | Target directory for backups (requires `--backup`) |
|
||||
| `--stats` | Print transfer statistics at end (bytes, files, timing) |
|
||||
| `--max-depth <n>` | Maximum directory depth to recurse (0 = unlimited, default: 0) |
|
||||
| `--log-file <path>` | Write log messages to file instead of stderr |
|
||||
| `--queue-size <n>` | Queue capacity for multithreaded mode (default: 100) |
|
||||
| `--source-dir <path>` | Source directory (overrides `FASTSYNC_SOURCE_DIR`) |
|
||||
| `--dest-dir <path>` | Server destination directory (overrides `FASTSYNC_DEST_DIR`) |
|
||||
| `--save-to-disk` | Write received files to disk |
|
||||
@@ -122,6 +164,12 @@ Config → (STATUS_NEXT | STATUS_CHUNK | STATUS_CHECK)* → [STATUS_MANIFEST]
|
||||
| `FASTSYNC_SOURCE_DIR` | — | Source directory fallback |
|
||||
| `FASTSYNC_DEST_DIR` | — | Destination directory fallback |
|
||||
| `FASTSYNC_SAVE_TO_DISK` | `false` | Disk persistence fallback |
|
||||
| `FASTSYNC_SSH_PORT` | `22` | Default SSH port |
|
||||
| `FASTSYNC_SERVER_HOST` | `127.0.0.1` | Default server host |
|
||||
| `FASTSYNC_SERVER_PORT` | `8080` | Default server port |
|
||||
| `FASTSYNC_TLS_CERT` | — | Default TLS certificate path |
|
||||
| `FASTSYNC_TLS_KEY` | — | Default TLS private key path |
|
||||
| `FASTSYNC_TLS_CA` | — | Default TLS CA certificate path |
|
||||
|
||||
## Implementation Details
|
||||
|
||||
@@ -129,21 +177,44 @@ Config → (STATUS_NEXT | STATUS_CHUNK | STATUS_CHECK)* → [STATUS_MANIFEST]
|
||||
1. **Chunk** — collection of files (~10 MB total by default)
|
||||
2. **File** — path, content (`Data`), optional `FileMetadata` pointer
|
||||
3. **FileMetadata** — `mode`, `uid`, `gid`, `mtime_sec`, `mtime_nsec`
|
||||
4. **Config** — runtime parameters (transported over wire, TLS settings excluded)
|
||||
4. **Config** — runtime parameters (transported over wire, TLS settings excluded). Includes `timeout`, `contimeout`, `quiet`, `backup`, `backup_dir`, `stats`, `max_depth`, `log_file`, `queue_size`.
|
||||
5. **Queue** — thread-safe bounded queue with condition variables
|
||||
6. **DirectoryScanner** — recursive BFS traversal with exclude and include pattern support
|
||||
6. **DirectoryScanner** — recursive BFS traversal with exclude and include pattern support, max-depth enforcement
|
||||
|
||||
### Key Algorithms
|
||||
1. **File scanning** — BFS directory traversal; entries matched against exclude and include patterns
|
||||
1. **File scanning** — BFS directory traversal; entries matched against exclude and include patterns, max-depth enforced
|
||||
2. **Chunking** — files accumulated until `chunk_size` threshold, then flushed
|
||||
3. **Compression** — streaming zstd via `ZSTD_compressStream2` / `ZSTD_decompressStream`
|
||||
4. **Network protocol** — status-code-driven exchange with metadata packing
|
||||
5. **Incremental check** — client sends `STATUS_CHECK` + path + size + mtime; server compares against destination
|
||||
4. **Network protocol** — status-code-driven exchange with metadata packing, keep-alive, and abort support
|
||||
5. **Incremental check** — client sends `STATUS_CHECK` + path + size + mtime; server compares against destination. Can be batched via `STATUS_CHECK_BATCH` for reduced round-trips.
|
||||
6. **Bandwidth limiting** — token-bucket algorithm with `nanosleep` throttling on 64 KB write chunks
|
||||
7. **Metadata restoration** — `chmod()`, `chown()`, `utimensat()` on the receiving side
|
||||
8. **`--delete`** — sender tracks all sent paths; receiver walks destination tree and removes unlisted files/directories
|
||||
9. **SSH transport** — `socketpair()` + `fork()` + `execvp("ssh", ...)` with `ControlMaster` and port support
|
||||
10. **TLS transport** — OpenSSL `SSL_CTX` with TLS 1.2 minimum, optional CA verification, transparent `SSL_read`/`SSL_write` via `io_set_ssl()`
|
||||
11. **Path traversal protection** — `has_path_traversal()` rejects any file path containing `..` components, preventing directory escape attacks
|
||||
12. **Connection limiting** — server tracks active connections and rejects new ones beyond `max_connections` (default 100)
|
||||
13. **Keep-alive** — idle connections receive periodic `STATUS_KEEPALIVE` to detect half-open TCP connections
|
||||
14. **Abort handling** — `SIGINT` sets an abort flag; the next protocol operation sends `STATUS_ABORT` for clean server cleanup
|
||||
15. **Atomic writes** — files are written to a `.tmp` suffix then atomically renamed via `rename()`, preventing partial files
|
||||
16. **Backup** — before overwriting, existing files are moved to `--backup-dir` (or same directory with `~` suffix) preserving the original
|
||||
|
||||
## Security Features
|
||||
|
||||
### Path Traversal Protection
|
||||
All received file paths are validated by `has_path_traversal()` before any disk operation. Any path containing `..` components is rejected with `STATUS_ERROR`, preventing directory escape attacks.
|
||||
|
||||
### TLS Certificate Verification
|
||||
When `--ca` is provided, the server performs mutual TLS verification (`SSL_VERIFY_PEER` with depth 4). Without `--ca`, TLS is still encrypted but peer certificates are not verified.
|
||||
|
||||
### Connection Limits
|
||||
The server enforces a maximum of 100 concurrent connections (configurable via `max_connections` in `Server`). When the limit is reached, new connections are immediately rejected and closed.
|
||||
|
||||
### Abort Handling
|
||||
If the client receives `SIGINT` (Ctrl+C) during a transfer, it sends `STATUS_ABORT` to the server. The server then cleans up temporary files and exits the child process, preventing incomplete files from remaining on disk.
|
||||
|
||||
### Atomic Writes
|
||||
Received files are written to a temporary path (suffixed with `.tmp`) and then atomically renamed to the final filename via `rename()`. This prevents partial or corrupted files from appearing at the destination if the transfer is interrupted.
|
||||
|
||||
## Build Requirements
|
||||
|
||||
@@ -223,6 +294,21 @@ Place the `fastsync-server` binary in the remote `$PATH`. The client runs `ssh u
|
||||
# Bandwidth limit to 1 MB/s
|
||||
./build/client --bwlimit 1024 /src user@host:/dst
|
||||
|
||||
# With timeouts, quiet mode, and stats
|
||||
./build/client --timeout 60 --contimeout 15 --quiet --stats /src user@host:/dst
|
||||
|
||||
# Backup overwritten files to a directory
|
||||
./build/client --backup --backup-dir /backups /src user@host:/dst
|
||||
|
||||
# Exclude patterns from file, limit depth
|
||||
./build/client --exclude-from ignore.txt --max-depth 3 /src user@host:/dst
|
||||
|
||||
# Custom queue size for multithreading
|
||||
./build/client -m --queue-size 200 /src user@host:/dst
|
||||
|
||||
# Log to file
|
||||
./build/client --log-file /tmp/fastsync.log /src user@host:/dst
|
||||
|
||||
# All features
|
||||
./build/client -a --progress --chunk-size 5242880 --exclude "*.log" --delete /src /dst
|
||||
```
|
||||
@@ -230,7 +316,9 @@ Place the `fastsync-server` binary in the remote `$PATH`. The client runs `ssh u
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
# Unit tests (7 suites)
|
||||
# Unit tests (18 suites — array_list, chunk, compression, config, data, delta, file, glob,
|
||||
# metadata, property, protocol, queue, robustness, scanner,
|
||||
# shared_utils, stress, transport_tcp, transport_ssh, transport_tls)
|
||||
./build/tests
|
||||
|
||||
# Integration + benchmark suite
|
||||
@@ -244,12 +332,15 @@ The benchmark prints throughput metrics, best configuration, and speedup vs rsyn
|
||||
1. Chunk size (~10 MB default) balances memory and transfer efficiency
|
||||
2. Compression level trades CPU for bandwidth
|
||||
3. `sendfile()` bypasses userspace — ~2× faster on localhost for large files
|
||||
4. Multithreading scales with core count
|
||||
4. Multithreading scales with core count; `--queue-size` controls pipeline buffering
|
||||
5. Metadata transfer adds negligible overhead (~24 bytes per file when enabled)
|
||||
6. SSH socketpair buffer set to 1 MB for improved pipe throughput
|
||||
7. SSH ControlMaster reuses connections across repeated invocations
|
||||
8. Incremental sync eliminates redundant transfers entirely
|
||||
9. Bandwidth limiting uses token-bucket with nanosleep for accurate throttling
|
||||
9. Batch incremental reduces round-trips by grouping multiple checks into one message
|
||||
10. Bandwidth limiting uses token-bucket with nanosleep for accurate throttling
|
||||
11. Atomic writes add a single `rename()` per file — negligible overhead
|
||||
12. Path traversal check is O(n) in path length with negligible cost
|
||||
|
||||
## Benchmark Results
|
||||
|
||||
|
||||
+525
-158
@@ -3,6 +3,7 @@
|
||||
#include "delta.h"
|
||||
#include "log.h"
|
||||
#include "protocol.h"
|
||||
#include "transport_tcp.h"
|
||||
#include "transport_tls.h"
|
||||
#include "utils.h"
|
||||
#include <errno.h>
|
||||
@@ -11,80 +12,53 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static void print_usage(void) {
|
||||
printf("Usage:\n");
|
||||
printf(" fastsync [options] <source> <destination>\n");
|
||||
printf(" fastsync [options] --source-dir <src> --dest-dir <dst>\n");
|
||||
printf("\n");
|
||||
printf("Destination formats:\n");
|
||||
printf(" user@host:/path SSH transport (rsync-style)\n");
|
||||
printf(" host:/path SSH transport (current user)\n");
|
||||
printf(" /local/path TCP transport (requires server on localhost:8080)\n");
|
||||
printf("\n");
|
||||
printf("Options:\n");
|
||||
printf(" -c [level] Enable compression (level 1-22, default 5)\n");
|
||||
printf(" -z [level] Alias for -c\n");
|
||||
printf(" -a, --archive Archive mode (-c -m -M)\n");
|
||||
printf(" -n, --dry-run Show what would be transferred\n");
|
||||
printf(" -p <port> SSH port (default: 22)\n");
|
||||
printf(" --progress Show transfer progress\n");
|
||||
printf(" --delete Delete files on receiver not in source\n");
|
||||
printf(" --exclude <pattern> Exclude files matching pattern\n");
|
||||
printf(" --include <pattern> Only include files matching pattern\n");
|
||||
printf(" --max-size <n> Skip files larger than n bytes\n");
|
||||
printf(" --min-size <n> Skip files smaller than n bytes\n");
|
||||
printf(" --incremental Skip files unchanged since last transfer\n");
|
||||
printf(" --delta Delta transfer for changed files (requires --incremental)\n");
|
||||
printf(" --delta-block <n> Delta block size in bytes (default: %d)\n",
|
||||
DELTA_BLOCK_SIZE_DEFAULT);
|
||||
printf(" --delta-max <n> Max file size for delta transfer (default: %llu)\n",
|
||||
DELTA_MAX_FILE_SIZE);
|
||||
printf(" -m Enable multithreading\n");
|
||||
printf(" -s Enable chunk serialization\n");
|
||||
printf(" -f Enable sendfile (TCP only, not with -c or -s)\n");
|
||||
printf(" -v, --verbose Enable debug logging\n");
|
||||
printf(" -M, --preserve Preserve file metadata\n");
|
||||
printf(" --chunk-size <n> Chunk size in bytes (default: %d)\n", DEFAULT_CHUNK_SIZE);
|
||||
printf(" --source-dir <path> Source directory\n");
|
||||
printf(" --dest-dir <path> Destination directory\n");
|
||||
printf(" --save-to-disk Write received files to disk\n");
|
||||
printf(" --server-host <ip> Server IP address (default: 127.0.0.1)\n");
|
||||
printf(" --server-port <n> Server port (default: 8080)\n");
|
||||
printf(" --bwlimit <KB/s> Bandwidth limit in kilobytes per second\n");
|
||||
printf(" --tls Enable TLS encryption\n");
|
||||
printf(" --cert <path> TLS certificate file (PEM)\n");
|
||||
printf(" --key <path> TLS private key file (PEM)\n");
|
||||
printf(" --ca <path> TLS CA certificate file (PEM)\n");
|
||||
printf(" --partial Keep partial files on interrupted transfer\n");
|
||||
printf(" --help Show this help\n");
|
||||
printf(" -V, --version Show version and exit\n");
|
||||
/* Parse environment variables for source/destination directories and save-to-disk flag. */
|
||||
static void parse_environment(const char** out_env_source, const char** out_env_dest,
|
||||
bool* out_save_to_disk) {
|
||||
*out_env_source = getenv("FASTSYNC_SOURCE_DIR");
|
||||
*out_env_dest = getenv("FASTSYNC_DEST_DIR");
|
||||
const char* env_save = getenv("FASTSYNC_SAVE_TO_DISK");
|
||||
*out_save_to_disk = false;
|
||||
if (env_save && (strcmp(env_save, "true") == 0 || strcmp(env_save, "1") == 0))
|
||||
*out_save_to_disk = true;
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
const char* env_source = getenv("FASTSYNC_SOURCE_DIR");
|
||||
const char* env_dest = getenv("FASTSYNC_DEST_DIR");
|
||||
const char* env_save = getenv("FASTSYNC_SAVE_TO_DISK");
|
||||
/* Parse a string as a positive integer, returning true on success. */
|
||||
static bool parse_positive_int(const char* s, int* out_val) {
|
||||
if (!s || *s == '\0')
|
||||
return false;
|
||||
char* endptr;
|
||||
errno = 0;
|
||||
long val = strtol(s, &endptr, 10);
|
||||
if (errno != 0 || *endptr != '\0' || val <= 0 || val > INT_MAX)
|
||||
return false;
|
||||
*out_val = (int)val;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool save_to_disk = false;
|
||||
if (env_save && (strcmp(env_save, "true") == 0 || strcmp(env_save, "1") == 0)) {
|
||||
save_to_disk = true;
|
||||
}
|
||||
/* Parse a string as a non-negative integer, returning true on success. */
|
||||
static bool parse_nonneg_int(const char* s, int* out_val) {
|
||||
if (!s || *s == '\0')
|
||||
return false;
|
||||
char* endptr;
|
||||
errno = 0;
|
||||
long val = strtol(s, &endptr, 10);
|
||||
if (errno != 0 || *endptr != '\0' || val < 0 || val > INT_MAX)
|
||||
return false;
|
||||
*out_val = (int)val;
|
||||
return true;
|
||||
}
|
||||
|
||||
Config* config = config_create(str_dup(PROTOCOL_VERSION), NULL, NULL, save_to_disk, false, false,
|
||||
false, false, 5, false, 0);
|
||||
int exit_code = 0;
|
||||
bool config_owned_by_pipeline = false;
|
||||
|
||||
int positional_args[2];
|
||||
int positional_count = 0;
|
||||
static void print_usage(void);
|
||||
static int read_patterns_from_file(const char* filepath, char*** patterns, int* count);
|
||||
|
||||
/* Parse CLI arguments into config. Returns 0 on success, -1 on error, 1 for help/clean-exit. */
|
||||
static int parse_args(Config* config, int argc, char* argv[], int* positional_args,
|
||||
int* positional_count) {
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (strcmp(argv[i], "--help") == 0) {
|
||||
print_usage();
|
||||
goto cleanup;
|
||||
} else if (strcmp(argv[i], "-V") == 0 || strcmp(argv[i], "--version") == 0) {
|
||||
printf("fastsync version %s\n", PROTOCOL_VERSION);
|
||||
goto cleanup;
|
||||
return 1;
|
||||
} else if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--archive") == 0) {
|
||||
config->use_compression = true;
|
||||
config->use_multithreading = true;
|
||||
@@ -93,34 +67,38 @@ int main(int argc, char* argv[]) {
|
||||
} else if (strcmp(argv[i], "-n") == 0 || strcmp(argv[i], "--dry-run") == 0) {
|
||||
config->dry_run = true;
|
||||
} else if (strcmp(argv[i], "-p") == 0 && i + 1 < argc) {
|
||||
char* end;
|
||||
long p = strtol(argv[++i], &end, 10);
|
||||
if (*end != '\0' || p <= 0 || p > 65535) {
|
||||
fprintf(stderr, "Error: invalid SSH port '%s' (must be 1-65535)\n", argv[i]);
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
if (!parse_positive_int(argv[++i], &config->ssh_port)) {
|
||||
fprintf(stderr, "Error: invalid --port/-p value: %s\n", argv[i]);
|
||||
return -1;
|
||||
}
|
||||
config->ssh_port = (int)p;
|
||||
} else if (strcmp(argv[i], "--delete") == 0) {
|
||||
config->use_delete = true;
|
||||
} else if (strcmp(argv[i], "--exclude") == 0 && i + 1 < argc) {
|
||||
char** tmp = realloc(config->exclude_patterns, (config->exclude_count + 1) * sizeof(char*));
|
||||
if (!tmp) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --exclude\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
return -1;
|
||||
}
|
||||
config->exclude_patterns = tmp;
|
||||
config->exclude_patterns[config->exclude_count++] = str_dup(argv[++i]);
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --exclude\n");
|
||||
return -1;
|
||||
}
|
||||
config->exclude_patterns[config->exclude_count++] = dup;
|
||||
} else if (strcmp(argv[i], "--include") == 0 && i + 1 < argc) {
|
||||
char** tmp = realloc(config->include_patterns, (config->include_count + 1) * sizeof(char*));
|
||||
if (!tmp) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --include\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
return -1;
|
||||
}
|
||||
config->include_patterns = tmp;
|
||||
config->include_patterns[config->include_count++] = str_dup(argv[++i]);
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --include\n");
|
||||
return -1;
|
||||
}
|
||||
config->include_patterns[config->include_count++] = dup;
|
||||
} else if (strcmp(argv[i], "--max-size") == 0 && i + 1 < argc) {
|
||||
config->max_size = strtoull(argv[++i], NULL, 10);
|
||||
} else if (strcmp(argv[i], "--min-size") == 0 && i + 1 < argc) {
|
||||
@@ -146,19 +124,29 @@ int main(int argc, char* argv[]) {
|
||||
log_message(LOG_LEVEL_INFO, "Enabled Compression");
|
||||
if (i + 1 < argc) {
|
||||
char* end_ptr;
|
||||
int level = strtol(argv[i + 1], &end_ptr, 10);
|
||||
long level = strtol(argv[i + 1], &end_ptr, 10);
|
||||
if (*end_ptr == '\0') {
|
||||
config->compression_level = level;
|
||||
log_message(LOG_LEVEL_INFO, "Set Compression level to %d", config->compression_level);
|
||||
config->compression_level = (int)level;
|
||||
log_message(LOG_LEVEL_INFO, "Set Compression level to %ld", level);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
} else if (strcmp(argv[i], "--source-dir") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --source-dir\n");
|
||||
return -1;
|
||||
}
|
||||
free(config->send_directory);
|
||||
config->send_directory = str_dup(argv[++i]);
|
||||
config->send_directory = dup;
|
||||
} else if (strcmp(argv[i], "--dest-dir") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --dest-dir\n");
|
||||
return -1;
|
||||
}
|
||||
free(config->receive_root_directory);
|
||||
config->receive_root_directory = str_dup(argv[++i]);
|
||||
config->receive_root_directory = dup;
|
||||
} else if (strcmp(argv[i], "--save-to-disk") == 0) {
|
||||
config->save_to_disk = true;
|
||||
} else if (strcmp(argv[i], "-M") == 0 || strcmp(argv[i], "--preserve") == 0) {
|
||||
@@ -174,30 +162,29 @@ int main(int argc, char* argv[]) {
|
||||
config->use_chunk_serialization = true;
|
||||
log_message(LOG_LEVEL_INFO, "Enabled Chunk Serialization");
|
||||
} else if (strcmp(argv[i], "--server-host") == 0 && i + 1 < argc) {
|
||||
free(config->server_host);
|
||||
config->server_host = str_dup(argv[++i]);
|
||||
} else if (strcmp(argv[i], "--server-port") == 0 && i + 1 < argc) {
|
||||
char* end;
|
||||
long p = strtol(argv[++i], &end, 10);
|
||||
if (*end != '\0' || p <= 0 || p > 65535) {
|
||||
fprintf(stderr, "Error: invalid server port '%s' (must be 1-65535)\n", argv[i]);
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --server-host\n");
|
||||
return -1;
|
||||
}
|
||||
free(config->server_host);
|
||||
config->server_host = dup;
|
||||
} else if (strcmp(argv[i], "--server-port") == 0 && i + 1 < argc) {
|
||||
if (!parse_positive_int(argv[++i], &config->server_port)) {
|
||||
fprintf(stderr, "Error: invalid --server-port value: %s\n", argv[i]);
|
||||
return -1;
|
||||
}
|
||||
config->server_port = (int)p;
|
||||
} else if (strcmp(argv[i], "--bwlimit") == 0 && i + 1 < argc) {
|
||||
char* end;
|
||||
errno = 0;
|
||||
unsigned long long kbps = strtoull(argv[++i], &end, 10);
|
||||
if (errno != 0 || *end != '\0' || kbps == 0) {
|
||||
fprintf(stderr, "Error: --bwlimit must be a positive integer\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
return -1;
|
||||
}
|
||||
if (kbps > ULLONG_MAX / 1024) {
|
||||
fprintf(stderr, "Error: --bwlimit value too large\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
return -1;
|
||||
}
|
||||
io_set_bwlimit(kbps * 1024);
|
||||
log_message(LOG_LEVEL_INFO, "Set bandwidth limit to %llu KB/s", kbps);
|
||||
@@ -210,42 +197,443 @@ int main(int argc, char* argv[]) {
|
||||
} else if (strcmp(argv[i], "--tls") == 0) {
|
||||
config->use_tls = true;
|
||||
} else if (strcmp(argv[i], "--cert") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --cert\n");
|
||||
return -1;
|
||||
}
|
||||
free(config->tls_cert);
|
||||
config->tls_cert = str_dup(argv[++i]);
|
||||
config->tls_cert = dup;
|
||||
} else if (strcmp(argv[i], "--key") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --key\n");
|
||||
return -1;
|
||||
}
|
||||
free(config->tls_key);
|
||||
config->tls_key = str_dup(argv[++i]);
|
||||
config->tls_key = dup;
|
||||
} else if (strcmp(argv[i], "--ca") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --ca\n");
|
||||
return -1;
|
||||
}
|
||||
free(config->tls_ca);
|
||||
config->tls_ca = str_dup(argv[++i]);
|
||||
config->tls_ca = dup;
|
||||
} else if (strcmp(argv[i], "--timeout") == 0 && i + 1 < argc) {
|
||||
int val;
|
||||
if (!parse_positive_int(argv[++i], &val)) {
|
||||
fprintf(stderr, "Error: --timeout must be a positive integer\n");
|
||||
return -1;
|
||||
}
|
||||
config->timeout = val;
|
||||
} else if (strcmp(argv[i], "--contimeout") == 0 && i + 1 < argc) {
|
||||
int val;
|
||||
if (!parse_positive_int(argv[++i], &val)) {
|
||||
fprintf(stderr, "Error: --contimeout must be a positive integer\n");
|
||||
return -1;
|
||||
}
|
||||
config->contimeout = val;
|
||||
} else if (strcmp(argv[i], "-q") == 0 || strcmp(argv[i], "--quiet") == 0 ||
|
||||
strcmp(argv[i], "--silent") == 0) {
|
||||
config->quiet = true;
|
||||
} else if (strcmp(argv[i], "--backup") == 0) {
|
||||
config->backup = true;
|
||||
} else if (strcmp(argv[i], "--backup-dir") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --backup-dir\n");
|
||||
return -1;
|
||||
}
|
||||
free(config->backup_dir);
|
||||
config->backup_dir = dup;
|
||||
} else if (strcmp(argv[i], "--stats") == 0) {
|
||||
config->stats = true;
|
||||
} else if (strcmp(argv[i], "--max-depth") == 0 && i + 1 < argc) {
|
||||
if (!parse_nonneg_int(argv[++i], &config->max_depth)) {
|
||||
fprintf(stderr, "Error: --max-depth must be a non-negative integer\n");
|
||||
return -1;
|
||||
}
|
||||
} else if (strcmp(argv[i], "--log-file") == 0 && i + 1 < argc) {
|
||||
FILE* lf = fopen(argv[++i], "a");
|
||||
if (!lf) {
|
||||
fprintf(stderr, "Error: could not open log file '%s': %s\n", argv[i], strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
config->log_file = lf;
|
||||
log_set_file(lf);
|
||||
} else if (strcmp(argv[i], "--queue-size") == 0 && i + 1 < argc) {
|
||||
int val;
|
||||
if (!parse_positive_int(argv[++i], &val)) {
|
||||
fprintf(stderr, "Error: --queue-size must be a positive integer\n");
|
||||
return -1;
|
||||
}
|
||||
config->queue_size = val;
|
||||
} else if (strcmp(argv[i], "--exclude-from") == 0 && i + 1 < argc) {
|
||||
if (read_patterns_from_file(argv[++i], &config->exclude_patterns, &config->exclude_count) !=
|
||||
0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--include-from") == 0 && i + 1 < argc) {
|
||||
if (read_patterns_from_file(argv[++i], &config->include_patterns, &config->include_count) !=
|
||||
0)
|
||||
return -1;
|
||||
} else if (strcmp(argv[i], "--partial") == 0) {
|
||||
config->partial = true;
|
||||
} else if (strcmp(argv[i], "--fastsync-server-path") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for --fastsync-server-path\n");
|
||||
return -1;
|
||||
}
|
||||
free(config->fastsync_server_path);
|
||||
config->fastsync_server_path = dup;
|
||||
} else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) {
|
||||
set_log_level(LOG_LEVEL_DEBUG);
|
||||
} else if (strcmp(argv[i], "-l") == 0 || strcmp(argv[i], "--links") == 0) {
|
||||
config->follow_symlinks = true;
|
||||
} else if (strcmp(argv[i], "--copy-links") == 0) {
|
||||
config->copy_links = true;
|
||||
} else if (strcmp(argv[i], "--safe-links") == 0) {
|
||||
config->safe_links = true;
|
||||
} else if (strcmp(argv[i], "--copy-unsafe-links") == 0) {
|
||||
config->copy_unsafe_links = true;
|
||||
} else if (strcmp(argv[i], "-H") == 0 || strcmp(argv[i], "--hard-links") == 0) {
|
||||
config->preserve_hard_links = true;
|
||||
} else if (strcmp(argv[i], "-A") == 0 || strcmp(argv[i], "--acls") == 0) {
|
||||
config->preserve_acls = true;
|
||||
} else if (strcmp(argv[i], "-X") == 0 || strcmp(argv[i], "--xattrs") == 0) {
|
||||
config->preserve_xattrs = true;
|
||||
} else if (strcmp(argv[i], "-D") == 0 || strcmp(argv[i], "--devices") == 0) {
|
||||
config->preserve_devices = true;
|
||||
} else if (strcmp(argv[i], "-S") == 0 || strcmp(argv[i], "--sparse") == 0) {
|
||||
config->preserve_sparse = true;
|
||||
} else if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--itemize-changes") == 0) {
|
||||
config->itemize_changes = true;
|
||||
} else if (strcmp(argv[i], "--out-format") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup)
|
||||
return -1;
|
||||
free(config->out_format);
|
||||
config->out_format = dup;
|
||||
} else if (strcmp(argv[i], "--info") == 0 && i + 1 < argc) {
|
||||
config->info_level = atoi(argv[++i]);
|
||||
} else if (strcmp(argv[i], "--debug") == 0 && i + 1 < argc) {
|
||||
config->debug_level = atoi(argv[++i]);
|
||||
} else if (strcmp(argv[i], "--list-only") == 0) {
|
||||
config->list_only = true;
|
||||
} else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--human-readable") == 0) {
|
||||
config->human_readable = true;
|
||||
} else if (strcmp(argv[i], "-u") == 0 || strcmp(argv[i], "--update") == 0) {
|
||||
config->update = true;
|
||||
} else if (strcmp(argv[i], "--inplace") == 0) {
|
||||
config->inplace = true;
|
||||
} else if (strcmp(argv[i], "--append") == 0) {
|
||||
config->append = true;
|
||||
} else if (strcmp(argv[i], "--append-verify") == 0) {
|
||||
config->append_verify = true;
|
||||
} else if (strcmp(argv[i], "--delete-excluded") == 0) {
|
||||
config->delete_excluded = true;
|
||||
} else if (strcmp(argv[i], "--delete-after") == 0) {
|
||||
config->delete_after = true;
|
||||
} else if (strcmp(argv[i], "--max-delete") == 0 && i + 1 < argc) {
|
||||
int val;
|
||||
if (!parse_nonneg_int(argv[++i], &val)) {
|
||||
fprintf(stderr, "Error: --max-delete must be a non-negative integer\n");
|
||||
return -1;
|
||||
}
|
||||
config->max_delete = val;
|
||||
} else if (strcmp(argv[i], "--filter") == 0 && i + 1 < argc) {
|
||||
if (!config->filters)
|
||||
config->filters = array_list_create(free);
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup)
|
||||
return -1;
|
||||
array_list_add(config->filters, dup);
|
||||
} else if (strcmp(argv[i], "--files-from") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup)
|
||||
return -1;
|
||||
free(config->files_from);
|
||||
config->files_from = dup;
|
||||
} else if (strcmp(argv[i], "--cvs-exclude") == 0) {
|
||||
config->cvs_exclude = true;
|
||||
} else if (strcmp(argv[i], "--prune-empty-dirs") == 0) {
|
||||
config->prune_empty_dirs = true;
|
||||
} else if (strcmp(argv[i], "-R") == 0 || strcmp(argv[i], "--relative") == 0) {
|
||||
config->relative = true;
|
||||
} else if (strcmp(argv[i], "-e") == 0 || strcmp(argv[i], "--rsh") == 0) {
|
||||
if (i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup)
|
||||
return -1;
|
||||
free(config->rsh_command);
|
||||
config->rsh_command = dup;
|
||||
} else {
|
||||
fprintf(stderr, "Error: -e/--rsh requires a command argument\n");
|
||||
return -1;
|
||||
}
|
||||
} else if (strcmp(argv[i], "--rsync-path") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup)
|
||||
return -1;
|
||||
free(config->rsync_path);
|
||||
config->rsync_path = dup;
|
||||
} else if (strcmp(argv[i], "--temp-dir") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup)
|
||||
return -1;
|
||||
free(config->temp_dir);
|
||||
config->temp_dir = dup;
|
||||
} else if (strcmp(argv[i], "--compare-dest") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup)
|
||||
return -1;
|
||||
free(config->compare_dest);
|
||||
config->compare_dest = dup;
|
||||
} else if (strcmp(argv[i], "--copy-dest") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup)
|
||||
return -1;
|
||||
free(config->copy_dest);
|
||||
config->copy_dest = dup;
|
||||
} else if (strcmp(argv[i], "--link-dest") == 0 && i + 1 < argc) {
|
||||
char* dup = str_dup(argv[++i]);
|
||||
if (!dup)
|
||||
return -1;
|
||||
free(config->link_dest);
|
||||
config->link_dest = dup;
|
||||
} else if (argv[i][0] == '-') {
|
||||
fprintf(stderr, "Unknown option: %s\n", argv[i]);
|
||||
print_usage();
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
return -1;
|
||||
} else {
|
||||
if (positional_count < 2)
|
||||
positional_args[positional_count++] = i;
|
||||
if (*positional_count < 2)
|
||||
positional_args[(*positional_count)++] = i;
|
||||
else {
|
||||
fprintf(stderr, "Unexpected argument: %s\n", argv[i]);
|
||||
print_usage();
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Validate config after parsing. Returns true if valid. */
|
||||
static bool validate_config(const Config* config) {
|
||||
if (!config->send_directory || !config->receive_root_directory) {
|
||||
fprintf(stderr, "Error: source and destination directories are required\n");
|
||||
print_usage();
|
||||
return false;
|
||||
}
|
||||
if (config->use_sendfile && (config->use_chunk_serialization || config->use_compression)) {
|
||||
fprintf(stderr, "Error: -f/--sendfile cannot be combined with -c (compression) or -s (chunk "
|
||||
"serialization)\n");
|
||||
return false;
|
||||
}
|
||||
if (config->transport == TRANSPORT_SSH && config->use_sendfile) {
|
||||
fprintf(stderr, "Error: -f/--sendfile is not supported with SSH transport\n");
|
||||
return false;
|
||||
}
|
||||
if (config->use_incremental && config->use_chunk_serialization) {
|
||||
fprintf(stderr, "Error: --incremental is not supported with -s (chunk serialization)\n");
|
||||
return false;
|
||||
}
|
||||
if (config->use_delta && !config->use_incremental) {
|
||||
fprintf(stderr, "Error: --delta requires --incremental\n");
|
||||
return false;
|
||||
}
|
||||
if (config->use_delta && config->use_chunk_serialization) {
|
||||
fprintf(stderr, "Error: --delta cannot be combined with -s (chunk serialization)\n");
|
||||
return false;
|
||||
}
|
||||
if (config->use_delta && config->use_sendfile) {
|
||||
fprintf(stderr, "Error: --delta cannot be combined with -f (sendfile)\n");
|
||||
return false;
|
||||
}
|
||||
if (config->use_tls) {
|
||||
if (!config->tls_cert || !config->tls_key) {
|
||||
fprintf(stderr, "Error: --tls requires --cert and --key\n");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void print_usage(void) {
|
||||
printf("Usage:\n");
|
||||
printf(" fastsync [options] <source> <destination>\n");
|
||||
printf(" fastsync [options] --source-dir <src> --dest-dir <dst>\n");
|
||||
printf("\n");
|
||||
printf("Destination formats:\n");
|
||||
printf(" user@host:/path SSH transport (rsync-style)\n");
|
||||
printf(" host:/path SSH transport (current user)\n");
|
||||
printf(" /local/path TCP transport (requires server on localhost:8080)\n");
|
||||
printf("\n");
|
||||
printf("Options:\n");
|
||||
printf(" -c [level] Enable compression (level 1-22, default 5)\n");
|
||||
printf(" -z [level] Alias for -c\n");
|
||||
printf(" -a, --archive Archive mode (-c -m -M)\n");
|
||||
printf(" -n, --dry-run Show what would be transferred\n");
|
||||
printf(" -p <port> SSH port (default: 22)\n");
|
||||
printf(" --progress Show transfer progress\n");
|
||||
printf(" --delete Delete files on receiver not in source\n");
|
||||
printf(" --exclude <pattern> Exclude files matching pattern\n");
|
||||
printf(" --include <pattern> Only include files matching pattern\n");
|
||||
printf(" --exclude-from <file> Read exclude patterns from file\n");
|
||||
printf(" --include-from <file> Read include patterns from file\n");
|
||||
printf(" --max-size <n> Skip files larger than n bytes\n");
|
||||
printf(" --min-size <n> Skip files smaller than n bytes\n");
|
||||
printf(" --incremental Skip files unchanged since last transfer\n");
|
||||
printf(" --delta Delta transfer for changed files (requires --incremental)\n");
|
||||
printf(" --delta-block <n> Delta block size in bytes (default: %d)\n",
|
||||
DELTA_BLOCK_SIZE_DEFAULT);
|
||||
printf(" --delta-max <n> Max file size for delta transfer (default: %llu)\n",
|
||||
DELTA_MAX_FILE_SIZE);
|
||||
printf(" -m Enable multithreading\n");
|
||||
printf(" -s Enable chunk serialization\n");
|
||||
printf(" -f Enable sendfile (TCP only, not with -c or -s)\n");
|
||||
printf(" -v, --verbose Enable debug logging\n");
|
||||
printf(" -M, --preserve Preserve file metadata\n");
|
||||
printf(" --chunk-size <n> Chunk size in bytes (default: %d)\n", DEFAULT_CHUNK_SIZE);
|
||||
printf(" --source-dir <path> Source directory\n");
|
||||
printf(" --dest-dir <path> Destination directory\n");
|
||||
printf(" --save-to-disk Write received files to disk\n");
|
||||
printf(" --server-host <ip> Server IP address (default: 127.0.0.1)\n");
|
||||
printf(" --server-port <n> Server port (default: 8080)\n");
|
||||
printf(" --bwlimit <KB/s> Bandwidth limit in kilobytes per second\n");
|
||||
printf(" --tls Enable TLS encryption\n");
|
||||
printf(" --cert <path> TLS certificate file (PEM)\n");
|
||||
printf(" --key <path> TLS private key file (PEM)\n");
|
||||
printf(" --ca <path> TLS CA certificate file (PEM)\n");
|
||||
printf(" --timeout <sec> I/O timeout in seconds (default: 30)\n");
|
||||
printf(" --contimeout <sec> Connection timeout in seconds (default: 10)\n");
|
||||
printf(" -q, --quiet Suppress non-error output\n");
|
||||
printf(" --silent Alias for --quiet\n");
|
||||
printf(" --backup Backup existing files before overwriting\n");
|
||||
printf(" --backup-dir <dir> Directory for backups (requires --backup)\n");
|
||||
printf(" --stats Print transfer statistics at end\n");
|
||||
printf(" --max-depth <n> Maximum directory depth (0=unlimited)\n");
|
||||
printf(" --log-file <path> Write log messages to file\n");
|
||||
printf(" --queue-size <n> Queue capacity for multithreaded mode (default: 100)\n");
|
||||
printf(" --partial Keep partial files on interrupted transfer\n");
|
||||
printf(" --fastsync-server-path <path>\n");
|
||||
printf(" Path to fastsync-server on remote (default: fastsync-server)\n");
|
||||
printf(" -l, --links Copy symlinks as symlinks\n");
|
||||
printf(" --copy-links Transform symlinks into referent files\n");
|
||||
printf(" --safe-links Skip symlinks that point outside transfer tree\n");
|
||||
printf(" --copy-unsafe-links Only transform unsafe symlinks into referent files\n");
|
||||
printf(" -H, --hard-links Preserve hard links\n");
|
||||
printf(" -A, --acls Preserve ACLs\n");
|
||||
printf(" -X, --xattrs Preserve extended attributes\n");
|
||||
printf(" -D, --devices Preserve device files\n");
|
||||
printf(" -S, --sparse Handle sparse files efficiently\n");
|
||||
printf(" -i, --itemize-changes Show per-file change summary\n");
|
||||
printf(" --out-format <fmt> Custom output format string\n");
|
||||
printf(" --info <flags> Info verbosity level\n");
|
||||
printf(" --debug <flags> Debug verbosity level\n");
|
||||
printf(" --list-only List files without transferring\n");
|
||||
printf(" -h, --human-readable Human-readable numbers\n");
|
||||
printf(" -u, --update Skip files newer on destination\n");
|
||||
printf(" --inplace Update files in-place (no temp+rename)\n");
|
||||
printf(" --append Append data to shorter files\n");
|
||||
printf(" --append-verify Append with verify\n");
|
||||
printf(" --delete-excluded Also delete excluded files\n");
|
||||
printf(" --delete-after Delete after transfer, not before\n");
|
||||
printf(" --max-delete <n> Maximum number of files to delete\n");
|
||||
printf(" --filter <rule> Add file filtering rule\n");
|
||||
printf(" --files-from <file> Read file list from file\n");
|
||||
printf(" --cvs-exclude Auto-ignore CVS files\n");
|
||||
printf(" --prune-empty-dirs Omit empty directories from transfer\n");
|
||||
printf(" -R, --relative Use relative paths\n");
|
||||
printf(" -e, --rsh <cmd> Specify remote shell\n");
|
||||
printf(" --rsync-path <path> Path to remote binary\n");
|
||||
printf(" --temp-dir <dir> Temporary directory for files\n");
|
||||
printf(" --compare-dest <dir> Compare destination\n");
|
||||
printf(" --copy-dest <dir> Copy destination\n");
|
||||
printf(" --link-dest <dir> Link destination\n");
|
||||
printf(" --help Show this help\n");
|
||||
}
|
||||
|
||||
static int read_patterns_from_file(const char* filepath, char*** patterns, int* count) {
|
||||
FILE* fp = fopen(filepath, "r");
|
||||
if (!fp) {
|
||||
fprintf(stderr, "Error: could not open pattern file '%s': %s\n", filepath, strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
char line[4096];
|
||||
while (fgets(line, sizeof(line), fp)) {
|
||||
char* p = line;
|
||||
while (*p == ' ' || *p == '\t')
|
||||
p++;
|
||||
if (*p == '#' || *p == '\n' || *p == '\0')
|
||||
continue;
|
||||
size_t len = strlen(p);
|
||||
while (len > 0 && (p[len - 1] == '\n' || p[len - 1] == '\r'))
|
||||
p[--len] = '\0';
|
||||
if (len == 0)
|
||||
continue;
|
||||
char** tmp = realloc(*patterns, (*count + 1) * sizeof(char*));
|
||||
if (!tmp) {
|
||||
fprintf(stderr, "Error: memory allocation failed for pattern file\n");
|
||||
fclose(fp);
|
||||
return -1;
|
||||
}
|
||||
*patterns = tmp;
|
||||
char* dup = str_dup(p);
|
||||
if (!dup) {
|
||||
fprintf(stderr, "Error: memory allocation failed for pattern file\n");
|
||||
fclose(fp);
|
||||
return -1;
|
||||
}
|
||||
(*patterns)[(*count)++] = dup;
|
||||
}
|
||||
fclose(fp);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
const char* env_source = NULL;
|
||||
const char* env_dest = NULL;
|
||||
bool save_to_disk = false;
|
||||
parse_environment(&env_source, &env_dest, &save_to_disk);
|
||||
|
||||
int exit_code = 0;
|
||||
bool config_owned_by_pipeline = false;
|
||||
Config* config = config_create();
|
||||
if (!config) {
|
||||
fprintf(stderr, "Error: failed to allocate config\n");
|
||||
return 1;
|
||||
}
|
||||
config->save_to_disk = save_to_disk;
|
||||
|
||||
int positional_args[2];
|
||||
int positional_count = 0;
|
||||
|
||||
int parse_ret = parse_args(config, argc, argv, positional_args, &positional_count);
|
||||
if (parse_ret != 0) {
|
||||
if (parse_ret < 0)
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/* Handle positional arguments or fall back to environment variables */
|
||||
if (positional_count == 2) {
|
||||
free(config->send_directory);
|
||||
free(config->receive_root_directory);
|
||||
config->send_directory = str_dup(argv[positional_args[0]]);
|
||||
if (!config->send_directory) {
|
||||
fprintf(stderr, "Error: memory allocation failed\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
config->receive_root_directory = str_dup(argv[positional_args[1]]);
|
||||
if (!config->receive_root_directory) {
|
||||
fprintf(stderr, "Error: memory allocation failed\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
config->save_to_disk = true;
|
||||
|
||||
config_parse_ssh_dest(config);
|
||||
} else if (positional_count == 1) {
|
||||
fprintf(stderr, "Error: missing destination argument\n");
|
||||
@@ -253,71 +641,46 @@ int main(int argc, char* argv[]) {
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
} else {
|
||||
if (!config->send_directory && env_source)
|
||||
config->send_directory = str_dup((char*)env_source);
|
||||
if (!config->receive_root_directory && env_dest)
|
||||
config->receive_root_directory = str_dup((char*)env_dest);
|
||||
if (!config->send_directory && env_source) {
|
||||
config->send_directory = str_dup(env_source);
|
||||
if (!config->send_directory) {
|
||||
fprintf(stderr, "Error: memory allocation failed\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
}
|
||||
if (!config->receive_root_directory && env_dest) {
|
||||
config->receive_root_directory = str_dup(env_dest);
|
||||
if (!config->receive_root_directory) {
|
||||
fprintf(stderr, "Error: memory allocation failed\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!config->send_directory || !config->receive_root_directory) {
|
||||
fprintf(stderr, "Error: source and destination directories are required\n");
|
||||
print_usage();
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
if (config->use_sendfile && (config->use_chunk_serialization || config->use_compression)) {
|
||||
fprintf(stderr, "Error: -f/--sendfile cannot be combined with -c (compression) or -s (chunk "
|
||||
"serialization)\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
if (config->transport == TRANSPORT_SSH && config->use_sendfile) {
|
||||
fprintf(stderr, "Error: -f/--sendfile is not supported with SSH transport\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
if (config->use_incremental && config->use_chunk_serialization) {
|
||||
fprintf(stderr, "Error: --incremental is not supported with -s (chunk serialization)\n");
|
||||
if (!validate_config(config)) {
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/* Enable implicit flags */
|
||||
if (config->use_incremental && !config->use_metadata) {
|
||||
log_message(LOG_LEVEL_INFO, "Enabling metadata preservation for --incremental");
|
||||
config->use_metadata = true;
|
||||
}
|
||||
|
||||
if (config->use_delta && !config->use_incremental) {
|
||||
fprintf(stderr, "Error: --delta requires --incremental\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
if (config->use_delta && config->use_chunk_serialization) {
|
||||
fprintf(stderr, "Error: --delta cannot be combined with -s (chunk serialization)\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
if (config->use_delta && config->use_sendfile) {
|
||||
fprintf(stderr, "Error: --delta cannot be combined with -f (sendfile)\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
if (config->use_delta && !config->use_metadata) {
|
||||
log_message(LOG_LEVEL_INFO, "Enabling metadata preservation for --delta");
|
||||
config->use_metadata = true;
|
||||
}
|
||||
|
||||
if (config->use_tls) {
|
||||
if (!config->tls_cert || !config->tls_key) {
|
||||
fprintf(stderr, "Error: --tls requires --cert and --key\n");
|
||||
exit_code = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
/* Initialize TLS if needed */
|
||||
if (config->use_tls)
|
||||
tls_global_init();
|
||||
}
|
||||
|
||||
tcp_set_timeouts(config->timeout, config->contimeout);
|
||||
|
||||
/* Execute transfer */
|
||||
if (config->use_multithreading) {
|
||||
config_owned_by_pipeline = true;
|
||||
exit_code = send_files_multithreaded(config);
|
||||
@@ -326,7 +689,11 @@ int main(int argc, char* argv[]) {
|
||||
}
|
||||
|
||||
cleanup:
|
||||
if (!config_owned_by_pipeline)
|
||||
config_delete(config);
|
||||
if (config) {
|
||||
if (config->log_file)
|
||||
fclose(config->log_file);
|
||||
if (!config_owned_by_pipeline)
|
||||
config_delete(config);
|
||||
}
|
||||
return exit_code;
|
||||
}
|
||||
|
||||
+91
-80
@@ -21,6 +21,48 @@
|
||||
#include <string.h>
|
||||
#include <threads.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define STREAM_THRESHOLD (64ULL * 1024 * 1024)
|
||||
|
||||
/* Print dry-run manifest showing files that would be transferred. Returns 0 on success. */
|
||||
static int send_dry_run_manifest(Config* config) {
|
||||
DirectoryScanner* scanner = directory_scanner_create(
|
||||
config->send_directory, config->use_metadata, config->chunk_size, config->exclude_patterns,
|
||||
config->exclude_count, config->include_patterns, config->include_count, config->max_size,
|
||||
config->min_size, config->max_depth, config->follow_symlinks, config->copy_links,
|
||||
config->safe_links, config->copy_unsafe_links);
|
||||
if (!scanner)
|
||||
return -1;
|
||||
Chunk* chunk;
|
||||
int file_count = 0;
|
||||
unsigned long long total_bytes = 0;
|
||||
printf("Dry run: files to be transferred\n");
|
||||
while ((chunk = directory_scanner_next(scanner)) != NULL) {
|
||||
for (int i = 0; i < chunk->element_count; i++) {
|
||||
printf(" %s (%zu bytes)\n", chunk->items[i]->path, chunk->items[i]->data->size);
|
||||
total_bytes += chunk->items[i]->data->size;
|
||||
file_count++;
|
||||
}
|
||||
chunk_destroy(chunk);
|
||||
}
|
||||
directory_scanner_destroy(scanner);
|
||||
printf("Total: %d files, %.1f MB\n", file_count, total_bytes / 1048576.0);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Send the delete manifest (list of files) to the server. Returns 0 on success, -1 on failure. */
|
||||
static int send_delete_manifest(int fd, ArrayList* manifest) {
|
||||
if (!send_status(fd, STATUS_MANIFEST))
|
||||
return -1;
|
||||
if (!send_int(fd, manifest->size))
|
||||
return -1;
|
||||
for (int i = 0; i < manifest->size; i++) {
|
||||
if (!send_str(fd, (char*)manifest->items[i]))
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int incremental_check(Client* client, File* file, DeltaSignature** out_sig) {
|
||||
*out_sig = NULL;
|
||||
@@ -208,10 +250,13 @@ int send_chunk(Client* client, Chunk* chunk, Config* config) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool use_sendfile = config->use_sendfile && !config->use_compression;
|
||||
for (int i = 0; i < chunk->element_count; i++) {
|
||||
int rc =
|
||||
send_single_file(client, chunk->items[i], config, config->use_incremental, use_sendfile);
|
||||
File* f = chunk->items[i];
|
||||
if (f == NULL)
|
||||
continue;
|
||||
bool stream = f->data->data == NULL && f->data->size > 0;
|
||||
bool use_sendfile = (config->use_sendfile && !config->use_compression) || stream;
|
||||
int rc = send_single_file(client, f, config, config->use_incremental, use_sendfile);
|
||||
if (rc == 1)
|
||||
continue;
|
||||
if (rc < 0)
|
||||
@@ -228,7 +273,8 @@ static int send_chunks_multithreaded(void* pipeline_context) {
|
||||
fprintf(stderr, "Error: -f/--sendfile is not supported with SSH transport\n");
|
||||
return 1;
|
||||
}
|
||||
client = client_connect_ssh(context->config->ssh_destination, context->config->ssh_port);
|
||||
client = client_connect_ssh(context->config->ssh_destination, context->config->ssh_port,
|
||||
context->config->fastsync_server_path);
|
||||
} else if (context->config->use_tls) {
|
||||
client = client_create();
|
||||
if (!client || !client_connect_tls(client, context->config->server_host,
|
||||
@@ -261,14 +307,8 @@ static int send_chunks_multithreaded(void* pipeline_context) {
|
||||
&context->condition_not_full_loader, &context->loader_done);
|
||||
if (current_chunk == NULL) {
|
||||
if (context->config->use_delete) {
|
||||
if (!send_status(client->file_descriptor, STATUS_MANIFEST))
|
||||
if (send_delete_manifest(client->file_descriptor, context->manifest) != 0)
|
||||
goto send_fail;
|
||||
if (!send_int(client->file_descriptor, context->manifest->size))
|
||||
goto send_fail;
|
||||
for (int i = 0; i < context->manifest->size; i++) {
|
||||
if (!send_str(client->file_descriptor, (char*)context->manifest->items[i]))
|
||||
goto send_fail;
|
||||
}
|
||||
}
|
||||
if (!send_status(client->file_descriptor, STATUS_FINISHED))
|
||||
goto send_fail;
|
||||
@@ -295,16 +335,15 @@ static int send_chunks_multithreaded(void* pipeline_context) {
|
||||
|
||||
static int scan_directory_multithreaded(void* pipeline_context) {
|
||||
PipelineContextSender* context = (PipelineContextSender*)pipeline_context;
|
||||
mtx_lock(&context->mutex_scanner);
|
||||
DirectoryScanner* scanner = directory_scanner_create(
|
||||
ParallelScanner* scanner = parallel_scanner_create(
|
||||
context->config->send_directory, context->config->use_metadata, context->config->chunk_size,
|
||||
context->config->exclude_patterns, context->config->exclude_count,
|
||||
context->config->include_patterns, context->config->include_count, context->config->max_size,
|
||||
context->config->min_size);
|
||||
mtx_unlock(&context->mutex_scanner);
|
||||
context->config->min_size, context->config->max_depth, 4, context->config->follow_symlinks,
|
||||
context->config->copy_links, context->config->safe_links, context->config->copy_unsafe_links);
|
||||
|
||||
Chunk* current_chunk;
|
||||
while ((current_chunk = directory_scanner_next(scanner)) != NULL) {
|
||||
while ((current_chunk = parallel_scanner_next(scanner)) != NULL) {
|
||||
if (context->config->use_delete) {
|
||||
mtx_lock(&context->mutex_scanner);
|
||||
for (int i = 0; i < current_chunk->element_count; i++) {
|
||||
@@ -324,7 +363,7 @@ static int scan_directory_multithreaded(void* pipeline_context) {
|
||||
cnd_signal(&context->condition_not_empty_scanner);
|
||||
mtx_unlock(&context->mutex_scanner);
|
||||
|
||||
directory_scanner_destroy(scanner);
|
||||
parallel_scanner_destroy(scanner);
|
||||
return thrd_success;
|
||||
}
|
||||
|
||||
@@ -343,9 +382,12 @@ static int load_files_multithreaded(void* pipeline_context) {
|
||||
}
|
||||
if (!context->config->use_sendfile) {
|
||||
for (int i = 0; i < chunk->element_count; i++) {
|
||||
if (!file_load_data(chunk->items[i])) {
|
||||
File* f = chunk->items[i];
|
||||
if (f->data->size > STREAM_THRESHOLD)
|
||||
continue;
|
||||
if (!file_load_data(f)) {
|
||||
log_message(LOG_LEVEL_ERROR, "Failed to load file data, skipping");
|
||||
file_destroy(chunk->items[i]);
|
||||
file_destroy(f);
|
||||
chunk->items[i] = NULL;
|
||||
}
|
||||
}
|
||||
@@ -357,27 +399,8 @@ static int load_files_multithreaded(void* pipeline_context) {
|
||||
}
|
||||
|
||||
int send_files(Config* config) {
|
||||
if (config->dry_run) {
|
||||
DirectoryScanner* scanner = directory_scanner_create(
|
||||
config->send_directory, config->use_metadata, config->chunk_size, config->exclude_patterns,
|
||||
config->exclude_count, config->include_patterns, config->include_count, config->max_size,
|
||||
config->min_size);
|
||||
Chunk* chunk;
|
||||
int file_count = 0;
|
||||
unsigned long long total_bytes = 0;
|
||||
printf("Dry run: files to be transferred\n");
|
||||
while ((chunk = directory_scanner_next(scanner)) != NULL) {
|
||||
for (int i = 0; i < chunk->element_count; i++) {
|
||||
printf(" %s (%zu bytes)\n", chunk->items[i]->path, chunk->items[i]->data->size);
|
||||
total_bytes += chunk->items[i]->data->size;
|
||||
file_count++;
|
||||
}
|
||||
chunk_destroy(chunk);
|
||||
}
|
||||
directory_scanner_destroy(scanner);
|
||||
printf("Total: %d files, %.1f MB\n", file_count, total_bytes / 1048576.0);
|
||||
return 0;
|
||||
}
|
||||
if (config->dry_run)
|
||||
return send_dry_run_manifest(config);
|
||||
|
||||
Client* client;
|
||||
if (config->transport == TRANSPORT_SSH) {
|
||||
@@ -385,7 +408,8 @@ int send_files(Config* config) {
|
||||
fprintf(stderr, "Error: -f/--sendfile is not supported with SSH transport\n");
|
||||
return 1;
|
||||
}
|
||||
client = client_connect_ssh(config->ssh_destination, config->ssh_port);
|
||||
client =
|
||||
client_connect_ssh(config->ssh_destination, config->ssh_port, config->fastsync_server_path);
|
||||
if (!client)
|
||||
return 1;
|
||||
} else if (config->use_tls) {
|
||||
@@ -414,7 +438,8 @@ int send_files(Config* config) {
|
||||
DirectoryScanner* scanner = directory_scanner_create(
|
||||
config->send_directory, config->use_metadata, config->chunk_size, config->exclude_patterns,
|
||||
config->exclude_count, config->include_patterns, config->include_count, config->max_size,
|
||||
config->min_size);
|
||||
config->min_size, config->max_depth, config->follow_symlinks, config->copy_links,
|
||||
config->safe_links, config->copy_unsafe_links);
|
||||
Chunk* current_chunk;
|
||||
unsigned long long total_bytes = 0;
|
||||
time_t last_progress = 0;
|
||||
@@ -433,7 +458,10 @@ int send_files(Config* config) {
|
||||
}
|
||||
if (!config->use_sendfile) {
|
||||
for (int i = 0; i < current_chunk->element_count; i++) {
|
||||
if (!file_load_data(current_chunk->items[i])) {
|
||||
File* f = current_chunk->items[i];
|
||||
if (f->data->size > STREAM_THRESHOLD)
|
||||
continue;
|
||||
if (!file_load_data(f)) {
|
||||
log_message(LOG_LEVEL_ERROR, "Failed to load file data");
|
||||
continue;
|
||||
}
|
||||
@@ -458,20 +486,10 @@ int send_files(Config* config) {
|
||||
chunk_destroy(current_chunk);
|
||||
}
|
||||
if (config->use_delete) {
|
||||
if (!send_status(client->file_descriptor, STATUS_MANIFEST)) {
|
||||
if (send_delete_manifest(client->file_descriptor, manifest) != 0) {
|
||||
array_list_delete(manifest);
|
||||
goto send_fail;
|
||||
}
|
||||
if (!send_int(client->file_descriptor, manifest->size)) {
|
||||
array_list_delete(manifest);
|
||||
goto send_fail;
|
||||
}
|
||||
for (int i = 0; i < manifest->size; i++) {
|
||||
if (!send_str(client->file_descriptor, (char*)manifest->items[i])) {
|
||||
array_list_delete(manifest);
|
||||
goto send_fail;
|
||||
}
|
||||
}
|
||||
array_list_delete(manifest);
|
||||
}
|
||||
if (!send_status(client->file_descriptor, STATUS_FINISHED))
|
||||
@@ -486,40 +504,33 @@ int send_files(Config* config) {
|
||||
directory_scanner_destroy(scanner);
|
||||
client_disconnect(client);
|
||||
client_delete(client);
|
||||
return ok ? 0 : -1;
|
||||
return ok ? 0 : 1;
|
||||
|
||||
send_fail:
|
||||
directory_scanner_destroy(scanner);
|
||||
client_disconnect(client);
|
||||
client_delete(client);
|
||||
return -1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int send_files_multithreaded(Config* config) {
|
||||
if (config->dry_run) {
|
||||
DirectoryScanner* scanner = directory_scanner_create(
|
||||
config->send_directory, config->use_metadata, config->chunk_size, config->exclude_patterns,
|
||||
config->exclude_count, config->include_patterns, config->include_count, config->max_size,
|
||||
config->min_size);
|
||||
Chunk* chunk;
|
||||
int file_count = 0;
|
||||
unsigned long long total_bytes = 0;
|
||||
printf("Dry run: files to be transferred\n");
|
||||
while ((chunk = directory_scanner_next(scanner)) != NULL) {
|
||||
for (int i = 0; i < chunk->element_count; i++) {
|
||||
printf(" %s (%zu bytes)\n", chunk->items[i]->path, chunk->items[i]->data->size);
|
||||
total_bytes += chunk->items[i]->data->size;
|
||||
file_count++;
|
||||
}
|
||||
chunk_destroy(chunk);
|
||||
}
|
||||
directory_scanner_destroy(scanner);
|
||||
printf("Total: %d files, %.1f MB\n", file_count, total_bytes / 1048576.0);
|
||||
return 0;
|
||||
}
|
||||
if (config->dry_run)
|
||||
return send_dry_run_manifest(config);
|
||||
|
||||
Queue* q1 = queue_create(100, chunk_destroy);
|
||||
Queue* q2 = queue_create(100, chunk_destroy);
|
||||
long pages = sysconf(_SC_AVPHYS_PAGES);
|
||||
long page_size = sysconf(_SC_PAGE_SIZE);
|
||||
unsigned long long available_memory =
|
||||
pages > 0 && page_size > 0 ? (unsigned long long)pages * (unsigned long long)page_size
|
||||
: 512ULL * 1024 * 1024;
|
||||
unsigned long long avg_file_size = 1024 * 1024;
|
||||
int qsize = (int)(available_memory / avg_file_size);
|
||||
if (qsize < 10)
|
||||
qsize = 10;
|
||||
if (qsize > 1000)
|
||||
qsize = 1000;
|
||||
|
||||
Queue* q1 = queue_create(qsize, chunk_destroy);
|
||||
Queue* q2 = queue_create(qsize, chunk_destroy);
|
||||
if (!q1 || !q2) {
|
||||
if (q1)
|
||||
queue_destroy(q1);
|
||||
@@ -551,5 +562,5 @@ int send_files_multithreaded(Config* config) {
|
||||
thrd_join(sender, &sender_result);
|
||||
|
||||
pipeline_context_sender_destroy(context);
|
||||
return sender_result == thrd_success ? 0 : -1;
|
||||
return sender_result == thrd_success ? 0 : 1;
|
||||
}
|
||||
|
||||
+406
-130
@@ -9,89 +9,59 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <threads.h>
|
||||
#include <unistd.h>
|
||||
|
||||
DirectoryScanner* directory_scanner_create(char* root_directory, bool use_metadata,
|
||||
unsigned long long chunk_size, char** exclude_patterns,
|
||||
int exclude_count, char** include_patterns,
|
||||
int include_count, unsigned long long max_size,
|
||||
unsigned long long min_size) {
|
||||
return directory_scanner_create_full(root_directory, use_metadata, chunk_size,
|
||||
exclude_patterns, exclude_count,
|
||||
include_patterns, include_count,
|
||||
max_size, min_size, true);
|
||||
typedef struct {
|
||||
char* path;
|
||||
int depth;
|
||||
} DirEntry;
|
||||
|
||||
static void dir_entry_destroy(void* item) {
|
||||
if (item) {
|
||||
DirEntry* de = (DirEntry*)item;
|
||||
free(de->path);
|
||||
free(de);
|
||||
}
|
||||
}
|
||||
|
||||
DirectoryScanner* directory_scanner_create_full(char* root_directory, bool use_metadata,
|
||||
static DirEntry* dir_entry_create(const char* path, int depth) {
|
||||
DirEntry* de = malloc(sizeof(DirEntry));
|
||||
if (de) {
|
||||
de->path = str_dup(path);
|
||||
de->depth = depth;
|
||||
}
|
||||
return de;
|
||||
}
|
||||
|
||||
DirectoryScanner* directory_scanner_create(const char* root_directory, bool use_metadata,
|
||||
unsigned long long chunk_size, char** exclude_patterns,
|
||||
int exclude_count, char** include_patterns,
|
||||
int include_count, unsigned long long max_size,
|
||||
unsigned long long min_size, bool follow_symlinks) {
|
||||
unsigned long long min_size, int max_depth,
|
||||
bool follow_symlinks, bool copy_links, bool safe_links,
|
||||
bool copy_unsafe_links) {
|
||||
DirectoryScanner* scanner = malloc(sizeof(DirectoryScanner));
|
||||
if (scanner == NULL)
|
||||
return NULL;
|
||||
scanner->directories = queue_create(100, free);
|
||||
scanner->directories = queue_create(100, dir_entry_destroy);
|
||||
scanner->current_dir = NULL;
|
||||
scanner->current_path = NULL;
|
||||
scanner->use_metadata = use_metadata;
|
||||
scanner->chunk_size = chunk_size > 0 ? chunk_size : DESIRED_CHUNK_SIZE;
|
||||
/* Deep-copy exclude patterns */
|
||||
if (exclude_count > 0 && exclude_patterns != NULL) {
|
||||
scanner->exclude_patterns = malloc((size_t)exclude_count * sizeof(char*));
|
||||
if (scanner->exclude_patterns == NULL) {
|
||||
queue_destroy(scanner->directories);
|
||||
free(scanner);
|
||||
return NULL;
|
||||
}
|
||||
for (int i = 0; i < exclude_count; i++) {
|
||||
scanner->exclude_patterns[i] = str_dup(exclude_patterns[i]);
|
||||
if (scanner->exclude_patterns[i] == NULL) {
|
||||
for (int j = 0; j < i; j++)
|
||||
free(scanner->exclude_patterns[j]);
|
||||
free(scanner->exclude_patterns);
|
||||
queue_destroy(scanner->directories);
|
||||
free(scanner);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
scanner->exclude_patterns = NULL;
|
||||
}
|
||||
scanner->exclude_patterns = exclude_patterns;
|
||||
scanner->exclude_count = exclude_count;
|
||||
|
||||
/* Deep-copy include patterns */
|
||||
if (include_count > 0 && include_patterns != NULL) {
|
||||
scanner->include_patterns = malloc((size_t)include_count * sizeof(char*));
|
||||
if (scanner->include_patterns == NULL) {
|
||||
for (int i = 0; i < exclude_count; i++)
|
||||
free(scanner->exclude_patterns[i]);
|
||||
free(scanner->exclude_patterns);
|
||||
queue_destroy(scanner->directories);
|
||||
free(scanner);
|
||||
return NULL;
|
||||
}
|
||||
for (int i = 0; i < include_count; i++) {
|
||||
scanner->include_patterns[i] = str_dup(include_patterns[i]);
|
||||
if (scanner->include_patterns[i] == NULL) {
|
||||
for (int j = 0; j < i; j++)
|
||||
free(scanner->include_patterns[j]);
|
||||
free(scanner->include_patterns);
|
||||
for (int j = 0; j < exclude_count; j++)
|
||||
free(scanner->exclude_patterns[j]);
|
||||
free(scanner->exclude_patterns);
|
||||
queue_destroy(scanner->directories);
|
||||
free(scanner);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
scanner->include_patterns = NULL;
|
||||
}
|
||||
scanner->include_patterns = include_patterns;
|
||||
scanner->include_count = include_count;
|
||||
scanner->max_size = max_size;
|
||||
scanner->min_size = min_size;
|
||||
scanner->max_depth = max_depth;
|
||||
scanner->current_depth = 0;
|
||||
scanner->follow_symlinks = follow_symlinks;
|
||||
queue_enqueue(scanner->directories, str_dup(root_directory));
|
||||
scanner->copy_links = copy_links;
|
||||
scanner->safe_links = safe_links;
|
||||
scanner->copy_unsafe_links = copy_unsafe_links;
|
||||
queue_enqueue(scanner->directories, dir_entry_create(root_directory, 0));
|
||||
return scanner;
|
||||
}
|
||||
|
||||
@@ -103,12 +73,6 @@ void directory_scanner_destroy(DirectoryScanner* scanner) {
|
||||
scanner->current_dir = NULL;
|
||||
}
|
||||
free(scanner->current_path);
|
||||
for (int i = 0; i < scanner->exclude_count; i++)
|
||||
free(scanner->exclude_patterns[i]);
|
||||
free(scanner->exclude_patterns);
|
||||
for (int i = 0; i < scanner->include_count; i++)
|
||||
free(scanner->include_patterns[i]);
|
||||
free(scanner->include_patterns);
|
||||
queue_destroy(scanner->directories);
|
||||
free(scanner);
|
||||
}
|
||||
@@ -122,7 +86,6 @@ static Chunk* chunk_data_to_chunk(ArrayList* chunk_data) {
|
||||
return chunk;
|
||||
}
|
||||
|
||||
// Returns: 1 on success, 0 if no more directories in queue, -1 on opendir failure
|
||||
static int open_next_directory(DirectoryScanner* scanner) {
|
||||
if (scanner->current_dir) {
|
||||
closedir(scanner->current_dir);
|
||||
@@ -133,7 +96,10 @@ static int open_next_directory(DirectoryScanner* scanner) {
|
||||
if (queue_is_empty(scanner->directories))
|
||||
return 0;
|
||||
|
||||
scanner->current_path = (char*)queue_dequeue(scanner->directories);
|
||||
DirEntry* de = (DirEntry*)queue_dequeue(scanner->directories);
|
||||
scanner->current_path = de->path;
|
||||
scanner->current_depth = de->depth;
|
||||
free(de);
|
||||
scanner->current_dir = opendir(scanner->current_path);
|
||||
if (scanner->current_dir == NULL) {
|
||||
perror("Could not open directory");
|
||||
@@ -171,77 +137,72 @@ Chunk* directory_scanner_next(DirectoryScanner* scanner) {
|
||||
|
||||
char* cur_path = path_cat(scanner->current_path, entry->d_name);
|
||||
struct stat stats;
|
||||
// Use lstat to detect symlinks
|
||||
if (lstat(cur_path, &stats) != 0) {
|
||||
struct stat lstats;
|
||||
bool is_symlink = false;
|
||||
if (lstat(cur_path, &lstats) != 0) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
is_symlink = S_ISLNK(lstats.st_mode);
|
||||
|
||||
if (is_symlink && !scanner->follow_symlinks && !scanner->copy_links && !scanner->safe_links &&
|
||||
!scanner->copy_unsafe_links) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
|
||||
// If follow_symlinks is enabled and this is a symlink, resolve it
|
||||
if (scanner->follow_symlinks && S_ISLNK(stats.st_mode)) {
|
||||
struct stat target_stats;
|
||||
if (stat(cur_path, &target_stats) != 0) {
|
||||
// Broken symlink, skip
|
||||
if (is_symlink && scanner->safe_links) {
|
||||
char link_target[4096];
|
||||
ssize_t len = readlink(cur_path, link_target, sizeof(link_target) - 1);
|
||||
if (len < 0) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
link_target[len] = '\0';
|
||||
if (link_target[0] == '/') {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (is_symlink && scanner->copy_unsafe_links && !scanner->copy_links) {
|
||||
char link_target[4096];
|
||||
ssize_t len = readlink(cur_path, link_target, sizeof(link_target) - 1);
|
||||
if (len < 0) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
link_target[len] = '\0';
|
||||
bool unsafe = (link_target[0] == '/');
|
||||
if (!unsafe) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
bool use_lstat = is_symlink && scanner->follow_symlinks && !scanner->copy_links;
|
||||
if (use_lstat) {
|
||||
stats = lstats;
|
||||
} else {
|
||||
if (stat(cur_path, &stats) != 0) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
stats = target_stats;
|
||||
}
|
||||
|
||||
if (S_ISDIR(stats.st_mode)) {
|
||||
queue_enqueue(scanner->directories, (void*)cur_path);
|
||||
} else if (S_ISLNK(stats.st_mode)) {
|
||||
// Handle symlink (not following)
|
||||
bool excluded = false;
|
||||
for (int i = 0; i < scanner->exclude_count; i++) {
|
||||
if (glob_match(scanner->exclude_patterns[i], entry->d_name)) {
|
||||
excluded = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (excluded) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (scanner->include_count > 0) {
|
||||
bool included = false;
|
||||
for (int i = 0; i < scanner->include_count; i++) {
|
||||
if (glob_match(scanner->include_patterns[i], entry->d_name)) {
|
||||
included = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!included) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
File* file = file_create(cur_path);
|
||||
if (file == NULL) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
file->type = FILE_TYPE_SYMLINK;
|
||||
// Read link target
|
||||
char link_buf[4096];
|
||||
ssize_t link_len = readlink(cur_path, link_buf, sizeof(link_buf) - 1);
|
||||
if (link_len >= 0) {
|
||||
link_buf[link_len] = '\0';
|
||||
file->link_target = str_dup(link_buf);
|
||||
}
|
||||
file->data->size = 0;
|
||||
if (scanner->use_metadata)
|
||||
file->metadata = file_metadata_create(&stats);
|
||||
array_list_add(chunk_data, file);
|
||||
chunk_data_size += 1; // small size for symlinks
|
||||
if (chunk_data_size > scanner->chunk_size) {
|
||||
free(cur_path);
|
||||
return chunk_data_to_chunk(chunk_data);
|
||||
int next_depth = scanner->current_depth + 1;
|
||||
if (scanner->max_depth <= 0 || next_depth < scanner->max_depth) {
|
||||
DirEntry* de = dir_entry_create(cur_path, next_depth);
|
||||
if (!queue_enqueue(scanner->directories, de))
|
||||
dir_entry_destroy(de);
|
||||
}
|
||||
free(cur_path);
|
||||
} else {
|
||||
if (scanner->max_depth > 0 && scanner->current_depth + 1 > scanner->max_depth) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
bool excluded = false;
|
||||
for (int i = 0; i < scanner->exclude_count; i++) {
|
||||
if (glob_match(scanner->exclude_patterns[i], entry->d_name)) {
|
||||
@@ -297,3 +258,318 @@ Chunk* directory_scanner_next(DirectoryScanner* scanner) {
|
||||
array_list_delete(chunk_data);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
ParallelScanner* ps;
|
||||
char** dirs;
|
||||
int dir_count;
|
||||
bool use_metadata;
|
||||
unsigned long long chunk_size;
|
||||
char** exclude_patterns;
|
||||
int exclude_count;
|
||||
char** include_patterns;
|
||||
int include_count;
|
||||
unsigned long long max_size;
|
||||
unsigned long long min_size;
|
||||
int max_depth;
|
||||
bool follow_symlinks;
|
||||
bool copy_links;
|
||||
bool safe_links;
|
||||
bool copy_unsafe_links;
|
||||
} ParallelWorkerArg;
|
||||
|
||||
static int parallel_worker_thread(void* arg) {
|
||||
ParallelWorkerArg* wa = (ParallelWorkerArg*)arg;
|
||||
for (int i = 0; i < wa->dir_count; i++) {
|
||||
DirectoryScanner* ds = directory_scanner_create(
|
||||
wa->dirs[i], wa->use_metadata, wa->chunk_size, wa->exclude_patterns, wa->exclude_count,
|
||||
wa->include_patterns, wa->include_count, wa->max_size, wa->min_size, wa->max_depth,
|
||||
wa->follow_symlinks, wa->copy_links, wa->safe_links, wa->copy_unsafe_links);
|
||||
Chunk* chunk;
|
||||
while ((chunk = directory_scanner_next(ds)) != NULL) {
|
||||
queue_enqueue_multithreaded(wa->ps->result_queue, chunk, &wa->ps->result_mutex,
|
||||
&wa->ps->result_not_empty, &wa->ps->result_not_full);
|
||||
}
|
||||
directory_scanner_destroy(ds);
|
||||
free(wa->dirs[i]);
|
||||
}
|
||||
ParallelScanner* ps = wa->ps;
|
||||
free(wa->dirs);
|
||||
free(wa);
|
||||
mtx_lock(&ps->result_mutex);
|
||||
ps->completed++;
|
||||
if (ps->completed >= ps->num_threads) {
|
||||
ps->done = true;
|
||||
cnd_signal(&ps->result_not_empty);
|
||||
}
|
||||
mtx_unlock(&ps->result_mutex);
|
||||
return thrd_success;
|
||||
}
|
||||
|
||||
ParallelScanner* parallel_scanner_create(char* root_directory, bool use_metadata,
|
||||
unsigned long long chunk_size, char** exclude_patterns,
|
||||
int exclude_count, char** include_patterns,
|
||||
int include_count, unsigned long long max_size,
|
||||
unsigned long long min_size, int max_depth,
|
||||
int num_threads, bool follow_symlinks, bool copy_links,
|
||||
bool safe_links, bool copy_unsafe_links) {
|
||||
ParallelScanner* ps = calloc(1, sizeof(ParallelScanner));
|
||||
if (!ps)
|
||||
return NULL;
|
||||
ps->result_queue = queue_create(100, chunk_destroy);
|
||||
if (!ps->result_queue) {
|
||||
free(ps);
|
||||
return NULL;
|
||||
}
|
||||
if (mtx_init(&ps->result_mutex, mtx_plain) != thrd_success ||
|
||||
cnd_init(&ps->result_not_empty) != thrd_success ||
|
||||
cnd_init(&ps->result_not_full) != thrd_success) {
|
||||
queue_destroy(ps->result_queue);
|
||||
free(ps);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
DIR* dir = opendir(root_directory);
|
||||
if (!dir) {
|
||||
perror("Could not open root directory for parallel scan");
|
||||
parallel_scanner_destroy(ps);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
ArrayList* root_files = array_list_create(file_destroy);
|
||||
ArrayList* subdirs = array_list_create(free);
|
||||
struct dirent* entry;
|
||||
while ((entry = readdir(dir)) != NULL) {
|
||||
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
|
||||
continue;
|
||||
char* cur_path = path_cat(root_directory, entry->d_name);
|
||||
if (!cur_path)
|
||||
continue;
|
||||
struct stat lstats;
|
||||
if (lstat(cur_path, &lstats) != 0) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
bool is_symlink = S_ISLNK(lstats.st_mode);
|
||||
|
||||
// Skip symlinks unless the user explicitly enabled following/copying them.
|
||||
if (is_symlink && !follow_symlinks && !copy_links && !safe_links &&
|
||||
!copy_unsafe_links) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
|
||||
// --safe-links: reject symlinks pointing outside the source tree.
|
||||
if (is_symlink && safe_links) {
|
||||
char link_target[4096];
|
||||
ssize_t len = readlink(cur_path, link_target, sizeof(link_target) - 1);
|
||||
if (len < 0) {
|
||||
free(cur_path);
|
||||
continue;
|
||||
}
|
||||
link_target[len] = ' | ||||