1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
|
/**
* @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 <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#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 = NULL;
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;
}
|