Home | History | Annotate | Line # | Download | only in sh
      1 /*	$NetBSD: miscbltin.c,v 1.59 2026/08/04 22:58:33 kre Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Kenneth Almquist.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``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 THE REGENTS OR CONTRIBUTORS 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.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)miscbltin.c	8.4 (Berkeley) 5/4/95";
     39 #else
     40 __RCSID("$NetBSD: miscbltin.c,v 1.59 2026/08/04 22:58:33 kre Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 /*
     45  * Miscellaneous builtins.
     46  */
     47 
     48 #include <sys/param.h>		/* BSD4_4 */
     49 #include <sys/resource.h>
     50 #include <sys/stat.h>
     51 #include <sys/time.h>
     52 #include <sys/types.h>		/* quad_t */
     53 
     54 #include <ctype.h>
     55 #include <errno.h>
     56 #include <limits.h>
     57 #include <stdlib.h>
     58 #ifndef SMALL
     59 #include <termios.h>
     60 #endif
     61 #include <unistd.h>
     62 
     63 #include "shell.h"
     64 #include "syntax.h"
     65 #include "options.h"
     66 #include "var.h"
     67 #include "input.h"		/* for whichprompt */
     68 #include "output.h"
     69 #include "parser.h"		/* for getprompt() */
     70 #include "memalloc.h"
     71 #include "error.h"
     72 #include "builtins.h"
     73 #include "mystring.h"
     74 #include "redir.h"		/* for user_fd_limit */
     75 #include "trap.h"		/* for run_traps() */
     76 
     77 /*
     78  * The read builtin.
     79  * Backslashes escape the next char unless -r is specified.
     80  *
     81  * This uses unbuffered input, which may be avoidable in some cases.
     82  *
     83  * Note that if IFS=' :' then read x y should work so that:
     84  * 'a b'	x='a', y='b'
     85  * ' a b '	x='a', y='b'
     86  * ':b'		x='',  y='b'
     87  * ':'		x='',  y=''
     88  * '::'		x='',  y=''
     89  * ': :'	x='',  y=''
     90  * ':::'	x='',  y='::'
     91  * ':b c:'	x='',  y='b c:'
     92  */
     93 
     94 #ifndef SMALL
     95 static int b_flag;
     96 
     97 static int
     98 setrawmode(int fd, int on, int end, struct termios *t)
     99 {
    100 	struct termios n;
    101 
    102 	if (on) {
    103 		if (tcgetattr(fd, t) != 0)
    104 			return 0;
    105 		n = *t;
    106 		if (on == 1 && b_flag) {
    107 			n.c_cc[VEOL] = end;
    108 		} else {
    109 			cfmakeraw(&n);
    110 			n.c_iflag |= ICRNL;
    111 			n.c_oflag = t->c_oflag;
    112 			n.c_lflag |= ECHO | ISIG;
    113 		}
    114 		if (tcsetattr(fd, TCSADRAIN | TCSASOFT, &n) == 0)
    115 			return 1;
    116 	} else
    117 		(void)tcsetattr(fd, TCSADRAIN | TCSASOFT, t);
    118 	return 0;
    119 }
    120 
    121 static int
    122 is_a_pipe(int fd)
    123 {
    124 	if (lseek(fd, 0, SEEK_CUR) == -1 && errno == ESPIPE) {
    125 		errno = 0;
    126 		return 1;
    127 	}
    128 	return 0;
    129 }
    130 
    131 /* what to do with caught signals during read */
    132 static int
    133 read_trap(int retry)
    134 {
    135 	if (pendingsigs) {	/* the signal was trapped */
    136 		run_traps(1);	/* process it */
    137 		if (!retry)	/* and if not "read -c", just finish */
    138 			return 0;
    139 	}
    140 	return 1;		/* any other case, restart the read */
    141 }
    142 
    143 #define	READ_BUFFER_SIZE	512
    144 
    145 static int
    146 next_read_char(int fd, size_t max, int retry)
    147 {
    148 	static char buffer[READ_BUFFER_SIZE];
    149 	static int pos = 0, len = 0;
    150 
    151 	if (max == 0) {
    152 		pos = len = 0;
    153 		return -1;
    154 	}
    155 	if (max == (size_t)-1) {
    156 		/*
    157 		 * If possible, and necessary, rewind the file
    158 		 * so unprocessed data  can be read again next time
    159 		 *
    160 		 * If that fails, never mind (-b allows that to happen)
    161 		 */
    162 		if (b_flag && pos < len)
    163 			(void)lseek(fd, (off_t)(pos - len), SEEK_CUR);
    164 		return -1;
    165 	}
    166 
    167 	if (b_flag == 0) {
    168 		char c;
    169 
    170 		(void) max;
    171 		while ((len = read(fd, &c, 1)) != 1) {
    172 			if (len == -1 && errno == EINTR) {
    173 				if (read_trap(retry))
    174 					continue;
    175 				errno = EINTR;
    176 			}
    177 			return len - 1;
    178 		}
    179 		return (c & 0xFF);
    180 	}
    181 
    182 	if (pos >= len) {
    183 		pos = 0;
    184 		if (max > sizeof buffer)
    185 			max = sizeof buffer;
    186 		while ((len = read(fd, buffer, max)) < 0) {
    187 			if (len == -1 && errno == EINTR) {
    188 				if (read_trap(retry))
    189 					continue;
    190 				errno = EINTR;
    191 			}
    192 			break;
    193 		}
    194 		if (len <= 0)
    195 			return len - 1;
    196 	}
    197 
    198 	return buffer[pos++] & 0xFF;
    199 }
    200 
    201 static void
    202 read_reset(int setraw, struct termios *ttystate)
    203 {
    204 	(void)next_read_char(0, (size_t)-1, 0);	/* attempt to seek back */
    205 	if (setraw)
    206 		setrawmode(0, 0, 0, ttystate);
    207 }
    208 
    209 #define READ_OPTS	"bcd:n:p:r"
    210 
    211 #else
    212 
    213 static inline int
    214 simple_next_read_char(int fd, size_t max)
    215 {
    216 	char c;
    217 	int len;
    218 
    219 	if (max == 0 || max == (size_t)-1)
    220 		return 0;
    221 
    222 	if ((len = read(fd, &c, 1)) != 1)
    223 		return len - 1;
    224 	return (c & 0xFF);
    225 }
    226 
    227 #define	next_read_char(fd, max, retry)	simple_next_read_char((fd), (max))
    228 
    229 #define read_reset(a, b) __nothing
    230 #define n_flag 0
    231 #define maxlen 0
    232 #define retry_reads 0
    233 
    234 #define READ_OPTS	"d:p:r"
    235 
    236 #endif
    237 
    238 int
    239 readcmd(int argc, char **argv)
    240 {
    241 	char **ap;
    242 	int c;
    243 	char end;
    244 	int r_flag;
    245 	char *prompt;
    246 	const char *ifs;
    247 	char *p;
    248 	int startword;
    249 	int status;
    250 	int i;
    251 	int is_ifs;
    252 	int saveall = 0;
    253 	int read_tty = 0;
    254 	ptrdiff_t wordlen = 0;
    255 	char *newifs = NULL;
    256 	struct stackmark mk;
    257 
    258 #ifndef SMALL
    259 	struct termios ttystate;
    260 	int n_flag, maxlen;
    261 	int setraw = 0;
    262 	int retry_reads = 0;
    263 
    264 	b_flag = 0;
    265 	n_flag = 0;
    266 	maxlen = READ_BUFFER_SIZE - 1;
    267 #endif
    268 
    269 	end = '\n';				/* record delimiter */
    270 	r_flag = 0;
    271 	prompt = NULL;
    272 	whichprompt = 2;			/* for continuation lines */
    273 
    274 	while ((i = nextopt(READ_OPTS)) != '\0') {
    275 		switch (i) {
    276 		case 'd':
    277 			end = *optionarg;	/* even if '\0' */
    278 			break;
    279 		case 'p':
    280 			prompt = optionarg;
    281 			break;
    282 		case 'r':
    283 			r_flag = 1;
    284 			break;
    285 #ifndef SMALL
    286 		case 'b':
    287 			if (!is_a_pipe(0))
    288 				b_flag = 1;
    289 			break;
    290 		case 'c':
    291 			retry_reads = 1;	/* upon EINTR */
    292 			break;
    293 		case 'n':
    294 			maxlen = number(optionarg);
    295 			if (maxlen > (INT_MAX >> 8) + 1)	/* sanity */
    296 				error("-n %s too large", optionarg);
    297 			n_flag = 1;
    298 			break;
    299 #endif
    300 		}
    301 	}
    302 
    303 	if (*(ap = argptr) == NULL)
    304 		error("variable name required\n"
    305 #ifdef SMALL
    306 		      "Usage: read [-r] [-d C] [-p prompt] var...");
    307 #else
    308 		      "Usage: read [-br] [-d C] [-n len] [-p prompt] var...");
    309 
    310 	while (*ap != NULL) {
    311 		if (!validname(*ap, '\0', NULL))
    312 			error("'%s': invalid variable name", *ap);
    313 		ap++;
    314 	}
    315 	ap = argptr;
    316 
    317 	(void)next_read_char(0, 0, 0);	/* ensure the buffer is empty */
    318 #endif
    319 
    320 	if (isatty(0)) {
    321 		read_tty = 1;
    322 		if (prompt) {
    323 			out2str(prompt);
    324 			flushall();
    325 		}
    326 #ifndef SMALL
    327 		b_flag = 1;	/* always buffer reads from ttys */
    328 
    329 		if (n_flag || end != '\n')
    330 			setraw = setrawmode(0, 1 + n_flag, end, &ttystate);
    331 #endif
    332 	}
    333 
    334 	if ((ifs = bltinlookup("IFS", 1)) == NULL)
    335 		ifs = " \t\n";
    336 
    337 	setstackmark(&mk);
    338 	status = 0;
    339 	startword = 2;
    340 	STARTSTACKSTR(p);
    341 
    342 #ifdef SMALL
    343 	for ( ; ; ) {
    344 #else
    345 	for ( ; !n_flag || --maxlen >= 0 ; ) {
    346 #endif
    347 		if ((c = next_read_char(0, maxlen + 1, retry_reads)) < 0) {
    348 #ifndef SMALL
    349 			if (c <= -2 && errno != EINTR) {
    350 				read_reset(setraw, &ttystate);
    351 				error("read error");
    352 			}
    353 			if (errno == EINTR)
    354 				status = 128 + SIGINT;
    355 			else
    356 #endif
    357 				status = 1;
    358 			break;
    359 		}
    360 		if (c == '\\' && c != end && !r_flag) {
    361 #ifndef SMALL
    362 			if (n_flag && --maxlen < 0)
    363 				break;
    364 #endif
    365 			if ((c = next_read_char(0, maxlen + 1, retry_reads))
    366 			    < 0) {
    367 #ifndef SMALL
    368 				if (c <= -2 && errno != EINTR) {
    369 					read_reset(setraw, &ttystate);
    370 					error("read error");
    371 				}
    372 				if (errno == EINTR)
    373 					status = 128 + SIGINT;
    374 				else
    375 #endif
    376 					status = 1;
    377 				break;
    378 			}
    379 			if (c != '\n')	/* \ \n is always just removed */
    380 				goto wdch;
    381 			if (read_tty)
    382 				out2str(getprompt(NULL));
    383 			continue;
    384 		}
    385 		if (c == end)
    386 			break;
    387 		if (c == '\0')
    388 			continue;
    389 		if (strchr(ifs, c))
    390 			is_ifs = strchr(" \t\n", c) ? 1 : 2;
    391 		else
    392 			is_ifs = 0;
    393 
    394 		if (startword != 0) {
    395 			if (is_ifs == 1) {
    396 				/* Ignore leading IFS whitespace */
    397 				if (saveall)
    398 					STPUTC(c, p);
    399 				continue;
    400 			}
    401 			if (is_ifs == 2 && startword == 1) {
    402 				/* Only one non-whitespace IFS per word */
    403 				startword = 2;
    404 				if (saveall)
    405 					STPUTC(c, p);
    406 				continue;
    407 			}
    408 		}
    409 
    410 		if (is_ifs == 0) {
    411   wdch:;
    412 			if (c == '\0') /* always ignore attempts to input \0 */
    413 				continue;
    414 			/* append this character to the current variable */
    415 			startword = 0;
    416 			if (saveall)
    417 				/* Not just a spare terminator */
    418 				saveall++;
    419 			STPUTC(c, p);
    420 			wordlen = p - stackblock();
    421 			continue;
    422 		}
    423 
    424 		/* end of variable... */
    425 		startword = is_ifs;
    426 
    427 		if (ap[1] == NULL) {
    428 			/* Last variable needs all IFS chars */
    429 			saveall++;
    430 			STPUTC(c, p);
    431 			continue;
    432 		}
    433 
    434 		if (equal(*ap, "IFS")) {
    435 			/*
    436 			 * we must not alter the value of IFS, as our
    437 			 * local "ifs" var is (perhaps) pointing at it,
    438 			 * at best we would be using data after free()
    439 			 * the next time we reference ifs - but that mem
    440 			 * may have been reused for something different.
    441 			 *
    442 			 * note that this might occur several times
    443 			 */
    444 			STPUTC('\0', p);
    445 			newifs = grabstackstr(p);
    446 		} else {
    447 			STACKSTRNUL(p);
    448 			setvar(*ap, stackblock(), 0);
    449 		}
    450 		ap++;
    451 		STARTSTACKSTR(p);
    452 		wordlen = 0;
    453 	}
    454 	STACKSTRNUL(p);
    455 
    456 	read_reset(setraw, &ttystate);
    457 
    458 	/* Remove trailing IFS chars */
    459 	for (; stackblock() + wordlen <= --p; *p = 0) {
    460 		if (!strchr(ifs, *p))
    461 			break;
    462 		if (strchr(" \t\n", *p))
    463 			/* Always remove whitespace */
    464 			continue;
    465 		if (saveall > 1)
    466 			/* Don't remove non-whitespace unless it was naked */
    467 			break;
    468 	}
    469 
    470 	/*
    471 	 * If IFS was one of the variables named, we can finally set it now
    472 	 * (no further references to ifs will be made)
    473 	 */
    474 	if (newifs != NULL)
    475 		setvar("IFS", newifs, 0);
    476 
    477 	/*
    478 	 * Now we can assign to the final variable (which might
    479 	 * also be IFS, hence the ordering here)
    480 	 */
    481 	setvar(*ap, stackblock(), 0);
    482 
    483 	/* Set any remaining args to "" */
    484 	while (*++ap != NULL)
    485 		setvar(*ap, nullstr, 0);
    486 
    487 	popstackmark(&mk);
    488 	return status;
    489 }
    490 
    491 /* -- end read builtin */
    492 
    493 
    494 /*
    495  * Other small builtin utilities   (the u*s)
    496  */
    497 
    498 int
    499 umaskcmd(int argc, char **argv)
    500 {
    501 	char *ap;
    502 	mode_t mask;
    503 	int i;
    504 	int symbolic_mode = 0;
    505 
    506 	while ((i = nextopt("S")) != '\0') {
    507 		symbolic_mode = 1;
    508 	}
    509 
    510 	INTOFF;
    511 	mask = umask(0);
    512 	umask(mask);
    513 	INTON;
    514 
    515 	if ((ap = *argptr) == NULL) {
    516 		if (symbolic_mode) {
    517 			char u[4], g[4], o[4];
    518 
    519 			i = 0;
    520 			if ((mask & S_IRUSR) == 0)
    521 				u[i++] = 'r';
    522 			if ((mask & S_IWUSR) == 0)
    523 				u[i++] = 'w';
    524 			if ((mask & S_IXUSR) == 0)
    525 				u[i++] = 'x';
    526 			u[i] = '\0';
    527 
    528 			i = 0;
    529 			if ((mask & S_IRGRP) == 0)
    530 				g[i++] = 'r';
    531 			if ((mask & S_IWGRP) == 0)
    532 				g[i++] = 'w';
    533 			if ((mask & S_IXGRP) == 0)
    534 				g[i++] = 'x';
    535 			g[i] = '\0';
    536 
    537 			i = 0;
    538 			if ((mask & S_IROTH) == 0)
    539 				o[i++] = 'r';
    540 			if ((mask & S_IWOTH) == 0)
    541 				o[i++] = 'w';
    542 			if ((mask & S_IXOTH) == 0)
    543 				o[i++] = 'x';
    544 			o[i] = '\0';
    545 
    546 			out1fmt("u=%s,g=%s,o=%s\n", u, g, o);
    547 		} else {
    548 			out1fmt("%.4o\n", mask);
    549 		}
    550 	} else {
    551 		if (is_digit(*ap)) {
    552 			int range = 0;
    553 
    554 			mask = 0;
    555 			do {
    556 				if (*ap >= '8' || *ap < '0')
    557 					error("Not a valid octal number: '%s'",
    558 					    *argptr);
    559 				mask = (mask << 3) + (*ap - '0');
    560 				if (mask & ~07777)
    561 					range = 1;
    562 			} while (*++ap != '\0');
    563 			if (range)
    564 			    error("Mask constant '%s' out of range", *argptr);
    565 			umask(mask);
    566 		} else {
    567 			void *set;
    568 
    569 			INTOFF;
    570 			if ((set = setmode(ap)) != 0) {
    571 				mask = getmode(set, ~mask & 0777);
    572 				ckfree(set);
    573 			}
    574 			INTON;
    575 			if (!set)
    576 				error("Cannot set mode `%s' (%s)", ap,
    577 				    strerror(errno));
    578 
    579 			umask(~mask & 0777);
    580 		}
    581 	}
    582 	flushout(out1);
    583 	if (io_err(out1)) {
    584 		out2str("umask: I/O error\n");
    585 		return 1;
    586 	}
    587 	return 0;
    588 }
    589 
    590 /*
    591  * ulimit builtin
    592  *
    593  * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
    594  * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
    595  * ash by J.T. Conklin.
    596  *
    597  * Public domain.
    598  */
    599 
    600 struct limits {
    601 	const char *name;
    602 	const char *unit;
    603 	char	option;
    604 	int8_t	cmd;		/* all RLIMIT_xxx are <= 127 */
    605 	unsigned short factor;	/* multiply by to get rlim_{cur,max} values */
    606 };
    607 
    608 #define	OPTSTRING_BASE "HSa"
    609 
    610 static const struct limits limits[] = {
    611 #ifdef RLIMIT_CPU
    612 	{ "time",	"seconds",	't',	RLIMIT_CPU,	   1 },
    613 #define	OPTSTRING_t	OPTSTRING_BASE "t"
    614 #else
    615 #define	OPTSTRING_t	OPTSTRING_BASE
    616 #endif
    617 #ifdef RLIMIT_FSIZE
    618 	{ "file",	"blocks",	'f',	RLIMIT_FSIZE,	 512 },
    619 #define	OPTSTRING_f	OPTSTRING_t "f"
    620 #else
    621 #define	OPTSTRING_f	OPTSTRING_t
    622 #endif
    623 #ifdef RLIMIT_DATA
    624 	{ "data",	"kbytes",	'd',	RLIMIT_DATA,	1024 },
    625 #define	OPTSTRING_d	OPTSTRING_f "d"
    626 #else
    627 #define	OPTSTRING_d	OPTSTRING_f
    628 #endif
    629 #ifdef RLIMIT_STACK
    630 	{ "stack",	"kbytes",	's',	RLIMIT_STACK,	1024 },
    631 #define	OPTSTRING_s	OPTSTRING_d "s"
    632 #else
    633 #define	OPTSTRING_s	OPTSTRING_d
    634 #endif
    635 #ifdef RLIMIT_CORE
    636 	{ "coredump",	"blocks",	'c',	RLIMIT_CORE,	 512 },
    637 #define	OPTSTRING_c	OPTSTRING_s "c"
    638 #else
    639 #define	OPTSTRING_c	OPTSTRING_s
    640 #endif
    641 #ifdef RLIMIT_RSS
    642 	{ "memory",	"kbytes",	'm',	RLIMIT_RSS,	1024 },
    643 #define	OPTSTRING_m	OPTSTRING_c "m"
    644 #else
    645 #define	OPTSTRING_m	OPTSTRING_c
    646 #endif
    647 #ifdef RLIMIT_MEMLOCK
    648 	{ "locked memory","kbytes",	'l',	RLIMIT_MEMLOCK, 1024 },
    649 #define	OPTSTRING_l	OPTSTRING_m "l"
    650 #else
    651 #define	OPTSTRING_l	OPTSTRING_m
    652 #endif
    653 #ifdef RLIMIT_NTHR
    654 	{ "thread",	"threads",	'r',	RLIMIT_NTHR,       1 },
    655 #define	OPTSTRING_r	OPTSTRING_l "r"
    656 #else
    657 #define	OPTSTRING_r	OPTSTRING_l
    658 #endif
    659 #ifdef RLIMIT_NPROC
    660 	{ "process",	"processes",	'p',	RLIMIT_NPROC,      1 },
    661 #define	OPTSTRING_p	OPTSTRING_r "p"
    662 #else
    663 #define	OPTSTRING_p	OPTSTRING_r
    664 #endif
    665 #ifdef RLIMIT_NOFILE
    666 	{ "nofiles",	"descriptors",	'n',	RLIMIT_NOFILE,     1 },
    667 #define	OPTSTRING_n	OPTSTRING_p "n"
    668 #else
    669 #define	OPTSTRING_n	OPTSTRING_p
    670 #endif
    671 #ifdef RLIMIT_VMEM
    672 	{ "vmemory",	"kbytes",	'v',	RLIMIT_VMEM,	1024 },
    673 #define	OPTSTRING_v	OPTSTRING_n "v"
    674 #else
    675 #define	OPTSTRING_v	OPTSTRING_n
    676 #endif
    677 #ifdef RLIMIT_SWAP
    678 	{ "swap",	"kbytes",	'w',	RLIMIT_SWAP,	1024 },
    679 #define	OPTSTRING_w	OPTSTRING_v "w"
    680 #else
    681 #define	OPTSTRING_w	OPTSTRING_v
    682 #endif
    683 #ifdef RLIMIT_SBSIZE
    684 	{ "sbsize",	"bytes",	'b',	RLIMIT_SBSIZE,	   1 },
    685 #define	OPTSTRING_b	OPTSTRING_w "b"
    686 #else
    687 #define	OPTSTRING_b	OPTSTRING_w
    688 #endif
    689 	{ NULL,		NULL,		'\0',	0,		   0 }
    690 };
    691 #define	OPTSTRING	OPTSTRING_b
    692 
    693 int
    694 ulimitcmd(int argc, char **argv)
    695 {
    696 	int	c;
    697 	rlim_t val = 0;
    698 	enum { SOFT = 0x1, HARD = 0x2 }
    699 			how = 0, which;
    700 	const struct limits	*l;
    701 	int		set, all = 0;
    702 	int		optc, what;
    703 	struct rlimit	limit;
    704 
    705 	what = 'f';
    706 	while ((optc = nextopt(OPTSTRING)) != '\0')
    707 		switch (optc) {
    708 		case 'H':
    709 			how |= HARD;
    710 			break;
    711 		case 'S':
    712 			how |= SOFT;
    713 			break;
    714 		case 'a':
    715 			all = 1;
    716 			break;
    717 		default:
    718 			what = optc;
    719 		}
    720 
    721 	for (l = limits; l->name && l->option != what; l++)
    722 		;
    723 	if (!l->name)
    724 		error("internal error (%c)", what);
    725 
    726 	set = *argptr ? 1 : 0;
    727 	if (set) {
    728 		char *p = *argptr;
    729 
    730 		if (all || argptr[1])
    731 			error("too many arguments");
    732 		if (how == 0)
    733 			how = HARD | SOFT;
    734 
    735 		if (strcmp(p, "unlimited") == 0)
    736 			val = RLIM_INFINITY;
    737 		else {
    738 			val = (rlim_t) 0;
    739 
    740 			while ((c = *p++) >= '0' && c <= '9') {
    741 				if (val >= RLIM_INFINITY/10)
    742 					error("%s: value overflow", *argptr);
    743 				val = (val * 10);
    744 				if (val >= RLIM_INFINITY - (long)(c - '0'))
    745 					error("%s: value overflow", *argptr);
    746 				val += (long)(c - '0');
    747 			}
    748 			if (c)
    749 				error("%s: bad number", *argptr);
    750 			if (val > RLIM_INFINITY / l->factor)
    751 				error("%s: value overflow", *argptr);
    752 			val *= l->factor;
    753 		}
    754 	} else if (how == 0)
    755 		how = SOFT;
    756 
    757 	if (all) {
    758 		for (l = limits; l->name; l++) {
    759 			getrlimit(l->cmd, &limit);
    760 			out1fmt("%-13s (-%c %-11s)    ", l->name, l->option,
    761 			    l->unit);
    762 
    763 			which = how;
    764 			while (which != 0) {
    765 				if (which & SOFT) {
    766 					val = limit.rlim_cur;
    767 					which &= ~SOFT;
    768 				} else if (which & HARD) {
    769 					val = limit.rlim_max;
    770 					which &= ~HARD;
    771 				}
    772 
    773 				if (val == RLIM_INFINITY)
    774 					out1fmt("unlimited");
    775 				else {
    776 					val /= l->factor;
    777 #ifdef BSD4_4
    778 					out1fmt("%9lld", (long long) val);
    779 #else
    780 					out1fmt("%9ld", (long) val);
    781 #endif
    782 				}
    783 				out1fmt("%c", which ? '\t' : '\n');
    784 			}
    785 		}
    786 		goto done;
    787 	}
    788 
    789 	if (getrlimit(l->cmd, &limit) == -1)
    790 		error("error getting limit (%s)", strerror(errno));
    791 	if (set) {
    792 		if (how & HARD)
    793 			limit.rlim_max = val;
    794 		if (how & SOFT)
    795 			limit.rlim_cur = val;
    796 		if (setrlimit(l->cmd, &limit) < 0)
    797 			error("error setting limit (%s)", strerror(errno));
    798 		if (l->cmd == RLIMIT_NOFILE)
    799 			user_fd_limit = sysconf(_SC_OPEN_MAX);
    800 	} else {
    801 		if (how & SOFT)
    802 			val = limit.rlim_cur;
    803 		else if (how & HARD)
    804 			val = limit.rlim_max;
    805 
    806 		if (val == RLIM_INFINITY)
    807 			out1fmt("unlimited\n");
    808 		else
    809 		{
    810 			val /= l->factor;
    811 #ifdef BSD4_4
    812 			out1fmt("%lld\n", (long long) val);
    813 #else
    814 			out1fmt("%ld\n", (long) val);
    815 #endif
    816 		}
    817 	}
    818   done:;
    819 	flushout(out1);
    820 	if (io_err(out1)) {
    821 		out2str("ulimit: I/O error (stdout)\n");
    822 		return 1;
    823 	}
    824 	return 0;
    825 }
    826