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