miscbltin.c revision 1.57 1 /* $NetBSD: miscbltin.c,v 1.57 2025/07/03 03:54:40 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.57 2025/07/03 03:54:40 kre Exp $");
41 #endif
42 #endif /* not lint */
43
44 /*
45 * Miscellaneous builtins.
46 */
47
48 #include <sys/param.h> /* BSD4_4 */
49 #include <sys/resource.h>
50 #include <sys/stat.h>
51 #include <sys/time.h>
52 #include <sys/types.h> /* quad_t */
53
54 #include <ctype.h>
55 #include <errno.h>
56 #include <limits.h>
57 #include <stdlib.h>
58 #ifndef SMALL
59 #include <termios.h>
60 #endif
61 #include <unistd.h>
62
63 #include "shell.h"
64 #include "syntax.h"
65 #include "options.h"
66 #include "var.h"
67 #include "input.h" /* for whichprompt */
68 #include "output.h"
69 #include "parser.h" /* for getprompt() */
70 #include "memalloc.h"
71 #include "error.h"
72 #include "builtins.h"
73 #include "mystring.h"
74 #include "redir.h" /* for user_fd_limit */
75
76 /*
77 * The read builtin.
78 * Backslashes escape the next char unless -r is specified.
79 *
80 * This uses unbuffered input, which may be avoidable in some cases.
81 *
82 * Note that if IFS=' :' then read x y should work so that:
83 * 'a b' x='a', y='b'
84 * ' a b ' x='a', y='b'
85 * ':b' x='', y='b'
86 * ':' x='', y=''
87 * '::' x='', y=''
88 * ': :' x='', y=''
89 * ':::' x='', y='::'
90 * ':b c:' x='', y='b c:'
91 */
92
93 #ifndef SMALL
94 static int b_flag;
95
96 static int
97 setrawmode(int fd, int on, int end, struct termios *t)
98 {
99 struct termios n;
100
101 if (on) {
102 if (tcgetattr(fd, t) != 0)
103 return 0;
104 n = *t;
105 if (on == 1 && b_flag) {
106 n.c_cc[VEOL] = end;
107 } else {
108 cfmakeraw(&n);
109 n.c_iflag |= ICRNL;
110 n.c_oflag = t->c_oflag;
111 n.c_lflag |= ECHO | ISIG;
112 }
113 if (tcsetattr(fd, TCSADRAIN | TCSASOFT, &n) == 0)
114 return 1;
115 } else
116 (void)tcsetattr(fd, TCSADRAIN | TCSASOFT, t);
117 return 0;
118 }
119
120 static int
121 is_a_pipe(int fd)
122 {
123 if (lseek(fd, 0, SEEK_CUR) == -1 && errno == ESPIPE) {
124 errno = 0;
125 return 1;
126 }
127 return 0;
128 }
129
130 #define READ_BUFFER_SIZE 512
131
132 static int
133 next_read_char(int fd, size_t max)
134 {
135 static char buffer[READ_BUFFER_SIZE];
136 static int pos = 0, len = 0;
137
138 if (max == 0) {
139 pos = len = 0;
140 return -1;
141 }
142 if (max == (size_t)-1) {
143 /*
144 * If possible, and necessary, rewind the file
145 * so unprocessed data can be read again next time
146 *
147 * If that fails, never mind (-b allows that to happen)
148 */
149 if (b_flag && pos < len)
150 (void)lseek(fd, (off_t)(pos - len), SEEK_CUR);
151 return -1;
152 }
153
154 if (b_flag == 0) {
155 char c;
156
157 (void) max;
158 if (read(fd, &c, 1) != 1)
159 return -1;
160 return (c & 0xFF);
161 }
162
163 if (pos >= len) {
164 pos = 0;
165 if (max > sizeof buffer)
166 max = sizeof buffer;
167 len = read(fd, buffer, max);
168 if (len <= 0)
169 return -1;
170 }
171
172 return buffer[pos++] & 0xFF;
173 }
174
175 #define READ_OPTS "bd:n:p:r"
176
177 #else
178
179 static inline int
180 next_read_char(int fd, size_t max)
181 {
182 char c;
183
184 if (max == 0 || max == (size_t)-1)
185 return 0;
186
187 if (read(fd, &c, 1) != 1)
188 return -1;
189 return (c & 0xFF);
190 }
191
192 #define n_flag 0
193 #define maxlen 0
194
195 #define READ_OPTS "d:p:r"
196
197 #endif
198
199 int
200 readcmd(int argc, char **argv)
201 {
202 char **ap;
203 int c;
204 char end;
205 int r_flag;
206 char *prompt;
207 const char *ifs;
208 char *p;
209 int startword;
210 int status;
211 int i;
212 int is_ifs;
213 int saveall = 0;
214 int read_tty = 0;
215 ptrdiff_t wordlen = 0;
216 char *newifs = NULL;
217 struct stackmark mk;
218
219 #ifndef SMALL
220 struct termios ttystate;
221 int n_flag, maxlen;
222 int setraw = 0;
223
224 b_flag = 0;
225 n_flag = 0;
226 maxlen = READ_BUFFER_SIZE - 1;
227 #endif
228
229 end = '\n'; /* record delimiter */
230 r_flag = 0;
231 prompt = NULL;
232 whichprompt = 2; /* for continuation lines */
233
234 while ((i = nextopt(READ_OPTS)) != '\0') {
235 switch (i) {
236 case 'd':
237 end = *optionarg; /* even if '\0' */
238 break;
239 case 'p':
240 prompt = optionarg;
241 break;
242 case 'r':
243 r_flag = 1;
244 break;
245 #ifndef SMALL
246 case 'n':
247 maxlen = number(optionarg);
248 if (maxlen > (INT_MAX >> 8) + 1) /* sanity */
249 error("-n %s too large", optionarg);
250 n_flag = 1;
251 break;
252 case 'b':
253 if (!is_a_pipe(0))
254 b_flag = 1;
255 break;
256 #endif
257 }
258 }
259
260 if (*(ap = argptr) == NULL)
261 error("variable name required\n"
262 #ifdef SMALL
263 "Usage: read [-r] [-d C] [-p prompt] var...");
264 #else
265 "Usage: read [-br] [-d C] [-n len] [-p prompt] var...");
266
267 while (*ap != NULL) {
268 if (!validname(*ap, '\0', NULL))
269 error("'%s': invalid variable name", *ap);
270 ap++;
271 }
272 ap = argptr;
273
274 (void)next_read_char(0, 0); /* make sure the buffer is empty */
275 #endif
276
277 if (isatty(0)) {
278 read_tty = 1;
279 if (prompt) {
280 out2str(prompt);
281 flushall();
282 }
283 #ifndef SMALL
284 b_flag = 1; /* always buffer reads from ttys */
285
286 if (n_flag || end != '\n')
287 setraw = setrawmode(0, 1 + n_flag, end, &ttystate);
288 #endif
289 }
290
291 if ((ifs = bltinlookup("IFS", 1)) == NULL)
292 ifs = " \t\n";
293
294 setstackmark(&mk);
295 status = 0;
296 startword = 2;
297 STARTSTACKSTR(p);
298
299 #ifdef SMALL
300 for ( ; ; ) {
301 #else
302 for ( ; !n_flag || --maxlen >= 0 ; ) {
303 #endif
304 if ((c = next_read_char(0, maxlen + 1)) < 0) {
305 status = 1;
306 break;
307 }
308 if (c == '\\' && c != end && !r_flag) {
309 #ifndef SMALL
310 if (n_flag && --maxlen < 0)
311 break;
312 #endif
313 if ((c = next_read_char(0, maxlen + 1)) < 0) {
314 status = 1;
315 break;
316 }
317 if (c != '\n') /* \ \n is always just removed */
318 goto wdch;
319 if (read_tty)
320 out2str(getprompt(NULL));
321 continue;
322 }
323 if (c == end)
324 break;
325 if (c == '\0')
326 continue;
327 if (strchr(ifs, c))
328 is_ifs = strchr(" \t\n", c) ? 1 : 2;
329 else
330 is_ifs = 0;
331
332 if (startword != 0) {
333 if (is_ifs == 1) {
334 /* Ignore leading IFS whitespace */
335 if (saveall)
336 STPUTC(c, p);
337 continue;
338 }
339 if (is_ifs == 2 && startword == 1) {
340 /* Only one non-whitespace IFS per word */
341 startword = 2;
342 if (saveall)
343 STPUTC(c, p);
344 continue;
345 }
346 }
347
348 if (is_ifs == 0) {
349 wdch:;
350 if (c == '\0') /* always ignore attempts to input \0 */
351 continue;
352 /* append this character to the current variable */
353 startword = 0;
354 if (saveall)
355 /* Not just a spare terminator */
356 saveall++;
357 STPUTC(c, p);
358 wordlen = p - stackblock();
359 continue;
360 }
361
362 /* end of variable... */
363 startword = is_ifs;
364
365 if (ap[1] == NULL) {
366 /* Last variable needs all IFS chars */
367 saveall++;
368 STPUTC(c, p);
369 continue;
370 }
371
372 if (equal(*ap, "IFS")) {
373 /*
374 * we must not alter the value of IFS, as our
375 * local "ifs" var is (perhaps) pointing at it,
376 * at best we would be using data after free()
377 * the next time we reference ifs - but that mem
378 * may have been reused for something different.
379 *
380 * note that this might occur several times
381 */
382 STPUTC('\0', p);
383 newifs = grabstackstr(p);
384 } else {
385 STACKSTRNUL(p);
386 setvar(*ap, stackblock(), 0);
387 }
388 ap++;
389 STARTSTACKSTR(p);
390 wordlen = 0;
391 }
392 STACKSTRNUL(p);
393
394 #ifndef SMALL
395 (void)next_read_char(0, (size_t)-1); /* attempt to seek back */
396 if (setraw)
397 setrawmode(0, 0, end, &ttystate);
398 #endif
399
400
401 /* Remove trailing IFS chars */
402 for (; stackblock() + wordlen <= --p; *p = 0) {
403 if (!strchr(ifs, *p))
404 break;
405 if (strchr(" \t\n", *p))
406 /* Always remove whitespace */
407 continue;
408 if (saveall > 1)
409 /* Don't remove non-whitespace unless it was naked */
410 break;
411 }
412
413 /*
414 * If IFS was one of the variables named, we can finally set it now
415 * (no further references to ifs will be made)
416 */
417 if (newifs != NULL)
418 setvar("IFS", newifs, 0);
419
420 /*
421 * Now we can assign to the final variable (which might
422 * also be IFS, hence the ordering here)
423 */
424 setvar(*ap, stackblock(), 0);
425
426 /* Set any remaining args to "" */
427 while (*++ap != NULL)
428 setvar(*ap, nullstr, 0);
429
430 popstackmark(&mk);
431 return status;
432 }
433
434
435
436 int
437 umaskcmd(int argc, char **argv)
438 {
439 char *ap;
440 mode_t mask;
441 int i;
442 int symbolic_mode = 0;
443
444 while ((i = nextopt("S")) != '\0') {
445 symbolic_mode = 1;
446 }
447
448 INTOFF;
449 mask = umask(0);
450 umask(mask);
451 INTON;
452
453 if ((ap = *argptr) == NULL) {
454 if (symbolic_mode) {
455 char u[4], g[4], o[4];
456
457 i = 0;
458 if ((mask & S_IRUSR) == 0)
459 u[i++] = 'r';
460 if ((mask & S_IWUSR) == 0)
461 u[i++] = 'w';
462 if ((mask & S_IXUSR) == 0)
463 u[i++] = 'x';
464 u[i] = '\0';
465
466 i = 0;
467 if ((mask & S_IRGRP) == 0)
468 g[i++] = 'r';
469 if ((mask & S_IWGRP) == 0)
470 g[i++] = 'w';
471 if ((mask & S_IXGRP) == 0)
472 g[i++] = 'x';
473 g[i] = '\0';
474
475 i = 0;
476 if ((mask & S_IROTH) == 0)
477 o[i++] = 'r';
478 if ((mask & S_IWOTH) == 0)
479 o[i++] = 'w';
480 if ((mask & S_IXOTH) == 0)
481 o[i++] = 'x';
482 o[i] = '\0';
483
484 out1fmt("u=%s,g=%s,o=%s\n", u, g, o);
485 } else {
486 out1fmt("%.4o\n", mask);
487 }
488 } else {
489 if (is_digit(*ap)) {
490 int range = 0;
491
492 mask = 0;
493 do {
494 if (*ap >= '8' || *ap < '0')
495 error("Not a valid octal number: '%s'",
496 *argptr);
497 mask = (mask << 3) + (*ap - '0');
498 if (mask & ~07777)
499 range = 1;
500 } while (*++ap != '\0');
501 if (range)
502 error("Mask constant '%s' out of range", *argptr);
503 umask(mask);
504 } else {
505 void *set;
506
507 INTOFF;
508 if ((set = setmode(ap)) != 0) {
509 mask = getmode(set, ~mask & 0777);
510 ckfree(set);
511 }
512 INTON;
513 if (!set)
514 error("Cannot set mode `%s' (%s)", ap,
515 strerror(errno));
516
517 umask(~mask & 0777);
518 }
519 }
520 flushout(out1);
521 if (io_err(out1)) {
522 out2str("umask: I/O error\n");
523 return 1;
524 }
525 return 0;
526 }
527
528 /*
529 * ulimit builtin
530 *
531 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
532 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
533 * ash by J.T. Conklin.
534 *
535 * Public domain.
536 */
537
538 struct limits {
539 const char *name;
540 const char *unit;
541 char option;
542 int8_t cmd; /* all RLIMIT_xxx are <= 127 */
543 unsigned short factor; /* multiply by to get rlim_{cur,max} values */
544 };
545
546 #define OPTSTRING_BASE "HSa"
547
548 static const struct limits limits[] = {
549 #ifdef RLIMIT_CPU
550 { "time", "seconds", 't', RLIMIT_CPU, 1 },
551 #define OPTSTRING_t OPTSTRING_BASE "t"
552 #else
553 #define OPTSTRING_t OPTSTRING_BASE
554 #endif
555 #ifdef RLIMIT_FSIZE
556 { "file", "blocks", 'f', RLIMIT_FSIZE, 512 },
557 #define OPTSTRING_f OPTSTRING_t "f"
558 #else
559 #define OPTSTRING_f OPTSTRING_t
560 #endif
561 #ifdef RLIMIT_DATA
562 { "data", "kbytes", 'd', RLIMIT_DATA, 1024 },
563 #define OPTSTRING_d OPTSTRING_f "d"
564 #else
565 #define OPTSTRING_d OPTSTRING_f
566 #endif
567 #ifdef RLIMIT_STACK
568 { "stack", "kbytes", 's', RLIMIT_STACK, 1024 },
569 #define OPTSTRING_s OPTSTRING_d "s"
570 #else
571 #define OPTSTRING_s OPTSTRING_d
572 #endif
573 #ifdef RLIMIT_CORE
574 { "coredump", "blocks", 'c', RLIMIT_CORE, 512 },
575 #define OPTSTRING_c OPTSTRING_s "c"
576 #else
577 #define OPTSTRING_c OPTSTRING_s
578 #endif
579 #ifdef RLIMIT_RSS
580 { "memory", "kbytes", 'm', RLIMIT_RSS, 1024 },
581 #define OPTSTRING_m OPTSTRING_c "m"
582 #else
583 #define OPTSTRING_m OPTSTRING_c
584 #endif
585 #ifdef RLIMIT_MEMLOCK
586 { "locked memory","kbytes", 'l', RLIMIT_MEMLOCK, 1024 },
587 #define OPTSTRING_l OPTSTRING_m "l"
588 #else
589 #define OPTSTRING_l OPTSTRING_m
590 #endif
591 #ifdef RLIMIT_NTHR
592 { "thread", "threads", 'r', RLIMIT_NTHR, 1 },
593 #define OPTSTRING_r OPTSTRING_l "r"
594 #else
595 #define OPTSTRING_r OPTSTRING_l
596 #endif
597 #ifdef RLIMIT_NPROC
598 { "process", "processes", 'p', RLIMIT_NPROC, 1 },
599 #define OPTSTRING_p OPTSTRING_r "p"
600 #else
601 #define OPTSTRING_p OPTSTRING_r
602 #endif
603 #ifdef RLIMIT_NOFILE
604 { "nofiles", "descriptors", 'n', RLIMIT_NOFILE, 1 },
605 #define OPTSTRING_n OPTSTRING_p "n"
606 #else
607 #define OPTSTRING_n OPTSTRING_p
608 #endif
609 #ifdef RLIMIT_VMEM
610 { "vmemory", "kbytes", 'v', RLIMIT_VMEM, 1024 },
611 #define OPTSTRING_v OPTSTRING_n "v"
612 #else
613 #define OPTSTRING_v OPTSTRING_n
614 #endif
615 #ifdef RLIMIT_SWAP
616 { "swap", "kbytes", 'w', RLIMIT_SWAP, 1024 },
617 #define OPTSTRING_w OPTSTRING_v "w"
618 #else
619 #define OPTSTRING_w OPTSTRING_v
620 #endif
621 #ifdef RLIMIT_SBSIZE
622 { "sbsize", "bytes", 'b', RLIMIT_SBSIZE, 1 },
623 #define OPTSTRING_b OPTSTRING_w "b"
624 #else
625 #define OPTSTRING_b OPTSTRING_w
626 #endif
627 { NULL, NULL, '\0', 0, 0 }
628 };
629 #define OPTSTRING OPTSTRING_b
630
631 int
632 ulimitcmd(int argc, char **argv)
633 {
634 int c;
635 rlim_t val = 0;
636 enum { SOFT = 0x1, HARD = 0x2 }
637 how = 0, which;
638 const struct limits *l;
639 int set, all = 0;
640 int optc, what;
641 struct rlimit limit;
642
643 what = 'f';
644 while ((optc = nextopt(OPTSTRING)) != '\0')
645 switch (optc) {
646 case 'H':
647 how |= HARD;
648 break;
649 case 'S':
650 how |= SOFT;
651 break;
652 case 'a':
653 all = 1;
654 break;
655 default:
656 what = optc;
657 }
658
659 for (l = limits; l->name && l->option != what; l++)
660 ;
661 if (!l->name)
662 error("internal error (%c)", what);
663
664 set = *argptr ? 1 : 0;
665 if (set) {
666 char *p = *argptr;
667
668 if (all || argptr[1])
669 error("too many arguments");
670 if (how == 0)
671 how = HARD | SOFT;
672
673 if (strcmp(p, "unlimited") == 0)
674 val = RLIM_INFINITY;
675 else {
676 val = (rlim_t) 0;
677
678 while ((c = *p++) >= '0' && c <= '9') {
679 if (val >= RLIM_INFINITY/10)
680 error("%s: value overflow", *argptr);
681 val = (val * 10);
682 if (val >= RLIM_INFINITY - (long)(c - '0'))
683 error("%s: value overflow", *argptr);
684 val += (long)(c - '0');
685 }
686 if (c)
687 error("%s: bad number", *argptr);
688 if (val > RLIM_INFINITY / l->factor)
689 error("%s: value overflow", *argptr);
690 val *= l->factor;
691 }
692 } else if (how == 0)
693 how = SOFT;
694
695 if (all) {
696 for (l = limits; l->name; l++) {
697 getrlimit(l->cmd, &limit);
698 out1fmt("%-13s (-%c %-11s) ", l->name, l->option,
699 l->unit);
700
701 which = how;
702 while (which != 0) {
703 if (which & SOFT) {
704 val = limit.rlim_cur;
705 which &= ~SOFT;
706 } else if (which & HARD) {
707 val = limit.rlim_max;
708 which &= ~HARD;
709 }
710
711 if (val == RLIM_INFINITY)
712 out1fmt("unlimited");
713 else {
714 val /= l->factor;
715 #ifdef BSD4_4
716 out1fmt("%9lld", (long long) val);
717 #else
718 out1fmt("%9ld", (long) val);
719 #endif
720 }
721 out1fmt("%c", which ? '\t' : '\n');
722 }
723 }
724 goto done;
725 }
726
727 if (getrlimit(l->cmd, &limit) == -1)
728 error("error getting limit (%s)", strerror(errno));
729 if (set) {
730 if (how & HARD)
731 limit.rlim_max = val;
732 if (how & SOFT)
733 limit.rlim_cur = val;
734 if (setrlimit(l->cmd, &limit) < 0)
735 error("error setting limit (%s)", strerror(errno));
736 if (l->cmd == RLIMIT_NOFILE)
737 user_fd_limit = sysconf(_SC_OPEN_MAX);
738 } else {
739 if (how & SOFT)
740 val = limit.rlim_cur;
741 else if (how & HARD)
742 val = limit.rlim_max;
743
744 if (val == RLIM_INFINITY)
745 out1fmt("unlimited\n");
746 else
747 {
748 val /= l->factor;
749 #ifdef BSD4_4
750 out1fmt("%lld\n", (long long) val);
751 #else
752 out1fmt("%ld\n", (long) val);
753 #endif
754 }
755 }
756 done:;
757 flushout(out1);
758 if (io_err(out1)) {
759 out2str("ulimit: I/O error (stdout)\n");
760 return 1;
761 }
762 return 0;
763 }
764