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