summaryrefslogtreecommitdiffhomepage
path: root/src/sys_posix.c
blob: 8ce561dff5199c288e820d012a98cfa0b53b057f (plain)
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
/**
 * @file sys_posix.c
 * @brief Platform layer for Linux and other POSIX systems, built on
 * posix_spawn().
 */
#define _GNU_SOURCE /* posix_spawn_file_actions_addtcsetpgrp_np() */

#include <errno.h>
#include <fcntl.h>
#include <spawn.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "sys.h"

/*
 * glibc 2.35 added a file action that hands the terminal to the child's
 * process group.  Without it the parent does the hand-over after the
 * fact (see sys_spawn_gives_tty()).
 */
#if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
#if __GLIBC_PREREQ(2, 35)
#define HAVE_SPAWN_TCSETPGRP 1
#endif
#endif
#ifndef HAVE_SPAWN_TCSETPGRP
#define HAVE_SPAWN_TCSETPGRP 0
#endif

/**
 * @brief Can sys_spawn() itself make the child's group the terminal's
 *        foreground group?
 *
 * When it cannot, the shell does so from the parent just after the spawn
 * and then sends SIGCONT, in case the child touched the terminal first
 * and was stopped.
 */
bool sys_spawn_gives_tty(void) {
    return HAVE_SPAWN_TCSETPGRP;
}

/**
 * @brief Describe a signal.
 * @return strsignal()'s text. Valid until the next call.
 */
const char *sys_strsignal(int sig) {
    return strsignal(sig);
}

/**
 * @brief Translate an fd map into posix_spawn file actions.
 *
 * The map is "parallel" (every entry names a descriptor as it is in the
 * parent) but file actions run one after another in the child, so a
 * source that an earlier action overwrites is first copied to a scratch
 * descriptor.
 *
 * @param fa  File actions to add to.
 * @param map Child descriptor i is to be the parent's map[i].
 * @return 0, or an errno value.
 */
static int add_fd_actions(posix_spawn_file_actions_t *fa, const int *map) {
    int scratch_fd[SYS_NFD];
    int next_scratch = SYS_NFD;
    int rc = 0;

    for (int i = 0; i < SYS_NFD; i++) {
        int src = map[i];
        scratch_fd[i] = -1;
        bool clobbered = src >= 0 && src < i && map[src] != src;
        if (!clobbered)
            continue;
        for (int j = 0; j < SYS_NFD; j++) { /* pick one no entry uses */
            if (map[j] == next_scratch) {
                next_scratch++;
                j = -1;
            }
        }
        scratch_fd[i] = next_scratch++;
        rc = posix_spawn_file_actions_adddup2(fa, src, scratch_fd[i]);
        if (rc)
            return rc;
    }
    for (int i = 0; i < SYS_NFD; i++) {
        int src = map[i];
        if (src == i)
            continue;
        if (src == FD_CLOSED) {
            rc = posix_spawn_file_actions_addclose(fa, i);
        } else if (scratch_fd[i] >= 0) {
            rc = posix_spawn_file_actions_adddup2(fa, scratch_fd[i], i);
            if (!rc)
                rc = posix_spawn_file_actions_addclose(fa, scratch_fd[i]);
        } else {
            rc = posix_spawn_file_actions_adddup2(fa, src, i);
        }
        if (rc)
            return rc;
    }
    return 0;
}

/**
 * @brief Create a process running a program.
 * @param rq What to run and how its descriptors, signals and process
 *           group are to be set up.
 * @return The child's pid, or -1 with errno set.
 */
pid_t sys_spawn(const spawn_req *rq) {
    posix_spawn_file_actions_t fa;
    posix_spawnattr_t attr;
    bool need_fa = false;
    pid_t pid;
    int rc;

    for (int i = 0; i < SYS_NFD && !need_fa; i++)
        need_fa = rq->fdmap[i] != i;
#if HAVE_SPAWN_TCSETPGRP
    if (rq->tty_fd >= 0)
        need_fa = true;
#endif

    if (need_fa) {
        rc = posix_spawn_file_actions_init(&fa);
        if (rc) {
            errno = rc;
            return -1;
        }
#if HAVE_SPAWN_TCSETPGRP
        /*
         * Runs in the child after it has joined its process group and
         * while every signal is still blocked, so the child owns the
         * terminal before its first instruction and cannot be stopped by
         * SIGTTOU for asking.
         */
        if (rq->tty_fd >= 0)
            rc = posix_spawn_file_actions_addtcsetpgrp_np(&fa, rq->tty_fd);
#endif
        if (!rc)
            rc = add_fd_actions(&fa, rq->fdmap);
        if (rc) {
            posix_spawn_file_actions_destroy(&fa);
            errno = rc;
            return -1;
        }
    }
    bool need_attr = rq->sigdfl || rq->pgroup >= 0;
    if (need_attr) {
        short flags = 0;
        posix_spawnattr_init(&attr);
        if (rq->sigdfl) {
            posix_spawnattr_setsigdefault(&attr, rq->sigdfl);
            flags |= POSIX_SPAWN_SETSIGDEF;
        }
        if (rq->pgroup >= 0) {
            posix_spawnattr_setpgroup(&attr, rq->pgroup);
            flags |= POSIX_SPAWN_SETPGROUP;
        }
        posix_spawnattr_setflags(&attr, flags);
    }
    rc = posix_spawn(&pid, rq->path, need_fa ? &fa : nullptr,
                     need_attr ? &attr : nullptr, rq->argv, rq->envp);
    if (need_fa)
        posix_spawn_file_actions_destroy(&fa);
    if (need_attr)
        posix_spawnattr_destroy(&attr);
    if (rc) {
        errno = rc;
        return -1;
    }
    return pid;
}

