xref: /freebsd/usr.bin/limits/limits.c (revision 6b13d60bf49ee40626d7e3a5d5a80519f0067307)
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 
24 #include <sys/cdefs.h>
25 #include <err.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/sysctl.h>
31 #include <sys/user.h>
32 #include <sys/param.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <stdarg.h>
36 #include <stdint.h>
37 #include <ctype.h>
38 #include <errno.h>
39 #include <pwd.h>
40 #include <login_cap.h>
41 #include <sys/time.h>
42 #include <sys/resource.h>
43 
44 enum
45 {
46     SH_NONE,
47     SH_SH,      /* sh */
48     SH_CSH,     /* csh */
49     SH_BASH,    /* gnu bash */
50     SH_TCSH,    /* tcsh */
51     SH_KSH,     /* (pd)ksh */
52     SH_ZSH,     /* zsh */
53     SH_RC,      /* rc or es */
54     SH_NUMBER
55 };
56 
57 
58 /* eval emitter for popular shells.
59  * Why aren't there any standards here? Most shells support either
60  * the csh 'limit' or sh 'ulimit' command, but each varies just
61  * enough that they aren't very compatible from one to the other.
62  */
63 static struct {
64     const char * name;	    /* Name of shell */
65     const char * inf;	    /* Name used for 'unlimited' resource */
66     const char * cmd;	    /* Intro text */
67     const char * hard;	    /* Hard limit text */
68     const char * soft;	    /* Soft limit text */
69     const char * both;	    /* Hard+Soft limit text */
70     struct {
71 	const char * pfx;
72 	const char * sfx;
73 	int divisor;
74     } lprm[RLIM_NLIMITS];
75 } shellparm[] =
76 {
77     { "", "infinity", "Resource limits%s%s:\n", "-max", "-cur", "",
78       {
79 	  { "  cputime%-4s          %8s", " secs\n",  1    },
80 	  { "  filesize%-4s         %8s", " kB\n",    1024 },
81 	  { "  datasize%-4s         %8s", " kB\n",    1024 },
82 	  { "  stacksize%-4s        %8s", " kB\n",    1024 },
83 	  { "  coredumpsize%-4s     %8s", " kB\n",    1024 },
84 	  { "  memoryuse%-4s        %8s", " kB\n",    1024 },
85 	  { "  memorylocked%-4s     %8s", " kB\n",    1024 },
86 	  { "  maxprocesses%-4s     %8s", "\n",       1    },
87 	  { "  openfiles%-4s        %8s", "\n",       1    },
88 	  { "  sbsize%-4s           %8s", " bytes\n", 1    },
89 	  { "  vmemoryuse%-4s       %8s", " kB\n",    1024 },
90 	  { "  pseudo-terminals%-4s %8s", "\n",       1    },
91 	  { "  swapuse%-4s          %8s", " kB\n",    1024 },
92 	  { "  kqueues%-4s          %8s", "\n",       1    },
93 	  { "  umtxp%-4s            %8s", "\n",       1    },
94       }
95     },
96     { "sh", "unlimited", "", " -H", " -S", "",
97       {
98 	  { "ulimit%s -t %s", ";\n",  1    },
99 	  { "ulimit%s -f %s", ";\n",  512  },
100 	  { "ulimit%s -d %s", ";\n",  1024 },
101 	  { "ulimit%s -s %s", ";\n",  1024 },
102 	  { "ulimit%s -c %s", ";\n",  512  },
103 	  { "ulimit%s -m %s", ";\n",  1024 },
104 	  { "ulimit%s -l %s", ";\n",  1024 },
105 	  { "ulimit%s -u %s", ";\n",  1    },
106 	  { "ulimit%s -n %s", ";\n",  1    },
107 	  { "ulimit%s -b %s", ";\n",  1    },
108 	  { "ulimit%s -v %s", ";\n",  1024 },
109 	  { "ulimit%s -p %s", ";\n",  1    },
110 	  { "ulimit%s -w %s", ";\n",  1024 },
111 	  { "ulimit%s -k %s", ";\n",  1    },
112 	  { "ulimit%s -o %s", ";\n",  1    },
113       }
114     },
115     { "csh", "unlimited", "", " -h", "", NULL,
116       {
117 	  { "limit%s cputime %s",         ";\n",  1    },
118 	  { "limit%s filesize %s",        ";\n",  1024 },
119 	  { "limit%s datasize %s",        ";\n",  1024 },
120 	  { "limit%s stacksize %s",       ";\n",  1024 },
121 	  { "limit%s coredumpsize %s",    ";\n",  1024 },
122 	  { "limit%s memoryuse %s",       ";\n",  1024 },
123 	  { "limit%s memorylocked %s",    ";\n",  1024 },
124 	  { "limit%s maxproc %s",         ";\n",  1    },
125 	  { "limit%s openfiles %s",       ";\n",  1    },
126 	  { "limit%s sbsize %s",          ";\n",  1    },
127 	  { "limit%s vmemoryuse %s",      ";\n",  1024 },
128 	  { "limit%s pseudoterminals %s", ";\n",  1    },
129 	  { "limit%s swapsize %s",        ";\n",  1024 },
130 	  { "limit%s kqueues %s",         ";\n",  1    },
131 	  { "limit%s umtxp %s",           ";\n",  1    },
132       }
133     },
134     { "bash|bash2", "unlimited", "", " -H", " -S", "",
135       {
136 	  { "ulimit%s -t %s", ";\n",  1    },
137 	  { "ulimit%s -f %s", ";\n",  1024 },
138 	  { "ulimit%s -d %s", ";\n",  1024 },
139 	  { "ulimit%s -s %s", ";\n",  1024 },
140 	  { "ulimit%s -c %s", ";\n",  1024 },
141 	  { "ulimit%s -m %s", ";\n",  1024 },
142 	  { "ulimit%s -l %s", ";\n",  1024 },
143 	  { "ulimit%s -u %s", ";\n",  1    },
144 	  { "ulimit%s -n %s", ";\n",  1    },
145 	  { "ulimit%s -b %s", ";\n",  1    },
146 	  { "ulimit%s -v %s", ";\n",  1024 },
147 	  { "ulimit%s -p %s", ";\n",  1    },
148 	  { "ulimit%s -w %s", ";\n",  1024 }
149       }
150     },
151     { "tcsh", "unlimited", "", " -h", "", NULL,
152       {
153 	  { "limit%s cputime %s",         ";\n",  1    },
154 	  { "limit%s filesize %s",        ";\n",  1024 },
155 	  { "limit%s datasize %s",        ";\n",  1024 },
156 	  { "limit%s stacksize %s",       ";\n",  1024 },
157 	  { "limit%s coredumpsize %s",    ";\n",  1024 },
158 	  { "limit%s memoryuse %s",       ";\n",  1024 },
159 	  { "limit%s memorylocked %s",    ";\n",  1024 },
160 	  { "limit%s maxproc %s",         ";\n",  1    },
161 	  { "limit%s descriptors %s",     ";\n",  1    },
162 	  { "limit%s sbsize %s",          ";\n",  1    },
163 	  { "limit%s vmemoryuse %s",      ";\n",  1024 },
164 	  { "limit%s pseudoterminals %s", ";\n",  1    },
165 	  { "limit%s swapsize %s",        ";\n",  1024 },
166 	  { "limit%s kqueues %s",         ";\n",  1    },
167 	  { "limit%s umtxp %s",           ";\n",  1    },
168       }
169     },
170     { "ksh|pdksh", "unlimited", "", " -H", " -S", "",
171       {
172 	  { "ulimit%s -t %s", ";\n",  1    },
173 	  { "ulimit%s -f %s", ";\n",  512  },
174 	  { "ulimit%s -d %s", ";\n",  1024 },
175 	  { "ulimit%s -s %s", ";\n",  1024 },
176 	  { "ulimit%s -c %s", ";\n",  512  },
177 	  { "ulimit%s -m %s", ";\n",  1024 },
178 	  { "ulimit%s -l %s", ";\n",  1024 },
179 	  { "ulimit%s -p %s", ";\n",  1    },
180 	  { "ulimit%s -n %s", ";\n",  1    },
181 	  { "ulimit%s -b %s", ";\n",  1    },
182 	  { "ulimit%s -v %s", ";\n",  1024 },
183 	  { "ulimit%s -p %s", ";\n",  1    },
184 	  { "ulimit%s -w %s", ";\n",  1024 }
185       }
186     },
187     { "zsh", "unlimited", "", " -H", " -S", "",
188       {
189 	  { "ulimit%s -t %s", ";\n",  1    },
190 	  { "ulimit%s -f %s", ";\n",  512  },
191 	  { "ulimit%s -d %s", ";\n",  1024 },
192 	  { "ulimit%s -s %s", ";\n",  1024 },
193 	  { "ulimit%s -c %s", ";\n",  512  },
194 	  { "ulimit%s -m %s", ";\n",  1024 },
195 	  { "ulimit%s -l %s", ";\n",  1024 },
196 	  { "ulimit%s -u %s", ";\n",  1    },
197 	  { "ulimit%s -n %s", ";\n",  1    },
198 	  { "ulimit%s -b %s", ";\n",  1    },
199 	  { "ulimit%s -v %s", ";\n",  1024 },
200 	  { "ulimit%s -p %s", ";\n",  1    },
201 	  { "ulimit%s -w %s", ";\n",  1024 }
202       }
203     },
204     { "rc|es", "unlimited", "", " -h", "", NULL,
205       {
206 	  { "limit%s cputime %s",         ";\n",  1    },
207 	  { "limit%s filesize %s",        ";\n",  1024 },
208 	  { "limit%s datasize %s",        ";\n",  1024 },
209 	  { "limit%s stacksize %s",       ";\n",  1024 },
210 	  { "limit%s coredumpsize %s",    ";\n",  1024 },
211 	  { "limit%s memoryuse %s",       ";\n",  1024 },
212 	  { "limit%s lockedmemory %s",    ";\n",  1024 },
213 	  { "limit%s processes %s",       ";\n",  1    },
214 	  { "limit%s descriptors %s",     ";\n",  1    },
215 	  { "limit%s sbsize %s",          ";\n",  1    },
216 	  { "limit%s vmemoryuse %s",      ";\n",  1024 },
217 	  { "limit%s pseudoterminals %s", ";\n",  1    },
218 	  { "limit%s swapuse %s",         ";\n",  1024 }
219       }
220     },
221     { NULL, NULL, NULL, NULL, NULL, NULL,
222       { }
223     }
224 };
225 
226 static struct {
227     const char * cap;
228     rlim_t (*func)(login_cap_t *, const char *, rlim_t, rlim_t);
229 } resources[RLIM_NLIMITS] = {
230     { "cputime",	login_getcaptime },
231     { "filesize",	login_getcapsize },
232     { "datasize",	login_getcapsize },
233     { "stacksize",	login_getcapsize },
234     { "coredumpsize",	login_getcapsize },
235     { "memoryuse",	login_getcapsize },
236     { "memorylocked",	login_getcapsize },
237     { "maxproc",	login_getcapnum  },
238     { "openfiles",	login_getcapnum  },
239     { "sbsize",		login_getcapsize },
240     { "vmemoryuse",	login_getcapsize },
241     { "pseudoterminals",login_getcapnum  },
242     { "swapuse",	login_getcapsize },
243     { "kqueues",	login_getcapnum  },
244     { "umtxp",		login_getcapnum  },
245 };
246 
247 /*
248  * One letter for each resource levels.
249  * NOTE: There is a dependency on the corresponding
250  * letter index being equal to the resource number.
251  * If sys/resource.h defines are changed, this needs
252  * to be modified accordingly!
253  */
254 
255 #define RCS_STRING  "tfdscmlunbvpwko"
256 
257 static rlim_t resource_num(int which, int ch, const char *str);
258 static void usage(void) __dead2;
259 static int getshelltype(void);
260 static void print_limit(rlim_t limit, unsigned divisor, const char *inf,
261 			const char *pfx, const char *sfx, const char *which);
262 static void getrlimit_proc(pid_t pid, int resource, struct rlimit *rlp);
263 static void setrlimit_proc(pid_t pid, int resource, const struct rlimit *rlp);
264 extern char **environ;
265 
266 static const char rcs_string[] = RCS_STRING;
267 
268 int
269 main(int argc, char *argv[])
270 {
271     char *p, *cls = NULL;
272     char *cleanenv[1];
273     struct passwd * pwd = NULL;
274     int rcswhich, shelltype;
275     int i, num_limits = 0;
276     int ch, doeval = 0, doall = 0;
277     int rtrn, setproc;
278     login_cap_t * lc = NULL;
279     enum { ANY=0, SOFT=1, HARD=2, BOTH=3, DISPLAYONLY=4 } type = ANY;
280     enum { RCSUNKNOWN=0, RCSSET=1, RCSSEL=2 } todo = RCSUNKNOWN;
281     int which_limits[RLIM_NLIMITS];
282     rlim_t set_limits[RLIM_NLIMITS];
283     struct rlimit limits[RLIM_NLIMITS];
284     pid_t pid;
285 
286     /* init resource tables */
287     for (i = 0; i < RLIM_NLIMITS; i++) {
288 	which_limits[i] = 0; /* Don't set/display any */
289 	set_limits[i] = RLIM_INFINITY;
290     }
291 
292     pid = -1;
293     optarg = NULL;
294     while ((ch = getopt(argc, argv,
295       ":EeC:U:BSHP:ab:c:d:f:l:m:n:s:t:u:v:p:w:k:o:")) != -1) {
296 	switch(ch) {
297 	case 'a':
298 	    doall = 1;
299 	    break;
300 	case 'E':
301 	    environ = cleanenv;
302 	    cleanenv[0] = NULL;
303 	    break;
304 	case 'e':
305 	    doeval = 1;
306 	    break;
307 	case 'C':
308 	    cls = optarg;
309 	    break;
310 	case 'U':
311 	    if ((pwd = getpwnam(optarg)) == NULL) {
312 		if (!isdigit(*optarg) ||
313 		    (pwd = getpwuid(atoi(optarg))) == NULL) {
314 		    warnx("invalid user `%s'", optarg);
315 		    usage();
316 		}
317 	    }
318 	    break;
319 	case 'H':
320 	    type = HARD;
321 	    break;
322 	case 'S':
323 	    type = SOFT;
324 	    break;
325 	case 'B':
326 	    type = SOFT|HARD;
327 	    break;
328 	case 'P':
329 	    if (!isdigit(*optarg) || (pid = atoi(optarg)) < 0) {
330 		warnx("invalid pid `%s'", optarg);
331 		usage();
332 	    }
333 	    break;
334 	default:
335 	case ':': /* Without arg */
336 	    if ((p = strchr(rcs_string, optopt)) != NULL) {
337 		int rcswhich1 = p - rcs_string;
338 		if (optarg && *optarg == '-') { /* 'arg' is actually a switch */
339 		    --optind;		/* back one arg, and make arg NULL */
340 		    optarg = NULL;
341 		}
342 		todo = optarg == NULL ? RCSSEL : RCSSET;
343 		if (type == ANY)
344 		    type = BOTH;
345 		which_limits[rcswhich1] = optarg ? type : DISPLAYONLY;
346 		set_limits[rcswhich1] = resource_num(rcswhich1, optopt, optarg);
347 		num_limits++;
348 		break;
349 	    }
350 	    /* FALLTHRU */
351 	case '?':
352 	    usage();
353 	}
354 	optarg = NULL;
355     }
356 
357     if (pid != -1) {
358 	if (cls != NULL) {
359 	    warnx("-C cannot be used with -P option");
360 	    usage();
361 	}
362 	if (pwd != NULL) {
363 	    warnx("-U cannot be used with -P option");
364 	    usage();
365 	}
366     }
367 
368     /* Get current resource values */
369     setproc = 0;
370     for (i = 0; i < RLIM_NLIMITS; i++) {
371 	if (pid == -1) {
372 	    getrlimit(i, &limits[i]);
373 	} else if (doall || num_limits == 0) {
374 	    getrlimit_proc(pid, i, &limits[i]);
375 	} else if (which_limits[i] != 0) {
376 	    getrlimit_proc(pid, i, &limits[i]);
377 	    setproc = 1;
378 	}
379     }
380 
381     /* If user was specified, get class from that */
382     if (pwd != NULL)
383 	lc = login_getpwclass(pwd);
384     else if (cls != NULL && *cls != '\0') {
385 	lc = login_getclassbyname(cls, NULL);
386 	if (lc == NULL || strcmp(cls, lc->lc_class) != 0)
387 	    fprintf(stderr, "login class '%s' non-existent, using %s\n",
388 		    cls, lc?lc->lc_class:"current settings");
389     }
390 
391     /* If we have a login class, update resource table from that */
392     if (lc != NULL) {
393 	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
394 	    char str[40];
395 	    rlim_t val;
396 
397 	    /* current value overridden by resourcename or resourcename-cur */
398 	    sprintf(str, "%s-cur", resources[rcswhich].cap);
399 	    val = resources[rcswhich].func(lc, resources[rcswhich].cap, limits[rcswhich].rlim_cur, limits[rcswhich].rlim_cur);
400 	    limits[rcswhich].rlim_cur = resources[rcswhich].func(lc, str, val, val);
401 	    /* maximum value overridden by resourcename or resourcename-max */
402 	    sprintf(str, "%s-max", resources[rcswhich].cap);
403 	    val = resources[rcswhich].func(lc, resources[rcswhich].cap, limits[rcswhich].rlim_max, limits[rcswhich].rlim_max);
404 	    limits[rcswhich].rlim_max = resources[rcswhich].func(lc, str, val, val);
405 	}
406     }
407 
408     /* now, let's determine what we wish to do with all this */
409 
410     argv += optind;
411 
412     /* If we're setting limits or doing an eval (ie. we're not just
413      * displaying), then check that hard limits are not lower than
414      * soft limits, and force rasing the hard limit if we need to if
415      * we are raising the soft limit, or lower the soft limit if we
416      * are lowering the hard limit.
417      */
418     if ((*argv || doeval) && getuid() == 0) {
419 
420 	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
421 	    if (limits[rcswhich].rlim_max != RLIM_INFINITY) {
422 		if (limits[rcswhich].rlim_cur == RLIM_INFINITY) {
423 		    limits[rcswhich].rlim_max = RLIM_INFINITY;
424 		    which_limits[rcswhich] |= HARD;
425 		} else if (limits[rcswhich].rlim_cur > limits[rcswhich].rlim_max) {
426 		    if (which_limits[rcswhich] == SOFT) {
427 			limits[rcswhich].rlim_max = limits[rcswhich].rlim_cur;
428 			which_limits[rcswhich] |= HARD;
429 		    }  else if (which_limits[rcswhich] == HARD) {
430 			limits[rcswhich].rlim_cur = limits[rcswhich].rlim_max;
431 			which_limits[rcswhich] |= SOFT;
432 		    } else {
433 			/* else.. if we're specifically setting both to
434 			 * silly values, then let it error out.
435 			 */
436 		    }
437 		}
438 	    }
439 	}
440     }
441 
442     /* See if we've overridden anything specific on the command line */
443     if (num_limits && todo == RCSSET) {
444 	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
445 	    if (which_limits[rcswhich] & HARD)
446 		limits[rcswhich].rlim_max = set_limits[rcswhich];
447 	    if (which_limits[rcswhich] & SOFT)
448 		limits[rcswhich].rlim_cur = set_limits[rcswhich];
449 	}
450     }
451 
452     /* If *argv is not NULL, then we are being asked to
453      * (perhaps) set environment variables and run a program
454      */
455     if (*argv) {
456 	if (doeval) {
457 	    warnx("-e cannot be used with `cmd' option");
458 	    usage();
459 	}
460 	if (pid != -1) {
461 	    warnx("-P cannot be used with `cmd' option");
462 	    usage();
463 	}
464 
465 	login_close(lc);
466 
467 	/* set leading environment variables, like eval(1) */
468 	while (*argv && (p = strchr(*argv, '='))) {
469 		*p = '\0';
470 		rtrn = setenv(*argv++, p + 1, 1);
471 		*p = '=';
472 		if (rtrn == -1)
473 			err(EXIT_FAILURE, "setenv %s", *argv);
474 	}
475 
476 	/* Set limits */
477 	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
478 	    if (doall || num_limits == 0 || which_limits[rcswhich] != 0)
479 		if (setrlimit(rcswhich, &limits[rcswhich]) == -1)
480 		    err(1, "setrlimit %s", resources[rcswhich].cap);
481 	}
482 
483 	if (*argv == NULL)
484 	    usage();
485 
486 	execvp(*argv, argv);
487 	err(1, "%s", *argv);
488     }
489 
490     if (setproc) {
491 	for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
492 	    if (which_limits[rcswhich] != 0)
493 		setrlimit_proc(pid, rcswhich, &limits[rcswhich]);
494 	}
495 	exit(EXIT_SUCCESS);
496     }
497 
498     shelltype = doeval ? getshelltype() : SH_NONE;
499 
500     if (type == ANY) /* Default to soft limits */
501 	type = SOFT;
502 
503     /* Display limits */
504     printf(shellparm[shelltype].cmd,
505 	   lc ? " for class " : " (current)",
506 	   lc ? lc->lc_class : "");
507 
508     for (rcswhich = 0; rcswhich < RLIM_NLIMITS; rcswhich++) {
509 	if (doall || num_limits == 0 || which_limits[rcswhich] != 0) {
510 	    if (which_limits[rcswhich] == ANY)
511 		which_limits[rcswhich] = type;
512 	    if (shellparm[shelltype].lprm[rcswhich].pfx) {
513 		if (shellparm[shelltype].both && limits[rcswhich].rlim_cur == limits[rcswhich].rlim_max) {
514 		    print_limit(limits[rcswhich].rlim_max,
515 				shellparm[shelltype].lprm[rcswhich].divisor,
516 				shellparm[shelltype].inf,
517 				shellparm[shelltype].lprm[rcswhich].pfx,
518 				shellparm[shelltype].lprm[rcswhich].sfx,
519 				shellparm[shelltype].both);
520 		} else {
521 		    if (which_limits[rcswhich] & HARD) {
522 			print_limit(limits[rcswhich].rlim_max,
523 				    shellparm[shelltype].lprm[rcswhich].divisor,
524 				    shellparm[shelltype].inf,
525 				    shellparm[shelltype].lprm[rcswhich].pfx,
526 				    shellparm[shelltype].lprm[rcswhich].sfx,
527 				    shellparm[shelltype].hard);
528 		    }
529 		    if (which_limits[rcswhich] & SOFT) {
530 			print_limit(limits[rcswhich].rlim_cur,
531 				    shellparm[shelltype].lprm[rcswhich].divisor,
532 				    shellparm[shelltype].inf,
533 				    shellparm[shelltype].lprm[rcswhich].pfx,
534 				    shellparm[shelltype].lprm[rcswhich].sfx,
535 				    shellparm[shelltype].soft);
536 		    }
537 		}
538 	    }
539 	}
540     }
541 
542     login_close(lc);
543     exit(EXIT_SUCCESS);
544 }
545 
546 
547 static void
548 usage(void)
549 {
550     (void)fprintf(stderr,
551 	"usage: limits [-C class|-P pid|-U user] [-eaSHBE] "
552 	"[-bcdfklmnostuvpw [val]] [[name=val ...] cmd]\n");
553     exit(EXIT_FAILURE);
554 }
555 
556 static void
557 print_limit(rlim_t limit, unsigned divisor, const char * inf, const char * pfx, const char * sfx, const char * which)
558 {
559     char numbr[64];
560 
561     if (limit == RLIM_INFINITY)
562 	strlcpy(numbr, inf, sizeof(numbr));
563     else
564 	sprintf(numbr, "%jd", (intmax_t)((limit + divisor/2) / divisor));
565     printf(pfx, which, numbr);
566     printf(sfx, which);
567 
568 }
569 
570 
571 static rlim_t
572 resource_num(int which, int ch, const char *str)
573 {
574     rlim_t res = RLIM_INFINITY;
575 
576     if (str != NULL &&
577 	!(strcasecmp(str, "inf") == 0 ||
578 	  strcasecmp(str, "infinity") == 0 ||
579 	  strcasecmp(str, "unlimit") == 0 ||
580 	  strcasecmp(str, "unlimited") == 0)) {
581 	const char * s = str;
582 	char *e;
583 
584 	switch (which) {
585 	case RLIMIT_CPU:	/* time values */
586 	    errno = 0;
587 	    res = 0;
588 	    while (*s) {
589 		rlim_t tim = strtoq(s, &e, 0);
590 		if (e == NULL || e == s || errno)
591 		    break;
592 		switch (*e++) {
593 		case 0:		   	/* end of string */
594 		    e--;
595 		default:
596 		case 's': case 'S':	/* seconds */
597 		    break;
598 		case 'm': case 'M':	/* minutes */
599 		    tim *= 60L;
600 		    break;
601 		case 'h': case 'H':	/* hours */
602 		    tim *= (60L * 60L);
603 		    break;
604 		case 'd': case 'D':	/* days */
605 		    tim *= (60L * 60L * 24L);
606 		    break;
607 		case 'w': case 'W':	/* weeks */
608 		    tim *= (60L * 60L * 24L * 7L);
609 		    break;
610 		case 'y': case 'Y':	/* Years */
611 		    tim *= (60L * 60L * 24L * 365L);
612 		}
613 		s = e;
614 		res += tim;
615 	    }
616 	    break;
617 	case RLIMIT_FSIZE: /* Size values */
618 	case RLIMIT_DATA:
619 	case RLIMIT_STACK:
620 	case RLIMIT_CORE:
621 	case RLIMIT_RSS:
622 	case RLIMIT_MEMLOCK:
623 	case RLIMIT_SBSIZE:
624 	case RLIMIT_VMEM:
625 	case RLIMIT_SWAP:
626 	    errno = 0;
627 	    res = 0;
628 	    while (*s) {
629 		rlim_t mult, tim = strtoq(s, &e, 0);
630 		if (e == NULL || e == s || errno)
631 		    break;
632 		switch (*e++) {
633 		case 0:	/* end of string */
634 		    e--;
635 		default:
636 		    mult = 1;
637 		    break;
638 		case 'b': case 'B':	/* 512-byte blocks */
639 		    mult = 512;
640 		    break;
641 		case 'k': case 'K':	/* 1024-byte Kilobytes */
642 		    mult = 1024;
643 		    break;
644 		case 'm': case 'M':	/* 1024-k kbytes */
645 		    mult = 1024 * 1024;
646 		    break;
647 		case 'g': case 'G':	/* 1Gbyte */
648 		    mult = 1024 * 1024 * 1024;
649 		    break;
650 		case 't': case 'T':	/* 1TBte */
651 		    mult = 1024LL * 1024LL * 1024LL * 1024LL;
652 		    break;
653 		}
654 		s = e;
655 		res += (tim * mult);
656 	    }
657 	    break;
658 	case RLIMIT_NPROC:
659 	case RLIMIT_NOFILE:
660 	case RLIMIT_NPTS:
661 	case RLIMIT_KQUEUES:
662 	case RLIMIT_UMTXP:
663 	    res = strtoq(s, &e, 0);
664 	    s = e;
665 	    break;
666 	}
667 	if (*s) {
668 	    warnx("invalid value -%c `%s'", ch, str);
669 	    usage();
670 	}
671     }
672     return res;
673 }
674 
675 
676 static int
677 getshellbyname(const char * shell)
678 {
679     int i;
680     const char * q;
681     const char * p = strrchr(shell, '/');
682 
683     p = p ? p+1 : shell;
684     for (i = 0; (q = shellparm[i].name) != NULL; i++) {
685 	while (*q) {
686 	    int j = strcspn(q, "|");
687 
688 	    if (j == 0)
689 		break;
690 	    if (strncmp(p, q, j) == 0)
691 		return i;
692 	    if (*(q += j))
693 		++q;
694 	}
695     }
696     return SH_SH;
697 }
698 
699 
700 /*
701  * Determine the type of shell our parent process is
702  * This is quite tricky, not 100% reliable and probably
703  * not nearly as thorough as it should be. Basically, this
704  * is a "best guess" only, but hopefully will work in
705  * most cases.
706  */
707 
708 static int
709 getshelltype(void)
710 {
711     pid_t ppid = getppid();
712 
713     if (ppid != 1) {
714 	struct kinfo_proc kp;
715 	struct stat st;
716 	char path[MAXPATHLEN];
717 	char * shell = getenv("SHELL");
718 	int mib[4];
719 	size_t len;
720 
721 	mib[0] = CTL_KERN;
722 	mib[1] = KERN_PROC;
723 	mib[3] = ppid;
724 
725 	if (shell != NULL && stat(shell, &st) != -1) {
726 	    struct stat st1;
727 
728 	    mib[2] = KERN_PROC_PATHNAME;
729 	    len = sizeof(path);
730 	    if (sysctl(mib, 4, path, &len, NULL, 0) != -1) {
731 		/* $SHELL is actual shell? */
732 		if (stat(path, &st1) != -1 && memcmp(&st, &st1, sizeof st) == 0)
733 		    return getshellbyname(shell);
734 	    }
735 	}
736 	mib[2] = KERN_PROC_PID;
737 	len = sizeof(kp);
738 	if (sysctl(mib, 4, &kp, &len, NULL, 0) != -1)
739 	    return getshellbyname(kp.ki_comm);
740     }
741     return SH_SH;
742 }
743 
744 static void
745 getrlimit_proc(pid_t pid, int resource, struct rlimit *rlp)
746 {
747     int error;
748     int name[5];
749     size_t len;
750 
751     name[0] = CTL_KERN;
752     name[1] = KERN_PROC;
753     name[2] = KERN_PROC_RLIMIT;
754     name[3] = pid;
755     name[4] = resource;
756     len = sizeof(*rlp);
757     error = sysctl(name, 5, rlp, &len, NULL, 0);
758     if (error == -1)
759 	err(EXIT_FAILURE, "sysctl: kern.proc.rlimit: %d", pid);
760     if (len != sizeof(*rlp))
761 	errx(EXIT_FAILURE, "sysctl() returns wrong size");
762 }
763 
764 static void
765 setrlimit_proc(pid_t pid, int resource, const struct rlimit *rlp)
766 {
767     int error;
768     int name[5];
769 
770     name[0] = CTL_KERN;
771     name[1] = KERN_PROC;
772     name[2] = KERN_PROC_RLIMIT;
773     name[3] = pid;
774     name[4] = resource;
775     error = sysctl(name, 5, NULL, 0, rlp, sizeof(*rlp));
776     if (error == -1)
777 	err(EXIT_FAILURE, "sysctl: kern.proc.rlimit: %d", pid);
778 }
779