Cosmetics (variable name changes).
[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.6"
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 typedef int64_t size_sum_t;
48
49 /* Yeah, global variables! */
50
51 int ignore_dotfiles = 0; /* 1 means ignore files and directories
52                             starting with a dot */
53
54 int ignore_empty_files = 0; /* 1 means ignore empty files */
55
56 int show_realpaths = 0; /* 1 means ignore files and directories
57                             starting with a dot */
58
59 int show_progress = 0; /* 1 means show a progress bar when we are in a
60                           tty */
61
62 int show_hits = 1; /* 1 means to show the files from dir2
63                       corresponding to the ones from dir1 */
64
65 int show_groups = 1; /* 1 means to show the group IDs when printing
66                         file names */
67
68 int ignore_same_inode = 0; /* 1 means that comparison between two file
69                               with same inode will always be false */
70
71 int tty_width = -1; /* Positive value means what width to use to show
72                        the progress bar */
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] == '.');
94 }
95
96 void print_size_sum(size_sum_t s) {
97   char tmp[100];
98   char *a = tmp + sizeof(tmp)/sizeof(char);
99   *(--a) = '\0';
100   if(s) {
101     while(s) {
102       *(--a) = s%10 + '0';
103       s /= 10;
104     }
105   } else {
106     *(--a) = '0';
107   }
108   printf(a);
109 }
110
111 /**********************************************************************/
112
113 struct file_with_size {
114   char *filename;
115   size_t size;
116   ino_t inode;
117   struct file_with_size *next;
118   int group_id, dir_id;
119 };
120
121 void file_list_delete(struct file_with_size *head) {
122   struct file_with_size *next;
123   while(head) {
124     next = head->next;
125     free(head->filename);
126     free(head);
127     head = next;
128   }
129 }
130
131 int file_list_length(struct file_with_size *head) {
132   int l = 0;
133   while(head) {
134     l++;
135     head = head->next;
136   }
137   return l;
138 }
139
140 /**********************************************************************/
141
142 int same_content(struct file_with_size *f1, struct file_with_size *f2,
143                  char *buffer1, char *buffer2) {
144   int fd1, fd2, s1, s2;
145
146   fd1 = open(f1->filename, O_RDONLY);
147   fd2 = open(f2->filename, O_RDONLY);
148
149   if(fd1 >= 0 && fd2 >= 0) {
150     while(1) {
151       s1 = read(fd1, buffer1, READ_BUFFER_SIZE);
152       s2 = read(fd2, buffer2, READ_BUFFER_SIZE);
153
154       if(s1 < 0 || s2 < 0) {
155         close(fd1);
156         close(fd2);
157         return 0;
158       }
159
160       if(s1 == s2) {
161         if(s1 == 0) {
162           close(fd1);
163           close(fd2);
164           return 1;
165         } else {
166           if(memcmp(buffer1, buffer2, s1)) {
167             close(fd1);
168             close(fd2);
169             return 0;
170           }
171         }
172       } else {
173         fprintf(stderr,
174                 "Different read size without error on files of same size.\n");
175         exit(EXIT_FAILURE);
176       }
177     }
178   } else {
179
180     if(fd1 < 0) {
181       fprintf(stderr,
182               "Can not open \"%s\" error: %s\n",
183               f1->filename,
184               strerror(errno));
185     }
186
187     if(fd2 < 0) {
188       fprintf(stderr,
189               "Can not open \"%s\" error: %s\n",
190               f2->filename,
191               strerror(errno));
192     }
193     exit(EXIT_FAILURE);
194   }
195 }
196
197 int same_files(struct file_with_size *f1, struct file_with_size *f2,
198                char *buffer1, char *buffer2) {
199   if(ignore_same_inode && f1->inode == f2->inode) {
200     return 0;
201   }
202   return f1->size == f2->size && same_content(f1, f2, buffer1, buffer2);
203 }
204
205 /**********************************************************************/
206
207 struct file_with_size *scan_directory(struct file_with_size *tail,
208                                       const char *name) {
209   DIR *dir;
210   struct dirent *dir_e;
211   struct stat sb;
212   struct file_with_size *tmp;
213   char subname[PATH_MAX + 1];
214
215   if(lstat(name, &sb) != 0) {
216     fprintf(stderr, "Can not stat \"%s\": %s\n", name, strerror(errno));
217     exit(EXIT_FAILURE);
218   }
219
220   if(S_ISLNK(sb.st_mode)) {
221     return tail;
222   }
223
224   dir = opendir(name);
225
226   if(dir) {
227     while((dir_e = readdir(dir))) {
228       if(!ignore_entry(dir_e->d_name)) {
229         snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
230         tail = scan_directory(tail, subname);
231       }
232     }
233     closedir(dir);
234   } else {
235     if(S_ISREG(sb.st_mode)) {
236       if(!ignore_entry(name)) {
237         if(!ignore_empty_files || sb.st_size > 0) {
238           tmp = safe_malloc(sizeof(struct file_with_size));
239           tmp->next = tail;
240           tmp->filename = strdup(name);
241           tmp->size = sb.st_size;
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 void print_file(struct file_with_size *node) {
255   char tmp[PATH_MAX + 1];
256   if(show_realpaths) {
257     if(show_groups) {
258       realpath(node->filename, tmp);
259       printf("%d %s\n", node->group_id, tmp);
260     } else {
261       realpath(node->filename, tmp);
262       printf("%s\n", tmp);
263     }
264   } else {
265     if(show_groups) {
266       printf("%d %s\n", node->group_id, node->filename);
267     } else {
268       printf("%s\n", node->filename);
269     }
270   }
271 }
272
273 int compare_nodes(const void *x1, const void *x2) {
274   const struct file_with_size **f1, **f2;
275
276   f1 = (const struct file_with_size **) x1;
277   f2 = (const struct file_with_size **) 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((*f1)->dir_id < (*f2)->dir_id) {
285       return -1;
286     } else if((*f1)->dir_id > (*f2)->dir_id) {
287       return 1;
288     } else {
289       return 0;
290     }
291   }
292 }
293
294
295 void print_result(struct file_with_size *list1, struct file_with_size *list2) {
296   struct file_with_size *node1, *node2;
297   struct file_with_size **nodes;
298   int nb, n;
299
300   nb = 0;
301   for(node1 = list1; node1; node1 = node1->next) {
302     if(node1->group_id >= 0) { nb++; }
303   }
304
305   if(list2) {
306     for(node2 = list2; node2; node2 = node2->next) {
307       if(node2->group_id >= 0) { nb++; }
308     }
309   }
310
311   nodes = safe_malloc(nb * sizeof(struct file_with_size *));
312
313   n = 0;
314   for(node1 = list1; node1; node1 = node1->next) {
315     if(node1->group_id >= 0) {
316       nodes[n++] = node1;
317     }
318   }
319
320   if(list2) {
321     for(node2 = list2; node2; node2 = node2->next) {
322       if(node2->group_id >= 0) {
323         nodes[n++] = node2;
324       }
325     }
326   }
327
328   qsort(nodes, nb, sizeof(struct file_with_size *), compare_nodes);
329
330   for(n = 0; n < nb; n++) {
331     if(!show_groups && n > 0 && nodes[n]->group_id != nodes[n-1]->group_id) {
332       printf("\n");
333     }
334     print_file(nodes[n]);
335   }
336
337   free(nodes);
338 }
339
340 void print_progress(int max, int n, int *pp) {
341   int p, k;
342   int width;
343   if(show_progress && tty_width > 0) {
344     width = tty_width - 7;
345     p = (width * n) / (max - 1);
346     if(p > *pp) {
347       for(k = 0; k < p; k++) {
348         fprintf(stderr, "+");
349       }
350       for(; k < width; k++) {
351         fprintf(stderr, "-");
352       }
353       *pp = p;
354       p = (100 * n) / (max - 1);
355       fprintf(stderr, " [%3d%%]\r", p);
356     }
357   }
358 }
359
360 void start(const char *dirname1, const char *dirname2) {
361   struct file_with_size *list1, *list2;
362   struct file_with_size *node1, *node2;
363   int not_in, found;
364   int nb_groups, nb_nodes;
365   int list1_length, previous_progress;
366
367   char *buffer1 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
368   char *buffer2 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
369
370   not_in = 0;
371
372   if(show_progress) {
373     fprintf(stderr, "Scanning %s ... ", dirname1);
374   }
375
376   list1 = scan_directory(0, dirname1);
377
378   if(dirname2) {
379     if(strncmp(dirname2, "not:", 4) == 0) {
380       not_in = 1;
381       /* groups are not computed in the not: mode */
382       show_groups = 0;
383       dirname2 += 4;
384     } else if(strncmp(dirname2, "and:", 4) == 0) {
385       dirname2 += 4;
386     }
387     if(show_progress) {
388       fprintf(stderr, "%s ... ", dirname2);
389     }
390     list2 = scan_directory(0, dirname2);
391   } else {
392     list2 = list1;
393   }
394
395   if(show_progress) {
396     fprintf(stderr, "done.\n");
397   }
398
399   nb_groups = 0;
400   previous_progress = -1;
401   nb_nodes = 0;
402   list1_length = file_list_length(list1);
403
404   if(not_in) {
405     for(node1 = list1; node1; node1 = node1->next) {
406       print_progress(list1_length, nb_nodes, &previous_progress);
407       nb_nodes++;
408
409       found = 0;
410
411       for(node2 = list2; !found && node2; node2 = node2->next) {
412         if(same_files(node1, node2, buffer1, buffer2)) {
413           found = 1;
414         }
415       }
416
417       if(!found) {
418         if(show_realpaths) {
419           printf("%s\n", realpath(node1->filename, 0));
420         } else {
421           printf("%s\n", node1->filename);
422         }
423       }
424     }
425
426   } else {
427     for(node1 = list1; node1; node1 = node1->next) {
428       print_progress(list1_length, nb_nodes, &previous_progress);
429       nb_nodes++;
430
431       for(node2 = list2; node2; node2 = node2->next) {
432         if(node1->group_id < 0 || node2->group_id < 0) {
433           if(same_files(node1, node2, buffer1, buffer2)) {
434             if(node1->group_id < 0) {
435               if(node2->group_id >= 0) {
436                 node1->group_id = node2->group_id;
437               } else {
438                 node1->group_id = nb_groups;
439                 node1->dir_id = 1;
440                 nb_groups++;
441               }
442             }
443             if(node2->group_id < 0) {
444               node2->group_id = node1->group_id;
445               node2->dir_id = 2;
446             }
447           }
448         }
449       }
450     }
451   }
452
453   if(show_progress) {
454     fprintf(stderr, "\n");
455   }
456
457   if(dirname2) {
458     print_result(list1, list2);
459     file_list_delete(list1);
460     file_list_delete(list2);
461   } else {
462     print_result(list1, 0);
463     file_list_delete(list1);
464   }
465
466   free(buffer1);
467   free(buffer2);
468 }
469
470 void print_help(FILE *out) {
471   fprintf(out, "Usage: finddup [OPTION]... DIR1 [[and:|not:]DIR2]\n");
472   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
473   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");
474   fprintf(out, "\n");
475   fprintf(out, "   -h   show this help\n");
476   fprintf(out, "   -d   ignore dot files and directories\n");
477   fprintf(out, "   -0   ignore empty files\n");
478   fprintf(out, "   -c   do not show which files in DIR2 corresponds to those in DIR1\n");
479   fprintf(out, "   -g   do not show the file groups\n");
480   fprintf(out, "   -p   show progress\n");
481   fprintf(out, "   -r   show the real file paths\n");
482   fprintf(out, "   -i   consider files with same inode as different\n");
483   fprintf(out, "\n");
484   fprintf(out, "Report bugs and comments to <francois@fleuret.org>\n");
485 }
486
487 /**********************************************************************/
488
489 int main(int argc, char **argv) {
490   int c;
491   struct file_with_size *root;
492   struct winsize win;
493
494   root = 0;
495
496   setlocale (LC_ALL, "");
497
498   while (1) {
499     c = getopt(argc, argv, "hircgd0p");
500     if (c == -1)
501       break;
502
503     switch (c) {
504
505     case 'h':
506       print_help(stdout);
507       exit(EXIT_SUCCESS);
508
509       break;
510
511     case 'd':
512       ignore_dotfiles = 1;
513       break;
514
515     case '0':
516       ignore_empty_files = 1;
517       break;
518
519     case 'r':
520       show_realpaths = 1;
521       break;
522
523     case 'i':
524       ignore_same_inode = 1;
525       break;
526
527     case 'g':
528       show_groups = 0;
529       break;
530
531     case 'p':
532       show_progress = 1;
533       break;
534
535     case 'c':
536       show_hits = 0;
537       break;
538
539     default:
540       exit(EXIT_FAILURE);
541     }
542   }
543
544   if(show_progress &&
545      isatty(STDOUT_FILENO) &&
546      !ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
547     tty_width = win.ws_col;
548   }
549
550   if(optind + 2 == argc) {
551     start(argv[optind], argv[optind + 1]);
552   } else if(optind + 1 == argc) {
553     ignore_same_inode = 1;
554     start(argv[optind], 0);
555   } else {
556     print_help(stderr);
557     exit(EXIT_FAILURE);
558   }
559
560   exit(EXIT_SUCCESS);
561 }