/**
 * @brief Create a pipe with both ends close-on-exec and above descriptor 9.
 *
 * A pipe the shell holds must never be mistaken for, or collide with, a
 * descriptor the script names in a redirection.
 */
int sys_pipe(int fd[2]) {
    /* pipe2() is not on every POSIX platform (macOS lacks it), so the ends
     * are made close-on-exec here instead. */
    if (pipe(fd) < 0)
        return -1;
    for (int i = 0; i < 2; i++) {
        if (fd[i] < SYS_NFD) {
            int high = fcntl(fd[i], F_DUPFD_CLOEXEC, SYS_NFD);
            if (high < 0) {
                int perr = errno;
                close(fd[0]);
                close(fd[1]);
                errno = perr;
                return -1;
            }
            close(fd[i]);
            fd[i] = high;
        } else if (fcntl(fd[i], F_SETFD, FD_CLOEXEC) < 0) {
            int perr = errno;
            close(fd[0]);
            close(fd[1]);
            errno = perr;
            return -1;
        }
    }
    return 0;
}

/**
 * @brief Duplicate a descriptor to the lowest free number >= `min`,
 * close-on-exec.
 */
int sys_dupfd(int fd, int min) {
    return fcntl(fd, F_DUPFD_CLOEXEC, min);
}

/**
 * @brief open() with close-on-exec.
 */
int sys_open(const char *path, int flags, mode_t mode) {
    return open(path, flags | O_CLOEXEC, mode);
}

/**
 * @brief Platform start-up.
 * @return Mask of descriptors 0..9 that are open (posix_spawn inherits by
 *         default, so here the mask is never consulted).
 */
unsigned sys_init(void) {
    /* posix_spawn inherits by default, so the mask is never consulted. */
    return (1u << SYS_NFD) - 1;
}

/* ---- file tags: there are none here ----------------------------------- */

/**
 * @brief Cached `_TAG_REDIR_IN`, `_OUT`, `_ERR`. See sys.h.
 */
tag_mode tag_redir[3];

/**
 * @brief Does this platform have file tags?  Not this one.
 */
bool sys_has_tags(void) {
    return false;
}

/**
 * @brief No file tags here: nothing to do.
 */
void sys_redir_tag(int fd, tag_stream stream, tag_mode mode, bool created) {
    (void)fd;
    (void)stream;
    (void)mode;
    (void)created;
}

/**
 * @brief No file tags here: nothing to do.
 */
void sys_tmp_tag(int fd) {
    (void)fd;
}

/**
 * @brief No conversion here: nothing to do.
 */
void sys_input_cvt(int fd) {
    (void)fd;
}

/**
 * @brief Query a file tag. Unsupported here.
 * @return -1 with errno ENOSYS.
 */
int sys_tag_get(const char *path, sys_tag *tag) {
    (void)path;
    (void)tag;
    errno = ENOSYS;
    return -1;
}

/**
 * @brief Set a file tag. Unsupported here.
 * @return -1 with errno ENOSYS.
 */
int sys_tag_set(const char *path, const char *codeset, int text) {
    (void)path;
    (void)codeset;
    (void)text;
    errno = ENOSYS;
    return -1;
}

/* ---- MVS services: stand-ins ------------------------------------------ */

/**
 * @brief System facts. None of the z/OS ones exist here.
 * @return nullptr: the ZOS_* variables are not defined on this platform.
 */
const char *sys_info(sys_info_kind kind) {
    (void)kind;
    return nullptr;
}

