1 /*	$NetBSD: du.c,v 1.36 2012/03/11 11:23:20 shattered Exp $	*/
2 
3 /*
4  * Copyright (c) 1989, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Chris Newcomb.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 __COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\
38  The Regents of the University of California.  All rights reserved.");
39 #endif /* not lint */
40 
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)du.c	8.5 (Berkeley) 5/4/95";
44 #else
45 __RCSID("$NetBSD: du.c,v 1.36 2012/03/11 11:23:20 shattered Exp $");
46 #endif
47 #endif /* not lint */
48 
49 #include <sys/param.h>
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 
53 #include <dirent.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fts.h>
57 #include <inttypes.h>
58 #include <util.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63 #include <limits.h>
64 
65 /* Count inodes or file size */
66 #define	COUNT	(iflag ? 1 : p->fts_statp->st_blocks)
67 
68 static int	linkchk(dev_t, ino_t);
69 static void	prstat(const char *, int64_t);
70 __dead static void	usage(void);
71 
72 static int hflag, iflag;
73 static long blocksize;
74 
75 int
main(int argc,char * argv[])76 main(int argc, char *argv[])
77 {
78 	FTS *fts;
79 	FTSENT *p;
80 	int64_t totalblocks;
81 	int ftsoptions, listfiles;
82 	int depth;
83 	int Hflag, Lflag, aflag, ch, cflag, dflag, gkmflag, nflag, rval, sflag;
84 	const char *noargv[2];
85 
86 	Hflag = Lflag = aflag = cflag = dflag = gkmflag = nflag = sflag = 0;
87 	totalblocks = 0;
88 	ftsoptions = FTS_PHYSICAL;
89 	depth = INT_MAX;
90 	while ((ch = getopt(argc, argv, "HLPacd:ghikmnrsx")) != -1)
91 		switch (ch) {
92 		case 'H':
93 			Hflag = 1;
94 			Lflag = 0;
95 			break;
96 		case 'L':
97 			Lflag = 1;
98 			Hflag = 0;
99 			break;
100 		case 'P':
101 			Hflag = Lflag = 0;
102 			break;
103 		case 'a':
104 			aflag = 1;
105 			break;
106 		case 'c':
107 			cflag = 1;
108 			break;
109 		case 'd':
110 			dflag = 1;
111 			depth = atoi(optarg);
112 			if (depth < 0 || depth > SHRT_MAX) {
113 				warnx("invalid argument to option d: %s",
114 					optarg);
115 				usage();
116 			}
117 			break;
118 		case 'g':
119 			blocksize = 1024 * 1024 * 1024;
120 			gkmflag = 1;
121 			break;
122 		case 'h':
123 			hflag = 1;
124 			break;
125 		case 'i':
126 			iflag = 1;
127 			break;
128 		case 'k':
129 			blocksize = 1024;
130 			gkmflag = 1;
131 			break;
132 		case 'm':
133 			blocksize = 1024 * 1024;
134 			gkmflag = 1;
135 			break;
136 		case 'n':
137 			nflag = 1;
138 			break;
139 		case 'r':
140 			break;
141 		case 's':
142 			sflag = 1;
143 			break;
144 		case 'x':
145 			ftsoptions |= FTS_XDEV;
146 			break;
147 		case '?':
148 		default:
149 			usage();
150 		}
151 	argc -= optind;
152 	argv += optind;
153 
154 	/*
155 	 * XXX
156 	 * Because of the way that fts(3) works, logical walks will not count
157 	 * the blocks actually used by symbolic links.  We rationalize this by
158 	 * noting that users computing logical sizes are likely to do logical
159 	 * copies, so not counting the links is correct.  The real reason is
160 	 * that we'd have to re-implement the kernel's symbolic link traversing
161 	 * algorithm to get this right.  If, for example, you have relative
162 	 * symbolic links referencing other relative symbolic links, it gets
163 	 * very nasty, very fast.  The bottom line is that it's documented in
164 	 * the man page, so it's a feature.
165 	 */
166 	if (Hflag)
167 		ftsoptions |= FTS_COMFOLLOW;
168 	if (Lflag) {
169 		ftsoptions &= ~FTS_PHYSICAL;
170 		ftsoptions |= FTS_LOGICAL;
171 	}
172 
173 	listfiles = 0;
174 	if (aflag) {
175 		if (sflag || dflag)
176 			usage();
177 		listfiles = 1;
178 	} else if (sflag) {
179 		if (dflag)
180 			usage();
181 		depth = 0;
182 	}
183 
184 	if (!*argv) {
185 		noargv[0] = ".";
186 		noargv[1] = NULL;
187 		argv = __UNCONST(noargv);
188 	}
189 
190 	if (!gkmflag)
191 		(void)getbsize(NULL, &blocksize);
192 	blocksize /= 512;
193 
194 	if ((fts = fts_open(argv, ftsoptions, NULL)) == NULL)
195 		err(1, "fts_open `%s'", *argv);
196 
197 	for (rval = 0; (p = fts_read(fts)) != NULL;) {
198 #ifndef __ANDROID__
199 		if (nflag) {
200 			switch (p->fts_info) {
201 			case FTS_NS:
202 			case FTS_SLNONE:
203 				/* nothing */
204 				break;
205 			default:
206 				if (p->fts_statp->st_flags & UF_NODUMP) {
207 					fts_set(fts, p, FTS_SKIP);
208 					continue;
209 				}
210 			}
211 		}
212 #endif
213 		switch (p->fts_info) {
214 		case FTS_D:			/* Ignore. */
215 			break;
216 		case FTS_DP:
217 			p->fts_parent->fts_number +=
218 			    p->fts_number += COUNT;
219 			if (cflag)
220 				totalblocks += COUNT;
221 			/*
222 			 * If listing each directory, or not listing files
223 			 * or directories and this is post-order of the
224 			 * root of a traversal, display the total.
225 			 */
226 			if (p->fts_level <= depth
227 			    || (!listfiles && !p->fts_level))
228 				prstat(p->fts_path, p->fts_number);
229 			break;
230 		case FTS_DC:			/* Ignore. */
231 			break;
232 		case FTS_DNR:			/* Warn, continue. */
233 		case FTS_ERR:
234 		case FTS_NS:
235 			warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
236 			rval = 1;
237 			break;
238 		default:
239 			if (p->fts_statp->st_nlink > 1 &&
240 			    linkchk(p->fts_statp->st_dev, p->fts_statp->st_ino))
241 				break;
242 			/*
243 			 * If listing each file, or a non-directory file was
244 			 * the root of a traversal, display the total.
245 			 */
246 			if (listfiles || !p->fts_level)
247 				prstat(p->fts_path, COUNT);
248 			p->fts_parent->fts_number += COUNT;
249 			if (cflag)
250 				totalblocks += COUNT;
251 		}
252 	}
253 	if (errno)
254 		err(1, "fts_read");
255 	if (cflag)
256 		prstat("total", totalblocks);
257 	exit(rval);
258 }
259 
260 static void
prstat(const char * fname,int64_t blocks)261 prstat(const char *fname, int64_t blocks)
262 {
263 	if (iflag) {
264 		(void)printf("%" PRId64 "\t%s\n", blocks, fname);
265 		return;
266 	}
267 
268 	if (hflag) {
269 		char buf[5];
270 		int64_t sz = blocks * 512;
271 
272 		humanize_number(buf, sizeof(buf), sz, "", HN_AUTOSCALE,
273 		    HN_B | HN_NOSPACE | HN_DECIMAL);
274 
275 		(void)printf("%s\t%s\n", buf, fname);
276 	} else
277 		(void)printf("%" PRId64 "\t%s\n",
278 		    howmany(blocks, (int64_t)blocksize),
279 		    fname);
280 }
281 
282 static int
linkchk(dev_t dev,ino_t ino)283 linkchk(dev_t dev, ino_t ino)
284 {
285 	static struct entry {
286 		dev_t	dev;
287 		ino_t	ino;
288 	} *htable;
289 	static int htshift;  /* log(allocated size) */
290 	static int htmask;   /* allocated size - 1 */
291 	static int htused;   /* 2*number of insertions */
292 	static int sawzero;  /* Whether zero is in table or not */
293 	int h, h2;
294 	uint64_t tmp;
295 	/* this constant is (1<<64)/((1+sqrt(5))/2)
296 	 * aka (word size)/(golden ratio)
297 	 */
298 	const uint64_t HTCONST = 11400714819323198485ULL;
299 	const int HTBITS = CHAR_BIT * sizeof(tmp);
300 
301 	/* Never store zero in hashtable */
302 	if (dev == 0 && ino == 0) {
303 		h = sawzero;
304 		sawzero = 1;
305 		return h;
306 	}
307 
308 	/* Extend hash table if necessary, keep load under 0.5 */
309 	if (htused<<1 >= htmask) {
310 		struct entry *ohtable;
311 
312 		if (!htable)
313 			htshift = 10;   /* starting hashtable size */
314 		else
315 			htshift++;   /* exponential hashtable growth */
316 
317 		htmask  = (1 << htshift) - 1;
318 		htused = 0;
319 
320 		ohtable = htable;
321 		htable = calloc(htmask+1, sizeof(*htable));
322 		if (!htable)
323 			err(1, "calloc");
324 
325 		/* populate newly allocated hashtable */
326 		if (ohtable) {
327 			int i;
328 			for (i = 0; i <= htmask>>1; i++)
329 				if (ohtable[i].ino || ohtable[i].dev)
330 					linkchk(ohtable[i].dev, ohtable[i].ino);
331 			free(ohtable);
332 		}
333 	}
334 
335 	/* multiplicative hashing */
336 	tmp = dev;
337 	tmp <<= HTBITS>>1;
338 	tmp |=  ino;
339 	tmp *= HTCONST;
340 	h  = tmp >> (HTBITS - htshift);
341 	h2 = 1 | ( tmp >> (HTBITS - (htshift<<1) - 1)); /* must be odd */
342 
343 	/* open address hashtable search with double hash probing */
344 	while (htable[h].ino || htable[h].dev) {
345 		if ((htable[h].ino == ino) && (htable[h].dev == dev))
346 			return 1;
347 		h = (h + h2) & htmask;
348 	}
349 
350 	/* Insert the current entry into hashtable */
351 	htable[h].dev = dev;
352 	htable[h].ino = ino;
353 	htused++;
354 	return 0;
355 }
356 
357 static void
usage(void)358 usage(void)
359 {
360 
361 	(void)fprintf(stderr,
362 		"usage: du [-H | -L | -P] [-a | -d depth | -s] [-cghikmnrx] [file ...]\n");
363 	exit(1);
364 }
365