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