-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdwipe.py
2037 lines (1706 loc) · 94.2 KB
/
dwipe.py
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
import os
import sys
import subprocess
import platform
# Global variable to store disk information
SELECTED_DISK_INFO = None
# --- VENV SETUP ---
VENV_DIR = os.path.join(os.path.dirname(__file__), 'venv')
def ensure_venv():
"""Check if running in virtual environment and set up if needed. Silent unless installation required."""
in_venv = hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
if not in_venv:
# Check if venv exists first
if not os.path.exists(VENV_DIR):
print(f"Creating virtual environment in {VENV_DIR}...")
subprocess.check_call([sys.executable, '-m', 'venv', VENV_DIR],
stdout=subprocess.DEVNULL if os.name != 'nt' else None)
# Prepare paths - handle platform differences
if platform.system() == 'Windows':
pip = os.path.join(VENV_DIR, 'Scripts', 'pip.exe')
python_bin = os.path.join(VENV_DIR, 'Scripts', 'python.exe')
else:
pip = os.path.join(VENV_DIR, 'bin', 'pip')
python_bin = os.path.join(VENV_DIR, 'bin', 'python')
# Check if executable files exist
if not os.path.isfile(pip) or not os.path.isfile(python_bin):
print(f"Warning: Virtual environment files not found. Recreating...")
import shutil
if os.path.exists(VENV_DIR):
shutil.rmtree(VENV_DIR)
subprocess.check_call([sys.executable, '-m', 'venv', VENV_DIR])
# Check if requirements are installed silently
required_packages = ['tqdm', 'colorama', 'psutil']
missing_packages = []
# Use subprocess.DEVNULL to hide output during checking
for package in required_packages:
try:
# Check if package is installed silently
result = subprocess.run(
[pip, 'show', package],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
if result.returncode != 0:
missing_packages.append(package)
except Exception:
missing_packages.append(package)
# If any packages are missing, install them
if missing_packages:
print(f"Installing required packages: {', '.join(missing_packages)}")
# Upgrade pip first
subprocess.check_call([pip, 'install', '--upgrade', 'pip'])
# Install missing packages
subprocess.check_call([pip, 'install'] + missing_packages)
# Execute the script within the virtual environment
os.execv(python_bin, [python_bin] + sys.argv)
ensure_venv()
# --- IMPORTS AFTER VENV ---
import errno
import argparse
import random
import tempfile
import psutil
import re
import time
import math
import datetime
import signal
import atexit
from tqdm import tqdm
from colorama import init, Fore, Style
# Initialize colorama for cross-platform color support
init(autoreset=True)
# Extended ANSI color codes
RED = Fore.RED
GREEN = Fore.GREEN
YELLOW = Fore.YELLOW
BLUE = Fore.BLUE
MAGENTA = Fore.MAGENTA
CYAN = Fore.CYAN
WHITE = Fore.WHITE
RESET = Style.RESET_ALL
BRIGHT = Style.BRIGHT
# --- ASCII BANNER with colors ---
def print_colorful_banner():
BANNER = [
"░ ░░░ ░░░░ ░░ ░░ ░░░ ░",
"▒ ▒▒▒▒ ▒▒ ▒ ▒ ▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒ ▒▒ ▒▒▒▒▒▒▒",
"▓ ▓▓▓▓ ▓▓ ▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓ ▓▓▓",
"█ ████ ██ ██ █████ █████ ████████ ███████",
"█ ███ ████ ██ ██ ████████ █",
" D W i p e v1.5 "
]
colors = [RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN]
# Print each line with a different color
for i, line in enumerate(BANNER):
color = colors[i % len(colors)]
print(f"{BRIGHT}{color}{line}{RESET}")
print("\n")
def format_size(num):
if num is None or num == 0:
return "Unknown"
for unit in ['B','KB','MB','GB','TB']:
if num < 1024.0:
return f"{num:.2f}{unit}"
num /= 1024.0
return f"{num:.2f}PB"
def parse_size(size_str):
"""Parse a size string like '500.1 GB' into bytes."""
if not size_str or size_str == "Unknown":
return 0
# Handle "X.XX Y" format (e.g., "500.1 GB")
match = re.match(r'([0-9,.]+)\s*([A-Za-z]+)', size_str)
if not match:
try:
return int(size_str)
except:
return 0
value = match.group(1).replace(',', '')
value = float(value)
unit = match.group(2).upper()
if unit == 'B':
return int(value)
elif unit == 'KB' or unit == 'K':
return int(value * 1024)
elif unit == 'MB' or unit == 'M':
return int(value * 1024**2)
elif unit == 'GB' or unit == 'G':
return int(value * 1024**3)
elif unit == 'TB' or unit == 'T':
return int(value * 1024**4)
elif unit == 'PB' or unit == 'P':
return int(value * 1024**5)
else:
return 0
def get_friendly_fs_type(fs_type):
"""Get a user-friendly filesystem type name."""
fs_type = fs_type.lower() if fs_type else ""
# Common filesystem types
if fs_type in ["apfs", "apple", "apfs_case_sensitive"]:
return "APFS"
elif fs_type in ["hfs", "hfs+"]:
return "HFS+"
elif fs_type in ["fat32", "vfat", "fat"]:
return "FAT32"
elif fs_type in ["exfat"]:
return "exFAT"
elif fs_type in ["ntfs"]:
return "NTFS"
elif fs_type in ["ext2", "ext3", "ext4"]:
return fs_type.upper()
elif fs_type in ["xfs"]:
return "XFS"
elif fs_type in ["btrfs"]:
return "Btrfs"
elif fs_type in ["zfs"]:
return "ZFS"
elif fs_type in ["ufs"]:
return "UFS"
elif fs_type in ["tmpfs"]:
return "tmpfs"
elif fs_type in ["devfs"]:
return "devfs"
else:
return fs_type.upper() if fs_type else "Unknown"
def get_macos_disk_info():
"""Get detailed disk information for macOS systems."""
try:
# First get list of physical disks
disks_output = subprocess.check_output(['diskutil', 'list'], stderr=subprocess.STDOUT).decode('utf-8')
physical_disks = []
# Extract the disk identifiers (disk0, disk1, etc.)
for line in disks_output.split('\n'):
if line.startswith('/dev/disk'):
disk_id = line.split()[0].replace('/dev/', '')
if disk_id not in physical_disks and not any(c.isdigit() and c != disk_id[-1] for c in disk_id):
physical_disks.append(disk_id)
disk_info = {}
# Get detailed info for each physical disk
for disk_id in physical_disks:
try:
disk_info[disk_id] = {}
info = subprocess.check_output(['diskutil', 'info', disk_id], stderr=subprocess.STDOUT).decode('utf-8')
# Get basic disk info
name_match = re.search(r'Device / Media Name:\s+(.+)', info)
if name_match:
disk_info[disk_id]['name'] = name_match.group(1).strip()
else:
disk_info[disk_id]['name'] = f"Disk {disk_id}"
# Get disk size directly from volume info
size_bytes = 0
size_human = "Unknown"
for part in psutil.disk_partitions(all=True):
if disk_id in part.device:
try:
# Get size from mount point rather than diskutil
usage = psutil.disk_usage(part.mountpoint)
if usage.total > size_bytes:
size_bytes = usage.total
size_human = format_size(usage.total)
except:
pass
# If we couldn't get size from volumes, try diskutil output
if size_bytes == 0:
size_match = re.search(r'Disk Size:\s+([0-9,]+)\s+Bytes\s+\(([^)]+)\)', info)
if size_match:
size_bytes = int(size_match.group(1).replace(',', ''))
size_human = size_match.group(2).strip()
disk_info[disk_id]['size'] = size_bytes
disk_info[disk_id]['size_human'] = size_human
# Now get info about volumes on this disk
volumes = []
for part in psutil.disk_partitions(all=True):
if disk_id in part.device:
vol_info = {
'device': part.device,
'mountpoint': part.mountpoint,
'fstype': part.fstype
}
try:
usage = psutil.disk_usage(part.mountpoint)
vol_info['total'] = usage.total
vol_info['free'] = usage.free
except:
# If we can't get usage, set defaults
vol_info['total'] = 0
vol_info['free'] = 0
volumes.append(vol_info)
# Find the "best" volume to use
best_vol = None
for vol in volumes:
if not best_vol:
best_vol = vol
elif vol['mountpoint'] == '/':
best_vol = vol
elif '/System/Volumes/Data' in vol['mountpoint'] and best_vol['mountpoint'] != '/':
best_vol = vol
if best_vol:
disk_info[disk_id]['mountpoint'] = best_vol['mountpoint']
disk_info[disk_id]['fstype'] = get_friendly_fs_type(best_vol['fstype'])
# Use the actual free space from the volume
disk_info[disk_id]['free'] = best_vol['free']
else:
# If no volumes found, disk is probably not mounted
disk_info[disk_id]['mountpoint'] = None
disk_info[disk_id]['fstype'] = "Unknown"
disk_info[disk_id]['free'] = 0
except Exception as e:
print(f"Error getting info for disk {disk_id}: {e}")
continue
return disk_info
except Exception as e:
print(f"Error getting disk info: {e}")
return {}
def get_physical_drives():
"""Get list of unique physical drives."""
system = platform.system()
physical_drives = []
if system == 'Darwin': # macOS
# Get disk info using macOS-specific method
disk_info = get_macos_disk_info()
# Convert disk_info to our standard format
for disk_id, info in disk_info.items():
if not info.get('mountpoint'):
continue # Skip unmounted disks
physical_drives.append({
'id': len(physical_drives),
'device': f"/dev/{disk_id}",
'name': info.get('name', f"Disk {disk_id}"),
'mountpoint': info.get('mountpoint', 'Not mounted'),
'fstype': info.get('fstype', 'Unknown'),
'size': info.get('size', 0),
'size_human': info.get('size_human', 'Unknown'),
'free': info.get('free', 0)
})
else:
# For non-macOS systems, use a more generic approach with psutil
seen_devices = set()
for part in psutil.disk_partitions(all=True):
try:
# Skip non-physical drives on Windows
if system == 'Windows' and ('cdrom' in part.opts or part.fstype == ''):
continue
# Get the base device name (e.g., "sda" from "sda1")
device_name = part.device
if system == 'Linux':
# For Linux: /dev/sda1 → sda
base_device = re.sub(r'[0-9]+$', '', device_name)
elif system == 'Windows':
# For Windows, just use the drive letter
base_device = device_name[:2] if len(device_name) >= 2 else device_name
else:
# For other systems, keep as is
base_device = device_name
# Skip if we've already seen this device
if base_device in seen_devices:
continue
seen_devices.add(base_device)
try:
usage = psutil.disk_usage(part.mountpoint)
physical_drives.append({
'id': len(physical_drives),
'device': base_device,
'name': f"Disk {len(physical_drives)}",
'mountpoint': part.mountpoint,
'fstype': get_friendly_fs_type(part.fstype),
'size': usage.total,
'size_human': format_size(usage.total),
'free': usage.free
})
except:
# Skip if we can't get usage information
continue
except:
continue
# If no drives were found, try a fallback method
if not physical_drives:
try:
for part in psutil.disk_partitions(all=True):
try:
usage = psutil.disk_usage(part.mountpoint)
physical_drives.append({
'id': len(physical_drives),
'device': part.device,
'name': f"Drive {len(physical_drives)}",
'mountpoint': part.mountpoint,
'fstype': get_friendly_fs_type(part.fstype),
'size': usage.total,
'size_human': format_size(usage.total),
'free': usage.free
})
except:
continue
except:
pass
return physical_drives
def find_writable_path_for_volume(mount_path):
"""Find a writable path for a volume that may have read-only restrictions."""
system = platform.system()
# Special handling for macOS
if system == 'Darwin':
# If this is the root volume
if mount_path == '/':
# Try to find the Data volume which is always writable
data_volume = '/System/Volumes/Data'
if os.path.exists(data_volume) and os.access(data_volume, os.W_OK):
return data_volume
# Try user's home directory
home_dir = os.path.expanduser('~')
if os.access(home_dir, os.W_OK):
return home_dir
# Try temp directory
tmp_dir = tempfile.gettempdir()
if os.access(tmp_dir, os.W_OK):
return tmp_dir
# Check if this is a system volume that might be read-only
if mount_path.startswith('/System/Volumes/'):
data_volume = '/System/Volumes/Data'
if os.path.exists(data_volume) and os.access(data_volume, os.W_OK):
return data_volume
# For all other cases, return the original path
return mount_path
def get_free_space(path):
"""Get free space in bytes using psutil."""
try:
usage = psutil.disk_usage(path)
return usage.free
except:
# Fall back to statvfs
try:
st = os.statvfs(path)
return st.f_bavail * st.f_frsize
except:
return 0
def interactive_drive_selection():
"""Display interactive menu to select drive."""
global SELECTED_DISK_INFO
drives = get_physical_drives()
if not drives:
print(f"{RED}{BRIGHT}Error: No accessible drives found.{RESET}")
sys.exit(1)
print(f"{CYAN}{BRIGHT}╔════════════════════════════════════════════════════════════════╗{RESET}")
print(f"{CYAN}{BRIGHT}║ SELECT PHYSICAL DRIVE TO WIPE ║{RESET}")
print(f"{CYAN}{BRIGHT}╠════════════════════════════════════════════════════════════════╣{RESET}")
for drive in drives:
# Make sure we have valid values
size_display = drive.get('size_human', format_size(drive.get('size', 0)))
free_display = format_size(drive.get('free', 0))
fs_display = drive.get('fstype', 'Unknown')
# Set consistent box width (matches other boxes in the code)
box_width = 64 # Reduced by 1 for perfect alignment
# Print drive information with consistent box formatting
drive_id_str = str(drive['id'])
drive_name = drive['name']
drive_device = drive['device']
drive_mount = drive['mountpoint']
# Print each line with proper padding, accounting for color codes
print(f"{CYAN}{BRIGHT}║{RESET} [{drive_id_str}] {drive_name}{' ' * (box_width - 4 - len(drive_id_str) - len(drive_name))}{CYAN}{BRIGHT}║{RESET}")
print(f"{CYAN}{BRIGHT}║{RESET} Device: {GREEN}{drive_device}{RESET}{' ' * (box_width - 13 - len(drive_device))}{CYAN}{BRIGHT}║{RESET}")
print(f"{CYAN}{BRIGHT}║{RESET} Mount: {GREEN}{drive_mount}{RESET}{' ' * (box_width - 12 - len(drive_mount))}{CYAN}{BRIGHT}║{RESET}")
print(f"{CYAN}{BRIGHT}║{RESET} Type: {GREEN}{fs_display}{RESET}{' ' * (box_width - 11 - len(fs_display))}{CYAN}{BRIGHT}║{RESET}")
print(f"{CYAN}{BRIGHT}║{RESET} Size: {GREEN}{size_display}{RESET}{' ' * (box_width - 11 - len(size_display))}{CYAN}{BRIGHT}║{RESET}")
print(f"{CYAN}{BRIGHT}║{RESET} Free: {GREEN}{free_display}{RESET}{' ' * (box_width - 11 - len(free_display))}{CYAN}{BRIGHT}║{RESET}")
print(f"{CYAN}{BRIGHT}╟────────────────────────────────────────────────────────────────╢{RESET}")
print(f"{CYAN}{BRIGHT}╚════════════════════════════════════════════════════════════════╝{RESET}")
while True:
try:
print(f"{YELLOW}Enter drive number or 'q' to quit: {RESET}", end="")
choice = input().strip().lower()
if choice == 'q':
print(f"{RED}Operation aborted by user.{RESET}")
sys.exit(0)
drive_id = int(choice)
for drive in drives:
if drive['id'] == drive_id:
# Store the selected disk info globally
SELECTED_DISK_INFO = drive
# Check if this mount point needs special handling
mount_point = drive['mountpoint']
writable_path = find_writable_path_for_volume(mount_point)
if writable_path != mount_point:
print(f"{YELLOW}Note: Using {writable_path} for wiping free space on {mount_point}{RESET}")
# Ensure we have a valid free space measurement
actual_free_space = get_free_space(writable_path)
return writable_path, actual_free_space
print(f"{RED}Invalid selection. Please try again.{RESET}")
except ValueError:
print(f"{RED}Please enter a valid number or 'q'.{RESET}")
def is_path_writable(path):
"""Check if the path is writable."""
if not os.path.exists(path):
try:
os.makedirs(path, exist_ok=True)
except (OSError, PermissionError):
return False
test_file = os.path.join(path, ".write_test")
try:
with open(test_file, "w") as f:
f.write("test")
os.remove(test_file)
return True
except (OSError, PermissionError):
return False
def find_writable_path(suggested_path):
"""Find a writable path, starting with the suggested one."""
# Special handling for volumes that might be read-only
suggested_path = find_writable_path_for_volume(suggested_path)
# Check if the suggested path is writable
if is_path_writable(suggested_path):
# Get free space using psutil for consistency
try:
free_space = get_free_space(suggested_path)
return suggested_path, free_space
except:
pass
# Try common writable locations
system = platform.system()
if system == 'Darwin': # macOS
# Try Data volume first
data_volume = '/System/Volumes/Data'
if os.path.exists(data_volume) and is_path_writable(data_volume):
print(f"{YELLOW}{BRIGHT}Using {data_volume} for wiping free space{RESET}")
try:
free_space = get_free_space(data_volume)
return data_volume, free_space
except:
pass
# Try the user's home directory
home_dir = os.path.expanduser('~')
if is_path_writable(home_dir):
print(f"{YELLOW}{BRIGHT}Using {home_dir} for wiping free space{RESET}")
try:
free_space = get_free_space(home_dir)
return home_dir, free_space
except:
pass
# Try temp directory
tmp_dir = tempfile.gettempdir()
if is_path_writable(tmp_dir):
print(f"{YELLOW}{BRIGHT}Using {tmp_dir} for wiping free space{RESET}")
try:
free_space = get_free_space(tmp_dir)
return tmp_dir, free_space
except:
pass
else:
# For other systems, try home and temp
home_dir = os.path.expanduser('~')
if is_path_writable(home_dir):
print(f"{YELLOW}{BRIGHT}Using {home_dir} for wiping free space{RESET}")
try:
free_space = get_free_space(home_dir)
return home_dir, free_space
except:
pass
tmp_dir = tempfile.gettempdir()
if is_path_writable(tmp_dir):
print(f"{YELLOW}{BRIGHT}Using {tmp_dir} for wiping free space{RESET}")
try:
free_space = get_free_space(tmp_dir)
return tmp_dir, free_space
except:
pass
# Go interactive if nothing found
print(f"{YELLOW}{BRIGHT}Warning: Path '{suggested_path}' is not writable.{RESET}")
print(f"{YELLOW}{BRIGHT}Switching to interactive mode.{RESET}\n")
return interactive_drive_selection()
def format_time_human_readable(seconds, abbreviated=False):
"""
Format time in seconds to a human-readable string.
Examples:
Normal: "2 hours 15 minutes", "45 minutes 30 seconds"
Abbreviated: "2h 15m", "45m 30s"
"""
if seconds < 0:
return "0s" if abbreviated else "0 seconds"
# Round to nearest second
seconds = int(seconds)
hours, remainder = divmod(seconds, 3600)
minutes, seconds = divmod(remainder, 60)
parts = []
if abbreviated:
# Abbreviated format
if hours > 0:
parts.append(f"{hours}h")
if minutes > 0 or (hours > 0 and seconds > 0):
parts.append(f"{minutes}m")
if seconds > 0 or (not parts):
parts.append(f"{seconds}s")
else:
# Full text format
if hours > 0:
parts.append(f"{hours} hour{'s' if hours != 1 else ''}")
if minutes > 0 or (hours > 0 and seconds > 0):
parts.append(f"{minutes} minute{'s' if minutes != 1 else ''}")
if seconds > 0 or (not parts):
parts.append(f"{seconds} second{'s' if seconds != 1 else ''}")
# For very long times, limit to two most significant units
if len(parts) > 2:
parts = parts[:2]
return " ".join(parts)
def get_confirmation(message, box_style=False):
"""Get user confirmation before proceeding."""
if box_style:
# Box width (excluding borders)
box_width = 65
# Break message into multiple lines if it's too long
message_lines = []
current_line = ""
# Check if the message already contains newlines
if "\n" in message:
# Split by newlines first
for line in message.split("\n"):
words = line.split()
line_current = ""
for word in words:
if len(line_current) + len(word) + 1 <= box_width - 6: # -6 for padding (extra 2 spaces)
if line_current:
line_current += " " + word
else:
line_current = word
else:
message_lines.append(line_current)
line_current = word
if line_current:
message_lines.append(line_current)
else:
# Process as a single line
words = message.split()
for word in words:
if len(current_line) + len(word) + 1 <= box_width - 6: # -6 for padding (extra 2 spaces)
if current_line:
current_line += " " + word
else:
current_line = word
else:
message_lines.append(current_line)
current_line = word
if current_line:
message_lines.append(current_line)
# If no lines were created (e.g., empty message), add an empty line
if not message_lines:
message_lines = [""]
# Print the confirmation box
print(f"{YELLOW}{BRIGHT}╔═{'═' * box_width}╗{RESET}")
print(f"{YELLOW}{BRIGHT}║ CONFIRMATION REQUIRED{' ' * (box_width - 21)}║{RESET}")
print(f"{YELLOW}{BRIGHT}╠═{'═' * box_width}╣{RESET}")
for line in message_lines:
# Add +2 to the padding for better alignment
padding = box_width - len(line) - 2 + 2 # -2 for initial space and border, +2 for extra padding
print(f"{YELLOW}{BRIGHT}║{RESET} {line}{' ' * padding}{YELLOW}{BRIGHT}║{RESET}")
print(f"{YELLOW}{BRIGHT}╚═{'═' * box_width}╝{RESET}")
print(f"{YELLOW}Please confirm (y/n, default=n): {RESET}", end="")
else:
print(f"{YELLOW}{BRIGHT}{message} (y/n, default=n): {RESET}", end="")
response = input().strip().lower()
return response in ["y", "yes"]
def wipe_free_space(root='/', passes=3, block_size=1048576, verify=False, pattern='all', no_confirm=False):
# Banner is now shown only at program start, not here
# Initialize free_space to 0
free_space = 0
# If root is '/' (default), go straight to interactive mode
if root == '/':
root, free_space = interactive_drive_selection()
else:
# Ensure the target path is writable
original_root = root
root, free_space = find_writable_path(root)
if root is None:
print(f"{RED}{BRIGHT}Error: Could not find a writable location. Please run with sudo or specify a writable path.{RESET}")
sys.exit(1)
# Ask if the user wants to format the entire device instead
device_path = None
if platform.system() == 'Darwin': # macOS
# Try to extract disk identifier from the mount point
try:
disk_info = subprocess.check_output(['df', '-h', root], stderr=subprocess.STDOUT).decode('utf-8')
lines = disk_info.strip().split('\n')
if len(lines) > 1:
device_path = lines[1].split()[0] # Get the device path from df output
except:
pass
elif platform.system() == 'Linux':
# Try to get the device from mount point
try:
disk_info = subprocess.check_output(['df', '-h', root], stderr=subprocess.STDOUT).decode('utf-8')
lines = disk_info.strip().split('\n')
if len(lines) > 1:
device_path = lines[1].split()[0] # Get the device path from df output
except:
pass
elif platform.system() == 'Windows':
# Try to get the device from mount point
try:
# Get volume information for the selected path
ps_cmd = f'Get-WmiObject -Query "SELECT * FROM Win32_Volume WHERE DriveLetter = \'{root[:2]}\'"'
vol_info = subprocess.check_output(['powershell', '-Command', ps_cmd], stderr=subprocess.STDOUT).decode('utf-8')
# Extract the device ID (e.g., \\.\PHYSICALDRIVE1)
device_match = re.search(r'DeviceID\s*:\s*(.+)', vol_info)
if device_match:
device_id = device_match.group(1).strip()
# Extract the number from the device ID
disk_num_match = re.search(r'PHYSICALDRIVE(\d+)', device_id)
if disk_num_match:
device_path = f"\\\\.\\PhysicalDrive{disk_num_match.group(1)}"
except:
pass
# If we found a device path, ask if they want to format it
if device_path:
format_prompt = f"Would you like to format the entire device ({device_path})\ninstead of just wiping free space?"
if get_confirmation(format_prompt, box_style=True):
print(f"{YELLOW}Switching to full disk format mode...{RESET}")
# Ask for filesystem type
print(f"{CYAN}{BRIGHT}Select filesystem type:{RESET}")
fs_options = ['exfat', 'fat32', 'ntfs']
# Add platform-specific filesystem options
if platform.system() == 'Darwin':
fs_options.extend(['apfs', 'hfs+'])
elif platform.system() == 'Linux':
fs_options.extend(['ext4', 'ext3', 'ext2'])
for i, fs in enumerate(fs_options):
print(f"{CYAN}[{i+1}] {fs.upper()}{RESET}")
# Get user selection
filesystem = 'exfat' # Default
try:
print(f"{YELLOW}Enter filesystem number (default: exFAT): {RESET}", end="")
choice = input().strip()
if choice:
fs_idx = int(choice) - 1
if 0 <= fs_idx < len(fs_options):
filesystem = fs_options[fs_idx]
except:
pass
# Ask for volume label
print(f"{YELLOW}Enter volume label (optional, press Enter to skip): {RESET}", end="")
label = input().strip() or None
# Call format_disk with the device path
format_disk(device_path, filesystem, label, no_confirm, pattern=pattern, verify=verify)
return # Exit this function
# If free_space is still 0, try to get it one more time to be sure
if free_space == 0:
free_space = get_free_space(root)
# Format for display only once
free_space_display = format_size(free_space)
fname = os.path.join(root, '.dwipe_free_space.tmp')
# Set up signal handlers and cleanup functions for the temp file
temp_files = [fname]
# Create a container for the progress bar reference so it can be modified in closures
progress_bar_container = {'instance': None}
def cleanup_temp_files():
"""Clean up any temporary files created during the wiping process."""
for temp_file in temp_files:
try:
if os.path.exists(temp_file):
os.remove(temp_file)
print(f"\n{GREEN}Cleaned up temporary file: {temp_file}{RESET}")
except Exception as e:
print(f"\n{YELLOW}Warning: Could not remove temporary file {temp_file}: {e}{RESET}")
def signal_handler(sig, frame):
"""Handle interrupt signals (CTRL+C)."""
# Disable progress bar updates before closing
if progress_bar_container['instance'] is not None:
progress_bar = progress_bar_container['instance']
progress_bar.disable = True # Disable any further output
progress_bar_container['instance'] = None # Remove reference
# Move to a new line to avoid overwriting the last message
print(f"\n\n{YELLOW}Operation interrupted by user. Cleaning up...{RESET}")
cleanup_temp_files()
print(f"{RED}Wiping operation canceled.{RESET}")
sys.exit(130) # 130 is the standard exit code for SIGINT
# Register cleanup functions
atexit.register(cleanup_temp_files)
signal.signal(signal.SIGINT, signal_handler)
# Enhanced status display
box_width = 65
print(f"{CYAN}{BRIGHT}╔═{'═' * box_width}╗{RESET}")
print(f"{CYAN}{BRIGHT}║ SECURE FREE SPACE WIPING{' ' * (box_width - 24)}║{RESET}")
print(f"{CYAN}{BRIGHT}╠═{'═' * box_width}╣{RESET}")
# Standardize padding calculations by adding consistent offsets
print(f"{CYAN}{BRIGHT}║{RESET} Target: {GREEN}{root}{' ' * (box_width - 9 - len(root) + 1)}{CYAN}{BRIGHT}║{RESET}")
print(f"{CYAN}{BRIGHT}║{RESET} Free space: {GREEN}{free_space_display}{' ' * (box_width - 13 - len(free_space_display) + 1)}{CYAN}{BRIGHT}║{RESET}")
print(f"{CYAN}{BRIGHT}║{RESET} Passes: {GREEN}{passes}{' ' * (box_width - 9 - len(str(passes)) + 1)}{CYAN}{BRIGHT}║{RESET}")
print(f"{CYAN}{BRIGHT}║{RESET} Block size: {GREEN}{format_size(block_size)}{' ' * (box_width - 13 - len(format_size(block_size)) + 1)}{CYAN}{BRIGHT}║{RESET}")
print(f"{CYAN}{BRIGHT}║{RESET} Pattern: {GREEN}{pattern}{' ' * (box_width - 10 - len(pattern) + 1)}{CYAN}{BRIGHT}║{RESET}")
print(f"{CYAN}{BRIGHT}╚═{'═' * box_width}╝{RESET}\n")
# Get confirmation before starting
if not no_confirm:
confirmation_msg = f"About to wipe {free_space_display} of free space on {root}.\nContinue?"
if not get_confirmation(confirmation_msg, box_style=True):
print(f"{RED}Operation aborted by user.{RESET}")
sys.exit(0)
# Start time for overall ETA calculation
overall_start_time = time.time()
try:
for p in range(passes):
if pattern == 'zeroes':
mode = 'zeroes'
elif pattern == 'ones':
mode = 'ones'
elif pattern == 'random':
mode = 'random'
elif pattern == 'dicks':
mode = 'dicks'
elif pattern == 'haha':
mode = 'haha'
else: # 'all' - default with first pass being random
if p == 0:
mode = 'random'
else:
mode = {1: 'zeroes', 2: 'ones'}.get(p % 3, 'random')
pass_color = [GREEN, YELLOW, CYAN, MAGENTA, BLUE][p % 5]
print(f"{pass_color}Pass {p+1}/{passes}: filling free space with {mode}{RESET}")
# Calculate and display overall ETA if we've already completed at least one pass
if p > 0:
elapsed_time = time.time() - overall_start_time
avg_time_per_pass = elapsed_time / p
remaining_passes = passes - p
overall_eta_seconds = avg_time_per_pass * remaining_passes
# Format the overall ETA in a readable format (non-abbreviated)
overall_eta = format_time_human_readable(overall_eta_seconds, abbreviated=False)
overall_eta_time = time.strftime("%I:%M %p", time.localtime(time.time() + overall_eta_seconds))
print(f"{YELLOW}Overall ETA: {overall_eta} (complete at approximately {overall_eta_time}){RESET}")
# Initialize variables for custom progress tracking
pass_start_time = time.time()
written = 0
last_display_time = 0
time_line = ""
# First print the time line that we'll update in place
time_line = "Elapsed: 00:00:00 • Remaining: calculating..."
print(time_line)
# Create a clean progress bar without time information in the description
progress_format = '{percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt}'
progress_bar = tqdm(total=free_space, unit='B', unit_scale=True,
unit_divisor=1024,
bar_format=progress_format,
leave=True)
# Make the progress bar accessible to the signal handler
progress_bar_container['instance'] = progress_bar
try:
with open(fname, 'wb') as f:
while True:
if mode == 'random':
chunk = os.urandom(block_size)
elif mode == 'ones':
chunk = b'\xFF' * block_size
elif mode == 'dicks':
# Create a pattern of "3===D" repeated
pattern_bytes = b'3===D'
chunk = (pattern_bytes * (block_size // len(pattern_bytes) + 1))[:block_size]
elif mode == 'haha':
# Create a pattern of "haha-" repeated
pattern_bytes = b'haha-'
chunk = (pattern_bytes * (block_size // len(pattern_bytes) + 1))[:block_size]
else: # zeroes
chunk = b'\x00' * block_size
f.write(chunk)
written += block_size
# Update display periodically
current_time = time.time()
if current_time - last_display_time >= 0.5: # Update twice per second
# Calculate elapsed and remaining time
elapsed_seconds = current_time - pass_start_time
# Format elapsed time in a more human-readable format (abbreviated)
elapsed_str = format_time_human_readable(elapsed_seconds, abbreviated=True)
# Calculate remaining time based on current speed
if written > 0:
bytes_per_second = written / elapsed_seconds
remaining_seconds = (free_space - written) / bytes_per_second if bytes_per_second > 0 else 0
# Use abbreviated format for remaining time too
remaining_str = format_time_human_readable(remaining_seconds, abbreviated=True)
else:
remaining_str = "calculating..."
# Create new time line
new_time_line = f"Elapsed: {elapsed_str} • Remaining: {remaining_str}"
# Only update if the line has changed
if new_time_line != time_line:
# Move cursor up one line and clear it
sys.stdout.write("\033[F\033[K")
sys.stdout.write(new_time_line + "\n")
sys.stdout.flush()
time_line = new_time_line
last_display_time = current_time
# Update the progress
progress_bar.update(block_size)
# Occasional flush
if written % (block_size * 100) == 0:
f.flush()
except OSError as e:
if e.errno not in (errno.ENOSPC, errno.EFBIG):
print(f"\n{YELLOW}Error: {e}{RESET}", file=sys.stderr)
# Break out of the loop if disk is full or another error occurred
pass
finally:
# Close the progress bar
progress_bar.close()
# Force sync and flush before removing
try:
if 'f' in locals() and hasattr(f, 'fileno'):
os.fsync(f.fileno())
except Exception:
pass
try:
if os.path.exists(fname):