/** * @file redir.c * @brief Redirection. * * Every redirection is first resolved to a descriptor, a duplicate, or a * close. It is then either applied to the shell's own descriptors (for * builtins, functions and compound commands) or recorded in an fd plan * that describes the descriptors of a child about to be spawned, leaving * the shell's untouched. */ #include #include #include #include #include #include #include #include #include "exec.h" #include "expand.h" /* A here-document up to this size fits in a pipe without blocking. */ #ifdef PIPE_BUF #define HEREDOC_PIPE_MAX ((size_t)PIPE_BUF) #else #define HEREDOC_PIPE_MAX ((size_t)512) /* _POSIX_PIPE_BUF */ #endif /** * @brief Where shell-private descriptors start: above everything a script can * name. */ #define PRIVATE_FD SYS_NFD /** * @brief What a redirection turned out to refer to. */ typedef enum resolved { RK_ERROR, RK_FD, /**< a newly opened descriptor, to be closed after use */ RK_DUP, /**< an existing descriptor number */ RK_CLOSE /**< n>&- */ } resolved; /** * @brief The innermost set of redirections applied to the shell itself. */ redirsave *redir_top; /** * @brief Bit i is set when descriptor i (0..9) is open. z/OS spawn() must not * be asked to pass on a descriptor that is closed. */ unsigned fd_open_mask; /** * @brief Record in #fd_open_mask that a low descriptor was opened or closed. */ static void note_fd(int fd, bool open) { if (fd < SYS_NFD) { if (open) fd_open_mask |= 1u << fd; else fd_open_mask &= ~(1u << fd); } } /** * @brief Write a whole buffer, retrying after interruptions. * @return false on a write error. */ static bool write_all(int fd, const char *s, size_t n) { while (n) { ssize_t w = write(fd, s, n); if (w < 0) { if (errno == EINTR) continue; return false; } s += w; n -= (size_t)w; } return true; } /** * @brief Open a descriptor from which a here-document's text can be read. * * A short document is written into a pipe, which costs no file. A long * one, which could block the pipe, goes to an unlinked temporary file. * * @param r The here-document redirection. * @return A readable descriptor, or -1. */ static int heredoc_open(const redir *r) { const char *text = expand_string(r->target->parts, 0); size_t len = strlen(text); if (len <= HEREDOC_PIPE_MAX) { int p[2]; if (sys_pipe(p) < 0) return -1; bool ok = write_all(p[1], text, len); close(p[1]); if (ok) return p[0]; close(p[0]); return -1; } const char *dir = var_get("TMPDIR"); char path[PATH_MAX]; snprintf(path, sizeof path, "%s/zashXXXXXX", dir && *dir ? dir : "/tmp"); int fd = mkstemp(path); if (fd < 0) return -1; unlink(path); if (SYS_MVS) sys_tmp_tag(fd); if (!write_all(fd, text, len) || lseek(fd, 0, SEEK_SET) < 0) { close(fd); return -1; } int copy = sys_dupfd(fd, PRIVATE_FD); close(fd); return copy; } /** * @brief Open the file a redirection names, honouring `noclobber`. * @param r The redirection (its operator decides the open mode). * @param path The expanded file name. * @return A descriptor, or -1 with errno set. */ static int open_file(const redir *r, const char *path) { int flags; switch (r->op) { case R_IN: flags = O_RDONLY; break; case R_RDWR: flags = O_RDWR | O_CREAT; break; case R_APPEND: flags = O_WRONLY | O_CREAT | O_APPEND; break; case R_OUT: if (opt.noclobber) { struct stat st; if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) { errno = EEXIST; return -1; } } [[fallthrough]]; default: flags = O_WRONLY | O_CREAT | O_TRUNC; break; } return sys_open(path, flags, 0666); } /** * @brief Apply file tagging and conversion control to a redirection's * newly opened file (z/OS. See sys_redir_tag()). * * `_TAG_REDIR_IN` governs `<` on descriptor 0, `_TAG_REDIR_OUT` output * to descriptor 1 and `_TAG_REDIR_ERR` output to descriptor 2, as in the * z/OS shell. Output to other descriptors gets the build's default * treatment only. * * @param r The redirection. * @param fd The descriptor it opened. */ static void redir_tag(const redir *r, int fd) { bool input = r->op == R_IN; bool created = r->op == R_OUT || r->op == R_CLOBBER || r->op == R_APPEND; if (input) { if (r->fd == 0) sys_redir_tag(fd, TAG_IN, tag_redir[TAG_IN], false); return; } tag_stream stream = r->fd == 2 ? TAG_ERR : TAG_OUT; tag_mode mode = r->fd == 1 || r->fd == 2 ? tag_redir[stream] : TAG_UNSET; sys_redir_tag(fd, stream, mode, created); } /** * @brief Work out what a redirection refers to, reporting any error. * @param r The redirection. * @param fdp Receives a descriptor for RK_FD and RK_DUP. * @return The kind of result. */ static resolved resolve(const redir *r, int *fdp) { if (r->op == R_HERE) { *fdp = heredoc_open(r); if (*fdp < 0) { sh_warn("cannot create here-document: %s", strerror(errno)); return RK_ERROR; } return RK_FD; } const char *target = expand_string(r->target->parts, XS_TILDE); if (r->op == R_DUPIN || r->op == R_DUPOUT) { if (!strcmp(target, "-")) return RK_CLOSE; long n; if (!parse_long(target, &n) || n < 0 || n >= SYS_NFD) { sh_warn("%s: bad file descriptor", target); return RK_ERROR; } *fdp = (int)n; return RK_DUP; } *fdp = open_file(r, target); if (*fdp < 0) { sh_warn("cannot %s %s: %s", r->op == R_IN ? "open" : "create", target, strerror(errno)); return RK_ERROR; } if (SYS_MVS) redir_tag(r, *fdp); return RK_FD; } /** * @brief Number of redirections in a list. */ static int count_redirs(const redir *r) { int n = 0; for (; r; r = r->next) n++; return n; } /* ---- applying redirections to the shell itself ----------------------- */ /** * @brief Has descriptor `fd` already been saved in this set? */ static bool is_saved(const redirsave *sv, int fd) { for (int i = 0; i < sv->n; i++) { if (sv->e[i].fd == fd) return true; } return false; } /** * @brief Remember a descriptor so that redir_pop() can put it back. * @param sv The save set. * @param fd The descriptor about to be changed. * @param was_closed It is not open now, so "putting it back" means closing. */ static void save_fd(redirsave *sv, int fd, bool was_closed) { if (is_saved(sv, fd)) return; int copy = was_closed ? -1 : sys_dupfd(fd, PRIVATE_FD); sv->e[sv->n].fd = fd; sv->e[sv->n].copy = copy; sv->n++; } /** * @brief Start a save set with room for `max` descriptors and make it * innermost. */ static void begin_save(redirsave *sv, int max) { sv->e = arena_alloc(&scratch, (size_t)(max ? max : 1) * sizeof *sv->e); sv->n = 0; sv->prev = redir_top; redir_top = sv; } /** * @brief Apply a list of redirections to the shell's own descriptors. * * The previous state of each descriptor touched is saved in `sv`. Undo * with redir_pop(). On failure everything done so far is undone. * * @param list The redirections. * @param sv Caller-provided save set. * @return false if a redirection failed (a message has been printed). */ bool redir_push(const redir *list, redirsave *sv) { begin_save(sv, count_redirs(list)); for (const redir *r = list; r; r = r->next) { int src = -1; resolved k = resolve(r, &src); if (k == RK_ERROR) goto fail; if (k == RK_DUP && src == r->fd) continue; if (k == RK_FD && src == r->fd) { /* open() returned the very descriptor wanted, so it was * closed before. It only needs close-on-exec cleared. */ save_fd(sv, r->fd, true); fcntl(src, F_SETFD, 0); note_fd(r->fd, true); continue; } save_fd(sv, r->fd, false); if (k == RK_CLOSE) { close(r->fd); note_fd(r->fd, false); continue; } if (dup2(src, r->fd) < 0) { sh_warn("%d: bad file descriptor", src); if (k == RK_FD) close(src); goto fail; } if (k == RK_FD) close(src); note_fd(r->fd, true); } return true; fail: redir_pop(false); return false; } /** * @brief Redirect one descriptor of the shell to another, saving the old one. * @param sv Caller-provided save set. * @param fd Descriptor to replace. * @param src Descriptor to put there. It is consumed (closed). */ void redir_push_fd(redirsave *sv, int fd, int src) { begin_save(sv, 1); save_fd(sv, fd, false); dup2(src, fd); close(src); note_fd(fd, true); } /** * @brief Undo the most recent redir_push(). * @param keep Leave the redirections in force (the `exec` builtin) and * only discard the saved copies. */ void redir_pop(bool keep) { redirsave *sv = redir_top; for (int i = sv->n; i-- > 0;) { int fd = sv->e[i].fd; int copy = sv->e[i].copy; if (keep) { if (copy >= 0) close(copy); } else if (copy >= 0) { dup2(copy, fd); close(copy); note_fd(fd, true); } else { close(fd); note_fd(fd, false); } } redir_top = sv->prev; } /** * @brief Undo redirections until `to` is the innermost set again. */ void redir_unwind(redirsave *to) { while (redir_top != to) redir_pop(false); } /* ---- planning redirections for a child ------------------------------- */ /** * @brief Start a descriptor plan in which the child inherits 0..9 unchanged. * @param p The plan. * @param in Descriptor for the child's stdin, or -1. * @param out Descriptor for the child's stdout, or -1. */ void plan_init(fdplan *p, int in, int out) { for (int i = 0; i < SYS_NFD; i++) p->map[i] = i; if (in >= 0) p->map[0] = in; if (out >= 0) p->map[1] = out; p->temps = nullptr; p->ntemps = 0; } /** * @brief Add a command's redirections to a plan. * * Files are opened in the shell, but the shell's descriptors 0..9 are not * changed: the plan only records which descriptor the child should get in * each slot. * * @param p The plan. * @param list The redirections. * @return false if a redirection failed (a message has been printed). */ bool plan_redirs(fdplan *p, const redir *list) { int max = count_redirs(list); if (max) p->temps = arena_alloc(&scratch, (size_t)max * sizeof *p->temps); for (const redir *r = list; r; r = r->next) { int src = -1; switch (resolve(r, &src)) { case RK_ERROR: return false; case RK_FD: if (src == r->fd) { /* Keep plan sources distinct from the slots they fill, so * "inherit descriptor n" never means a temporary. */ int moved = sys_dupfd(src, PRIVATE_FD); close(src); src = moved; } p->temps[p->ntemps++] = src; p->map[r->fd] = src; break; case RK_DUP: p->map[r->fd] = p->map[src]; break; case RK_CLOSE: p->map[r->fd] = FD_CLOSED; break; } } return true; } /** * @brief Close the descriptors that were opened for a plan. */ void plan_close(fdplan *p) { for (int i = 0; i < p->ntemps; i++) close(p->temps[i]); p->ntemps = 0; } /** * @brief Make the shell's own descriptors match a plan. * * Used only immediately before exec() replaces the shell, so nothing is * saved. */ void plan_apply(fdplan *p) { /* Move every source out of the 0..9 range so no dup2 below can * overwrite a descriptor that is still needed. */ for (int i = 0; i < SYS_NFD; i++) { int src = p->map[i]; if (src == i || src < 0 || src >= SYS_NFD) continue; int moved = sys_dupfd(src, PRIVATE_FD); for (int j = i; j < SYS_NFD; j++) { if (p->map[j] == src) p->map[j] = moved; } for (int t = 0; t < p->ntemps; t++) { if (p->temps[t] == src) { close(src); p->temps[t] = -1; } } } for (int i = 0; i < SYS_NFD; i++) { if (p->map[i] == FD_CLOSED) close(i); else if (p->map[i] != i) dup2(p->map[i], i); } for (int t = 0; t < p->ntemps; t++) { if (p->temps[t] >= SYS_NFD) close(p->temps[t]); } p->ntemps = 0; }