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