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