This repository has been archived by the owner on Dec 19, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 130
/
fdupes.c
1811 lines (1537 loc) · 50.2 KB
/
fdupes.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
/* FDUPES Copyright (C) 1999-2015 Adrian Lopez
Ported to MinGW by Jody Bruchon <[email protected]>
Includes jody_hash (C) 2015 by Jody Bruchon
Single-file consumption modifications (C) 2015 by Jon Simons
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/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#ifndef OMIT_GETOPT_LONG
#include <getopt.h>
#endif
#include <string.h>
#include <errno.h>
#include <libgen.h>
/* jody_hash.h */
typedef uint64_t hash_t;
/* Version increments when algorithm changes incompatibly */
#define JODY_HASH_VERSION 1
hash_t jody_block_hash(const hash_t * restrict data,
const hash_t start_hash, const unsigned int count);
/* end jody_hash.h */
/* Detect Windows and modify as needed */
#if defined _WIN32 || defined __CYGWIN__
#define ON_WINDOWS 1
#define NO_SYMLINKS 1
#define NO_PERMS 1
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include "getino.h"
// #define NO_HARDLINKS 1
#endif
/* How many operations to wait before updating progress counters */
#define DELAY_COUNT 512
#define ISFLAG(a,b) ((a & b) == b)
#define SETFLAG(a,b) (a |= b)
/* Behavior modification flags */
uint_fast32_t flags = 0;
#define F_RECURSE 0x00000001
#define F_HIDEPROGRESS 0x00000002
#define F_DSAMELINE 0x00000004
#define F_FOLLOWLINKS 0x00000008
#define F_DELETEFILES 0x00000010
#define F_EXCLUDEEMPTY 0x00000020
#define F_CONSIDERHARDLINKS 0x00000040
#define F_SHOWSIZE 0x00000080
#define F_OMITFIRST 0x00000100
#define F_RECURSEAFTER 0x00000200
#define F_NOPROMPT 0x00000400
#define F_SUMMARIZEMATCHES 0x00000800
#define F_EXCLUDEHIDDEN 0x00001000
#define F_PERMISSIONS 0x00002000
#define F_HARDLINKFILES 0x00004000
#define F_EXCLUDESIZE 0x00008000
#define F_QUICKCOMPARE 0x00010000
#define F_USEPARAMORDER 0x00020000
typedef enum {
ORDER_TIME = 0,
ORDER_NAME
} ordertype_t;
const char *program_name;
off_t excludesize = 0;
/* Larger chunk size makes large files process faster but uses more RAM */
#define CHUNK_SIZE 1048576
#define INPUT_SIZE 256
#define PARTIAL_HASH_SIZE 4096
/* These used to be functions. This way saves lots of call overhead */
#define getcrcsignature(a) getcrcsignatureuntil(a, 0)
#define getcrcpartialsignature(a) getcrcsignatureuntil(a, PARTIAL_HASH_SIZE)
/* TODO: Cachegrind indicates that size, inode, and device get hammered hard
* in the checkmatch() code and trigger lots of cache line evictions.
* Maybe we can compact these into a separate structure to improve speed.
* Also look into compacting the true/false flags into one integer and see
* if that improves performance (it'll certainly lower memory usage) */
typedef struct _file {
char *d_name;
uint_fast8_t valid_stat; /* Only call stat() once per file (1 = stat'ed) */
off_t size;
dev_t device;
ino_t inode;
mode_t mode;
#ifndef NO_PERMS
uid_t uid;
gid_t gid;
#endif
time_t mtime;
int user_order; /* Order of the originating command-line parameter */
hash_t crcpartial;
hash_t crcsignature;
uint_fast8_t crcpartial_set; /* 1 = crcpartial is valid */
uint_fast8_t crcsignature_set; /* 1 = crcsignature is valid */
uint_fast8_t hasdupes; /* 1 only if file is first on duplicate chain */
struct _file *duplicates;
struct _file *next;
} file_t;
typedef struct _filetree {
file_t *file;
struct _filetree *left;
struct _filetree *right;
} filetree_t;
/* Hash/compare performance statistics */
int small_file = 0, partial_hash = 0, partial_to_full = -1, hash_fail = 0;
/* Directory parameter position counter */
int user_dir_count = 1;
/***** End definitions, begin code *****/
/*
* String table allocator
* A replacement for malloc() for tables of fixed strings
*
* Copyright (C) 2015 by Jody Bruchon <[email protected]>
* Released under The MIT License or GNU GPL v2 (your choice)
*
* Included here using the license for this software
* (Inlined for performance reasons)
*/
/* Must be divisible by uintptr_t */
#define SMA_PAGE_SIZE 65536
static void *sma_head = NULL;
static uintptr_t *sma_lastpage = NULL;
static unsigned int sma_pages = 0;
static unsigned int sma_lastfree = 0;
static unsigned int sma_nextfree = sizeof(uintptr_t);
/*
static void dump_string_table(void)
{
char *p = sma_head;
unsigned int i = sizeof(uintptr_t);
int pg = sma_pages;
while (pg > 0) {
while (i < SMA_PAGE_SIZE && *(p+i) == '\0') i++;
printf("[%16p] (%jd) '%s'\n", p+i, strlen(p+i), p+i);
i += strlen(p+i);
if (pg <= 1 && i >= sma_nextfree) return;
if (i < SMA_PAGE_SIZE) i++;
else {
p = (char *)*(uintptr_t *)p;
pg--;
i = sizeof(uintptr_t);
}
if (p == NULL) return;
}
return;
}
*/
static inline void *string_malloc_page(void)
{
uintptr_t * restrict pageptr;
/* Allocate page and set up pointers at page starts */
pageptr = (uintptr_t *)malloc(SMA_PAGE_SIZE);
if (pageptr == NULL) return NULL;
*pageptr = (uintptr_t)NULL;
/* Link previous page to this page, if applicable */
if (sma_lastpage != NULL) *sma_lastpage = (uintptr_t)pageptr;
/* Update last page pointers and total page counter */
sma_lastpage = pageptr;
sma_pages++;
return (char *)pageptr;
}
static void *string_malloc(unsigned int len)
{
const char * restrict page = (char *)sma_lastpage;
char *retval;
/* Calling with no actual length is invalid */
if (len < 1) return NULL;
/* Align objects where possible */
if (len & (sizeof(uintptr_t) - 1)) {
len &= ~(sizeof(uintptr_t) - 1);
len += sizeof(uintptr_t);
}
/* Refuse to allocate a space larger than we can store */
if (len > (unsigned int)(SMA_PAGE_SIZE - sizeof(uintptr_t))) return NULL;
/* Initialize on first use */
if (sma_pages == 0) {
sma_head = string_malloc_page();
sma_nextfree = sizeof(uintptr_t);
page = sma_head;
}
/* Allocate new pages when objects don't fit anymore */
if ((sma_nextfree + len) > SMA_PAGE_SIZE) {
page = string_malloc_page();
sma_nextfree = sizeof(uintptr_t);
}
/* Allocate the space */
retval = (char *)page + sma_nextfree;
sma_lastfree = sma_nextfree;
sma_nextfree += len;
return retval;
}
/* Roll back the last allocation */
static inline void string_free(void *addr)
{
const char * restrict p;
/* Do nothing on NULL address or no last length */
if (addr == NULL) return;
if (sma_lastfree < sizeof(uintptr_t)) return;
p = (char *)sma_lastpage + sma_lastfree;
/* Only take action on the last pointer in the page */
if ((uintptr_t)addr != (uintptr_t)p) return;
sma_nextfree = sma_lastfree;
sma_lastfree = 0;
return;
}
/* Destroy all allocated pages */
static inline void string_malloc_destroy(void)
{
uintptr_t *next;
while (sma_pages > 0) {
next = (uintptr_t *)*(uintptr_t *)sma_head;
free(sma_head);
sma_head = (char *)next;
sma_pages--;
}
sma_head = NULL;
return;
}
/* Compare two jody_hashes like memcmp() */
static inline int crc_cmp(const hash_t hash1, const hash_t hash2)
{
if (hash1 > hash2) return 1;
if (hash1 == hash2) return 0;
/* No need to compare a third time */
return -1;
}
/* Print error message. NULL will output "out of memory" and exit */
static void errormsg(char *message, ...)
{
va_list ap;
/* A null pointer means "out of memory" */
if (message == NULL) {
fprintf(stderr, "\r%40s\rout of memory\n", "");
exit(1);
}
va_start(ap, message);
/* Windows will dump the full program path into argv[0] */
#ifndef ON_WINDOWS
fprintf(stderr, "\r%40s\r%s: ", "", program_name);
#else
fprintf(stderr, "\r%40s\r%s: ", "", "fdupes");
#endif
vfprintf(stderr, message, ap);
}
static void escapefilename(char *escape_list, char **filename_ptr)
{
unsigned int x;
unsigned int tx;
static char tmp[8192];
char *filename;
filename = *filename_ptr;
for (x = 0, tx = 0; x < strlen(filename); x++) {
if (tx >= 8192) errormsg("escapefilename() path overflow");
if (strchr(escape_list, filename[x]) != NULL) tmp[tx++] = '\\';
tmp[tx++] = filename[x];
}
tmp[tx] = '\0';
if (x != tx) {
//*filename_ptr = realloc(*filename_ptr, strlen(tmp) + 1);
*filename_ptr = string_malloc(strlen(tmp) + 1);
if (*filename_ptr == NULL) errormsg(NULL);
strcpy(*filename_ptr, tmp);
}
}
static inline char **cloneargs(const int argc, char **argv)
{
int x;
char **args;
args = (char **) string_malloc(sizeof(char*) * argc);
if (args == NULL) errormsg(NULL);
for (x = 0; x < argc; x++) {
args[x] = string_malloc(strlen(argv[x]) + 1);
if (args[x] == NULL) errormsg(NULL);
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 optind)
{
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;
}
static inline void getfilestats(file_t * const restrict file)
{
static struct stat s;
/* Don't stat() the same file more than once */
if (file->valid_stat == 1) return;
file->valid_stat = 1;
if (stat(file->d_name, &s) != 0) {
/* These are already set during file entry initialization */
/* file->size = -1;
file->inode = 0;
file->device = 0;
file->mtime = 0;
file->mode = 0;
file->uid = 0;
file->gid = 0; */
return;
}
file->size = s.st_size;
file->device = s.st_dev;
file->mtime = s.st_mtime;
file->mode = s.st_mode;
#ifndef NO_PERMS
file->uid = s.st_uid;
file->gid = s.st_gid;
#endif
#ifdef ON_WINDOWS
file->inode = getino(file->d_name);
#else
file->inode = s.st_ino;
#endif /* ON_WINDOWS */
return;
}
static uintmax_t grokdir(const char * const restrict dir, file_t ** const restrict filelistp)
{
DIR *cd;
file_t *newfile;
static struct dirent *dirinfo;
int lastchar;
uintmax_t filecount = 0;
#ifndef NO_SYMLINKS
static struct stat linfo;
#endif
static uintmax_t progress = 0, dir_progress = 0;
static int grokdir_level = 0;
static int delay = DELAY_COUNT;
char *name;
static char tempname[8192];
cd = opendir(dir);
dir_progress++;
grokdir_level++;
if (!cd) {
errormsg("could not chdir to %s\n", dir);
return 0;
}
while ((dirinfo = readdir(cd)) != NULL) {
if (strcmp(dirinfo->d_name, ".") && strcmp(dirinfo->d_name, "..")) {
if (!ISFLAG(flags, F_HIDEPROGRESS)) {
if (delay >= DELAY_COUNT) {
delay = 0;
fprintf(stderr, "\rScanning: %ju files, %ju dirs (in %u specified)",
progress, dir_progress, user_dir_count);
} else delay++;
}
/* Assemble the file's full path name */
strcpy(tempname, dir);
lastchar = strlen(dir) - 1;
if (lastchar >= 0 && dir[lastchar] != '/')
strcat(tempname, "/");
strcat(tempname, dirinfo->d_name);
/* Allocate the file_t and the d_name entries in one shot */
newfile = (file_t *)string_malloc(sizeof(file_t) + strlen(dir) + strlen(dirinfo->d_name) + 2);
if (!newfile) errormsg(NULL);
else newfile->next = *filelistp;
newfile->d_name = (char *)newfile + sizeof(file_t);
newfile->user_order = user_dir_count;
newfile->size = -1;
newfile->device = 0;
newfile->inode = 0;
newfile->mtime = 0;
newfile->mode = 0;
#ifndef NO_PERMS
newfile->uid = 0;
newfile->gid = 0;
#endif
newfile->valid_stat = 0;
newfile->crcsignature_set = 0;
newfile->crcsignature = 0;
newfile->crcpartial_set = 0;
newfile->crcpartial = 0;
newfile->duplicates = NULL;
newfile->hasdupes = 0;
strcpy(newfile->d_name, tempname);
if (ISFLAG(flags, F_EXCLUDEHIDDEN)) {
/* WARNING: Re-used tempname here to eliminate a strdup() */
strcpy(tempname, newfile->d_name);
name = basename(tempname);
if (name[0] == '.' && strcmp(name, ".") && strcmp(name, "..")) {
string_free((char *)newfile);
continue;
}
}
/* Get file information and check for validity */
getfilestats(newfile);
if (newfile->size == -1) {
string_free((char *)newfile);
continue;
}
/* Exclude zero-length files if requested */
if (!S_ISDIR(newfile->mode) && newfile->size == 0 && ISFLAG(flags, F_EXCLUDEEMPTY)) {
string_free((char *)newfile);
continue;
}
/* Exclude files below --xsize parameter */
if (!S_ISDIR(newfile->mode) && ISFLAG(flags, F_EXCLUDESIZE) && newfile->size < excludesize) {
string_free((char *)newfile);
continue;
}
#ifndef NO_SYMLINKS
/* Get lstat() information */
if (lstat(newfile->d_name, &linfo) == -1) {
string_free((char *)newfile);
continue;
}
#endif
/* Optionally recurse directories, including symlinked ones if requested */
if (S_ISDIR(newfile->mode)) {
#ifndef NO_SYMLINKS
if (ISFLAG(flags, F_RECURSE) && (ISFLAG(flags, F_FOLLOWLINKS) || !S_ISLNK(linfo.st_mode)))
filecount += grokdir(newfile->d_name, filelistp);
#else
if (ISFLAG(flags, F_RECURSE))
filecount += grokdir(newfile->d_name, filelistp);
#endif
string_free((char *)newfile);
} 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 {
string_free((char *)newfile);
}
}
}
}
closedir(cd);
grokdir_level--;
if (grokdir_level == 0 && !ISFLAG(flags, F_HIDEPROGRESS)) {
fprintf(stderr, "\rExamining %ju files, %ju dirs (in %u specified)",
progress, dir_progress, user_dir_count);
}
return filecount;
}
/* Use Jody Bruchon's hash function on part or all of a file */
static hash_t *getcrcsignatureuntil(file_t * const checkfile,
const off_t max_read)
{
off_t fsize;
off_t bytes_to_read;
/* 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;
/* Get the file size. If we can't read it, bail out early */
getfilestats(checkfile);
if (checkfile->size == -1) return NULL;
fsize = checkfile->size;
/* Do not read more than the requested number of bytes */
if (max_read != 0 && fsize > max_read)
fsize = max_read;
/* Initialize the hash and file read parameters (with crcpartial 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! */
if (checkfile->crcpartial_set) {
*hash = checkfile->crcpartial;
/* Don't bother going further if max_read is already fulfilled */
if (max_read <= CHUNK_SIZE) return hash;
} else *hash = 0;
file = fopen(checkfile->d_name, "rb");
if (file == NULL) {
errormsg("error opening file %s\n", checkfile->d_name);
return NULL;
}
/* Actually seek past the first chunk if applicable
* This is part of the crcpartial skip optimization */
if (checkfile->crcpartial_set) {
if (!fseeko(file, CHUNK_SIZE, SEEK_SET)) {
fclose(file);
errormsg("error seeking in file %s\n", checkfile->d_name);
return NULL;
}
fsize -= CHUNK_SIZE;
}
/* Read the file in CHUNK_SIZE chunks until we've read it all. */
while (fsize > 0) {
bytes_to_read = (fsize >= CHUNK_SIZE) ? CHUNK_SIZE : fsize;
if (fread((void *)chunk, bytes_to_read, 1, file) != 1) {
errormsg("error reading from file %s\n", checkfile->d_name);
fclose(file);
return NULL;
}
*hash = jody_block_hash(chunk, *hash, bytes_to_read);
if (bytes_to_read > fsize) break;
else fsize -= bytes_to_read;
}
fclose(file);
return hash;
}
static inline void purgetree(filetree_t *checktree)
{
if (checktree->left != NULL) purgetree(checktree->left);
if (checktree->right != NULL) purgetree(checktree->right);
string_free(checktree);
}
static inline void registerfile(filetree_t ** restrict branch, file_t * restrict file)
{
getfilestats(file);
*branch = (filetree_t*)string_malloc(sizeof(filetree_t));
if (*branch == NULL) errormsg(NULL);
(*branch)->file = file;
(*branch)->left = NULL;
(*branch)->right = NULL;
return;
}
static file_t **checkmatch(filetree_t * const restrict checktree,
file_t * const restrict file)
{
int cmpresult = 0;
hash_t * restrict crcsignature;
/* If device and inode fields are equal one of the files is a
* hard link to the other or the files have been listed twice
* unintentionally. We don't want to flag these files as
* duplicates unless the user specifies otherwise. */
getfilestats(file);
/* If considering hard linked files as duplicates, they are
* automatically duplicates without being read further since
* they point to the exact same inode. If we aren't considering
* hard links as duplicates, we just return NULL. */
#ifndef NO_HARDLINKS
if ((file->inode ==
checktree->file->inode) && (file->device ==
checktree->file->device)) {
if (ISFLAG(flags, F_CONSIDERHARDLINKS)) return &checktree->file;
else return NULL;
}
#endif
/* Exclude files that are not the same size */
if (file->size < checktree->file->size) cmpresult = -1;
else if (file->size > checktree->file->size) cmpresult = 1;
/* Exclude files by permissions if requested */
else if (ISFLAG(flags, F_PERMISSIONS) &&
(file->mode != checktree->file->mode
#ifndef NO_PERMS
|| file->uid != checktree->file->uid
|| file->gid != checktree->file->gid
#endif
)) cmpresult = -1;
else {
/* Attempt to exclude files quickly with partial file hashing */
partial_hash++;
if (checktree->file->crcpartial_set == 0) {
crcsignature = getcrcpartialsignature(checktree->file);
if (crcsignature == NULL) {
errormsg("cannot read file %s\n", checktree->file->d_name);
return NULL;
}
checktree->file->crcpartial = *crcsignature;
checktree->file->crcpartial_set = 1;
}
if (file->crcpartial_set == 0) {
crcsignature = getcrcpartialsignature(file);
if (crcsignature == NULL) {
errormsg("cannot read file %s\n", file->d_name);
return NULL;
}
file->crcpartial = *crcsignature;
file->crcpartial_set = 1;
}
cmpresult = crc_cmp(file->crcpartial, checktree->file->crcpartial);
if (file->size <= PARTIAL_HASH_SIZE) {
/* crcpartial = crcsignature if file is small enough */
if (file->crcsignature_set == 0) {
file->crcsignature = file->crcpartial;
file->crcsignature_set = 1;
small_file++;
}
if (checktree->file->crcsignature_set == 0) {
checktree->file->crcsignature = checktree->file->crcpartial;
checktree->file->crcsignature_set = 1;
small_file++;
}
} else if (cmpresult == 0) {
/* If partial match was correct, perform a full file hash match */
if (checktree->file->crcsignature_set == 0) {
crcsignature = getcrcsignature(checktree->file);
if (crcsignature == NULL) return NULL;
checktree->file->crcsignature = *crcsignature;
checktree->file->crcsignature_set = 1;
}
if (file->crcsignature_set == 0) {
crcsignature = getcrcsignature(file);
if (crcsignature == NULL) return NULL;
file->crcsignature = *crcsignature;
file->crcsignature_set = 1;
}
cmpresult = crc_cmp(file->crcsignature, checktree->file->crcsignature);
/*if (cmpresult != 0) errormsg("P on %s vs %s\n",
file->d_name, checktree->file->d_name);
else errormsg("P F on %s vs %s\n", file->d_name,
checktree->file->d_name);
printf("%s matches %s\n", file->d_name, checktree->file->d_name);*/
}
}
if (cmpresult < 0) {
if (checktree->left != NULL) {
return checkmatch(checktree->left, file);
} else {
registerfile(&(checktree->left), file);
return NULL;
}
} else if (cmpresult > 0) {
if (checktree->right != NULL) {
return checkmatch(checktree->right, file);
} else {
registerfile(&(checktree->right), file);
return NULL;
}
} else {
/* All compares matched */
partial_to_full++;
return &checktree->file;
}
/* Fall through - should never be reached */
return NULL;
}
/* Do a byte-by-byte comparison in case two different files produce the
same signature. Unlikely, but better safe than sorry. */
static inline int confirmmatch(FILE * const file1, FILE * const file2)
{
static char c1[CHUNK_SIZE];
static char c2[CHUNK_SIZE];
size_t r1;
size_t r2;
fseek(file1, 0, SEEK_SET);
fseek(file2, 0, SEEK_SET);
do {
r1 = fread(c1, sizeof(char), CHUNK_SIZE, file1);
r2 = fread(c2, sizeof(char), CHUNK_SIZE, file2);
if (r1 != r2) return 0; /* file lengths are different */
if (memcmp (c1, c2, r1)) return 0; /* file contents are different */
} while (r2);
return 1;
}
static void summarizematches(const file_t * restrict files)
{
unsigned int numsets = 0;
#ifdef NO_FLOAT
off_t numbytes = 0;
#else
double numbytes = 0.0;
#endif /* NO_FLOAT */
int numfiles = 0;
file_t *tmpfile;
while (files != NULL) {
if (files->hasdupes) {
numsets++;
tmpfile = files->duplicates;
while (tmpfile != NULL) {
numfiles++;
numbytes += files->size;
tmpfile = tmpfile->duplicates;
}
}
files = files->next;
}
if (numsets == 0)
printf("No duplicates found.\n");
else
{
printf("%d duplicate files (in %d sets), occupying ", numfiles, numsets);
#ifdef NO_FLOAT
if (numbytes < 1000) printf("%jd byte%c\n", numbytes, (numbytes != 1) ? 's' : ' ');
else if (numbytes <= 1000000) printf("%jd KB\n", numbytes / 1000);
else printf("%jd MB\n", numbytes / 1000000);
#else
if (numbytes < 1000.0) printf("%.0f bytes\n", numbytes);
else if (numbytes <= (1000.0 * 1000.0)) printf("%.1f KB\n", numbytes / 1000.0);
else printf("%.1f MB\n", numbytes / (1000.0 * 1000.0));
#endif /* NO_FLOAT */
}
}
static void printmatches(file_t * restrict files)
{
file_t * restrict tmpfile;
while (files != NULL) {
if (files->hasdupes) {
if (!ISFLAG(flags, F_OMITFIRST)) {
if (ISFLAG(flags, F_SHOWSIZE)) printf("%jd byte%c each:\n", (intmax_t)files->size,
(files->size != 1) ? 's' : ' ');
if (ISFLAG(flags, F_DSAMELINE)) escapefilename("\\ ", &files->d_name);
printf("%s%c", files->d_name, ISFLAG(flags, F_DSAMELINE)?' ':'\n');
}
tmpfile = files->duplicates;
while (tmpfile != NULL) {
if (ISFLAG(flags, F_DSAMELINE)) escapefilename("\\ ", &tmpfile->d_name);
printf("%s%c", tmpfile->d_name, ISFLAG(flags, F_DSAMELINE)?' ':'\n');
tmpfile = tmpfile->duplicates;
}
printf("\n");
}
files = files->next;
}
}
static void deletefiles(file_t *files, int prompt, FILE *tty)
{
int counter;
int groups = 0;
int curgroup = 0;
file_t *tmpfile;
file_t *curfile;
file_t **dupelist;
int *preserve;
char *preservestr;
char *token;
char *tstr;
int number;
int sum;
int max = 0;
int x, i;
curfile = files;
while (curfile) {
if (curfile->hasdupes) {
counter = 1;
groups++;
tmpfile = curfile->duplicates;
while (tmpfile) {
counter++;
tmpfile = tmpfile->duplicates;
}
if (counter > max) max = counter;
}
curfile = curfile->next;
}
max++;
dupelist = (file_t**) malloc(sizeof(file_t*) * max);
preserve = (int*) malloc(sizeof(int) * max);
preservestr = (char*) malloc(INPUT_SIZE);
if (!dupelist || !preserve || !preservestr) errormsg(NULL);
while (files) {
if (files->hasdupes) {
curgroup++;
counter = 1;
dupelist[counter] = files;
if (prompt) printf("[%d] %s\n", counter, files->d_name);
tmpfile = files->duplicates;
while (tmpfile) {
dupelist[++counter] = tmpfile;
if (prompt) printf("[%d] %s\n", counter, tmpfile->d_name);
tmpfile = tmpfile->duplicates;
}
if (prompt) printf("\n");
/* preserve only the first file */
if (!prompt) {
preserve[1] = 1;
for (x = 2; x <= counter; x++) preserve[x] = 0;
} else do {
/* prompt for files to preserve */
printf("Set %d of %d: keep which files? (1 - %d, [a]ll)",
curgroup, groups, counter);
if (ISFLAG(flags, F_SHOWSIZE)) printf(" (%jd byte%c each)", (intmax_t)files->size,
(files->size != 1) ? 's' : ' ');
printf(": ");
fflush(stdout);
if (!fgets(preservestr, INPUT_SIZE, tty))
preservestr[0] = '\n'; /* treat fgets() failure as if nothing was entered */
i = strlen(preservestr) - 1;
/* tail of buffer must be a newline */
while (preservestr[i]!='\n') {
tstr = (char*)
realloc(preservestr, strlen(preservestr) + 1 + INPUT_SIZE);
if (!tstr) errormsg(NULL);
preservestr = tstr;
if (!fgets(preservestr + i + 1, INPUT_SIZE, tty))
{
preservestr[0] = '\n'; /* treat fgets() failure as if nothing was entered */
break;
}
i = strlen(preservestr)-1;
}
for (x = 1; x <= counter; x++) preserve[x] = 0;
token = strtok(preservestr, " ,\n");
while (token != NULL) {
if (*token == 'a' || *token == 'A')
for (x = 0; x <= counter; x++) preserve[x] = 1;
number = 0;
sscanf(token, "%d", &number);
if (number > 0 && number <= counter) preserve[number] = 1;