/*
 * There is no catalog here.  So that data set completion runs end to end
 * on Linux (and under the sanitizers), the file named by
 * `ZASH_TEST_CATALOG` stands in for one: one entry per line,
 *
 *     SYS1.MACLIB            a data set (type A)
 *     SYS1.MACLIB(GETMAIN)   a member of it
 *     X SYS1                 an entry of another type (here an alias)
 *     DD:SYSIN               an allocated DD name
 *
 * The stand-ins do not hand the names over directly.  They build the
 * bytes IGGCSI00, a PDS directory and the TIOT would hold, in EBCDIC,
 * with small work areas that force the resume protocol and blocks
 * that split across directory entries, and decode them with the same
 * mvsfmt.c code the z/OS build uses.
 */

/** @brief One line of the test catalog, split up. */
typedef struct test_entry {
    char type;     /**< CSI type letter, or 'M' member, 'D' DD name */
    char name[64]; /**< data set name (for a member: its data set) */
    char member[9];
} test_entry;

/**
 * @brief Read the next entry of the test catalog.
 * @return false at end of file.
 */
static bool test_next(FILE *f, test_entry *e) {
    char line[128];
    while (fgets(line, sizeof line, f)) {
        line[strcspn(line, "\n")] = '\0';
        const char *p = line;
        e->type = 'A';
        e->member[0] = '\0';
        if (!strncmp(p, "DD:", 3)) {
            e->type = 'D';
            p += 3;
        } else if (p[0] && p[1] == ' ') {
            e->type = p[0];
            p += 2;
        }
        size_t len = strlen(p);
        if (!len || len >= sizeof e->name)
            continue;
        memcpy(e->name, p, len + 1);
        char *paren = strchr(e->name, '(');
        if (paren && e->type == 'A') {
            *paren = '\0';
            paren[strcspn(paren + 1, ")") + 1] = '\0';
            snprintf(e->member, sizeof e->member, "%.8s", paren + 1);
            e->type = 'M';
        }
        return true;
    }
    return false;
}

/**
 * @brief Does a data set name match a CSI filter key?
 *
 * `%` is one character, `*` any run within a qualifier, `**` any run of
 * qualifiers. A trailing `.**` also matches no qualifier at all.
 */
static bool filter_match(const char *f, const char *s) {
    for (; *f; f++) {
        if (*f == '*') {
            bool deep = f[1] == '*';
            const char *rest = f + (deep ? 2 : 1);
            for (;; s++) {
                if (filter_match(rest, s))
                    return true;
                if (!*s || (!deep && *s == '.'))
                    return false;
            }
        }
        if (*f == '.' && f[1] == '*' && f[2] == '*' && !f[3] && !*s)
            return true; /* "A.**" matches "A" */
        if (!*s || (*f != '%' && *f != *s) || (*f == '%' && *s == '.'))
            return false;
        s++;
    }
    return !*s;
}

/** @brief Store a big-endian halfword. */
static void put16(unsigned char *p, size_t v) {
    p[0] = (unsigned char)(v >> 8);
    p[1] = (unsigned char)v;
}

/** @brief Store a big-endian fullword. */
static void put32(unsigned char *p, size_t v) {
    put16(p, v >> 16);
    put16(p + 2, v & 0xffff);
}

/** @brief Store a name, blank-padded, in EBCDIC. */
static void put_name(unsigned char *p, const char *name, size_t n) {
    size_t len = strlen(name);
    if (len > n)
        len = n;
    memset(p, ' ', n);
    memcpy(p, name, len); // NOLINT(bugprone-not-null-terminated-result):
                          // fixed-width MVS field
    mvs_to_ebcdic((char *)p, n);
}

/**
 * @brief Behave like IGGCSI00 over the test catalog.
 *
 * Fills the work area with a catalog entry and as many matching entries
 * as fit, each with a VOLSER field. If any are left, sets CSIRESUM to
 * 'Y' and CSIRESNM to the last name returned, and continues after that
 * name on the next call, as the real interface does.
 */
static int stub_iggcsi00(csi_area *a, void *ctx) {
    FILE *f = ctx;
    char filter[45];
    char resume[45];
    mvs_name(a->field, 44, filter);
    bool resuming = a->field[149] == mvs_a2e['Y'];
    mvs_name(a->field + 88, 44, resume);
    if (fseek(f, 0, SEEK_SET) != 0)
        return 12; /* as the CSI does for an I/O error */
    size_t off = 14;
    unsigned char *w = a->work;
    uint32_t len = a->worklen;
    w[off] = 0; /* catalog entry: flags 0, type '0' */
    w[off + 1] = mvs_a2e['0'];
    put_name(w + off + 2, "CATALOG.TEST.MASTER", 44);
    memset(w + off + 46, 0, 4);
    off += 50;
    a->field[149] = mvs_a2e[' '];
    test_entry e;
    char last[64] = "";
    while (test_next(f, &e)) {
        if (e.type == 'M' || e.type == 'D' || !filter_match(filter, e.name))
            continue;
        if (resuming && strcmp(e.name, resume) <= 0)
            continue;
        if (!strcmp(e.name, last))
            continue;
        if (off + 46 + 12 > len) {
            a->field[149] = mvs_a2e['Y'];
            put_name(a->field + 88, last, 44);
            break;
        }
        unsigned char *p = w + off;
        p[0] = 0x80; /* CSIPMENT: a primary entry */
        p[1] = mvs_a2e[(unsigned char)e.type];
        put_name(p + 2, e.name, 44);
        put16(p + 46, 12); /* CSITOTLN: 2 + 2 + 2 + 6 */
        put16(p + 48, 0);
        put16(p + 50, 6);
        put_name(p + 52, "TEST01", 6);
        off += 58;
        snprintf(last, sizeof last, "%s", e.name);
    }
    put32(w + 4, 64);
    put32(w + 8, off);
    put16(w + 12, 2);
    return 0;
}

