Removed the MD5 option which was useless.
[finddup.git] / finddup.c
1
2 /*
3  *  finddup is a simple utility to find duplicated files, files common
4  *  to several directories, or files present in one directory and not
5  *  in another one.
6  *
7  *  Copyright (c) 2010 Francois Fleuret
8  *  Written by Francois Fleuret <francois@fleuret.org>
9  *
10  *  This file is part of finddup.
11  *
12  *  finddup is free software: you can redistribute it and/or modify it
13  *  under the terms of the GNU General Public License version 3 as
14  *  published by the Free Software Foundation.
15  *
16  *  finddup is distributed in the hope that it will be useful, but WITHOUT
17  *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18  *  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
19  *  License for more details.
20  *
21  *  You should have received a copy of the GNU General Public License
22  *  along with finddup.  If not, see <http://www.gnu.org/licenses/>.
23  *
24  */
25
26 #define VERSION_NUMBER "0.9"
27
28 #define _BSD_SOURCE
29
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/param.h>
33 #include <dirent.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <unistd.h>
37 #include <errno.h>
38 #include <string.h>
39 #include <sys/ioctl.h>
40 #include <locale.h>
41 #include <getopt.h>
42 #include <fcntl.h>
43
44 /* 1M really helps compared to 64k */
45 #define READ_BUFFER_SIZE (1024 * 1024)
46
47 #define PROGRESS_BUFFER_SIZE 1024
48
49 typedef int64_t size_sum_t;
50
51 /* Yeah, global variables! */
52
53 int ignore_dotfiles = 0; /* 1 means ignore files and directories
54                             starting with a dot */
55
56 int ignore_empty_files = 0; /* 1 means ignore empty files */
57
58 int show_realpaths = 0; /* 1 means ignore files and directories
59                             starting with a dot */
60
61 int show_progress = 0; /* 1 means show a progress bar when we are in a
62                           tty */
63
64 int show_hits = 1; /* 1 means to show the files from dir2
65                       corresponding to the ones from dir1 */
66
67 int show_groups = 1; /* 1 means to show the group IDs when printing
68                         file names */
69
70 int same_inodes_are_different = 0; /* 1 means that comparison between
71                                       two files with same inode will
72                                       always be false */
73
74 /********************************************************************/
75
76 /* malloc with error checking.  */
77
78 void *safe_malloc(size_t n) {
79   void *p = malloc(n);
80   if (!p && n != 0) {
81     printf("Can not allocate memory: %s\n", strerror(errno));
82     exit(EXIT_FAILURE);
83   }
84   return p;
85 }
86
87 /********************************************************************/
88
89 int ignore_entry(const char *name) {
90   return
91     strcmp(name, ".") == 0 ||
92     strcmp(name, "..") == 0 ||
93     (ignore_dotfiles && name[0] == '.' && name[1] != '/');
94 }
95
96 /**********************************************************************/
97
98 struct file_node {
99   struct file_node *next;
100   char *name;
101   size_t size;
102   ino_t inode;
103   int group_id; /* one per identical file content */
104   int dir_id; /* 1 for DIR1, and 2 for DIR2 */
105 };
106
107 void file_list_delete(struct file_node *head) {
108   struct file_node *next;
109   while(head) {
110     next = head->next;
111     free(head->name);
112     free(head);
113     head = next;
114   }
115 }
116
117 int file_list_length(struct file_node *head) {
118   int l = 0;
119   while(head) {
120     l++;
121     head = head->next;
122   }
123   return l;
124 }
125
126 /**********************************************************************/
127
128 int same_content(struct file_node *f1, struct file_node *f2,
129                  char *buffer1, char *buffer2) {
130   int fd1, fd2, s1, s2;
131
132   fd1 = open(f1->name, O_RDONLY);
133   fd2 = open(f2->name, O_RDONLY);
134
135   if(fd1 >= 0 && fd2 >= 0) {
136     while(1) {
137       s1 = read(fd1, buffer1, READ_BUFFER_SIZE);
138       s2 = read(fd2, buffer2, READ_BUFFER_SIZE);
139
140       if(s1 < 0 || s2 < 0) {
141         close(fd1);
142         close(fd2);
143         return 0;
144       }
145
146       if(s1 == s2) {
147         if(s1 == 0) {
148           close(fd1);
149           close(fd2);
150           return 1;
151         } else {
152           if(memcmp(buffer1, buffer2, s1)) {
153             /* printf("size_to_read = %d\n", size_to_read); */
154             close(fd1);
155             close(fd2);
156             return 0;
157           }
158         }
159       } else {
160         fprintf(stderr,
161                 "Different read size without error on files of same size.\n");
162         exit(EXIT_FAILURE);
163       }
164     }
165   } else {
166
167     if(fd1 < 0) {
168       fprintf(stderr,
169               "Can not open \"%s\" error: %s\n",
170               f1->name,
171               strerror(errno));
172     }
173
174     if(fd2 < 0) {
175       fprintf(stderr,
176               "Can not open \"%s\" error: %s\n",
177               f2->name,
178               strerror(errno));
179     }
180
181     exit(EXIT_FAILURE);
182   }
183 }
184
185 int same_files(struct file_node *f1, struct file_node *f2,
186                char *buffer1, char *buffer2) {
187   if(same_inodes_are_different && f1->inode == f2->inode) {
188     return 0;
189   }
190
191   return f1->size == f2->size && same_content(f1, f2, buffer1, buffer2);
192 }
193
194 /**********************************************************************/
195
196 struct file_node *scan_directory(struct file_node *tail, const char *name) {
197   DIR *dir;
198   struct dirent *dir_e;
199   struct stat sb;
200   struct file_node *tmp;
201   char subname[PATH_MAX + 1];
202
203   if(lstat(name, &sb) != 0) {
204     fprintf(stderr, "Can not stat \"%s\": %s\n", name, strerror(errno));
205     exit(EXIT_FAILURE);
206   }
207
208   if(S_ISLNK(sb.st_mode)) {
209     return tail;
210   }
211
212   dir = opendir(name);
213
214   if(dir) {
215     while((dir_e = readdir(dir))) {
216       if(!ignore_entry(dir_e->d_name)) {
217         snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
218         tail = scan_directory(tail, subname);
219       }
220     }
221     closedir(dir);
222   } else {
223     if(S_ISREG(sb.st_mode)) {
224       if(!ignore_entry(name)) {
225         if(!ignore_empty_files || sb.st_size > 0) {
226           tmp = safe_malloc(sizeof(struct file_node));
227           tmp->next = tail;
228           tmp->name = strdup(name);
229           tmp->size = sb.st_size;
230           tmp->inode = sb.st_ino;
231           tmp->group_id = -1;
232           tmp->dir_id = -1;
233           tail = tmp;
234         }
235       }
236     }
237   }
238
239   return tail;
240 }
241
242 void print_file(struct file_node *node) {
243   char tmp[PATH_MAX + 1];
244   if(show_realpaths) {
245     if(realpath(node->name, tmp)) {
246       if(show_groups) {
247         printf("%d %s\n", node->group_id, tmp);
248       } else {
249         printf("%s\n", tmp);
250       }
251     } else {
252       printf("Can not get the realpath of \"%s\": %s\n",
253              node->name,
254              strerror(errno));
255       exit(EXIT_FAILURE);
256     }
257   } else {
258     if(show_groups) {
259       printf("%d %s\n", node->group_id, node->name);
260     } else {
261       printf("%s\n", node->name);
262     }
263   }
264 }
265
266 int compare_nodes(const void *x1, const void *x2) {
267   const struct file_node **f1, **f2;
268
269   f1 = (const struct file_node **) x1;
270   f2 = (const struct file_node **) x2;
271
272   if((*f1)->group_id < (*f2)->group_id) {
273     return -1;
274   } else if((*f1)->group_id > (*f2)->group_id) {
275     return 1;
276   } else {
277     if((*f1)->dir_id < (*f2)->dir_id) {
278       return -1;
279     } else if((*f1)->dir_id > (*f2)->dir_id) {
280       return 1;
281     } else {
282       return 0;
283     }
284   }
285 }
286
287
288 void print_result(struct file_node *list1, struct file_node *list2) {
289   struct file_node *node1, *node2;
290   struct file_node **nodes;
291   int nb, n;
292
293   nb = 0;
294   for(node1 = list1; node1; node1 = node1->next) {
295     if(node1->group_id >= 0) { nb++; }
296   }
297
298   if(list2) {
299     for(node2 = list2; node2; node2 = node2->next) {
300       if(node2->group_id >= 0) { nb++; }
301     }
302   }
303
304   nodes = safe_malloc(nb * sizeof(struct file_node *));
305
306   n = 0;
307   for(node1 = list1; node1; node1 = node1->next) {
308     if(node1->group_id >= 0) {
309       nodes[n++] = node1;
310     }
311   }
312
313   if(list2) {
314     for(node2 = list2; node2; node2 = node2->next) {
315       if(node2->group_id >= 0) {
316         nodes[n++] = node2;
317       }
318     }
319   }
320
321   qsort(nodes, nb, sizeof(struct file_node *), compare_nodes);
322
323   for(n = 0; n < nb; n++) {
324     if(!show_groups && n > 0 && nodes[n]->group_id != nodes[n-1]->group_id) {
325       printf("\n");
326     }
327     print_file(nodes[n]);
328   }
329
330   free(nodes);
331 }
332
333 struct progress_state {
334   int bar_width;
335   int nb_values, value;
336   int last_position;
337 };
338
339 void print_progress(struct progress_state *state) {
340   int position, k;
341   struct winsize win;
342   char buffer[PROGRESS_BUFFER_SIZE];
343   char *s;
344
345   if(show_progress) {
346     /* We use the previous bar_width to compute the position, so that
347        we avoid doing too many ioctls */
348     position = (state->bar_width * state->value) / (state->nb_values - 1);
349     if(state->bar_width <= 0 || position != state->last_position) {
350       if(!ioctl (STDERR_FILENO, TIOCGWINSZ, (char *) &win)) {
351         /* Something weird is going on if the previous test is wrong */
352         if(win.ws_col >= PROGRESS_BUFFER_SIZE - 3) {
353           state->bar_width = PROGRESS_BUFFER_SIZE - 10;
354         } else {
355           state->bar_width = win.ws_col - 7;
356         }
357         position = (state->bar_width * state->value) / (state->nb_values - 1);
358         state->last_position = position;
359         s = buffer;
360         for(k = 0; k < position; k++) {
361           *(s++) = '+';
362         }
363         for(; k < state->bar_width; k++) {
364           *(s++) = '-';
365         }
366
367         /* We need four % because of the fprintf that follows */
368         sprintf(s, " [%3d%%%%]\r",
369                 (100 * state->value) / (state->nb_values - 1));
370
371         fprintf(stderr, buffer);
372       }
373     }
374   }
375 }
376
377 void start(const char *dirname1, const char *dirname2) {
378   struct file_node *list1, *list2;
379   struct file_node *node1, *node2;
380   struct progress_state progress_state;
381   int not_in, found;
382   int nb_groups, nb_nodes;
383   int list1_length, list2_length, previous_progress;
384
385   char *buffer1 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
386   char *buffer2 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
387
388   not_in = 0;
389
390   if(show_progress) {
391     fprintf(stderr, "Scanning '%s' ... ", dirname1);
392   }
393
394   list1 = scan_directory(0, dirname1);
395
396   list1_length = file_list_length(list1);
397
398   if(show_progress) {
399     fprintf(stderr, "done (%d file%s).\n",
400             list1_length, (list1_length > 1 ? "s" : ""));
401   }
402
403   if(dirname2) {
404     if(strncmp(dirname2, "not:", 4) == 0) {
405       not_in = 1;
406       /* groups are not computed in the not: mode */
407       show_groups = 0;
408       dirname2 += 4;
409     } else if(strncmp(dirname2, "and:", 4) == 0) {
410       dirname2 += 4;
411     }
412     if(show_progress) {
413       fprintf(stderr, "Scanning '%s' ... ", dirname2);
414     }
415     list2 = scan_directory(0, dirname2);
416     if(show_progress) {
417       list2_length = file_list_length(list2);
418       fprintf(stderr, "done (%d file%s).\n",
419               list2_length, (list2_length > 1 ? "s" : ""));
420     }
421   } else {
422     list2 = list1;
423   }
424
425   if(show_progress) {
426     fprintf(stderr, "Now looking for identical files (this may take a while).\n");
427   }
428
429   nb_groups = 0;
430   previous_progress = -1;
431   nb_nodes = 0;
432
433   progress_state.bar_width = -1;
434   progress_state.last_position = -1;
435   progress_state.nb_values = list1_length;
436
437   if(not_in) {
438     for(node1 = list1; node1; node1 = node1->next) {
439       progress_state.value = nb_nodes;
440       print_progress(&progress_state);
441       nb_nodes++;
442
443       found = 0;
444
445       for(node2 = list2; !found && node2; node2 = node2->next) {
446         if(same_files(node1, node2, buffer1, buffer2)) {
447           found = 1;
448         }
449       }
450
451       if(!found) {
452         if(show_realpaths) {
453           printf("%s\n", realpath(node1->name, 0));
454         } else {
455           printf("%s\n", node1->name);
456         }
457       }
458     }
459
460   } else {
461     for(node1 = list1; node1; node1 = node1->next) {
462       progress_state.value = nb_nodes;
463       print_progress(&progress_state);
464       nb_nodes++;
465
466       for(node2 = list2; node2; node2 = node2->next) {
467         if(node1->group_id < 0 || node2->group_id < 0) {
468           if(same_files(node1, node2, buffer1, buffer2)) {
469             if(node1->group_id < 0) {
470               if(node2->group_id >= 0) {
471                 node1->group_id = node2->group_id;
472               } else {
473                 node1->group_id = nb_groups;
474                 node1->dir_id = 1;
475                 nb_groups++;
476               }
477             }
478             if(node2->group_id < 0) {
479               node2->group_id = node1->group_id;
480               node2->dir_id = 2;
481             }
482           }
483         }
484       }
485     }
486   }
487
488   if(show_progress) {
489     fprintf(stderr, "\n");
490   }
491
492   if(dirname2) {
493     print_result(list1, list2);
494     file_list_delete(list1);
495     file_list_delete(list2);
496   } else {
497     print_result(list1, 0);
498     file_list_delete(list1);
499   }
500
501   free(buffer1);
502   free(buffer2);
503 }
504
505 void usage(FILE *out) {
506   fprintf(out, "Usage: finddup [OPTION]... DIR1 [[and:|not:]DIR2]\n");
507   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
508   fprintf(out, "Without DIR2, lists duplicated files found in DIR1. With DIR2, lists files common to both directories. With the not: prefix, lists files found in DIR1 which do not exist in DIR2. The and: prefix is the default and should be used only if you have a directory starting with 'not:'\n");
509   fprintf(out, "\n");
510   /*            01234567890123456789012345678901234567890123456789012345678901234567890123456789*/
511   fprintf(out, "   -h, --help                 show this help\n");
512   fprintf(out, "   -d, --ignore-dots          ignore dot files and directories\n");
513   fprintf(out, "   -0, --ignore-empty         ignore empty files\n");
514   fprintf(out, "   -c, --hide-matchings       do not show which files in DIR2 corresponds to\n");
515   fprintf(out, "                              those in DIR1\n");
516   fprintf(out, "   -g, --no-group-ids         do not show the file groups\n");
517   fprintf(out, "   -p, --show-progress        show progress\n");
518   fprintf(out, "   -r, --real-paths           show the real file paths\n");
519   fprintf(out, "   -i, --same-inodes-are-different\n");
520   fprintf(out, "                              consider files with same inode as different\n");
521   fprintf(out, "\n");
522   fprintf(out, "Report bugs and comments to <francois@fleuret.org>.\n");
523 }
524
525 /**********************************************************************/
526
527 static struct option long_options[] = {
528   { "help", no_argument, 0, 'h' },
529   { "same-inodes-are-different", no_argument, 0, 'i' },
530   { "real-paths", no_argument, 0, 'r' },
531   { "hide-matchings", no_argument, 0, 'c' },
532   { "no-group-ids", no_argument, 0, 'g' },
533   { "ignore-dots", no_argument, 0, 'd' },
534   { "ignore-empty", no_argument, 0, '0' },
535   { "show-progress", no_argument, 0, 'p' },
536   { 0, 0, 0, 0 }
537 };
538
539 int main(int argc, char **argv) {
540   int c;
541
542   setlocale (LC_ALL, "");
543
544   while ((c = getopt_long(argc, argv, "hircgd0pm",
545                           long_options, NULL)) != -1) {
546     switch (c) {
547
548     case 'h':
549       usage(stdout);
550       exit(EXIT_SUCCESS);
551
552       break;
553
554     case 'd':
555       ignore_dotfiles = 1;
556       break;
557
558     case '0':
559       ignore_empty_files = 1;
560       break;
561
562     case 'r':
563       show_realpaths = 1;
564       break;
565
566     case 'i':
567       same_inodes_are_different = 1;
568       break;
569
570     case 'g':
571       show_groups = 0;
572       break;
573
574     case 'p':
575       show_progress = 1;
576       break;
577
578     case 'c':
579       show_hits = 0;
580       break;
581
582     default:
583       usage(stderr);
584       exit(EXIT_FAILURE);
585     }
586   }
587
588   if(!isatty(STDERR_FILENO)) {
589     show_progress = 0;
590   }
591
592   if(optind + 2 == argc) {
593     start(argv[optind], argv[optind + 1]);
594   } else if(optind + 1 == argc) {
595     same_inodes_are_different = 1;
596     start(argv[optind], 0);
597   } else {
598     usage(stderr);
599     exit(EXIT_FAILURE);
600   }
601
602   exit(EXIT_SUCCESS);
603 }