Home | History | Annotate | Line # | Download | only in sh
miscbltin.c revision 1.48
      1 /*	$NetBSD: miscbltin.c,v 1.48 2022/04/16 14:20:45 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.48 2022/04/16 14:20:45 kre Exp $");
     41 #endif
     42 #endif /* not lint */
     43 
     44 /*
     45  * Miscellaneous builtins.
     46  */
     47 
     48 #include <sys/types.h>		/* quad_t */
     49 #include <sys/param.h>		/* BSD4_4 */
     50 #include <sys/stat.h>
     51 #include <sys/time.h>
     52 #include <sys/resource.h>
     53 #include <unistd.h>
     54 #include <stdlib.h>
     55 #include <ctype.h>
     56 #include <errno.h>
     57 
     58 #include "shell.h"
     59 #include "options.h"
     60 #include "var.h"
     61 #include "output.h"
     62 #include "memalloc.h"
     63 #include "error.h"
     64 #include "builtins.h"
     65 #include "mystring.h"
     66 #include "redir.h"		/* for user_fd_limit */
     67 
     68 #undef rflag
     69 
     70 
     71 
     72 /*
     73  * The read builtin.
     74  * Backslashes escape the next char unless -r is specified.
     75  *
     76  * This uses unbuffered input, which may be avoidable in some cases.
     77  *
     78  * Note that if IFS=' :' then read x y should work so that:
     79  * 'a b'	x='a', y='b'
     80  * ' a b '	x='a', y='b'
     81  * ':b'		x='',  y='b'
     82  * ':'		x='',  y=''
     83  * '::'		x='',  y=''
     84  * ': :'	x='',  y=''
     85  * ':::'	x='',  y='::'
     86  * ':b c:'	x='',  y='b c:'
     87  */
     88 
     89 int
     90 readcmd(int argc, char **argv)
     91 {
     92 	char **ap;
     93 	char c;
     94 	int rflag;
     95 	char *prompt;
     96 	const char *ifs;
     97 	char *p;
     98 	int startword;
     99 	int status;
    100 	int i;
    101 	int is_ifs;
    102 	int saveall = 0;
    103 
    104 	rflag = 0;
    105 	prompt = NULL;
    106 	while ((i = nextopt("p:r")) != '\0') {
    107 		if (i == 'p')
    108 			prompt = optionarg;
    109 		else
    110 			rflag = 1;
    111 	}
    112 
    113 	if (prompt && isatty(0)) {
    114 		out2str(prompt);
    115 		flushall();
    116 	}
    117 
    118 	if (*(ap = argptr) == NULL)
    119 		error("arg count");
    120 
    121 	if ((ifs = bltinlookup("IFS", 1)) == NULL)
    122 		ifs = " \t\n";
    123 
    124 	status = 0;
    125 	startword = 2;
    126 	STARTSTACKSTR(p);
    127 	for (;;) {
    128 		if (read(0, &c, 1) != 1) {
    129 			status = 1;
    130 			break;
    131 		}
    132 		if (c == '\0')
    133 			continue;
    134 		if (c == '\\' && !rflag) {
    135 			if (read(0, &c, 1) != 1) {
    136 				status = 1;
    137 				break;
    138 			}
    139 			if (c != '\n')
    140 				STPUTC(c, p);
    141 			continue;
    142 		}
    143 		if (c == '\n')
    144 			break;
    145 		if (strchr(ifs, c))
    146 			is_ifs = strchr(" \t\n", c) ? 1 : 2;
    147 		else
    148 			is_ifs = 0;
    149 
    150 		if (startword != 0) {
    151 			if (is_ifs == 1) {
    152 				/* Ignore leading IFS whitespace */
    153 				if (saveall)
    154 					STPUTC(c, p);
    155 				continue;
    156 			}
    157 			if (is_ifs == 2 && startword == 1) {
    158 				/* Only one non-whitespace IFS per word */
    159 				startword = 2;
    160 				if (saveall)
    161 					STPUTC(c, p);
    162 				continue;
    163 			}
    164 		}
    165 
    166 		if (is_ifs == 0) {
    167 			/* append this character to the current variable */
    168 			startword = 0;
    169 			if (saveall)
    170 				/* Not just a spare terminator */
    171 				saveall++;
    172 			STPUTC(c, p);
    173 			continue;
    174 		}
    175 
    176 		/* end of variable... */
    177 		startword = is_ifs;
    178 
    179 		if (ap[1] == NULL) {
    180 			/* Last variable needs all IFS chars */
    181 			saveall++;
    182 			STPUTC(c, p);
    183 			continue;
    184 		}
    185 
    186 		STACKSTRNUL(p);
    187 		setvar(*ap, stackblock(), 0);
    188 		ap++;
    189 		STARTSTACKSTR(p);
    190 	}
    191 	STACKSTRNUL(p);
    192 
    193 	/* Remove trailing IFS chars */
    194 	for (; stackblock() <= --p; *p = 0) {
    195 		if (!strchr(ifs, *p))
    196 			break;
    197 		if (strchr(" \t\n", *p))
    198 			/* Always remove whitespace */
    199 			continue;
    200 		if (saveall > 1)
    201 			/* Don't remove non-whitespace unless it was naked */
    202 			break;
    203 	}
    204 	setvar(*ap, stackblock(), 0);
    205 
    206 	/* Set any remaining args to "" */
    207 	while (*++ap != NULL)
    208 		setvar(*ap, nullstr, 0);
    209 	return status;
    210 }
    211 
    212 
    213 
    214 int
    215 umaskcmd(int argc, char **argv)
    216 {
    217 	char *ap;
    218 	int mask;
    219 	int i;
    220 	int symbolic_mode = 0;
    221 
    222 	while ((i = nextopt("S")) != '\0') {
    223 		symbolic_mode = 1;
    224 	}
    225 
    226 	INTOFF;
    227 	mask = umask(0);
    228 	umask(mask);
    229 	INTON;
    230 
    231 	if ((ap = *argptr) == NULL) {
    232 		if (symbolic_mode) {
    233 			char u[4], g[4], o[4];
    234 
    235 			i = 0;
    236 			if ((mask & S_IRUSR) == 0)
    237 				u[i++] = 'r';
    238 			if ((mask & S_IWUSR) == 0)
    239 				u[i++] = 'w';
    240 			if ((mask & S_IXUSR) == 0)
    241 				u[i++] = 'x';
    242 			u[i] = '\0';
    243 
    244 			i = 0;
    245 			if ((mask & S_IRGRP) == 0)
    246 				g[i++] = 'r';
    247 			if ((mask & S_IWGRP) == 0)
    248 				g[i++] = 'w';
    249 			if ((mask & S_IXGRP) == 0)
    250 				g[i++] = 'x';
    251 			g[i] = '\0';
    252 
    253 			i = 0;
    254 			if ((mask & S_IROTH) == 0)
    255 				o[i++] = 'r';
    256 			if ((mask & S_IWOTH) == 0)
    257 				o[i++] = 'w';
    258 			if ((mask & S_IXOTH) == 0)
    259 				o[i++] = 'x';
    260 			o[i] = '\0';
    261 
    262 			out1fmt("u=%s,g=%s,o=%s\n", u, g, o);
    263 		} else {
    264 			out1fmt("%.4o\n", mask);
    265 		}
    266 	} else {
    267 		if (isdigit((unsigned char)*ap)) {
    268 			mask = 0;
    269 			do {
    270 				if (*ap >= '8' || *ap < '0')
    271 					error("Not a valid octal number: '%s'",
    272 					    argv[1]);
    273 				mask = (mask << 3) + (*ap - '0');
    274 			} while (*++ap != '\0');
    275 			umask(mask);
    276 		} else {
    277 			void *set;
    278 
    279 			INTOFF;
    280 			if ((set = setmode(ap)) != 0) {
    281 				mask = getmode(set, ~mask & 0777);
    282 				ckfree(set);
    283 			}
    284 			INTON;
    285 			if (!set)
    286 				error("Cannot set mode `%s' (%s)", ap,
    287 				    strerror(errno));
    288 
    289 			umask(~mask & 0777);
    290 		}
    291 	}
    292 	flushout(out1);
    293 	if (io_err(out1)) {
    294 		out2str("umask: I/O error\n");
    295 		return 1;
    296 	}
    297 	return 0;
    298 }
    299 
    300 /*
    301  * ulimit builtin
    302  *
    303  * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
    304  * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
    305  * ash by J.T. Conklin.
    306  *
    307  * Public domain.
    308  */
    309 
    310 struct limits {
    311 	const char *name;
    312 	const char *unit;
    313 	int	cmd;
    314 	int	factor;	/* multiply by to get rlim_{cur,max} values */
    315 	char	option;
    316 };
    317 
    318 static const struct limits limits[] = {
    319 #ifdef RLIMIT_CPU
    320 	{ "time",	"seconds",	RLIMIT_CPU,	   1, 't' },
    321 #endif
    322 #ifdef RLIMIT_FSIZE
    323 	{ "file",	"blocks",	RLIMIT_FSIZE,	 512, 'f' },
    324 #endif
    325 #ifdef RLIMIT_DATA
    326 	{ "data",	"kbytes",	RLIMIT_DATA,	1024, 'd' },
    327 #endif
    328 #ifdef RLIMIT_STACK
    329 	{ "stack",	"kbytes",	RLIMIT_STACK,	1024, 's' },
    330 #endif
    331 #ifdef RLIMIT_CORE
    332 	{ "coredump",	"blocks",	RLIMIT_CORE,	 512, 'c' },
    333 #endif
    334 #ifdef RLIMIT_RSS
    335 	{ "memory",	"kbytes",	RLIMIT_RSS,	1024, 'm' },
    336 #endif
    337 #ifdef RLIMIT_MEMLOCK
    338 	{ "locked memory","kbytes",	RLIMIT_MEMLOCK, 1024, 'l' },
    339 #endif
    340 #ifdef RLIMIT_NTHR
    341 	{ "thread",	"threads",	RLIMIT_NTHR,       1, 'r' },
    342 #endif
    343 #ifdef RLIMIT_NPROC
    344 	{ "process",	"processes",	RLIMIT_NPROC,      1, 'p' },
    345 #endif
    346 #ifdef RLIMIT_NOFILE
    347 	{ "nofiles",	"descriptors",	RLIMIT_NOFILE,     1, 'n' },
    348 #endif
    349 #ifdef RLIMIT_VMEM
    350 	{ "vmemory",	"kbytes",	RLIMIT_VMEM,	1024, 'v' },
    351 #endif
    352 #ifdef RLIMIT_SWAP
    353 	{ "swap",	"kbytes",	RLIMIT_SWAP,	1024, 'w' },
    354 #endif
    355 #ifdef RLIMIT_SBSIZE
    356 	{ "sbsize",	"bytes",	RLIMIT_SBSIZE,	   1, 'b' },
    357 #endif
    358 	{ NULL,		NULL,		0,		   0,  '\0' }
    359 };
    360 
    361 int
    362 ulimitcmd(int argc, char **argv)
    363 {
    364 	int	c;
    365 	rlim_t val = 0;
    366 	enum { SOFT = 0x1, HARD = 0x2 }
    367 			how = 0, which;
    368 	const struct limits	*l;
    369 	int		set, all = 0;
    370 	int		optc, what;
    371 	struct rlimit	limit;
    372 
    373 	what = 'f';
    374 	while ((optc = nextopt("HSabtfdscmlrpnv")) != '\0')
    375 		switch (optc) {
    376 		case 'H':
    377 			how |= HARD;
    378 			break;
    379 		case 'S':
    380 			how |= SOFT;
    381 			break;
    382 		case 'a':
    383 			all = 1;
    384 			break;
    385 		default:
    386 			what = optc;
    387 		}
    388 
    389 	for (l = limits; l->name && l->option != what; l++)
    390 		;
    391 	if (!l->name)
    392 		error("internal error (%c)", what);
    393 
    394 	set = *argptr ? 1 : 0;
    395 	if (set) {
    396 		char *p = *argptr;
    397 
    398 		if (all || argptr[1])
    399 			error("too many arguments");
    400 		if (how == 0)
    401 			how = HARD | SOFT;
    402 
    403 		if (strcmp(p, "unlimited") == 0)
    404 			val = RLIM_INFINITY;
    405 		else {
    406 			val = (rlim_t) 0;
    407 
    408 			while ((c = *p++) >= '0' && c <= '9') {
    409 				if (val >= RLIM_INFINITY/10)
    410 					error("value overflow");
    411 				val = (val * 10);
    412 				if (val >= RLIM_INFINITY - (long)(c - '0'))
    413 					error("value overflow");
    414 				val += (long)(c - '0');
    415 			}
    416 			if (c)
    417 				error("bad number");
    418 			if (val > RLIM_INFINITY / l->factor)
    419 				error("value overflow");
    420 			val *= l->factor;
    421 		}
    422 	} else if (how == 0)
    423 		how = SOFT;
    424 
    425 	if (all) {
    426 		for (l = limits; l->name; l++) {
    427 			getrlimit(l->cmd, &limit);
    428 			out1fmt("%-13s (-%c %-11s)    ", l->name, l->option,
    429 			    l->unit);
    430 
    431 			which = how;
    432 			while (which != 0) {
    433 				if (which & SOFT) {
    434 					val = limit.rlim_cur;
    435 					which &= ~SOFT;
    436 				} else if (which & HARD) {
    437 					val = limit.rlim_max;
    438 					which &= ~HARD;
    439 				}
    440 
    441 				if (val == RLIM_INFINITY)
    442 					out1fmt("unlimited");
    443 				else {
    444 					val /= l->factor;
    445 #ifdef BSD4_4
    446 					out1fmt("%9lld", (long long) val);
    447 #else
    448 					out1fmt("%9ld", (long) val);
    449 #endif
    450 				}
    451 				out1fmt("%c", which ? '\t' : '\n');
    452 			}
    453 		}
    454 		goto done;
    455 	}
    456 
    457 	if (getrlimit(l->cmd, &limit) == -1)
    458 		error("error getting limit (%s)", strerror(errno));
    459 	if (set) {
    460 		if (how & HARD)
    461 			limit.rlim_max = val;
    462 		if (how & SOFT)
    463 			limit.rlim_cur = val;
    464 		if (setrlimit(l->cmd, &limit) < 0)
    465 			error("error setting limit (%s)", strerror(errno));
    466 		if (l->cmd == RLIMIT_NOFILE)
    467 			user_fd_limit = sysconf(_SC_OPEN_MAX);
    468 	} else {
    469 		if (how & SOFT)
    470 			val = limit.rlim_cur;
    471 		else if (how & HARD)
    472 			val = limit.rlim_max;
    473 
    474 		if (val == RLIM_INFINITY)
    475 			out1fmt("unlimited\n");
    476 		else
    477 		{
    478 			val /= l->factor;
    479 #ifdef BSD4_4
    480 			out1fmt("%lld\n", (long long) val);
    481 #else
    482 			out1fmt("%ld\n", (long) val);
    483 #endif
    484 		}
    485 	}
    486   done:;
    487 	flushout(out1);
    488 	if (io_err(out1)) {
    489 		out2str("ulimit: I/O error (stdout)\n");
    490 		return 1;
    491 	}
    492 	return 0;
    493 }
    494