1 /* $NetBSD: redir.c,v 1.76 2024/11/11 22:57:42 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[] = "@(#)redir.c 8.2 (Berkeley) 5/4/95"; 39 #else 40 __RCSID("$NetBSD: redir.c,v 1.76 2024/11/11 22:57:42 kre Exp $"); 41 #endif 42 #endif /* not lint */ 43 44 #include <sys/types.h> 45 #include <sys/param.h> /* PIPE_BUF */ 46 #include <sys/stat.h> 47 #include <signal.h> 48 #include <string.h> 49 #include <fcntl.h> 50 #include <errno.h> 51 #include <unistd.h> 52 #include <stdlib.h> 53 54 /* 55 * Code for dealing with input/output redirection. 56 */ 57 58 #include "main.h" 59 #include "builtins.h" 60 #include "shell.h" 61 #include "nodes.h" 62 #include "jobs.h" 63 #include "options.h" 64 #include "expand.h" 65 #include "redir.h" 66 #include "output.h" 67 #include "memalloc.h" 68 #include "mystring.h" 69 #include "error.h" 70 #include "show.h" 71 72 73 #define CLOSED -1 /* fd was not open before redir */ 74 75 #ifndef PIPE_BUF 76 # define PIPESIZE 4096 /* amount of buffering in a pipe */ 77 #else 78 # define PIPESIZE PIPE_BUF 79 #endif 80 81 #ifndef FD_CLOEXEC 82 # define FD_CLOEXEC 1 /* well known from before there was a name */ 83 #endif 84 85 #ifndef F_DUPFD_CLOEXEC 86 #define F_DUPFD_CLOEXEC F_DUPFD 87 #define CLOEXEC(fd) (fcntl((fd), F_SETFD, \ 88 (fcntl_int)(fcntl((fd), F_GETFD) | FD_CLOEXEC))) 89 #else 90 #define CLOEXEC(fd) __nothing 91 #endif 92 93 /* yes, this is correct, bizarre parens and all -- used only as a cast */ 94 #define fcntl_int void *)(intptr_t 95 #undef fcntl_int 96 #define fcntl_int int 97 98 99 MKINIT 100 struct renamelist { 101 struct renamelist *next; 102 int orig; 103 int into; 104 int cloexec; /* orig had FD_CLOEXEC set (into always does) */ 105 }; 106 107 MKINIT 108 struct redirtab { 109 struct redirtab *next; 110 struct renamelist *renamed; 111 }; 112 113 114 MKINIT struct redirtab *redirlist; 115 116 /* 117 * We keep track of whether or not fd0 has been redirected. This is for 118 * background commands, where we want to redirect fd0 to /dev/null only 119 * if it hasn't already been redirected. 120 */ 121 STATIC int fd0_redirected = 0; 122 123 /* 124 * And also where to put internal use fds that should be out of the 125 * way of user defined fds (normally) 126 */ 127 STATIC int big_sh_fd = 0; 128 STATIC int biggest_sh_fd = 2; 129 130 STATIC const struct renamelist *is_renamed(const struct renamelist *, int); 131 STATIC void fd_rename(struct redirtab *, int, int, int); 132 STATIC int * saved_redirected_fd(int); 133 STATIC void free_rl(struct redirtab *, int); 134 STATIC void openredirect(union node *, char[10], int); 135 STATIC int openhere(const union node *); 136 STATIC int copyfd(int, int, int, int); 137 STATIC void find_big_fd(void); 138 139 140 struct shell_fds { /* keep track of internal shell fds */ 141 struct shell_fds *nxt; 142 void (*cb)(int, int); 143 int fd; 144 }; 145 146 STATIC struct shell_fds *sh_fd_list; 147 148 STATIC int pick_new_fd(int); 149 STATIC void renumber_sh_fd(struct shell_fds *); 150 STATIC struct shell_fds *sh_fd(int); 151 152 STATIC const struct renamelist * 153 is_renamed(const struct renamelist *rl, int fd) 154 { 155 while (rl != NULL) { 156 if (rl->orig == fd) 157 return rl; 158 rl = rl->next; 159 } 160 return NULL; 161 } 162 163 STATIC int * 164 saved_redirected_fd(int fd) 165 { 166 struct redirtab *rt; 167 struct renamelist *rl; 168 169 for (rt = redirlist; rt != NULL; rt = rt->next) { 170 for (rl = rt->renamed; rl != NULL; rl = rl->next) { 171 if (rl->into == fd) 172 return &rl->into; 173 } 174 } 175 return NULL; 176 } 177 178 STATIC void 179 free_rl(struct redirtab *rt, int reset) 180 { 181 struct renamelist *rl, *rn = rt->renamed; 182 183 while ((rl = rn) != NULL) { 184 rn = rl->next; 185 186 if (rl->orig == 0) 187 fd0_redirected--; 188 189 VTRACE(DBG_REDIR, ("popredir %d%s: %s", 190 rl->orig, rl->orig==0 ? " (STDIN)" : "", 191 reset == POPREDIR_UNDO ? "" : 192 reset == POPREDIR_PERMANENT ? "make permanent" : 193 "no reset\n")); 194 195 switch (reset) { 196 case POPREDIR_UNDO: 197 if (rl->into < 0) { 198 VTRACE(DBG_REDIR, (" closed\n")); 199 close(rl->orig); 200 } else { 201 VTRACE(DBG_REDIR, 202 (" from %d%s\n", rl->into, 203 rl->cloexec ? " (colexec)" : "")); 204 copyfd(rl->into, rl->orig, rl->cloexec, 1); 205 } 206 break; 207 208 case POPREDIR_PERMANENT: 209 if (rl->into < 0) { 210 VTRACE(DBG_REDIR, (" was closed\n")); 211 /* nothing to do */ 212 } else { 213 VTRACE(DBG_REDIR, 214 (" close savefd %d\n", rl->into)); 215 close(rl->into); 216 } 217 break; 218 219 default: 220 /* nothing to do */ 221 break; 222 } 223 ckfree(rl); 224 } 225 rt->renamed = NULL; 226 } 227 228 STATIC void 229 fd_rename(struct redirtab *rt, int from, int to, int cloexec) 230 { 231 /* XXX someday keep a short list (8..10) of freed renamelists XXX */ 232 struct renamelist *rl = ckmalloc(sizeof(struct renamelist)); 233 234 /* 235 * Note this list is operated as LIFO so saved fd's are 236 * undone in the opposite order to that they were saved 237 * (needed to ensure correct results) 238 */ 239 rl->next = rt->renamed; 240 rt->renamed = rl; 241 242 rl->orig = from; 243 rl->into = to; 244 rl->cloexec = cloexec; 245 } 246 247 /* 248 * Process a list of redirection commands. If the REDIR_PUSH flag is set, 249 * old file descriptors are stashed away so that the redirection can be 250 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the 251 * standard output, and the standard error if it becomes a duplicate of 252 * stdout, is saved in memory. 253 */ 254 255 void 256 redirect(union node *redir, int flags) 257 { 258 union node *n; 259 struct redirtab *sv = NULL; 260 int i; 261 int fd; 262 char memory[10]; /* file descriptors to write to memory */ 263 264 CTRACE(DBG_REDIR, ("redirect(F=0x%x):%s\n", flags, redir?"":" NONE")); 265 266 for (i = 10 ; --i >= 0 ; ) 267 memory[i] = 0; 268 memory[1] = flags & REDIR_BACKQ; 269 if (flags & REDIR_PUSH) { 270 /* 271 * We don't have to worry about REDIR_VFORK here, as 272 * flags & REDIR_PUSH is never true if REDIR_VFORK is set. 273 */ 274 sv = ckmalloc(sizeof (struct redirtab)); 275 sv->renamed = NULL; 276 sv->next = redirlist; 277 redirlist = sv; 278 } 279 for (n = redir ; n ; n = n->nfile.next) { 280 int *renamed; 281 282 fd = n->nfile.fd; 283 VTRACE(DBG_REDIR, ("redir %d (max=%d limit=%ld) ", 284 fd, max_user_fd, user_fd_limit)); 285 if (fd < user_fd_limit && fd > max_user_fd) 286 max_user_fd = fd; 287 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) && 288 n->ndup.dupfd == fd) { 289 VTRACE(DBG_REDIR, ("!cloexec\n")); 290 if (sh_fd(fd) != NULL || 291 saved_redirected_fd(fd) != NULL) 292 error("fd %d: %s", fd, strerror(EBADF)); 293 /* redirect from/to same file descriptor */ 294 /* make sure it stays open */ 295 if (fcntl(fd, F_SETFD, (fcntl_int)0) < 0) 296 error("fd %d: %s", fd, strerror(errno)); 297 continue; 298 } 299 if ((renamed = saved_redirected_fd(fd)) != NULL) { 300 int to = pick_new_fd(fd); 301 302 VTRACE(DBG_REDIR, 303 ("redirect: moved holding fd %d to %d\n", fd, to)); 304 *renamed = to; 305 if (to != fd) /* always... */ 306 (void)close(fd); 307 } 308 renumber_sh_fd(sh_fd(fd)); 309 310 if ((flags & REDIR_PUSH) && !is_renamed(sv->renamed, fd)) { 311 int bigfd; 312 int cloexec; 313 314 cloexec = fcntl(fd, F_GETFD); 315 if (cloexec >= 0) 316 cloexec &= FD_CLOEXEC; 317 else 318 cloexec = 0; 319 320 INTOFF; 321 if (big_sh_fd < 10) 322 find_big_fd(); 323 if ((bigfd = big_sh_fd) < max_user_fd) 324 bigfd = max_user_fd; 325 if ((i = fcntl(fd, F_DUPFD, 326 (fcntl_int)(bigfd + 1))) == -1) { 327 switch (errno) { 328 case EBADF: 329 i = CLOSED; 330 break; 331 case EMFILE: 332 case EINVAL: 333 find_big_fd(); 334 i = fcntl(fd, F_DUPFD, 335 (fcntl_int) big_sh_fd); 336 if (i >= 0) 337 break; 338 if (errno == EMFILE || errno == EINVAL) 339 i = fcntl(fd, F_DUPFD, 340 (fcntl_int) 3); 341 if (i >= 0) 342 break; 343 /* FALLTHRU */ 344 default: 345 error("%d: %s", fd, strerror(errno)); 346 /* NOTREACHED */ 347 } 348 } 349 if (i > biggest_sh_fd) 350 biggest_sh_fd = i; 351 if (i >= 0) 352 (void)fcntl(i, F_SETFD, (fcntl_int) FD_CLOEXEC); 353 fd_rename(sv, fd, i, cloexec); 354 VTRACE(DBG_REDIR, ("fd %d saved as %d%s ", fd, i, 355 cloexec ? "+" : "")); 356 INTON; 357 } 358 VTRACE(DBG_REDIR, ("%s\n", fd == 0 ? "STDIN" : "")); 359 if (fd == 0) 360 fd0_redirected++; 361 openredirect(n, memory, flags); 362 } 363 if (memory[1]) 364 out1 = &memout; 365 if (memory[2]) 366 out2 = &memout; 367 } 368 369 370 STATIC void 371 openredirect(union node *redir, char memory[10], int flags) 372 { 373 struct stat sb; 374 int fd = redir->nfile.fd; 375 char *fname; 376 int f; 377 int eflags, cloexec; 378 379 /* 380 * We suppress interrupts so that we won't leave open file 381 * descriptors around. This may not be such a good idea because 382 * an open of a device or a fifo can block indefinitely. 383 */ 384 INTOFF; 385 if (fd < 10) 386 memory[fd] = 0; 387 switch (redir->nfile.type) { 388 case NFROM: 389 fname = redir->nfile.expfname; 390 if (flags & REDIR_VFORK) 391 eflags = O_NONBLOCK; 392 else 393 eflags = 0; 394 if ((f = open(fname, O_RDONLY|eflags)) < 0) 395 goto eopen; 396 VTRACE(DBG_REDIR, ("openredirect(< '%s') -> %d [%#x]", 397 fname, f, eflags)); 398 if (eflags) 399 (void)fcntl(f, F_SETFL, 400 (fcntl_int)(fcntl(f, F_GETFL) & ~eflags)); 401 break; 402 case NFROMTO: 403 fname = redir->nfile.expfname; 404 if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0) 405 goto ecreate; 406 VTRACE(DBG_REDIR, ("openredirect(<> '%s') -> %d", fname, f)); 407 break; 408 case NTO: 409 if (Cflag) { 410 fname = redir->nfile.expfname; 411 if ((f = open(fname, O_WRONLY)) == -1) { 412 if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 413 0666)) < 0) 414 goto ecreate; 415 } else if (fstat(f, &sb) == -1) { 416 int serrno = errno; 417 close(f); 418 errno = serrno; 419 goto ecreate; 420 } else if (S_ISREG(sb.st_mode)) { 421 close(f); 422 errno = EEXIST; 423 goto ecreate; 424 } 425 VTRACE(DBG_REDIR, ("openredirect(>| '%s') -> %d", 426 fname, f)); 427 break; 428 } 429 /* FALLTHROUGH */ 430 case NCLOBBER: 431 fname = redir->nfile.expfname; 432 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0) 433 goto ecreate; 434 VTRACE(DBG_REDIR, ("openredirect(> '%s') -> %d", fname, f)); 435 break; 436 case NAPPEND: 437 fname = redir->nfile.expfname; 438 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0) 439 goto ecreate; 440 VTRACE(DBG_REDIR, ("openredirect(>> '%s') -> %d", fname, f)); 441 break; 442 case NTOFD: 443 case NFROMFD: 444 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */ 445 if (sh_fd(redir->ndup.dupfd) != NULL || 446 saved_redirected_fd(redir->ndup.dupfd) != NULL) 447 error("Redirect (from %d to %d) failed: %s", 448 redir->ndup.dupfd, fd, strerror(EBADF)); 449 if (fd < 10 && redir->ndup.dupfd < 10 && 450 memory[redir->ndup.dupfd]) 451 memory[fd] = 1; 452 else if (copyfd(redir->ndup.dupfd, fd, 453 (flags & REDIR_KEEP) == 0, 0) < 0) 454 error("Redirect (from %d to %d) failed: %s", 455 redir->ndup.dupfd, fd, strerror(errno)); 456 VTRACE(DBG_REDIR, ("openredirect: %d%c&%d\n", fd, 457 "<>"[redir->nfile.type==NTOFD], redir->ndup.dupfd)); 458 } else { 459 (void) close(fd); 460 VTRACE(DBG_REDIR, ("openredirect: %d%c&-\n", fd, 461 "<>"[redir->nfile.type==NTOFD])); 462 } 463 INTON; 464 return; 465 case NHERE: 466 case NXHERE: 467 VTRACE(DBG_REDIR, ("openredirect: %d<<...", fd)); 468 f = openhere(redir); 469 break; 470 default: 471 abort(); 472 } 473 474 if (f > biggest_sh_fd) 475 biggest_sh_fd = f; 476 477 cloexec = fd > 2 && (flags & REDIR_KEEP) == 0 && !posix; 478 if (f != fd) { 479 VTRACE(DBG_REDIR, (" -> %d", fd)); 480 if (copyfd(f, fd, cloexec, 1) < 0) { 481 int e = errno; 482 483 VTRACE(DBG_REDIR, (" failed: %s\n", strerror(e))); 484 error("redirect reassignment (fd %d) failed: %s", fd, 485 strerror(e)); 486 } 487 } else if (cloexec) 488 (void)fcntl(f, F_SETFD, (fcntl_int) FD_CLOEXEC); 489 VTRACE(DBG_REDIR, ("%s\n", cloexec ? " cloexec" : "")); 490 491 INTON; 492 return; 493 ecreate: 494 exerrno = 1; 495 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT)); 496 eopen: 497 exerrno = 1; 498 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN)); 499 } 500 501 502 /* 503 * Handle here documents. Normally we fork off a process to write the 504 * data to a pipe. If the document is short, we can stuff the data in 505 * the pipe without forking. 506 */ 507 508 STATIC int 509 openhere(const union node *redir) 510 { 511 int pip[2]; 512 int len = 0; 513 514 if (pipe(pip) < 0) 515 error("Pipe call failed"); 516 if (pip[1] > biggest_sh_fd) 517 biggest_sh_fd = pip[1]; 518 len = strlen(redir->nhere.text); 519 VTRACE(DBG_REDIR, ("openhere(%p) [%d] \"%.*s\"%s\n", redir, len, 520 (len < 40 ? len : 40), redir->nhere.text, (len < 40 ? "" : "..."))); 521 if (len <= PIPESIZE) { /* XXX eventually copy FreeBSD method */ 522 xwrite(pip[1], redir->nhere.text, len); 523 goto out; 524 } 525 VTRACE(DBG_REDIR, (" forking [%d,%d]\n", pip[0], pip[1])); 526 if (forkshell(NULL, NULL, FORK_NOJOB) == 0) { 527 close(pip[0]); 528 signal(SIGINT, SIG_IGN); 529 signal(SIGQUIT, SIG_IGN); 530 signal(SIGHUP, SIG_IGN); 531 #ifdef SIGTSTP 532 signal(SIGTSTP, SIG_IGN); 533 #endif 534 signal(SIGPIPE, SIG_DFL); 535 xwrite(pip[1], redir->nhere.text, len); 536 VTRACE(DBG_PROCS|DBG_REDIR, ("wrote here doc. exiting(0)\n")); 537 _exit(0); 538 } 539 VTRACE(DBG_REDIR, ("openhere (closing %d)", pip[1])); 540 out:; 541 close(pip[1]); 542 VTRACE(DBG_REDIR, (" (pipe fd=%d)", pip[0])); 543 return pip[0]; 544 } 545 546 547 548 /* 549 * if (reset == POPREDIR_UNDO) 550 * Undo the effects of the last redirection. 551 * else if (reset == POPREDIR_PERMANENT) 552 * Make the last redirection permanent 553 * else / * reset == POPREDIR_DISCARD * / 554 * Just throw away the redirection 555 */ 556 557 void 558 popredir(int reset) 559 { 560 struct redirtab *rp = redirlist; 561 562 INTOFF; 563 free_rl(rp, reset); 564 redirlist = rp->next; 565 ckfree(rp); 566 INTON; 567 } 568 569 /* 570 * Undo all redirections. Called on error or interrupt. 571 */ 572 573 #ifdef mkinit 574 575 INCLUDE "redir.h" 576 577 RESET { 578 while (redirlist) 579 popredir(POPREDIR_UNDO); 580 } 581 582 SHELLPROC { 583 clearredir(0); 584 } 585 586 #endif 587 588 /* Return true if fd 0 has already been redirected at least once. */ 589 int 590 fd0_redirected_p(void) 591 { 592 return fd0_redirected != 0; 593 } 594 595 /* 596 * Discard all saved file descriptors. 597 */ 598 599 void 600 clearredir(int vforked) 601 { 602 struct redirtab *rp; 603 struct renamelist *rl; 604 605 /* 606 * This happens only in a child process attempting to 607 * exec a script which failed ENOEXEC. Any redirections 608 * that have been made are for that script, after it 609 * is done, we exit, there is nothing to restore, so 610 * just make the refirectoins permanent. 611 * 612 * free_rl() does that does that for us, unless we're 613 * a child of a vfork() in which case that is unsafe to 614 * call - that should never happen, but just in case, fale 615 * it here 616 */ 617 618 for (rp = redirlist ; rp ; rp = rp->next) { 619 if (!vforked) 620 free_rl(rp, POPREDIR_PERMANENT); 621 else for (rl = rp->renamed; rl; rl = rl->next) 622 if (rl->into >= 0) 623 close(rl->into); 624 } 625 } 626 627 628 629 /* 630 * Copy a file descriptor (from) to (also) be 'to'.. 631 * cloexec indicates if we want close-on-exec or not. 632 * move indicates if "from" should be closed on success (yes if set). 633 * Returns -1 if any error occurs. 634 */ 635 636 STATIC int 637 copyfd(int from, int to, int cloexec, int move) 638 { 639 int newfd; 640 641 if (cloexec && to > 2) { 642 #ifdef O_CLOEXEC 643 newfd = dup3(from, to, O_CLOEXEC); 644 #else 645 newfd = dup2(from, to); 646 if (newfd >= 0) 647 fcntl(newfd, F_SETFD, 648 (fcntl_int)(fcntl(newfd, F_GETFD) | FD_CLOEXEC)); 649 #endif 650 } else 651 newfd = dup2(from, to); 652 653 if (move && newfd == to && from != to) 654 close(from); 655 656 if (newfd != to) { 657 if (newfd < 0) 658 error("Unable to dup(%d->%d): %s", from, to, 659 strerror(errno)); 660 else { 661 close(newfd); 662 error("Moving fd %d to %d made %d!", from, to, newfd); 663 } 664 } 665 666 if (newfd > biggest_sh_fd) 667 biggest_sh_fd = newfd; 668 669 return newfd; 670 } 671 672 /* 673 * rename fd from to be fd to (closing from). 674 * close-on-exec is never set on 'to' (unless 675 * from==to and it was set on from) - ie: a no-op 676 * returns to (or errors() if an error occurs). 677 * 678 * This is mostly used for rearranging the 679 * results from pipe(). 680 */ 681 int 682 movefd(int from, int to) 683 { 684 if (from > biggest_sh_fd) 685 biggest_sh_fd = from; 686 if (to > biggest_sh_fd) 687 biggest_sh_fd = to; 688 689 if (from == to) 690 return to; 691 692 (void)close(to); 693 if (copyfd(from, to, 0, 1) != to) { 694 int e = errno; 695 696 (void) close(from); 697 error("Unable to make fd %d: %s", to, strerror(e)); 698 } 699 700 return to; 701 } 702 703 STATIC void 704 find_big_fd(void) 705 { 706 int i, fd; 707 static int last_start = 3; /* aim to keep sh fd's under 20 */ 708 709 if (last_start < 10) 710 last_start++; 711 712 for (i = (1 << last_start); i >= 10; i >>= 1) { 713 if ((fd = fcntl(0, F_DUPFD, (fcntl_int)(i - 1))) >= 0) { 714 if (fd > biggest_sh_fd) 715 biggest_sh_fd = fd; 716 close(fd); 717 break; 718 } 719 } 720 721 fd = (i / 5) * 4; 722 if (fd < 10) 723 fd = 10; 724 725 big_sh_fd = fd; 726 } 727 728 /* 729 * If possible, move file descriptor fd out of the way 730 * of expected user fd values. Returns the new fd 731 * (which may be the input fd if things do not go well.) 732 * Always set close-on-exec on the result, and close 733 * the input fd unless it is to be our result. 734 */ 735 int 736 to_upper_fd(int fd) 737 { 738 int i; 739 740 VTRACE(DBG_REDIR|DBG_OUTPUT, ("to_upper_fd(%d)", fd)); 741 if (big_sh_fd < 10 || big_sh_fd >= user_fd_limit) 742 find_big_fd(); 743 do { 744 i = fcntl(fd, F_DUPFD_CLOEXEC, (fcntl_int) big_sh_fd); 745 if (i >= 0) { 746 if (i > biggest_sh_fd) 747 biggest_sh_fd = i; 748 if (fd != i) 749 close(fd); 750 VTRACE(DBG_REDIR|DBG_OUTPUT, ("-> %d\n", i)); 751 return i; 752 } 753 if (errno != EMFILE && errno != EINVAL) 754 break; 755 find_big_fd(); 756 } while (big_sh_fd > 10); 757 758 /* 759 * If we wanted to move this fd to some random high number 760 * we certainly do not intend to pass it through exec, even 761 * if the reassignment failed. 762 */ 763 (void)fcntl(fd, F_SETFD, (fcntl_int) FD_CLOEXEC); 764 VTRACE(DBG_REDIR|DBG_OUTPUT, (" fails ->%d\n", fd)); 765 return fd; 766 } 767 768 void 769 register_sh_fd(int fd, void (*cb)(int, int)) 770 { 771 struct shell_fds *fp; 772 773 fp = ckmalloc(sizeof (struct shell_fds)); 774 if (fp != NULL) { 775 fp->nxt = sh_fd_list; 776 sh_fd_list = fp; 777 778 fp->fd = fd; 779 fp->cb = cb; 780 } 781 } 782 783 void 784 sh_close(int fd) 785 { 786 struct shell_fds **fpp, *fp; 787 788 fpp = &sh_fd_list; 789 while ((fp = *fpp) != NULL) { 790 if (fp->fd == fd) { 791 *fpp = fp->nxt; 792 ckfree(fp); 793 break; 794 } 795 fpp = &fp->nxt; 796 } 797 (void)close(fd); 798 } 799 800 STATIC struct shell_fds * 801 sh_fd(int fd) 802 { 803 struct shell_fds *fp; 804 805 for (fp = sh_fd_list; fp != NULL; fp = fp->nxt) 806 if (fp->fd == fd) 807 return fp; 808 return NULL; 809 } 810 811 STATIC int 812 pick_new_fd(int fd) 813 { 814 int to; 815 816 to = fcntl(fd, F_DUPFD_CLOEXEC, (fcntl_int) big_sh_fd); 817 if (to == -1 && big_sh_fd >= 22) 818 to = fcntl(fd, F_DUPFD_CLOEXEC, (fcntl_int) (big_sh_fd / 2)); 819 if (to == -1) 820 to = fcntl(fd, F_DUPFD_CLOEXEC, (fcntl_int) (fd + 1)); 821 if (to == -1) 822 to = fcntl(fd, F_DUPFD_CLOEXEC, (fcntl_int) 10); 823 if (to == -1) 824 to = fcntl(fd, F_DUPFD_CLOEXEC, (fcntl_int) 3); 825 if (to == -1) 826 error("insufficient file descriptors available"); 827 CLOEXEC(to); 828 if (to > biggest_sh_fd) 829 biggest_sh_fd = to; 830 return to; 831 } 832 833 STATIC void 834 renumber_sh_fd(struct shell_fds *fp) 835 { 836 int to; 837 838 if (fp == NULL) 839 return; 840 841 /* 842 * if we have had a collision, and the sh fd was a "big" one 843 * try moving the sh fd base to a higher number (if possible) 844 * so future sh fds are less likely to be in the user's sights 845 * (incl this one when moved) 846 */ 847 if (fp->fd >= big_sh_fd) 848 find_big_fd(); 849 850 to = pick_new_fd(fp->fd); 851 852 if (fp->fd == to) /* impossible? */ 853 return; 854 855 VTRACE(DBG_REDIR, ("renumber_sh_fd: moved shell fd %d to %d\n", 856 fp->fd, to)); 857 858 (*fp->cb)(fp->fd, to); 859 (void)close(fp->fd); 860 fp->fd = to; 861 } 862 863 static const struct flgnames { 864 const char *name; 865 uint16_t minch; 866 uint32_t value; 867 } nv[] = { 868 #ifdef O_APPEND 869 { "append", 2, O_APPEND }, 870 #else 871 # define O_APPEND 0 872 #endif 873 #ifdef O_ASYNC 874 { "async", 2, O_ASYNC }, 875 #else 876 # define O_ASYNC 0 877 #endif 878 #ifdef O_SYNC 879 { "sync", 2, O_SYNC }, 880 #else 881 # define O_SYNC 0 882 #endif 883 #ifdef O_NONBLOCK 884 { "nonblock", 3, O_NONBLOCK }, 885 #else 886 # define O_NONBLOCK 0 887 #endif 888 #ifdef O_FSYNC 889 { "fsync", 2, O_FSYNC }, 890 #else 891 # define O_FSYNC 0 892 #endif 893 #ifdef O_DSYNC 894 { "dsync", 2, O_DSYNC }, 895 #else 896 # define O_DSYNC 0 897 #endif 898 #ifdef O_RSYNC 899 { "rsync", 2, O_RSYNC }, 900 #else 901 # define O_RSYNC 0 902 #endif 903 #ifdef O_ALT_IO 904 { "altio", 2, O_ALT_IO }, 905 #else 906 # define O_ALT_IO 0 907 #endif 908 #ifdef O_DIRECT 909 { "direct", 2, O_DIRECT }, 910 #else 911 # define O_DIRECT 0 912 #endif 913 #ifdef O_NOSIGPIPE 914 { "nosigpipe", 3, O_NOSIGPIPE }, 915 #else 916 # define O_NOSIGPIPE 0 917 #endif 918 919 #define ALLFLAGS (O_APPEND|O_ASYNC|O_SYNC|O_NONBLOCK|O_DSYNC|O_RSYNC|\ 920 O_ALT_IO|O_DIRECT|O_NOSIGPIPE) 921 922 #ifndef O_CLOEXEC 923 # define O_CLOEXEC ((~ALLFLAGS) ^ ((~ALLFLAGS) & ((~ALLFLAGS) - 1))) 924 #endif 925 926 /* for any system we support, close on exec is always defined */ 927 { "cloexec", 2, O_CLOEXEC }, 928 { 0, 0, 0 } 929 }; 930 931 #ifndef O_ACCMODE 932 # define O_ACCMODE 0 933 #endif 934 #ifndef O_RDONLY 935 # define O_RDONLY 0 936 #endif 937 #ifndef O_WRONLY 938 # define O_WRONLY 0 939 #endif 940 #ifndef O_RWDR 941 # define O_RWDR 0 942 #endif 943 #ifndef O_SHLOCK 944 # define O_SHLOCK 0 945 #endif 946 #ifndef O_EXLOCK 947 # define O_EXLOCK 0 948 #endif 949 #ifndef O_NOFOLLOW 950 # define O_NOFOLLOW 0 951 #endif 952 #ifndef O_CREAT 953 # define O_CREAT 0 954 #endif 955 #ifndef O_TRUNC 956 # define O_TRUNC 0 957 #endif 958 #ifndef O_EXCL 959 # define O_EXCL 0 960 #endif 961 #ifndef O_NOCTTY 962 # define O_NOCTTY 0 963 #endif 964 #ifndef O_DIRECTORY 965 # define O_DIRECTORY 0 966 #endif 967 #ifndef O_REGULAR 968 # define O_REGULAR 0 969 #endif 970 /* 971 * flags that F_GETFL might return that we want to ignore 972 * 973 * F_GETFL should not actually return these, they're all just open() 974 * modifiers, rather than state, but just in case... 975 */ 976 #define IGNFLAGS (O_ACCMODE|O_RDONLY|O_WRONLY|O_RDWR|O_SHLOCK|O_EXLOCK| \ 977 O_NOFOLLOW|O_CREAT|O_TRUNC|O_EXCL|O_NOCTTY|O_DIRECTORY|O_REGULAR) 978 979 static int 980 getflags(int fd, int p, int all) 981 { 982 int c, f; 983 984 if (!all && (sh_fd(fd) != NULL || saved_redirected_fd(fd) != NULL)) { 985 if (!p) 986 return -1; 987 error("Can't get status for fd=%d (%s)", fd, strerror(EBADF)); 988 } 989 990 if ((c = fcntl(fd, F_GETFD)) == -1) { 991 if (!p) 992 return -1; 993 error("Can't get status for fd=%d (%s)", fd, strerror(errno)); 994 } 995 if ((f = fcntl(fd, F_GETFL)) == -1) { 996 if (!p) 997 return -1; 998 error("Can't get flags for fd=%d (%s)", fd, strerror(errno)); 999 } 1000 f &= ~IGNFLAGS; /* clear anything we know about, but ignore */ 1001 if (c & FD_CLOEXEC) 1002 f |= O_CLOEXEC; 1003 return f; 1004 } 1005 1006 static void 1007 printone(int fd, int p, int verbose, int pfd) 1008 { 1009 int f = getflags(fd, p, verbose > 1); 1010 const struct flgnames *fn; 1011 1012 if (f == -1) 1013 return; 1014 1015 if (pfd) 1016 outfmt(out1, "%d: ", fd); 1017 for (fn = nv; fn->name; fn++) { 1018 if (f & fn->value) { 1019 outfmt(out1, "%s%s", verbose ? "+" : "", fn->name); 1020 f &= ~fn->value; 1021 } else if (verbose) 1022 outfmt(out1, "-%s", fn->name); 1023 else 1024 continue; 1025 if (f || (verbose && fn[1].name)) 1026 outfmt(out1, ","); 1027 } 1028 if (verbose && f) /* f should be normally be 0 */ 1029 outfmt(out1, " +%#x", f); 1030 outfmt(out1, "\n"); 1031 } 1032 1033 static void 1034 parseflags(char *s, int *p, int *n) 1035 { 1036 int *v, *w; 1037 const struct flgnames *fn; 1038 size_t len; 1039 1040 *p = 0; 1041 *n = 0; 1042 for (s = strtok(s, ","); s; s = strtok(NULL, ",")) { 1043 switch (*s++) { 1044 case '+': 1045 v = p; 1046 w = n; 1047 break; 1048 case '-': 1049 v = n; 1050 w = p; 1051 break; 1052 default: 1053 error("Missing +/- indicator before flag %s", s-1); 1054 } 1055 1056 len = strlen(s); 1057 for (fn = nv; fn->name; fn++) 1058 if (len >= fn->minch && strncmp(s,fn->name,len) == 0) { 1059 *v |= fn->value; 1060 *w &=~ fn->value; 1061 break; 1062 } 1063 if (fn->name == 0) 1064 error("Bad flag `%s'", s); 1065 } 1066 } 1067 1068 static void 1069 setone(int fd, int pos, int neg, int verbose) 1070 { 1071 int f = getflags(fd, 1, 0); 1072 int n, cloexec; 1073 1074 if (f == -1) 1075 return; 1076 1077 cloexec = -1; 1078 if ((pos & O_CLOEXEC) && !(f & O_CLOEXEC)) 1079 cloexec = FD_CLOEXEC; 1080 if ((neg & O_CLOEXEC) && (f & O_CLOEXEC)) 1081 cloexec = 0; 1082 1083 /* Don't allow O_CLOEXEC on stdin, stdout, or stderr */ 1084 if ((cloexec > 0 && fd <= 2 && (errno = EINVAL)) || 1085 (cloexec != -1 && fcntl(fd, F_SETFD, (fcntl_int) cloexec) == -1)) 1086 error("Can't set status for fd=%d (%s)", fd, strerror(errno)); 1087 1088 pos &= ~O_CLOEXEC; 1089 neg &= ~O_CLOEXEC; 1090 f &= ~O_CLOEXEC; 1091 n = f; 1092 n |= pos; 1093 n &= ~neg; 1094 if (n != f && fcntl(fd, F_SETFL, (fcntl_int)n) == -1) 1095 error("Can't set flags for fd=%d (%s)", fd, strerror(errno)); 1096 if (verbose) 1097 printone(fd, 1, verbose, 1); 1098 } 1099 1100 int 1101 fdflagscmd(int argc, char *argv[]) 1102 { 1103 char *num; 1104 int verbose = 0, ch, pos = 0, neg = 0; 1105 char *setflags = NULL; 1106 1107 optreset = 1; optind = 1; /* initialize getopt */ 1108 while ((ch = getopt(argc, argv, ":vs:" 1109 #ifdef DEBUG 1110 "V" 1111 #endif 1112 )) != -1) 1113 switch ((char)ch) { 1114 #ifdef DEBUG 1115 case 'V': 1116 verbose = 2; 1117 break; 1118 #endif 1119 case 'v': 1120 verbose = 1; 1121 break; 1122 case 's': 1123 if (setflags) 1124 goto msg; 1125 setflags = optarg; 1126 break; 1127 case '?': 1128 default: 1129 msg: 1130 error("Usage: fdflags [-v] [-s <flags> fd] [fd...]"); 1131 /* NOTREACHED */ 1132 } 1133 1134 argc -= optind, argv += optind; 1135 1136 if (setflags) 1137 parseflags(setflags, &pos, &neg); 1138 1139 if (argc == 0) { 1140 int i; 1141 1142 if (setflags) 1143 goto msg; 1144 1145 for (i = 0; i <= max_user_fd; i++) 1146 printone(i, 0, verbose, 1); 1147 if (verbose > 1) 1148 while (i <= biggest_sh_fd) 1149 printone(i++, 0, verbose, 1); 1150 1151 } else while ((num = *argv++) != NULL) { 1152 int fd = number(num); 1153 1154 while (num[0] == '0' && num[1] != '\0') /* skip 0's */ 1155 num++; 1156 if (strlen(num) > 5 || 1157 (fd >= user_fd_limit && fd > max_user_fd)) 1158 error("%s: too big to be a file descriptor", num); 1159 1160 if (setflags) 1161 setone(fd, pos, neg, verbose); 1162 else 1163 printone(fd, 1, verbose, argc > 1); 1164 } 1165 flushout(out1); 1166 if (io_err(out1)) { 1167 out2str("fdflags: I/O error\n"); 1168 return 1; 1169 } 1170 return 0; 1171 } 1172 1173 #undef MAX /* in case we inherited them from somewhere */ 1174 #undef MIN 1175 1176 #define MIN(a,b) (/*CONSTCOND*/((a)<=(b)) ? (a) : (b)) 1177 #define MAX(a,b) (/*CONSTCOND*/((a)>=(b)) ? (a) : (b)) 1178 1179 /* now make the compiler work for us... */ 1180 #define MIN_REDIR MIN(MIN(MIN(MIN(NTO,NFROM), MIN(NTOFD,NFROMFD)), \ 1181 MIN(MIN(NCLOBBER,NAPPEND), MIN(NHERE,NXHERE))), NFROMTO) 1182 #define MAX_REDIR MAX(MAX(MAX(MAX(NTO,NFROM), MAX(NTOFD,NFROMFD)), \ 1183 MAX(MAX(NCLOBBER,NAPPEND), MAX(NHERE,NXHERE))), NFROMTO) 1184 1185 static const char *redir_sym[MAX_REDIR - MIN_REDIR + 1] = { 1186 [NTO - MIN_REDIR]= ">", 1187 [NFROM - MIN_REDIR]= "<", 1188 [NTOFD - MIN_REDIR]= ">&", 1189 [NFROMFD - MIN_REDIR]= "<&", 1190 [NCLOBBER - MIN_REDIR]= ">|", 1191 [NAPPEND - MIN_REDIR]= ">>", 1192 [NHERE - MIN_REDIR]= "<<", 1193 [NXHERE - MIN_REDIR]= "<<", 1194 [NFROMTO - MIN_REDIR]= "<>", 1195 }; 1196 1197 int 1198 outredir(struct output *out, union node *n, int sep) 1199 { 1200 if (n == NULL) 1201 return 0; 1202 if (n->type < MIN_REDIR || n->type > MAX_REDIR || 1203 redir_sym[n->type - MIN_REDIR] == NULL) 1204 return 0; 1205 1206 if (sep) 1207 outc(sep, out); 1208 1209 /* 1210 * ugly, but all redir node types have "fd" in same slot... 1211 * (and code other places assumes it as well) 1212 */ 1213 if ((redir_sym[n->type - MIN_REDIR][0] == '<' && n->nfile.fd != 0) || 1214 (redir_sym[n->type - MIN_REDIR][0] == '>' && n->nfile.fd != 1)) 1215 outfmt(out, "%d", n->nfile.fd); 1216 1217 outstr(redir_sym[n->type - MIN_REDIR], out); 1218 1219 switch (n->type) { 1220 case NHERE: 1221 outstr("'...'", out); 1222 break; 1223 case NXHERE: 1224 outstr("...", out); 1225 break; 1226 case NTOFD: 1227 case NFROMFD: 1228 if (n->ndup.dupfd < 0) 1229 outc('-', out); 1230 else 1231 outfmt(out, "%d", n->ndup.dupfd); 1232 break; 1233 default: 1234 outstr(n->nfile.expfname, out); 1235 break; 1236 } 1237 return 1; 1238 } 1239