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