xref: /netbsd-src/bin/sh/miscbltin.c (revision 2718af68c3efc72c9769069b5c7f9ed36f6b9def)
1 /*	$NetBSD: miscbltin.c,v 1.50 2022/04/16 14:26:26 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.50 2022/04/16 14:26:26 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 	mode_t 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 			int range = 0;
269 
270 			mask = 0;
271 			do {
272 				if (*ap >= '8' || *ap < '0')
273 					error("Not a valid octal number: '%s'",
274 					    *argptr);
275 				mask = (mask << 3) + (*ap - '0');
276 				if (mask & ~07777)
277 					range = 1;
278 			} while (*++ap != '\0');
279 			if (range)
280 			    error("Mask constant '%s' out of range", *argptr);
281 			umask(mask);
282 		} else {
283 			void *set;
284 
285 			INTOFF;
286 			if ((set = setmode(ap)) != 0) {
287 				mask = getmode(set, ~mask & 0777);
288 				ckfree(set);
289 			}
290 			INTON;
291 			if (!set)
292 				error("Cannot set mode `%s' (%s)", ap,
293 				    strerror(errno));
294 
295 			umask(~mask & 0777);
296 		}
297 	}
298 	flushout(out1);
299 	if (io_err(out1)) {
300 		out2str("umask: I/O error\n");
301 		return 1;
302 	}
303 	return 0;
304 }
305 
306 /*
307  * ulimit builtin
308  *
309  * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
310  * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
311  * ash by J.T. Conklin.
312  *
313  * Public domain.
314  */
315 
316 struct limits {
317 	const char *name;
318 	const char *unit;
319 	char	option;
320 	int8_t	cmd;		/* all RLIMIT_xxx are <= 127 */
321 	unsigned short factor;	/* multiply by to get rlim_{cur,max} values */
322 };
323 
324 #define	OPTSTRING_BASE "HSa"
325 
326 static const struct limits limits[] = {
327 #ifdef RLIMIT_CPU
328 	{ "time",	"seconds",	't',	RLIMIT_CPU,	   1 },
329 #define	OPTSTRING_t	OPTSTRING_BASE "t"
330 #else
331 #define	OPTSTRING_t	OPTSTRING_BASE
332 #endif
333 #ifdef RLIMIT_FSIZE
334 	{ "file",	"blocks",	'f',	RLIMIT_FSIZE,	 512 },
335 #define	OPTSTRING_f	OPTSTRING_t "f"
336 #else
337 #define	OPTSTRING_f	OPTSTRING_t
338 #endif
339 #ifdef RLIMIT_DATA
340 	{ "data",	"kbytes",	'd',	RLIMIT_DATA,	1024 },
341 #define	OPTSTRING_d	OPTSTRING_f "d"
342 #else
343 #define	OPTSTRING_d	OPTSTRING_f
344 #endif
345 #ifdef RLIMIT_STACK
346 	{ "stack",	"kbytes",	's',	RLIMIT_STACK,	1024 },
347 #define	OPTSTRING_s	OPTSTRING_d "s"
348 #else
349 #define	OPTSTRING_s	OPTSTRING_d
350 #endif
351 #ifdef RLIMIT_CORE
352 	{ "coredump",	"blocks",	'c',	RLIMIT_CORE,	 512 },
353 #define	OPTSTRING_c	OPTSTRING_s "c"
354 #else
355 #define	OPTSTRING_c	OPTSTRING_s
356 #endif
357 #ifdef RLIMIT_RSS
358 	{ "memory",	"kbytes",	'm',	RLIMIT_RSS,	1024 },
359 #define	OPTSTRING_m	OPTSTRING_c "m"
360 #else
361 #define	OPTSTRING_m	OPTSTRING_c
362 #endif
363 #ifdef RLIMIT_MEMLOCK
364 	{ "locked memory","kbytes",	'l',	RLIMIT_MEMLOCK, 1024 },
365 #define	OPTSTRING_l	OPTSTRING_m "l"
366 #else
367 #define	OPTSTRING_l	OPTSTRING_m
368 #endif
369 #ifdef RLIMIT_NTHR
370 	{ "thread",	"threads",	'r',	RLIMIT_NTHR,       1 },
371 #define	OPTSTRING_r	OPTSTRING_l "r"
372 #else
373 #define	OPTSTRING_r	OPTSTRING_l
374 #endif
375 #ifdef RLIMIT_NPROC
376 	{ "process",	"processes",	'p',	RLIMIT_NPROC,      1 },
377 #define	OPTSTRING_p	OPTSTRING_r "p"
378 #else
379 #define	OPTSTRING_p	OPTSTRING_r
380 #endif
381 #ifdef RLIMIT_NOFILE
382 	{ "nofiles",	"descriptors",	'n',	RLIMIT_NOFILE,     1 },
383 #define	OPTSTRING_n	OPTSTRING_p "n"
384 #else
385 #define	OPTSTRING_n	OPTSTRING_p
386 #endif
387 #ifdef RLIMIT_VMEM
388 	{ "vmemory",	"kbytes",	'v',	RLIMIT_VMEM,	1024 },
389 #define	OPTSTRING_v	OPTSTRING_n "v"
390 #else
391 #define	OPTSTRING_v	OPTSTRING_n
392 #endif
393 #ifdef RLIMIT_SWAP
394 	{ "swap",	"kbytes",	'w',	RLIMIT_SWAP,	1024 },
395 #define	OPTSTRING_w	OPTSTRING_v "w"
396 #else
397 #define	OPTSTRING_w	OPTSTRING_v
398 #endif
399 #ifdef RLIMIT_SBSIZE
400 	{ "sbsize",	"bytes",	'b',	RLIMIT_SBSIZE,	   1 },
401 #define	OPTSTRING_b	OPTSTRING_w "b"
402 #else
403 #define	OPTSTRING_b	OPTSTRING_w
404 #endif
405 	{ NULL,		NULL,		'\0',	0,		   0 }
406 };
407 #define	OPTSTRING	OPTSTRING_b
408 
409 int
410 ulimitcmd(int argc, char **argv)
411 {
412 	int	c;
413 	rlim_t val = 0;
414 	enum { SOFT = 0x1, HARD = 0x2 }
415 			how = 0, which;
416 	const struct limits	*l;
417 	int		set, all = 0;
418 	int		optc, what;
419 	struct rlimit	limit;
420 
421 	what = 'f';
422 	while ((optc = nextopt(OPTSTRING)) != '\0')
423 		switch (optc) {
424 		case 'H':
425 			how |= HARD;
426 			break;
427 		case 'S':
428 			how |= SOFT;
429 			break;
430 		case 'a':
431 			all = 1;
432 			break;
433 		default:
434 			what = optc;
435 		}
436 
437 	for (l = limits; l->name && l->option != what; l++)
438 		;
439 	if (!l->name)
440 		error("internal error (%c)", what);
441 
442 	set = *argptr ? 1 : 0;
443 	if (set) {
444 		char *p = *argptr;
445 
446 		if (all || argptr[1])
447 			error("too many arguments");
448 		if (how == 0)
449 			how = HARD | SOFT;
450 
451 		if (strcmp(p, "unlimited") == 0)
452 			val = RLIM_INFINITY;
453 		else {
454 			val = (rlim_t) 0;
455 
456 			while ((c = *p++) >= '0' && c <= '9') {
457 				if (val >= RLIM_INFINITY/10)
458 					error("%s: value overflow", *argptr);
459 				val = (val * 10);
460 				if (val >= RLIM_INFINITY - (long)(c - '0'))
461 					error("%s: value overflow", *argptr);
462 				val += (long)(c - '0');
463 			}
464 			if (c)
465 				error("%s: bad number", *argptr);
466 			if (val > RLIM_INFINITY / l->factor)
467 				error("%s: value overflow", *argptr);
468 			val *= l->factor;
469 		}
470 	} else if (how == 0)
471 		how = SOFT;
472 
473 	if (all) {
474 		for (l = limits; l->name; l++) {
475 			getrlimit(l->cmd, &limit);
476 			out1fmt("%-13s (-%c %-11s)    ", l->name, l->option,
477 			    l->unit);
478 
479 			which = how;
480 			while (which != 0) {
481 				if (which & SOFT) {
482 					val = limit.rlim_cur;
483 					which &= ~SOFT;
484 				} else if (which & HARD) {
485 					val = limit.rlim_max;
486 					which &= ~HARD;
487 				}
488 
489 				if (val == RLIM_INFINITY)
490 					out1fmt("unlimited");
491 				else {
492 					val /= l->factor;
493 #ifdef BSD4_4
494 					out1fmt("%9lld", (long long) val);
495 #else
496 					out1fmt("%9ld", (long) val);
497 #endif
498 				}
499 				out1fmt("%c", which ? '\t' : '\n');
500 			}
501 		}
502 		goto done;
503 	}
504 
505 	if (getrlimit(l->cmd, &limit) == -1)
506 		error("error getting limit (%s)", strerror(errno));
507 	if (set) {
508 		if (how & HARD)
509 			limit.rlim_max = val;
510 		if (how & SOFT)
511 			limit.rlim_cur = val;
512 		if (setrlimit(l->cmd, &limit) < 0)
513 			error("error setting limit (%s)", strerror(errno));
514 		if (l->cmd == RLIMIT_NOFILE)
515 			user_fd_limit = sysconf(_SC_OPEN_MAX);
516 	} else {
517 		if (how & SOFT)
518 			val = limit.rlim_cur;
519 		else if (how & HARD)
520 			val = limit.rlim_max;
521 
522 		if (val == RLIM_INFINITY)
523 			out1fmt("unlimited\n");
524 		else
525 		{
526 			val /= l->factor;
527 #ifdef BSD4_4
528 			out1fmt("%lld\n", (long long) val);
529 #else
530 			out1fmt("%ld\n", (long) val);
531 #endif
532 		}
533 	}
534   done:;
535 	flushout(out1);
536 	if (io_err(out1)) {
537 		out2str("ulimit: I/O error (stdout)\n");
538 		return 1;
539 	}
540 	return 0;
541 }
542