xref: /freebsd/bin/sh/miscbltin.c (revision c0020399a650364d0134f79f3fa319f84064372d)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)miscbltin.c	8.4 (Berkeley) 5/4/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 /*
42  * Miscellaneous builtins.
43  */
44 
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <sys/time.h>
48 #include <sys/resource.h>
49 #include <unistd.h>
50 #include <ctype.h>
51 #include <errno.h>
52 #include <stdint.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <termios.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 
65 #undef eflag
66 
67 int readcmd(int, char **);
68 int umaskcmd(int, char **);
69 int ulimitcmd(int, char **);
70 
71 /*
72  * The read builtin.  The -r option causes backslashes to be treated like
73  * ordinary characters.
74  *
75  * This uses unbuffered input, which may be avoidable in some cases.
76  *
77  * Note that if IFS=' :' then read x y should work so that:
78  * 'a b'	x='a', y='b'
79  * ' a b '	x='a', y='b'
80  * ':b'		x='',  y='b'
81  * ':'		x='',  y=''
82  * '::'		x='',  y=''
83  * ': :'	x='',  y=''
84  * ':::'	x='',  y='::'
85  * ':b c:'	x='',  y='b c:'
86  */
87 
88 int
89 readcmd(int argc __unused, char **argv __unused)
90 {
91 	char **ap;
92 	int backslash;
93 	char c;
94 	int rflag;
95 	char *prompt;
96 	char *ifs;
97 	char *p;
98 	int startword;
99 	int status;
100 	int i;
101 	int is_ifs;
102 	int saveall = 0;
103 	struct timeval tv;
104 	char *tvptr;
105 	fd_set ifds;
106 	struct termios told, tnew;
107 	int tsaved;
108 
109 	rflag = 0;
110 	prompt = NULL;
111 	tv.tv_sec = -1;
112 	tv.tv_usec = 0;
113 	while ((i = nextopt("erp:t:")) != '\0') {
114 		switch(i) {
115 		case 'p':
116 			prompt = shoptarg;
117 			break;
118 		case 'e':
119 			break;
120 		case 'r':
121 			rflag = 1;
122 			break;
123 		case 't':
124 			tv.tv_sec = strtol(shoptarg, &tvptr, 0);
125 			if (tvptr == shoptarg)
126 				error("timeout value");
127 			switch(*tvptr) {
128 			case 0:
129 			case 's':
130 				break;
131 			case 'h':
132 				tv.tv_sec *= 60;
133 				/* FALLTHROUGH */
134 			case 'm':
135 				tv.tv_sec *= 60;
136 				break;
137 			default:
138 				error("timeout unit");
139 			}
140 			break;
141 		}
142 	}
143 	if (prompt && isatty(0)) {
144 		out2str(prompt);
145 		flushall();
146 	}
147 	if (*(ap = argptr) == NULL)
148 		error("arg count");
149 	if ((ifs = bltinlookup("IFS", 1)) == NULL)
150 		ifs = " \t\n";
151 
152 	if (tv.tv_sec >= 0) {
153 		/*
154 		 * See if we can disable input processing; this will
155 		 * not give the desired result if we are in a pipeline
156 		 * and someone upstream is still in line-by-line mode.
157 		 */
158 		tsaved = 0;
159 		if (tcgetattr(0, &told) == 0) {
160 			memcpy(&tnew, &told, sizeof(told));
161 			cfmakeraw(&tnew);
162 			tnew.c_iflag |= told.c_iflag & ICRNL;
163 			tcsetattr(0, TCSANOW, &tnew);
164 			tsaved = 1;
165 		}
166 		/*
167 		 * Wait for something to become available.
168 		 */
169 		FD_ZERO(&ifds);
170 		FD_SET(0, &ifds);
171 		status = select(1, &ifds, NULL, NULL, &tv);
172 		if (tsaved)
173 			tcsetattr(0, TCSANOW, &told);
174 		/*
175 		 * If there's nothing ready, return an error.
176 		 */
177 		if (status <= 0)
178 			return(1);
179 	}
180 
181 	status = 0;
182 	startword = 2;
183 	backslash = 0;
184 	STARTSTACKSTR(p);
185 	for (;;) {
186 		if (read(STDIN_FILENO, &c, 1) != 1) {
187 			status = 1;
188 			break;
189 		}
190 		if (c == '\0')
191 			continue;
192 		if (backslash) {
193 			backslash = 0;
194 			if (c != '\n')
195 				STPUTC(c, p);
196 			continue;
197 		}
198 		if (!rflag && c == '\\') {
199 			backslash++;
200 			continue;
201 		}
202 		if (c == '\n')
203 			break;
204 		if (strchr(ifs, c))
205 			is_ifs = strchr(" \t\n", c) ? 1 : 2;
206 		else
207 			is_ifs = 0;
208 
209 		if (startword != 0) {
210 			if (is_ifs == 1) {
211 				/* Ignore leading IFS whitespace */
212 				if (saveall)
213 					STPUTC(c, p);
214 				continue;
215 			}
216 			if (is_ifs == 2 && startword == 1) {
217 				/* Only one non-whitespace IFS per word */
218 				startword = 2;
219 				if (saveall)
220 					STPUTC(c, p);
221 				continue;
222 			}
223 		}
224 
225 		if (is_ifs == 0) {
226 			/* append this character to the current variable */
227 			startword = 0;
228 			if (saveall)
229 				/* Not just a spare terminator */
230 				saveall++;
231 			STPUTC(c, p);
232 			continue;
233 		}
234 
235 		/* end of variable... */
236 		startword = is_ifs;
237 
238 		if (ap[1] == NULL) {
239 			/* Last variable needs all IFS chars */
240 			saveall++;
241 			STPUTC(c, p);
242 			continue;
243 		}
244 
245 		STACKSTRNUL(p);
246 		setvar(*ap, stackblock(), 0);
247 		ap++;
248 		STARTSTACKSTR(p);
249 	}
250 	STACKSTRNUL(p);
251 
252 	/* Remove trailing IFS chars */
253 	for (; stackblock() <= --p; *p = 0) {
254 		if (!strchr(ifs, *p))
255 			break;
256 		if (strchr(" \t\n", *p))
257 			/* Always remove whitespace */
258 			continue;
259 		if (saveall > 1)
260 			/* Don't remove non-whitespace unless it was naked */
261 			break;
262 	}
263 	setvar(*ap, stackblock(), 0);
264 
265 	/* Set any remaining args to "" */
266 	while (*++ap != NULL)
267 		setvar(*ap, nullstr, 0);
268 	return status;
269 }
270 
271 
272 
273 int
274 umaskcmd(int argc __unused, char **argv)
275 {
276 	char *ap;
277 	int mask;
278 	int i;
279 	int symbolic_mode = 0;
280 
281 	while ((i = nextopt("S")) != '\0') {
282 		symbolic_mode = 1;
283 	}
284 
285 	INTOFF;
286 	mask = umask(0);
287 	umask(mask);
288 	INTON;
289 
290 	if ((ap = *argptr) == NULL) {
291 		if (symbolic_mode) {
292 			char u[4], g[4], o[4];
293 
294 			i = 0;
295 			if ((mask & S_IRUSR) == 0)
296 				u[i++] = 'r';
297 			if ((mask & S_IWUSR) == 0)
298 				u[i++] = 'w';
299 			if ((mask & S_IXUSR) == 0)
300 				u[i++] = 'x';
301 			u[i] = '\0';
302 
303 			i = 0;
304 			if ((mask & S_IRGRP) == 0)
305 				g[i++] = 'r';
306 			if ((mask & S_IWGRP) == 0)
307 				g[i++] = 'w';
308 			if ((mask & S_IXGRP) == 0)
309 				g[i++] = 'x';
310 			g[i] = '\0';
311 
312 			i = 0;
313 			if ((mask & S_IROTH) == 0)
314 				o[i++] = 'r';
315 			if ((mask & S_IWOTH) == 0)
316 				o[i++] = 'w';
317 			if ((mask & S_IXOTH) == 0)
318 				o[i++] = 'x';
319 			o[i] = '\0';
320 
321 			out1fmt("u=%s,g=%s,o=%s\n", u, g, o);
322 		} else {
323 			out1fmt("%.4o\n", mask);
324 		}
325 	} else {
326 		if (isdigit(*ap)) {
327 			mask = 0;
328 			do {
329 				if (*ap >= '8' || *ap < '0')
330 					error("Illegal number: %s", *argptr);
331 				mask = (mask << 3) + (*ap - '0');
332 			} while (*++ap != '\0');
333 			umask(mask);
334 		} else {
335 			void *set;
336 			INTOFF;
337 			if ((set = setmode (ap)) == 0)
338 				error("Illegal number: %s", ap);
339 
340 			mask = getmode (set, ~mask & 0777);
341 			umask(~mask & 0777);
342 			free(set);
343 			INTON;
344 		}
345 	}
346 	return 0;
347 }
348 
349 /*
350  * ulimit builtin
351  *
352  * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
353  * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
354  * ash by J.T. Conklin.
355  *
356  * Public domain.
357  */
358 
359 struct limits {
360 	const char *name;
361 	const char *units;
362 	int	cmd;
363 	int	factor;	/* multiply by to get rlim_{cur,max} values */
364 	char	option;
365 };
366 
367 static const struct limits limits[] = {
368 #ifdef RLIMIT_CPU
369 	{ "cpu time",		"seconds",	RLIMIT_CPU,	   1, 't' },
370 #endif
371 #ifdef RLIMIT_FSIZE
372 	{ "file size",		"512-blocks",	RLIMIT_FSIZE,	 512, 'f' },
373 #endif
374 #ifdef RLIMIT_DATA
375 	{ "data seg size",	"kbytes",	RLIMIT_DATA,	1024, 'd' },
376 #endif
377 #ifdef RLIMIT_STACK
378 	{ "stack size",		"kbytes",	RLIMIT_STACK,	1024, 's' },
379 #endif
380 #ifdef  RLIMIT_CORE
381 	{ "core file size",	"512-blocks",	RLIMIT_CORE,	 512, 'c' },
382 #endif
383 #ifdef RLIMIT_RSS
384 	{ "max memory size",	"kbytes",	RLIMIT_RSS,	1024, 'm' },
385 #endif
386 #ifdef RLIMIT_MEMLOCK
387 	{ "locked memory",	"kbytes",	RLIMIT_MEMLOCK, 1024, 'l' },
388 #endif
389 #ifdef RLIMIT_NPROC
390 	{ "max user processes",	(char *)0,	RLIMIT_NPROC,      1, 'u' },
391 #endif
392 #ifdef RLIMIT_NOFILE
393 	{ "open files",		(char *)0,	RLIMIT_NOFILE,     1, 'n' },
394 #endif
395 #ifdef RLIMIT_VMEM
396 	{ "virtual mem size",	"kbytes",	RLIMIT_VMEM,	1024, 'v' },
397 #endif
398 #ifdef RLIMIT_SWAP
399 	{ "swap limit",		"kbytes",	RLIMIT_SWAP,	1024, 'w' },
400 #endif
401 #ifdef RLIMIT_SBSIZE
402 	{ "sbsize",		"bytes",	RLIMIT_SBSIZE,	   1, 'b' },
403 #endif
404 #ifdef RLIMIT_NPTS
405 	{ "pseudo-terminals",	(char *)0,	RLIMIT_NPTS,	   1, 'p' },
406 #endif
407 	{ (char *) 0,		(char *)0,	0,		   0, '\0' }
408 };
409 
410 int
411 ulimitcmd(int argc __unused, char **argv __unused)
412 {
413 	int	c;
414 	rlim_t val = 0;
415 	enum { SOFT = 0x1, HARD = 0x2 }
416 			how = SOFT | HARD;
417 	const struct limits	*l;
418 	int		set, all = 0;
419 	int		optc, what;
420 	struct rlimit	limit;
421 
422 	what = 'f';
423 	while ((optc = nextopt("HSatfdsmcnuvlbp")) != '\0')
424 		switch (optc) {
425 		case 'H':
426 			how = HARD;
427 			break;
428 		case 'S':
429 			how = SOFT;
430 			break;
431 		case 'a':
432 			all = 1;
433 			break;
434 		default:
435 			what = optc;
436 		}
437 
438 	for (l = limits; l->name && l->option != what; l++)
439 		;
440 	if (!l->name)
441 		error("internal error (%c)", what);
442 
443 	set = *argptr ? 1 : 0;
444 	if (set) {
445 		char *p = *argptr;
446 
447 		if (all || argptr[1])
448 			error("too many arguments");
449 		if (strcmp(p, "unlimited") == 0)
450 			val = RLIM_INFINITY;
451 		else {
452 			val = 0;
453 
454 			while ((c = *p++) >= '0' && c <= '9')
455 			{
456 				val = (val * 10) + (long)(c - '0');
457 				if (val < 0)
458 					break;
459 			}
460 			if (c)
461 				error("bad number");
462 			val *= l->factor;
463 		}
464 	}
465 	if (all) {
466 		for (l = limits; l->name; l++) {
467 			char optbuf[40];
468 			if (getrlimit(l->cmd, &limit) < 0)
469 				error("can't get limit: %s", strerror(errno));
470 			if (how & SOFT)
471 				val = limit.rlim_cur;
472 			else if (how & HARD)
473 				val = limit.rlim_max;
474 
475 			if (l->units)
476 				snprintf(optbuf, sizeof(optbuf),
477 					"(%s, -%c) ", l->units, l->option);
478 			else
479 				snprintf(optbuf, sizeof(optbuf),
480 					"(-%c) ", l->option);
481 			out1fmt("%-18s %18s ", l->name, optbuf);
482 			if (val == RLIM_INFINITY)
483 				out1fmt("unlimited\n");
484 			else
485 			{
486 				val /= l->factor;
487 				out1fmt("%jd\n", (intmax_t)val);
488 			}
489 		}
490 		return 0;
491 	}
492 
493 	if (getrlimit(l->cmd, &limit) < 0)
494 		error("can't get limit: %s", strerror(errno));
495 	if (set) {
496 		if (how & SOFT)
497 			limit.rlim_cur = val;
498 		if (how & HARD)
499 			limit.rlim_max = val;
500 		if (setrlimit(l->cmd, &limit) < 0)
501 			error("bad limit: %s", strerror(errno));
502 	} else {
503 		if (how & SOFT)
504 			val = limit.rlim_cur;
505 		else if (how & HARD)
506 			val = limit.rlim_max;
507 
508 		if (val == RLIM_INFINITY)
509 			out1fmt("unlimited\n");
510 		else
511 		{
512 			val /= l->factor;
513 			out1fmt("%jd\n", (intmax_t)val);
514 		}
515 	}
516 	return 0;
517 }
518