forked from simonsj/fdupes-jody
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjdupes.c
2094 lines (1838 loc) · 65.9 KB
/
jdupes.c
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
/* jdupes (C) 2015-2017 Jody Bruchon <[email protected]>
Derived from fdupes (C) 1999-2017 Adrian Lopez
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <dirent.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#ifndef OMIT_GETOPT_LONG
#include <getopt.h>
#endif
#include <string.h>
#include <errno.h>
#include <libgen.h>
#include <sys/time.h>
#include "jdupes.h"
#include "string_malloc.h"
#include "jody_hash.h"
#include "jody_sort.h"
#include "jody_win_unicode.h"
#include "jody_cacheinfo.h"
#include "version.h"
/* Headers for post-scanning actions */
#include "act_deletefiles.h"
#include "act_dedupefiles.h"
#include "act_linkfiles.h"
#include "act_printmatches.h"
#include "act_summarize.h"
/* Detect Windows and modify as needed */
#if defined _WIN32 || defined __CYGWIN__
const char dir_sep = '\\';
#ifdef UNICODE
const wchar_t *FILE_MODE_RO = L"rbS";
#else
const char *FILE_MODE_RO = "rbS";
#endif /* UNICODE */
#else /* Not Windows */
const char *FILE_MODE_RO = "rb";
const char dir_sep = '/';
#ifdef UNICODE
#error Do not define UNICODE on non-Windows platforms.
#undef UNICODE
#endif
#endif /* _WIN32 || __CYGWIN__ */
/* Windows + Unicode compilation */
#ifdef UNICODE
wchar_t wname[PATH_MAX];
wchar_t wname2[PATH_MAX];
wchar_t wstr[PATH_MAX];
int out_mode = _O_TEXT;
int err_mode = _O_TEXT;
#define M2W(a,b) MultiByteToWideChar(CP_UTF8, 0, a, -1, (LPWSTR)b, PATH_MAX)
#define W2M(a,b) WideCharToMultiByte(CP_UTF8, 0, a, -1, (LPSTR)b, PATH_MAX, NULL, NULL)
#endif /* UNICODE */
#ifndef NO_SYMLINKS
#include "jody_paths.h"
#endif
/* Behavior modification flags */
uint_fast32_t flags = 0;
static const char *program_name;
/* This gets used in many functions */
#ifdef ON_WINDOWS
struct winstat ws;
#else
struct stat s;
#endif
/* Larger chunk size makes large files process faster but uses more RAM */
#ifndef CHUNK_SIZE
#define CHUNK_SIZE 32768
#endif
#ifndef PARTIAL_HASH_SIZE
#define PARTIAL_HASH_SIZE 4096
#endif
static size_t auto_chunk_size;
/* Maximum path buffer size to use; must be large enough for a path plus
* any work that might be done to the array it's stored in. PATH_MAX is
* not always true. Read this article on the false promises of PATH_MAX:
* http://insanecoding.blogspot.com/2007/11/pathmax-simply-isnt.html
* Windows + Unicode needs a lot more space than UTF-8 in Linux/Mac OS X
*/
#ifndef PATHBUF_SIZE
#define PATHBUF_SIZE 4096
#endif
/* Refuse to build if PATHBUF_SIZE is too small */
#if PATHBUF_SIZE < PATH_MAX
#error "PATHBUF_SIZE can't be less than PATH_MAX"
#endif
#ifndef INITIAL_DEPTH_THRESHOLD
#define INITIAL_DEPTH_THRESHOLD 8
#endif
/* For interactive deletion input */
#define INPUT_SIZE 512
/* Assemble extension string from compile-time options */
static const char *extensions[] = {
#ifdef ON_WINDOWS
"windows",
#endif
#ifdef UNICODE
"unicode",
#endif
#ifdef OMIT_GETOPT_LONG
"nolong",
#endif
#ifdef __FAST_MATH__
"fastmath",
#endif
#ifdef DEBUG
"debug",
#endif
#ifdef LOUD_DEBUG
"loud",
#endif
#ifdef ENABLE_BTRFS
"btrfs",
#endif
#ifdef LOW_MEMORY
"lowmem",
#endif
#ifdef SMA_PAGE_SIZE
"smapage",
#endif
#if JODY_HASH_WIDTH == 32
"hash32",
#endif
#if JODY_HASH_WIDTH == 16
"hash16",
#endif
#ifdef NO_PERMS
"noperm",
#endif
#ifdef NO_SYMLINKS
"nosymlink",
#endif
#ifdef USE_TREE_REBALANCE
"rebal",
#endif
#ifdef CONSIDER_IMBALANCE
"ci",
#endif
#ifdef BALANCE_THRESHOLD
"bt",
#endif
NULL
};
/* Tree to track each directory traversed */
struct travdone {
struct travdone *left;
struct travdone *right;
jdupes_ino_t inode;
dev_t device;
};
static struct travdone *travdone_head = NULL;
/* Exclusion tree head and static tag list */
struct exclude *exclude_head = NULL;
const struct exclude_tags exclude_tags[] = {
{ "dir", X_DIR },
{ "size+", X_SIZE_GT },
{ "size+=", X_SIZE_GTEQ },
{ "size-=", X_SIZE_LTEQ },
{ "size-", X_SIZE_LT },
{ "size=", X_SIZE_EQ },
{ NULL, 0 },
};
/* Required for progress indicator code */
static uintmax_t filecount = 0;
static uintmax_t progress = 0, dir_progress = 0, dupecount = 0;
/* Number of read loops before checking progress indicator */
#define CHECK_MINIMUM 256
/* Hash/compare performance statistics (debug mode) */
#ifdef DEBUG
static unsigned int small_file = 0, partial_hash = 0, partial_elim = 0;
static unsigned int full_hash = 0, partial_to_full = 0, hash_fail = 0;
static uintmax_t comparisons = 0;
static unsigned int left_branch = 0, right_branch = 0;
#ifdef ON_WINDOWS
#ifndef NO_HARDLINKS
static unsigned int hll_exclude = 0;
#endif
#endif
#endif /* DEBUG */
#ifdef TREE_DEPTH_STATS
static unsigned int tree_depth = 0;
static unsigned int max_depth = 0;
#endif
/* File tree head */
static filetree_t *checktree = NULL;
/* Directory parameter position counter */
static unsigned int user_dir_count = 1;
/* registerfile() direction options */
enum tree_direction { NONE, LEFT, RIGHT };
/* Sort order reversal */
static int sort_direction = 1;
/* Signal handler */
static int interrupt = 0;
/* Progress indicator time */
struct timeval time1, time2;
/***** End definitions, begin code *****/
/* Catch CTRL-C and either notify or terminate */
void sighandler(const int signum)
{
(void)signum;
if (interrupt || !ISFLAG(flags, F_SOFTABORT)) {
fprintf(stderr, "\n");
string_malloc_destroy();
exit(EXIT_FAILURE);
}
interrupt = 1;
return;
}
/* Out of memory */
extern void oom(const char * const restrict msg)
{
fprintf(stderr, "\nout of memory: %s\n", msg);
string_malloc_destroy();
exit(EXIT_FAILURE);
}
/* Null pointer failure */
extern void nullptr(const char * restrict func)
{
static const char n[] = "(NULL)";
if (func == NULL) func = n;
fprintf(stderr, "\ninternal error: NULL pointer passed to %s\n", func);
string_malloc_destroy();
exit(EXIT_FAILURE);
}
/* Compare two jody_hashes like memcmp() */
#define HASH_COMPARE(a,b) ((a > b) ? 1:((a == b) ? 0:-1))
static inline char **cloneargs(const int argc, char **argv)
{
static int x;
static char **args;
args = (char **)string_malloc(sizeof(char *) * (unsigned int)argc);
if (args == NULL) oom("cloneargs() start");
for (x = 0; x < argc; x++) {
args[x] = (char *)string_malloc(strlen(argv[x]) + 1);
if (args[x] == NULL) oom("cloneargs() loop");
strcpy(args[x], argv[x]);
}
return args;
}
static int findarg(const char * const arg, const int start,
const int argc, char **argv)
{
int x;
for (x = start; x < argc; x++)
if (strcmp(argv[x], arg) == 0)
return x;
return x;
}
/* Find the first non-option argument after specified option. */
static int nonoptafter(const char *option, const int argc,
char **oldargv, char **newargv)
{
int x;
int targetind;
int testind;
int startat = 1;
targetind = findarg(option, 1, argc, oldargv);
for (x = optind; x < argc; x++) {
testind = findarg(newargv[x], startat, argc, oldargv);
if (testind > targetind) return x;
else startat = testind;
}
return x;
}
/* Update progress indicator if requested */
static void update_progress(const char * const restrict msg, const int file_percent)
{
static int did_fpct = 0;
/* The caller should be doing this anyway...but don't trust that they did */
if (ISFLAG(flags, F_HIDEPROGRESS)) return;
gettimeofday(&time2, NULL);
if (progress == 0 || time2.tv_sec > time1.tv_sec) {
fprintf(stderr, "\rProgress [%" PRIuMAX "/%" PRIuMAX ", %" PRIuMAX " pairs matched] %" PRIuMAX "%%",
progress, filecount, dupecount, (progress * 100) / filecount);
if (file_percent > -1 && msg != NULL) {
fprintf(stderr, " (%s: %d%%) ", msg, file_percent);
did_fpct = 1;
} else if (did_fpct != 0) {
fprintf(stderr, " ");
did_fpct = 0;
}
fflush(stderr);
}
time1.tv_sec = time2.tv_sec;
return;
}
/* Check file's stat() info to make sure nothing has changed
* Returns 1 if changed, 0 if not changed, negative if error */
extern int file_has_changed(file_t * const restrict file)
{
if (file == NULL || file->d_name == NULL) nullptr("file_has_changed()");
LOUD(fprintf(stderr, "file_has_changed('%s')\n", file->d_name);)
if (!ISFLAG(file->flags, F_VALID_STAT)) return -66;
#ifdef ON_WINDOWS
int i;
if ((i = win_stat(file->d_name, &ws)) != 0) return i;
if (file->inode != ws.inode) return 1;
if (file->size != ws.size) return 1;
if (file->device != ws.device) return 1;
if (file->mtime != ws.mtime) return 1;
if (file->mode != ws.mode) return 1;
#else
if (stat(file->d_name, &s) != 0) return -2;
if (file->inode != s.st_ino) return 1;
if (file->size != s.st_size) return 1;
if (file->device != s.st_dev) return 1;
if (file->mtime != s.st_mtime) return 1;
if (file->mode != s.st_mode) return 1;
#ifndef NO_PERMS
if (file->uid != s.st_uid) return 1;
if (file->gid != s.st_gid) return 1;
#endif
#ifndef NO_SYMLINKS
if (lstat(file->d_name, &s) != 0) return -3;
if ((S_ISLNK(s.st_mode) > 0) ^ ISFLAG(file->flags, F_IS_SYMLINK)) return 1;
#endif
#endif /* ON_WINDOWS */
return 0;
}
extern inline int getfilestats(file_t * const restrict file)
{
if (file == NULL || file->d_name == NULL) nullptr("getfilestats()");
LOUD(fprintf(stderr, "getfilestats('%s')\n", file->d_name);)
/* Don't stat the same file more than once */
if (ISFLAG(file->flags, F_VALID_STAT)) return 0;
SETFLAG(file->flags, F_VALID_STAT);
#ifdef ON_WINDOWS
if (win_stat(file->d_name, &ws) != 0) return -1;
file->inode = ws.inode;
file->size = ws.size;
file->device = ws.device;
file->mtime = ws.mtime;
file->mode = ws.mode;
#ifndef NO_HARDLINKS
file->nlink = ws.nlink;
#endif /* NO_HARDLINKS */
#else
if (stat(file->d_name, &s) != 0) return -1;
file->inode = s.st_ino;
file->size = s.st_size;
file->device = s.st_dev;
file->mtime = s.st_mtime;
file->mode = s.st_mode;
file->nlink = s.st_nlink;
#ifndef NO_PERMS
file->uid = s.st_uid;
file->gid = s.st_gid;
#endif
#ifndef NO_SYMLINKS
if (lstat(file->d_name, &s) != 0) return -1;
if (S_ISLNK(s.st_mode) > 0) SETFLAG(file->flags, F_IS_SYMLINK);
#endif
#endif /* ON_WINDOWS */
return 0;
}
static void add_exclude(const char *option)
{
char *opt, *p;
struct exclude *excl = exclude_head;
const struct exclude_tags *tags = exclude_tags;
const struct size_suffix *ss = size_suffix;
if (option == NULL) nullptr("add_exclude()");
LOUD(fprintf(stderr, "add_exclude '%s'\n", option);)
opt = string_malloc(strlen(option) + 1);
if (opt == NULL) oom("add_exclude option");
strcpy(opt, option);
p = opt;
while (*p != ':' && *p != '\0') p++;
/* Split tag string into *opt (tag) and *p (value) */
if (*p == ':') {
*p = '\0';
p++;
}
while (tags->tag != NULL && strcmp(tags->tag, opt) != 0) tags++;
if (tags->tag == NULL) goto bad_tag;
/* Check for a tag that requires a value */
if (tags->flags & XX_EXCL_DATA && *p == '\0') goto spec_missing;
/* *p is now at the value, NOT the tag string! */
if (exclude_head != NULL) {
/* Add to end of exclusion stack if head is present */
while (excl->next != NULL) excl = excl->next;
excl->next = string_malloc(sizeof(struct exclude) + strlen(p));
if (excl->next == NULL) oom("add_exclude alloc");
excl = excl->next;
} else {
/* Allocate exclude_head if no exclusions exist yet */
exclude_head = string_malloc(sizeof(struct exclude) + strlen(p));
if (exclude_head == NULL) oom("add_exclude alloc");
excl = exclude_head;
}
/* Set tag value from predefined tag array */
excl->flags = tags->flags;
/* Initialize the new exclude element */
excl->next = NULL;
if (excl->flags & XX_EXCL_OFFSET) {
/* Exclude uses a number; handle it with possible suffixes */
*(excl->param) = '\0';
/* Get base size */
if (*p < '0' || *p > '9') goto bad_size_suffix;
excl->size = strtoll(p, &p, 10);
/* Handle suffix, if any */
if (*p != '\0') {
while (ss->suffix != NULL && strcasecmp(ss->suffix, p) != 0) ss++;
if (ss->suffix == NULL) goto bad_size_suffix;
excl->size *= ss->multiplier;
}
} else {
/* Exclude uses string data; just copy it */
excl->size = 0;
strcpy(excl->param, p);
}
LOUD(fprintf(stderr, "Added exclude: tag '%s', data '%s', size %lu, flags %d\n", opt, excl->param, excl->size, excl->flags);)
string_free(opt);
return;
spec_missing:
fprintf(stderr, "Exclude spec missing or invalid: -X spec:data\n");
exit(EXIT_FAILURE);
bad_tag:
fprintf(stderr, "Invalid exclusion tag was specified\n");
exit(EXIT_FAILURE);
bad_size_suffix:
fprintf(stderr, "Invalid -X size suffix specified; use B or KMGTPE[i][B]\n");
exit(EXIT_FAILURE);
}
extern int getdirstats(const char * const restrict name,
jdupes_ino_t * const restrict inode, dev_t * const restrict dev)
{
if (name == NULL || inode == NULL || dev == NULL) nullptr("getdirstats");
LOUD(fprintf(stderr, "getdirstats('%s', %p, %p)\n", name, (void *)inode, (void *)dev);)
#ifdef ON_WINDOWS
if (win_stat(name, &ws) != 0) return -1;
*inode = ws.inode;
*dev = ws.device;
#else
if (stat(name, &s) != 0) return -1;
*inode = s.st_ino;
*dev = s.st_dev;
#endif /* ON_WINDOWS */
return 0;
}
/* Check a pair of files for match exclusion conditions
* Returns:
* 0 if all condition checks pass
* -1 or 1 on compare result less/more
* -2 on an absolute exclusion condition met
* 2 on an absolute match condition met */
extern int check_conditions(const file_t * const restrict file1, const file_t * const restrict file2)
{
if (file1 == NULL || file2 == NULL || file1->d_name == NULL || file2->d_name == NULL) nullptr("check_conditions()");
LOUD(fprintf(stderr, "check_conditions('%s', '%s')\n", file1->d_name, file2->d_name);)
/* Exclude based on -I/--isolate */
if (ISFLAG(flags, F_ISOLATE) && (file1->user_order == file2->user_order)) {
LOUD(fprintf(stderr, "check_conditions: files ignored: parameter isolation\n"));
return -1;
}
/* Exclude based on -1/--one-file-system */
if (ISFLAG(flags, F_ONEFS) && (file1->device != file2->device)) {
LOUD(fprintf(stderr, "check_conditions: files ignored: not on same filesystem\n"));
return -1;
}
/* Exclude files by permissions if requested */
if (ISFLAG(flags, F_PERMISSIONS) &&
(file1->mode != file2->mode
#ifndef NO_PERMS
|| file1->uid != file2->uid
|| file1->gid != file2->gid
#endif
)) {
return -1;
LOUD(fprintf(stderr, "check_conditions: no match: permissions/ownership differ (-p on)\n"));
}
/* Hard link and symlink + '-s' check */
#ifndef NO_HARDLINKS
if ((file1->inode == file2->inode) && (file1->device == file2->device)) {
if (ISFLAG(flags, F_CONSIDERHARDLINKS)) {
LOUD(fprintf(stderr, "check_conditions: files match: hard/soft linked (-H on)\n"));
return 2;
} else {
LOUD(fprintf(stderr, "check_conditions: files ignored: hard/soft linked (-H off)\n"));
return -2;
}
}
#endif
/* Exclude files that are not the same size */
if (file1->size > file2->size) {
LOUD(fprintf(stderr, "check_conditions: no match: size of file1 > file2 (%" PRIdMAX " > %" PRIdMAX ")\n",
(intmax_t)file1->size, (intmax_t)file2->size));
return -1;
}
if (file1->size < file2->size) {
LOUD(fprintf(stderr, "check_conditions: no match: size of file1 < file2 (%" PRIdMAX " < %"PRIdMAX ")\n",
(intmax_t)file1->size, (intmax_t)file2->size));
return 1;
}
/* Fall through: all checks passed */
LOUD(fprintf(stderr, "check_conditions: all condition checks passed\n"));
return 0;
}
/* Create a new traversal check object and initialize its values */
static struct travdone *travdone_alloc(const jdupes_ino_t inode, const dev_t device)
{
struct travdone *trav;
LOUD(fprintf(stderr, "travdone_alloc(%" PRIdMAX ", %" PRIdMAX ")\n", (intmax_t)inode, (intmax_t)device);)
trav = (struct travdone *)string_malloc(sizeof(struct travdone));
if (trav == NULL) {
LOUD(fprintf(stderr, "travdone_alloc: malloc failed\n");)
return NULL;
}
trav->left = NULL;
trav->right = NULL;
trav->inode = inode;
trav->device = device;
LOUD(fprintf(stderr, "travdone_alloc returned %p\n", (void *)trav);)
return trav;
}
/* Load a directory's contents into the file tree, recursing as needed */
static void grokdir(const char * const restrict dir,
file_t * restrict * const restrict filelistp,
int recurse)
{
file_t * restrict newfile;
#ifndef NO_SYMLINKS
static struct stat linfo;
#endif
struct dirent *dirinfo;
static int grokdir_level = 0;
static char tempname[PATHBUF_SIZE * 2];
size_t dirlen;
struct travdone *traverse;
struct exclude *excl;
int excluded;
jdupes_ino_t inode, n_inode;
dev_t device, n_device;
#ifdef UNICODE
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
char *p;
#else
DIR *cd;
#endif
if (dir == NULL || filelistp == NULL) nullptr("grokdir()");
LOUD(fprintf(stderr, "grokdir: scanning '%s' (order %d)\n", dir, user_dir_count));
/* Double traversal prevention tree */
if (getdirstats(dir, &inode, &device) != 0) goto error_travdone;
if (travdone_head == NULL) {
travdone_head = travdone_alloc(inode, device);
if (travdone_head == NULL) goto error_travdone;
} else {
traverse = travdone_head;
while (1) {
if (traverse == NULL) nullptr("grokdir() traverse");
/* Don't re-traverse directories we've already seen */
if (inode == traverse->inode && device == traverse->device) {
LOUD(fprintf(stderr, "already seen dir '%s', skipping\n", dir);)
return;
} else if (inode > traverse->inode || (inode == traverse->inode && device > traverse->device)) {
/* Traverse right */
if (traverse->right == NULL) {
LOUD(fprintf(stderr, "traverse dir right '%s'\n", dir);)
traverse->right = travdone_alloc(inode, device);
if (traverse->right == NULL) goto error_travdone;
break;
}
traverse = traverse->right;
continue;
} else {
/* Traverse left */
if (traverse->left == NULL) {
LOUD(fprintf(stderr, "traverse dir left '%s'\n", dir);)
traverse->left = travdone_alloc(inode, device);
if (traverse->left == NULL) goto error_travdone;
break;
}
traverse = traverse->left;
continue;
}
}
}
dir_progress++;
grokdir_level++;
#ifdef UNICODE
/* Windows requires \* at the end of directory names */
strncpy(tempname, dir, PATHBUF_SIZE * 2);
dirlen = strlen(tempname) - 1;
p = tempname + dirlen;
if (*p == '/' || *p == '\\') *p = '\0';
strncat(tempname, "\\*", PATHBUF_SIZE * 2);
if (!M2W(tempname, wname)) goto error_cd;
LOUD(fprintf(stderr, "FindFirstFile: %s\n", dir));
hFind = FindFirstFile((LPCWSTR)wname, &ffd);
if (hFind == INVALID_HANDLE_VALUE) { fprintf(stderr, "\nfile handle bad\n"); goto error_cd; }
LOUD(fprintf(stderr, "Loop start\n"));
do {
char * restrict tp = tempname;
size_t d_name_len;
/* Get necessary length and allocate d_name */
dirinfo = (struct dirent *)string_malloc(sizeof(struct dirent));
if (!W2M(ffd.cFileName, dirinfo->d_name)) continue;
#else
cd = opendir(dir);
if (!cd) goto error_cd;
while ((dirinfo = readdir(cd)) != NULL) {
char * restrict tp = tempname;
size_t d_name_len;
#endif /* UNICODE */
LOUD(fprintf(stderr, "grokdir: readdir: '%s'\n", dirinfo->d_name));
if (strcmp(dirinfo->d_name, ".") && strcmp(dirinfo->d_name, "..")) {
if (!ISFLAG(flags, F_HIDEPROGRESS)) {
gettimeofday(&time2, NULL);
if (progress == 0 || time2.tv_sec > time1.tv_sec) {
fprintf(stderr, "\rScanning: %" PRIuMAX " files, %" PRIuMAX " dirs (in %u specified)",
progress, dir_progress, user_dir_count);
}
time1.tv_sec = time2.tv_sec;
}
/* Assemble the file's full path name, optimized to avoid strcat() */
dirlen = strlen(dir);
d_name_len = strlen(dirinfo->d_name);
memcpy(tp, dir, dirlen+1);
if (dirlen != 0 && tp[dirlen-1] != dir_sep) {
tp[dirlen] = dir_sep;
dirlen++;
}
if (dirlen + d_name_len + 1 >= (PATHBUF_SIZE * 2)) goto error_overflow;
tp += dirlen;
memcpy(tp, dirinfo->d_name, d_name_len);
tp += d_name_len;
*tp = '\0';
d_name_len++;
/* Allocate the file_t and the d_name entries */
newfile = (file_t *)string_malloc(sizeof(file_t));
if (!newfile) oom("grokdir() file structure");
memset(newfile, 0, sizeof(file_t));
newfile->d_name = (char *)string_malloc(dirlen + d_name_len + 2);
if (!newfile->d_name) oom("grokdir() filename");
newfile->next = *filelistp;
newfile->user_order = user_dir_count;
newfile->size = -1;
newfile->duplicates = NULL;
tp = tempname;
memcpy(newfile->d_name, tp, dirlen + d_name_len);
if (ISFLAG(flags, F_EXCLUDEHIDDEN)) {
/* WARNING: Re-used tp here to eliminate a strdup() */
strncpy(tp, newfile->d_name, dirlen + d_name_len);
tp = basename(tp);
if (tp[0] == '.' && strcmp(tp, ".") && strcmp(tp, "..")) {
LOUD(fprintf(stderr, "grokdir: excluding hidden file (-A on)\n"));
string_free(newfile->d_name);
string_free(newfile);
continue;
}
}
/* Get file information and check for validity */
const int i = getfilestats(newfile);
if (i || newfile->size == -1) {
LOUD(fprintf(stderr, "grokdir: excluding due to bad stat()\n"));
string_free(newfile->d_name);
string_free(newfile);
continue;
}
if (!S_ISDIR(newfile->mode)) {
/* Exclude zero-length files if requested */
if (newfile->size == 0 && !ISFLAG(flags, F_INCLUDEEMPTY)) {
LOUD(fprintf(stderr, "grokdir: excluding zero-length empty file (-z not set)\n"));
string_free(newfile->d_name);
string_free(newfile);
continue;
}
/* Exclude files based on exclusion stack size specs */
excl = exclude_head;
excluded = 0;
while (excl != NULL) {
uint32_t sflag = excl->flags & XX_EXCL_SIZE;
if (
((sflag == X_SIZE_EQ) && (newfile->size != excl->size)) ||
((sflag == X_SIZE_LTEQ) && (newfile->size <= excl->size)) ||
((sflag == X_SIZE_GTEQ) && (newfile->size >= excl->size)) ||
((sflag == X_SIZE_GT) && (newfile->size > excl->size)) ||
((sflag == X_SIZE_LT) && (newfile->size < excl->size))
) excluded = 1;
excl = excl->next;
}
if (excluded) {
LOUD(fprintf(stderr, "grokdir: excluding based on xsize limit (-x set)\n"));
string_free(newfile->d_name);
string_free(newfile);
continue;
}
}
#ifndef NO_SYMLINKS
/* Get lstat() information */
if (lstat(newfile->d_name, &linfo) == -1) {
LOUD(fprintf(stderr, "grokdir: excluding due to bad lstat()\n"));
string_free(newfile->d_name);
string_free(newfile);
continue;
}
#endif
/* Windows has a 1023 (+1) hard link limit. If we're hard linking,
* ignore all files that have hit this limit */
#ifdef ON_WINDOWS
#ifndef NO_HARDLINKS
if (ISFLAG(flags, F_HARDLINKFILES) && newfile->nlink >= 1024) {
#ifdef DEBUG
hll_exclude++;
#endif
LOUD(fprintf(stderr, "grokdir: excluding due to Windows 1024 hard link limit\n"));
string_free(newfile->d_name);
string_free(newfile);
continue;
}
#endif
#endif
/* Optionally recurse directories, including symlinked ones if requested */
if (S_ISDIR(newfile->mode)) {
if (recurse) {
/* --one-file-system */
if (ISFLAG(flags, F_ONEFS)
&& (getdirstats(newfile->d_name, &n_inode, &n_device) == 0)
&& (device != n_device)) {
LOUD(fprintf(stderr, "grokdir: directory: not recursing (--one-file-system)\n"));
string_free(newfile->d_name);
string_free(newfile);
continue;
}
#ifndef NO_SYMLINKS
else if (/*ISFLAG(flags, F_FOLLOWLINKS) ||*/ !S_ISLNK(linfo.st_mode)) {
LOUD(fprintf(stderr, "grokdir: directory: recursing (-r/-R)\n"));
grokdir(newfile->d_name, filelistp, recurse);
}
#else
else {
LOUD(fprintf(stderr, "grokdir: directory: recursing (-r/-R)\n"));
grokdir(newfile->d_name, filelistp, recurse);
}
#endif
}
LOUD(fprintf(stderr, "grokdir: directory: not recursing\n"));
string_free(newfile->d_name);
string_free(newfile);
continue;
} else {
/* Add regular files to list, including symlink targets if requested */
#ifndef NO_SYMLINKS
if (S_ISREG(linfo.st_mode) || (S_ISLNK(linfo.st_mode) && ISFLAG(flags, F_FOLLOWLINKS))) {
#else
if (S_ISREG(newfile->mode)) {
#endif
*filelistp = newfile;
filecount++;
progress++;
} else {
LOUD(fprintf(stderr, "grokdir: not a regular file: %s\n", newfile->d_name);)
string_free(newfile->d_name);
string_free(newfile);
continue;
}
}
}
}
#ifdef UNICODE
while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
#else
closedir(cd);
#endif
grokdir_level--;
if (grokdir_level == 0 && !ISFLAG(flags, F_HIDEPROGRESS)) {
fprintf(stderr, "\rScanning: %" PRIuMAX " files, %" PRIuMAX " dirs (in %u specified)",
progress, dir_progress, user_dir_count);
}
return;
error_travdone:
fprintf(stderr, "\ncould not stat dir "); fwprint(stderr, dir, 1);
return;
error_cd:
fprintf(stderr, "\ncould not chdir to "); fwprint(stderr, dir, 1);
return;
error_overflow:
fprintf(stderr, "\nerror: a path buffer overflowed\n");
exit(EXIT_FAILURE);
}
/* Use Jody Bruchon's hash function on part or all of a file */
static hash_t *get_filehash(const file_t * const restrict checkfile,
const size_t max_read)
{
off_t fsize;
/* This is an array because we return a pointer to it */
static hash_t hash[1];
static hash_t chunk[(CHUNK_SIZE / sizeof(hash_t))];
FILE *file;
int check = 0;
if (checkfile == NULL || checkfile->d_name == NULL) nullptr("get_filehash()");
LOUD(fprintf(stderr, "get_filehash('%s', %" PRIdMAX ")\n", checkfile->d_name, (intmax_t)max_read);)
/* Get the file size. If we can't read it, bail out early */
if (checkfile->size == -1) {
LOUD(fprintf(stderr, "get_filehash: not hashing because stat() info is bad\n"));
return NULL;
}
fsize = checkfile->size;
/* Do not read more than the requested number of bytes */
if (max_read > 0 && fsize > (off_t)max_read)
fsize = (off_t)max_read;
/* Initialize the hash and file read parameters (with filehash_partial skipped)
*
* If we already hashed the first chunk of this file, we don't want to
* wastefully read and hash it again, so skip the first chunk and use
* the computed hash for that chunk as our starting point.
*
* WARNING: We assume max_read is NEVER less than CHUNK_SIZE here! */
*hash = 0;
if (ISFLAG(checkfile->flags, F_HASH_PARTIAL)) {
*hash = checkfile->filehash_partial;
/* Don't bother going further if max_read is already fulfilled */
if (max_read != 0 && max_read <= PARTIAL_HASH_SIZE) {
LOUD(fprintf(stderr, "Partial hash size (%d) >= max_read (%" PRIuMAX "), not hashing anymore\n", PARTIAL_HASH_SIZE, (uintmax_t)max_read);)
return hash;
}
}
#ifdef UNICODE
if (!M2W(checkfile->d_name, wstr)) file = NULL;
else file = _wfopen(wstr, FILE_MODE_RO);
#else
file = fopen(checkfile->d_name, FILE_MODE_RO);
#endif
if (file == NULL) {
fprintf(stderr, "\nerror opening file "); fwprint(stderr, checkfile->d_name, 1);
return NULL;
}
/* Actually seek past the first chunk if applicable
* This is part of the filehash_partial skip optimization */
if (ISFLAG(checkfile->flags, F_HASH_PARTIAL)) {
if (fseeko(file, PARTIAL_HASH_SIZE, SEEK_SET) == -1) {
fclose(file);
fprintf(stderr, "\nerror seeking in file "); fwprint(stderr, checkfile->d_name, 1);
return NULL;
}
fsize -= PARTIAL_HASH_SIZE;
}
/* Read the file in CHUNK_SIZE chunks until we've read it all. */
while (fsize > 0) {
size_t bytes_to_read;
if (interrupt) return 0;
bytes_to_read = (fsize >= (off_t)auto_chunk_size) ? auto_chunk_size : (size_t)fsize;
if (fread((void *)chunk, bytes_to_read, 1, file) != 1) {
fprintf(stderr, "\nerror reading from file "); fwprint(stderr, checkfile->d_name, 1);
fclose(file);
return NULL;
}