Fixed the permission denied with the -i option on lstat().
[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 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.2"
26
27 #define _BSD_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 ignore_protected_files = 0; /* Should we simply ignore files or
70                                    directories which are protected
71                                    ? */
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) {
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
106   if(lstat(name, &dummy) != 0) {
107     if(!(errno == EACCES && ignore_protected_files)) {
108       fprintf(stderr,
109               "dus: Can not stat %s: %s\n",
110               name, strerror(errno));
111       exit(EXIT_FAILURE);
112     } else {
113       return 0;
114     }
115   }
116
117   if(S_ISLNK(dummy.st_mode)) {
118     return 0;
119   }
120
121   if(S_ISDIR(dummy.st_mode)) {
122     dir = opendir(name);
123     if(dir) {
124       while((dir_e = readdir(dir))) {
125         if(!ignore_entry(dir_e->d_name)) {
126           snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
127           result += entry_size(subname);
128         }
129       }
130       closedir(dir);
131     } else {
132       if(!(errno == EACCES && ignore_protected_files)) {
133         fprintf(stderr,
134                 "dus: Can not open directory %s: %s\n",
135                 name, strerror(errno));
136         exit(EXIT_FAILURE);
137       }
138     }
139   } else if(S_ISREG(dummy.st_mode)) {
140     result += dummy.st_size;
141   }
142
143   return result;
144 }
145
146 size_sum_t atoss(const char *string) {
147   size_sum_t total, partial_total;
148   const char *c;
149   total = 0;
150   partial_total = 0;
151
152   for(c = string; *c; c++) {
153     if(*c >= '0' && *c <= '9') {
154       partial_total = 10 * partial_total + ((int) (*c - '0'));
155     } else if(*c == 'B' || *c == 'b') {
156       total += partial_total;
157       partial_total = 0;
158     } else if(*c == 'K' || *c == 'k') {
159       total += partial_total * 1024;
160       partial_total = 0;
161     } else if(*c == 'M' || *c == 'm') {
162       total += partial_total * 1024 * 1024;
163       partial_total = 0;
164     } else if(*c == 'G' || *c == 'g') {
165       total += partial_total * 1024 * 1024 * 1024;
166       partial_total = 0;
167     } else {
168       fprintf(stderr,
169               "dus: Syntax error in size specification `%s'\n",
170               string);
171       exit(EXIT_FAILURE);
172     }
173   }
174
175   total += partial_total;
176
177   return total;
178 }
179
180 /**********************************************************************/
181
182 struct entry_node {
183   struct entry_node *next;
184   char *name;
185   size_sum_t size;
186 };
187
188 struct entry_node *push_entry(char *name, struct entry_node *head) {
189   struct entry_node *result;
190   result = safe_malloc(sizeof(struct entry_node));
191   result->name = strdup(name);
192   result->size = entry_size(name);
193   result->next = head;
194   return result;
195 }
196
197 struct entry_node *push_dir_content(char *name, struct entry_node *head) {
198   char subname[PATH_MAX];
199   DIR *dir;
200   struct dirent *dir_e;
201   dir = opendir(name);
202   if(dir) {
203     while((dir_e = readdir(dir))) {
204       if(!ignore_entry(dir_e->d_name)) {
205         snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
206         head = push_entry(subname, head);
207       }
208     }
209     closedir(dir);
210   } else {
211     fprintf(stderr,
212             "dus: Can not open directory %s: %s\n",
213             name, strerror(errno));
214     exit (EXIT_FAILURE);
215   }
216   return head;
217 }
218
219 void destroy_entry_list(struct entry_node *node) {
220   struct entry_node *next;
221   while(node) {
222     next = node->next;
223     free(node->name);
224     free(node);
225     node = next;
226   }
227 }
228
229 /**********************************************************************/
230
231 int compare_files(const void *x1, const void *x2) {
232   const struct entry_node **f1, **f2;
233
234   f1 = (const struct entry_node **) x1;
235   f2 = (const struct entry_node **) x2;
236
237   if(reverse_sorting) {
238     if((*f1)->size < (*f2)->size) {
239       return 1;
240     } else if((*f1)->size > (*f2)->size) {
241       return -1;
242     } else {
243       return 0;
244     }
245   } else {
246     if((*f1)->size < (*f2)->size) {
247       return -1;
248     } else if((*f1)->size > (*f2)->size) {
249       return 1;
250     } else {
251       return 0;
252     }
253   }
254 }
255
256 void raw_print(char *buffer, size_t buffer_size,
257                char *filename,  size_sum_t size) {
258   char *a, *b, *c, u;
259
260   b = buffer;
261   do {
262     if(b >= buffer + buffer_size) {
263       fprintf(stderr,
264               "dus: Buffer overflow in raw_print (hu?!).\n");
265       exit(EXIT_FAILURE);
266     }
267     *(b++) = size%10 + '0';
268     size /= 10;
269   } while(size);
270
271   a = buffer;
272   c = b;
273   while(a < c) {
274     u = *a;
275     *(a++) = *(--c);
276     *c = u;
277   }
278
279   *(b++) = ' ';
280
281   snprintf(b, buffer_size - (b - buffer), "%s\n", filename);
282 }
283
284 void fancy_print(char *buffer, size_t buffer_size,
285                  char *filename, size_sum_t size) {
286   if(size < 1024) {
287     snprintf(buffer,
288              buffer_size,
289              "% 8d -- %s\n",
290              ((int) size),
291              filename);
292   } else if(size < 1024 * 1024) {
293     snprintf(buffer,
294              buffer_size,
295              "% 7.1fK -- %s\n",
296              ((double) (size))/(1024.0),
297              filename);
298   } else if(size < 1024 * 1024 * 1024) {
299     snprintf(buffer,
300              buffer_size,
301              "% 7.1fM -- %s\n",
302              ((double) (size))/(1024.0 * 1024),
303              filename);
304   } else {
305     snprintf(buffer,
306              buffer_size,
307              "% 7.1fG -- %s\n",
308              ((double) (size))/(1024.0 * 1024.0 * 1024.0),
309              filename);
310   }
311 }
312
313 void print_sorted(struct entry_node *root, int width, int height) {
314   char line[BUFFER_SIZE];
315   struct entry_node *node;
316   struct entry_node **nodes;
317   int nb_nodes, n, first, last;
318
319   nb_nodes = 0;
320   for(node = root; node; node = node->next) {
321     if(size_min < 0 || node->size >= size_min) {
322       nb_nodes++;
323     }
324   }
325
326   nodes = safe_malloc(nb_nodes * sizeof(struct entry_node *));
327
328   n = 0;
329   for(node = root; node; node = node->next) {
330     if(size_min < 0 || node->size >= size_min) {
331       nodes[n++] = node;
332     }
333   }
334
335   qsort(nodes, nb_nodes, sizeof(struct entry_node *), compare_files);
336
337   first = 0;
338   last = nb_nodes;
339
340   if(forced_height) {
341     height = forced_height;
342   }
343
344   if(forced_width) {
345     width = forced_width;
346   }
347
348   if(height >= 0 && nb_nodes > height && !show_top && !forced_height) {
349     printf("...\n");
350   }
351
352   if(height > 0 && height < nb_nodes) {
353     first = nb_nodes - height;
354   }
355
356   if(show_top) {
357     n = last;
358     last = nb_nodes - first;
359     first = nb_nodes - n;
360   }
361
362   /* I do not like valgrind to complain about uninitialized data */
363   if(width < BUFFER_SIZE) {
364     line[width] = '\0';
365   }
366
367   for(n = first; n < last; n++) {
368     if(fancy_size_display) {
369       fancy_print(line, BUFFER_SIZE, nodes[n]->name, nodes[n]->size);
370     } else {
371       raw_print(line, BUFFER_SIZE, nodes[n]->name, nodes[n]->size);
372     }
373     if(width >= 1 && width + 1 < BUFFER_SIZE && line[width]) {
374       line[width] = '\n';
375       line[width + 1] = '\0';
376     }
377     printf(line);
378   }
379
380   if(height >= 0 && nb_nodes > height && show_top && !forced_height) {
381     printf("...\n");
382   }
383
384   free(nodes);
385 }
386
387 /**********************************************************************/
388
389 void usage(FILE *out) {
390   fprintf(out, "Usage: dus [OPTION]... [FILE]...\n");
391   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
392   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");
393   fprintf(out, "\n");
394   /*            01234567890123456789012345678901234567890123456789012345678901234567890123456789*/
395   fprintf(out, "   -h, --help                 show this help.\n");
396   fprintf(out, "   -v, --version              prints the version number and exit\n");
397   fprintf(out, "   -d, --ignore-dots          ignore files and directories starting with a '.'\n");
398   fprintf(out, "   -i, --ignore-protected     ignore files and directories for which we do not\n");
399   fprintf(out, "                              have permission\n");
400   fprintf(out, "   -f, --fancy                display size with float values and K, M and G\n");
401   fprintf(out, "                              units.\n");
402   fprintf(out, "   -r, --reverse-order        reverse the sorting order.\n");
403   fprintf(out, "   -t, --show-top             show the top of the list.\n");
404   fprintf(out, "   -c <cols>, --nb-columns <cols>\n");
405   fprintf(out, "                              specificy the number of columns to display. The\n");
406   fprintf(out, "                              value -1 corresponds to no constraint. By default\n");
407   fprintf(out, "                              the command uses the tty width, or no constraint\n");
408   fprintf(out, "                              if the stdout is not a tty.\n");
409   fprintf(out, "   -l <lines>, --nb-lines <lines>\n");
410   fprintf(out, "                              same as -c for number of lines.\n");
411   fprintf(out, "   -m <size>, --size-min <size>\n");
412   fprintf(out, "                              set the listed entries minimum size. The size\n");
413   fprintf(out, "                              can be specified using the G, M, K, and B units.\n");
414   fprintf(out, "\n");
415   fprintf(out, "Report bugs and comments to <francois@fleuret.org>.\n");
416 }
417
418 /**********************************************************************/
419
420 static struct option long_options[] = {
421   { "version", no_argument, 0, 'v' },
422   { "ignore-dots", no_argument, 0, 'd' },
423   { "ignore-protected", no_argument, 0, 'i' },
424   { "reverse-order", no_argument, 0, 'r' },
425   { "show-top", no_argument, 0, 't' },
426   { "help", no_argument, 0, 'h' },
427   { "fancy", no_argument, 0, 'f' },
428   { "nb-columns", 1, 0, 'c' },
429   { "nb-lines", 1, 0, 'l' },
430   { "size-min", 1, 0, 'm' },
431   { 0, 0, 0, 0 }
432 };
433
434 int main(int argc, char **argv) {
435   int c, l;
436   struct entry_node *root;
437   struct winsize win;
438
439   root = 0;
440
441   setlocale (LC_ALL, "");
442
443   while ((c = getopt_long(argc, argv, "ivdfrtl:c:m:hd",
444                           long_options, NULL)) != -1) {
445     switch (c) {
446
447     case 'v':
448       printf("dus version %s (%s)\n", VERSION_NUMBER, UNAME);
449       exit(EXIT_SUCCESS);
450       break;
451
452     case 'd':
453       ignore_dotfiles = 1;
454       break;
455
456     case 'i':
457       ignore_protected_files = 1;
458       break;
459
460     case 'f':
461       fancy_size_display = 1;
462       break;
463
464     case 'r':
465       reverse_sorting = 1;
466       break;
467
468     case 't':
469       show_top = 1;
470       break;
471
472     case 'l':
473       forced_height = atoi(optarg);
474       break;
475
476     case 'c':
477       forced_width = atoi(optarg);
478       break;
479
480     case 'm':
481       size_min = atoss(optarg);
482       break;
483
484     case 'h':
485       usage(stdout);
486       exit(EXIT_SUCCESS);
487
488       break;
489
490     default:
491       usage(stderr);
492       exit(EXIT_FAILURE);
493     }
494   }
495
496   if (optind < argc) {
497     while (optind < argc) {
498       l = strlen(argv[optind]);
499       if(l > 0 && argv[optind][l - 1] == '/') {
500         argv[optind][l - 1] = '\0';
501         root = push_dir_content(argv[optind++], root);
502       } else {
503         root = push_entry(argv[optind++], root);
504       }
505     }
506   } else {
507     root = push_dir_content(".", root);
508   }
509
510   if(isatty(STDOUT_FILENO) &&
511      !ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
512     print_sorted(root, win.ws_col, win.ws_row - 2);
513   } else {
514     print_sorted(root, -1, -1);
515   }
516
517   destroy_entry_list(root);
518
519   exit(EXIT_SUCCESS);
520 }