vm, kernel, top: report memory usage of vm, kernel
[minix.git] / lib / libutil / login_cap.c
blob8e8745a49354ac8df2543a2193677f5f9a1884a4
1 /* $NetBSD: login_cap.c,v 1.29 2007/12/04 22:09:02 mjf Exp $ */
3 /*-
4 * Copyright (c) 1995,1997 Berkeley Software Design, Inc. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. All advertising materials mentioning features or use of this software
15 * must display the following acknowledgement:
16 * This product includes software developed by Berkeley Software Design,
17 * Inc.
18 * 4. The name of Berkeley Software Design, Inc. may not be used to endorse
19 * or promote products derived from this software without specific prior
20 * written permission.
22 * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN, INC. ``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 BERKELEY SOFTWARE DESIGN, INC. 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.
34 * BSDI login_cap.c,v 2.13 1998/02/07 03:17:05 prb Exp
37 #include <sys/cdefs.h>
38 #if defined(LIBC_SCCS) && !defined(lint)
39 __RCSID("$NetBSD: login_cap.c,v 1.29 2007/12/04 22:09:02 mjf Exp $");
40 #endif /* LIBC_SCCS and not lint */
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <sys/time.h>
45 #include <sys/resource.h>
46 #include <sys/param.h>
48 #include <assert.h>
49 #include <ctype.h>
50 #include <err.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <limits.h>
54 #include <login_cap.h>
55 #include <paths.h>
56 #include <pwd.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <syslog.h>
61 #include <unistd.h>
62 #include <util.h>
64 static u_quad_t multiply(u_quad_t, u_quad_t);
65 static u_quad_t strtolimit(const char *, char **, int);
66 static u_quad_t strtosize(const char *, char **, int);
67 static int gsetrl(login_cap_t *, int, const char *, int type);
68 static int isinfinite(const char *);
69 static int envset(void *, const char *, const char *, int);
71 login_cap_t *
72 login_getclass(const char *class)
74 const char *classfiles[2];
75 login_cap_t *lc;
76 int res;
78 /* class may be NULL */
80 if (secure_path(_PATH_LOGIN_CONF) == 0) {
81 classfiles[0] = _PATH_LOGIN_CONF;
82 classfiles[1] = NULL;
83 } else {
84 classfiles[0] = NULL;
87 if ((lc = malloc(sizeof(login_cap_t))) == NULL) {
88 syslog(LOG_ERR, "%s:%d malloc: %m", __FILE__, __LINE__);
89 return (0);
92 lc->lc_cap = 0;
93 lc->lc_style = 0;
95 if (class == NULL || class[0] == '\0')
96 class = LOGIN_DEFCLASS;
98 if ((lc->lc_class = strdup(class)) == NULL) {
99 syslog(LOG_ERR, "%s:%d strdup: %m", __FILE__, __LINE__);
100 free(lc);
101 return (0);
105 * Not having a login.conf file is not an error condition.
106 * The individual routines deal reasonably with missing
107 * capabilities and use default values.
109 if (classfiles[0] == NULL)
110 return(lc);
112 if ((res = cgetent(&lc->lc_cap, classfiles, lc->lc_class)) != 0) {
113 lc->lc_cap = 0;
114 switch (res) {
115 case 1:
116 syslog(LOG_ERR, "%s: couldn't resolve 'tc'",
117 lc->lc_class);
118 break;
119 case -1:
120 if (strcmp(lc->lc_class, LOGIN_DEFCLASS) == 0)
121 return (lc);
122 syslog(LOG_ERR, "%s: unknown class", lc->lc_class);
123 break;
124 case -2:
125 syslog(LOG_ERR, "%s: getting class information: %m",
126 lc->lc_class);
127 break;
128 case -3:
129 syslog(LOG_ERR, "%s: 'tc' reference loop",
130 lc->lc_class);
131 break;
132 default:
133 syslog(LOG_ERR, "%s: unexpected cgetent error",
134 lc->lc_class);
135 break;
137 free(lc->lc_class);
138 free(lc);
139 return (0);
141 return (lc);
144 login_cap_t *
145 login_getpwclass(const struct passwd *pwd)
148 /* pwd may be NULL */
150 return login_getclass(pwd ? pwd->pw_class : NULL);
153 char *
154 login_getcapstr(login_cap_t *lc, const char *cap, char *def, char *e)
156 char *res = NULL;
157 int status;
159 errno = 0;
161 _DIAGASSERT(cap != NULL);
163 if (!lc || !lc->lc_cap)
164 return (def);
166 switch (status = cgetstr(lc->lc_cap, cap, &res)) {
167 case -1:
168 if (res)
169 free(res);
170 return (def);
171 case -2:
172 syslog(LOG_ERR, "%s: getting capability %s: %m",
173 lc->lc_class, cap);
174 if (res)
175 free(res);
176 return (e);
177 default:
178 if (status >= 0)
179 return (res);
180 syslog(LOG_ERR, "%s: unexpected error with capability %s",
181 lc->lc_class, cap);
182 if (res)
183 free(res);
184 return (e);
188 quad_t
189 login_getcaptime(login_cap_t *lc, const char *cap, quad_t def, quad_t e)
191 char *ep;
192 char *res = NULL, *sres;
193 int status;
194 quad_t q, r;
196 _DIAGASSERT(cap != NULL);
198 errno = 0;
199 if (!lc || !lc->lc_cap)
200 return (def);
202 switch (status = cgetstr(lc->lc_cap, cap, &res)) {
203 case -1:
204 if (res)
205 free(res);
206 return (def);
207 case -2:
208 syslog(LOG_ERR, "%s: getting capability %s: %m",
209 lc->lc_class, cap);
210 errno = ERANGE;
211 if (res)
212 free(res);
213 return (e);
214 default:
215 if (status >= 0)
216 break;
217 syslog(LOG_ERR, "%s: unexpected error with capability %s",
218 lc->lc_class, cap);
219 errno = ERANGE;
220 if (res)
221 free(res);
222 return (e);
225 if (isinfinite(res))
226 return (RLIM_INFINITY);
228 errno = 0;
230 q = 0;
231 sres = res;
232 while (*res) {
233 r = strtoq(res, &ep, 0);
234 if (!ep || ep == res ||
235 ((r == QUAD_MIN || r == QUAD_MAX) && errno == ERANGE)) {
236 invalid:
237 syslog(LOG_ERR, "%s:%s=%s: invalid time",
238 lc->lc_class, cap, sres);
239 errno = ERANGE;
240 free(sres);
241 return (e);
243 switch (*ep++) {
244 case '\0':
245 --ep;
246 break;
247 case 's': case 'S':
248 break;
249 case 'm': case 'M':
250 r *= 60;
251 break;
252 case 'h': case 'H':
253 r *= 60 * 60;
254 break;
255 case 'd': case 'D':
256 r *= 60 * 60 * 24;
257 break;
258 case 'w': case 'W':
259 r *= 60 * 60 * 24 * 7;
260 break;
261 case 'y': case 'Y': /* Pretty absurd */
262 r *= 60 * 60 * 24 * 365;
263 break;
264 default:
265 goto invalid;
267 res = ep;
268 q += r;
270 free(sres);
271 return (q);
274 quad_t
275 login_getcapnum(login_cap_t *lc, const char *cap, quad_t def, quad_t e)
277 char *ep;
278 char *res = NULL;
279 int status;
280 quad_t q;
282 _DIAGASSERT(cap != NULL);
284 errno = 0;
285 if (!lc || !lc->lc_cap)
286 return (def);
288 switch (status = cgetstr(lc->lc_cap, cap, &res)) {
289 case -1:
290 if (res)
291 free(res);
292 return (def);
293 case -2:
294 syslog(LOG_ERR, "%s: getting capability %s: %m",
295 lc->lc_class, cap);
296 errno = ERANGE;
297 if (res)
298 free(res);
299 return (e);
300 default:
301 if (status >= 0)
302 break;
303 syslog(LOG_ERR, "%s: unexpected error with capability %s",
304 lc->lc_class, cap);
305 errno = ERANGE;
306 if (res)
307 free(res);
308 return (e);
311 if (isinfinite(res))
312 return (RLIM_INFINITY);
314 errno = 0;
315 q = strtoq(res, &ep, 0);
316 if (!ep || ep == res || ep[0] ||
317 ((q == QUAD_MIN || q == QUAD_MAX) && errno == ERANGE)) {
318 syslog(LOG_ERR, "%s:%s=%s: invalid number",
319 lc->lc_class, cap, res);
320 errno = ERANGE;
321 free(res);
322 return (e);
324 free(res);
325 return (q);
328 quad_t
329 login_getcapsize(login_cap_t *lc, const char *cap, quad_t def, quad_t e)
331 char *ep;
332 char *res = NULL;
333 int status;
334 quad_t q;
336 _DIAGASSERT(cap != NULL);
338 errno = 0;
340 if (!lc || !lc->lc_cap)
341 return (def);
343 switch (status = cgetstr(lc->lc_cap, cap, &res)) {
344 case -1:
345 if (res)
346 free(res);
347 return (def);
348 case -2:
349 syslog(LOG_ERR, "%s: getting capability %s: %m",
350 lc->lc_class, cap);
351 errno = ERANGE;
352 if (res)
353 free(res);
354 return (e);
355 default:
356 if (status >= 0)
357 break;
358 syslog(LOG_ERR, "%s: unexpected error with capability %s",
359 lc->lc_class, cap);
360 errno = ERANGE;
361 if (res)
362 free(res);
363 return (e);
366 errno = 0;
367 q = strtolimit(res, &ep, 0);
368 if (!ep || ep == res || (ep[0] && ep[1]) ||
369 ((q == QUAD_MIN || q == QUAD_MAX) && errno == ERANGE)) {
370 syslog(LOG_ERR, "%s:%s=%s: invalid size",
371 lc->lc_class, cap, res);
372 errno = ERANGE;
373 free(res);
374 return (e);
376 free(res);
377 return (q);
381 login_getcapbool(login_cap_t *lc, const char *cap, u_int def)
384 _DIAGASSERT(cap != NULL);
386 if (!lc || !lc->lc_cap)
387 return (def);
389 return (cgetcap(lc->lc_cap, cap, ':') != NULL);
392 void
393 login_close(login_cap_t *lc)
396 if (lc) {
397 if (lc->lc_class)
398 free(lc->lc_class);
399 if (lc->lc_cap)
400 free(lc->lc_cap);
401 if (lc->lc_style)
402 free(lc->lc_style);
403 free(lc);
407 #define R_CTIME 1
408 #define R_CSIZE 2
409 #define R_CNUMB 3
411 static struct {
412 int what;
413 int type;
414 const char *name;
415 } r_list[] = {
416 { RLIMIT_CPU, R_CTIME, "cputime", },
417 { RLIMIT_FSIZE, R_CSIZE, "filesize", },
418 { RLIMIT_DATA, R_CSIZE, "datasize", },
419 { RLIMIT_STACK, R_CSIZE, "stacksize", },
420 #ifndef __minix
421 { RLIMIT_RSS, R_CSIZE, "memoryuse", },
422 { RLIMIT_MEMLOCK, R_CSIZE, "memorylocked", },
423 { RLIMIT_NPROC, R_CNUMB, "maxproc", },
424 #endif
425 { RLIMIT_NOFILE, R_CNUMB, "openfiles", },
426 { RLIMIT_CORE, R_CSIZE, "coredumpsize", },
427 #ifdef RLIMIT_SBSIZE
428 { RLIMIT_SBSIZE, R_CSIZE, "sbsize", },
429 #endif
430 { -1, 0, 0 }
433 static int
434 gsetrl(login_cap_t *lc, int what, const char *name, int type)
436 struct rlimit rl;
437 struct rlimit r;
438 char name_cur[32];
439 char name_max[32];
441 _DIAGASSERT(name != NULL);
443 (void)snprintf(name_cur, sizeof(name_cur), "%s-cur", name);
444 (void)snprintf(name_max, sizeof(name_max), "%s-max", name);
446 if (getrlimit(what, &r)) {
447 syslog(LOG_ERR, "getting resource limit: %m");
448 return (-1);
451 #define RCUR r.rlim_cur
452 #define RMAX r.rlim_max
454 switch (type) {
455 case R_CTIME:
456 RCUR = login_getcaptime(lc, name, RCUR, RCUR);
457 RMAX = login_getcaptime(lc, name, RMAX, RMAX);
458 rl.rlim_cur = login_getcaptime(lc, name_cur, RCUR, RCUR);
459 rl.rlim_max = login_getcaptime(lc, name_max, RMAX, RMAX);
460 break;
461 case R_CSIZE:
462 RCUR = login_getcapsize(lc, name, RCUR, RCUR);
463 RMAX = login_getcapsize(lc, name, RMAX, RMAX);
464 rl.rlim_cur = login_getcapsize(lc, name_cur, RCUR, RCUR);
465 rl.rlim_max = login_getcapsize(lc, name_max, RMAX, RMAX);
466 break;
467 case R_CNUMB:
468 RCUR = login_getcapnum(lc, name, RCUR, RCUR);
469 RMAX = login_getcapnum(lc, name, RMAX, RMAX);
470 rl.rlim_cur = login_getcapnum(lc, name_cur, RCUR, RCUR);
471 rl.rlim_max = login_getcapnum(lc, name_max, RMAX, RMAX);
472 break;
473 default:
474 syslog(LOG_ERR, "%s: invalid type %d setting resource limit %s",
475 lc->lc_class, type, name);
476 return (-1);
479 #ifndef __minix
480 if (setrlimit(what, &rl)) {
481 syslog(LOG_ERR, "%s: setting resource limit %s: %m",
482 lc->lc_class, name);
483 return (-1);
485 #endif
486 #undef RCUR
487 #undef RMAX
488 return (0);
491 static int
492 /*ARGSUSED*/
493 envset(void *envp __unused, const char *name, const char *value, int overwrite)
495 return setenv(name, value, overwrite);
499 setuserenv(login_cap_t *lc, envfunc_t senv, void *envp)
501 const char *stop = ", \t";
502 size_t i, count;
503 char *ptr;
504 char **res;
505 char *str = login_getcapstr(lc, "setenv", NULL, NULL);
507 if (str == NULL || *str == '\0')
508 return 0;
511 * count the sub-strings, this may over-count since we don't
512 * account for escaped delimiters.
514 for (i = 1, ptr = str; *ptr; i++) {
515 ptr += strcspn(ptr, stop);
516 if (*ptr)
517 ptr++;
520 /* allocate ptr array and string */
521 count = i;
522 res = malloc(count * sizeof(char *) + strlen(str) + 1);
524 if (!res)
525 return -1;
527 ptr = (char *)(void *)&res[count];
528 (void)strcpy(ptr, str);
530 /* split string */
531 for (i = 0; (res[i] = stresep(&ptr, stop, '\\')) != NULL; )
532 if (*res[i])
533 i++;
535 count = i;
537 for (i = 0; i < count; i++) {
538 if ((ptr = strchr(res[i], '=')) != NULL)
539 *ptr++ = '\0';
540 else
541 ptr = NULL;
542 (void)(*senv)(envp, res[i], ptr ? ptr : "", 1);
545 free(res);
546 return 0;
550 setclasscontext(const char *class, u_int flags)
552 int ret;
553 login_cap_t *lc;
555 flags &= LOGIN_SETRESOURCES | LOGIN_SETPRIORITY | LOGIN_SETUMASK |
556 LOGIN_SETPATH;
558 lc = login_getclass(class);
559 ret = lc ? setusercontext(lc, NULL, 0, flags) : -1;
560 login_close(lc);
561 return (ret);
565 setusercontext(login_cap_t *lc, struct passwd *pwd, uid_t uid, u_int flags)
567 char per_user_tmp[MAXPATHLEN + 1];
568 const char *component_name;
569 login_cap_t *flc;
570 quad_t p;
571 int i;
572 ssize_t len;
574 flc = NULL;
576 if (!lc)
577 flc = lc = login_getclass(pwd ? pwd->pw_class : NULL);
579 #define LOGIN_SETLOGIN 0
581 * Without the pwd entry being passed we cannot set either
582 * the group or the login. We could complain about it.
584 if (pwd == NULL)
585 flags &= ~(LOGIN_SETGROUP|LOGIN_SETLOGIN);
587 #ifdef LOGIN_OSETGROUP
588 if (pwd == NULL)
589 flags &= ~LOGIN_OSETGROUP;
590 if (flags & LOGIN_OSETGROUP)
591 flags = (flags & ~LOGIN_OSETGROUP) | LOGIN_SETGROUP;
592 #endif
593 if (flags & LOGIN_SETRESOURCES)
594 for (i = 0; r_list[i].name; ++i)
595 (void)gsetrl(lc, r_list[i].what, r_list[i].name,
596 r_list[i].type);
598 if (flags & LOGIN_SETPRIORITY) {
599 p = login_getcapnum(lc, "priority", (quad_t)0, (quad_t)0);
601 if (setpriority(PRIO_PROCESS, 0, (int)p) == -1)
602 syslog(LOG_ERR, "%s: setpriority: %m", lc->lc_class);
605 if (flags & LOGIN_SETUMASK) {
606 p = login_getcapnum(lc, "umask", (quad_t) LOGIN_DEFUMASK,
607 (quad_t)LOGIN_DEFUMASK);
608 umask((mode_t)p);
611 if (flags & LOGIN_SETGID) {
612 if (setgid(pwd->pw_gid) == -1) {
613 syslog(LOG_ERR, "setgid(%d): %m", pwd->pw_gid);
614 login_close(flc);
615 return (-1);
619 if (flags & LOGIN_SETGROUPS) {
620 if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
621 syslog(LOG_ERR, "initgroups(%s,%d): %m",
622 pwd->pw_name, pwd->pw_gid);
623 login_close(flc);
624 return (-1);
628 /* Create per-user temporary directories if needed. */
629 if ((len = readlink("/tmp", per_user_tmp,
630 sizeof(per_user_tmp) - 6)) != -1) {
632 static const char atuid[] = "/@ruid";
633 char *lp;
635 /* readlink does not nul-terminate the string */
636 per_user_tmp[len] = '\0';
638 /* Check if it's magic symlink. */
639 lp = strstr(per_user_tmp, atuid);
640 if (lp != NULL && *(lp + (sizeof(atuid) - 1)) == '\0') {
641 lp++;
643 if (snprintf(lp, 11, "/%u", pwd->pw_uid) > 10) {
644 syslog(LOG_ERR, "real temporary path too long");
645 login_close(flc);
646 return (-1);
648 if (mkdir(per_user_tmp, S_IRWXU) != -1) {
649 if (chown(per_user_tmp, pwd->pw_uid,
650 pwd->pw_gid)) {
651 component_name = "chown";
652 goto out;
656 * Must set sticky bit for tmp directory, some
657 * programs rely on this.
659 if(chmod(per_user_tmp, S_IRWXU | S_ISVTX)) {
660 component_name = "chmod";
661 goto out;
663 } else {
664 if (errno != EEXIST) {
665 component_name = "mkdir";
666 goto out;
667 } else {
669 * We must ensure that we own the
670 * directory and that is has the correct
671 * permissions, otherwise a DOS attack
672 * is possible.
674 struct stat sb;
675 if (stat(per_user_tmp, &sb) == -1) {
676 component_name = "stat";
677 goto out;
680 if (sb.st_uid != pwd->pw_uid) {
681 if (chown(per_user_tmp,
682 pwd->pw_uid, pwd->pw_gid)) {
683 component_name = "chown";
684 goto out;
688 if (sb.st_mode != (S_IRWXU | S_ISVTX)) {
689 if (chmod(per_user_tmp,
690 S_IRWXU | S_ISVTX)) {
691 component_name = "chmod";
692 goto out;
699 errno = 0;
701 if (flags & LOGIN_SETLOGIN)
702 if (setlogin(pwd->pw_name) == -1) {
703 syslog(LOG_ERR, "setlogin(%s) failure: %m",
704 pwd->pw_name);
705 login_close(flc);
706 return (-1);
709 if (flags & LOGIN_SETUSER)
710 if (setuid(uid) == -1) {
711 syslog(LOG_ERR, "setuid(%d): %m", uid);
712 login_close(flc);
713 return (-1);
716 if (flags & LOGIN_SETENV)
717 setuserenv(lc, envset, NULL);
719 if (flags & LOGIN_SETPATH)
720 setuserpath(lc, pwd ? pwd->pw_dir : "", envset, NULL);
722 login_close(flc);
723 return (0);
725 out:
726 if (component_name != NULL) {
727 syslog(LOG_ERR, "%s %s: %m", component_name, per_user_tmp);
728 login_close(flc);
729 return (-1);
730 } else {
731 syslog(LOG_ERR, "%s: %m", per_user_tmp);
732 login_close(flc);
733 return (-1);
737 void
738 setuserpath(login_cap_t *lc, const char *home, envfunc_t senv, void *envp)
740 size_t hlen, plen;
741 int cnt = 0;
742 char *path;
743 const char *cpath;
744 char *p, *q;
746 _DIAGASSERT(home != NULL);
748 hlen = strlen(home);
750 p = path = login_getcapstr(lc, "path", NULL, NULL);
751 if (p) {
752 while (*p)
753 if (*p++ == '~')
754 ++cnt;
755 plen = (p - path) + cnt * (hlen + 1) + 1;
756 p = path;
757 q = path = malloc(plen);
758 if (q) {
759 while (*p) {
760 p += strspn(p, " \t");
761 if (*p == '\0')
762 break;
763 plen = strcspn(p, " \t");
764 if (hlen == 0 && *p == '~') {
765 p += plen;
766 continue;
768 if (q != path)
769 *q++ = ':';
770 if (*p == '~') {
771 strcpy(q, home);
772 q += hlen;
773 ++p;
774 --plen;
776 memcpy(q, p, plen);
777 p += plen;
778 q += plen;
780 *q = '\0';
781 cpath = path;
782 } else
783 cpath = _PATH_DEFPATH;
784 } else
785 cpath = _PATH_DEFPATH;
786 if ((*senv)(envp, "PATH", cpath, 1))
787 warn("could not set PATH");
791 * Convert an expression of the following forms
792 * 1) A number.
793 * 2) A number followed by a b (mult by 512).
794 * 3) A number followed by a k (mult by 1024).
795 * 5) A number followed by a m (mult by 1024 * 1024).
796 * 6) A number followed by a g (mult by 1024 * 1024 * 1024).
797 * 7) A number followed by a t (mult by 1024 * 1024 * 1024 * 1024).
798 * 8) Two or more numbers (with/without k,b,m,g, or t).
799 * separated by x (also * for backwards compatibility), specifying
800 * the product of the indicated values.
802 static u_quad_t
803 strtosize(const char *str, char **endptr, int radix)
805 u_quad_t num, num2;
806 char *expr, *expr2;
808 _DIAGASSERT(str != NULL);
809 /* endptr may be NULL */
811 errno = 0;
812 num = strtouq(str, &expr, radix);
813 if (errno || expr == str) {
814 if (endptr)
815 *endptr = expr;
816 return (num);
819 switch(*expr) {
820 case 'b': case 'B':
821 num = multiply(num, (u_quad_t)512);
822 ++expr;
823 break;
824 case 'k': case 'K':
825 num = multiply(num, (u_quad_t)1024);
826 ++expr;
827 break;
828 case 'm': case 'M':
829 num = multiply(num, (u_quad_t)1024 * 1024);
830 ++expr;
831 break;
832 case 'g': case 'G':
833 num = multiply(num, (u_quad_t)1024 * 1024 * 1024);
834 ++expr;
835 break;
836 case 't': case 'T':
837 num = multiply(num, (u_quad_t)1024 * 1024);
838 num = multiply(num, (u_quad_t)1024 * 1024);
839 ++expr;
840 break;
843 if (errno)
844 goto erange;
846 switch(*expr) {
847 case '*': /* Backward compatible. */
848 case 'x':
849 num2 = strtosize(expr+1, &expr2, radix);
850 if (errno) {
851 expr = expr2;
852 goto erange;
855 if (expr2 == expr + 1) {
856 if (endptr)
857 *endptr = expr;
858 return (num);
860 expr = expr2;
861 num = multiply(num, num2);
862 if (errno)
863 goto erange;
864 break;
866 if (endptr)
867 *endptr = expr;
868 return (num);
869 erange:
870 if (endptr)
871 *endptr = expr;
872 errno = ERANGE;
873 return (UQUAD_MAX);
876 static u_quad_t
877 strtolimit(const char *str, char **endptr, int radix)
880 _DIAGASSERT(str != NULL);
881 /* endptr may be NULL */
883 if (isinfinite(str)) {
884 if (endptr)
885 *endptr = (char *)__UNCONST(str) + strlen(str);
886 return ((u_quad_t)RLIM_INFINITY);
888 return (strtosize(str, endptr, radix));
891 static int
892 isinfinite(const char *s)
894 static const char *infs[] = {
895 "infinity",
896 "inf",
897 "unlimited",
898 "unlimit",
899 NULL
901 const char **i;
903 _DIAGASSERT(s != NULL);
905 for (i = infs; *i; i++) {
906 if (!strcasecmp(s, *i))
907 return 1;
909 return 0;
912 static u_quad_t
913 multiply(u_quad_t n1, u_quad_t n2)
915 static int bpw = 0;
916 u_quad_t m;
917 u_quad_t r;
918 int b1, b2;
921 * Get rid of the simple cases
923 if (n1 == 0 || n2 == 0)
924 return (0);
925 if (n1 == 1)
926 return (n2);
927 if (n2 == 1)
928 return (n1);
931 * sizeof() returns number of bytes needed for storage.
932 * This may be different from the actual number of useful bits.
934 if (!bpw) {
935 bpw = sizeof(u_quad_t) * 8;
936 while (((u_quad_t)1 << (bpw-1)) == 0)
937 --bpw;
941 * First check the magnitude of each number. If the sum of the
942 * magnatude is way to high, reject the number. (If this test
943 * is not done then the first multiply below may overflow.)
945 for (b1 = bpw; (((u_quad_t)1 << (b1-1)) & n1) == 0; --b1)
947 for (b2 = bpw; (((u_quad_t)1 << (b2-1)) & n2) == 0; --b2)
949 if (b1 + b2 - 2 > bpw) {
950 errno = ERANGE;
951 return (UQUAD_MAX);
955 * Decompose the multiplication to be:
956 * h1 = n1 & ~1
957 * h2 = n2 & ~1
958 * l1 = n1 & 1
959 * l2 = n2 & 1
960 * (h1 + l1) * (h2 + l2)
961 * (h1 * h2) + (h1 * l2) + (l1 * h2) + (l1 * l2)
963 * Since h1 && h2 do not have the low bit set, we can then say:
965 * (h1>>1 * h2>>1 * 4) + ...
967 * So if (h1>>1 * h2>>1) > (1<<(bpw - 2)) then the result will
968 * overflow.
970 * Finally, if MAX - ((h1 * l2) + (l1 * h2) + (l1 * l2)) < (h1*h2)
971 * then adding in residual amout will cause an overflow.
974 m = (n1 >> 1) * (n2 >> 1);
976 if (m >= ((u_quad_t)1 << (bpw-2))) {
977 errno = ERANGE;
978 return (UQUAD_MAX);
981 m *= 4;
983 r = (n1 & n2 & 1)
984 + (n2 & 1) * (n1 & ~(u_quad_t)1)
985 + (n1 & 1) * (n2 & ~(u_quad_t)1);
987 if ((u_quad_t)(m + r) < m) {
988 errno = ERANGE;
989 return (UQUAD_MAX);
991 m += r;
993 return (m);