Added the -e option to execute a command for each group of identical files.
[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 "1.1"
27
28 #define _BSD_SOURCE
29
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/param.h>
33 #include <sys/wait.h>
34 #include <dirent.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <unistd.h>
38 #include <errno.h>
39 #include <string.h>
40 #include <sys/ioctl.h>
41 #include <locale.h>
42 #include <getopt.h>
43 #include <fcntl.h>
44
45 /* 1M really helps compared to 64k */
46 #define READ_BUFFER_SIZE (1024 * 1024)
47
48 #define PROGRESS_BUFFER_SIZE 1024
49
50 typedef int64_t size_sum_t;
51
52 /* Yeah, global variables! */
53
54 int ignore_dotfiles = 0; /* 1 means ignore files and directories
55                             starting with a dot */
56
57 int ignore_empty_files = 0; /* 1 means ignore empty files */
58
59 int show_realpaths = 0; /* 1 means ignore files and directories
60                             starting with a dot */
61
62 int show_progress = 0; /* 1 means show a progress bar when we are in a
63                           tty */
64
65 int show_hits = 1; /* 1 means to show the files from dir2
66                       corresponding to the ones from dir1 */
67
68 int show_groups = 1; /* 1 means to show the group IDs when printing
69                         file names */
70
71 int same_inodes_are_different = 0; /* 1 means that comparison between
72                                       two files with same inode will
73                                       always be false */
74
75 int sort_by_time = 0; /* 1 means to sort files in each group according
76                          to the modification time */
77
78 char *command_to_exec = 0; /* the name of the command to exec for each
79                               group of identical files */
80
81 /********************************************************************/
82
83 /* malloc with error checking.  */
84
85 void *safe_malloc(size_t n) {
86   void *p = malloc(n);
87   if (!p && n != 0) {
88     fprintf(stderr,
89             "finddup: Can not allocate memory: %s\n", strerror(errno));
90     exit(EXIT_FAILURE);
91   }
92   return p;
93 }
94
95 /********************************************************************/
96
97 int ignore_entry(const char *name) {
98   return
99     strcmp(name, ".") == 0 ||
100     strcmp(name, "..") == 0 ||
101     (ignore_dotfiles && name[0] == '.' && name[1] != '/');
102 }
103
104 /**********************************************************************/
105
106 struct file_node {
107   struct file_node *next;
108   char *name;
109   size_t size;
110   time_t atime, mtime, ctime;
111   ino_t inode;
112   int group_id; /* one per identical file content */
113   int dir_id; /* 1 for DIR1, and 2 for DIR2 */
114 };
115
116 void file_list_delete(struct file_node *head) {
117   struct file_node *next;
118   while(head) {
119     next = head->next;
120     free(head->name);
121     free(head);
122     head = next;
123   }
124 }
125
126 int file_list_length(struct file_node *head) {
127   int l = 0;
128   while(head) {
129     l++;
130     head = head->next;
131   }
132   return l;
133 }
134
135 /**********************************************************************/
136
137 int same_content(struct file_node *f1, struct file_node *f2,
138                  char *buffer1, char *buffer2) {
139   int fd1, fd2, s1, s2;
140
141   fd1 = open(f1->name, O_RDONLY);
142   fd2 = open(f2->name, O_RDONLY);
143
144   if(fd1 >= 0 && fd2 >= 0) {
145     while(1) {
146       s1 = read(fd1, buffer1, READ_BUFFER_SIZE);
147       s2 = read(fd2, buffer2, READ_BUFFER_SIZE);
148
149       if(s1 < 0 || s2 < 0) {
150         close(fd1);
151         close(fd2);
152         return 0;
153       }
154
155       if(s1 == s2) {
156         if(s1 == 0) {
157           close(fd1);
158           close(fd2);
159           return 1;
160         } else {
161           if(memcmp(buffer1, buffer2, s1)) {
162             /* printf("size_to_read = %d\n", size_to_read); */
163             close(fd1);
164             close(fd2);
165             return 0;
166           }
167         }
168       } else {
169         fprintf(stderr,
170                 "finddup: Different read size without error on files of same size.\n");
171         exit(EXIT_FAILURE);
172       }
173     }
174   } else {
175
176     if(fd1 < 0) {
177       fprintf(stderr,
178               "finddup: Can not open \"%s\" error: %s\n",
179               f1->name,
180               strerror(errno));
181     }
182
183     if(fd2 < 0) {
184       fprintf(stderr,
185               "finddup: Can not open \"%s\" error: %s\n",
186               f2->name,
187               strerror(errno));
188     }
189
190     exit(EXIT_FAILURE);
191   }
192 }
193
194 int same_files(struct file_node *f1, struct file_node *f2,
195                char *buffer1, char *buffer2) {
196   if(same_inodes_are_different && f1->inode == f2->inode) {
197     return 0;
198   }
199
200   return f1->size == f2->size && same_content(f1, f2, buffer1, buffer2);
201 }
202
203 /**********************************************************************/
204
205 struct file_node *scan_directory_rec(struct file_node *tail, const char *name) {
206   DIR *dir;
207   struct dirent *dir_e;
208   struct stat sb;
209   struct file_node *tmp;
210   char subname[PATH_MAX + 1];
211
212   if(lstat(name, &sb) != 0) {
213     fprintf(stderr, "finddup: Can not stat \"%s\": %s\n", name, strerror(errno));
214     exit(EXIT_FAILURE);
215   }
216
217   if(S_ISLNK(sb.st_mode)) {
218     return tail;
219   }
220
221   dir = opendir(name);
222
223   if(dir) {
224     while((dir_e = readdir(dir))) {
225       if(!ignore_entry(dir_e->d_name)) {
226         snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
227         tail = scan_directory_rec(tail, subname);
228       }
229     }
230     closedir(dir);
231   } else {
232     if(S_ISREG(sb.st_mode)) {
233       if(!ignore_entry(name)) {
234         if(!ignore_empty_files || sb.st_size > 0) {
235           tmp = safe_malloc(sizeof(struct file_node));
236           tmp->next = tail;
237           tmp->name = strdup(name);
238           tmp->size = sb.st_size;
239           tmp->atime = sb.st_atime;
240           tmp->mtime = sb.st_mtime;
241           tmp->ctime = sb.st_ctime;
242           tmp->inode = sb.st_ino;
243           tmp->group_id = -1;
244           tmp->dir_id = -1;
245           tail = tmp;
246         }
247       }
248     }
249   }
250
251   return tail;
252 }
253
254 struct file_node *scan_directory(struct file_node *tail, const char *name) {
255   struct file_node *result;
256   int length;
257
258   if(show_progress) {
259     fprintf(stderr, "Scanning '%s' ... ", name);
260   }
261
262   result = scan_directory_rec(tail, name);
263   length = file_list_length(result);
264
265   if(show_progress) {
266     fprintf(stderr, "done (%d file%s).\n",
267             length, (length > 1 ? "s" : ""));
268   }
269
270
271   return result;
272 }
273
274 void print_file(struct file_node *node) {
275   char tmp[PATH_MAX + 1];
276   if(show_realpaths) {
277     if(realpath(node->name, tmp)) {
278       if(show_groups) {
279         printf("%d %s\n", node->group_id, tmp);
280       } else {
281         printf("%s\n", tmp);
282       }
283     } else {
284       fprintf(stderr,
285               "finddup: Can not get the realpath of \"%s\": %s\n",
286               node->name,
287               strerror(errno));
288       exit(EXIT_FAILURE);
289     }
290   } else {
291     if(show_groups) {
292       printf("%d %s\n", node->group_id, node->name);
293     } else {
294       printf("%s\n", node->name);
295     }
296   }
297 }
298
299 int compare_nodes(const void *x1, const void *x2) {
300   const struct file_node **f1, **f2;
301
302   f1 = (const struct file_node **) x1;
303   f2 = (const struct file_node **) x2;
304
305   if((*f1)->group_id < (*f2)->group_id) {
306     return -1;
307   } else if((*f1)->group_id > (*f2)->group_id) {
308     return 1;
309   } else {
310     if(sort_by_time) {
311       if((*f1)->mtime < (*f2)->mtime) {
312         return -1;
313       } else if((*f1)->mtime > (*f2)->mtime) {
314         return 1;
315       } else {
316         return 0;
317       }
318     } else {
319       if((*f1)->dir_id < (*f2)->dir_id) {
320         return -1;
321       } else if((*f1)->dir_id > (*f2)->dir_id) {
322         return 1;
323       } else {
324         return 0;
325       }
326     }
327   }
328 }
329
330 void exec_command(int nb, struct file_node **nodes) {
331   char **args;
332   int max_group_size = 0, group_size, m, n, status;
333   pid_t pid;
334
335   for(n = 0; n < nb; n++) {
336     if(n == 0 || nodes[n]->group_id != nodes[n-1]->group_id) {
337       group_size = 0;
338     }
339     group_size++;
340     if(group_size > max_group_size) {
341       max_group_size = group_size;
342     }
343   }
344
345   args = safe_malloc((max_group_size + 2) * sizeof(char *));
346   args[0] = command_to_exec;
347
348   n = 0;
349   while(n < nb) {
350     m = n;
351     while(n < nb && nodes[n]->group_id == nodes[m]->group_id) {
352       args[n - m + 1] = nodes[n]->name;
353       n++;
354     }
355     args[n - m + 1] = 0;
356     pid = fork();
357     if(pid < 0) {
358     } else if(pid == 0) {
359       if(execvp(command_to_exec, args) < 0) {
360         perror("execvp");
361         exit(EXIT_FAILURE);
362       }
363     } else {
364       while(wait(&status) != pid);
365       if(status > 0) {
366         exit(EXIT_FAILURE);
367       }
368     }
369   }
370
371   free(args);
372 }
373
374 void print_result(struct file_node *list1, struct file_node *list2) {
375   struct file_node *node1, *node2;
376   struct file_node **nodes;
377   int nb, n;
378
379   nb = 0;
380   for(node1 = list1; node1; node1 = node1->next) {
381     if(node1->group_id >= 0) { nb++; }
382   }
383
384   if(list2) {
385     for(node2 = list2; node2; node2 = node2->next) {
386       if(node2->group_id >= 0) { nb++; }
387     }
388   }
389
390   nodes = safe_malloc(nb * sizeof(struct file_node *));
391
392   n = 0;
393   for(node1 = list1; node1; node1 = node1->next) {
394     if(node1->group_id >= 0) {
395       nodes[n++] = node1;
396     }
397   }
398
399   if(list2) {
400     for(node2 = list2; node2; node2 = node2->next) {
401       if(node2->group_id >= 0) {
402         nodes[n++] = node2;
403       }
404     }
405   }
406
407   qsort(nodes, nb, sizeof(struct file_node *), compare_nodes);
408
409   if(command_to_exec) {
410     exec_command(nb, nodes);
411   } else {
412     for(n = 0; n < nb; n++) {
413       if(!show_groups && n > 0 && nodes[n]->group_id != nodes[n-1]->group_id) {
414         printf("\n");
415       }
416       print_file(nodes[n]);
417     }
418   }
419
420   free(nodes);
421 }
422
423 struct progress_state {
424   int bar_width;
425   int nb_values, value;
426   int last_position;
427 };
428
429 void print_progress(struct progress_state *state) {
430   int position, k, normalizer;
431   struct winsize win;
432   char buffer[PROGRESS_BUFFER_SIZE];
433   char *s;
434
435   normalizer = (state->nb_values > 1 ? state->nb_values - 1 : 1);
436
437   if(show_progress) {
438     /* We use the previous bar_width to compute the position, so that
439        we avoid doing too many ioctls */
440     position = (state->bar_width * state->value) / normalizer;
441     if(state->bar_width <= 0 || position != state->last_position) {
442       if(!ioctl (STDERR_FILENO, TIOCGWINSZ, (char *) &win)) {
443         /* Something weird is going on if the previous test is wrong */
444         if(win.ws_col >= PROGRESS_BUFFER_SIZE - 3) {
445           state->bar_width = PROGRESS_BUFFER_SIZE - 10;
446         } else {
447           state->bar_width = win.ws_col - 7;
448         }
449         position = (state->bar_width * state->value) / normalizer;
450         state->last_position = position;
451         s = buffer;
452         for(k = 0; k < position; k++) {
453           *(s++) = '+';
454         }
455         for(; k < state->bar_width; k++) {
456           *(s++) = '-';
457         }
458
459         /* We need four % because of the fprintf that follows */
460         sprintf(s, " [%3d%%%%]\r",
461                 (100 * state->value) / normalizer);
462
463         fprintf(stderr, buffer);
464       }
465     }
466   }
467 }
468
469 void start(const char *dirname1, const char *dirname2) {
470   struct file_node *list1, *list2;
471   struct file_node *node1, *node2;
472   struct progress_state progress_state;
473   int not_in, found;
474   int nb_groups, nb_nodes;
475   int list1_length, previous_progress;
476
477   char *buffer1 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
478   char *buffer2 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
479
480   not_in = 0;
481
482   list1 = scan_directory(0, dirname1);
483   list1_length = file_list_length(list1);
484
485   if(dirname2) {
486     if(strncmp(dirname2, "not:", 4) == 0) {
487       not_in = 1;
488       /* groups are not computed in the not: mode */
489       show_groups = 0;
490       dirname2 += 4;
491     } else if(strncmp(dirname2, "and:", 4) == 0) {
492       dirname2 += 4;
493     }
494     list2 = scan_directory(0, dirname2);
495   } else {
496     list2 = list1;
497   }
498
499   if(show_progress) {
500     fprintf(stderr,
501             "Now looking for identical files (this may take a while).\n");
502   }
503
504   nb_groups = 0;
505   previous_progress = -1;
506   nb_nodes = 0;
507
508   progress_state.bar_width = -1;
509   progress_state.last_position = -1;
510   progress_state.nb_values = list1_length;
511
512   if(not_in) {
513     for(node1 = list1; node1; node1 = node1->next) {
514       progress_state.value = nb_nodes;
515       print_progress(&progress_state);
516       nb_nodes++;
517
518       found = 0;
519
520       for(node2 = list2; !found && node2; node2 = node2->next) {
521         if(same_files(node1, node2, buffer1, buffer2)) {
522           found = 1;
523         }
524       }
525
526       if(!found) {
527         if(show_realpaths) {
528           printf("%s\n", realpath(node1->name, 0));
529         } else {
530           printf("%s\n", node1->name);
531         }
532       }
533     }
534
535   } else {
536     for(node1 = list1; node1; node1 = node1->next) {
537       progress_state.value = nb_nodes;
538       print_progress(&progress_state);
539       nb_nodes++;
540
541       for(node2 = list2; node2; node2 = node2->next) {
542         if(node1->group_id < 0 || node2->group_id < 0) {
543           if(same_files(node1, node2, buffer1, buffer2)) {
544             if(node1->group_id < 0) {
545               if(node2->group_id >= 0) {
546                 node1->group_id = node2->group_id;
547               } else {
548                 node1->group_id = nb_groups;
549                 node1->dir_id = 1;
550                 nb_groups++;
551               }
552             }
553             if(node2->group_id < 0) {
554               node2->group_id = node1->group_id;
555               node2->dir_id = 2;
556             }
557           }
558         }
559       }
560     }
561   }
562
563   if(show_progress) {
564     fprintf(stderr, "\n");
565   }
566
567   if(dirname2) {
568     print_result(list1, list2);
569     file_list_delete(list1);
570     file_list_delete(list2);
571   } else {
572     print_result(list1, 0);
573     file_list_delete(list1);
574   }
575
576   free(buffer1);
577   free(buffer2);
578 }
579
580 void usage(FILE *out) {
581   fprintf(out, "Usage: finddup [OPTION]... [DIR1 [[and:|not:]DIR2]]\n");
582   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
583   fprintf(out, "Without DIR2, lists duplicated files found in DIR1, or the current directory if DIR1 is not provided. 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");
584   fprintf(out, "\n");
585   /*            01234567890123456789012345678901234567890123456789012345678901234567890123456789*/
586   fprintf(out, "   -v, --version              prints the version number and exit\n");
587   fprintf(out, "   -h, --help                 show this help\n");
588   fprintf(out, "   -d, --ignore-dots          ignore dot files and directories\n");
589   fprintf(out, "   -0, --ignore-empty         ignore empty files\n");
590   fprintf(out, "   -c, --hide-matchings       do not show which files in DIR2 corresponds to\n");
591   fprintf(out, "                              those in DIR1\n");
592   fprintf(out, "   -g, --no-group-ids         do not show the file groups\n");
593   fprintf(out, "   -t, --time-sort            sort according to modification time in each group\n");
594   fprintf(out, "   -p, --show-progress        show progress\n");
595   fprintf(out, "   -r, --real-paths           show the real file paths\n");
596   fprintf(out, "   -i, --same-inodes-are-different\n");
597   fprintf(out, "                              consider files with same inode as different\n");
598   fprintf(out, "   -e <command>, --exec <command>\n");
599   fprintf(out, "                              execute the provided command for each group of\n");
600   fprintf(out, "                              identical files, with their names as arguments\n");
601   fprintf(out, "\n");
602   fprintf(out, "Report bugs and comments to <francois@fleuret.org>.\n");
603 }
604
605 /**********************************************************************/
606
607 static struct option long_options[] = {
608   { "version", no_argument, 0, 'v' },
609   { "help", no_argument, 0, 'h' },
610   { "same-inodes-are-different", no_argument, 0, 'i' },
611   { "real-paths", no_argument, 0, 'r' },
612   { "hide-matchings", no_argument, 0, 'c' },
613   { "no-group-ids", no_argument, 0, 'g' },
614   { "time-sort", no_argument, 0, 't' },
615   { "ignore-dots", no_argument, 0, 'd' },
616   { "ignore-empty", no_argument, 0, '0' },
617   { "show-progress", no_argument, 0, 'p' },
618   { "exec", 1, 0, 'e' },
619   { 0, 0, 0, 0 }
620 };
621
622 int main(int argc, char **argv) {
623   int c;
624
625   setlocale (LC_ALL, "");
626
627   while ((c = getopt_long(argc, argv, "vhircgtd0pme:",
628                           long_options, NULL)) != -1) {
629     switch (c) {
630
631     case 'v':
632       printf("finddup version %s (%s)\n", VERSION_NUMBER, UNAME);
633       exit(EXIT_SUCCESS);
634       break;
635
636     case 'h':
637       usage(stdout);
638       exit(EXIT_SUCCESS);
639
640       break;
641
642     case 'd':
643       ignore_dotfiles = 1;
644       break;
645
646     case '0':
647       ignore_empty_files = 1;
648       break;
649
650     case 'r':
651       show_realpaths = 1;
652       break;
653
654     case 'i':
655       same_inodes_are_different = 1;
656       break;
657
658     case 'g':
659       show_groups = 0;
660       break;
661
662     case 't':
663       sort_by_time = 1;
664       break;
665
666     case 'p':
667       show_progress = 1;
668       break;
669
670     case 'c':
671       show_hits = 0;
672       break;
673
674     case 'e':
675       if(command_to_exec != 0) {
676         free(command_to_exec);
677       }
678       command_to_exec = strdup(optarg);
679       break;
680
681     default:
682       usage(stderr);
683       exit(EXIT_FAILURE);
684     }
685   }
686
687   if(!isatty(STDERR_FILENO)) {
688     show_progress = 0;
689   }
690
691   if(optind + 2 == argc) {
692     start(argv[optind], argv[optind + 1]);
693   } else if(optind + 1 == argc) {
694     same_inodes_are_different = 1;
695     start(argv[optind], 0);
696   } else if(optind == argc) {
697     same_inodes_are_different = 1;
698     start(".", 0);
699   } else {
700     usage(stderr);
701     exit(EXIT_FAILURE);
702   }
703
704   exit(EXIT_SUCCESS);
705 }