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