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