-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfast_copy.py
More file actions
5722 lines (4958 loc) · 239 KB
/
fast_copy.py
File metadata and controls
5722 lines (4958 loc) · 239 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright 2026 George Kapellakis
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
"""
FAST BLOCK-ORDER COPY — Copies files and folders at maximum speed via SSH.
Supports all four copy modes:
• local → local (block-order copy with dedup)
• local → remote (SFTP + tar stream to SSH server)
• remote → local (SFTP + tar stream from SSH server)
• remote → remote (relay through local machine: src SSH → dst SSH)
Features:
• Reads files in PHYSICAL disk order (eliminates random seeks)
• Pre-flight space check (compares source size vs destination free space)
• Content-aware deduplication (hashes files, copies each unique file once,
hard-links duplicates — like Dell's backup dedup)
• Cross-run dedup database (SQLite cache at destination — skips re-hashing
unchanged files, detects content already on destination from prior runs)
• Strong hashing (xxh128 / SHA-256 fallback) for collision safety
• Large I/O buffers (64MB default)
• Post-copy verification
• SSH remote support via paramiko (SFTP + tar streaming)
• Incremental sync — skips files already present and identical
• Small-file bundling via tar pipe for fast network transfers
Usage:
python fast_copy.py <source> <destination>
Source and destination can be local paths or remote SSH paths (user@host:/path).
Examples:
# Local to local
python fast_copy.py /home/user/data /media/usb/data
# Local to remote
python fast_copy.py /data user@server:/backup/data
# Remote to local
python fast_copy.py user@server:/data /local/backup
# Remote to remote (relay through local machine)
python fast_copy.py user@src-host:/data user@dst-host:/backup/data
# With options
python fast_copy.py user@src:/data user@dst:/backup -z --no-dedup
python fast_copy.py user@host:/data /local --src-port 2222
Options:
--buffer MB Read/write buffer size in MB (default: 64)
--threads N Threads for hashing & layout resolution (default: 4)
--dry-run Show copy plan without copying
--no-verify Skip post-copy verification
--log-file PATH Write structured JSON log to file
--no-dedup Disable deduplication (copy all files even if identical)
--overwrite Overwrite all files, skip identical-file detection
--exclude NAME Exclude files/dirs by name (can use multiple times)
--no-cache Disable persistent hash cache (cross-run dedup database)
--force Skip space check and copy anyway
--ssh-dst-port PORT SSH port for remote destination (default: 22)
--ssh-dst-key PATH SSH private key for remote destination
--ssh-dst-password Prompt for SSH password for destination
--ssh-src-port PORT SSH port for remote source (default: 22)
--ssh-src-key PATH SSH private key for remote source
--ssh-src-password Prompt for SSH password for source
-z, --compress Enable SSH compression (good for slow links)
--version, -V Show version and exit
--check-update Show available updates and release notes
--update [VERSION] Download and install (latest, or a specific version)
Requires: python -m pip install paramiko
"""
import os
import sys
import stat
import time
import glob as globmod
import struct
import ctypes
import shutil
import hashlib
import tarfile
import io
import json
import sqlite3
import tempfile
import re
import getpass
import posixpath
import shlex
import argparse
import platform
import threading
from pathlib import Path
from collections import namedtuple, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
# ════════════════════════════════════════════════════════════════════════════
# VERSION
# ════════════════════════════════════════════════════════════════════════════
__version__ = "3.0.1"
GITHUB_REPO = "gekap/fast-copy"
# ════════════════════════════════════════════════════════════════════════════
# CONFIG
# ════════════════════════════════════════════════════════════════════════════
DEFAULT_BUFFER_MB = 64
DEFAULT_THREADS = 4
HASH_CHUNK = 1048571 # ~1MB chunks for hashing (prime for alignment)
HASH_ALGO = "xxh128" # try xxhash first, fallback to sha256
FileEntry = namedtuple("FileEntry", ["src", "rel", "size", "physical_offset", "content_hash"])
# ════════════════════════════════════════════════════════════════════════════
# STRUCTURED LOG — collects per-file actions for --log-file output
# ════════════════════════════════════════════════════════════════════════════
_log_entries = []
_log_enabled = False
_log_lock = threading.Lock()
def _log(action, rel_path, size, **extra):
"""Append a log entry if logging is enabled. Thread-safe."""
if not _log_enabled:
return
entry = {"action": action, "path": rel_path, "size": size}
entry.update(extra)
with _log_lock:
_log_entries.append(entry)
def write_log_file(path, summary):
"""Write JSON log with per-file entries and summary."""
import datetime
log = {
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"summary": summary,
"files": list(_log_entries),
}
with open(path, "w") as f:
json.dump(log, f, indent=2)
_log_entries.clear()
print(f" Log: {C.BOLD}{path}{C.RESET}")
# ════════════════════════════════════════════════════════════════════════════
# TERMINAL OUTPUT
# ════════════════════════════════════════════════════════════════════════════
_is_tty = sys.stdout.isatty()
class C:
GREEN = "\033[92m" if _is_tty else ""
YELLOW = "\033[93m" if _is_tty else ""
RED = "\033[91m" if _is_tty else ""
CYAN = "\033[96m" if _is_tty else ""
BOLD = "\033[1m" if _is_tty else ""
DIM = "\033[2m" if _is_tty else ""
RESET = "\033[0m" if _is_tty else ""
def fmt_size(n):
for u in ("B", "KB", "MB", "GB", "TB"):
if n < 1024:
return f"{n:.1f} {u}"
n /= 1024
return f"{n:.1f} PB"
def fmt_speed(bps):
return f"{fmt_size(bps)}/s"
def fmt_time(s):
if s < 60:
return f"{s:.1f}s"
m, s = divmod(int(s), 60)
if m < 60:
return f"{m}m {s}s"
h, m = divmod(m, 60)
return f"{h}h {m}m {s}s"
def fmt_pct(a, b):
if b == 0:
return "0%"
return f"{a / b * 100:.1f}%"
def banner(msg):
print(f"\n{C.BOLD}{C.CYAN}{'─'*60}")
print(f" {msg}")
print(f"{'─'*60}{C.RESET}\n")
# ════════════════════════════════════════════════════════════════════════════
# HASHING — use xxhash if available (10x faster), fallback to sha256
#
# Algorithm selection is dynamic: defaults to "auto" at import time, but can
# be overridden via --hash before Phase 2. See _set_hash_algo() below.
# ════════════════════════════════════════════════════════════════════════════
try:
import xxhash
_HAS_XXHASH = True
except ImportError:
_HAS_XXHASH = False
def _make_sha256_hasher():
return hashlib.sha256()
def _make_xxh128_hasher():
return xxhash.xxh128()
# Initial auto-selection: xxh128 if installed, else sha256.
# new_hasher and _hash_name may be reassigned later by _set_hash_algo().
if _HAS_XXHASH:
new_hasher = _make_xxh128_hasher
_hash_name = "xxh128"
else:
new_hasher = _make_sha256_hasher
_hash_name = "sha256"
_EMPTY_HASH = new_hasher().hexdigest() # hash of zero bytes for active algorithm
_hash_source = "auto" # "auto" | "forced" — set by --hash flag
def _set_hash_algo(choice):
"""Configure the active hash algorithm based on the --hash flag.
choice must be one of: "auto", "xxh128", "sha256".
Raises SystemExit if "xxh128" is requested but the xxhash package
isn't installed.
Updates module-level globals: new_hasher, _hash_name, _EMPTY_HASH,
_hash_source. Must be called before any hashing happens (i.e. before
Phase 2), otherwise cached hashes would use the previous algorithm.
"""
global new_hasher, _hash_name, _EMPTY_HASH, _hash_source
if choice == "auto":
# Keep the initial auto-selection (already set at import time).
_hash_source = "auto"
return
if choice == "xxh128":
if not _HAS_XXHASH:
print(
f"{C.RED}Error: --hash=xxh128 requested but xxhash package "
f"not installed.{C.RESET}\n"
f" Install with: {C.BOLD}python -m pip install xxhash{C.RESET}\n"
f" Or use --hash=sha256 or --hash=auto instead.",
file=sys.stderr,
)
sys.exit(2)
new_hasher = _make_xxh128_hasher
_hash_name = "xxh128"
elif choice == "sha256":
new_hasher = _make_sha256_hasher
_hash_name = "sha256"
else:
raise ValueError("invalid hash choice: {}".format(choice))
_EMPTY_HASH = new_hasher().hexdigest()
_hash_source = "forced"
def hash_file(filepath, buf_size=HASH_CHUNK):
"""Hash file contents. Returns hex digest string."""
h = new_hasher()
try:
with open(filepath, "rb") as f:
chunk = f.read(buf_size)
if not chunk:
return _EMPTY_HASH
while chunk:
h.update(chunk)
chunk = f.read(buf_size)
return h.hexdigest()
except OSError:
return None
# ════════════════════════════════════════════════════════════════════════════
# PATH SAFETY — prevents path traversal attacks
# ════════════════════════════════════════════════════════════════════════════
def _validate_rel_path(rel):
"""Check that a relative path is safe for tar inclusion. Returns True or error string."""
if not rel or rel.startswith('/') or os.path.isabs(rel):
return "absolute path"
for part in rel.replace('\\', '/').split('/'):
if part == '..':
return "path traversal (..)"
if '\0' in rel or '\n' in rel:
return "null or newline in path"
return True
def _validate_tar_member(member, dst_root):
"""Validate a tar member for safety. Returns True or error string."""
# Reject absolute paths
if member.name.startswith('/') or os.path.isabs(member.name):
return "blocked: absolute path"
# Check every component for '..'
for part in member.name.replace('\\', '/').split('/'):
if part == '..':
return "blocked: path traversal (..)"
# Explicitly reject dangerous member types (symlinks, hard links, devices, FIFOs)
if member.issym():
return "blocked: symlink"
if member.islnk():
return "blocked: tar hard link"
if member.isdev() or member.isfifo() or member.ischr() or member.isblk():
return "blocked: device/fifo"
# Only allow regular files and directories
if not (member.isfile() or member.isdir()):
return "blocked: unsupported member type"
# Reject null bytes in name
if '\0' in member.name:
return "blocked: null byte in name"
# Resolve final path and verify it stays within dst_root.
# Use os.path.normcase for the comparison so case-insensitive
# filesystems (Windows NTFS, macOS HFS+ default, APFS default)
# don't reject legitimate paths just because Python's string
# comparison is case-sensitive while the filesystem is not.
resolved = os.path.realpath(os.path.join(dst_root, member.name))
real_dst = os.path.realpath(dst_root)
nc_resolved = os.path.normcase(resolved)
nc_real_dst = os.path.normcase(real_dst)
if not (nc_resolved == nc_real_dst or
nc_resolved.startswith(nc_real_dst + os.sep)):
return "blocked: resolves outside destination"
return True
def _safe_tar_extract(tar, member, dst_root):
"""Extract a single tar member safely. Returns True on success, error string on failure."""
check = _validate_tar_member(member, dst_root)
if check is not True:
return check
# Safe to extract — sanitize member metadata
member.uid = member.gid = 0
member.uname = member.gname = ""
extract_path = _long_path(dst_root) if _system == "Windows" else dst_root
try:
tar.extract(member, path=extract_path, filter='data')
except TypeError:
# Python <3.12: filter not supported, but member is already sanitized
tar.extract(member, path=extract_path)
return True
# ════════════════════════════════════════════════════════════════════════════
# DEDUP DATABASE — persistent hash cache across runs
# ════════════════════════════════════════════════════════════════════════════
DEDUP_DB_NAME = ".fast_copy_dedup.db"
def _find_mount_point(path):
"""Walk up from path to find the filesystem mount point."""
path = os.path.realpath(path)
while not os.path.ismount(path):
path = os.path.dirname(path)
return path
class DedupDB:
"""
SQLite-backed hash cache stored at the mount/drive root.
Shared across all destinations on the same drive.
Two tables:
source_cache — keyed on (source rel_path, size, mtime_ns)
Speeds up hashing: same source file → same hash
regardless of which destination subfolder you copy to.
dest_files — keyed on mount-relative path
Tracks what's actually on the drive for cross-run dedup.
"""
def __init__(self, dst_root):
self.dst_root = os.path.realpath(dst_root)
self.mount = _find_mount_point(dst_root)
# Avoid writing DB to filesystem root — fall back to destination dir
if self.mount == "/" or not os.access(self.mount, os.W_OK):
db_path = os.path.join(self.dst_root, DEDUP_DB_NAME)
else:
db_path = os.path.join(self.mount, DEDUP_DB_NAME)
self.db_path = db_path
# Prefix to convert dest-relative → mount-relative
self._prefix = os.path.relpath(self.dst_root, self.mount)
# Reject if db_path is a symlink — use O_NOFOLLOW to avoid TOCTOU race
if hasattr(os, 'O_NOFOLLOW'):
try:
fd = os.open(db_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
os.close(fd)
except OSError as e:
import errno
if e.errno in (errno.ELOOP, errno.EMLINK):
raise OSError(f"Refusing to open dedup DB: {db_path} is a symlink")
raise
elif os.path.islink(db_path):
raise OSError(f"Refusing to open dedup DB: {db_path} is a symlink")
# Create DB with restrictive permissions (owner-only)
old_umask = os.umask(0o077)
try:
self.conn = sqlite3.connect(db_path, check_same_thread=False)
finally:
os.umask(old_umask)
try:
self.conn.execute("PRAGMA journal_mode=WAL")
self.conn.execute("PRAGMA synchronous=NORMAL") # WAL default, crash-safe
self.conn.execute("PRAGMA user_version=4718") # schema v2
self.lock = threading.Lock()
self._init_schema()
except Exception:
self.conn.close()
raise
def _mount_rel(self, rel_path):
"""Convert destination-relative path to mount-relative path.
Normalizes to forward slashes for cross-platform DB portability."""
return os.path.join(self._prefix, rel_path).replace(os.sep, '/')
def _init_schema(self):
c = self.conn.cursor()
# Source hash cache — shared across all destination folders
c.execute("""
CREATE TABLE IF NOT EXISTS source_cache (
rel_path TEXT NOT NULL,
size INTEGER NOT NULL,
mtime_ns INTEGER NOT NULL,
content_hash TEXT NOT NULL,
hash_algo TEXT NOT NULL,
PRIMARY KEY (rel_path, hash_algo)
)
""")
# Destination file index — tracks files on the drive
c.execute("""
CREATE TABLE IF NOT EXISTS dest_files (
mount_rel TEXT PRIMARY KEY,
size INTEGER NOT NULL,
content_hash TEXT NOT NULL,
hash_algo TEXT NOT NULL
)
""")
c.execute("""
CREATE INDEX IF NOT EXISTS idx_dest_hash
ON dest_files (content_hash)
""")
# Migrate old single-table schema if present
try:
c.execute("SELECT 1 FROM file_hashes LIMIT 1")
c.execute("DROP TABLE file_hashes")
except sqlite3.OperationalError:
pass
self.conn.commit()
# ── Source cache (hash speedup) ───────────────────────────────
def lookup(self, rel_path, size, mtime_ns):
"""Return cached hash if source file size+mtime match, else None."""
with self.lock:
c = self.conn.cursor()
c.execute(
"SELECT content_hash FROM source_cache "
"WHERE rel_path = ? AND size = ? AND mtime_ns = ? AND hash_algo = ?",
(rel_path, size, mtime_ns, _hash_name),
)
row = c.fetchone()
return row[0] if row else None
def store_source_batch(self, rows):
"""Cache source hashes. rows = list of (rel_path, size, mtime_ns, hash)."""
with self.lock:
self.conn.executemany(
"INSERT OR REPLACE INTO source_cache "
"(rel_path, size, mtime_ns, content_hash, hash_algo) "
"VALUES (?, ?, ?, ?, ?)",
[(r[0], r[1], r[2], r[3], _hash_name) for r in rows],
)
self.conn.commit()
# ── Destination index (cross-run dedup) ───────────────────────
def store_dest_batch(self, rows):
"""Record files on the drive. rows = list of (rel_path, size, hash).
rel_path is destination-relative; stored as mount-relative."""
with self.lock:
self.conn.executemany(
"INSERT OR REPLACE INTO dest_files "
"(mount_rel, size, content_hash, hash_algo) "
"VALUES (?, ?, ?, ?)",
[(self._mount_rel(r[0]), r[1], r[2], _hash_name) for r in rows],
)
self.conn.commit()
def lookup_by_hash(self, content_hash):
"""Find files on this drive with this hash.
Returns list of (mount_rel_path, size)."""
with self.lock:
c = self.conn.cursor()
c.execute(
"SELECT mount_rel, size FROM dest_files "
"WHERE content_hash = ? AND hash_algo = ?",
(content_hash, _hash_name),
)
return c.fetchall()
def close(self):
with self.lock:
self.conn.commit()
self.conn.close()
# ════════════════════════════════════════════════════════════════════════════
# SSH REMOTE — connection, parsing, remote operations
# ════════════════════════════════════════════════════════════════════════════
try:
import paramiko
_has_paramiko = True
except ImportError:
_has_paramiko = False
RemoteSpec = namedtuple("RemoteSpec", ["user", "host", "port", "path"])
REMOTE_MANIFEST_NAME = ".fast_copy_manifest.json"
def parse_remote_path(path_str):
"""Parse user@host:/path or host:/path. Returns RemoteSpec or None.
Supports IPv6 in brackets: user@[::1]:/path"""
# Try IPv6 in brackets first: user@[host]:/path or [host]:/path
m = re.match(r'^(?:([^@]+)@)?\[([^\]]+)\]:(.+)$', path_str)
if not m:
# Standard: user@host:/path or host:/path
# Host must not contain whitespace
m = re.match(r'^(?:([^@]+)@)?([^:\s]+):(.+)$', path_str)
if not m:
return None
# Single-letter host is a Windows drive letter (e.g. C:\), not a remote
if len(m.group(2)) == 1 and m.group(2).isalpha():
return None
user = m.group(1) or getpass.getuser()
host = m.group(2)
path = m.group(3)
return RemoteSpec(user=user, host=host, port=22, path=path)
_ParamikoHostKeyBase = paramiko.MissingHostKeyPolicy if _has_paramiko else object
class _InteractiveHostKeyPolicy(_ParamikoHostKeyBase):
"""Prompts the user to accept unknown host keys, like OpenSSH does."""
def missing_host_key(self, client, hostname, key):
key_type = key.get_name()
fingerprint_md5 = ":".join(f"{b:02x}" for b in key.get_fingerprint())
import base64
fingerprint_sha256 = base64.b64encode(
hashlib.sha256(key.asbytes()).digest()
).decode().rstrip("=")
print(f"\n {C.RED}WARNING: Unknown host key for {hostname}.{C.RESET}")
print(f" {C.YELLOW}Verify this fingerprint with the server administrator{C.RESET}")
print(f" {C.YELLOW}before accepting to prevent man-in-the-middle attacks.{C.RESET}")
print(f" Type: {key_type}")
print(f" MD5: {fingerprint_md5}")
print(f" SHA256: {fingerprint_sha256}")
try:
answer = input(f" Accept and save to known_hosts? [y/N]: ").strip().lower()
except (EOFError, KeyboardInterrupt):
answer = ""
if answer not in ("y", "yes"):
raise paramiko.SSHException(
f"Host key for {hostname} rejected by user"
)
# Save to ~/.ssh/known_hosts
known_hosts = os.path.expanduser("~/.ssh/known_hosts")
os.makedirs(os.path.dirname(known_hosts), exist_ok=True)
try:
host_keys = paramiko.HostKeys(known_hosts)
except (IOError, OSError):
host_keys = paramiko.HostKeys()
host_keys.add(hostname, key_type, key)
try:
host_keys.save(known_hosts)
print(f" {C.GREEN}Host key saved to {known_hosts}{C.RESET}")
except (IOError, OSError) as e:
print(f" {C.YELLOW}Could not save host key: {e}{C.RESET}")
class SSHConnection:
"""Paramiko SSH wrapper with exec, SFTP, and capability detection."""
def __init__(self, spec, port=22, key_path=None, password=None, compress=False):
self.spec = spec._replace(port=port)
self.key_path = key_path
self.password = password
self.compress = compress
self.client = None
self.sftp = None
self.caps = {}
def connect(self):
self.client = paramiko.SSHClient()
# Load system known_hosts for host key verification
try:
self.client.load_system_host_keys()
except IOError:
pass
known_hosts = os.path.expanduser("~/.ssh/known_hosts")
if os.path.isfile(known_hosts):
try:
self.client.load_host_keys(known_hosts)
except IOError:
pass
self.client.set_missing_host_key_policy(_InteractiveHostKeyPolicy())
connect_kwargs = {
"hostname": self.spec.host,
"port": self.spec.port,
"username": self.spec.user,
"compress": self.compress,
}
# Auth: try key file → agent/default keys → password
if self.key_path:
connect_kwargs["key_filename"] = self.key_path
if self.password:
connect_kwargs["password"] = self.password
max_attempts = 3
try:
for attempt in range(1, max_attempts + 1):
try:
self.client.connect(**connect_kwargs)
break # success
except (paramiko.AuthenticationException, paramiko.SSHException) as e:
# Only retry on auth-related errors, not connection errors
if "auth" not in str(e).lower() and "No authentication" not in str(e):
raise
if attempt == max_attempts:
print(f"\n {C.RED}Authentication failed after {max_attempts} attempts.{C.RESET}")
self.client.close()
sys.exit(1)
print(f" {C.YELLOW}Authentication failed. Attempt {attempt}/{max_attempts}.{C.RESET}")
pw = getpass.getpass(f" Password for {self.spec.user}@{self.spec.host}: ")
connect_kwargs["password"] = pw
except (KeyboardInterrupt, EOFError):
print(f"\n {C.YELLOW}Authentication cancelled.{C.RESET}")
self.client.close()
sys.exit(0)
transport = self.client.get_transport()
transport.set_keepalive(30)
# Increase default window/packet size for much faster SFTP throughput
transport.default_window_size = 16 * 1024 * 1024 # 16 MB
transport.default_max_packet_size = 512 * 1024 # 512 KB
self._detect_capabilities()
return self
MAX_CMD_OUTPUT = 100 * 1024 * 1024 # 100 MB cap on command output
def exec_cmd(self, cmd, input_data=None, timeout=300):
"""Execute remote command. Returns (stdout_str, stderr_str, exit_code)."""
import threading
stdin, stdout, stderr = self.client.exec_command(cmd, timeout=timeout)
if input_data:
# Write stdin in a background thread to avoid deadlock: the remote
# command may produce stdout while we're still writing stdin, and if
# either buffer fills both sides stall.
data = input_data.encode("utf-8") if isinstance(input_data, str) else input_data
def _write_stdin():
try:
chunk_size = 65536
for i in range(0, len(data), chunk_size):
stdin.write(data[i:i + chunk_size])
finally:
stdin.channel.shutdown_write()
writer = threading.Thread(target=_write_stdin, daemon=True)
writer.start()
out_bytes = stdout.read(self.MAX_CMD_OUTPUT)
err_bytes = stderr.read(self.MAX_CMD_OUTPUT)
# Warn if output was likely truncated
if len(out_bytes) >= self.MAX_CMD_OUTPUT:
print(f" {C.YELLOW}Warning: remote command output truncated at "
f"{self.MAX_CMD_OUTPUT // (1024*1024)}MB{C.RESET}")
out = out_bytes.decode("utf-8", errors="replace")
err = err_bytes.decode("utf-8", errors="replace")
rc = stdout.channel.recv_exit_status()
if input_data:
writer.join(timeout=30)
return out, err, rc
def open_sftp(self):
if self.sftp is None:
transport = self.client.get_transport()
try:
self.sftp = paramiko.SFTPClient.from_transport(
transport,
window_size=16 * 1024 * 1024, # 16 MB (default ~2 MB)
max_packet_size=512 * 1024, # 512 KB (default 32 KB)
)
except Exception:
# Some SSH servers reject large window/packet sizes — fall back
self.sftp = paramiko.SFTPClient.from_transport(transport)
return self.sftp
def open_channel(self):
"""Open a raw exec channel for streaming."""
return self.client.get_transport().open_session()
def _detect_capabilities(self):
"""Check what tools are available on remote."""
for tool, cmd in [
("gnu_find", "find --version 2>/dev/null"),
("tar", "tar --version 2>/dev/null"),
("python3", "python3 --version 2>/dev/null"),
("sha256sum", "sha256sum --version 2>/dev/null"),
]:
_, _, rc = self.exec_cmd(cmd, timeout=10)
self.caps[tool] = (rc == 0)
def close(self):
if self.sftp:
self.sftp.close()
if self.client:
self.client.close()
def check_remote_space(ssh, remote_path, required_bytes, force=False):
"""Check free space on remote via df. Walks up to parent if path doesn't exist."""
# Try the path itself, then walk up to find an existing parent
check_path = remote_path
for _ in range(10):
out, _, rc = ssh.exec_cmd(f"df -B1 {shlex.quote(check_path)} 2>/dev/null")
if rc == 0:
break
parent = posixpath.dirname(check_path.rstrip("/"))
if parent == check_path or not parent:
break
check_path = parent
if rc != 0:
print(f" {C.YELLOW}Could not check remote space — continuing anyway{C.RESET}")
return True # don't block copy just because df failed
lines = out.strip().split("\n")
if len(lines) < 2:
if force:
return True
print(f" {C.RED}Could not parse remote df output{C.RESET}")
return False
parts = lines[1].split()
try:
total = int(parts[1])
free = int(parts[3])
except (IndexError, ValueError):
if force:
return True
return False
pct_free = free / total * 100 if total else 0
print(f" Destination disk (remote):")
print(f" Total: {C.BOLD}{fmt_size(total)}{C.RESET}")
print(f" Free: {C.BOLD}{fmt_size(free)}{C.RESET} ({pct_free:.1f}% free)")
print(f" Required: {C.BOLD}{fmt_size(required_bytes)}{C.RESET}")
if required_bytes > free:
shortfall = required_bytes - free
print(f"\n {C.RED}✗ NOT ENOUGH SPACE — need {fmt_size(shortfall)} more{C.RESET}")
if force:
print(f" {C.YELLOW}Proceeding anyway (--force){C.RESET}")
return True
return False
print(f" Headroom: {fmt_size(free - required_bytes)}")
print(f"\n {C.GREEN}✓ Enough space{C.RESET}")
return True
def ensure_remote_dirs(ssh, remote_root, entries):
"""Create all needed directories on remote in one SSH call."""
dirs = sorted(set(
posixpath.join(remote_root, posixpath.dirname(e.rel))
for e in entries if posixpath.dirname(e.rel)
))
if not dirs:
return
# Batch mkdir -p
dir_args = " ".join(shlex.quote(d) for d in dirs)
ssh.exec_cmd(f"mkdir -p {dir_args}")
import hmac as _hmac_mod
# Key derived from username + hostname + persistent random salt.
# NOTE: This is an integrity check (detects corruption/accidental edits),
# not cryptographic authentication against a fully compromised remote.
# The random salt prevents key prediction from public info alone.
_MANIFEST_SALT_FILE = os.path.join(os.path.expanduser("~"), ".fast_copy_salt")
def _manifest_key():
# Load or create a persistent random salt
salt = b""
try:
with open(_MANIFEST_SALT_FILE, "rb") as f:
salt = f.read(32)
except (IOError, OSError):
pass
if len(salt) < 32:
salt = os.urandom(32)
try:
old_umask = os.umask(0o077)
try:
with open(_MANIFEST_SALT_FILE, "wb") as f:
f.write(salt)
finally:
os.umask(old_umask)
except (IOError, OSError):
pass # proceed with ephemeral salt — manifests won't persist across runs
return hashlib.sha256(
f"fast_copy:{getpass.getuser()}:{platform.node()}:".encode() + salt
).digest()
def _read_remote_file(ssh, path):
"""Read a file from remote, trying SFTP first then exec."""
try:
sftp = ssh.open_sftp()
with sftp.open(path, "r") as f:
return f.read().decode("utf-8")
except Exception:
pass
# Fallback: exec
try:
out, _, rc = ssh.exec_cmd(f"cat {shlex.quote(path)}", timeout=30)
if rc == 0 and out.strip():
return out
except Exception:
pass
return None
def _write_remote_file(ssh, path, content):
"""Write a file to remote, trying SFTP first then exec."""
try:
sftp = ssh.open_sftp()
with sftp.open(path, "w") as f:
f.write(content.encode("utf-8") if isinstance(content, str) else content)
return
except Exception:
pass
# Fallback: exec
try:
ssh.exec_cmd(
f"cat > {shlex.quote(path)}", input_data=content, timeout=30
)
except Exception:
pass
def load_remote_manifest(ssh, remote_root):
"""Load previous-run manifest from remote. Verifies HMAC. Returns dict or empty."""
manifest_path = posixpath.join(remote_root, REMOTE_MANIFEST_NAME)
try:
raw = _read_remote_file(ssh, manifest_path)
if not raw:
return {}
data = json.loads(raw)
stored_mac = data.pop("__hmac__", None)
if stored_mac is None:
return {} # unsigned manifest — treat as absent
payload = json.dumps(data, sort_keys=True).encode()
expected = _hmac_mod.new(_manifest_key(), payload, hashlib.sha256).hexdigest()
if not _hmac_mod.compare_digest(stored_mac, expected):
return {} # tampered — ignore
return data
except (IOError, OSError, json.JSONDecodeError, KeyError):
return {}
def save_remote_manifest(ssh, remote_root, entries, link_map):
"""Save HMAC-signed manifest after successful copy."""
manifest = {}
for e in entries:
if e.content_hash:
manifest[e.rel] = {"size": e.size, "hash": e.content_hash}
for dup_rel, target in link_map.items():
if isinstance(target, tuple):
continue
for e in entries:
if e.rel == target and e.content_hash:
manifest[dup_rel] = {"size": e.size, "hash": e.content_hash}
break
# Sign with HMAC
payload = json.dumps(manifest, sort_keys=True).encode()
mac = _hmac_mod.new(_manifest_key(), payload, hashlib.sha256).hexdigest()
manifest["__hmac__"] = mac
manifest_path = posixpath.join(remote_root, REMOTE_MANIFEST_NAME)
_write_remote_file(ssh, manifest_path, json.dumps(manifest))
def scan_remote_destination(ssh, remote_root):
"""Get file listing from remote in one SSH call. Returns {rel_path: size}."""
# Check if remote directory exists first
_, _, rc = ssh.exec_cmd(f'test -d {shlex.quote(remote_root)}', timeout=10)
if rc != 0:
return {} # directory doesn't exist yet — nothing to compare
if ssh.caps.get("gnu_find"):
cmd = f'find {shlex.quote(remote_root)} -type f -printf "%s\\t%p\\n" 2>/dev/null'
out, _, rc = ssh.exec_cmd(cmd)
result = {}
for line in out.strip().split("\n"):
if not line:
continue
parts = line.split("\t", 1)
if len(parts) == 2:
try:
size = int(parts[0])
path = parts[1]
rel = posixpath.relpath(path, remote_root)
result[rel] = size
except (ValueError, TypeError):
continue
return result
else:
# Portable fallback: find + stat (Linux stat -c, not BSD stat -f)
cmd = (f'find {shlex.quote(remote_root)} -type f '
f'-exec stat -c "%s %n" {{}} + 2>/dev/null || '
f'find {shlex.quote(remote_root)} -type f '
f'-exec stat -f "%z %N" {{}} + 2>/dev/null')
out, _, rc = ssh.exec_cmd(cmd)
result = {}
for line in out.strip().split("\n"):
if not line:
continue
parts = line.split(None, 1)
if len(parts) == 2:
try:
size = int(parts[0])
path = parts[1]
rel = posixpath.relpath(path, remote_root)
result[rel] = size
except (ValueError, TypeError):
continue
return result
def remote_hash_files(ssh, remote_root, rel_paths):
"""Hash files on remote in batches. Returns {rel_path: hash_hex}."""
if not rel_paths:
return {}
BATCH_SIZE = 5000 # files per SSH command to avoid channel timeouts
result = {}
for batch_start in range(0, len(rel_paths), BATCH_SIZE):
batch = rel_paths[batch_start:batch_start + BATCH_SIZE]
full_paths = [posixpath.join(remote_root, rp) for rp in batch]
path_input = "\n".join(full_paths) + "\n"
if ssh.caps.get("python3"):
script = (
'import sys,hashlib\n'
'for line in sys.stdin:\n'
' p=line.strip()\n'
' h=hashlib.sha256()\n'
' try:\n'
' with open(p,"rb") as f:\n'
' while True:\n'
' c=f.read(1048576)\n'
' if not c:break\n'
' h.update(c)\n'
' print(h.hexdigest(),p)\n'
' except Exception:print("ERROR",p)\n'
)
out, _, _ = ssh.exec_cmd(
f"python3 -c {shlex.quote(script)}", input_data=path_input,
timeout=600
)
elif ssh.caps.get("sha256sum"):
out, _, _ = ssh.exec_cmd(
"xargs -d '\\n' sha256sum",
input_data=path_input, timeout=600
)
else:
return {} # can't hash remotely
for line in out.strip().split("\n"):
if not line or line.startswith("ERROR"):
continue
parts = line.split(None, 1)
if len(parts) == 2:
h, path = parts
rel = posixpath.relpath(path.strip(), remote_root)
result[rel] = h
if len(rel_paths) > BATCH_SIZE:
done = min(batch_start + BATCH_SIZE, len(rel_paths))