1/*
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1980, 1990, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Robert Elz at The University of Melbourne.
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#ifndef lint
36static const char copyright[] =
37"@(#) Copyright (c) 1980, 1990, 1993\n\
38	The Regents of the University of California.  All rights reserved.\n";
39#endif
40
41#ifndef lint
42static const char sccsid[] = "from: @(#)quota.c	8.1 (Berkeley) 6/6/93";
43#endif /* not lint */
44
45/*
46 * Disk quota reporting program.
47 */
48#include <sys/cdefs.h>
49__FBSDID("$FreeBSD$");
50
51#include <sys/param.h>
52#include <sys/types.h>
53#include <sys/file.h>
54#include <sys/stat.h>
55#include <sys/mount.h>
56#include <sys/socket.h>
57
58#include <rpc/rpc.h>
59#include <rpc/pmap_prot.h>
60#include <rpcsvc/rquota.h>
61
62#include <ufs/ufs/quota.h>
63
64#include <ctype.h>
65#include <err.h>
66#include <fstab.h>
67#include <grp.h>
68#include <libutil.h>
69#include <netdb.h>
70#include <pwd.h>
71#include <stdio.h>
72#include <stdint.h>
73#include <stdlib.h>
74#include <string.h>
75#include <time.h>
76#include <unistd.h>
77
78static const char *qfextension[] = INITQFNAMES;
79
80struct quotause {
81	struct	quotause *next;
82	long	flags;
83	struct	dqblk dqblk;
84	char	fsname[MAXPATHLEN + 1];
85};
86
87static char *timeprt(int64_t seconds);
88static struct quotause *getprivs(long id, int quotatype);
89static void usage(void);
90static int showuid(u_long uid);
91static int showgid(u_long gid);
92static int showusrname(char *name);
93static int showgrpname(char *name);
94static int showquotas(int type, u_long id, const char *name);
95static void showrawquotas(int type, u_long id, struct quotause *qup);
96static void heading(int type, u_long id, const char *name, const char *tag);
97static int getufsquota(struct fstab *fs, struct quotause *qup, long id,
98	int quotatype);
99static int getnfsquota(struct statfs *fst, struct quotause *qup, long id,
100	int quotatype);
101static enum clnt_stat callaurpc(char *host, int prognum, int versnum, int procnum,
102	xdrproc_t inproc, char *in, xdrproc_t outproc, char *out);
103static int alldigits(char *s);
104
105static int	hflag;
106static int	lflag;
107static int	rflag;
108static int	qflag;
109static int	vflag;
110static char	*filename = NULL;
111
112int
113main(int argc, char *argv[])
114{
115	int ngroups;
116	gid_t mygid, gidset[NGROUPS];
117	int i, ch, gflag = 0, uflag = 0, errflag = 0;
118
119	while ((ch = getopt(argc, argv, "f:ghlrquv")) != -1) {
120		switch(ch) {
121		case 'f':
122			filename = optarg;
123			break;
124		case 'g':
125			gflag++;
126			break;
127		case 'h':
128			hflag++;
129			break;
130		case 'l':
131			lflag++;
132			break;
133		case 'q':
134			qflag++;
135			break;
136		case 'r':
137			rflag++;
138			break;
139		case 'u':
140			uflag++;
141			break;
142		case 'v':
143			vflag++;
144			break;
145		default:
146			usage();
147		}
148	}
149	argc -= optind;
150	argv += optind;
151	if (!uflag && !gflag)
152		uflag++;
153	if (argc == 0) {
154		if (uflag)
155			errflag += showuid(getuid());
156		if (gflag) {
157			mygid = getgid();
158			ngroups = getgroups(NGROUPS, gidset);
159			if (ngroups < 0)
160				err(1, "getgroups");
161			errflag += showgid(mygid);
162			for (i = 0; i < ngroups; i++)
163				if (gidset[i] != mygid)
164					errflag += showgid(gidset[i]);
165		}
166		return(errflag);
167	}
168	if (uflag && gflag)
169		usage();
170	if (uflag) {
171		for (; argc > 0; argc--, argv++) {
172			if (alldigits(*argv))
173				errflag += showuid(atoi(*argv));
174			else
175				errflag += showusrname(*argv);
176		}
177		return(errflag);
178	}
179	if (gflag) {
180		for (; argc > 0; argc--, argv++) {
181			if (alldigits(*argv))
182				errflag += showgid(atoi(*argv));
183			else
184				errflag += showgrpname(*argv);
185		}
186	}
187	return(errflag);
188}
189
190static void
191usage(void)
192{
193
194	fprintf(stderr, "%s\n%s\n%s\n",
195	    "usage: quota [-ghlu] [-f path] [-v | -q | -r]",
196	    "       quota [-hlu] [-f path] [-v | -q | -r] user ...",
197	    "       quota -g [-hl] [-f path] [-v | -q | -r] group ...");
198	exit(1);
199}
200
201/*
202 * Print out quotas for a specified user identifier.
203 */
204static int
205showuid(u_long uid)
206{
207	struct passwd *pwd = getpwuid(uid);
208	const char *name;
209
210	if (pwd == NULL)
211		name = "(no account)";
212	else
213		name = pwd->pw_name;
214	return(showquotas(USRQUOTA, uid, name));
215}
216
217/*
218 * Print out quotas for a specifed user name.
219 */
220static int
221showusrname(char *name)
222{
223	struct passwd *pwd = getpwnam(name);
224
225	if (pwd == NULL) {
226		warnx("%s: unknown user", name);
227		return(1);
228	}
229	return(showquotas(USRQUOTA, pwd->pw_uid, name));
230}
231
232/*
233 * Print out quotas for a specified group identifier.
234 */
235static int
236showgid(u_long gid)
237{
238	struct group *grp = getgrgid(gid);
239	const char *name;
240
241	if (grp == NULL)
242		name = "(no entry)";
243	else
244		name = grp->gr_name;
245	return(showquotas(GRPQUOTA, gid, name));
246}
247
248/*
249 * Print out quotas for a specifed group name.
250 */
251static int
252showgrpname(char *name)
253{
254	struct group *grp = getgrnam(name);
255
256	if (grp == NULL) {
257		warnx("%s: unknown group", name);
258		return(1);
259	}
260	return(showquotas(GRPQUOTA, grp->gr_gid, name));
261}
262
263static void
264prthumanval(int len, u_int64_t bytes)
265{
266	char buf[len + 1];
267
268	/*
269	 * Limit the width to 5 bytes as that is what users expect.
270	 */
271	humanize_number(buf, MIN(sizeof(buf), 5), bytes, "",
272			HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
273
274	(void)printf(" %*s", len, buf);
275}
276
277static int
278showquotas(int type, u_long id, const char *name)
279{
280	struct quotause *qup;
281	struct quotause *quplist;
282	const char *msgi, *msgb;
283	const char *nam;
284	char *bgrace = NULL, *igrace = NULL;
285	int lines = 0, overquota = 0;
286	static time_t now;
287
288	if (now == 0)
289		time(&now);
290	quplist = getprivs(id, type);
291	for (qup = quplist; qup; qup = qup->next) {
292		msgi = NULL;
293		if (qup->dqblk.dqb_ihardlimit &&
294		    qup->dqblk.dqb_curinodes >= qup->dqblk.dqb_ihardlimit) {
295			overquota++;
296			msgi = "File limit reached on";
297		}
298		else if (qup->dqblk.dqb_isoftlimit &&
299		    qup->dqblk.dqb_curinodes >= qup->dqblk.dqb_isoftlimit) {
300			overquota++;
301			if (qup->dqblk.dqb_itime > now)
302				msgi = "In file grace period on";
303			else
304				msgi = "Over file quota on";
305		}
306		msgb = NULL;
307		if (qup->dqblk.dqb_bhardlimit &&
308		    qup->dqblk.dqb_curblocks >= qup->dqblk.dqb_bhardlimit) {
309			overquota++;
310			msgb = "Block limit reached on";
311		}
312		else if (qup->dqblk.dqb_bsoftlimit &&
313		    qup->dqblk.dqb_curblocks >= qup->dqblk.dqb_bsoftlimit) {
314			overquota++;
315			if (qup->dqblk.dqb_btime > now)
316				msgb = "In block grace period on";
317			else
318				msgb = "Over block quota on";
319		}
320		if (rflag) {
321			showrawquotas(type, id, qup);
322			continue;
323		}
324		if (!vflag &&
325		    qup->dqblk.dqb_isoftlimit == 0 &&
326		    qup->dqblk.dqb_ihardlimit == 0 &&
327		    qup->dqblk.dqb_bsoftlimit == 0 &&
328		    qup->dqblk.dqb_bhardlimit == 0)
329			continue;
330		if (qflag) {
331			if ((msgi != NULL || msgb != NULL) &&
332			    lines++ == 0)
333				heading(type, id, name, "");
334			if (msgi != NULL)
335				printf("\t%s %s\n", msgi, qup->fsname);
336			if (msgb != NULL)
337				printf("\t%s %s\n", msgb, qup->fsname);
338			continue;
339		}
340		if (!vflag &&
341		    qup->dqblk.dqb_curblocks == 0 &&
342		    qup->dqblk.dqb_curinodes == 0)
343			continue;
344		if (lines++ == 0)
345			heading(type, id, name, "");
346		nam = qup->fsname;
347		if (strlen(qup->fsname) > 15) {
348			printf("%s\n", qup->fsname);
349			nam = "";
350		}
351		printf("%-15s", nam);
352		if (hflag) {
353			prthumanval(7, dbtob(qup->dqblk.dqb_curblocks));
354			printf("%c", (msgb == NULL) ? ' ' : '*');
355			prthumanval(7, dbtob(qup->dqblk.dqb_bsoftlimit));
356			prthumanval(7, dbtob(qup->dqblk.dqb_bhardlimit));
357		} else {
358			printf(" %7ju%c %7ju %7ju",
359			    (uintmax_t)dbtob(qup->dqblk.dqb_curblocks)
360				/ 1024,
361			    (msgb == NULL) ? ' ' : '*',
362			    (uintmax_t)dbtob(qup->dqblk.dqb_bsoftlimit)
363				/ 1024,
364			    (uintmax_t)dbtob(qup->dqblk.dqb_bhardlimit)
365				/ 1024);
366		}
367		if (msgb != NULL)
368			bgrace = timeprt(qup->dqblk.dqb_btime);
369		if (msgi != NULL)
370			igrace = timeprt(qup->dqblk.dqb_itime);
371		printf("%8s %6ju%c %6ju %6ju%8s\n"
372			, (msgb == NULL) ? "" : bgrace
373			, (uintmax_t)qup->dqblk.dqb_curinodes
374			, (msgi == NULL) ? ' ' : '*'
375			, (uintmax_t)qup->dqblk.dqb_isoftlimit
376			, (uintmax_t)qup->dqblk.dqb_ihardlimit
377			, (msgi == NULL) ? "" : igrace
378		);
379		if (msgb != NULL)
380			free(bgrace);
381		if (msgi != NULL)
382			free(igrace);
383	}
384	if (!qflag && !rflag && lines == 0)
385		heading(type, id, name, "none");
386	return (overquota);
387}
388
389static void
390showrawquotas(int type, u_long id, struct quotause *qup)
391{
392	time_t t;
393
394	printf("Raw %s quota information for id %lu on %s\n",
395	    type == USRQUOTA ? "user" : "group", id, qup->fsname);
396	printf("block hard limit:     %ju\n",
397	    (uintmax_t)qup->dqblk.dqb_bhardlimit);
398	printf("block soft limit:     %ju\n",
399	    (uintmax_t)qup->dqblk.dqb_bsoftlimit);
400	printf("current block count:  %ju\n",
401	    (uintmax_t)qup->dqblk.dqb_curblocks);
402	printf("i-node hard limit:    %ju\n",
403	    (uintmax_t)qup->dqblk.dqb_ihardlimit);
404	printf("i-node soft limit:    %ju\n",
405	    (uintmax_t)qup->dqblk.dqb_isoftlimit);
406	printf("current i-node count: %ju\n",
407	    (uintmax_t)qup->dqblk.dqb_curinodes);
408	printf("block grace time:     %jd",
409	    (intmax_t)qup->dqblk.dqb_btime);
410	if (qup->dqblk.dqb_btime != 0) {
411		t = qup->dqblk.dqb_btime;
412		printf(" %s", ctime(&t));
413	} else {
414		printf("\n");
415	}
416	printf("i-node grace time:    %jd", (intmax_t)qup->dqblk.dqb_itime);
417	if (qup->dqblk.dqb_itime != 0) {
418		t = qup->dqblk.dqb_itime;
419		printf(" %s", ctime(&t));
420	} else {
421		printf("\n");
422	}
423}
424
425
426static void
427heading(int type, u_long id, const char *name, const char *tag)
428{
429
430	printf("Disk quotas for %s %s (%cid %lu): %s\n", qfextension[type],
431	    name, *qfextension[type], id, tag);
432	if (!qflag && tag[0] == '\0') {
433		printf("%-15s %7s %8s %7s %7s %6s %7s %6s%8s\n"
434			, "Filesystem"
435			, "usage"
436			, "quota"
437			, "limit"
438			, "grace"
439			, "files"
440			, "quota"
441			, "limit"
442			, "grace"
443		);
444	}
445}
446
447/*
448 * Calculate the grace period and return a printable string for it.
449 */
450static char *
451timeprt(int64_t seconds)
452{
453	time_t hours, minutes;
454	char *buf;
455	static time_t now;
456
457	if (now == 0)
458		time(&now);
459	if (now > seconds) {
460		if ((buf = strdup("none")) == NULL)
461			errx(1, "strdup() failed in timeprt()");
462		return (buf);
463	}
464	seconds -= now;
465	minutes = (seconds + 30) / 60;
466	hours = (minutes + 30) / 60;
467	if (hours >= 36) {
468		if (asprintf(&buf, "%lddays", ((long)hours + 12) / 24) < 0)
469			errx(1, "asprintf() failed in timeprt(1)");
470		return (buf);
471	}
472	if (minutes >= 60) {
473		if (asprintf(&buf, "%2ld:%ld", (long)minutes / 60,
474		    (long)minutes % 60) < 0)
475			errx(1, "asprintf() failed in timeprt(2)");
476		return (buf);
477	}
478	if (asprintf(&buf, "%2ld", (long)minutes) < 0)
479		errx(1, "asprintf() failed in timeprt(3)");
480	return (buf);
481}
482
483/*
484 * Collect the requested quota information.
485 */
486static struct quotause *
487getprivs(long id, int quotatype)
488{
489	struct quotause *qup, *quptail = NULL;
490	struct fstab *fs;
491	struct quotause *quphead;
492	struct statfs *fst;
493	int nfst, i;
494	struct statfs sfb;
495
496	qup = quphead = (struct quotause *)0;
497
498	if (filename != NULL && statfs(filename, &sfb) != 0)
499		err(1, "cannot statfs %s", filename);
500	nfst = getmntinfo(&fst, MNT_NOWAIT);
501	if (nfst == 0)
502		errx(2, "no filesystems mounted!");
503	setfsent();
504	for (i = 0; i < nfst; i++) {
505		if (qup == NULL) {
506			if ((qup = (struct quotause *)malloc(sizeof *qup))
507			    == NULL)
508				errx(2, "out of memory");
509		}
510		/*
511		 * See if the user requested a specific file system
512		 * or specified a file inside a mounted file system.
513		 */
514		if (filename != NULL &&
515		    strcmp(sfb.f_mntonname, fst[i].f_mntonname) != 0)
516			continue;
517		if (strcmp(fst[i].f_fstypename, "nfs") == 0) {
518			if (lflag)
519				continue;
520			if (getnfsquota(&fst[i], qup, id, quotatype) == 0)
521				continue;
522		} else if (strcmp(fst[i].f_fstypename, "ufs") == 0) {
523			/*
524			 * XXX
525			 * UFS filesystems must be in /etc/fstab, and must
526			 * indicate that they have quotas on (?!) This is quite
527			 * unlike SunOS where quotas can be enabled/disabled
528			 * on a filesystem independent of /etc/fstab, and it
529			 * will still print quotas for them.
530			 */
531			if ((fs = getfsspec(fst[i].f_mntfromname)) == NULL)
532				continue;
533			if (getufsquota(fs, qup, id, quotatype) == 0)
534				continue;
535		} else
536			continue;
537		strcpy(qup->fsname, fst[i].f_mntonname);
538		if (quphead == NULL)
539			quphead = qup;
540		else
541			quptail->next = qup;
542		quptail = qup;
543		quptail->next = 0;
544		qup = NULL;
545	}
546	if (qup)
547		free(qup);
548	endfsent();
549	return (quphead);
550}
551
552/*
553 * Check to see if a particular quota is available.
554 */
555static int
556getufsquota(struct fstab *fs, struct quotause *qup, long id, int quotatype)
557{
558	struct quotafile *qf;
559
560	if ((qf = quota_open(fs, quotatype, O_RDONLY)) == NULL)
561		return (0);
562	if (quota_read(qf, &qup->dqblk, id) != 0)
563		return (0);
564	quota_close(qf);
565	return (1);
566}
567
568static int
569getnfsquota(struct statfs *fst, struct quotause *qup, long id, int quotatype)
570{
571	struct ext_getquota_args gq_args;
572	struct getquota_args old_gq_args;
573	struct getquota_rslt gq_rslt;
574	struct dqblk *dqp = &qup->dqblk;
575	struct timeval tv;
576	char *cp, host[NI_MAXHOST];
577	enum clnt_stat call_stat;
578
579	if (fst->f_flags & MNT_LOCAL)
580		return (0);
581
582	/*
583	 * must be some form of "hostname:/path"
584	 */
585	cp = fst->f_mntfromname;
586	do {
587		cp = strrchr(cp, ':');
588	} while (cp != NULL && *(cp + 1) != '/');
589	if (cp == NULL) {
590		warnx("cannot find hostname for %s", fst->f_mntfromname);
591		return (0);
592	}
593	memset(host, 0, sizeof(host));
594	memcpy(host, fst->f_mntfromname, cp - fst->f_mntfromname);
595	host[sizeof(host) - 1] = '\0';
596
597	/* Avoid attempting the RPC for special amd(8) filesystems. */
598	if (strncmp(fst->f_mntfromname, "pid", 3) == 0 &&
599	    strchr(fst->f_mntfromname, '@') != NULL)
600		return (0);
601
602	gq_args.gqa_pathp = cp + 1;
603	gq_args.gqa_id = id;
604	gq_args.gqa_type = quotatype;
605
606	call_stat = callaurpc(host, RQUOTAPROG, EXT_RQUOTAVERS,
607			      RQUOTAPROC_GETQUOTA, (xdrproc_t)xdr_ext_getquota_args, (char *)&gq_args,
608			      (xdrproc_t)xdr_getquota_rslt, (char *)&gq_rslt);
609	if (call_stat == RPC_PROGVERSMISMATCH || call_stat == RPC_PROGNOTREGISTERED) {
610		if (quotatype == USRQUOTA) {
611			old_gq_args.gqa_pathp = cp + 1;
612			old_gq_args.gqa_uid = id;
613			call_stat = callaurpc(host, RQUOTAPROG, RQUOTAVERS,
614					      RQUOTAPROC_GETQUOTA, (xdrproc_t)xdr_getquota_args, (char *)&old_gq_args,
615					      (xdrproc_t)xdr_getquota_rslt, (char *)&gq_rslt);
616		} else {
617			/* Old rpc quota does not support group type */
618			return (0);
619		}
620	}
621	if (call_stat != 0)
622		return (call_stat);
623
624	switch (gq_rslt.status) {
625	case Q_NOQUOTA:
626		break;
627	case Q_EPERM:
628		warnx("quota permission error, host: %s",
629			fst->f_mntfromname);
630		break;
631	case Q_OK:
632		gettimeofday(&tv, NULL);
633			/* blocks*/
634		dqp->dqb_bhardlimit =
635		    ((uint64_t)gq_rslt.getquota_rslt_u.gqr_rquota.rq_bhardlimit *
636		    gq_rslt.getquota_rslt_u.gqr_rquota.rq_bsize) / DEV_BSIZE;
637		dqp->dqb_bsoftlimit =
638		    ((uint64_t)gq_rslt.getquota_rslt_u.gqr_rquota.rq_bsoftlimit *
639		    gq_rslt.getquota_rslt_u.gqr_rquota.rq_bsize) / DEV_BSIZE;
640		dqp->dqb_curblocks =
641		    ((uint64_t)gq_rslt.getquota_rslt_u.gqr_rquota.rq_curblocks *
642		    gq_rslt.getquota_rslt_u.gqr_rquota.rq_bsize) / DEV_BSIZE;
643			/* inodes */
644		dqp->dqb_ihardlimit =
645			gq_rslt.getquota_rslt_u.gqr_rquota.rq_fhardlimit;
646		dqp->dqb_isoftlimit =
647			gq_rslt.getquota_rslt_u.gqr_rquota.rq_fsoftlimit;
648		dqp->dqb_curinodes =
649			gq_rslt.getquota_rslt_u.gqr_rquota.rq_curfiles;
650			/* grace times */
651		dqp->dqb_btime =
652		    tv.tv_sec + gq_rslt.getquota_rslt_u.gqr_rquota.rq_btimeleft;
653		dqp->dqb_itime =
654		    tv.tv_sec + gq_rslt.getquota_rslt_u.gqr_rquota.rq_ftimeleft;
655		return (1);
656	default:
657		warnx("bad rpc result, host: %s", fst->f_mntfromname);
658		break;
659	}
660
661	return (0);
662}
663
664static enum clnt_stat
665callaurpc(char *host, int prognum, int versnum, int procnum,
666    xdrproc_t inproc, char *in, xdrproc_t outproc, char *out)
667{
668	enum clnt_stat clnt_stat;
669	struct timeval timeout, tottimeout;
670
671	CLIENT *client = NULL;
672
673 	client = clnt_create(host, prognum, versnum, "udp");
674	if (client == NULL)
675		return ((int)rpc_createerr.cf_stat);
676	timeout.tv_usec = 0;
677	timeout.tv_sec = 6;
678	CLNT_CONTROL(client, CLSET_RETRY_TIMEOUT, (char *)(void *)&timeout);
679
680	client->cl_auth = authunix_create_default();
681	tottimeout.tv_sec = 25;
682	tottimeout.tv_usec = 0;
683	clnt_stat = clnt_call(client, procnum, inproc, in,
684	    outproc, out, tottimeout);
685	return (clnt_stat);
686}
687
688static int
689alldigits(char *s)
690{
691	int c;
692
693	c = *s++;
694	do {
695		if (!isdigit(c))
696			return (0);
697	} while ((c = *s++));
698	return (1);
699}
700