/**
 * @brief Open the test catalog.
 * @return The file, or nullptr if there is none.
 */
static FILE *test_catalog(void) {
    const char *path = getenv("ZASH_TEST_CATALOG");
    return path ? fopen(path, "r") : nullptr;
}

/**
 * @brief Is there a catalog to complete data set names from?
 * @return true if a test catalog is named.
 */
bool sys_has_catalog(void) {
    return getenv("ZASH_TEST_CATALOG") != nullptr;
}

/** @brief Work area size for the stand-in: small, to force resumes. */
#define TEST_WORK 1024

/**
 * @brief List cataloged names that match a CSI filter key.
 * @return false if no catalog is available or the search failed.
 */
bool sys_catalog_list(const char *filter, mvs_name_fn *fn, void *arg) {
    FILE *f = test_catalog();
    if (!f)
        return false;
    unsigned char reason[4];
    unsigned char field[CSI_FIELD_LEN];
    unsigned char *work = malloc(TEST_WORK);
    bool ok = false;
    if (work) {
        csi_area a = {reason, field, work, TEST_WORK};
        ok = csi_search(filter, &a, stub_iggcsi00, f, fn, arg);
        free(work);
    }
    fclose(f);
    return ok;
}

/**
 * @brief List the members of a partitioned data set.
 *
 * Builds directory blocks the way a PDS holds them (members in
 * collating order, user data of varying length so that entries do not
 * line up with block boundaries) and decodes them block by block.
 *
 * @return false if there is no catalog or the directory was malformed.
 */
bool sys_pds_members(const char *dsn, mvs_name_fn *fn, void *arg) {
    FILE *f = test_catalog();
    if (!f)
        return false;
    unsigned char blk[PDS_DIRBLK];
    size_t used = 2;
    bool ok = true;
    bool end = false;
    test_entry e;
    unsigned userdata = 0;
    for (bool more = true; ok && !end;) {
        more = more && test_next(f, &e);
        if (more && (e.type != 'M' || strcmp(e.name, dsn)))
            continue;
        size_t len = more ? 12 + (size_t)(userdata % 32) * 2 : 8;
        if (used + len > PDS_DIRBLK) { /* block full: decode it */
            put16(blk, used);
            ok = pds_parse_block(blk, fn, arg, &end);
            used = 2;
        }
        unsigned char *p = blk + used;
        if (more) {
            put_name(p, e.member, 8);
            memset(p + 8, 0, len - 8);
            p[11] = (unsigned char)(userdata++ % 32);
        } else {
            memset(p, 0xff, 8);
        }
        used += len;
        if (!more) {
            put16(blk, used);
            ok = ok && pds_parse_block(blk, fn, arg, &end);
            break;
        }
    }
    fclose(f);
    return ok;
}

/**
 * @brief List the DD names allocated to this address space.
 *
 * Builds TIOT entries (with a concatenation entry after each, which has
 * a blank name) and decodes them with tiot_parse().
 */
bool sys_dd_names(mvs_name_fn *fn, void *arg) {
    FILE *f = test_catalog();
    if (!f)
        return false;
    unsigned char tiot[4096];
    size_t off = 0;
    test_entry e;
    while (test_next(f, &e) && off + 2 * 20 + 1 < sizeof tiot) {
        if (e.type != 'D')
            continue;
        for (int concat = 0; concat < 2; concat++) {
            unsigned char *p = tiot + off;
            memset(p, 0, 20);
            p[0] = 20;
            put_name(p + 4, concat ? "" : e.name, 8);
            off += 20;
        }
    }
    tiot[off] = 0;
    fclose(f);
    return tiot_parse(tiot, off + 1, fn, arg);
}

/**
 * @brief Dynamic allocation (BPXWDYN). Z/OS only.
 * @return -1: not available on this platform.
 */
int sys_dynalloc(const char *request, char *msg, size_t msglen) {
    (void)request;
    snprintf(msg, msglen, "dynamic allocation needs z/OS");
    return -1;
}