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