xref: /freebsd/usr.bin/du/du.c (revision a3e8fd0b7f663db7eafff527d5c3ca3bcfa8a537)
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 <math.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <sysexits.h>
64 #include <unistd.h>
65 
66 #define	KILO_SZ(n) (n)
67 #define	MEGA_SZ(n) ((n) * (n))
68 #define	GIGA_SZ(n) ((n) * (n) * (n))
69 #define	TERA_SZ(n) ((n) * (n) * (n) * (n))
70 #define	PETA_SZ(n) ((n) * (n) * (n) * (n) * (n))
71 
72 #define	KILO_2_SZ (KILO_SZ(1024ULL))
73 #define	MEGA_2_SZ (MEGA_SZ(1024ULL))
74 #define	GIGA_2_SZ (GIGA_SZ(1024ULL))
75 #define	TERA_2_SZ (TERA_SZ(1024ULL))
76 #define	PETA_2_SZ (PETA_SZ(1024ULL))
77 
78 #define	KILO_SI_SZ (KILO_SZ(1000ULL))
79 #define	MEGA_SI_SZ (MEGA_SZ(1000ULL))
80 #define	GIGA_SI_SZ (GIGA_SZ(1000ULL))
81 #define	TERA_SI_SZ (TERA_SZ(1000ULL))
82 #define	PETA_SI_SZ (PETA_SZ(1000ULL))
83 
84 unsigned long long vals_si [] = {1, KILO_SI_SZ, MEGA_SI_SZ, GIGA_SI_SZ, TERA_SI_SZ, PETA_SI_SZ};
85 unsigned long long vals_base2[] = {1, KILO_2_SZ, MEGA_2_SZ, GIGA_2_SZ, TERA_2_SZ, PETA_2_SZ};
86 unsigned long long *valp;
87 
88 typedef enum { NONE, KILO, MEGA, GIGA, TERA, PETA, UNIT_MAX } unit_t;
89 
90 int unitp [] = { NONE, KILO, MEGA, GIGA, TERA, PETA };
91 
92 SLIST_HEAD(ignhead, ignentry) ignores;
93 struct ignentry {
94 	char			*mask;
95 	SLIST_ENTRY(ignentry)	next;
96 };
97 
98 int		linkchk(FTSENT *);
99 static void	usage(void);
100 void		prthumanval(double);
101 unit_t		unit_adjust(double *);
102 void		ignoreadd(const char *);
103 void		ignoreclean(void);
104 int		ignorep(FTSENT *);
105 
106 int
107 main(int argc, char *argv[])
108 {
109 	FTS		*fts;
110 	FTSENT		*p;
111 	long		blocksize, savednumber = 0;
112 	int		ftsoptions;
113 	int		listall;
114 	int		depth;
115 	int		Hflag, Lflag, Pflag, aflag, sflag, dflag, cflag, hflag, ch, rval;
116 	size_t		notused;
117 	char 		**save;
118 	static char	dot[] = ".";
119 
120 	Hflag = Lflag = Pflag = aflag = sflag = dflag = cflag = hflag = 0;
121 
122 	save = argv;
123 	ftsoptions = 0;
124 	depth = INT_MAX;
125 	SLIST_INIT(&ignores);
126 
127 	while ((ch = getopt(argc, argv, "HI:LPasd:chkrx")) != -1)
128 		switch (ch) {
129 			case 'H':
130 				Hflag = 1;
131 				break;
132 			case 'I':
133 				ignoreadd(optarg);
134 				break;
135 			case 'L':
136 				if (Pflag)
137 					usage();
138 				Lflag = 1;
139 				break;
140 			case 'P':
141 				if (Lflag)
142 					usage();
143 				Pflag = 1;
144 				break;
145 			case 'a':
146 				aflag = 1;
147 				break;
148 			case 's':
149 				sflag = 1;
150 				break;
151 			case 'd':
152 				dflag = 1;
153 				errno = 0;
154 				depth = atoi(optarg);
155 				if (errno == ERANGE || depth < 0) {
156 					warnx("invalid argument to option d: %s", optarg);
157 					usage();
158 				}
159 				break;
160 			case 'c':
161 				cflag = 1;
162 				break;
163 			case 'h':
164 				putenv("BLOCKSIZE=512");
165 				hflag = 1;
166 				valp = vals_base2;
167 				break;
168 			case 'k':
169 				if (!hflag)
170 					putenv("BLOCKSIZE=1024");
171 				break;
172 			case 'r':		 /* Compatibility. */
173 				break;
174 			case 'x':
175 				ftsoptions |= FTS_XDEV;
176 				break;
177 			case '?':
178 			default:
179 				usage();
180 		}
181 
182 	argc -= optind;
183 	argv += optind;
184 
185 	/*
186 	 * XXX
187 	 * Because of the way that fts(3) works, logical walks will not count
188 	 * the blocks actually used by symbolic links.  We rationalize this by
189 	 * noting that users computing logical sizes are likely to do logical
190 	 * copies, so not counting the links is correct.  The real reason is
191 	 * that we'd have to re-implement the kernel's symbolic link traversing
192 	 * algorithm to get this right.  If, for example, you have relative
193 	 * symbolic links referencing other relative symbolic links, it gets
194 	 * very nasty, very fast.  The bottom line is that it's documented in
195 	 * the man page, so it's a feature.
196 	 */
197 
198 	if (Hflag + Lflag + Pflag > 1)
199 		usage();
200 
201 	if (Hflag + Lflag + Pflag == 0)
202 		Pflag = 1;			/* -P (physical) is default */
203 
204 	if (Hflag)
205 		ftsoptions |= FTS_COMFOLLOW;
206 
207 	if (Lflag)
208 		ftsoptions |= FTS_LOGICAL;
209 
210 	if (Pflag)
211 		ftsoptions |= FTS_PHYSICAL;
212 
213 	listall = 0;
214 
215 	if (aflag) {
216 		if (sflag || dflag)
217 			usage();
218 		listall = 1;
219 	} else if (sflag) {
220 		if (dflag)
221 			usage();
222 		depth = 0;
223 	}
224 
225 	if (!*argv) {
226 		argv = save;
227 		argv[0] = dot;
228 		argv[1] = NULL;
229 	}
230 
231 	(void) getbsize(&notused, &blocksize);
232 	blocksize /= 512;
233 
234 	rval = 0;
235 
236 	if ((fts = fts_open(argv, ftsoptions, NULL)) == NULL)
237 		err(1, "fts_open");
238 
239 	while ((p = fts_read(fts)) != NULL) {
240 		switch (p->fts_info) {
241 			case FTS_D:			/* Ignore. */
242 				if (ignorep(p))
243 					fts_set(fts, p, FTS_SKIP);
244 				break;
245 			case FTS_DP:
246 				if (ignorep(p))
247 					break;
248 
249 				p->fts_parent->fts_number +=
250 				    p->fts_number += p->fts_statp->st_blocks;
251 
252 				if (p->fts_level <= depth) {
253 					if (hflag) {
254 						(void) prthumanval(howmany(p->fts_number, blocksize));
255 						(void) printf("\t%s\n", p->fts_path);
256 					} else {
257 					(void) printf("%ld\t%s\n",
258 					    howmany(p->fts_number, blocksize),
259 					    p->fts_path);
260 					}
261 				}
262 				break;
263 			case FTS_DC:			/* Ignore. */
264 				break;
265 			case FTS_DNR:			/* Warn, continue. */
266 			case FTS_ERR:
267 			case FTS_NS:
268 				warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
269 				rval = 1;
270 				break;
271 			default:
272 				if (ignorep(p))
273 					break;
274 
275 				if (p->fts_statp->st_nlink > 1 && linkchk(p))
276 					break;
277 
278 				if (listall || p->fts_level == 0) {
279 					if (hflag) {
280 						(void) prthumanval(howmany(p->fts_statp->st_blocks,
281 							blocksize));
282 						(void) printf("\t%s\n", p->fts_path);
283 					} else {
284 						(void) printf("%qd\t%s\n",
285 							(long long)howmany(p->fts_statp->st_blocks, blocksize),
286 							p->fts_path);
287 					}
288 				}
289 
290 				p->fts_parent->fts_number += p->fts_statp->st_blocks;
291 		}
292 		savednumber = p->fts_parent->fts_number;
293 	}
294 
295 	if (errno)
296 		err(1, "fts_read");
297 
298 	if (cflag) {
299 		if (hflag) {
300 			(void) prthumanval(howmany(savednumber, blocksize));
301 			(void) printf("\ttotal\n");
302 		} else {
303 			(void) printf("%ld\ttotal\n", howmany(savednumber, blocksize));
304 		}
305 	}
306 
307 	ignoreclean();
308 	exit(rval);
309 }
310 
311 
312 typedef struct _ID {
313 	dev_t	dev;
314 	ino_t	inode;
315 } ID;
316 
317 
318 int
319 linkchk(FTSENT *p)
320 {
321 	static ID *files;
322 	static int maxfiles, nfiles;
323 	ID *fp, *start;
324 	ino_t ino;
325 	dev_t dev;
326 
327 	ino = p->fts_statp->st_ino;
328 	dev = p->fts_statp->st_dev;
329 	if ((start = files) != NULL)
330 		for (fp = start + nfiles - 1; fp >= start; --fp)
331 			if (ino == fp->inode && dev == fp->dev)
332 				return (1);
333 
334 	if (nfiles == maxfiles && (files = realloc((char *)files,
335 	    (u_int)(sizeof(ID) * (maxfiles += 128)))) == NULL)
336 		errx(1, "can't allocate memory");
337 	files[nfiles].inode = ino;
338 	files[nfiles].dev = dev;
339 	++nfiles;
340 	return (0);
341 }
342 
343 /*
344  * Output in "human-readable" format.  Uses 3 digits max and puts
345  * unit suffixes at the end.  Makes output compact and easy to read,
346  * especially on huge disks.
347  *
348  */
349 unit_t
350 unit_adjust(double *val)
351 {
352 	double abval;
353 	unit_t unit;
354 	unsigned int unit_sz;
355 
356 	abval = fabs(*val);
357 
358 	unit_sz = abval ? ilogb(abval) / 10 : 0;
359 
360 	if (unit_sz >= UNIT_MAX) {
361 		unit = NONE;
362 	} else {
363 		unit = unitp[unit_sz];
364 		*val /= (double)valp[unit_sz];
365 	}
366 
367 	return (unit);
368 }
369 
370 void
371 prthumanval(double bytes)
372 {
373 	unit_t unit;
374 
375 	bytes *= 512;
376 	unit = unit_adjust(&bytes);
377 
378 	if (bytes == 0)
379 		(void)printf("  0B");
380 	else if (bytes > 10)
381 		(void)printf("%3.0f%c", bytes, "BKMGTPE"[unit]);
382 	else
383 		(void)printf("%3.1f%c", bytes, "BKMGTPE"[unit]);
384 }
385 
386 static void
387 usage(void)
388 {
389 	(void)fprintf(stderr,
390 		"usage: du [-H | -L | -P] [-a | -s | -d depth] [-c] [-h | -k] [-x] [-I mask] [file ...]\n");
391 	exit(EX_USAGE);
392 }
393 
394 void
395 ignoreadd(const char *mask)
396 {
397 	struct ignentry *ign;
398 
399 	ign = calloc(1, sizeof(*ign));
400 	if (ign == NULL)
401 		errx(1, "cannot allocate memory");
402 	ign->mask = strdup(mask);
403 	if (ign->mask == NULL)
404 		errx(1, "cannot allocate memory");
405 	SLIST_INSERT_HEAD(&ignores, ign, next);
406 }
407 
408 void
409 ignoreclean(void)
410 {
411 	struct ignentry *ign;
412 
413 	while (!SLIST_EMPTY(&ignores)) {
414 		ign = SLIST_FIRST(&ignores);
415 		SLIST_REMOVE_HEAD(&ignores, next);
416 		free(ign->mask);
417 		free(ign);
418 	}
419 }
420 
421 int
422 ignorep(FTSENT *ent)
423 {
424 	struct ignentry *ign;
425 
426 	SLIST_FOREACH(ign, &ignores, next)
427 		if (fnmatch(ign->mask, ent->fts_name, 0) != FNM_NOMATCH)
428 			return 1;
429 	return 0;
430 }
431