limits.c revision 27573
1/*-
2 * Copyright (c) 1997 by
3 * David L. Nugent <davidn@blaze.net.au>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, is permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice immediately at the beginning of the file, without modification,
11 *    this list of conditions, and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. This work was done expressly for inclusion into FreeBSD.  Other use
16 *    is permitted provided this notation is included.
17 * 4. Absolutely no warranty of function or purpose is made by the authors.
18 * 5. Modifications may be freely made to this file providing the above
19 *    conditions are met.
20 *
21 * Display/change(+runprogram)/eval resource limits.
22 *
23 *	$Id: limits.c,v 1.4 1997/05/10 19:00:58 davidn Exp $
24 */
25
26#include <err.h>
27#include <stdio.h>
28#include <string.h>
29#include <sys/types.h>
30#include <sys/stat.h>
31#include <sys/param.h>
32#include <stdlib.h>
33#include <unistd.h>
34#include <stdarg.h>
35#include <ctype.h>
36#include <errno.h>
37#include <pwd.h>
38#include <login_cap.h>
39#include <sys/time.h>
40#include <sys/resource.h>
41
42enum
43{
44    SH_NONE,
45    SH_SH,      /* sh */
46    SH_CSH,     /* csh */
47    SH_BASH,    /* gnu bash */
48    SH_TCSH,    /* tcsh */
49    SH_KSH,     /* (pd)ksh */
50    SH_ZSH,     /* zsh */
51    SH_RC,      /* rc or es */
52    SH_NUMBER
53};
54
55
56/* eval emitter for popular shells.
57 * Why aren't there any standards here? Most shells support either
58 * the csh 'limit' or sh 'ulimit' command, but each varies just
59 * enough that they aren't very compatible from one to the other.
60 */
61static struct {
62    const char * name;	    /* Name of shell */
63    const char * inf;	    /* Name used for 'unlimited' resource */
64    const char * cmd;	    /* Intro text */
65    const char * hard;	    /* Hard limit text */
66    const char * soft;	    /* Soft limit text */
67    const char * both;	    /* Hard+Soft limit text */
68    struct {
69	const char * pfx;
70	const char * sfx;
71	int divisor;
72    } lprm[RLIM_NLIMITS];
73} shellparm[] =
74{
75    { "", "infinity", "Resource limits%s%s:\n", "-max", "-cur", "",
76      {
77	  { "  cputime%-4s      %8s", " secs\n",  1    },
78	  { "  filesize%-4s     %8s", " kb\n",    1024 },
79	  { "  datasize%-4s     %8s", " kb\n",    1024 },
80	  { "  stacksize%-4s    %8s", " kb\n",    1024 },
81	  { "  coredumpsize%-4s %8s", " kb\n",    1024 },
82	  { "  memoryuse%-4s    %8s", " kb\n",    1024 },
83	  { "  memorylocked%-4s %8s", " kb\n",    1024 },
84	  { "  maxprocesses%-4s %8s", "\n",       1    },
85	  { "  openfiles%-4s    %8s", "\n",       1    }
86      }
87    },
88    { "sh", "unlimited", "", " -H", " -S", "",
89      {
90	  { "ulimit%s -t %s", ";\n",  1    },
91	  { "ulimit%s -f %s", ";\n",  512  },
92	  { "ulimit%s -d %s", ";\n",  1024 },
93	  { "ulimit%s -s %s", ";\n",  1024 },
94	  { "ulimit%s -c %s", ";\n",  512  },
95	  { "ulimit%s -m %s", ";\n",  1024 },
96	  { "ulimit%s -l %s", ";\n",  1024 },
97	  { "ulimit%s -u %s", ";\n",  1    },
98	  { "ulimit%s -n %s", ";\n",  1    }
99      }
100    },
101    { "csh", "unlimited", "", " -h", "", NULL,
102      {
103	  { "limit%s cputime %s",      ";\n",  1    },
104	  { "limit%s filesize %s",     ";\n",  1024 },
105	  { "limit%s datasize %s",     ";\n",  1024 },
106	  { "limit%s stacksize %s",    ";\n",  1024 },
107	  { "limit%s coredumpsize %s", ";\n",  1024 },
108	  { "limit%s memoryuse %s",    ";\n",  1024 },
109	  { "limit%s memorylocked %s", ";\n",  1024 },
110	  { "limit%s maxproc %s",      ";\n",  1    },
111	  { "limit%s openfiles %s",    ";\n",  1    }
112      }
113    },
114    { "bash|bash2", "unlimited", "", " -H", " -S", "",
115      {
116	  { "ulimit%s -t %s", ";\n",  1    },
117	  { "ulimit%s -f %s", ";\n",  1024 },
118	  { "ulimit%s -d %s", ";\n",  1024 },
119	  { "ulimit%s -s %s", ";\n",  1024 },
120	  { "ulimit%s -c %s", ";\n",  1024 },
121	  { "ulimit%s -m %s", ";\n",  1024 },
122	  { "ulimit%s -l %s", ";\n",  1024 },
123	  { "ulimit%s -u %s", ";\n",  1    },
124	  { "ulimit%s -n %s", ";\n",  1    }
125      }
126    },
127    { "tcsh", "unlimited", "", " -h", "", NULL,
128      {
129	  { "limit%s cputime %s",      ";\n",  1    },
130	  { "limit%s filesize %s",     ";\n",  1024 },
131	  { "limit%s datasize %s",     ";\n",  1024 },
132	  { "limit%s stacksize %s",    ";\n",  1024 },
133	  { "limit%s coredumpsize %s", ";\n",  1024 },
134	  { "limit%s memoryuse %s",    ";\n",  1024 },
135	  { "limit%s memorylocked %s", ";\n",  1024 },
136	  { "limit%s maxproc %s",      ";\n",  1    },
137	  { "limit%s descriptors %s",  ";\n",  1    }
138      }
139    },
140    { "ksh|pdksh", "unlimited", "", " -H", " -S", "",
141      {
142	  { "ulimit%s -t %s", ";\n",  1    },
143	  { "ulimit%s -f %s", ";\n",  512  },
144	  { "ulimit%s -d %s", ";\n",  1024 },
145	  { "ulimit%s -s %s", ";\n",  1024 },
146	  { "ulimit%s -c %s", ";\n",  512  },
147	  { "ulimit%s -m %s", ";\n",  1024 },
148	  { "ulimit%s -l %s", ";\n",  1024 },
149	  { "ulimit%s -p %s", ";\n",  1    },
150	  { "ulimit%s -n %s", ";\n",  1    }
151      }
152    },
153    { "zsh", "unlimited", "", " -H", " -S", "",
154      {
155	  { "ulimit%s -t %s", ";\n",  1    },
156	  { "ulimit%s -f %s", ";\n",  512  },
157	  { "ulimit%s -d %s", ";\n",  1024 },
158	  { "ulimit%s -s %s", ";\n",  1024 },
159	  { "ulimit%s -c %s", ";\n",  512  },
160	  { "ulimit%s -m %s", ";\n",  1024 },
161	  { "ulimit%s -l %s", ";\n",  1024 },
162	  { "ulimit%s -u %s", ";\n",  1    },
163	  { "ulimit%s -n %s", ";\n",  1    }
164      }
165    },
166    { "rc|es", "unlimited", "", " -h", "", NULL,
167      {
168	  { "limit%s cputime %s",      ";\n",  1    },
169	  { "limit%s filesize %s",     ";\n",  1024 },
170	  { "limit%s datasize %s",     ";\n",  1024 },
171	  { "limit%s stacksize %s",    ";\n",  1024 },
172	  { "limit%s coredumpsize %s", ";\n",  1024 },
173	  { "limit%s memoryuse %s",    ";\n",  1024 },
174	  { "limit%s lockedmemory %s", ";\n",  1024 },
175	  { "limit%s processes %s",    ";\n",  1    },
176	  { "limit%s descriptors %s",  ";\n",  1    }
177      }
178    },
179    { NULL }
180};
181
182static struct {
183    const char * cap;
184    rlim_t (*func)(login_cap_t *, const char *, rlim_t, rlim_t);
185} resources[RLIM_NLIMITS] = {
186    { "cputime",	login_getcaptime },
187    { "filesize",	login_getcapsize },
188    { "datasize",	login_getcapsize },
189    { "stacksize",	login_getcapsize },
190    { "coredumpsize",	login_getcapsize },
191    { "memoryuse",	login_getcapsize },
192    { "memorylocked",	login_getcapsize },
193    { "maxproc",	login_getcapnum, },
194    { "openfiles",	login_getcapnum  }
195};
196
197/*
198 * One letter for each resource levels.
199 * NOTE: There is a dependancy on the corresponding
200 * letter index being equal to the resource number.
201 * If sys/resource.h defines are changed, this needs
202 * to be modified accordingly!
203 */
204
205#define RCS_STRING  "tfdscmlun"
206
207static rlim_t resource_num(int which, int ch, const char *str);
208static void usage(const char *msg, ...);
209static int getshelltype(void);
210static void print_limit(rlim_t limit, unsigned divisor, const char *inf,
211			const char *pfx, const char *sfx, const char *which);
212extern char **environ;
213
214static const char rcs_string[] = RCS_STRING;
215
216int
217main(int argc, char *argv[])
218{
219    char *p, *cls = NULL;
220    char *cleanenv[1];
221    struct passwd * pwd = NULL;
222    int rcswhich, shelltype;
223    int i, num_limits = 0;
224    int ch, doeval = 0, doall = 0;
225    login_cap_t * lc = NULL;
226    enum { ANY=0, SOFT=1, HARD=2, BOTH=3, DISPLAYONLY=4 } type = ANY;
227    enum { RCSUNKNOWN=0, RCSSET=1, RCSSEL=2 } todo = RCSUNKNOWN;
228    int which_limits[RLIM_NLIMITS];
229    rlim_t set_limits[RLIM_NLIMITS];
230    struct rlimit limits[RLIM_NLIMITS];
231
232    /* init resource tables */
233    for (i = 0; i < RLIM_NLIMITS; i++) {
234	which_limits[i] = 0; /* Don't set/display any */
235	set_limits[i] = RLIM_INFINITY;
236	/* Get current resource values */
237	getrlimit(i, &limits[i]);
238    }
239
240    optarg = NULL;
241    while ((ch = getopt(argc, argv, ":EeC:U:BSHac:d:f:l:m:n:s:t:u:")) != -1) {
242	switch(ch) {
243	case 'a':
244	    doall = 1;
245	    break;
246	case 'E':
247	    environ = cleanenv;
248	    cleanenv[0] = NULL;
249	    break;
250	case 'e':
251	    doeval = 1;
252	    break;
253	case 'C':
254	    cls = optarg;
255	    break;
256	case 'U':
257	    if ((pwd = getpwnam(optarg)) == NULL) {
258		if (!isdigit(*optarg) ||
259		    (pwd = getpwuid(atoi(optarg))) == NULL) {
260		    usage("Invalid user `%s'\n", optarg);
261		}
262	    }
263	    break;
264	case 'H':
265	    type = HARD;
266	    break;
267	case 'S':
268	    type = SOFT;
269	    break;
270	case 'B':
271	    type = SOFT|HARD;
272	    break;
273	default:
274	case ':': /* Without arg */
275	    if ((p = strchr(rcs_string, optopt)) != NULL) {
276		int rcswhich = p - rcs_string;
277		if (optarg && *optarg == '-') { /* 'arg' is actually a switch */
278		    --optind;		/* back one arg, and make arg NULL */
279		    optarg = NULL;
280		}
281		todo = optarg == NULL ? RCSSEL : RCSSET;
282		if (type == ANY)
283		    type = BOTH;
284		which_limits[rcswhich] = optarg ? type : DISPLAYONLY;
285		set_limits[rcswhich] = resource_num(rcswhich, optopt, optarg);
286		num_limits++;
287		break;
288	    }
289	    /* FALLTHRU */
290	case '?':
291	    usage(NULL);
292	}
293	optarg = NULL;
294    }
295
296    /* If user was specified, get class from that */
297    if (pwd != NULL)
298	lc = login_getpwclass(pwd);
299    else if (cls != NULL && *cls != '\0') {
300	lc = login_getclassbyname(cls, NULL);
301	if (lc == NULL || strcmp(cls, lc->lc_class) != 0)
302	    fprintf(stderr, "login class '%s' non-existent, using %s\n",
303		    cls, lc?lc->lc_class:"current settings");
304    }
305
306    /* If we have a login class, update resource table from that */
307    if (lc != NULL) {
308	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
309	    char str[40];
310	    rlim_t val;
311
312	    /* current value overridden by resourcename or resourcename-cur */
313	    sprintf(str, "%s-cur", resources[rcswhich].cap);
314	    val = resources[rcswhich].func(lc, resources[rcswhich].cap, limits[rcswhich].rlim_cur, limits[rcswhich].rlim_cur);
315	    limits[rcswhich].rlim_cur = resources[rcswhich].func(lc, str, val, val);
316	    /* maximum value overridden by resourcename or resourcename-max */
317	    sprintf(str, "%s-max", resources[rcswhich].cap);
318	    val = resources[rcswhich].func(lc, resources[rcswhich].cap, limits[rcswhich].rlim_max, limits[rcswhich].rlim_max);
319	    limits[rcswhich].rlim_max = resources[rcswhich].func(lc, str, val, val);
320	}
321    }
322
323    /* now, let's determine what we wish to do with all this */
324
325    argv += optind;
326
327    /* If we're setting limits or doing an eval (ie. we're not just
328     * displaying), then check that hard limits are not lower than
329     * soft limits, and force rasing the hard limit if we need to if
330     * we are raising the soft limit, or lower the soft limit if we
331     * are lowering the hard limit.
332     */
333    if ((*argv || doeval) && getuid() == 0) {
334
335	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
336	    if (limits[rcswhich].rlim_max != RLIM_INFINITY) {
337		if (limits[rcswhich].rlim_cur == RLIM_INFINITY) {
338		    limits[rcswhich].rlim_max = RLIM_INFINITY;
339		    which_limits[rcswhich] |= HARD;
340		} else if (limits[rcswhich].rlim_cur > limits[rcswhich].rlim_max) {
341		    if (which_limits[rcswhich] == SOFT) {
342			limits[rcswhich].rlim_max = limits[rcswhich].rlim_cur;
343			which_limits[rcswhich] |= HARD;
344		    }  else if (which_limits[rcswhich] == HARD) {
345			limits[rcswhich].rlim_cur = limits[rcswhich].rlim_max;
346			which_limits[rcswhich] |= SOFT;
347		    } else {
348			/* else.. if we're specifically setting both to
349			 * silly values, then let it error out.
350			 */
351		    }
352		}
353	    }
354	}
355    }
356
357    /* See if we've overridden anything specific on the command line */
358    if (num_limits && todo == RCSSET) {
359	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
360	    if (which_limits[rcswhich] & HARD)
361		limits[rcswhich].rlim_max = set_limits[rcswhich];
362	    if (which_limits[rcswhich] & SOFT)
363		limits[rcswhich].rlim_cur = set_limits[rcswhich];
364	}
365    }
366
367    /* If *argv is not NULL, then we are being asked to
368     * (perhaps) set environment variables and run a program
369     */
370    if (*argv) {
371	if (doeval)
372	    usage("-e cannot be used with `cmd' option\n");
373
374	login_close(lc);
375
376	/* set leading environment variables, like eval(1) */
377	while (*argv && (p = strchr(*argv, '=')))
378	    (void)setenv(*argv++, ++p, 1);
379
380	/* Set limits */
381	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
382	    if (doall || num_limits == 0 || which_limits[rcswhich] != 0)
383		if (setrlimit(rcswhich, &limits[rcswhich]) == -1)
384		    err(1, "setrlimit %s", resources[rcswhich].cap);
385	}
386
387	if (*argv == NULL)
388	    usage(NULL);
389
390	execvp(*argv, argv);
391	err(1, "%s", *argv);
392    }
393
394    shelltype = doeval ? getshelltype() : SH_NONE;
395
396    if (type == ANY) /* Default to soft limits */
397	type = SOFT;
398
399    /* Display limits */
400    printf(shellparm[shelltype].cmd,
401	   lc ? " for class " : " (current)",
402	   lc ? lc->lc_class : "");
403
404    for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
405	if (doall || num_limits == 0 || which_limits[rcswhich] != 0) {
406	    if (which_limits[rcswhich] == ANY || which_limits[rcswhich])
407		which_limits[rcswhich] = type;
408	    if (shellparm[shelltype].lprm[rcswhich].pfx) {
409		if (shellparm[shelltype].both && limits[rcswhich].rlim_cur == limits[rcswhich].rlim_max) {
410		    print_limit(limits[rcswhich].rlim_max,
411				shellparm[shelltype].lprm[rcswhich].divisor,
412				shellparm[shelltype].inf,
413				shellparm[shelltype].lprm[rcswhich].pfx,
414				shellparm[shelltype].lprm[rcswhich].sfx,
415				shellparm[shelltype].both);
416		} else {
417		    if (which_limits[rcswhich] & HARD) {
418			print_limit(limits[rcswhich].rlim_max,
419				    shellparm[shelltype].lprm[rcswhich].divisor,
420				    shellparm[shelltype].inf,
421				    shellparm[shelltype].lprm[rcswhich].pfx,
422				    shellparm[shelltype].lprm[rcswhich].sfx,
423				    shellparm[shelltype].hard);
424		    }
425		    if (which_limits[rcswhich] & SOFT) {
426			print_limit(limits[rcswhich].rlim_cur,
427				    shellparm[shelltype].lprm[rcswhich].divisor,
428				    shellparm[shelltype].inf,
429				    shellparm[shelltype].lprm[rcswhich].pfx,
430				    shellparm[shelltype].lprm[rcswhich].sfx,
431				    shellparm[shelltype].soft);
432		    }
433		}
434	    }
435	}
436    }
437
438    login_close(lc);
439    exit(EXIT_SUCCESS);
440}
441
442
443static void
444usage(char const *msg, ...)
445{
446    if (msg) {
447	va_list argp;
448	va_start(argp, msg);
449	vfprintf(stderr, msg, argp);
450	va_end(argp);
451    }
452    (void)fprintf(stderr,
453"usage: limits [-C class|-U user] [-eaSHBE] [-cdflmnstu [val]] [[name=val ...] cmd]\n");
454    exit(EXIT_FAILURE);
455}
456
457static void
458print_limit(rlim_t limit, unsigned divisor, const char * inf, const char * pfx, const char * sfx, const char * which)
459{
460    char numbr[64];
461
462    if (limit == RLIM_INFINITY)
463	strcpy(numbr, inf);
464    else
465	sprintf(numbr, "%qd", (quad_t)((limit + divisor/2) / divisor));
466    printf(pfx, which, numbr);
467    printf(sfx, which);
468
469}
470
471
472static rlim_t
473resource_num(int which, int ch, const char *str)
474{
475    rlim_t res = RLIM_INFINITY;
476
477    if (str != NULL &&
478	!(strcasecmp(str, "inf") == 0 ||
479	  strcasecmp(str, "infinity") == 0 ||
480	  strcasecmp(str, "unlimit") == 0 ||
481	  strcasecmp(str, "unlimited") == 0)) {
482	const char * s = str;
483	char *e;
484
485	switch (which) {
486	case RLIMIT_CPU:	/* time values */
487	    errno = 0;
488	    res = 0;
489	    while (*s) {
490		rlim_t tim = strtoq(s, &e, 0);
491		if (e == NULL || e == s || errno)
492		    break;
493		switch (*e++) {
494		case 0:		   	/* end of string */
495		    e--;
496		default:
497		case 's': case 'S':	/* seconds */
498		    break;
499		case 'm': case 'M':	/* minutes */
500		    tim *= 60L;
501		    break;
502		case 'h': case 'H':	/* hours */
503		    tim *= (60L * 60L);
504		    break;
505		case 'd': case 'D':	/* days */
506		    tim *= (60L * 60L * 24L);
507		    break;
508		case 'w': case 'W':	/* weeks */
509		    tim *= (60L * 60L * 24L * 7L);
510		case 'y': case 'Y':	/* Years */
511		    tim *= (60L * 60L * 24L * 365L);
512		}
513		s = e;
514		res += tim;
515	    }
516	    break;
517	case RLIMIT_FSIZE: /* Size values */
518	case RLIMIT_DATA:
519	case RLIMIT_STACK:
520	case RLIMIT_CORE:
521	case RLIMIT_RSS:
522	case RLIMIT_MEMLOCK:
523	    errno = 0;
524	    res = 0;
525	    while (*s) {
526		rlim_t mult, tim = strtoq(s, &e, 0);
527		if (e == NULL || e == s || errno)
528		    break;
529		switch (*e++) {
530		case 0:	/* end of string */
531		    e--;
532		default:
533		    mult = 1;
534		    break;
535		case 'b': case 'B':	/* 512-byte blocks */
536		    mult = 512;
537		    break;
538		case 'k': case 'K':	/* 1024-byte Kilobytes */
539		    mult = 1024;
540		    break;
541		case 'm': case 'M':	/* 1024-k kbytes */
542		    mult = 1024 * 1024;
543		    break;
544		case 'g': case 'G':	/* 1Gbyte */
545		    mult = 1024 * 1024 * 1024;
546		    break;
547		case 't': case 'T':	/* 1TBte */
548		    mult = 1024LL * 1024LL * 1024LL * 1024LL;
549		    break;
550		}
551		s = e;
552		res += (tim * mult);
553	    }
554	    break;
555	case RLIMIT_NPROC:
556	case RLIMIT_NOFILE:
557	    res = strtoq(s, &e, 0);
558	    s = e;
559	    break;
560	}
561	if (*s)
562	    usage("invalid value -%c `%s'\n", ch, str);
563    }
564    return res;
565}
566
567
568static int
569getshellbyname(const char * shell)
570{
571    int i;
572    const char * q;
573    const char * p = strrchr(shell, '/');
574
575    p = p ? ++p : shell;
576    for (i = 0; (q = shellparm[i].name) != NULL; i++) {
577	while (*q) {
578	    int j = strcspn(q, "|");
579
580	    if (j == 0)
581		break;
582	    if (strncmp(p, q, j) == 0)
583		return i;
584	    if (*(q += j))
585		++q;
586	}
587    }
588    return SH_SH;
589}
590
591
592/*
593 * Determine the type of shell our parent process is
594 * This is quite tricky, not 100% reliable and probably
595 * not nearly as thorough as it should be. Basically, this
596 * is a "best guess" only, but hopefully will work in
597 * most cases.
598 */
599
600static int
601getshelltype(void)
602{
603    pid_t ppid = getppid();
604
605    if (ppid != 1) {
606	FILE * fp;
607	struct stat st;
608	char procdir[MAXPATHLEN], buf[128];
609	int l = sprintf(procdir, "/proc/%ld/", (long)ppid);
610	char * shell = getenv("SHELL");
611
612	if (shell != NULL && stat(shell, &st) != -1) {
613	    struct stat st1;
614
615	    strcpy(procdir+l, "file");
616	    /* $SHELL is actual shell? */
617	    if (stat(procdir, &st1) != -1 && memcmp(&st, &st1, sizeof st) == 0)
618		return getshellbyname(shell);
619	}
620	strcpy(procdir+l, "status");
621	if (stat(procdir, &st) == 0 && (fp = fopen(procdir, "r")) != NULL) {
622	    char * p = fgets(buf, sizeof buf, fp)==NULL ? NULL : strtok(buf, " \t");
623	    fclose(fp);
624	    if (p != NULL)
625		return getshellbyname(p);
626	}
627    }
628    return SH_SH;
629}
630
631