hush: if we did match "LINENO" or "OPTIND", stop further comparisons
[oweals/busybox.git] / coreutils / du.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini du implementation for busybox
4  *
5  * Copyright (C) 1999,2000,2001 by Lineo, inc. and John Beppu
6  * Copyright (C) 1999,2000,2001 by John Beppu <beppu@codepoet.org>
7  * Copyright (C) 2002  Edward Betts <edward@debian.org>
8  *
9  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
10  */
11 /* Mar 16, 2003      Manuel Novoa III   (mjn3@codepoet.org)
12  *
13  * Mostly rewritten for SUSv3 compliance and to fix bugs/defects.
14  * 1) Added support for SUSv3 -a, -H, -L, gnu -c, and (busybox) -d options.
15  *    The -d option allows setting of max depth (similar to gnu --max-depth).
16  * 2) Fixed incorrect size calculations for links and directories, especially
17  *    when errors occurred.  Calculates sizes should now match gnu du output.
18  * 3) Added error checking of output.
19  * 4) Fixed busybox bug #1284 involving long overflow with human_readable.
20  */
21 //config:config DU
22 //config:       bool "du (default blocksize of 512 bytes)"
23 //config:       default y
24 //config:       help
25 //config:       du is used to report the amount of disk space used
26 //config:       for specified files.
27 //config:
28 //config:config FEATURE_DU_DEFAULT_BLOCKSIZE_1K
29 //config:       bool "Use a default blocksize of 1024 bytes (1K)"
30 //config:       default y
31 //config:       depends on DU
32 //config:       help
33 //config:       Use a blocksize of (1K) instead of the default 512b.
34
35 //applet:IF_DU(APPLET(du, BB_DIR_USR_BIN, BB_SUID_DROP))
36
37 //kbuild:lib-$(CONFIG_DU) += du.o
38
39 /* BB_AUDIT SUSv3 compliant (unless default blocksize set to 1k) */
40 /* http://www.opengroup.org/onlinepubs/007904975/utilities/du.html */
41
42 //usage:#define du_trivial_usage
43 //usage:       "[-aHLdclsx" IF_FEATURE_HUMAN_READABLE("hm") "k] [FILE]..."
44 //usage:#define du_full_usage "\n\n"
45 //usage:       "Summarize disk space used for each FILE and/or directory\n"
46 //usage:     "\n        -a      Show file sizes too"
47 //usage:     "\n        -L      Follow all symlinks"
48 //usage:     "\n        -H      Follow symlinks on command line"
49 //usage:     "\n        -d N    Limit output to directories (and files with -a) of depth < N"
50 //usage:     "\n        -c      Show grand total"
51 //usage:     "\n        -l      Count sizes many times if hard linked"
52 //usage:     "\n        -s      Display only a total for each argument"
53 //usage:     "\n        -x      Skip directories on different filesystems"
54 //usage:        IF_FEATURE_HUMAN_READABLE(
55 //usage:     "\n        -h      Sizes in human readable format (e.g., 1K 243M 2G)"
56 //usage:     "\n        -m      Sizes in megabytes"
57 //usage:        )
58 //usage:     "\n        -k      Sizes in kilobytes" IF_FEATURE_DU_DEFAULT_BLOCKSIZE_1K(" (default)")
59 //usage:        IF_NOT_FEATURE_DU_DEFAULT_BLOCKSIZE_1K(
60 //usage:     "\n                Default unit is 512 bytes"
61 //usage:        )
62 //usage:
63 //usage:#define du_example_usage
64 //usage:       "$ du\n"
65 //usage:       "16      ./CVS\n"
66 //usage:       "12      ./kernel-patches/CVS\n"
67 //usage:       "80      ./kernel-patches\n"
68 //usage:       "12      ./tests/CVS\n"
69 //usage:       "36      ./tests\n"
70 //usage:       "12      ./scripts/CVS\n"
71 //usage:       "16      ./scripts\n"
72 //usage:       "12      ./docs/CVS\n"
73 //usage:       "104     ./docs\n"
74 //usage:       "2417    .\n"
75
76 #include "libbb.h"
77 #include "common_bufsiz.h"
78
79 enum {
80         OPT_a_files_too    = (1 << 0),
81         OPT_H_follow_links = (1 << 1),
82         OPT_k_kbytes       = (1 << 2),
83         OPT_L_follow_links = (1 << 3),
84         OPT_s_total_norecurse = (1 << 4),
85         OPT_x_one_FS       = (1 << 5),
86         OPT_d_maxdepth     = (1 << 6),
87         OPT_l_hardlinks    = (1 << 7),
88         OPT_c_total        = (1 << 8),
89         OPT_h_for_humans   = (1 << 9),
90         OPT_m_mbytes       = (1 << 10),
91 };
92
93 struct globals {
94 #if ENABLE_FEATURE_HUMAN_READABLE
95         unsigned long disp_unit;
96 #else
97         unsigned disp_k;
98 #endif
99         int max_print_depth;
100         bool status;
101         int slink_depth;
102         int du_depth;
103         dev_t dir_dev;
104 } FIX_ALIASING;
105 #define G (*(struct globals*)bb_common_bufsiz1)
106 #define INIT_G() do { setup_common_bufsiz(); } while (0)
107
108
109 static void print(unsigned long long size, const char *filename)
110 {
111         /* TODO - May not want to defer error checking here. */
112 #if ENABLE_FEATURE_HUMAN_READABLE
113 # if ENABLE_DESKTOP
114         /* ~30 bytes of code for extra comtat:
115          * coreutils' du rounds sizes up:
116          * for example,  1025k file is shown as "2" by du -m.
117          * We round to nearest if human-readable [too hard to fix],
118          * else (fixed scale such as -m), we round up. To that end,
119          * add yet another half of the unit before displaying:
120          */
121         if (G.disp_unit)
122                 size += (G.disp_unit-1) / (unsigned)(512 * 2);
123 # endif
124         printf("%s\t%s\n",
125                         /* size x 512 / G.disp_unit.
126                          * If G.disp_unit == 0, show one fractional
127                          * and use suffixes
128                          */
129                         make_human_readable_str(size, 512, G.disp_unit),
130                         filename);
131 #else
132         if (G.disp_k) {
133                 size++;
134                 size >>= 1;
135         }
136         printf("%llu\t%s\n", size, filename);
137 #endif
138 }
139
140 /* tiny recursive du */
141 static unsigned long long du(const char *filename)
142 {
143         struct stat statbuf;
144         unsigned long long sum;
145
146         if (lstat(filename, &statbuf) != 0) {
147                 bb_simple_perror_msg(filename);
148                 G.status = EXIT_FAILURE;
149                 return 0;
150         }
151
152         if (option_mask32 & OPT_x_one_FS) {
153                 if (G.du_depth == 0) {
154                         G.dir_dev = statbuf.st_dev;
155                 } else if (G.dir_dev != statbuf.st_dev) {
156                         return 0;
157                 }
158         }
159
160         sum = statbuf.st_blocks;
161
162         if (S_ISLNK(statbuf.st_mode)) {
163                 if (G.slink_depth > G.du_depth) { /* -H or -L */
164                         if (stat(filename, &statbuf) != 0) {
165                                 bb_simple_perror_msg(filename);
166                                 G.status = EXIT_FAILURE;
167                                 return 0;
168                         }
169                         sum = statbuf.st_blocks;
170                         if (G.slink_depth == 1) {
171                                 /* Convert -H to -L */
172                                 G.slink_depth = INT_MAX;
173                         }
174                 }
175         }
176
177         if (!(option_mask32 & OPT_l_hardlinks)
178          && statbuf.st_nlink > 1
179         ) {
180                 /* Add files/directories with links only once */
181                 if (is_in_ino_dev_hashtable(&statbuf)) {
182                         return 0;
183                 }
184                 add_to_ino_dev_hashtable(&statbuf, NULL);
185         }
186
187         if (S_ISDIR(statbuf.st_mode)) {
188                 DIR *dir;
189                 struct dirent *entry;
190                 char *newfile;
191
192                 dir = warn_opendir(filename);
193                 if (!dir) {
194                         G.status = EXIT_FAILURE;
195                         return sum;
196                 }
197
198                 while ((entry = readdir(dir))) {
199                         newfile = concat_subpath_file(filename, entry->d_name);
200                         if (newfile == NULL)
201                                 continue;
202                         ++G.du_depth;
203                         sum += du(newfile);
204                         --G.du_depth;
205                         free(newfile);
206                 }
207                 closedir(dir);
208         } else {
209                 if (!(option_mask32 & OPT_a_files_too) && G.du_depth != 0)
210                         return sum;
211         }
212         if (G.du_depth <= G.max_print_depth) {
213                 print(sum, filename);
214         }
215         return sum;
216 }
217
218 int du_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
219 int du_main(int argc UNUSED_PARAM, char **argv)
220 {
221         unsigned long long total;
222         int slink_depth_save;
223         unsigned opt;
224
225         INIT_G();
226
227 #if ENABLE_FEATURE_HUMAN_READABLE
228         IF_FEATURE_DU_DEFAULT_BLOCKSIZE_1K(G.disp_unit = 1024;)
229         IF_NOT_FEATURE_DU_DEFAULT_BLOCKSIZE_1K(G.disp_unit = 512;)
230         if (getenv("POSIXLY_CORRECT"))  /* TODO - a new libbb function? */
231                 G.disp_unit = 512;
232 #else
233         IF_FEATURE_DU_DEFAULT_BLOCKSIZE_1K(G.disp_k = 1;)
234         /* IF_NOT_FEATURE_DU_DEFAULT_BLOCKSIZE_1K(G.disp_k = 0;) - G is pre-zeroed */
235 #endif
236         G.max_print_depth = INT_MAX;
237
238         /* Note: SUSv3 specifies that -a and -s options cannot be used together
239          * in strictly conforming applications.  However, it also says that some
240          * du implementations may produce output when -a and -s are used together.
241          * gnu du exits with an error code in this case.  We choose to simply
242          * ignore -a.  This is consistent with -s being equivalent to -d 0.
243          */
244 #if ENABLE_FEATURE_HUMAN_READABLE
245         opt = getopt32(argv, "^"
246                         "aHkLsxd:+lchm"
247                         "\0" "h-km:k-hm:m-hk:H-L:L-H:s-d:d-s",
248                         &G.max_print_depth
249         );
250         argv += optind;
251         if (opt & OPT_h_for_humans) {
252                 G.disp_unit = 0;
253         }
254         if (opt & OPT_m_mbytes) {
255                 G.disp_unit = 1024*1024;
256         }
257         if (opt & OPT_k_kbytes) {
258                 G.disp_unit = 1024;
259         }
260 #else
261         opt = getopt32(argv, "^"
262                         "aHkLsxd:+lc"
263                         "\0" "H-L:L-H:s-d:d-s",
264                         &G.max_print_depth
265         );
266         argv += optind;
267 #if !ENABLE_FEATURE_DU_DEFAULT_BLOCKSIZE_1K
268         if (opt & OPT_k_kbytes) {
269                 G.disp_k = 1;
270         }
271 #endif
272 #endif
273         if (opt & OPT_H_follow_links) {
274                 G.slink_depth = 1;
275         }
276         if (opt & OPT_L_follow_links) {
277                 G.slink_depth = INT_MAX;
278         }
279         if (opt & OPT_s_total_norecurse) {
280                 G.max_print_depth = 0;
281         }
282
283         /* go through remaining args (if any) */
284         if (!*argv) {
285                 *--argv = (char*)".";
286                 if (G.slink_depth == 1) {
287                         G.slink_depth = 0;
288                 }
289         }
290
291         slink_depth_save = G.slink_depth;
292         total = 0;
293         do {
294                 total += du(*argv);
295                 /* otherwise du /dir /dir won't show /dir twice: */
296                 reset_ino_dev_hashtable();
297                 G.slink_depth = slink_depth_save;
298         } while (*++argv);
299
300         if (opt & OPT_c_total)
301                 print(total, "total");
302
303         fflush_stdout_and_exit(G.status);
304 }