xref: /freebsd/bin/sh/miscbltin.c (revision f7c32ed617858bcd22f8d1b03199099d50125721)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 #ifndef lint
36 #if 0
37 static char sccsid[] = "@(#)miscbltin.c	8.4 (Berkeley) 5/4/95";
38 #endif
39 #endif /* not lint */
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 /*
44  * Miscellaneous builtins.
45  */
46 
47 #include <sys/types.h>
48 #include <sys/stat.h>
49 #include <sys/time.h>
50 #include <sys/resource.h>
51 #include <unistd.h>
52 #include <errno.h>
53 #include <stdint.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 
57 #include "shell.h"
58 #include "options.h"
59 #include "var.h"
60 #include "output.h"
61 #include "memalloc.h"
62 #include "error.h"
63 #include "mystring.h"
64 #include "syntax.h"
65 #include "trap.h"
66 
67 #undef eflag
68 
69 #define	READ_BUFLEN	1024
70 struct fdctx {
71 	int	fd;
72 	size_t	off;	/* offset in buf */
73 	size_t	buflen;
74 	char	*ep;	/* tail pointer */
75 	char	buf[READ_BUFLEN];
76 };
77 
78 static void fdctx_init(int, struct fdctx *);
79 static void fdctx_destroy(struct fdctx *);
80 static ssize_t fdgetc(struct fdctx *, char *);
81 int readcmd(int, char **);
82 int umaskcmd(int, char **);
83 int ulimitcmd(int, char **);
84 
85 static void
86 fdctx_init(int fd, struct fdctx *fdc)
87 {
88 	off_t cur;
89 
90 	/* Check if fd is seekable. */
91 	cur = lseek(fd, 0, SEEK_CUR);
92 	*fdc = (struct fdctx){
93 		.fd = fd,
94 		.buflen = (cur != -1) ? READ_BUFLEN : 1,
95 		.ep = &fdc->buf[0],	/* No data */
96 	};
97 }
98 
99 static ssize_t
100 fdgetc(struct fdctx *fdc, char *c)
101 {
102 	ssize_t nread;
103 
104 	if (&fdc->buf[fdc->off] == fdc->ep) {
105 		nread = read(fdc->fd, fdc->buf, fdc->buflen);
106 		if (nread > 0) {
107 			fdc->off = 0;
108 			fdc->ep = fdc->buf + nread;
109 		} else
110 			return (nread);
111 	}
112 	*c = fdc->buf[fdc->off++];
113 
114 	return (1);
115 }
116 
117 static void
118 fdctx_destroy(struct fdctx *fdc)
119 {
120 	off_t residue;
121 
122 	if (fdc->buflen > 1) {
123 	/*
124 	 * Reposition the file offset.  Here is the layout of buf:
125 	 *
126 	 *     | off
127 	 *     v
128 	 * |*****************|-------|
129 	 * buf               ep   buf+buflen
130 	 *     |<- residue ->|
131 	 *
132 	 * off: current character
133 	 * ep:  offset just after read(2)
134 	 * residue: length for reposition
135 	 */
136 		residue = (fdc->ep - fdc->buf) - fdc->off;
137 		if (residue > 0)
138 			(void) lseek(fdc->fd, -residue, SEEK_CUR);
139 	}
140 }
141 
142 /*
143  * The read builtin.  The -r option causes backslashes to be treated like
144  * ordinary characters.
145  *
146  * Note that if IFS=' :' then read x y should work so that:
147  * 'a b'	x='a', y='b'
148  * ' a b '	x='a', y='b'
149  * ':b'		x='',  y='b'
150  * ':'		x='',  y=''
151  * '::'		x='',  y=''
152  * ': :'	x='',  y=''
153  * ':::'	x='',  y='::'
154  * ':b c:'	x='',  y='b c:'
155  */
156 
157 int
158 readcmd(int argc __unused, char **argv __unused)
159 {
160 	char **ap;
161 	int backslash;
162 	char c;
163 	int rflag;
164 	char *prompt;
165 	const char *ifs;
166 	char *p;
167 	int startword;
168 	int status;
169 	int i;
170 	int is_ifs;
171 	int saveall = 0;
172 	ptrdiff_t lastnonifs, lastnonifsws;
173 	struct timeval tv;
174 	char *tvptr;
175 	fd_set ifds;
176 	ssize_t nread;
177 	int sig;
178 	struct fdctx fdctx;
179 
180 	rflag = 0;
181 	prompt = NULL;
182 	tv.tv_sec = -1;
183 	tv.tv_usec = 0;
184 	while ((i = nextopt("erp:t:")) != '\0') {
185 		switch(i) {
186 		case 'p':
187 			prompt = shoptarg;
188 			break;
189 		case 'e':
190 			break;
191 		case 'r':
192 			rflag = 1;
193 			break;
194 		case 't':
195 			tv.tv_sec = strtol(shoptarg, &tvptr, 0);
196 			if (tvptr == shoptarg)
197 				error("timeout value");
198 			switch(*tvptr) {
199 			case 0:
200 			case 's':
201 				break;
202 			case 'h':
203 				tv.tv_sec *= 60;
204 				/* FALLTHROUGH */
205 			case 'm':
206 				tv.tv_sec *= 60;
207 				break;
208 			default:
209 				error("timeout unit");
210 			}
211 			break;
212 		}
213 	}
214 	if (prompt && isatty(0)) {
215 		out2str(prompt);
216 		flushall();
217 	}
218 	if (*(ap = argptr) == NULL)
219 		error("arg count");
220 	if ((ifs = bltinlookup("IFS", 1)) == NULL)
221 		ifs = " \t\n";
222 
223 	if (tv.tv_sec >= 0) {
224 		/*
225 		 * Wait for something to become available.
226 		 */
227 		FD_ZERO(&ifds);
228 		FD_SET(0, &ifds);
229 		status = select(1, &ifds, NULL, NULL, &tv);
230 		/*
231 		 * If there's nothing ready, return an error.
232 		 */
233 		if (status <= 0) {
234 			while (*ap != NULL)
235 				setvar(*ap++, "", 0);
236 			sig = pendingsig;
237 			return (128 + (sig != 0 ? sig : SIGALRM));
238 		}
239 	}
240 
241 	status = 0;
242 	startword = 2;
243 	backslash = 0;
244 	STARTSTACKSTR(p);
245 	lastnonifs = lastnonifsws = -1;
246 	fdctx_init(STDIN_FILENO, &fdctx);
247 	for (;;) {
248 		c = 0;
249 		nread = fdgetc(&fdctx, &c);
250 		if (nread == -1) {
251 			if (errno == EINTR) {
252 				sig = pendingsig;
253 				if (sig == 0)
254 					continue;
255 				status = 128 + sig;
256 				break;
257 			}
258 			warning("read error: %s", strerror(errno));
259 			status = 2;
260 			break;
261 		} else if (nread != 1) {
262 			status = 1;
263 			break;
264 		}
265 		if (c == '\0')
266 			continue;
267 		CHECKSTRSPACE(1, p);
268 		if (backslash) {
269 			backslash = 0;
270 			if (c != '\n') {
271 				startword = 0;
272 				lastnonifs = lastnonifsws = p - stackblock();
273 				USTPUTC(c, p);
274 			}
275 			continue;
276 		}
277 		if (!rflag && c == '\\') {
278 			backslash++;
279 			continue;
280 		}
281 		if (c == '\n')
282 			break;
283 		if (strchr(ifs, c))
284 			is_ifs = strchr(" \t\n", c) ? 1 : 2;
285 		else
286 			is_ifs = 0;
287 
288 		if (startword != 0) {
289 			if (is_ifs == 1) {
290 				/* Ignore leading IFS whitespace */
291 				if (saveall)
292 					USTPUTC(c, p);
293 				continue;
294 			}
295 			if (is_ifs == 2 && startword == 1) {
296 				/* Only one non-whitespace IFS per word */
297 				startword = 2;
298 				if (saveall) {
299 					lastnonifsws = p - stackblock();
300 					USTPUTC(c, p);
301 				}
302 				continue;
303 			}
304 		}
305 
306 		if (is_ifs == 0) {
307 			/* append this character to the current variable */
308 			startword = 0;
309 			if (saveall)
310 				/* Not just a spare terminator */
311 				saveall++;
312 			lastnonifs = lastnonifsws = p - stackblock();
313 			USTPUTC(c, p);
314 			continue;
315 		}
316 
317 		/* end of variable... */
318 		startword = is_ifs;
319 
320 		if (ap[1] == NULL) {
321 			/* Last variable needs all IFS chars */
322 			saveall++;
323 			if (is_ifs == 2)
324 				lastnonifsws = p - stackblock();
325 			USTPUTC(c, p);
326 			continue;
327 		}
328 
329 		STACKSTRNUL(p);
330 		setvar(*ap, stackblock(), 0);
331 		ap++;
332 		STARTSTACKSTR(p);
333 		lastnonifs = lastnonifsws = -1;
334 	}
335 	fdctx_destroy(&fdctx);
336 	STACKSTRNUL(p);
337 
338 	/*
339 	 * Remove trailing IFS chars: always remove whitespace, don't remove
340 	 * non-whitespace unless it was naked
341 	 */
342 	if (saveall <= 1)
343 		lastnonifsws = lastnonifs;
344 	stackblock()[lastnonifsws + 1] = '\0';
345 	setvar(*ap, stackblock(), 0);
346 
347 	/* Set any remaining args to "" */
348 	while (*++ap != NULL)
349 		setvar(*ap, "", 0);
350 	return status;
351 }
352 
353 
354 
355 int
356 umaskcmd(int argc __unused, char **argv __unused)
357 {
358 	char *ap;
359 	int mask;
360 	int i;
361 	int symbolic_mode = 0;
362 
363 	while ((i = nextopt("S")) != '\0') {
364 		symbolic_mode = 1;
365 	}
366 
367 	INTOFF;
368 	mask = umask(0);
369 	umask(mask);
370 	INTON;
371 
372 	if ((ap = *argptr) == NULL) {
373 		if (symbolic_mode) {
374 			char u[4], g[4], o[4];
375 
376 			i = 0;
377 			if ((mask & S_IRUSR) == 0)
378 				u[i++] = 'r';
379 			if ((mask & S_IWUSR) == 0)
380 				u[i++] = 'w';
381 			if ((mask & S_IXUSR) == 0)
382 				u[i++] = 'x';
383 			u[i] = '\0';
384 
385 			i = 0;
386 			if ((mask & S_IRGRP) == 0)
387 				g[i++] = 'r';
388 			if ((mask & S_IWGRP) == 0)
389 				g[i++] = 'w';
390 			if ((mask & S_IXGRP) == 0)
391 				g[i++] = 'x';
392 			g[i] = '\0';
393 
394 			i = 0;
395 			if ((mask & S_IROTH) == 0)
396 				o[i++] = 'r';
397 			if ((mask & S_IWOTH) == 0)
398 				o[i++] = 'w';
399 			if ((mask & S_IXOTH) == 0)
400 				o[i++] = 'x';
401 			o[i] = '\0';
402 
403 			out1fmt("u=%s,g=%s,o=%s\n", u, g, o);
404 		} else {
405 			out1fmt("%.4o\n", mask);
406 		}
407 	} else {
408 		if (is_digit(*ap)) {
409 			mask = 0;
410 			do {
411 				if (*ap >= '8' || *ap < '0')
412 					error("Illegal number: %s", *argptr);
413 				mask = (mask << 3) + (*ap - '0');
414 			} while (*++ap != '\0');
415 			umask(mask);
416 		} else {
417 			void *set;
418 			INTOFF;
419 			if ((set = setmode (ap)) == NULL)
420 				error("Illegal number: %s", ap);
421 
422 			mask = getmode (set, ~mask & 0777);
423 			umask(~mask & 0777);
424 			free(set);
425 			INTON;
426 		}
427 	}
428 	return 0;
429 }
430 
431 /*
432  * ulimit builtin
433  *
434  * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
435  * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
436  * ash by J.T. Conklin.
437  *
438  * Public domain.
439  */
440 
441 struct limits {
442 	const char *name;
443 	const char *units;
444 	int	cmd;
445 	short	factor;	/* multiply by to get rlim_{cur,max} values */
446 	char	option;
447 };
448 
449 static const struct limits limits[] = {
450 #ifdef RLIMIT_CPU
451 	{ "cpu time",		"seconds",	RLIMIT_CPU,	   1, 't' },
452 #endif
453 #ifdef RLIMIT_FSIZE
454 	{ "file size",		"512-blocks",	RLIMIT_FSIZE,	 512, 'f' },
455 #endif
456 #ifdef RLIMIT_DATA
457 	{ "data seg size",	"kbytes",	RLIMIT_DATA,	1024, 'd' },
458 #endif
459 #ifdef RLIMIT_STACK
460 	{ "stack size",		"kbytes",	RLIMIT_STACK,	1024, 's' },
461 #endif
462 #ifdef  RLIMIT_CORE
463 	{ "core file size",	"512-blocks",	RLIMIT_CORE,	 512, 'c' },
464 #endif
465 #ifdef RLIMIT_RSS
466 	{ "max memory size",	"kbytes",	RLIMIT_RSS,	1024, 'm' },
467 #endif
468 #ifdef RLIMIT_MEMLOCK
469 	{ "locked memory",	"kbytes",	RLIMIT_MEMLOCK, 1024, 'l' },
470 #endif
471 #ifdef RLIMIT_NPROC
472 	{ "max user processes",	(char *)0,	RLIMIT_NPROC,      1, 'u' },
473 #endif
474 #ifdef RLIMIT_NOFILE
475 	{ "open files",		(char *)0,	RLIMIT_NOFILE,     1, 'n' },
476 #endif
477 #ifdef RLIMIT_VMEM
478 	{ "virtual mem size",	"kbytes",	RLIMIT_VMEM,	1024, 'v' },
479 #endif
480 #ifdef RLIMIT_SWAP
481 	{ "swap limit",		"kbytes",	RLIMIT_SWAP,	1024, 'w' },
482 #endif
483 #ifdef RLIMIT_SBSIZE
484 	{ "socket buffer size",	"bytes",	RLIMIT_SBSIZE,	   1, 'b' },
485 #endif
486 #ifdef RLIMIT_NPTS
487 	{ "pseudo-terminals",	(char *)0,	RLIMIT_NPTS,	   1, 'p' },
488 #endif
489 #ifdef RLIMIT_KQUEUES
490 	{ "kqueues",		(char *)0,	RLIMIT_KQUEUES,	   1, 'k' },
491 #endif
492 #ifdef RLIMIT_UMTXP
493 	{ "umtx shared locks",	(char *)0,	RLIMIT_UMTXP,	   1, 'o' },
494 #endif
495 	{ (char *) 0,		(char *)0,	0,		   0, '\0' }
496 };
497 
498 enum limithow { SOFT = 0x1, HARD = 0x2 };
499 
500 static void
501 printlimit(enum limithow how, const struct rlimit *limit,
502     const struct limits *l)
503 {
504 	rlim_t val = 0;
505 
506 	if (how & SOFT)
507 		val = limit->rlim_cur;
508 	else if (how & HARD)
509 		val = limit->rlim_max;
510 	if (val == RLIM_INFINITY)
511 		out1str("unlimited\n");
512 	else
513 	{
514 		val /= l->factor;
515 		out1fmt("%jd\n", (intmax_t)val);
516 	}
517 }
518 
519 int
520 ulimitcmd(int argc __unused, char **argv __unused)
521 {
522 	rlim_t val = 0;
523 	enum limithow how = SOFT | HARD;
524 	const struct limits	*l;
525 	int		set, all = 0;
526 	int		optc, what;
527 	struct rlimit	limit;
528 
529 	what = 'f';
530 	while ((optc = nextopt("HSatfdsmcnuvlbpwko")) != '\0')
531 		switch (optc) {
532 		case 'H':
533 			how = HARD;
534 			break;
535 		case 'S':
536 			how = SOFT;
537 			break;
538 		case 'a':
539 			all = 1;
540 			break;
541 		default:
542 			what = optc;
543 		}
544 
545 	for (l = limits; l->name && l->option != what; l++)
546 		;
547 	if (!l->name)
548 		error("internal error (%c)", what);
549 
550 	set = *argptr ? 1 : 0;
551 	if (set) {
552 		char *p = *argptr;
553 
554 		if (all || argptr[1])
555 			error("too many arguments");
556 		if (strcmp(p, "unlimited") == 0)
557 			val = RLIM_INFINITY;
558 		else {
559 			char *end;
560 			uintmax_t uval;
561 
562 			if (*p < '0' || *p > '9')
563 				error("bad number");
564 			errno = 0;
565 			uval = strtoumax(p, &end, 10);
566 			if (errno != 0 || *end != '\0')
567 				error("bad number");
568 			if (uval > UINTMAX_MAX / l->factor)
569 				error("bad number");
570 			uval *= l->factor;
571 			val = (rlim_t)uval;
572 			if (val < 0 || (uintmax_t)val != uval ||
573 			    val == RLIM_INFINITY)
574 				error("bad number");
575 		}
576 	}
577 	if (all) {
578 		for (l = limits; l->name; l++) {
579 			char optbuf[40];
580 			if (getrlimit(l->cmd, &limit) < 0)
581 				error("can't get limit: %s", strerror(errno));
582 
583 			if (l->units)
584 				snprintf(optbuf, sizeof(optbuf),
585 					"(%s, -%c) ", l->units, l->option);
586 			else
587 				snprintf(optbuf, sizeof(optbuf),
588 					"(-%c) ", l->option);
589 			out1fmt("%-18s %18s ", l->name, optbuf);
590 			printlimit(how, &limit, l);
591 		}
592 		return 0;
593 	}
594 
595 	if (getrlimit(l->cmd, &limit) < 0)
596 		error("can't get limit: %s", strerror(errno));
597 	if (set) {
598 		if (how & SOFT)
599 			limit.rlim_cur = val;
600 		if (how & HARD)
601 			limit.rlim_max = val;
602 		if (setrlimit(l->cmd, &limit) < 0)
603 			error("bad limit: %s", strerror(errno));
604 	} else
605 		printlimit(how, &limit, l);
606 	return 0;
607 }
608