xref: /freebsd/usr.bin/du/du.c (revision 641a6cfb86023499caafe26a4d821a0b885cf00b)
1 /*
2  * Copyright (c) 1989, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Chris Newcomb.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1989, 1993, 1994\n\
36 	The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38 
39 #ifndef lint
40 #if 0
41 static const char sccsid[] = "@(#)du.c	8.5 (Berkeley) 5/4/95";
42 #endif
43 #endif /* not lint */
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include <sys/param.h>
48 #include <sys/queue.h>
49 #include <sys/stat.h>
50 
51 #include <err.h>
52 #include <errno.h>
53 #include <fnmatch.h>
54 #include <fts.h>
55 #include <libutil.h>
56 #include <locale.h>
57 #include <stdint.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <sysexits.h>
62 #include <unistd.h>
63 
64 static SLIST_HEAD(ignhead, ignentry) ignores;
65 struct ignentry {
66 	char			*mask;
67 	SLIST_ENTRY(ignentry)	next;
68 };
69 
70 static int	linkchk(FTSENT *);
71 static void	usage(void);
72 static void	prthumanval(int64_t);
73 static void	ignoreadd(const char *);
74 static void	ignoreclean(void);
75 static int	ignorep(FTSENT *);
76 static void	siginfo(int __unused);
77 
78 static int	nodumpflag = 0;
79 static int	Aflag;
80 static long	blocksize, cblocksize;
81 static volatile sig_atomic_t info;
82 
83 int
84 main(int argc, char *argv[])
85 {
86 	FTS		*fts;
87 	FTSENT		*p;
88 	off_t		savednumber, curblocks;
89 	off_t		threshold, threshold_sign;
90 	int		ftsoptions;
91 	int		depth;
92 	int		Hflag, Lflag, aflag, sflag, dflag, cflag;
93 	int		hflag, lflag, ch, notused, rval;
94 	char 		**save;
95 	static char	dot[] = ".";
96 
97 	setlocale(LC_ALL, "");
98 
99 	Hflag = Lflag = aflag = sflag = dflag = cflag = hflag =
100 	    lflag = Aflag = 0;
101 
102 	save = argv;
103 	ftsoptions = FTS_PHYSICAL;
104 	savednumber = 0;
105 	threshold = 0;
106 	threshold_sign = 1;
107 	cblocksize = DEV_BSIZE;
108 	blocksize = 0;
109 	depth = INT_MAX;
110 	SLIST_INIT(&ignores);
111 
112 	while ((ch = getopt(argc, argv, "AB:HI:LPasd:chklmnrt:x")) != -1)
113 		switch (ch) {
114 		case 'A':
115 			Aflag = 1;
116 			break;
117 		case 'B':
118 			errno = 0;
119 			cblocksize = atoi(optarg);
120 			if (errno == ERANGE || cblocksize <= 0) {
121 				warnx("invalid argument to option B: %s",
122 				    optarg);
123 				usage();
124 			}
125 			break;
126 		case 'H':
127 			Hflag = 1;
128 			Lflag = 0;
129 			break;
130 		case 'I':
131 			ignoreadd(optarg);
132 			break;
133 		case 'L':
134 			Lflag = 1;
135 			Hflag = 0;
136 			break;
137 		case 'P':
138 			Hflag = Lflag = 0;
139 			break;
140 		case 'a':
141 			aflag = 1;
142 			break;
143 		case 's':
144 			sflag = 1;
145 			break;
146 		case 'd':
147 			dflag = 1;
148 			errno = 0;
149 			depth = atoi(optarg);
150 			if (errno == ERANGE || depth < 0) {
151 				warnx("invalid argument to option d: %s",
152 				    optarg);
153 				usage();
154 			}
155 			break;
156 		case 'c':
157 			cflag = 1;
158 			break;
159 		case 'h':
160 			hflag = 1;
161 			break;
162 		case 'k':
163 			hflag = 0;
164 			blocksize = 1024;
165 			break;
166 		case 'l':
167 			lflag = 1;
168 			break;
169 		case 'm':
170 			hflag = 0;
171 			blocksize = 1048576;
172 			break;
173 		case 'n':
174 			nodumpflag = 1;
175 			break;
176 		case 'r':		 /* Compatibility. */
177 			break;
178 		case 't' :
179 			if (expand_number(optarg, &threshold) != 0 ||
180 			    threshold == 0) {
181 				warnx("invalid threshold: %s", optarg);
182 				usage();
183 			} else if (threshold < 0)
184 				threshold_sign = -1;
185 			break;
186 		case 'x':
187 			ftsoptions |= FTS_XDEV;
188 			break;
189 		case '?':
190 		default:
191 			usage();
192 			/* NOTREACHED */
193 		}
194 
195 	argc -= optind;
196 	argv += optind;
197 
198 	/*
199 	 * XXX
200 	 * Because of the way that fts(3) works, logical walks will not count
201 	 * the blocks actually used by symbolic links.  We rationalize this by
202 	 * noting that users computing logical sizes are likely to do logical
203 	 * copies, so not counting the links is correct.  The real reason is
204 	 * that we'd have to re-implement the kernel's symbolic link traversing
205 	 * algorithm to get this right.  If, for example, you have relative
206 	 * symbolic links referencing other relative symbolic links, it gets
207 	 * very nasty, very fast.  The bottom line is that it's documented in
208 	 * the man page, so it's a feature.
209 	 */
210 
211 	if (Hflag)
212 		ftsoptions |= FTS_COMFOLLOW;
213 	if (Lflag) {
214 		ftsoptions &= ~FTS_PHYSICAL;
215 		ftsoptions |= FTS_LOGICAL;
216 	}
217 
218 	if (!Aflag && (cblocksize % DEV_BSIZE) != 0)
219 		cblocksize = howmany(cblocksize, DEV_BSIZE) * DEV_BSIZE;
220 
221 	if (aflag + dflag + sflag > 1)
222 		usage();
223 	if (sflag)
224 		depth = 0;
225 
226 	if (!*argv) {
227 		argv = save;
228 		argv[0] = dot;
229 		argv[1] = NULL;
230 	}
231 
232 	if (blocksize == 0)
233 		(void)getbsize(&notused, &blocksize);
234 
235 	if (!Aflag) {
236 		cblocksize /= DEV_BSIZE;
237 		blocksize /= DEV_BSIZE;
238 	}
239 
240 	if (threshold != 0)
241 		threshold = howmany(threshold / DEV_BSIZE * cblocksize,
242 		    blocksize);
243 
244 	rval = 0;
245 
246 	(void)signal(SIGINFO, siginfo);
247 
248 	if ((fts = fts_open(argv, ftsoptions, NULL)) == NULL)
249 		err(1, "fts_open");
250 
251 	while ((p = fts_read(fts)) != NULL) {
252 		switch (p->fts_info) {
253 		case FTS_D:			/* Ignore. */
254 			if (ignorep(p))
255 				fts_set(fts, p, FTS_SKIP);
256 			break;
257 		case FTS_DP:
258 			if (ignorep(p))
259 				break;
260 
261 			curblocks = Aflag ?
262 			    howmany(p->fts_statp->st_size, cblocksize) :
263 			    howmany(p->fts_statp->st_blocks, cblocksize);
264 			p->fts_parent->fts_bignum += p->fts_bignum +=
265 			    curblocks;
266 
267 			if (p->fts_level <= depth && threshold <=
268 			    threshold_sign * howmany(p->fts_bignum *
269 			    cblocksize, blocksize)) {
270 				if (hflag) {
271 					prthumanval(p->fts_bignum);
272 					(void)printf("\t%s\n", p->fts_path);
273 				} else {
274 					(void)printf("%jd\t%s\n",
275 					    (intmax_t)howmany(p->fts_bignum *
276 					    cblocksize, blocksize),
277 					    p->fts_path);
278 				}
279 			}
280 			if (info) {
281 				info = 0;
282 				(void)printf("\t%s\n", p->fts_path);
283 			}
284 			break;
285 		case FTS_DC:			/* Ignore. */
286 			break;
287 		case FTS_DNR:			/* Warn, continue. */
288 		case FTS_ERR:
289 		case FTS_NS:
290 			warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
291 			rval = 1;
292 			break;
293 		default:
294 			if (ignorep(p))
295 				break;
296 
297 			if (lflag == 0 && p->fts_statp->st_nlink > 1 &&
298 			    linkchk(p))
299 				break;
300 
301 			curblocks = Aflag ?
302 			    howmany(p->fts_statp->st_size, cblocksize) :
303 			    howmany(p->fts_statp->st_blocks, cblocksize);
304 
305 			if (aflag || p->fts_level == 0) {
306 				if (hflag) {
307 					prthumanval(curblocks);
308 					(void)printf("\t%s\n", p->fts_path);
309 				} else {
310 					(void)printf("%jd\t%s\n",
311 					    (intmax_t)howmany(curblocks *
312 					    cblocksize, blocksize),
313 					    p->fts_path);
314 				}
315 			}
316 
317 			p->fts_parent->fts_bignum += curblocks;
318 		}
319 		savednumber = p->fts_parent->fts_bignum;
320 	}
321 
322 	if (errno)
323 		err(1, "fts_read");
324 
325 	if (cflag) {
326 		if (hflag) {
327 			prthumanval(savednumber);
328 			(void)printf("\ttotal\n");
329 		} else {
330 			(void)printf("%jd\ttotal\n", (intmax_t)howmany(
331 			    savednumber * cblocksize, blocksize));
332 		}
333 	}
334 
335 	ignoreclean();
336 	exit(rval);
337 }
338 
339 static int
340 linkchk(FTSENT *p)
341 {
342 	struct links_entry {
343 		struct links_entry *next;
344 		struct links_entry *previous;
345 		int	 links;
346 		dev_t	 dev;
347 		ino_t	 ino;
348 	};
349 	static const size_t links_hash_initial_size = 8192;
350 	static struct links_entry **buckets;
351 	static struct links_entry *free_list;
352 	static size_t number_buckets;
353 	static unsigned long number_entries;
354 	static char stop_allocating;
355 	struct links_entry *le, **new_buckets;
356 	struct stat *st;
357 	size_t i, new_size;
358 	int hash;
359 
360 	st = p->fts_statp;
361 
362 	/* If necessary, initialize the hash table. */
363 	if (buckets == NULL) {
364 		number_buckets = links_hash_initial_size;
365 		buckets = malloc(number_buckets * sizeof(buckets[0]));
366 		if (buckets == NULL)
367 			errx(1, "No memory for hardlink detection");
368 		for (i = 0; i < number_buckets; i++)
369 			buckets[i] = NULL;
370 	}
371 
372 	/* If the hash table is getting too full, enlarge it. */
373 	if (number_entries > number_buckets * 10 && !stop_allocating) {
374 		new_size = number_buckets * 2;
375 		new_buckets = malloc(new_size * sizeof(struct links_entry *));
376 
377 		/* Try releasing the free list to see if that helps. */
378 		if (new_buckets == NULL && free_list != NULL) {
379 			while (free_list != NULL) {
380 				le = free_list;
381 				free_list = le->next;
382 				free(le);
383 			}
384 			new_buckets = malloc(new_size *
385 			    sizeof(new_buckets[0]));
386 		}
387 
388 		if (new_buckets == NULL) {
389 			stop_allocating = 1;
390 			warnx("No more memory for tracking hard links");
391 		} else {
392 			memset(new_buckets, 0,
393 			    new_size * sizeof(struct links_entry *));
394 			for (i = 0; i < number_buckets; i++) {
395 				while (buckets[i] != NULL) {
396 					/* Remove entry from old bucket. */
397 					le = buckets[i];
398 					buckets[i] = le->next;
399 
400 					/* Add entry to new bucket. */
401 					hash = (le->dev ^ le->ino) % new_size;
402 
403 					if (new_buckets[hash] != NULL)
404 						new_buckets[hash]->previous =
405 						    le;
406 					le->next = new_buckets[hash];
407 					le->previous = NULL;
408 					new_buckets[hash] = le;
409 				}
410 			}
411 			free(buckets);
412 			buckets = new_buckets;
413 			number_buckets = new_size;
414 		}
415 	}
416 
417 	/* Try to locate this entry in the hash table. */
418 	hash = ( st->st_dev ^ st->st_ino ) % number_buckets;
419 	for (le = buckets[hash]; le != NULL; le = le->next) {
420 		if (le->dev == st->st_dev && le->ino == st->st_ino) {
421 			/*
422 			 * Save memory by releasing an entry when we've seen
423 			 * all of it's links.
424 			 */
425 			if (--le->links <= 0) {
426 				if (le->previous != NULL)
427 					le->previous->next = le->next;
428 				if (le->next != NULL)
429 					le->next->previous = le->previous;
430 				if (buckets[hash] == le)
431 					buckets[hash] = le->next;
432 				number_entries--;
433 				/* Recycle this node through the free list */
434 				if (stop_allocating) {
435 					free(le);
436 				} else {
437 					le->next = free_list;
438 					free_list = le;
439 				}
440 			}
441 			return (1);
442 		}
443 	}
444 
445 	if (stop_allocating)
446 		return (0);
447 
448 	/* Add this entry to the links cache. */
449 	if (free_list != NULL) {
450 		/* Pull a node from the free list if we can. */
451 		le = free_list;
452 		free_list = le->next;
453 	} else
454 		/* Malloc one if we have to. */
455 		le = malloc(sizeof(struct links_entry));
456 	if (le == NULL) {
457 		stop_allocating = 1;
458 		warnx("No more memory for tracking hard links");
459 		return (0);
460 	}
461 	le->dev = st->st_dev;
462 	le->ino = st->st_ino;
463 	le->links = st->st_nlink - 1;
464 	number_entries++;
465 	le->next = buckets[hash];
466 	le->previous = NULL;
467 	if (buckets[hash] != NULL)
468 		buckets[hash]->previous = le;
469 	buckets[hash] = le;
470 	return (0);
471 }
472 
473 static void
474 prthumanval(int64_t bytes)
475 {
476 	char buf[5];
477 
478 	bytes *= cblocksize;
479 	if (!Aflag)
480 		bytes *= DEV_BSIZE;
481 
482 	humanize_number(buf, sizeof(buf), bytes, "", HN_AUTOSCALE,
483 	    HN_B | HN_NOSPACE | HN_DECIMAL);
484 
485 	(void)printf("%4s", buf);
486 }
487 
488 static void
489 usage(void)
490 {
491 	(void)fprintf(stderr,
492 		"usage: du [-Aclnx] [-H | -L | -P] [-h | -k | -m ] "
493 		"[-a | -s | -d depth] [-B blocksize] [-I mask] "
494 		"[-t threshold] [file ...]\n");
495 	exit(EX_USAGE);
496 }
497 
498 static void
499 ignoreadd(const char *mask)
500 {
501 	struct ignentry *ign;
502 
503 	ign = calloc(1, sizeof(*ign));
504 	if (ign == NULL)
505 		errx(1, "cannot allocate memory");
506 	ign->mask = strdup(mask);
507 	if (ign->mask == NULL)
508 		errx(1, "cannot allocate memory");
509 	SLIST_INSERT_HEAD(&ignores, ign, next);
510 }
511 
512 static void
513 ignoreclean(void)
514 {
515 	struct ignentry *ign;
516 
517 	while (!SLIST_EMPTY(&ignores)) {
518 		ign = SLIST_FIRST(&ignores);
519 		SLIST_REMOVE_HEAD(&ignores, next);
520 		free(ign->mask);
521 		free(ign);
522 	}
523 }
524 
525 static int
526 ignorep(FTSENT *ent)
527 {
528 	struct ignentry *ign;
529 
530 	if (nodumpflag && (ent->fts_statp->st_flags & UF_NODUMP))
531 		return 1;
532 	SLIST_FOREACH(ign, &ignores, next)
533 		if (fnmatch(ign->mask, ent->fts_name, 0) != FNM_NOMATCH)
534 			return 1;
535 	return 0;
536 }
537 
538 static void
539 siginfo(int sig __unused)
540 {
541 
542 	info = 1;
543 }
544