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