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