Brain bug.
[dus.git] / dus.c
1
2 /*
3  *  dus is a simple utility to display the files and directories
4  *  according to their total disk occupancy.
5  *
6  *  Copyright (c) 2010, 2011 Francois Fleuret
7  *  Written by Francois Fleuret <francois@fleuret.org>
8  *
9  *  This file is part of dus.
10  *
11  *  dus is free software: you can redistribute it and/or modify it
12  *  under the terms of the GNU General Public License version 3 as
13  *  published by the Free Software Foundation.
14  *
15  *  dus is distributed in the hope that it will be useful, but WITHOUT
16  *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17  *  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
18  *  License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with dus.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 #define VERSION_NUMBER "1.3"
26
27 #define _DEFAULT_SOURCE
28
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/param.h>
32 #include <dirent.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <unistd.h>
36 #include <errno.h>
37 #include <string.h>
38 #include <sys/ioctl.h>
39 #include <locale.h>
40 #include <getopt.h>
41
42 #define BUFFER_SIZE 4096
43
44 typedef int64_t size_sum_t;
45
46 /* Yeah, global variables! */
47
48 int ignore_dotfiles = 0; /* 1 means ignore files and directories
49                             starting with a dot */
50
51 int forced_width = 0; /* -1 means no width limit, strictly positive
52                          means limit, 0 means not active */
53
54 int forced_height = 0; /* -1 means no height limit, strictly positive
55                            means limit, 0 means not active */
56
57 int fancy_size_display = 0; /* 1 means to use floating values with K, M and G
58                                as units */
59
60 int reverse_sorting = 0; /* 1 means to show the large ones first */
61
62 int show_top = 0; /* 1 means to show the top of the sorted list
63                      instead of the bottom */
64
65 size_sum_t size_min = -1; /* -1 means no minimum size, otherwise lower
66                               bound on the size to display a
67                               file/dir */
68
69 int dont_exit_on_protected_files = 0; /* Should we go on when we meet
70                                          files or directories which
71                                          are protected ? */
72
73 /********************************************************************/
74
75 /* malloc with error checking.  */
76
77 void *safe_malloc(size_t n) {
78   void *p = malloc(n);
79   if (!p && n != 0) {
80     fprintf(stderr,
81             "dus: Can not allocate memory: %s\n",
82             strerror(errno));
83     exit(EXIT_FAILURE);
84   }
85   return p;
86 }
87
88 /********************************************************************/
89
90 int ignore_entry(const char *name) {
91   return
92     strcmp(name, ".") == 0 ||
93     strcmp(name, "..") == 0 ||
94     (ignore_dotfiles && name[0] == '.' && name[1] != '/');
95 }
96
97 size_sum_t entry_size(const char *name, int *isdir) {
98   DIR *dir;
99   struct dirent *dir_e;
100   struct stat dummy;
101   size_sum_t result;
102   char subname[PATH_MAX];
103
104   result = 0;
105   if(isdir) { *isdir = 0; }
106
107   if(lstat(name, &dummy) != 0) {
108     fprintf(stderr,
109             "dus: Can not stat %s: %s\n",
110             name, strerror(errno));
111     if(!(errno == EACCES && dont_exit_on_protected_files)) {
112       exit(EXIT_FAILURE);
113     } else {
114       return 0;
115     }
116   }
117
118   if(S_ISLNK(dummy.st_mode)) {
119     return 0;
120   }
121
122   if(S_ISDIR(dummy.st_mode)) {
123     if(isdir) { *isdir = 1; }
124     dir = opendir(name);
125     if(dir) {
126       while((dir_e = readdir(dir))) {
127         if(!ignore_entry(dir_e->d_name)) {
128           snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
129           result += entry_size(subname, 0);
130         }
131       }
132       closedir(dir);
133     } else {
134       fprintf(stderr,
135               "dus: Can not open directory %s: %s\n",
136               name, strerror(errno));
137       if(!(errno == EACCES && dont_exit_on_protected_files)) {
138         exit(EXIT_FAILURE);
139       }
140     }
141   } else if(S_ISREG(dummy.st_mode)) {
142     result += dummy.st_size;
143   }
144
145   return result;
146 }
147
148 size_sum_t atoss(const char *string) {
149   size_sum_t total, partial_total;
150   const char *c;
151   total = 0;
152   partial_total = 0;
153
154   for(c = string; *c; c++) {
155     if(*c >= '0' && *c <= '9') {
156       partial_total = 10 * partial_total + ((int) (*c - '0'));
157     } else if(*c == 'B' || *c == 'b') {
158       total += partial_total;
159       partial_total = 0;
160     } else if(*c == 'K' || *c == 'k') {
161       total += partial_total * 1024;
162       partial_total = 0;
163     } else if(*c == 'M' || *c == 'm') {
164       total += partial_total * 1024 * 1024;
165       partial_total = 0;
166     } else if(*c == 'G' || *c == 'g') {
167       total += partial_total * 1024 * 1024 * 1024;
168       partial_total = 0;
169     } else {
170       fprintf(stderr,
171               "dus: Syntax error in size specification `%s'\n",
172               string);
173       exit(EXIT_FAILURE);
174     }
175   }
176
177   total += partial_total;
178
179   return total;
180 }
181
182 /**********************************************************************/
183
184 struct entry_node {
185   struct entry_node *next;
186   char *name;
187   size_sum_t size;
188 };
189
190 struct entry_node *push_entry(char *name, struct entry_node *head) {
191   char tmp_name[PATH_MAX];
192   struct entry_node *result;
193   int isdir;
194   result = safe_malloc(sizeof(struct entry_node));
195   result->size = entry_size(name, &isdir);
196   if(isdir) {
197     snprintf(tmp_name, PATH_MAX, "%s/", name);
198     result->name = strdup(tmp_name);
199   } else {
200     result->name = strdup(name);
201   }
202   result->next = head;
203   return result;
204 }
205
206 struct entry_node *push_dir_content(char *name, struct entry_node *head) {
207   char subname[PATH_MAX];
208   DIR *dir;
209   struct dirent *dir_e;
210   dir = opendir(name);
211   if(dir) {
212     while((dir_e = readdir(dir))) {
213       if(!ignore_entry(dir_e->d_name)) {
214         snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
215         head = push_entry(subname, head);
216       }
217     }
218     closedir(dir);
219   } else {
220     fprintf(stderr,
221             "dus: Can not open directory %s: %s\n",
222             name, strerror(errno));
223     exit (EXIT_FAILURE);
224   }
225   return head;
226 }
227
228 void destroy_entry_list(struct entry_node *node) {
229   struct entry_node *next;
230   while(node) {
231     next = node->next;
232     free(node->name);
233     free(node);
234     node = next;
235   }
236 }
237
238 /**********************************************************************/
239
240 int compare_files(const void *x1, const void *x2) {
241   const struct entry_node **f1, **f2;
242
243   f1 = (const struct entry_node **) x1;
244   f2 = (const struct entry_node **) x2;
245
246   if(reverse_sorting) {
247     if((*f1)->size < (*f2)->size) {
248       return 1;
249     } else if((*f1)->size > (*f2)->size) {
250       return -1;
251     } else {
252       return 0;
253     }
254   } else {
255     if((*f1)->size < (*f2)->size) {
256       return -1;
257     } else if((*f1)->size > (*f2)->size) {
258       return 1;
259     } else {
260       return 0;
261     }
262   }
263 }
264
265 void raw_print(char *buffer, size_t buffer_size,
266                char *filename,  size_sum_t size) {
267   char *a, *b, *c, u;
268
269   b = buffer;
270   do {
271     if(b >= buffer + buffer_size) {
272       fprintf(stderr,
273               "dus: Buffer overflow in raw_print (hu?!).\n");
274       exit(EXIT_FAILURE);
275     }
276     *(b++) = size%10 + '0';
277     size /= 10;
278   } while(size);
279
280   a = buffer;
281   c = b;
282   while(a < c) {
283     u = *a;
284     *(a++) = *(--c);
285     *c = u;
286   }
287
288   *(b++) = ' ';
289
290   snprintf(b, buffer_size - (b - buffer), "%s\n", filename);
291 }
292
293 void fancy_print(char *buffer, size_t buffer_size,
294                  char *filename, size_sum_t size) {
295   if(size < 1024) {
296     snprintf(buffer,
297              buffer_size,
298              "% 8d %s\n",
299              ((int) size),
300              filename);
301   } else if(size < 1024 * 1024) {
302     snprintf(buffer,
303              buffer_size,
304              "% 7.1fK %s\n",
305              ((double) (size))/(1024.0),
306              filename);
307   } else if(size < 1024 * 1024 * 1024) {
308     snprintf(buffer,
309              buffer_size,
310              "% 7.1fM %s\n",
311              ((double) (size))/(1024.0 * 1024),
312              filename);
313   } else {
314     snprintf(buffer,
315              buffer_size,
316              "% 7.1fG %s\n",
317              ((double) (size))/(1024.0 * 1024.0 * 1024.0),
318              filename);
319   }
320 }
321
322 void print_sorted(struct entry_node *root, int width, int height) {
323   char line[BUFFER_SIZE];
324   struct entry_node *node;
325   struct entry_node **nodes;
326   int nb_nodes, n, first, last;
327
328   nb_nodes = 0;
329   for(node = root; node; node = node->next) {
330     if(size_min < 0 || node->size >= size_min) {
331       nb_nodes++;
332     }
333   }
334
335   nodes = safe_malloc(nb_nodes * sizeof(struct entry_node *));
336
337   n = 0;
338   for(node = root; node; node = node->next) {
339     if(size_min < 0 || node->size >= size_min) {
340       nodes[n++] = node;
341     }
342   }
343
344   qsort(nodes, nb_nodes, sizeof(struct entry_node *), compare_files);
345
346   first = 0;
347   last = nb_nodes;
348
349   if(forced_height) {
350     height = forced_height;
351   }
352
353   if(forced_width) {
354     width = forced_width;
355   }
356
357   if(height >= 0 && nb_nodes > height && !show_top && !forced_height) {
358     printf("...\n");
359   }
360
361   if(height > 0 && height < nb_nodes) {
362     first = nb_nodes - height;
363   }
364
365   if(show_top) {
366     n = last;
367     last = nb_nodes - first;
368     first = nb_nodes - n;
369   }
370
371   /* I do not like valgrind to complain about uninitialized data */
372   if(width < BUFFER_SIZE) {
373     line[width] = '\0';
374   }
375
376   for(n = first; n < last; n++) {
377     if(fancy_size_display) {
378       fancy_print(line, BUFFER_SIZE, nodes[n]->name, nodes[n]->size);
379     } else {
380       raw_print(line, BUFFER_SIZE, nodes[n]->name, nodes[n]->size);
381     }
382     if(width >= 1 && width + 1 < BUFFER_SIZE && line[width]) {
383       line[width] = '\n';
384       line[width + 1] = '\0';
385     }
386     printf("%s", line);
387   }
388
389   if(height >= 0 && nb_nodes > height && show_top && !forced_height) {
390     printf("...\n");
391   }
392
393   free(nodes);
394 }
395
396 /**********************************************************************/
397
398 void usage(FILE *out) {
399   fprintf(out, "Usage: dus [OPTION]... [FILE]...\n");
400   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
401   fprintf(out, "Lists files and directories according to their size. The sizes are computed by summing recursively exact file sizes through directories. If a given directory has its name appended with '/', it is not listed, but the elements it contains are. If no files or directories are provided as arguments, the current directory is used as default.\n");
402   fprintf(out, "\n");
403   /*            01234567890123456789012345678901234567890123456789012345678901234567890123456789*/
404   fprintf(out, "   -h, --help                 show this help.\n");
405   fprintf(out, "   -v, --version              prints the version number and exit\n");
406   fprintf(out, "   -d, --ignore-dots          ignore files and directories starting with a '.'\n");
407   fprintf(out, "   -i, --ignore-protected     do not exit when visiting files and directories\n");
408   fprintf(out, "                              for which we do not have permission\n");
409   fprintf(out, "   -f, --fancy                display size with float values and K, M and G\n");
410   fprintf(out, "                              units.\n");
411   fprintf(out, "   -r, --reverse-order        reverse the sorting order.\n");
412   fprintf(out, "   -t, --show-top             show the top of the list.\n");
413   fprintf(out, "   -c <cols>, --nb-columns <cols>\n");
414   fprintf(out, "                              specificy the number of columns to display. The\n");
415   fprintf(out, "                              value -1 corresponds to no constraint. By default\n");
416   fprintf(out, "                              the command uses the tty width, or no constraint\n");
417   fprintf(out, "                              if the stdout is not a tty.\n");
418   fprintf(out, "   -l <lines>, --nb-lines <lines>\n");
419   fprintf(out, "                              same as -c for number of lines.\n");
420   fprintf(out, "   -m <size>, --size-min <size>\n");
421   fprintf(out, "                              set the listed entries minimum size. The size\n");
422   fprintf(out, "                              can be specified using the G, M, K, and B units.\n");
423   fprintf(out, "\n");
424   fprintf(out, "Report bugs and comments to <francois@fleuret.org>.\n");
425 }
426
427 /**********************************************************************/
428
429 static struct option long_options[] = {
430   { "version", no_argument, 0, 'v' },
431   { "ignore-dots", no_argument, 0, 'd' },
432   { "ignore-protected", no_argument, 0, 'i' },
433   { "reverse-order", no_argument, 0, 'r' },
434   { "show-top", no_argument, 0, 't' },
435   { "help", no_argument, 0, 'h' },
436   { "fancy", no_argument, 0, 'f' },
437   { "nb-columns", 1, 0, 'c' },
438   { "nb-lines", 1, 0, 'l' },
439   { "size-min", 1, 0, 'm' },
440   { 0, 0, 0, 0 }
441 };
442
443 int main(int argc, char **argv) {
444   int c, l;
445   struct entry_node *root;
446   struct winsize win;
447
448   root = 0;
449
450   setlocale (LC_ALL, "");
451
452   while ((c = getopt_long(argc, argv, "ivdfrtl:c:m:hd",
453                           long_options, NULL)) != -1) {
454     switch (c) {
455
456     case 'v':
457       printf("dus version %s (%s)\n", VERSION_NUMBER, UNAME);
458       exit(EXIT_SUCCESS);
459       break;
460
461     case 'd':
462       ignore_dotfiles = 1;
463       break;
464
465     case 'i':
466       dont_exit_on_protected_files = 1;
467       break;
468
469     case 'f':
470       fancy_size_display = 1;
471       break;
472
473     case 'r':
474       reverse_sorting = 1;
475       break;
476
477     case 't':
478       show_top = 1;
479       break;
480
481     case 'l':
482       forced_height = atoi(optarg);
483       break;
484
485     case 'c':
486       forced_width = atoi(optarg);
487       break;
488
489     case 'm':
490       size_min = atoss(optarg);
491       break;
492
493     case 'h':
494       usage(stdout);
495       exit(EXIT_SUCCESS);
496
497       break;
498
499     default:
500       usage(stderr);
501       exit(EXIT_FAILURE);
502     }
503   }
504
505   if (optind < argc) {
506     while (optind < argc) {
507       l = strlen(argv[optind]);
508       if(l > 0 && argv[optind][l - 1] == '/') {
509         argv[optind][l - 1] = '\0';
510         root = push_dir_content(argv[optind++], root);
511       } else {
512         root = push_entry(argv[optind++], root);
513       }
514     }
515   } else {
516     root = push_dir_content(".", root);
517   }
518
519   if(isatty(STDOUT_FILENO) &&
520      !ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
521     print_sorted(root, win.ws_col, win.ws_row - 2);
522   } else {
523     print_sorted(root, -1, -1);
524   }
525
526   destroy_entry_list(root);
527
528   exit(EXIT_SUCCESS);
529 }