1/*	$NetBSD: df.c,v 1.102 2023/12/18 08:27:24 kre Exp $ */
2
3/*
4 * Copyright (c) 1980, 1990, 1993, 1994
5 *	The Regents of the University of California.  All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 3. 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#include <sys/cdefs.h>
38#ifndef lint
39__COPYRIGHT(
40"@(#) Copyright (c) 1980, 1990, 1993, 1994\
41 The Regents of the University of California.  All rights reserved.");
42#endif /* not lint */
43
44#ifndef lint
45#if 0
46static char sccsid[] = "@(#)df.c	8.7 (Berkeley) 4/2/94";
47#else
48__RCSID("$NetBSD: df.c,v 1.102 2023/12/18 08:27:24 kre Exp $");
49#endif
50#endif /* not lint */
51
52#include <sys/param.h>
53#include <sys/stat.h>
54#include <sys/mount.h>
55
56#include <assert.h>
57#include <err.h>
58#include <errno.h>
59#include <stdbool.h>
60#include <fcntl.h>
61#include <locale.h>
62#include <util.h>
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66#include <unistd.h>
67#include <util.h>
68
69static char	*getmntpt(const char *);
70static void	 addstat(struct statvfs *, const struct statvfs *);
71static void	 prtstat(const struct statvfs *, int);
72static int	 selected(const char *, size_t);
73static void	 maketypelist(char *);
74static size_t	 regetmntinfo(struct statvfs **, size_t);
75__dead static void usage(void);
76static void	 prthumanval(int64_t, int);
77static void	 prthuman(const struct statvfs *, int64_t, int64_t);
78
79static int	 aflag, cflag, fflag, gflag, hflag, iflag, lflag;
80static int	 Nflag, nflag, Pflag, Wflag;
81static long	 usize;
82static char	**typelist;
83static size_t	 mntcount;
84
85#define WIDTH_INODE	10
86#define WIDTH_BLKSIZE	12
87static int blksize_width = WIDTH_BLKSIZE;
88
89static int fudgeunits = 0;
90
91int
92main(int argc, char *argv[])
93{
94	struct stat stbuf;
95	struct statvfs *mntbuf, totals;
96	int ch, maxwidth, width;
97	size_t i;
98	char *mntpt;
99
100	setprogname(argv[0]);
101	(void)setlocale(LC_ALL, "");
102
103	while ((ch = getopt(argc, argv, "abcfGgHhiklmNnPt:W")) != -1)
104		switch (ch) {
105		case 'a':
106			aflag = 1;
107			break;
108		case 'b':
109			hflag = 0;
110			usize = 512;
111			break;
112		case 'c':
113			cflag = 1;
114			break;
115		case 'f':
116			fflag = 1;
117			break;
118		case 'g':
119			hflag = 0;
120			usize = 1024 * 1024 * 1024;
121			break;
122		case 'G':
123			gflag = 1;
124			break;
125		case 'H':
126			fudgeunits = HN_DIVISOR_1000;
127			/* FALL THROUGH */
128		case 'h':
129			hflag = 1;
130			usize = 0;
131			break;
132		case 'i':
133			iflag = 1;
134			break;
135		case 'k':
136			hflag = 0;
137			usize = 1024;
138			break;
139		case 'l':
140			lflag = 1;
141			break;
142		case 'm':
143			hflag = 0;
144			usize = 1024 * 1024;
145			break;
146		case 'N':
147			Nflag = 1;
148			break;
149		case 'n':
150			nflag = 1;
151			break;
152		case 'P':
153			Pflag = 1;
154			break;
155		case 'W':
156			Wflag = 1;
157			break;
158		case 't':
159			if (typelist != NULL)
160				errx(EXIT_FAILURE,
161				    "only one -t option may be specified.");
162			maketypelist(optarg);
163			break;
164		case '?':
165		default:
166			usage();
167		}
168
169	if (fflag && (Pflag || gflag))
170		errx(EXIT_FAILURE,
171		    "only one of -f -G and -P may be specified");
172	if (gflag && (Pflag || iflag))
173		errx(EXIT_FAILURE,
174		    "only one of -G and -P or -i may be specified");
175	if (Pflag && iflag)
176		errx(EXIT_FAILURE,
177		    "only one of -P and -i may be specified");
178	if (fflag)
179		Nflag = 1;
180
181#if 0
182	/*
183	 * The block size cannot be checked until after getbsize() is called.
184	 */
185	if (Pflag && (hflag || (usize != 1024 && usize != 512)))
186		errx(EXIT_FAILURE,
187		    "non-standard block size incompatible with -P");
188#endif
189	argc -= optind;
190	argv += optind;
191
192	mntcount = getmntinfo(&mntbuf, MNT_NOWAIT);
193	if (mntcount == 0)
194		err(EXIT_FAILURE,
195		    "retrieving information on mounted file systems");
196
197	if (*argv == NULL) {
198		mntcount = regetmntinfo(&mntbuf, mntcount);
199	} else {
200		if ((mntbuf = calloc(argc, sizeof(*mntbuf))) == NULL)
201			err(EXIT_FAILURE, "can't allocate statvfs array");
202		mntcount = 0;
203		for (/*EMPTY*/; *argv != NULL; argv++) {
204			if (stat(*argv, &stbuf) < 0) {
205				if ((mntpt = getmntpt(*argv)) == 0) {
206					warn("%s", *argv);
207					continue;
208				}
209			} else if (S_ISBLK(stbuf.st_mode)) {
210				if ((mntpt = getmntpt(*argv)) == 0)
211					mntpt = *argv;
212			} else
213				mntpt = *argv;
214			/*
215			 * Statfs does not take a `wait' flag, so we cannot
216			 * implement nflag here.
217			 */
218			if (!statvfs(mntpt, &mntbuf[mntcount]))
219				if (lflag &&
220				    (mntbuf[mntcount].f_flag & MNT_LOCAL) == 0)
221					warnx("Warning: %s is not a local %s",
222					    *argv, "file system");
223				else if
224				    (!selected(mntbuf[mntcount].f_fstypename,
225					sizeof(mntbuf[mntcount].f_fstypename)))
226					warnx("Warning: %s mounted as a %s %s",
227					    *argv,
228					    mntbuf[mntcount].f_fstypename,
229					    "file system");
230				else
231					++mntcount;
232			else
233				warn("%s", *argv);
234		}
235	}
236
237	if (cflag) {
238		memset(&totals, 0, sizeof(totals));
239		totals.f_frsize = DEV_BSIZE;
240		strlcpy(totals.f_mntfromname, "total",
241			sizeof(totals.f_mntfromname));
242	}
243
244	maxwidth = 0;
245	for (i = 0; i < mntcount; i++) {
246		width = 0;
247		if (Wflag && mntbuf[i].f_mntfromlabel[0]) {
248			/* +5 is for "NAME=" added later */
249			width = (int)strlen(mntbuf[i].f_mntfromlabel) + 5;
250		}
251		if (width == 0)
252			width = (int)strlen(mntbuf[i].f_mntfromname);
253		if (width > maxwidth)
254			maxwidth = width;
255		if (cflag)
256			addstat(&totals, &mntbuf[i]);
257	}
258
259	if (cflag == 0 || fflag == 0)
260		for (i = 0; i < mntcount; i++)
261			prtstat(&mntbuf[i], maxwidth);
262
263	mntcount = fflag;
264	if (cflag)
265		prtstat(&totals, maxwidth);
266
267	return 0;
268}
269
270static char *
271getmntpt(const char *name)
272{
273	size_t count, i;
274	struct statvfs *mntbuf;
275
276	count = getmntinfo(&mntbuf, MNT_NOWAIT);
277	if (count == 0)
278		err(EXIT_FAILURE, "Can't get mount information");
279	for (i = 0; i < count; i++) {
280		if (!strcmp(mntbuf[i].f_mntfromname, name))
281			return mntbuf[i].f_mntonname;
282	}
283	return 0;
284}
285
286static enum { IN_LIST, NOT_IN_LIST } which;
287
288static int
289selected(const char *type, size_t len)
290{
291	char **av;
292
293	/* If no type specified, it's always selected. */
294	if (typelist == NULL)
295		return 1;
296	for (av = typelist; *av != NULL; ++av)
297		if (!strncmp(type, *av, len))
298			return which == IN_LIST ? 1 : 0;
299	return which == IN_LIST ? 0 : 1;
300}
301
302static void
303maketypelist(char *fslist)
304{
305	size_t i;
306	char *nextcp, **av;
307
308	if ((fslist == NULL) || (fslist[0] == '\0'))
309		errx(EXIT_FAILURE, "empty type list");
310
311	/*
312	 * XXX
313	 * Note: the syntax is "noxxx,yyy" for no xxx's and
314	 * no yyy's, not the more intuitive "noyyy,noyyy".
315	 */
316	if (fslist[0] == 'n' && fslist[1] == 'o') {
317		fslist += 2;
318		which = NOT_IN_LIST;
319	} else
320		which = IN_LIST;
321
322	/* Count the number of types. */
323	for (i = 1, nextcp = fslist;
324	    (nextcp = strchr(nextcp, ',')) != NULL; i++)
325		++nextcp;
326
327	/* Build an array of that many types. */
328	if ((av = typelist = calloc((i + 1), sizeof(*av))) == NULL)
329		err(EXIT_FAILURE, "can't allocate type array");
330	av[0] = fslist;
331	for (i = 1, nextcp = fslist;
332	    (nextcp = strchr(nextcp, ',')) != NULL; i++) {
333		*nextcp = '\0';
334		av[i] = ++nextcp;
335	}
336	/* Terminate the array. */
337	av[i] = NULL;
338}
339
340/*
341 * Make a pass over the filesystem info in ``mntbuf'' filtering out
342 * filesystem types not in ``fsmask'' and possibly re-stating to get
343 * current (not cached) info.  Returns the new count of valid statvfs bufs.
344 */
345static size_t
346regetmntinfo(struct statvfs **mntbufp, size_t count)
347{
348	size_t i, j;
349	struct statvfs *mntbuf;
350
351	if (!lflag && typelist == NULL && aflag)
352		return nflag ? count : (size_t)getmntinfo(mntbufp, MNT_WAIT);
353
354	mntbuf = *mntbufp;
355	j = 0;
356	for (i = 0; i < count; i++) {
357		if (!aflag && (mntbuf[i].f_flag & MNT_IGNORE) != 0)
358			continue;
359		if (lflag && (mntbuf[i].f_flag & MNT_LOCAL) == 0)
360			continue;
361		if (!selected(mntbuf[i].f_fstypename,
362		    sizeof(mntbuf[i].f_fstypename)))
363			continue;
364		if (nflag)
365			mntbuf[j] = mntbuf[i];
366		else {
367			struct statvfs layerbuf = mntbuf[i];
368			(void)statvfs(mntbuf[i].f_mntonname, &mntbuf[j]);
369			/*
370			 * If the FS name changed, then new data is for
371			 * a different layer and we don't want it.
372			 */
373			if (memcmp(layerbuf.f_mntfromname,
374			    mntbuf[j].f_mntfromname, MNAMELEN))
375				mntbuf[j] = layerbuf;
376		}
377		j++;
378	}
379	return j;
380}
381
382static void
383prthumanval(int64_t bytes, int width)
384{
385	char buf[6];
386
387	(void)humanize_number(buf, sizeof(buf) - (bytes < 0 ? 0 : 1),
388	    bytes, "", HN_AUTOSCALE,
389	    HN_B | HN_NOSPACE | HN_DECIMAL | fudgeunits);
390
391	(void)printf("%*s", width, buf);
392}
393
394static void
395prthuman(const struct statvfs *sfsp, int64_t used, int64_t bavail)
396{
397
398	prthumanval((int64_t)(sfsp->f_blocks * sfsp->f_frsize), blksize_width);
399	prthumanval((int64_t)(used * sfsp->f_frsize), 1 + blksize_width);
400	prthumanval((int64_t)(bavail * sfsp->f_frsize), 1 + blksize_width);
401}
402
403/*
404 * Convert statvfs returned filesystem size into BLOCKSIZE units.
405 * Attempts to avoid overflow for large filesystems.
406 */
407#define fsbtoblk(num, fsbs, bs)					\
408	(((fsbs) != 0 && (uint64_t)(fsbs) < (uint64_t)(bs)) ?	\
409	    (int64_t)(num) / (int64_t)((bs) / (fsbs)) :		\
410	    (int64_t)(num) * (int64_t)((fsbs) / (bs)))
411
412static void
413addstat(struct statvfs *totalfsp, const struct statvfs *sfsp)
414{
415	uint64_t frsize;
416
417	frsize = sfsp->f_frsize / totalfsp->f_frsize;
418	totalfsp->f_blocks += sfsp->f_blocks * frsize;
419	totalfsp->f_bfree += sfsp->f_bfree * frsize;
420	totalfsp->f_bavail += sfsp->f_bavail * frsize;
421	totalfsp->f_bresvd += sfsp->f_bresvd * frsize;
422	totalfsp->f_files += sfsp->f_files;
423	totalfsp->f_ffree += sfsp->f_ffree;
424	totalfsp->f_favail += sfsp->f_favail;
425	totalfsp->f_fresvd += sfsp->f_fresvd;
426}
427
428/*
429 * Print out status about a filesystem.
430 */
431static void
432prtstat(const struct statvfs *sfsp, int maxwidth)
433{
434	static long blocksize;
435	static int headerlen, timesthrough;
436	static const char *header;
437	static const char full[] = "100";
438	static const char empty[] = "  0";
439	int64_t used, availblks, inodes;
440	int64_t bavail;
441	char pb[64];
442	char mntfromname[sizeof(sfsp->f_mntfromname) + 10];
443
444	if (Wflag && sfsp->f_mntfromlabel[0]) {
445		snprintf(mntfromname, sizeof(mntfromname), "NAME=%s",
446		    sfsp->f_mntfromlabel);
447	} else {
448		strlcpy(mntfromname, sfsp->f_mntfromname, sizeof(mntfromname));
449	}
450
451	if (gflag) {
452		/*
453		 * From SunOS-5.6:
454		 *
455		 * /var               (/dev/dsk/c0t0d0s3 ):         8192 block size          1024 frag size
456		 *   984242 total blocks     860692 free blocks   859708 available         249984 total files
457		 *   248691 free files      8388611 filesys id
458		 *      ufs fstype       0x00000004 flag             255 filename length
459		 *
460		 */
461		(void)printf("%10s (%-12s): %7ld block size %12ld frag size\n",
462		    sfsp->f_mntonname, mntfromname,
463		    sfsp->f_bsize,	/* On UFS/FFS systems this is
464					 * also called the "optimal
465					 * transfer block size" but it
466					 * is of course the file
467					 * system's block size too.
468					 */
469		    sfsp->f_frsize);	/* not so surprisingly the
470					 * "fundamental file system
471					 * block size" is the frag
472					 * size.
473					 */
474		(void)printf("%10" PRId64 " total blocks %10" PRId64
475		    " free blocks  %10" PRId64 " available\n",
476		    (uint64_t)sfsp->f_blocks, (uint64_t)sfsp->f_bfree,
477		    (uint64_t)sfsp->f_bavail);
478		(void)printf("%10" PRId64 " total files  %10" PRId64
479		    " free files %12lx filesys id\n",
480		    (uint64_t)sfsp->f_ffree, (uint64_t)sfsp->f_files,
481		    sfsp->f_fsid);
482		(void)printf("%10s fstype  %#15lx flag  %17ld filename "
483		    "length\n", sfsp->f_fstypename, sfsp->f_flag,
484		    sfsp->f_namemax);
485		(void)printf("%10lu owner %17" PRId64 " syncwrites %12" PRId64
486		    " asyncwrites\n\n", (unsigned long)sfsp->f_owner,
487		    sfsp->f_syncwrites, sfsp->f_asyncwrites);
488
489		/*
490		 * a concession by the structured programming police to the
491		 * indentation police....
492		 */
493		return;
494	}
495	if (maxwidth < 12)
496		maxwidth = 12;
497	if (++timesthrough == 1) {
498		switch (blocksize = usize) {
499		case 512:
500			header = "512-blocks";
501			headerlen = (int)strlen(header);
502			break;
503		case 1024:
504			header = Pflag ? "1024-blocks" : "1K-blocks";
505			headerlen = (int)strlen(header);
506			break;
507		case 1024 * 1024:
508			header = "1M-blocks";
509			headerlen = (int)strlen(header);
510			break;
511		case 1024 * 1024 * 1024:
512			header = "1G-blocks";
513			headerlen = (int)strlen(header);
514			break;
515		default:
516			if (hflag) {
517				header = "Size";
518				headerlen = (int)strlen(header);
519				blksize_width = 6;
520			} else
521				header = getbsize(&headerlen, &blocksize);
522			break;
523		}
524
525		if (blocksize >= 1024 * 1024)
526			blksize_width -= 3;
527		if (blocksize >= 1024 * 1024 * 1024)
528			blksize_width -= 3;
529		if (blksize_width < headerlen)
530			blksize_width = headerlen;
531
532		if (Pflag) {
533			/*
534			 * either:
535			 *  "Filesystem 1024-blocks Used Available Capacity Mounted on\n"
536			 * or:
537			 *  "Filesystem 512-blocks Used Available Capacity Mounted on\n"
538			 */
539			if (blocksize != 1024 && blocksize != 512)
540				errx(EXIT_FAILURE,
541				    "non-standard block size incompatible with -P");
542			(void)printf("Filesystem %s Used Available Capacity "
543			    "Mounted on\n", header);
544		} else if (!Nflag) {
545			(void)printf("%-*.*s %*s %*s %*s %%Cap",
546			    maxwidth, maxwidth, "Filesystem",
547			    blksize_width, header,
548			    blksize_width, "Used",
549			    blksize_width, "Avail");
550			if (iflag) {
551				(void)printf(" %*s %*s %%iCap",
552				    WIDTH_INODE, "iUsed",
553				    WIDTH_INODE, "iAvail");
554			}
555			(void)printf(" Mounted on\n");
556		}
557	}
558	used = sfsp->f_blocks - sfsp->f_bfree;
559	bavail = sfsp->f_bfree - sfsp->f_bresvd;
560	availblks = bavail + used;
561	if (Pflag) {
562		assert(hflag == 0);
563		assert(blocksize > 0);
564		/*
565		 * "%s %d %d %d %s %s\n", <file system name>, <total space>,
566		 * <space used>, <space free>, <percentage used>,
567		 * <file system root>
568		 */
569		(void)printf("%s %" PRId64 " %" PRId64 " %" PRId64 " %s%% %s\n",
570		    mntfromname,
571		    fsbtoblk(sfsp->f_blocks, sfsp->f_frsize, blocksize),
572		    fsbtoblk(used, sfsp->f_frsize, blocksize),
573		    fsbtoblk(bavail, sfsp->f_frsize, blocksize),
574		    availblks == 0 ? full : strspct(pb, sizeof(pb), used,
575		    availblks, 0), sfsp->f_mntonname);
576		/*
577		 * another concession by the structured programming police to
578		 * the indentation police....
579		 *
580		 * Note iflag cannot be set when Pflag is set.
581		 */
582		return;
583	}
584
585	if (fflag) {
586		if (iflag)
587			(void)printf("%jd", sfsp->f_ffree);
588		else if (hflag)
589			prthumanval(bavail * sfsp->f_frsize, 1);
590		else
591			(void)printf("%jd", fsbtoblk(bavail,
592			    sfsp->f_frsize, blocksize));
593
594		if (mntcount != 1)
595			(void)printf(" %s\n", sfsp->f_mntonname);
596		else
597			(void)printf("\n");
598		return;
599	}
600
601	(void)printf("%-*.*s ", maxwidth, maxwidth, mntfromname);
602
603	if (hflag)
604		prthuman(sfsp, used, bavail);
605	else
606		(void)printf("%*" PRId64 " %*" PRId64 " %*" PRId64,
607		    blksize_width,
608		    fsbtoblk(sfsp->f_blocks, sfsp->f_frsize, blocksize),
609		    blksize_width, fsbtoblk(used, sfsp->f_frsize, blocksize),
610		    blksize_width, fsbtoblk(bavail, sfsp->f_frsize, blocksize));
611	(void)printf(" %3s%%",
612	    availblks == 0 ? full :
613	    strspct(pb, sizeof(pb), used, availblks, 0));
614	if (iflag) {
615		inodes = sfsp->f_files;
616		used = inodes - sfsp->f_ffree;
617		(void)printf(" %*jd %*jd %4s%%",
618		    WIDTH_INODE, (intmax_t)used,
619		    WIDTH_INODE, (intmax_t)sfsp->f_ffree,
620		    inodes == 0 ? (used == 0 ? empty : full) :
621		    strspct(pb, sizeof(pb), used, inodes, 0));
622	}
623	(void)printf(" %s\n", sfsp->f_mntonname);
624}
625
626static void
627usage(void)
628{
629
630	(void)fprintf(stderr,
631	    "Usage: %s [-aclnW] [-G|-bkP|-bfgHhikmN] [-t type] [file | "
632	    "file_system]...\n",
633	    getprogname());
634	exit(1);
635	/* NOTREACHED */
636}
637