rifle

coreutils in one C file, 86 tools, no GNU
git clone https://github.com/tortr-rs/rifle
Log | Files | Refs | README | LICENSE

rifle.c (549185B)


      1 /* rifle: coreutils in one C file, on c.h. cat, ls, cp and the rest are links to this program, it runs
      2  * whichever name it was called by. build.sh makes them in bin/, "rifle --install DIR" anywhere else. */
      3 #include "c.h"
      4 
      5 #define VERSION "0.3"
      6 
      7 /* ---- messages ---- */
      8 
      9 static const char *prog = "rifle";
     10 static const char *tool_usage;
     11 static const char *tool_about;
     12 static int status;                   /* 1 once something failed; tools go on with the next file */
     13 static int usage_status = 1;           /* env and a few others exit 125 on a bad option */
     14 
     15 static void say(const char *fmt, ...)
     16 {
     17     va_list ap;
     18     fflush(stdout);
     19     fprintf(stderr, "%s: ", prog);
     20     va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap);
     21     fputc('\n', stderr);
     22 }
     23 static void perr(const char *fmt, ...)
     24 {
     25     va_list ap;
     26     int e = errno;
     27     fflush(stdout);
     28     fprintf(stderr, "%s: ", prog);
     29     va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap);
     30     fprintf(stderr, ": %s\n", strerror(e));
     31 }
     32 static __attribute__((noreturn)) void die(int code, const char *fmt, ...)
     33 {
     34     va_list ap;
     35     fflush(stdout);
     36     fprintf(stderr, "%s: ", prog);
     37     va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap);
     38     fputc('\n', stderr);
     39     exit(code);
     40 }
     41 static void try_help(void) { fprintf(stderr, "Try '%s --help' for more information.\n", prog); }
     42 static __attribute__((noreturn)) void usage_error(void) { try_help(); exit(usage_status); }
     43 static __attribute__((noreturn)) void missing_operand(void) { say("missing operand"); usage_error(); }
     44 static __attribute__((noreturn)) void extra_operand(const char *s) { say("extra operand '%s'", s); usage_error(); }
     45 static void print_usage(void)
     46 {
     47     printf("Usage: %s %s\n%s\n", prog, tool_usage, tool_about);
     48 }
     49 
     50 static void *xmalloc(size_t n) { void *p = malloc(n ? n : 1); if (!p) die(1, "memory exhausted"); return p; }
     51 static void *xrealloc(void *p, size_t n) { p = realloc(p, n ? n : 1); if (!p) die(1, "memory exhausted"); return p; }
     52 static char *xstrdup(const char *s) { char *d = xmalloc(strlen(s) + 1); return strcpy(d, s); }
     53 
     54 static int write_all(int fd, const char *buf, size_t n)
     55 {
     56     while (n) {
     57         ssize_t w = write(fd, buf, n);
     58         if (w < 0) { if (errno == EINTR) continue; return -1; }
     59         buf += w; n -= w;
     60     }
     61     return 0;
     62 }
     63 static int finish_stdout(void)
     64 {
     65     if (fflush(stdout) == EOF || ferror(stdout)) { say("write error: %s", strerror(errno ? errno : EIO)); return 1; }
     66     return 0;
     67 }
     68 
     69 /* ---- options ----
     70  * getopt_long, more or less: options between operands, -abc and -s5, --name=x, short forms of long names.
     71  * a leading + in the short list stops at the first operand. what's left lands in ops */
     72 
     73 struct opt { const char *name; int arg; int val; };
     74 static char **ops;
     75 static int nops;
     76 static int opt_i = 1, opt_c, opt_stop;
     77 
     78 static void opts_reset(void) { opt_i = 1; opt_c = 0; opt_stop = 0; nops = 0; optarg = NULL; }
     79 
     80 static int getopts(int argc, char **argv, const char *shorts, const struct opt *longs)
     81 {
     82     int posix = shorts[0] == '+';
     83     if (posix) shorts++;
     84     if (!ops) ops = xmalloc((argc + 1) * sizeof *ops);
     85     for (;;) {
     86         char *a;
     87         if (opt_c == 0) {
     88             if (opt_i >= argc) { ops[nops] = NULL; return 0; }
     89             a = argv[opt_i];
     90             if (opt_stop || a[0] != '-' || !a[1]) {
     91                 if (posix) opt_stop = 1;
     92                 ops[nops++] = a; opt_i++;
     93                 continue;
     94             }
     95             if (a[1] == '-') {
     96                 static const struct opt builtin[] = { { "help", 0, -100 }, { "version", 0, -101 }, { NULL, 0, 0 } };
     97                 const struct opt *o = NULL, *hit;
     98                 char *eq = strchr(a + 2, '=');
     99                 size_t l = eq ? (size_t)(eq - a - 2) : strlen(a + 2);
    100                 int found = 0, exact = 0, pass;
    101                 if (!a[2]) { opt_stop = 1; opt_i++; continue; }
    102                 /* the tool's own options, then --help and --version. an exact name wins, else a start that fits
    103                  * exactly one option (two names for the same option don't count as two) */
    104                 for (pass = 0; pass < 2 && !exact; pass++)
    105                     for (hit = pass ? builtin : longs; hit && hit->name; hit++)
    106                         if (!strncmp(hit->name, a + 2, l)) {
    107                             if (!hit->name[l]) { o = hit; exact = 1; found = 1; break; }
    108                             if (!found) { o = hit; found = 1; }
    109                             else if (hit->val != o->val) found++;
    110                         }
    111                 if (!found) { say("unrecognized option '%.*s'", (int)(eq ? eq - a : (long)strlen(a)), a); usage_error(); }
    112                 if (found > 1) { say("option '%.*s' is ambiguous", (int)(eq ? eq - a : (long)strlen(a)), a); usage_error(); }
    113                 if (o->val == -100) { print_usage(); exit(0); }
    114                 if (o->val == -101) { printf("%s (rifle) " VERSION "\n", prog); exit(0); }
    115                 opt_i++;
    116                 if (o->arg == 0) {
    117                     if (eq) { say("option '--%s' doesn't allow an argument", o->name); usage_error(); }
    118                     optarg = NULL;
    119                 } else if (eq) optarg = eq + 1;
    120                 else if (o->arg == 1) {
    121                     if (opt_i >= argc) { say("option '--%s' requires an argument", o->name); usage_error(); }
    122                     optarg = argv[opt_i++];
    123                 } else optarg = NULL;
    124                 return o->val;
    125             }
    126             opt_c = 1;
    127         }
    128         a = argv[opt_i];
    129         {
    130             char c = a[opt_c++];
    131             const char *p = strchr(shorts, c);
    132             int last = !a[opt_c];
    133             if (!p || c == ':') { say("invalid option -- '%c'", c); usage_error(); }
    134             if (p[1] == ':' && p[2] == ':') {
    135                 optarg = last ? NULL : a + opt_c;
    136                 opt_c = 0; opt_i++;
    137             } else if (p[1] == ':') {
    138                 if (!last) { optarg = a + opt_c; opt_c = 0; opt_i++; }
    139                 else {
    140                     opt_c = 0; opt_i++;
    141                     if (opt_i >= argc) { say("option requires an argument -- '%c'", c); usage_error(); }
    142                     optarg = argv[opt_i++];
    143                 }
    144             } else {
    145                 optarg = NULL;
    146                 if (last) { opt_c = 0; opt_i++; }
    147             }
    148             return (unsigned char)c;
    149         }
    150     }
    151 }
    152 
    153 /* ---- small helpers ---- */
    154 
    155 static int parse_ulong(const char *s, unsigned long *out)
    156 {
    157     char *end;
    158     if (!isdigit((unsigned char)*s)) return 0;
    159     errno = 0;
    160     *out = strtoul(s, &end, 10);
    161     return !*end && errno != ERANGE;
    162 }
    163 
    164 static const char *user_name(uid_t u)
    165 {
    166     static char buf[24];
    167     struct passwd *p = getpwuid(u);
    168     if (p) return p->pw_name;
    169     snprintf(buf, sizeof buf, "%u", u);
    170     return buf;
    171 }
    172 static const char *group_name(gid_t g)
    173 {
    174     static char buf[24];
    175     struct group *p = getgrgid(g);
    176     if (p) return p->gr_name;
    177     snprintf(buf, sizeof buf, "%u", g);
    178     return buf;
    179 }
    180 static int lookup_user(const char *s, uid_t *u)
    181 {
    182     unsigned long n;
    183     struct passwd *p;
    184     if (!*s) return -1;
    185     if ((p = getpwnam(s))) { *u = p->pw_uid; return 0; }
    186     if (parse_ulong(s, &n)) { *u = n; return 0; }
    187     return -1;
    188 }
    189 static int lookup_group(const char *s, gid_t *g)
    190 {
    191     unsigned long n;
    192     struct group *p;
    193     if (!*s) return -1;
    194     if ((p = getgrnam(s))) { *g = p->gr_gid; return 0; }
    195     if (parse_ulong(s, &n)) { *g = n; return 0; }
    196     return -1;
    197 }
    198 
    199 /* ---- modes ----
    200  * chmod's language (755, u=rwx,go=rx, g=u, +X ...), compiled to a list of changes and applied to the old mode */
    201 
    202 struct change { char op; char flag; mode_t affected, value, mentioned; };
    203 #define MODE_ORDINARY 0
    204 #define MODE_COPY 1
    205 #define MODE_X_IF_ANY 2
    206 #define MODE_BITS 07777
    207 
    208 static struct change *mode_compile(const char *s)
    209 {
    210     struct change *list;
    211     int n = 0;
    212     if (*s >= '0' && *s <= '7') {
    213         unsigned long v = 0; const char *p = s;
    214         for (; *p >= '0' && *p <= '7'; p++) { v = v * 8 + (*p - '0'); if (v > 07777) return NULL; }
    215         if (*p) return NULL;
    216         list = xmalloc(2 * sizeof *list);
    217         list[0].op = '='; list[0].flag = MODE_ORDINARY; list[0].affected = MODE_BITS; list[0].value = v;
    218         /* with fewer than 5 digits the setuid and setgid bits are only touched if the mode has them */
    219         list[0].mentioned = (p - s < 5) ? ((v & (S_ISUID | S_ISGID)) | S_ISVTX | 0777) : MODE_BITS;
    220         list[1].op = 0;
    221         return list;
    222     }
    223     list = xmalloc((strlen(s) + 2) * sizeof *list);
    224     for (;;) {
    225         mode_t affected = 0;
    226         char op;
    227         for (;; s++) {
    228             if (*s == 'u') affected |= S_ISUID | S_IRWXU;
    229             else if (*s == 'g') affected |= S_ISGID | S_IRWXG;
    230             else if (*s == 'o') affected |= S_ISVTX | S_IRWXO;
    231             else if (*s == 'a') affected |= MODE_BITS;
    232             else break;
    233         }
    234         if (*s != '+' && *s != '-' && *s != '=') { free(list); return NULL; }
    235         while (*s == '+' || *s == '-' || *s == '=') {
    236             mode_t value = 0;
    237             char flag = MODE_ORDINARY;
    238             op = *s++;
    239             if (*s == 'u' || *s == 'g' || *s == 'o') {
    240                 value = *s == 'u' ? S_IRWXU : *s == 'g' ? S_IRWXG : S_IRWXO;
    241                 flag = MODE_COPY; s++;
    242             } else {
    243                 for (;; s++) {
    244                     if (*s == 'r') value |= S_IRUSR | S_IRGRP | S_IROTH;
    245                     else if (*s == 'w') value |= S_IWUSR | S_IWGRP | S_IWOTH;
    246                     else if (*s == 'x') value |= S_IXUSR | S_IXGRP | S_IXOTH;
    247                     else if (*s == 'X') flag = MODE_X_IF_ANY;
    248                     else if (*s == 's') value |= S_ISUID | S_ISGID;
    249                     else if (*s == 't') value |= S_ISVTX;
    250                     else break;
    251                 }
    252             }
    253             list[n].op = op; list[n].flag = flag; list[n].affected = affected; list[n].value = value;
    254             list[n].mentioned = affected ? (affected & value) : value;
    255             n++;
    256         }
    257         if (*s == ',') { s++; continue; }
    258         if (*s) { free(list); return NULL; }
    259         break;
    260     }
    261     list[n].op = 0;
    262     return list;
    263 }
    264 
    265 /* the mode a file gets: old is what it has, dir says whether it's a directory (setuid and setgid on those stay unless
    266  * asked about), umask is applied to changes that don't say who they're for */
    267 static mode_t mode_apply(mode_t old, int dir, mode_t um, const struct change *c)
    268 {
    269     mode_t newmode = old & MODE_BITS;
    270     for (; c->op; c++) {
    271         mode_t affected = c->affected, value = c->value;
    272         mode_t omit = (dir ? S_ISUID | S_ISGID : 0) & ~c->mentioned;
    273         if (c->flag == MODE_COPY) {
    274             value &= newmode;
    275             value |= ((value & (S_IRUSR | S_IRGRP | S_IROTH)) ? S_IRUSR | S_IRGRP | S_IROTH : 0)
    276                    | ((value & (S_IWUSR | S_IWGRP | S_IWOTH)) ? S_IWUSR | S_IWGRP | S_IWOTH : 0)
    277                    | ((value & (S_IXUSR | S_IXGRP | S_IXOTH)) ? S_IXUSR | S_IXGRP | S_IXOTH : 0);
    278         } else if (c->flag == MODE_X_IF_ANY) {
    279             if ((newmode & (S_IXUSR | S_IXGRP | S_IXOTH)) || dir) value |= S_IXUSR | S_IXGRP | S_IXOTH;
    280         }
    281         value &= (affected ? affected : (mode_t)~um) & ~omit;
    282         if (c->op == '=') {
    283             mode_t keep = (affected ? ~affected : 0) | omit;
    284             newmode = (newmode & keep) | value;
    285         } else if (c->op == '+') newmode |= value;
    286         else newmode &= ~value;
    287     }
    288     return newmode;
    289 }
    290 
    291 static void mode_string(mode_t m, char *s)
    292 {
    293     s[0] = m & S_IRUSR ? 'r' : '-'; s[1] = m & S_IWUSR ? 'w' : '-';
    294     s[2] = m & S_ISUID ? (m & S_IXUSR ? 's' : 'S') : (m & S_IXUSR ? 'x' : '-');
    295     s[3] = m & S_IRGRP ? 'r' : '-'; s[4] = m & S_IWGRP ? 'w' : '-';
    296     s[5] = m & S_ISGID ? (m & S_IXGRP ? 's' : 'S') : (m & S_IXGRP ? 'x' : '-');
    297     s[6] = m & S_IROTH ? 'r' : '-'; s[7] = m & S_IWOTH ? 'w' : '-';
    298     s[8] = m & S_ISVTX ? (m & S_IXOTH ? 't' : 'T') : (m & S_IXOTH ? 'x' : '-');
    299     s[9] = 0;
    300 }
    301 
    302 static mode_t current_umask(void) { mode_t m = umask(0); umask(m); return m; }
    303 
    304 static char *strtok_r_simple(char **p)
    305 {
    306     char *s = *p, *w;
    307     while (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r') s++;
    308     if (!*s) { *p = s; return NULL; }
    309     w = s;
    310     while (*s && *s != ' ' && *s != '\t' && *s != '\n' && *s != '\r') s++;
    311     if (*s) *s++ = 0;
    312     *p = s;
    313     return w;
    314 }
    315 
    316 static const char *base_of(const char *p)
    317 {
    318     const char *s = strrchr(p, '/');
    319     return s && s[1] ? s + 1 : p;
    320 }
    321 
    322 /* ---- true false ---- */
    323 
    324 static int t_true(int argc, char **argv)
    325 {
    326     /* they ignore everything, except as the only argument: --help and --version still work */
    327     if (argc == 2 && !strcmp(argv[1], "--help")) { print_usage(); return prog[0] == 'f'; }
    328     if (argc == 2 && !strcmp(argv[1], "--version")) { printf("%s (rifle) " VERSION "\n", prog); return prog[0] == 'f'; }
    329     return prog[0] == 'f';
    330 }
    331 
    332 /* ---- echo ---- */
    333 
    334 static int t_echo(int argc, char **argv)
    335 {
    336     int nl = 1, esc = 0, i = 1, first;
    337     if (argc == 2 && !strcmp(argv[1], "--help")) { print_usage(); return 0; }
    338     if (argc == 2 && !strcmp(argv[1], "--version")) { printf("echo (rifle) " VERSION "\n"); return 0; }
    339     for (; i < argc; i++) {
    340         char *a = argv[i]; int j;
    341         if (a[0] != '-' || !a[1]) break;
    342         for (j = 1; a[j] && strchr("neE", a[j]); j++) ;
    343         if (a[j]) break;
    344         for (j = 1; a[j]; j++) { if (a[j] == 'n') nl = 0; else if (a[j] == 'e') esc = 1; else esc = 0; }
    345     }
    346     first = i;
    347     for (; i < argc; i++) {
    348         const char *s = argv[i];
    349         if (i > first) putchar(' ');
    350         if (!esc) { fputs(s, stdout); continue; }
    351         while (*s) {
    352             int c = (unsigned char)*s++;
    353             if (c != '\\' || !*s) { putchar(c); continue; }
    354             c = *s++;
    355             switch (c) {
    356             case 'a': putchar('\a'); break;
    357             case 'b': putchar('\b'); break;
    358             case 'c': return finish_stdout();
    359             case 'e': putchar(27); break;
    360             case 'f': putchar('\f'); break;
    361             case 'n': putchar('\n'); break;
    362             case 'r': putchar('\r'); break;
    363             case 't': putchar('\t'); break;
    364             case 'v': putchar('\v'); break;
    365             case '\\': putchar('\\'); break;
    366             case 'x':
    367                 if (!isxdigit((unsigned char)*s)) { putchar('\\'); putchar('x'); break; }
    368                 c = digit_of(*s++);
    369                 if (isxdigit((unsigned char)*s)) c = c * 16 + digit_of(*s++);
    370                 putchar(c);
    371                 break;
    372             case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7':
    373                 if (c == '0') { if (!(*s >= '0' && *s <= '7')) { putchar(0); break; } c = *s++; }
    374                 c -= '0';
    375                 if (*s >= '0' && *s <= '7') c = c * 8 + (*s++ - '0');
    376                 if (*s >= '0' && *s <= '7') c = c * 8 + (*s++ - '0');
    377                 putchar(c & 255);
    378                 break;
    379             default: putchar('\\'); putchar(c); break;
    380             }
    381         }
    382     }
    383     if (nl) putchar('\n');
    384     return finish_stdout();
    385 }
    386 
    387 /* ---- yes ---- */
    388 
    389 static int t_yes(int argc, char **argv)
    390 {
    391     static char buf[16384];
    392     size_t len = 0, i;
    393     int c;
    394     opts_reset();
    395     while ((c = getopts(argc, argv, "", NULL))) ;
    396     if (!nops) { memcpy(buf, "y\n", 2); len = 2; }
    397     else {
    398         for (i = 0; i < (size_t)nops; i++) {
    399             size_t l = strlen(ops[i]);
    400             if (len + l + 1 > sizeof buf) break;
    401             if (i) buf[len++] = ' ';
    402             memcpy(buf + len, ops[i], l); len += l;
    403         }
    404         buf[len++] = '\n';
    405     }
    406     for (i = len; i + len <= sizeof buf; i += len) memcpy(buf + i, buf, len);
    407     len = i;
    408     for (;;) if (write_all(1, buf, len) < 0) { perr("standard output"); return 1; }
    409 }
    410 
    411 /* ---- cat ---- */
    412 
    413 static char cat_out[1 << 16];
    414 static size_t cat_n;
    415 static int cat_flush(void)
    416 {
    417     int r = cat_n ? write_all(1, cat_out, cat_n) : 0;
    418     cat_n = 0;
    419     return r;
    420 }
    421 
    422 static int t_cat(int argc, char **argv)
    423 {
    424     static const struct opt lo[] = {
    425         { "show-all", 0, 'A' }, { "number-nonblank", 0, 'b' }, { "show-ends", 0, 'E' }, { "number", 0, 'n' },
    426         { "squeeze-blank", 0, 's' }, { "show-tabs", 0, 'T' }, { "show-nonprinting", 0, 'v' }, { NULL, 0, 0 } };
    427     int c, number = 0, nonblank = 0, ends = 0, tabs = 0, nonprint = 0, squeeze = 0, i;
    428     static char in[1 << 17];
    429     struct stat out_st; int out_reg;
    430     static unsigned long line_no;
    431     opts_reset();
    432     while ((c = getopts(argc, argv, "AbeEnstTuv", lo)))
    433         switch (c) {
    434         case 'A': nonprint = ends = tabs = 1; break;
    435         case 'b': number = nonblank = 1; break;
    436         case 'e': nonprint = ends = 1; break;
    437         case 'E': ends = 1; break;
    438         case 'n': number = 1; break;
    439         case 's': squeeze = 1; break;
    440         case 't': nonprint = tabs = 1; break;
    441         case 'T': tabs = 1; break;
    442         case 'v': nonprint = 1; break;
    443         default: break;
    444         }
    445     if (!nops) ops[nops++] = "-";
    446     out_reg = fstat(1, &out_st) == 0 && S_ISREG(out_st.st_mode);
    447     for (i = 0; i < nops; i++) {
    448         int fd = strcmp(ops[i], "-") ? open(ops[i], O_RDONLY) : 0;
    449         struct stat st;
    450         ssize_t n;
    451         int at_bol = 1, blank_run = 0;
    452         if (fd < 0) { perr("%s", ops[i]); status = 1; continue; }
    453         if (fstat(fd, &st) == 0 && out_reg && st.st_dev == out_st.st_dev && st.st_ino == out_st.st_ino &&
    454             lseek(fd, 0, SEEK_CUR) < st.st_size) {
    455             say("%s: input file is output file", ops[i]); status = 1; if (fd) close(fd); continue;
    456         }
    457         while ((n = read(fd, in, sizeof in)) != 0) {
    458             ssize_t k;
    459             if (n < 0) { if (errno == EINTR) continue; perr("%s", ops[i]); status = 1; break; }
    460             if (!(number || ends || tabs || nonprint || squeeze)) {
    461                 if (cat_flush() < 0 || write_all(1, in, n) < 0) { perr("write error"); exit(1); }
    462                 continue;
    463             }
    464             for (k = 0; k < n; k++) {
    465                 int ch = (unsigned char)in[k];
    466                 if (cat_n > sizeof cat_out - 32) if (cat_flush() < 0) { perr("write error"); exit(1); }
    467                 if (at_bol) {
    468                     if (ch == '\n') {
    469                         if (squeeze && blank_run) continue;
    470                         blank_run++;
    471                         if (number && !nonblank) cat_n += snprintf(cat_out + cat_n, 32, "%6lu\t", ++line_no);
    472                         if (ends) cat_out[cat_n++] = '$';
    473                         cat_out[cat_n++] = '\n';
    474                         continue;
    475                     }
    476                     blank_run = 0;
    477                     if (number) cat_n += snprintf(cat_out + cat_n, 32, "%6lu\t", ++line_no);
    478                     at_bol = 0;
    479                 }
    480                 if (ch == '\n') { if (ends) cat_out[cat_n++] = '$'; cat_out[cat_n++] = '\n'; at_bol = 1; continue; }
    481                 if (ch == '\t') { if (tabs) { cat_out[cat_n++] = '^'; cat_out[cat_n++] = 'I'; } else cat_out[cat_n++] = '\t'; continue; }
    482                 if (nonprint) {
    483                     if (ch >= 128) { cat_out[cat_n++] = 'M'; cat_out[cat_n++] = '-'; ch -= 128; }
    484                     if (ch < 32) { cat_out[cat_n++] = '^'; cat_out[cat_n++] = ch + 64; continue; }
    485                     if (ch == 127) { cat_out[cat_n++] = '^'; cat_out[cat_n++] = '?'; continue; }
    486                 }
    487                 cat_out[cat_n++] = ch;
    488             }
    489         }
    490         if (fd) close(fd);
    491     }
    492     if (cat_flush() < 0) { perr("write error"); return 1; }
    493     return status;
    494 }
    495 
    496 /* ---- pwd ---- */
    497 
    498 static int t_pwd(int argc, char **argv)
    499 {
    500     static const struct opt lo[] = { { "logical", 0, 'L' }, { "physical", 0, 'P' }, { NULL, 0, 0 } };
    501     int c, logical = getenv("POSIXLY_CORRECT") != NULL;
    502     char buf[PATH_MAX], *w;
    503     opts_reset();
    504     while ((c = getopts(argc, argv, "LP", lo))) logical = c == 'L';
    505     if (nops) say("ignoring non-option arguments");
    506     if (logical && (w = getenv("PWD")) && w[0] == '/') {
    507         /* $PWD is good if it's this directory and has no . or .. in it */
    508         struct stat a, b; const char *p;
    509         int ok = stat(w, &a) == 0 && stat(".", &b) == 0 && a.st_dev == b.st_dev && a.st_ino == b.st_ino;
    510         for (p = w; ok && *p; ) {
    511             if (*p == '/') { p++; continue; }
    512             if (p[0] == '.' && (p[1] == '/' || !p[1])) ok = 0;
    513             if (p[0] == '.' && p[1] == '.' && (p[2] == '/' || !p[2])) ok = 0;
    514             while (*p && *p != '/') p++;
    515         }
    516         if (ok) { puts(w); return finish_stdout(); }
    517     }
    518     if (!getcwd(buf, sizeof buf)) { perr("cannot get current directory"); return 1; }
    519     puts(buf);
    520     return finish_stdout();
    521 }
    522 
    523 /* ---- sleep ---- */
    524 
    525 static int t_sleep(int argc, char **argv)
    526 {
    527     double total = 0;
    528     int i, bad = 0, c;
    529     struct timespec t;
    530     opts_reset();
    531     while ((c = getopts(argc, argv, "", NULL))) ;
    532     if (!nops) missing_operand();
    533     for (i = 0; i < nops; i++) {
    534         char *end;
    535         double v = strtod(ops[i], &end);
    536         double mult = 1;
    537         if (end == ops[i] || v < 0 || ops[i][0] == '-') { bad = 1; say("invalid time interval '%s'", ops[i]); continue; }
    538         if (*end == 's') end++;
    539         else if (*end == 'm') { mult = 60; end++; }
    540         else if (*end == 'h') { mult = 3600; end++; }
    541         else if (*end == 'd') { mult = 86400; end++; }
    542         if (*end) { bad = 1; say("invalid time interval '%s'", ops[i]); continue; }
    543         total += v * mult;
    544     }
    545     if (bad) usage_error();
    546     t.tv_sec = (long)total;
    547     t.tv_nsec = (long)((total - (double)t.tv_sec) * 1e9);
    548     while (nanosleep(&t, &t) < 0 && errno == EINTR) ;
    549     return 0;
    550 }
    551 
    552 /* ---- basename dirname ---- */
    553 
    554 static int t_basename(int argc, char **argv)
    555 {
    556     static const struct opt lo[] = { { "multiple", 0, 'a' }, { "suffix", 1, 's' }, { "zero", 0, 'z' }, { NULL, 0, 0 } };
    557     int c, multiple = 0, zero = 0, i;
    558     const char *suffix = NULL;
    559     opts_reset();
    560     while ((c = getopts(argc, argv, "as:z", lo)))
    561         switch (c) {
    562         case 'a': multiple = 1; break;
    563         case 's': multiple = 1; suffix = optarg; break;
    564         case 'z': zero = 1; break;
    565         }
    566     if (!nops) missing_operand();
    567     if (!multiple) {
    568         if (nops > 2) extra_operand(ops[2]);
    569         if (nops == 2) suffix = ops[1];
    570         nops = 1;
    571     }
    572     for (i = 0; i < nops; i++) {
    573         char *s = xstrdup(ops[i]), *b;
    574         size_t n = strlen(s);
    575         while (n > 1 && s[n - 1] == '/') s[--n] = 0;
    576         b = n > 1 || s[0] != '/' ? (strrchr(s, '/') ? strrchr(s, '/') + 1 : s) : s;
    577         if (suffix && *suffix) {
    578             size_t bl = strlen(b), sl = strlen(suffix);
    579             if (bl > sl && !memcmp(b + bl - sl, suffix, sl)) b[bl - sl] = 0;
    580         }
    581         fputs(b, stdout);
    582         putchar(zero ? 0 : '\n');
    583         free(s);
    584     }
    585     return finish_stdout();
    586 }
    587 
    588 static int t_dirname(int argc, char **argv)
    589 {
    590     static const struct opt lo[] = { { "zero", 0, 'z' }, { NULL, 0, 0 } };
    591     int c, zero = 0, i;
    592     opts_reset();
    593     while ((c = getopts(argc, argv, "z", lo))) zero = 1;
    594     if (!nops) missing_operand();
    595     for (i = 0; i < nops; i++) {
    596         const char *s = ops[i];
    597         size_t n = strlen(s), k;
    598         while (n > 1 && s[n - 1] == '/') n--;
    599         k = n;
    600         while (k > 0 && s[k - 1] != '/') k--;
    601         if (k == 0) fputs(".", stdout);
    602         else {
    603             while (k > 1 && s[k - 1] == '/') k--;
    604             fwrite(s, 1, k, stdout);
    605         }
    606         putchar(zero ? 0 : '\n');
    607     }
    608     return finish_stdout();
    609 }
    610 
    611 /* ---- sync ---- */
    612 
    613 static int t_sync(int argc, char **argv)
    614 {
    615     static const struct opt lo[] = { { "data", 0, 'd' }, { "file-system", 0, 'f' }, { NULL, 0, 0 } };
    616     int c, data = 0, fs = 0, i, st = 0;
    617     opts_reset();
    618     while ((c = getopts(argc, argv, "df", lo))) { if (c == 'd') data = 1; else fs = 1; }
    619     if (data && fs) { say("cannot specify both --data and --file-system"); usage_error(); }
    620     if (data && !nops) { say("--data needs at least one argument"); usage_error(); }
    621     if (!nops) { sync(); return 0; }
    622     for (i = 0; i < nops; i++) {
    623         int fd = open(ops[i], O_RDONLY | O_NONBLOCK);
    624         if (fd < 0) fd = open(ops[i], O_WRONLY | O_NONBLOCK);
    625         if (fd < 0) { perr("error opening '%s'", ops[i]); st = 1; continue; }
    626         if ((fs ? syncfs(fd) : data ? fdatasync(fd) : fsync(fd)) < 0) { perr("error syncing '%s'", ops[i]); st = 1; }
    627         close(fd);
    628     }
    629     return st;
    630 }
    631 
    632 /* ---- uname arch hostname ---- */
    633 
    634 static int t_uname(int argc, char **argv)
    635 {
    636     static const struct opt lo[] = {
    637         { "all", 0, 'a' }, { "kernel-name", 0, 's' }, { "nodename", 0, 'n' }, { "kernel-release", 0, 'r' },
    638         { "kernel-version", 0, 'v' }, { "machine", 0, 'm' }, { "processor", 0, 'p' },
    639         { "hardware-platform", 0, 'i' }, { "operating-system", 0, 'o' }, { NULL, 0, 0 } };
    640     struct utsname u;
    641     int c, all = 0, s = 0, n = 0, r = 0, v = 0, m = 0, p = 0, hw = 0, o = 0, any, first = 1;
    642     opts_reset();
    643     if (!strcmp(prog, "arch")) { m = 1; while ((c = getopts(argc, argv, "", NULL))) ; if (nops) extra_operand(ops[0]); }
    644     else {
    645         while ((c = getopts(argc, argv, "asnrvmpio", lo)))
    646             switch (c) {
    647             case 'a': all = 1; break; case 's': s = 1; break; case 'n': n = 1; break; case 'r': r = 1; break;
    648             case 'v': v = 1; break; case 'm': m = 1; break; case 'p': p = 1; break; case 'i': hw = 1; break;
    649             case 'o': o = 1; break;
    650             }
    651         if (nops) extra_operand(ops[0]);
    652         if (all) s = n = r = v = m = o = 1;
    653         any = s | n | r | v | m | p | hw | o;
    654         if (!any) s = 1;
    655     }
    656     if (uname(&u) < 0) { perr("cannot get system name"); return 1; }
    657 #define PUT(flag, str) if (flag) { if (!first) putchar(' '); fputs(str, stdout); first = 0; }
    658     PUT(s, u.sysname) PUT(n, u.nodename) PUT(r, u.release) PUT(v, u.version) PUT(m, u.machine)
    659     PUT(p, "unknown") PUT(hw, "unknown") PUT(o, "Linux")
    660     putchar('\n');
    661     return finish_stdout();
    662 }
    663 
    664 static int t_hostname(int argc, char **argv)
    665 {
    666     struct utsname u;
    667     int c;
    668     opts_reset();
    669     while ((c = getopts(argc, argv, "", NULL))) ;
    670     if (nops > 1) extra_operand(ops[1]);
    671     if (nops == 1) {
    672         if (sethostname(ops[0], strlen(ops[0])) < 0) { perr("cannot set name to '%s'", ops[0]); return 1; }
    673         return 0;
    674     }
    675     if (uname(&u) < 0) { perr("cannot determine hostname"); return 1; }
    676     puts(u.nodename);
    677     return finish_stdout();
    678 }
    679 
    680 /* ---- printenv env ---- */
    681 
    682 static int t_printenv(int argc, char **argv)
    683 {
    684     static const struct opt lo[] = { { "null", 0, '0' }, { NULL, 0, 0 } };
    685     int c, nul = 0, i, st = 0;
    686     char **e;
    687     opts_reset();
    688     while ((c = getopts(argc, argv, "0", lo))) nul = 1;
    689     if (!nops) {
    690         for (e = environ; e && *e; e++) { fputs(*e, stdout); putchar(nul ? 0 : '\n'); }
    691         return finish_stdout();
    692     }
    693     for (i = 0; i < nops; i++) {
    694         char *v = strchr(ops[i], '=') ? NULL : getenv(ops[i]);
    695         if (!v) { st = 1; continue; }
    696         fputs(v, stdout); putchar(nul ? 0 : '\n');
    697     }
    698     return finish_stdout() ? 2 : st;
    699 }
    700 
    701 static int t_env(int argc, char **argv)
    702 {
    703     static const struct opt lo[] = {
    704         { "ignore-environment", 0, 'i' }, { "unset", 1, 'u' }, { "null", 0, '0' }, { "chdir", 1, 'C' }, { NULL, 0, 0 } };
    705     int c, nul = 0, i;
    706     const char *dir = NULL;
    707     usage_status = 125;
    708     opts_reset();
    709     for (i = 1; i < argc && !strcmp(argv[i], "-"); i++) argv[i] = "-i";
    710     while ((c = getopts(argc, argv, "+iu:0C:", lo)))
    711         switch (c) {
    712         case 'i': clearenv(); break;
    713         case 'u': unsetenv(optarg); break;
    714         case '0': nul = 1; break;
    715         case 'C': dir = optarg; break;
    716         }
    717     for (i = 0; i < nops && strchr(ops[i], '=') && ops[i][0] != '='; i++)
    718         if (putenv(ops[i]) < 0) die(125, "cannot set '%s'", ops[i]);
    719     if (i == nops) {
    720         char **e;
    721         if (dir && chdir(dir) < 0) { perr("cannot change directory to '%s'", dir); return 125; }
    722         for (e = environ; e && *e; e++) { fputs(*e, stdout); putchar(nul ? 0 : '\n'); }
    723         return finish_stdout();
    724     }
    725     if (nul) { say("cannot specify --null (-0) with command"); usage_error(); }
    726     if (dir && chdir(dir) < 0) { perr("cannot change directory to '%s'", dir); return 125; }
    727     fflush(stdout);
    728     execvp(ops[i], ops + i);
    729     perr("'%s'", ops[i]);
    730     return errno == ENOENT ? 127 : 126;
    731 }
    732 
    733 /* ---- link unlink ---- */
    734 
    735 static int t_link(int argc, char **argv)
    736 {
    737     int c;
    738     opts_reset();
    739     while ((c = getopts(argc, argv, "", NULL))) ;
    740     if (nops < 1) missing_operand();
    741     if (nops < 2) { say("missing operand after '%s'", ops[0]); usage_error(); }
    742     if (nops > 2) extra_operand(ops[2]);
    743     if (link(ops[0], ops[1]) < 0) { perr("cannot create link '%s' to '%s'", ops[1], ops[0]); return 1; }
    744     return 0;
    745 }
    746 
    747 static int t_unlink(int argc, char **argv)
    748 {
    749     int c;
    750     opts_reset();
    751     while ((c = getopts(argc, argv, "", NULL))) ;
    752     if (nops < 1) missing_operand();
    753     if (nops > 1) extra_operand(ops[1]);
    754     if (unlink(ops[0]) < 0) { perr("cannot unlink '%s'", ops[0]); return 1; }
    755     return 0;
    756 }
    757 
    758 /* ---- tty nproc whoami logname hostid ---- */
    759 
    760 static int t_tty(int argc, char **argv)
    761 {
    762     static const struct opt lo[] = { { "silent", 0, 's' }, { "quiet", 0, 's' }, { NULL, 0, 0 } };
    763     int c, silent = 0;
    764     char name[PATH_MAX];
    765     ssize_t n;
    766     usage_status = 2;
    767     opts_reset();
    768     while ((c = getopts(argc, argv, "s", lo))) silent = 1;
    769     if (nops) extra_operand(ops[0]);
    770     if (isatty(0) && (n = readlink("/proc/self/fd/0", name, sizeof name - 1)) > 0) {
    771         name[n] = 0;
    772         if (!silent) puts(name);
    773         return finish_stdout() ? 3 : 0;
    774     }
    775     if (!silent) puts("not a tty");
    776     return finish_stdout() ? 3 : 1;
    777 }
    778 
    779 static unsigned long omp_value(const char *name)
    780 {
    781     const char *s = getenv(name);
    782     unsigned long v = 0;
    783     char *end;
    784     if (!s) return 0;
    785     v = strtoul(s, &end, 10);
    786     return end != s && (*end == 0 || *end == ',') ? v : 0;
    787 }
    788 
    789 static int t_nproc(int argc, char **argv)
    790 {
    791     static const struct opt lo[] = { { "all", 0, 'a' }, { "ignore", 1, 'i' }, { NULL, 0, 0 } };
    792     int c, all = 0;
    793     unsigned long ignore = 0, n = 0;
    794     opts_reset();
    795     while ((c = getopts(argc, argv, "", lo)))
    796         switch (c) {
    797         case 'a': all = 1; break;
    798         case 'i': if (!parse_ulong(optarg, &ignore)) die(1, "invalid number: '%s'", optarg); break;
    799         }
    800     if (nops) extra_operand(ops[0]);
    801     if (all) {
    802         DIR *d = opendir("/sys/devices/system/cpu");
    803         struct dirent *e;
    804         if (d) {
    805             while ((e = readdir(d)))
    806                 if (!strncmp(e->d_name, "cpu", 3) && isdigit((unsigned char)e->d_name[3])) n++;
    807             closedir(d);
    808         }
    809     }
    810     if (!n) {
    811         unsigned long mask[16], limit;
    812         int i;
    813         if (!all && (n = omp_value("OMP_NUM_THREADS"))) goto done;
    814         memset(mask, 0, sizeof mask);
    815         if (sched_getaffinity(0, sizeof mask, mask) < 0) n = 1;
    816         else for (i = 0; i < 16; i++) n += __builtin_popcountl(mask[i]);
    817         if (!all && (limit = omp_value("OMP_THREAD_LIMIT")) && limit < n) n = limit;
    818         if (!n) n = 1;
    819     }
    820 done:
    821     n = ignore < n ? n - ignore : 1;
    822     printf("%lu\n", n);
    823     return finish_stdout();
    824 }
    825 
    826 static int t_whoami(int argc, char **argv)
    827 {
    828     int c;
    829     struct passwd *p;
    830     opts_reset();
    831     while ((c = getopts(argc, argv, "", NULL))) ;
    832     if (nops) extra_operand(ops[0]);
    833     if (!(p = getpwuid(geteuid()))) die(1, "cannot find name for user ID %u", geteuid());
    834     puts(p->pw_name);
    835     return finish_stdout();
    836 }
    837 
    838 static int t_logname(int argc, char **argv)
    839 {
    840     int c;
    841     char buf[32];
    842     ssize_t n;
    843     int fd;
    844     unsigned long uid;
    845     opts_reset();
    846     while ((c = getopts(argc, argv, "", NULL))) ;
    847     if (nops) extra_operand(ops[0]);
    848     fd = open("/proc/self/loginuid", O_RDONLY);
    849     n = fd < 0 ? -1 : read(fd, buf, sizeof buf - 1);
    850     if (fd >= 0) close(fd);
    851     if (n > 0) {
    852         buf[n] = 0;
    853         if (parse_ulong(buf, &uid) || (buf[n - 1] == '\n' && (buf[n - 1] = 0, parse_ulong(buf, &uid))))
    854             if (uid != 4294967295UL && getpwuid(uid)) { puts(getpwuid(uid)->pw_name); return finish_stdout(); }
    855     }
    856     die(1, "no login name");
    857 }
    858 
    859 static int t_hostid(int argc, char **argv)
    860 {
    861     int c;
    862     unsigned id = 0;
    863     int fd;
    864     opts_reset();
    865     while ((c = getopts(argc, argv, "", NULL))) ;
    866     if (nops) extra_operand(ops[0]);
    867     fd = open("/etc/hostid", O_RDONLY);
    868     if (fd >= 0 && read(fd, &id, 4) == 4) { close(fd); }
    869     else {
    870         /* like glibc without /etc/hostid: our name's IPv4 address from /etc/hosts, halves swapped */
    871         struct utsname u; FILE *f; char line[1024];
    872         if (fd >= 0) close(fd);
    873         id = 0;
    874         if (uname(&u) == 0 && (f = fopen("/etc/hosts", "r"))) {
    875             while (fgets(line, sizeof line, f)) {
    876                 char *p = line, *tok, *ip = NULL, *hash = strchr(line, '#');
    877                 int idx = 0, hit = 0;
    878                 if (hash) *hash = 0;
    879                 while ((tok = strtok_r_simple(&p))) {
    880                     if (idx++ == 0) { ip = tok; continue; }
    881                     if (!strcasecmp(tok, u.nodename)) hit = 1;
    882                 }
    883                 if (hit && ip) {
    884                     unsigned b[4] = { 0 }; int k = 0; char *q = ip;
    885                     for (; *q && k < 4; q++) { if (*q == '.') k++; else if (isdigit((unsigned char)*q)) b[k] = b[k] * 10 + *q - '0'; else { k = 9; break; } }
    886                     if (k == 3) { unsigned ipn = b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24; id = ipn << 16 | ipn >> 16; break; }
    887                 }
    888             }
    889             fclose(f);
    890         }
    891     }
    892     printf("%08x\n", id);
    893     return finish_stdout();
    894 }
    895 
    896 /* ---- sizes, inputs, paths, dates ---- */
    897 
    898 /* 10, 4K, 2M, 1kB: a number with the size suffixes the GNU tools take */
    899 static int parse_size(const char *s, unsigned long long *out)
    900 {
    901     char *end;
    902     unsigned long long v, mult = 1;
    903     errno = 0;
    904     if (!isdigit((unsigned char)*s)) return 0;
    905     v = strtoull(s, &end, 10);
    906     if (errno == ERANGE) return 0;
    907     if (*end) {
    908         static const struct { const char *s; unsigned long long m; } suf[] = {
    909             { "b", 512 }, { "kB", 1000 }, { "KB", 1000 }, { "K", 1024 }, { "KiB", 1024 }, { "k", 1024 },
    910             { "MB", 1000000ULL }, { "M", 1ULL << 20 }, { "MiB", 1ULL << 20 },
    911             { "GB", 1000000000ULL }, { "G", 1ULL << 30 }, { "GiB", 1ULL << 30 },
    912             { "TB", 1000000000000ULL }, { "T", 1ULL << 40 }, { "TiB", 1ULL << 40 },
    913             { "PB", 1000000000000000ULL }, { "P", 1ULL << 50 }, { "PiB", 1ULL << 50 },
    914             { "EB", 1000000000000000000ULL }, { "E", 1ULL << 60 }, { "EiB", 1ULL << 60 }, { NULL, 0 } };
    915         int i;
    916         for (i = 0; suf[i].s; i++) if (!strcmp(end, suf[i].s)) { mult = suf[i].m; break; }
    917         if (!suf[i].s) return 0;
    918     }
    919     if (mult > 1 && v > ~0ULL / mult) { *out = ~0ULL; return 1; }
    920     *out = v * mult;
    921     return 1;
    922 }
    923 
    924 /* the rest of fd in one block, with a NUL after it */
    925 static int read_all(int fd, char **buf, size_t *len)
    926 {
    927     size_t cap = 65536, n = 0;
    928     char *b = xmalloc(cap + 1);
    929     for (;;) {
    930         ssize_t r;
    931         if (n == cap) { cap *= 2; b = xrealloc(b, cap + 1); }
    932         r = read(fd, b + n, cap - n);
    933         if (r < 0) { if (errno == EINTR) continue; free(b); return -1; }
    934         if (!r) break;
    935         n += r;
    936     }
    937     b[n] = 0;
    938     *buf = b; *len = n;
    939     return 0;
    940 }
    941 static int open_input(const char *name) { return strcmp(name, "-") ? open(name, O_RDONLY) : 0; }
    942 
    943 /* . and .. resolved and symlinks followed. CAN_EXISTING is readlink -e, CAN_ALL_BUT_LAST is -f, CAN_MISSING is -m */
    944 #define CAN_EXISTING 0
    945 #define CAN_ALL_BUT_LAST 1
    946 #define CAN_MISSING 2
    947 static char *canonicalize(const char *path, int mode, int nolinks)
    948 {
    949     char *dest = xmalloc(PATH_MAX + 2), *rest = xstrdup(path), *p;
    950     size_t n = 0;               /* used part of dest. no slash at the end, n 0 is the root */
    951     int links = 0;
    952     dest[0] = 0;
    953     if (path[0] != '/') {
    954         if (!getcwd(dest, PATH_MAX)) goto fail;
    955         n = strlen(dest);
    956         if (n == 1) n = 0;
    957         dest[n] = 0;
    958     }
    959     p = rest;
    960     for (;;) {
    961         char *seg, *q;
    962         size_t l;
    963         int last;
    964         struct stat sb;
    965         while (*p == '/') p++;
    966         if (!*p) break;
    967         seg = p;
    968         while (*p && *p != '/') p++;
    969         l = p - seg;
    970         if (l == 1 && seg[0] == '.') continue;
    971         if (l == 2 && seg[0] == '.' && seg[1] == '.') { while (n && dest[n - 1] != '/') n--; if (n) n--; dest[n] = 0; continue; }
    972         if (n + l + 2 > PATH_MAX) { errno = ENAMETOOLONG; goto fail; }
    973         dest[n++] = '/'; memcpy(dest + n, seg, l); n += l; dest[n] = 0;
    974         for (q = p; *q == '/'; q++) ;
    975         last = !*q;
    976         if (nolinks) continue;
    977         if (lstat(dest, &sb) < 0) {
    978             if (errno == ENOENT && (mode == CAN_MISSING || (mode == CAN_ALL_BUT_LAST && last))) continue;
    979             goto fail;
    980         }
    981         if (S_ISLNK(sb.st_mode)) {
    982             char target[PATH_MAX], *nr;
    983             ssize_t k;
    984             if (++links > 40) { errno = ELOOP; goto fail; }
    985             if ((k = readlink(dest, target, sizeof target - 1)) < 0) goto fail;
    986             target[k] = 0;
    987             n -= l + 1; dest[n] = 0;
    988             if (target[0] == '/') { n = 0; dest[0] = 0; }
    989             nr = xmalloc(strlen(target) + strlen(p) + 2);
    990             strcpy(nr, target); strcat(nr, "/"); strcat(nr, p);
    991             free(rest); rest = nr; p = rest;
    992         } else if (!S_ISDIR(sb.st_mode) && !last) { errno = ENOTDIR; goto fail; }
    993     }
    994     if (!n) { dest[0] = '/'; dest[1] = 0; }
    995     free(rest);
    996     return dest;
    997 fail:
    998     free(dest); free(rest);
    999     return NULL;
   1000 }
   1001 
   1002 /* `to` as seen from the directory `from`, both canonical */
   1003 static char *relative_path(const char *from, const char *to)
   1004 {
   1005     char *r = xmalloc(strlen(from) * 3 + strlen(to) + 8);
   1006     const char *f = from, *t = to;
   1007     size_t n = 0;
   1008     for (;;) {
   1009         const char *fe, *te;
   1010         while (*f == '/') f++;
   1011         while (*t == '/') t++;
   1012         for (fe = f; *fe && *fe != '/'; fe++) ;
   1013         for (te = t; *te && *te != '/'; te++) ;
   1014         if (fe == f || te == t || fe - f != te - t || memcmp(f, t, fe - f)) break;
   1015         f = fe; t = te;
   1016     }
   1017     for (;;) {
   1018         while (*f == '/') f++;
   1019         if (!*f) break;
   1020         memcpy(r + n, "../", 3); n += 3;
   1021         while (*f && *f != '/') f++;
   1022     }
   1023     while (*t == '/') t++;
   1024     strcpy(r + n, t);
   1025     n = strlen(r);
   1026     if (n > 1 && r[n - 1] == '/') r[n - 1] = 0;
   1027     if (!r[0]) strcpy(r, ".");
   1028     return r;
   1029 }
   1030 
   1031 /* @SECONDS, 2024-01-31, 2024-01-31 10:20[:30[.123]], now, today, yesterday, tomorrow, "3 days ago", "+2 hours".
   1032  * UTC until rifle reads TZ. 0 on success */
   1033 static int parse_date(const char *s, struct timespec *ts)
   1034 {
   1035     struct timespec now;
   1036     struct tm t;
   1037     long y, mo, d, h = 0, mi = 0, sec = 0;
   1038     long nsec = 0;
   1039     const char *p = s;
   1040     clock_gettime(0, &now);
   1041     while (*p == ' ') p++;
   1042     if (*p == '@') {
   1043         char *end; long long v = strtoll(p + 1, &end, 10);
   1044         if (end == p + 1) return -1;
   1045         ts->tv_sec = v; ts->tv_nsec = 0;
   1046         if (*end == '.') { long f = 0, digits = 0; end++; while (isdigit((unsigned char)*end)) { if (digits < 9) { f = f * 10 + *end - '0'; digits++; } end++; } while (digits++ < 9) f *= 10; ts->tv_nsec = f; }
   1047         return *end ? -1 : 0;
   1048     }
   1049     ts->tv_sec = now.tv_sec; ts->tv_nsec = now.tv_nsec;
   1050     if (!*p) return 0;
   1051     if (isdigit((unsigned char)*p)) {
   1052         char *end;
   1053         y = strtol(p, &end, 10);
   1054         if (end - p == 4 && *end == '-') {
   1055             p = end + 1; mo = strtol(p, &end, 10);
   1056             if (*end != '-' || end == p) return -1;
   1057             p = end + 1; d = strtol(p, &end, 10);
   1058             if (end == p) return -1;
   1059             p = end;
   1060             if (*p == ' ' || *p == 'T') {
   1061                 p++;
   1062                 h = strtol(p, &end, 10);
   1063                 if (*end != ':' || end == p) return -1;
   1064                 p = end + 1; mi = strtol(p, &end, 10);
   1065                 if (end == p) return -1;
   1066                 p = end;
   1067                 if (*p == ':') { p++; sec = strtol(p, &end, 10); if (end == p) return -1; p = end; }
   1068                 if (*p == '.' || *p == ',') { long f = 0, digits = 0; p++; while (isdigit((unsigned char)*p)) { if (digits < 9) { f = f * 10 + *p - '0'; digits++; } p++; } while (digits++ < 9) f *= 10; nsec = f; }
   1069             }
   1070             if (*p == 'Z') p++;
   1071             while (*p == ' ') p++;
   1072             if (*p) return -1;
   1073             if (mo < 1 || mo > 12 || d < 1 || d > 31 || h > 24 || mi > 59 || sec > 61) return -1;
   1074             memset(&t, 0, sizeof t);
   1075             t.tm_year = y - 1900; t.tm_mon = mo - 1; t.tm_mday = d; t.tm_hour = h; t.tm_min = mi; t.tm_sec = sec;
   1076             ts->tv_sec = timegm(&t); ts->tv_nsec = nsec;
   1077             return 0;
   1078         }
   1079     }
   1080     {
   1081         char word[64];
   1082         long total = 0;
   1083         int sign = 1, any = 0;
   1084         while (*p) {
   1085             char *end;
   1086             long n;
   1087             int i = 0;
   1088             while (*p == ' ') p++;
   1089             if (!*p) break;
   1090             if (*p == '+' || *p == '-' || isdigit((unsigned char)*p)) {
   1091                 sign = *p == '-' ? -1 : 1;
   1092                 if (*p == '+' || *p == '-') p++;
   1093                 n = strtol(p, &end, 10);
   1094                 if (end == p) return -1;
   1095                 p = end;
   1096                 while (*p == ' ') p++;
   1097                 while (isalpha((unsigned char)*p) && i < 63) word[i++] = tolower(*p++);
   1098                 word[i] = 0;
   1099                 if (!strncmp(word, "sec", 3) || !strcmp(word, "s")) total += sign * n;
   1100                 else if (!strncmp(word, "min", 3)) total += sign * n * 60;
   1101                 else if (!strncmp(word, "hour", 4) || !strcmp(word, "h")) total += sign * n * 3600;
   1102                 else if (!strncmp(word, "day", 3)) total += sign * n * 86400;
   1103                 else if (!strncmp(word, "week", 4)) total += sign * n * 7 * 86400;
   1104                 else return -1;
   1105                 any = 1;
   1106                 continue;
   1107             }
   1108             while (isalpha((unsigned char)*p) && i < 63) word[i++] = tolower(*p++);
   1109             word[i] = 0;
   1110             if (!word[0]) return -1;
   1111             if (!strcmp(word, "now") || !strcmp(word, "today")) { if (word[0] == 't') ts->tv_sec -= ts->tv_sec % 86400; }
   1112             else if (!strcmp(word, "yesterday")) total -= 86400;
   1113             else if (!strcmp(word, "tomorrow")) total += 86400;
   1114             else if (!strcmp(word, "ago")) total = -total;
   1115             else return -1;
   1116             any = 1;
   1117         }
   1118         if (!any) return -1;
   1119         ts->tv_sec += total;
   1120         return 0;
   1121     }
   1122 }
   1123 
   1124 /* ---- walking trees ----
   1125  * children first, then the directory, so chmod -R 000 works */
   1126 
   1127 typedef int (*visit_fn)(const char *path, const struct stat *st, void *ctx);
   1128 
   1129 static int walk(const char *path, int top, int follow_top, int follow_all, int recurse, visit_fn fn, void *ctx)
   1130 {
   1131     struct stat st;
   1132     int follow = top ? follow_top : follow_all, bad = 0;
   1133     if ((follow ? stat(path, &st) : lstat(path, &st)) < 0) {
   1134         perr("cannot access '%s'", path);
   1135         return 1;
   1136     }
   1137     if (recurse && S_ISDIR(st.st_mode)) {
   1138         DIR *d = opendir(path);
   1139         if (!d) { perr("cannot read directory '%s'", path); bad = 1; }
   1140         else {
   1141             struct dirent *e;
   1142             char **names = NULL; int n = 0, cap = 0, i;
   1143             while ((e = readdir(d))) {
   1144                 if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
   1145                 if (n == cap) { cap = cap ? cap * 2 : 32; names = xrealloc(names, cap * sizeof *names); }
   1146                 names[n++] = xstrdup(e->d_name);
   1147             }
   1148             closedir(d);
   1149             for (i = 0; i < n; i++) {
   1150                 size_t pl = strlen(path);
   1151                 char *child = xmalloc(pl + strlen(names[i]) + 2);
   1152                 memcpy(child, path, pl);
   1153                 if (pl && path[pl - 1] != '/') child[pl++] = '/';
   1154                 strcpy(child + pl, names[i]);
   1155                 bad |= walk(child, 0, follow_top, follow_all, recurse, fn, ctx);
   1156                 free(child); free(names[i]);
   1157             }
   1158             free(names);
   1159         }
   1160     }
   1161     return bad | fn(path, &st, ctx);
   1162 }
   1163 
   1164 /* ---- mkdir rmdir ---- */
   1165 
   1166 static int t_mkdir(int argc, char **argv)
   1167 {
   1168     static const struct opt lo[] = {
   1169         { "mode", 1, 'm' }, { "parents", 0, 'p' }, { "verbose", 0, 'v' }, { "context", 2, 'Z' }, { NULL, 0, 0 } };
   1170     int c, parents = 0, verbose = 0, i, st = 0;
   1171     struct change *change = NULL;
   1172     mode_t um = current_umask(), mode = 0777;
   1173     opts_reset();
   1174     while ((c = getopts(argc, argv, "m:pvZ", lo)))
   1175         switch (c) {
   1176         case 'm': if (!(change = mode_compile(optarg))) die(1, "invalid mode '%s'", optarg); break;
   1177         case 'p': parents = 1; break;
   1178         case 'v': verbose = 1; break;
   1179         default: break;
   1180         }
   1181     if (!nops) missing_operand();
   1182     if (change) mode = mode_apply(0777 & ~um, 1, um, change);
   1183     for (i = 0; i < nops; i++) {
   1184         char *path = xstrdup(ops[i]), *p;
   1185         struct stat sb;
   1186         if (parents) {
   1187             /* parents get the umask's mode plus u+wx so we can go on into them */
   1188             for (p = path; *p == '/'; p++) ;
   1189             for (; *p; p++) {
   1190                 if (*p != '/') continue;
   1191                 *p = 0;
   1192                 if (stat(path, &sb) < 0 && errno == ENOENT) {
   1193                     if (mkdir(path, (0777 & ~um) | S_IWUSR | S_IXUSR) < 0) {
   1194                         if (errno != EEXIST || stat(path, &sb) < 0 || !S_ISDIR(sb.st_mode)) { perr("cannot create directory '%s'", path); st = 1; goto next; }
   1195                     } else if (verbose) printf("%s: created directory '%s'\n", prog, path);
   1196                 }
   1197                 *p = '/';
   1198                 while (p[1] == '/') p++;
   1199             }
   1200             if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) goto next;
   1201         }
   1202         if (change) umask(0);
   1203         if (mkdir(path, change ? (mode & 0777) : 0777) < 0) {
   1204             if (change) umask(um);
   1205             if (parents && errno == EEXIST && stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) goto next; /* someone else made it meanwhile */
   1206             perr("cannot create directory '%s'", path); st = 1; goto next;
   1207         }
   1208         if (change) {
   1209             umask(um);
   1210             if (mode & ~0777) chmod(path, mode);
   1211         }
   1212         if (verbose) printf("%s: created directory '%s'\n", prog, path);
   1213 next:
   1214         free(path);
   1215     }
   1216     return finish_stdout() ? 1 : st;
   1217 }
   1218 
   1219 static int t_rmdir(int argc, char **argv)
   1220 {
   1221     static const struct opt lo[] = {
   1222         { "ignore-fail-on-non-empty", 0, 'I' }, { "parents", 0, 'p' }, { "verbose", 0, 'v' }, { NULL, 0, 0 } };
   1223     int c, ignore = 0, parents = 0, verbose = 0, i, st = 0;
   1224     opts_reset();
   1225     while ((c = getopts(argc, argv, "pv", lo))) { if (c == 'I') ignore = 1; else if (c == 'p') parents = 1; else verbose = 1; }
   1226     if (!nops) missing_operand();
   1227     for (i = 0; i < nops; i++) {
   1228         char *dir = xstrdup(ops[i]);
   1229         int first = 1;
   1230         for (;;) {
   1231             char *slash;
   1232             if (verbose) printf("%s: removing directory, '%s'\n", prog, dir);
   1233             if (rmdir(dir) < 0) {
   1234                 if (ignore && (errno == ENOTEMPTY || errno == EEXIST)) break;
   1235                 if (first) perr("failed to remove '%s'", dir); else perr("failed to remove directory '%s'", dir);
   1236                 st = 1;
   1237                 break;
   1238             }
   1239             if (!parents) break;
   1240             first = 0;
   1241             slash = dir + strlen(dir);
   1242             while (slash > dir && slash[-1] == '/') slash--;
   1243             while (slash > dir && slash[-1] != '/') slash--;
   1244             while (slash > dir && slash[-1] == '/') slash--;
   1245             if (slash == dir) break;
   1246             *slash = 0;
   1247         }
   1248         free(dir);
   1249     }
   1250     return finish_stdout() ? 1 : st;
   1251 }
   1252 
   1253 /* ---- rm ---- */
   1254 
   1255 struct rm_opts { int force, ask, recursive, dir, verbose; };
   1256 
   1257 static int rm_confirm(const char *what, const char *path)
   1258 {
   1259     char line[16];
   1260     fflush(stdout);
   1261     fprintf(stderr, "%s: remove %s '%s'? ", prog, what, path);
   1262     if (!fgets(line, sizeof line, stdin)) return 0;
   1263     return line[0] == 'y' || line[0] == 'Y';
   1264 }
   1265 
   1266 static int rm_entry(int dfd, const char *name, const char *path, const struct rm_opts *o)
   1267 {
   1268     struct stat st;
   1269     if (fstatat(dfd, name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
   1270         if (o->force && errno == ENOENT) return 0;
   1271         perr("cannot remove '%s'", path);
   1272         return 1;
   1273     }
   1274     if (S_ISDIR(st.st_mode)) {
   1275         if (!o->recursive) {
   1276             if (!o->dir) { say("cannot remove '%s': Is a directory", path); return 1; }
   1277             if (o->ask && !rm_confirm("directory", path)) return 0;
   1278             if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) { perr("cannot remove '%s'", path); return 1; }
   1279             if (o->verbose) printf("removed directory '%s'\n", path);
   1280             return 0;
   1281         } else {
   1282             int fd, bad = 0, n = 0, cap = 0, i;
   1283             DIR *d;
   1284             struct dirent *e;
   1285             char **names = NULL;
   1286             if (o->ask && !rm_confirm("directory", path)) return 0;
   1287             fd = openat(dfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
   1288             if (fd < 0 || !(d = fdopendir(fd))) { perr("cannot remove '%s'", path); if (fd >= 0) close(fd); return 1; }
   1289             while ((e = readdir(d))) {
   1290                 if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
   1291                 if (n == cap) { cap = cap ? cap * 2 : 32; names = xrealloc(names, cap * sizeof *names); }
   1292                 names[n++] = xstrdup(e->d_name);
   1293             }
   1294             for (i = 0; i < n; i++) {
   1295                 size_t pl = strlen(path);
   1296                 char *child = xmalloc(pl + strlen(names[i]) + 2);
   1297                 memcpy(child, path, pl);
   1298                 if (pl && path[pl - 1] != '/') child[pl++] = '/';
   1299                 strcpy(child + pl, names[i]);
   1300                 bad |= rm_entry(dirfd(d), names[i], child, o);
   1301                 free(child); free(names[i]);
   1302             }
   1303             free(names);
   1304             closedir(d);
   1305             if (bad) return 1;
   1306             if (unlinkat(dfd, name, AT_REMOVEDIR) < 0) { perr("cannot remove '%s'", path); return 1; }
   1307             if (o->verbose) printf("removed directory '%s'\n", path);
   1308             return 0;
   1309         }
   1310     }
   1311     if (o->ask && !rm_confirm(S_ISLNK(st.st_mode) ? "symbolic link" : st.st_size ? "regular file" : "regular empty file", path))
   1312         return 0;
   1313     if (unlinkat(dfd, name, 0) < 0) { perr("cannot remove '%s'", path); return 1; }
   1314     if (o->verbose) printf("removed '%s'\n", path);
   1315     return 0;
   1316 }
   1317 
   1318 static int t_rm(int argc, char **argv)
   1319 {
   1320     static const struct opt lo[] = {
   1321         { "force", 0, 'f' }, { "interactive", 2, 'i' }, { "recursive", 0, 'r' }, { "dir", 0, 'd' }, { "verbose", 0, 'v' },
   1322         { "preserve-root", 2, 'P' }, { "no-preserve-root", 0, 'N' }, { "one-file-system", 0, 'x' }, { NULL, 0, 0 } };
   1323     struct rm_opts o = { 0, 0, 0, 0, 0 };
   1324     int c, preserve_root = 1, i, st = 0;
   1325     opts_reset();
   1326     while ((c = getopts(argc, argv, "fiIrRdv", lo)))
   1327         switch (c) {
   1328         case 'f': o.force = 1; o.ask = 0; break;
   1329         case 'i': o.ask = !(optarg && (!strcmp(optarg, "never") || !strcmp(optarg, "no") || !strcmp(optarg, "none"))); o.force = 0; break;
   1330         case 'I': break;
   1331         case 'r': case 'R': o.recursive = 1; break;
   1332         case 'd': o.dir = 1; break;
   1333         case 'v': o.verbose = 1; break;
   1334         case 'P': preserve_root = 1; break;
   1335         case 'N': preserve_root = 0; break;
   1336         default: break;
   1337         }
   1338     if (!nops) { if (o.force) return 0; missing_operand(); }
   1339     for (i = 0; i < nops; i++) {
   1340         const char *path = ops[i], *b = base_of(path);
   1341         /* the root check comes before anything is touched */
   1342         if (o.recursive && preserve_root) {
   1343             struct stat a, r;
   1344             if (stat(path, &a) == 0 && stat("/", &r) == 0 && a.st_dev == r.st_dev && a.st_ino == r.st_ino) {
   1345                 say("it is dangerous to operate recursively on '%s'", path);
   1346                 say("use --no-preserve-root to override this failsafe");
   1347                 st = 1; continue;
   1348             }
   1349         }
   1350         if (o.recursive && (!strcmp(b, ".") || !strcmp(b, ".."))) {
   1351             say("refusing to remove '.' or '..' directory: skipping '%s'", path);
   1352             st = 1; continue;
   1353         }
   1354         st |= rm_entry(AT_FDCWD, path, path, &o);
   1355     }
   1356     return finish_stdout() ? 1 : st;
   1357 }
   1358 
   1359 /* ---- chmod chown chgrp ---- */
   1360 
   1361 struct chmod_ctx { const struct change *change; int verbose, changes_only, quiet; mode_t um; };
   1362 
   1363 static int chmod_visit(const char *path, const struct stat *st, void *v)
   1364 {
   1365     struct chmod_ctx *x = v;
   1366     mode_t old = st->st_mode & MODE_BITS, new;
   1367     char a[10], b[10];
   1368     if (S_ISLNK(st->st_mode)) return 0;
   1369     new = mode_apply(st->st_mode, S_ISDIR(st->st_mode), x->um, x->change) & MODE_BITS;
   1370     if (chmod(path, new) < 0) {
   1371         if (!x->quiet) perr("changing permissions of '%s'", path);
   1372         return 1;
   1373     }
   1374     if (x->verbose || x->changes_only) {
   1375         mode_string(old, a); mode_string(new, b);
   1376         if (new != old) printf("mode of '%s' changed from %04o (%s) to %04o (%s)\n", path, old, a, new, b);
   1377         else if (x->verbose) printf("mode of '%s' retained as %04o (%s)\n", path, old, a);
   1378     }
   1379     return 0;
   1380 }
   1381 
   1382 static int t_chmod(int argc, char **argv)
   1383 {
   1384     struct chmod_ctx x = { NULL, 0, 0, 0, 0 };
   1385     char *modestr = NULL, *reference = NULL;
   1386     char **files = xmalloc((argc + 1) * sizeof *files);
   1387     int nfiles = 0, i, recurse = 0, st = 0, ends = 0;
   1388     /* an argument starting with - that isn't an option is the mode: chmod -w f */
   1389     for (i = 1; i < argc; i++) {
   1390         char *a = argv[i];
   1391         if (ends || a[0] != '-' || !a[1]) {
   1392             if (!modestr && !reference) modestr = a; else files[nfiles++] = a;
   1393             continue;
   1394         }
   1395         if (!strcmp(a, "--")) { ends = 1; continue; }
   1396         if (a[1] == '-') {
   1397             if (!strcmp(a, "--recursive")) recurse = 1;
   1398             else if (!strcmp(a, "--verbose")) x.verbose = 1;
   1399             else if (!strcmp(a, "--changes")) x.changes_only = 1;
   1400             else if (!strcmp(a, "--silent") || !strcmp(a, "--quiet")) x.quiet = 1;
   1401             else if (!strncmp(a, "--reference=", 12)) reference = a + 12;
   1402             else if (!strcmp(a, "--reference") && i + 1 < argc) reference = argv[++i];
   1403             else if (!strcmp(a, "--no-preserve-root") || !strcmp(a, "--preserve-root")) ;
   1404             else if (!strcmp(a, "--help")) { print_usage(); return 0; }
   1405             else if (!strcmp(a, "--version")) { printf("chmod (rifle) " VERSION "\n"); return 0; }
   1406             else { say("unrecognized option '%s'", a); usage_error(); }
   1407             continue;
   1408         }
   1409         if (strchr("Rcfv", a[1])) {
   1410             int j;
   1411             for (j = 1; a[j]; j++) {
   1412                 if (a[j] == 'R') recurse = 1; else if (a[j] == 'c') x.changes_only = 1;
   1413                 else if (a[j] == 'f') x.quiet = 1; else if (a[j] == 'v') x.verbose = 1;
   1414                 else { say("invalid option -- '%c'", a[j]); usage_error(); }
   1415             }
   1416             continue;
   1417         }
   1418         if (!modestr && !reference) modestr = a; else files[nfiles++] = a;   /* -w, -x, -rw: it's the mode */
   1419     }
   1420     if (reference) {
   1421         struct stat rs; struct change *list;
   1422         if (stat(reference, &rs) < 0) die(1, "failed to get attributes of '%s': %s", reference, strerror(errno));
   1423         list = xmalloc(2 * sizeof *list);
   1424         list[0].op = '='; list[0].flag = MODE_ORDINARY; list[0].affected = MODE_BITS; list[0].value = rs.st_mode & MODE_BITS;
   1425         list[0].mentioned = MODE_BITS; list[1].op = 0;
   1426         x.change = list;
   1427         if (modestr) files[nfiles++] = modestr;
   1428     } else {
   1429         if (!modestr) missing_operand();
   1430         if (!(x.change = mode_compile(modestr))) { say("invalid mode: '%s'", modestr); usage_error(); }
   1431     }
   1432     if (!nfiles) { if (reference) missing_operand(); say("missing operand after '%s'", modestr); usage_error(); }
   1433     x.um = current_umask();
   1434     for (i = 0; i < nfiles; i++) st |= walk(files[i], 1, 1, 0, recurse, chmod_visit, &x);
   1435     return finish_stdout() ? 1 : st;
   1436 }
   1437 
   1438 struct chown_ctx {
   1439     int have_u, have_g, verbose, changes_only, quiet, deref;
   1440     uid_t u; gid_t g;
   1441     int from_u, from_g; uid_t fu; gid_t fg;
   1442 };
   1443 
   1444 static int chown_visit(const char *path, const struct stat *st, void *v)
   1445 {
   1446     struct chown_ctx *x = v;
   1447     uid_t nu = x->have_u ? x->u : st->st_uid;
   1448     gid_t ng = x->have_g ? x->g : st->st_gid;
   1449     int ch;
   1450     if (x->from_u && st->st_uid != x->fu) return 0;
   1451     if (x->from_g && st->st_gid != x->fg) return 0;
   1452     if ((S_ISLNK(st->st_mode) ? lchown(path, x->have_u ? x->u : (uid_t)-1, x->have_g ? x->g : (gid_t)-1)
   1453                               : chown(path, x->have_u ? x->u : (uid_t)-1, x->have_g ? x->g : (gid_t)-1)) < 0) {
   1454         if (!x->quiet) perr("changing ownership of '%s'", path);
   1455         return 1;
   1456     }
   1457     ch = nu != st->st_uid || ng != st->st_gid;
   1458     if (x->verbose || (x->changes_only && ch)) {
   1459         char old[100], new[100];
   1460         const char *what = x->have_u ? "ownership" : "group";
   1461         if (x->have_u && x->have_g) {
   1462             snprintf(old, sizeof old, "%s:%s", user_name(st->st_uid), group_name(st->st_gid));
   1463             snprintf(new, sizeof new, "%s:%s", user_name(nu), group_name(ng));
   1464         } else if (x->have_u) {
   1465             snprintf(old, sizeof old, "%s", user_name(st->st_uid)); snprintf(new, sizeof new, "%s", user_name(nu));
   1466         } else {
   1467             snprintf(old, sizeof old, "%s", group_name(st->st_gid)); snprintf(new, sizeof new, "%s", group_name(ng));
   1468         }
   1469         if (ch) printf("changed %s of '%s' from %s to %s\n", what, path, old, new);
   1470         else printf("%s of '%s' retained as %s\n", what, path, new);
   1471     }
   1472     return 0;
   1473 }
   1474 
   1475 /* "user", "user:group", "user:", ":group", or numbers. returns -1 after saying what was wrong */
   1476 static int parse_owner(const char *spec, struct chown_ctx *x, int group_only)
   1477 {
   1478     char *s = xstrdup(spec), *colon = group_only ? NULL : strchr(s, ':'), *g = NULL, *u = s;
   1479     if (group_only) g = s, u = NULL;
   1480     else if (!colon && strchr(s, '.') && lookup_user(s, &x->u) < 0) colon = strchr(s, '.');
   1481     if (colon) { *colon = 0; g = colon + 1; }
   1482     if (u && *u) {
   1483         if (lookup_user(u, &x->u) < 0) { say("invalid user: '%s'", spec); return -1; }
   1484         x->have_u = 1;
   1485     }
   1486     if (g && *g) {
   1487         if (lookup_group(g, &x->g) < 0) { say("invalid group: '%s'", spec); return -1; }
   1488         x->have_g = 1;
   1489     } else if (colon && x->have_u) {
   1490         struct passwd *p = getpwuid(x->u);
   1491         if (!p) { say("invalid spec: '%s'", spec); return -1; }
   1492         x->g = p->pw_gid; x->have_g = 1;
   1493     }
   1494     free(s);
   1495     return 0;
   1496 }
   1497 
   1498 static int t_chown(int argc, char **argv)
   1499 {
   1500     static const struct opt lo[] = {
   1501         { "recursive", 0, 'R' }, { "verbose", 0, 'v' }, { "changes", 0, 'c' }, { "silent", 0, 'f' }, { "quiet", 0, 'f' },
   1502         { "no-dereference", 0, 'h' }, { "dereference", 0, 'D' }, { "from", 1, 'F' }, { "reference", 1, 'r' },
   1503         { "preserve-root", 0, 'p' }, { "no-preserve-root", 0, 'n' }, { NULL, 0, 0 } };
   1504     struct chown_ctx x; int c, recurse = 0, follow_top = 0, follow_all = 0, deref = -1, i, st = 0, isgrp = !strcmp(prog, "chgrp");
   1505     const char *reference = NULL, *from = NULL;
   1506     memset(&x, 0, sizeof x);
   1507     opts_reset();
   1508     while ((c = getopts(argc, argv, "RvcfhHLP", lo)))
   1509         switch (c) {
   1510         case 'R': recurse = 1; break;
   1511         case 'v': x.verbose = 1; break;
   1512         case 'c': x.changes_only = 1; break;
   1513         case 'f': x.quiet = 1; break;
   1514         case 'h': deref = 0; break;
   1515         case 'D': deref = 1; break;
   1516         case 'H': follow_top = 1; break;
   1517         case 'L': follow_all = follow_top = 1; break;
   1518         case 'P': follow_top = follow_all = 0; break;
   1519         case 'F': from = optarg; break;
   1520         case 'r': reference = optarg; break;
   1521         default: break;
   1522         }
   1523     if (!nops) missing_operand();
   1524     if (reference) {
   1525         struct stat rs;
   1526         if (stat(reference, &rs) < 0) die(1, "failed to get attributes of '%s': %s", reference, strerror(errno));
   1527         if (!isgrp) { x.u = rs.st_uid; x.have_u = 1; }
   1528         x.g = rs.st_gid; x.have_g = 1;
   1529     } else {
   1530         if (nops < 2) { say("missing operand after '%s'", ops[0]); usage_error(); }
   1531         if (parse_owner(ops[0], &x, isgrp) < 0) return 1;
   1532         ops++; nops--;
   1533     }
   1534     if (from) {
   1535         struct chown_ctx f; memset(&f, 0, sizeof f);
   1536         if (parse_owner(from, &f, 0) < 0) return 1;
   1537         x.from_u = f.have_u; x.fu = f.u; x.from_g = f.have_g; x.fg = f.g;
   1538     }
   1539     if (!nops) missing_operand();
   1540     if (!recurse) { follow_top = deref != 0; follow_all = 0; }
   1541     else if (deref == 0) follow_top = follow_all = 0;
   1542     for (i = 0; i < nops; i++) st |= walk(ops[i], 1, follow_top, follow_all, recurse, chown_visit, &x);
   1543     return finish_stdout() ? 1 : st;
   1544 }
   1545 
   1546 /* ---- mkfifo mknod ---- */
   1547 
   1548 static int t_mkfifo(int argc, char **argv)
   1549 {
   1550     static const struct opt lo[] = { { "mode", 1, 'm' }, { "context", 2, 'Z' }, { NULL, 0, 0 } };
   1551     int c, i, st = 0;
   1552     struct change *change = NULL;
   1553     mode_t um = current_umask(), mode = 0666;
   1554     opts_reset();
   1555     while ((c = getopts(argc, argv, "m:Z", lo)))
   1556         if (c == 'm' && !(change = mode_compile(optarg))) die(1, "invalid mode '%s'", optarg);
   1557     if (!nops) missing_operand();
   1558     if (change) mode = mode_apply(0666 & ~um, 0, um, change);
   1559     for (i = 0; i < nops; i++) {
   1560         if (change) umask(0);
   1561         if (mkfifo(ops[i], mode) < 0) { perr("cannot create fifo '%s'", ops[i]); st = 1; }
   1562         if (change) umask(um);
   1563     }
   1564     return st;
   1565 }
   1566 
   1567 static int t_mknod(int argc, char **argv)
   1568 {
   1569     static const struct opt lo[] = { { "mode", 1, 'm' }, { "context", 2, 'Z' }, { NULL, 0, 0 } };
   1570     int c;
   1571     struct change *change = NULL;
   1572     mode_t um = current_umask(), mode = 0666, type;
   1573     dev_t dev = 0;
   1574     opts_reset();
   1575     while ((c = getopts(argc, argv, "m:Z", lo)))
   1576         if (c == 'm' && !(change = mode_compile(optarg))) die(1, "invalid mode '%s'", optarg);
   1577     if (nops < 1) missing_operand();
   1578     if (nops < 2) { say("missing operand after '%s'", ops[0]); usage_error(); }
   1579     if (change) mode = mode_apply(0666 & ~um, 0, um, change);
   1580     if (strlen(ops[1]) != 1 || !strchr("pbcu", ops[1][0])) { say("invalid device type '%s'", ops[1]); usage_error(); }
   1581     if (ops[1][0] == 'p') {
   1582         if (nops > 2) { say("Fifos do not have major and minor device numbers."); usage_error(); }
   1583         type = S_IFIFO;
   1584     } else {
   1585         unsigned long ma, mi;
   1586         if (nops < 4) { say("Special files require major and minor device numbers."); usage_error(); }
   1587         if (nops > 4) extra_operand(ops[4]);
   1588         if (!parse_ulong(ops[2], &ma)) die(1, "invalid major device number '%s'", ops[2]);
   1589         if (!parse_ulong(ops[3], &mi)) die(1, "invalid minor device number '%s'", ops[3]);
   1590         dev = makedev(ma, mi);
   1591         type = ops[1][0] == 'b' ? S_IFBLK : S_IFCHR;
   1592     }
   1593     if (change) umask(0);
   1594     c = mknod(ops[0], type | (mode & 07777), dev);
   1595     if (change) umask(um);
   1596     if (c < 0) { perr("'%s'", ops[0]); return 1; }
   1597     return 0;
   1598 }
   1599 
   1600 /* ---- touch ---- */
   1601 
   1602 /* [[CC]YY]MMDDhhmm[.ss] */
   1603 static int parse_stamp(const char *s, struct timespec *ts)
   1604 {
   1605     char buf[32];
   1606     size_t n, i;
   1607     long cc = 0, yy, mo, d, h, mi, sec = 0;
   1608     struct tm t;
   1609     const char *dot = strchr(s, '.');
   1610     n = dot ? (size_t)(dot - s) : strlen(s);
   1611     if (n != 8 && n != 10 && n != 12) return -1;
   1612     for (i = 0; i < n; i++) if (!isdigit((unsigned char)s[i])) return -1;
   1613     memcpy(buf, s, n); buf[n] = 0;
   1614     if (dot) { if (strlen(dot) != 3 || !isdigit((unsigned char)dot[1]) || !isdigit((unsigned char)dot[2])) return -1; sec = (dot[1] - '0') * 10 + dot[2] - '0'; }
   1615 #define TWO(p) ((p)[0] - '0') * 10 + (p)[1] - '0'
   1616     {
   1617         const char *p = buf;
   1618         long year;
   1619         if (n == 12) { cc = TWO(p); p += 2; yy = TWO(p); p += 2; year = cc * 100 + yy; }
   1620         else if (n == 10) { yy = TWO(p); p += 2; year = yy < 69 ? 2000 + yy : 1900 + yy; }
   1621         else { clock_gettime(0, ts); { time_t now = ts->tv_sec; year = localtime(&now)->tm_year + 1900; } }
   1622         mo = TWO(p); p += 2; d = TWO(p); p += 2; h = TWO(p); p += 2; mi = TWO(p);
   1623         if (mo < 1 || mo > 12 || d < 1 || d > 31 || h > 23 || mi > 59 || sec > 61) return -1;
   1624         memset(&t, 0, sizeof t);
   1625         t.tm_year = year - 1900; t.tm_mon = mo - 1; t.tm_mday = d; t.tm_hour = h; t.tm_min = mi; t.tm_sec = sec;
   1626     }
   1627     ts->tv_sec = timegm(&t); ts->tv_nsec = 0;
   1628     return 0;
   1629 }
   1630 
   1631 static int t_touch(int argc, char **argv)
   1632 {
   1633     static const struct opt lo[] = {
   1634         { "no-create", 0, 'c' }, { "date", 1, 'd' }, { "no-dereference", 0, 'h' }, { "reference", 1, 'r' }, { "time", 1, 'T' }, { NULL, 0, 0 } };
   1635     int c, a_only = 0, m_only = 0, nocreate = 0, nofollow = 0, i, st = 0;
   1636     const char *datestr = NULL, *stamp = NULL, *ref = NULL;
   1637     struct timespec ts[2];
   1638     opts_reset();
   1639     while ((c = getopts(argc, argv, "acd:fhmr:t:", lo)))
   1640         switch (c) {
   1641         case 'a': a_only = 1; break;
   1642         case 'm': m_only = 1; break;
   1643         case 'c': nocreate = 1; break;
   1644         case 'd': datestr = optarg; break;
   1645         case 'h': nofollow = 1; break;
   1646         case 'r': ref = optarg; break;
   1647         case 't': stamp = optarg; break;
   1648         case 'T':
   1649             if (!strcmp(optarg, "atime") || !strcmp(optarg, "access") || !strcmp(optarg, "use")) a_only = 1;
   1650             else if (!strcmp(optarg, "mtime") || !strcmp(optarg, "modify")) m_only = 1;
   1651             else die(1, "invalid argument '%s' for '--time'", optarg);
   1652             break;
   1653         }
   1654     if (!nops) { say("missing file operand"); usage_error(); }
   1655     ts[0].tv_sec = ts[1].tv_sec = 0; ts[0].tv_nsec = ts[1].tv_nsec = UTIME_NOW;
   1656     if (ref) {
   1657         struct stat rs;
   1658         if ((nofollow ? lstat(ref, &rs) : stat(ref, &rs)) < 0) die(1, "failed to get attributes of '%s': %s", ref, strerror(errno));
   1659         ts[0].tv_sec = rs.st_atime; ts[0].tv_nsec = rs.st_atime_nsec;
   1660         ts[1].tv_sec = rs.st_mtime; ts[1].tv_nsec = rs.st_mtime_nsec;
   1661     }
   1662     if (datestr) {
   1663         struct timespec when;
   1664         if (parse_date(datestr, &when) < 0) die(1, "invalid date format '%s'", datestr);
   1665         ts[0] = ts[1] = when;
   1666     }
   1667     if (stamp) {
   1668         struct timespec when;
   1669         if (parse_stamp(stamp, &when) < 0) die(1, "invalid date format '%s'", stamp);
   1670         ts[0] = ts[1] = when;
   1671     }
   1672     if (a_only && !m_only) ts[1].tv_nsec = UTIME_OMIT;
   1673     if (m_only && !a_only) ts[0].tv_nsec = UTIME_OMIT;
   1674     for (i = 0; i < nops; i++) {
   1675         int flags = nofollow ? AT_SYMLINK_NOFOLLOW : 0, r;
   1676         if (!strcmp(ops[i], "-")) { r = utimensat(1, NULL, ts, 0); if (r < 0) { perr("setting times of standard output"); st = 1; } continue; }
   1677         r = utimensat(AT_FDCWD, ops[i], ts, flags);
   1678         if (r < 0 && errno == ENOENT && !nocreate) {
   1679             int fd = open(ops[i], O_WRONLY | O_CREAT | O_NOCTTY | O_NONBLOCK, 0666);
   1680             if (fd >= 0) { close(fd); r = utimensat(AT_FDCWD, ops[i], ts, flags); }
   1681         }
   1682         if (r < 0 && !(nocreate && errno == ENOENT)) { perr("cannot touch '%s'", ops[i]); st = 1; }
   1683     }
   1684     return st;
   1685 }
   1686 
   1687 /* ---- ln ---- */
   1688 
   1689 static int t_ln(int argc, char **argv)
   1690 {
   1691     static const struct opt lo[] = {
   1692         { "symbolic", 0, 's' }, { "force", 0, 'f' }, { "no-dereference", 0, 'n' }, { "verbose", 0, 'v' }, { "relative", 0, 'r' },
   1693         { "no-target-directory", 0, 'T' }, { "target-directory", 1, 't' }, { "interactive", 0, 'i' }, { "logical", 0, 'L' },
   1694         { "physical", 0, 'P' }, { NULL, 0, 0 } };
   1695     int c, sym = 0, force = 0, nofollow = 0, verbose = 0, rel = 0, notdir = 0, ask = 0, i, st = 0, ntargets;
   1696     const char *tdir = NULL;
   1697     char **targets;
   1698     struct stat sb;
   1699     opts_reset();
   1700     while ((c = getopts(argc, argv, "sfnvrTt:iLPdF", lo)))
   1701         switch (c) {
   1702         case 's': sym = 1; break; case 'f': force = 1; ask = 0; break; case 'n': nofollow = 1; break;
   1703         case 'v': verbose = 1; break; case 'r': rel = 1; break; case 'T': notdir = 1; break;
   1704         case 't': tdir = optarg; break; case 'i': ask = 1; force = 0; break;
   1705         default: break;
   1706         }
   1707     if (!nops) missing_operand();
   1708     if (tdir && notdir) { say("cannot combine --target-directory and --no-target-directory"); usage_error(); }
   1709     if (tdir) { targets = ops; ntargets = nops; }
   1710     else if (notdir) {
   1711         if (nops < 2) { say("missing destination file operand after '%s'", ops[0]); usage_error(); }
   1712         if (nops > 2) extra_operand(ops[2]);
   1713         targets = ops; ntargets = 1; tdir = NULL;
   1714     } else if (nops == 1) { targets = ops; ntargets = 1; tdir = "."; }
   1715     else {
   1716         const char *last = ops[nops - 1];
   1717         int isdir = (nofollow ? lstat(last, &sb) : stat(last, &sb)) == 0 && S_ISDIR(sb.st_mode);
   1718         if (isdir) { tdir = last; targets = ops; ntargets = nops - 1; }
   1719         else if (nops == 2) { targets = ops; ntargets = 1; }
   1720         else { say("target '%s' is not a directory", last); usage_error(); }
   1721     }
   1722     for (i = 0; i < ntargets; i++) {
   1723         const char *src = targets[i];
   1724         char *dest, *tmp = NULL;
   1725         if (tdir) {
   1726             char *b;
   1727             tmp = xstrdup(src);
   1728             { size_t n = strlen(tmp); while (n > 1 && tmp[n - 1] == '/') tmp[--n] = 0; }
   1729             b = strrchr(tmp, '/'); b = b && b[1] ? b + 1 : tmp;
   1730             dest = xmalloc(strlen(tdir) + strlen(b) + 2);
   1731             sprintf(dest, "%s%s%s", tdir, tdir[strlen(tdir) - 1] == '/' ? "" : "/", b);
   1732         } else dest = xstrdup(targets[ntargets]);
   1733         if (!sym) {
   1734             struct stat a, b;
   1735             if (stat(src, &a) < 0 && lstat(src, &a) < 0) { perr("failed to access '%s'", src); st = 1; goto next; }
   1736             if (lstat(dest, &b) == 0 && a.st_dev == b.st_dev && a.st_ino == b.st_ino && !S_ISLNK(b.st_mode) && !S_ISLNK(a.st_mode)) {
   1737                 say("'%s' and '%s' are the same file", src, dest); st = 1; goto next;
   1738             }
   1739         }
   1740         if (ask && lstat(dest, &sb) == 0) {
   1741             char line[8];
   1742             fprintf(stderr, "%s: replace '%s'? ", prog, dest);
   1743             if (!fgets(line, sizeof line, stdin) || (line[0] != 'y' && line[0] != 'Y')) goto next;
   1744             force = 1;
   1745         }
   1746         {
   1747             const char *text = src;
   1748             char *relp = NULL;
   1749             if (sym && rel) {
   1750                 char *dd = xstrdup(dest), *s2, *d2, *dir;
   1751                 char *sl = strrchr(dd, '/');
   1752                 if (sl) { if (sl == dd) dd[1] = 0; else *sl = 0; } else strcpy(dd, ".");
   1753                 s2 = canonicalize(src, CAN_MISSING, 0); d2 = canonicalize(dd, CAN_MISSING, 0);
   1754                 if (s2 && d2) { dir = relative_path(d2, s2); relp = dir; text = relp; }
   1755                 free(s2); free(d2); free(dd);
   1756             }
   1757             for (;;) {
   1758                 int r = sym ? symlink(text, dest) : link(src, dest);
   1759                 if (r == 0) {
   1760                     if (verbose) printf("'%s' %s '%s'\n", dest, sym ? "->" : "=>", text);
   1761                     break;
   1762                 }
   1763                 if (errno == EEXIST && force && unlink(dest) == 0) continue;
   1764                 if (sym) perr("failed to create symbolic link '%s'", dest);
   1765                 else perr("failed to create hard link '%s' => '%s'", dest, src);
   1766                 st = 1;
   1767                 break;
   1768             }
   1769             free(relp);
   1770         }
   1771 next:
   1772         free(dest); free(tmp);
   1773     }
   1774     return finish_stdout() ? 1 : st;
   1775 }
   1776 
   1777 /* ---- cp mv ---- */
   1778 
   1779 /* where each operand goes: into a directory (*tdir) or onto one name (the last operand) */
   1780 static int plan_dest(const char *tdir_opt, int notdir, int follow, const char **tdir, char ***srcs, int *nsrcs)
   1781 {
   1782     struct stat sb;
   1783     *tdir = tdir_opt;
   1784     *srcs = ops; *nsrcs = nops;
   1785     if (!nops) missing_operand();
   1786     if (tdir_opt && notdir) { say("cannot combine --target-directory and --no-target-directory"); usage_error(); }
   1787     if (tdir_opt) return 0;
   1788     if (nops == 1) { say("missing destination file operand after '%s'", ops[0]); usage_error(); }
   1789     if (notdir) {
   1790         if (nops > 2) extra_operand(ops[2]);
   1791         *nsrcs = 1;
   1792         return 0;
   1793     }
   1794     *nsrcs = nops - 1;
   1795     if ((follow ? stat(ops[nops - 1], &sb) : lstat(ops[nops - 1], &sb)) == 0 && S_ISDIR(sb.st_mode)) *tdir = ops[nops - 1];
   1796     else if (nops > 2) { say("target '%s' is not a directory", ops[nops - 1]); usage_error(); }
   1797     return 0;
   1798 }
   1799 
   1800 static char *dest_in(const char *dir, const char *src)
   1801 {
   1802     char *t = xstrdup(src), *b, *d;
   1803     size_t n = strlen(t);
   1804     while (n > 1 && t[n - 1] == '/') t[--n] = 0;
   1805     b = strrchr(t, '/'); b = b && b[1] ? b + 1 : t;
   1806     d = xmalloc(strlen(dir) + strlen(b) + 2);
   1807     sprintf(d, "%s%s%s", dir, dir[strlen(dir) - 1] == '/' ? "" : "/", b);
   1808     free(t);
   1809     return d;
   1810 }
   1811 
   1812 static int yes_answer(void)
   1813 {
   1814     char line[16];
   1815     return fgets(line, sizeof line, stdin) && (line[0] == 'y' || line[0] == 'Y');
   1816 }
   1817 
   1818 struct cp {
   1819     int rec, force, ask, keep, verbose, preserve, follow_top, follow_all, hard, sym, update;
   1820     mode_t um;
   1821     dev_t top_dev; ino_t top_ino;           /* the destination directory we are filling */
   1822     const char *top_src, *top_dest;
   1823 };
   1824 
   1825 static int cp_data(int in, int out)
   1826 {
   1827     char buf[65536];
   1828     ssize_t n;
   1829     while ((n = read(in, buf, sizeof buf)) > 0)
   1830         if (write_all(out, buf, n) < 0) return -1;
   1831     return n < 0 ? -1 : 0;
   1832 }
   1833 
   1834 static void cp_keep(const struct cp *o, const char *dest, const struct stat *st, int fd)
   1835 {
   1836     struct timespec t[2];
   1837     if (!o->preserve) return;
   1838     if (fd >= 0) { if (fchown(fd, st->st_uid, st->st_gid) < 0) fchown(fd, -1, st->st_gid); }
   1839     else if (lchown(dest, st->st_uid, st->st_gid) < 0) lchown(dest, -1, st->st_gid);
   1840     if (!S_ISLNK(st->st_mode)) {
   1841         if (fd >= 0) fchmod(fd, st->st_mode & 07777); else chmod(dest, st->st_mode & 07777);
   1842     }
   1843     t[0].tv_sec = st->st_atime; t[0].tv_nsec = st->st_atime_nsec;
   1844     t[1].tv_sec = st->st_mtime; t[1].tv_nsec = st->st_mtime_nsec;
   1845     utimensat(AT_FDCWD, dest, t, S_ISLNK(st->st_mode) ? AT_SYMLINK_NOFOLLOW : 0);
   1846 }
   1847 
   1848 static int cp_one(struct cp *o, const char *src, const char *dest, int top)
   1849 {
   1850     struct stat st, ds;
   1851     int follow = top ? o->follow_top : o->follow_all, have;
   1852     if ((follow ? stat(src, &st) : lstat(src, &st)) < 0) { perr("cannot stat '%s'", src); return 1; }
   1853     have = lstat(dest, &ds) == 0;
   1854     if (have && !S_ISDIR(st.st_mode) && !S_ISLNK(st.st_mode) && !o->hard) {
   1855         struct stat dd;
   1856         if (stat(dest, &dd) == 0 && dd.st_dev == st.st_dev && dd.st_ino == st.st_ino) {
   1857             say("'%s' and '%s' are the same file", src, dest);
   1858             return 1;
   1859         }
   1860     }
   1861     if (S_ISDIR(st.st_mode)) {
   1862         mode_t m;
   1863         int bad = 0, n = 0, cap = 0, i;
   1864         DIR *d;
   1865         struct dirent *e;
   1866         char **names = NULL;
   1867         if (!o->rec) { say("-r not specified; omitting directory '%s'", src); return 1; }
   1868         if (o->top_ino && st.st_dev == o->top_dev && st.st_ino == o->top_ino) {
   1869             say("cannot copy a directory, '%s', into itself, '%s'", o->top_src, o->top_dest);
   1870             return 1;
   1871         }
   1872         if (have && !S_ISDIR(ds.st_mode)) { say("cannot overwrite non-directory '%s' with directory '%s'", dest, src); return 1; }
   1873         m = o->preserve ? st.st_mode & 07777 : st.st_mode & ~o->um & 0777;
   1874         if (!have) {
   1875             if (mkdir(dest, m | S_IRWXU) < 0) { perr("cannot create directory '%s'", dest); return 1; }
   1876             if (o->verbose) printf("'%s' -> '%s'\n", src, dest);
   1877         }
   1878         if (top) {
   1879             struct stat t;
   1880             if (stat(dest, &t) == 0) { o->top_dev = t.st_dev; o->top_ino = t.st_ino; o->top_src = src; o->top_dest = dest; }
   1881         }
   1882         d = opendir(src);
   1883         if (!d) { perr("cannot access '%s'", src); return 1; }
   1884         while ((e = readdir(d))) {
   1885             if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
   1886             if (n == cap) { cap = cap ? cap * 2 : 32; names = xrealloc(names, cap * sizeof *names); }
   1887             names[n++] = xstrdup(e->d_name);
   1888         }
   1889         closedir(d);
   1890         for (i = 0; i < n; i++) {
   1891             char *cs = xmalloc(strlen(src) + strlen(names[i]) + 2), *cd = xmalloc(strlen(dest) + strlen(names[i]) + 2);
   1892             sprintf(cs, "%s%s%s", src, src[strlen(src) - 1] == '/' ? "" : "/", names[i]);
   1893             sprintf(cd, "%s%s%s", dest, dest[strlen(dest) - 1] == '/' ? "" : "/", names[i]);
   1894             bad |= cp_one(o, cs, cd, 0);
   1895             free(cs); free(cd); free(names[i]);
   1896         }
   1897         free(names);
   1898         if (!have) chmod(dest, m);
   1899         cp_keep(o, dest, &st, -1);
   1900         return bad;
   1901     }
   1902     if (have && S_ISDIR(ds.st_mode)) { say("cannot overwrite directory '%s' with non-directory", dest); return 1; }
   1903     if (have) {
   1904         if (o->update) {
   1905             struct stat dd;
   1906             if (stat(dest, &dd) == 0 && (dd.st_mtime > st.st_mtime || (dd.st_mtime == st.st_mtime && dd.st_mtime_nsec >= st.st_mtime_nsec))) return 0;
   1907         }
   1908         if (o->keep) return 0;
   1909         if (o->ask) {
   1910             fflush(stdout);
   1911             fprintf(stderr, "%s: overwrite '%s'? ", prog, dest);
   1912             if (!yes_answer()) return 0;
   1913         }
   1914     }
   1915     if (o->hard || o->sym) {
   1916         int r;
   1917         if (have && (unlink(dest) < 0 && errno != ENOENT)) { perr("cannot remove '%s'", dest); return 1; }
   1918         r = o->sym ? symlink(src, dest) : link(src, dest);
   1919         if (r < 0) { perr("cannot create %s link '%s'", o->sym ? "symbolic" : "hard", dest); return 1; }
   1920         if (o->verbose) printf("'%s' -> '%s'\n", src, dest);
   1921         return 0;
   1922     }
   1923     if (S_ISLNK(st.st_mode)) {
   1924         char tgt[PATH_MAX];
   1925         ssize_t n = readlink(src, tgt, sizeof tgt - 1);
   1926         if (n < 0) { perr("cannot read symbolic link '%s'", src); return 1; }
   1927         tgt[n] = 0;
   1928         if (have) unlink(dest);
   1929         if (symlink(tgt, dest) < 0) { perr("cannot create symbolic link '%s'", dest); return 1; }
   1930         if (o->verbose) printf("'%s' -> '%s'\n", src, dest);
   1931         cp_keep(o, dest, &st, -1);
   1932         return 0;
   1933     }
   1934     if (S_ISFIFO(st.st_mode) && o->rec) {
   1935         if (have) unlink(dest);
   1936         if (mkfifo(dest, st.st_mode & 0777 & ~o->um) < 0) { perr("cannot create fifo '%s'", dest); return 1; }
   1937         if (o->verbose) printf("'%s' -> '%s'\n", src, dest);
   1938         cp_keep(o, dest, &st, -1);
   1939         return 0;
   1940     }
   1941     if ((S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) && o->rec) {
   1942         if (have) unlink(dest);
   1943         if (mknod(dest, st.st_mode, st.st_rdev) < 0) { perr("cannot create special file '%s'", dest); return 1; }
   1944         if (o->verbose) printf("'%s' -> '%s'\n", src, dest);
   1945         cp_keep(o, dest, &st, -1);
   1946         return 0;
   1947     }
   1948     {
   1949         int in = open(src, O_RDONLY), out;
   1950         mode_t m = o->preserve ? st.st_mode & 07777 : st.st_mode & ~o->um & 0777;
   1951         if (in < 0) { perr("cannot open '%s' for reading", src); return 1; }
   1952         out = open(dest, O_WRONLY | O_CREAT | (have ? O_TRUNC : O_EXCL), m);
   1953         if (out < 0 && have && o->force) { unlink(dest); out = open(dest, O_WRONLY | O_CREAT | O_EXCL, m); }
   1954         if (out < 0) { perr("cannot create regular file '%s'", dest); close(in); return 1; }
   1955         if (o->verbose) printf("'%s' -> '%s'\n", src, dest);
   1956         if (cp_data(in, out) < 0) { perr("error copying '%s'", src); close(in); close(out); return 1; }
   1957         cp_keep(o, dest, &st, out);
   1958         close(in);
   1959         if (close(out) < 0) { perr("failed to close '%s'", dest); return 1; }
   1960     }
   1961     return 0;
   1962 }
   1963 
   1964 static int t_cp(int argc, char **argv)
   1965 {
   1966     static const struct opt lo[] = {
   1967         { "recursive", 0, 'R' }, { "archive", 0, 'a' }, { "force", 0, 'f' }, { "interactive", 0, 'i' }, { "no-clobber", 0, 'n' },
   1968         { "verbose", 0, 'v' }, { "preserve", 2, 'p' }, { "no-dereference", 0, 'P' }, { "dereference", 0, 'L' },
   1969         { "link", 0, 'l' }, { "symbolic-link", 0, 's' }, { "update", 0, 'u' }, { "no-target-directory", 0, 'T' },
   1970         { "target-directory", 1, 't' }, { NULL, 0, 0 } };
   1971     struct cp o = { 0 };
   1972     int c, notdir = 0, bad = 0, i, nsrc, h = 0, l = 0, p = 0;
   1973     const char *tdir = NULL;
   1974     char **srcs;
   1975     opts_reset();
   1976     while ((c = getopts(argc, argv, "rRafinvpPLHlsuTt:d", lo)))
   1977         switch (c) {
   1978         case 'r': case 'R': o.rec = 1; break;
   1979         case 'a': o.rec = 1; o.preserve = 1; p = 1; break;
   1980         case 'f': o.force = 1; o.ask = 0; break;
   1981         case 'i': o.ask = 1; o.keep = 0; break;
   1982         case 'n': o.keep = 1; o.ask = 0; break;
   1983         case 'v': o.verbose = 1; break;
   1984         case 'p': o.preserve = 1; break;
   1985         case 'P': p = 1; l = 0; h = 0; break;
   1986         case 'L': l = 1; p = 0; h = 0; break;
   1987         case 'H': h = 1; l = 0; p = 0; break;
   1988         case 'd': p = 1; l = 0; h = 0; break;
   1989         case 'l': o.hard = 1; break;
   1990         case 's': o.sym = 1; break;
   1991         case 'u': o.update = 1; break;
   1992         case 'T': notdir = 1; break;
   1993         case 't': tdir = optarg; break;
   1994         default: break;
   1995         }
   1996     o.um = current_umask();
   1997     o.follow_all = l || (!o.rec && !p);
   1998     o.follow_top = l || h || o.follow_all;
   1999     plan_dest(tdir, notdir, 1, &tdir, &srcs, &nsrc);
   2000     for (i = 0; i < nsrc; i++) {
   2001         char *dest = tdir ? dest_in(tdir, srcs[i]) : xstrdup(ops[nops - 1]);
   2002         o.top_ino = 0;
   2003         bad |= cp_one(&o, srcs[i], dest, 1);
   2004         free(dest);
   2005     }
   2006     return finish_stdout() ? 1 : bad;
   2007 }
   2008 
   2009 static int t_mv(int argc, char **argv)
   2010 {
   2011     static const struct opt lo[] = {
   2012         { "force", 0, 'f' }, { "interactive", 0, 'i' }, { "no-clobber", 0, 'n' }, { "verbose", 0, 'v' },
   2013         { "update", 0, 'u' }, { "no-target-directory", 0, 'T' }, { "target-directory", 1, 't' }, { NULL, 0, 0 } };
   2014     int c, notdir = 0, bad = 0, i, nsrc, force = 0, ask = 0, keep = 0, verbose = 0, update = 0;
   2015     const char *tdir = NULL;
   2016     char **srcs;
   2017     opts_reset();
   2018     while ((c = getopts(argc, argv, "finvuTt:", lo)))
   2019         switch (c) {
   2020         case 'f': force = 1; ask = 0; keep = 0; break;
   2021         case 'i': ask = 1; force = 0; keep = 0; break;
   2022         case 'n': keep = 1; ask = 0; force = 0; break;
   2023         case 'v': verbose = 1; break;
   2024         case 'u': update = 1; break;
   2025         case 'T': notdir = 1; break;
   2026         case 't': tdir = optarg; break;
   2027         default: break;
   2028         }
   2029     plan_dest(tdir, notdir, 1, &tdir, &srcs, &nsrc);
   2030     for (i = 0; i < nsrc; i++) {
   2031         const char *src = srcs[i];
   2032         char *dest = tdir ? dest_in(tdir, src) : xstrdup(ops[nops - 1]);
   2033         struct stat s, d;
   2034         int have;
   2035         if (lstat(src, &s) < 0) { perr("cannot stat '%s'", src); bad = 1; goto next; }
   2036         have = lstat(dest, &d) == 0;
   2037         if (have && s.st_dev == d.st_dev && s.st_ino == d.st_ino && !S_ISLNK(s.st_mode)) {
   2038             say("'%s' and '%s' are the same file", src, dest); bad = 1; goto next;
   2039         }
   2040         if (have && S_ISDIR(d.st_mode) && !S_ISDIR(s.st_mode)) { say("cannot overwrite directory '%s' with non-directory", dest); bad = 1; goto next; }
   2041         if (have && !S_ISDIR(d.st_mode) && S_ISDIR(s.st_mode)) { say("cannot overwrite non-directory '%s' with directory '%s'", dest, src); bad = 1; goto next; }
   2042         if (have && update && s.st_mtime < d.st_mtime) goto next;
   2043         if (have && keep) goto next;
   2044         if (have && (ask || (!force && access(dest, W_OK) < 0 && !S_ISLNK(d.st_mode) && isatty(0)))) {
   2045             fflush(stdout);
   2046             fprintf(stderr, ask ? "%s: overwrite '%s'? " : "%s: replace '%s', overriding mode? ", prog, dest);
   2047             if (!yes_answer()) goto next;
   2048         }
   2049         if (rename(src, dest) == 0) {
   2050             if (verbose) printf("renamed '%s' -> '%s'\n", src, dest);
   2051         } else if (errno == EXDEV) {
   2052             struct cp o = { 0 };
   2053             struct rm_opts r = { 1, 0, 1, 0, 0 };
   2054             o.rec = 1; o.preserve = 1; o.verbose = verbose; o.um = current_umask();
   2055             if (have && !S_ISDIR(d.st_mode)) unlink(dest);
   2056             if (cp_one(&o, src, dest, 1)) { bad = 1; goto next; }
   2057             if (rm_entry(AT_FDCWD, src, src, &r)) bad = 1;
   2058         } else if (errno == EINVAL && S_ISDIR(s.st_mode)) {
   2059             say("cannot move '%s' to a subdirectory of itself, '%s'", src, dest); bad = 1;
   2060         } else { perr("cannot move '%s' to '%s'", src, dest); bad = 1; }
   2061 next:
   2062         free(dest);
   2063     }
   2064     return finish_stdout() ? 1 : bad;
   2065 }
   2066 
   2067 /* ---- readlink realpath ---- */
   2068 
   2069 static int t_readlink(int argc, char **argv)
   2070 {
   2071     static const struct opt lo[] = {
   2072         { "canonicalize", 0, 'f' }, { "canonicalize-existing", 0, 'e' }, { "canonicalize-missing", 0, 'm' },
   2073         { "no-newline", 0, 'n' }, { "quiet", 0, 'q' }, { "silent", 0, 's' }, { "verbose", 0, 'v' }, { "zero", 0, 'z' }, { NULL, 0, 0 } };
   2074     int c, mode = -1, nonl = 0, verbose = 0, zero = 0, i, st = 0;
   2075     opts_reset();
   2076     while ((c = getopts(argc, argv, "femnqsvz", lo)))
   2077         switch (c) {
   2078         case 'f': mode = CAN_ALL_BUT_LAST; break; case 'e': mode = CAN_EXISTING; break; case 'm': mode = CAN_MISSING; break;
   2079         case 'n': nonl = 1; break; case 'v': verbose = 1; break; case 'z': zero = 1; break;
   2080         }
   2081     if (!nops) missing_operand();
   2082     if (nops > 1 && nonl) { say("ignoring --no-newline with multiple arguments"); nonl = 0; }
   2083     for (i = 0; i < nops; i++) {
   2084         char buf[PATH_MAX], *r;
   2085         if (mode < 0) {
   2086             ssize_t n = readlink(ops[i], buf, sizeof buf - 1);
   2087             if (n < 0) { if (verbose) perr("%s", ops[i]); st = 1; continue; }
   2088             buf[n] = 0; r = buf;
   2089         } else {
   2090             r = canonicalize(ops[i], mode, 0);
   2091             if (!r) { if (verbose) perr("%s", ops[i]); st = 1; continue; }
   2092         }
   2093         fputs(r, stdout);
   2094         if (!nonl) putchar(zero ? 0 : '\n');
   2095         if (r != buf) free(r);
   2096     }
   2097     return finish_stdout() ? 1 : st;
   2098 }
   2099 
   2100 static int t_realpath(int argc, char **argv)
   2101 {
   2102     static const struct opt lo[] = {
   2103         { "canonicalize-existing", 0, 'e' }, { "canonicalize-missing", 0, 'm' }, { "logical", 0, 'L' }, { "physical", 0, 'P' },
   2104         { "strip", 0, 's' }, { "no-symlinks", 0, 's' }, { "quiet", 0, 'q' }, { "zero", 0, 'z' }, { "relative-to", 1, 'R' },
   2105         { "relative-base", 1, 'B' }, { NULL, 0, 0 } };
   2106     int c, mode = CAN_ALL_BUT_LAST, nolinks = 0, quiet = 0, zero = 0, i, st = 0;
   2107     const char *relto = NULL, *relbase = NULL;
   2108     opts_reset();
   2109     while ((c = getopts(argc, argv, "emLPsqz", lo)))
   2110         switch (c) {
   2111         case 'e': mode = CAN_EXISTING; break; case 'm': mode = CAN_MISSING; break; case 's': nolinks = 1; break;
   2112         case 'L': nolinks = 0; break; case 'P': nolinks = 0; break; case 'q': quiet = 1; break; case 'z': zero = 1; break;
   2113         case 'R': relto = optarg; break; case 'B': relbase = optarg; break;
   2114         }
   2115     if (!nops) missing_operand();
   2116     {
   2117         char *to = relto ? canonicalize(relto, mode == CAN_EXISTING ? CAN_EXISTING : CAN_MISSING, nolinks) : NULL;
   2118         char *base = relbase ? canonicalize(relbase, CAN_MISSING, nolinks) : NULL;
   2119         if (relto && !to) die(1, "%s: %s", relto, strerror(errno));
   2120         if (relbase && !base) die(1, "%s: %s", relbase, strerror(errno));
   2121         if (base && !to) to = base;
   2122         for (i = 0; i < nops; i++) {
   2123             char *r = canonicalize(ops[i], mode, nolinks), *out = r;
   2124             if (r && mode == CAN_EXISTING && nolinks) { struct stat sb; if (lstat(r, &sb) < 0) { free(r); r = NULL; } }
   2125             if (!r) { if (!quiet) perr("%s", ops[i]); st = 1; continue; }
   2126             if (to) {
   2127                 size_t bl = base ? strlen(base) : 0;
   2128                 int inside = !base || (!strncmp(r, base, bl) && (r[bl] == '/' || !r[bl] || bl == 1));
   2129                 if (inside) out = relative_path(to, r);
   2130             }
   2131             fputs(out, stdout);
   2132             putchar(zero ? 0 : '\n');
   2133             if (out != r) free(out);
   2134             free(r);
   2135         }
   2136     }
   2137     return finish_stdout() ? 1 : st;
   2138 }
   2139 
   2140 /* ---- mktemp ---- */
   2141 
   2142 static int t_mktemp(int argc, char **argv)
   2143 {
   2144     static const struct opt lo[] = {
   2145         { "directory", 0, 'd' }, { "dry-run", 0, 'u' }, { "quiet", 0, 'q' }, { "tmpdir", 2, 'p' }, { "suffix", 1, 'S' }, { NULL, 0, 0 } };
   2146     int c, dir = 0, dry = 0, quiet = 0, use_tmpdir = 0, tries;
   2147     const char *tmpdir = NULL, *suffix = "", *tmpl;
   2148     char *path, *x;
   2149     size_t len, nx = 0, sl;
   2150     static const char alpha[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   2151     opts_reset();
   2152     while ((c = getopts(argc, argv, "dqp:tuV", lo)))
   2153         switch (c) {
   2154         case 'd': dir = 1; break; case 'u': dry = 1; break; case 'q': quiet = 1; break;
   2155         case 'p': use_tmpdir = 1; tmpdir = optarg; break; case 't': use_tmpdir = 1; break;
   2156         case 'S': suffix = optarg; break; default: break;
   2157         }
   2158     if (nops > 1) extra_operand(ops[1]);
   2159     if (!nops) { tmpl = "tmp.XXXXXXXXXX"; use_tmpdir = 1; } else tmpl = ops[0];
   2160     if (use_tmpdir && !tmpdir) tmpdir = getenv("TMPDIR") && *getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp";
   2161     if (strchr(suffix, '/')) die(1, "invalid suffix '%s', contains directory separator", suffix);
   2162     len = strlen(tmpl); sl = strlen(suffix);
   2163     if (use_tmpdir && strchr(tmpl, '/') && nops) die(1, "invalid template, '%s', contains directory separator", tmpl);
   2164     path = xmalloc((tmpdir ? strlen(tmpdir) : 0) + len + sl + 4);
   2165     path[0] = 0;
   2166     if (use_tmpdir) { strcpy(path, tmpdir); if (path[0] && path[strlen(path) - 1] != '/') strcat(path, "/"); }
   2167     strcat(path, tmpl); strcat(path, suffix);
   2168     {
   2169         size_t end = strlen(path) - sl;
   2170         x = path + end;
   2171         while (x > path && x[-1] == 'X') { x--; nx++; }
   2172     }
   2173     if (nx < 3) { if (!quiet) say("too few X's in template '%s'", tmpl); return 1; }
   2174     for (tries = 0; tries < 100; tries++) {
   2175         unsigned char rnd[64];
   2176         size_t k;
   2177         if (getrandom(rnd, nx, 0) < (ssize_t)nx) { size_t j; unsigned long long v = (unsigned long long)time(NULL) * 6364136223846793005ULL + tries; for (j = 0; j < nx; j++) { v = v * 6364136223846793005ULL + 1442695040888963407ULL; rnd[j] = v >> 33; } }
   2178         for (k = 0; k < nx; k++) x[k] = alpha[rnd[k] % (sizeof alpha - 1)];
   2179         if (dry) { struct stat sb; if (lstat(path, &sb) < 0 && errno == ENOENT) break; continue; }
   2180         if (dir) { if (mkdir(path, 0700) == 0) break; }
   2181         else { int fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0600); if (fd >= 0) { close(fd); break; } }
   2182         if (errno != EEXIST) { if (!quiet) perr("failed to create %s via template '%s'", dir ? "directory" : "file", tmpl); return 1; }
   2183     }
   2184     if (tries == 100) { if (!quiet) say("too many files could not be created"); return 1; }
   2185     puts(path);
   2186     return finish_stdout();
   2187 }
   2188 
   2189 /* ---- head tail ---- */
   2190 
   2191 /* head -5 and fold -5 for -n 5 and -w 5: only as the first argument, digits and maybe a b, k or m */
   2192 static char **old_count_form(int *argc, char **argv, const char *opt)
   2193 {
   2194     char **n;
   2195     const char *a;
   2196     int i;
   2197     if (*argc < 2) return argv;
   2198     a = argv[1];
   2199     if (a[0] != '-' || !isdigit((unsigned char)a[1])) return argv;
   2200     for (i = 1; isdigit((unsigned char)a[i]); i++) ;
   2201     if (a[i] && !(strchr("bkm", a[i]) && !a[i + 1])) return argv;
   2202     n = xmalloc((*argc + 2) * sizeof *n);
   2203     n[0] = argv[0]; n[1] = (char *)opt; n[2] = (char *)a + 1;
   2204     for (i = 2; i <= *argc; i++) n[i + 1] = argv[i];
   2205     (*argc)++;
   2206     return n;
   2207 }
   2208 
   2209 static void print_header(const char *name, int *first)
   2210 {
   2211     printf("%s==> %s <==\n", *first ? "" : "\n", !strcmp(name, "-") ? "'standard input'" : name);
   2212     *first = 0;
   2213 }
   2214 
   2215 static int t_head(int argc, char **argv)
   2216 {
   2217     static const struct opt lo[] = {
   2218         { "bytes", 1, 'c' }, { "lines", 1, 'n' }, { "quiet", 0, 'q' }, { "silent", 0, 'q' }, { "verbose", 0, 'v' },
   2219         { "zero-terminated", 0, 'z' }, { NULL, 0, 0 } };
   2220     int c, bytes = 0, quiet = 0, verbose = 0, i, st = 0, first = 1, sep = '\n', from_end = 0;
   2221     unsigned long long count = 10;
   2222     static char buf[1 << 16];
   2223     argv = old_count_form(&argc, argv, "-n");
   2224     opts_reset();
   2225     while ((c = getopts(argc, argv, "c:n:qvz", lo)))
   2226         switch (c) {
   2227         case 'c': case 'n': {
   2228             const char *s = optarg;
   2229             bytes = c == 'c'; from_end = 0;
   2230             if (*s == '-') { from_end = 1; s++; } else if (*s == '+') s++;
   2231             if (!parse_size(s, &count)) die(1, "invalid number of %s: '%s'", bytes ? "bytes" : "lines", optarg);
   2232             break;
   2233         }
   2234         case 'q': quiet = 1; break;
   2235         case 'v': verbose = 1; break;
   2236         case 'z': sep = 0; break;
   2237         }
   2238     if (!nops) ops[nops++] = "-";
   2239     for (i = 0; i < nops; i++) {
   2240         int fd = open_input(ops[i]);
   2241         unsigned long long left = count;
   2242         ssize_t n;
   2243         if (fd < 0) { perr("cannot open '%s' for reading", ops[i]); st = 1; continue; }
   2244         if (verbose || (!quiet && nops > 1)) print_header(ops[i], &first);
   2245         fflush(stdout);
   2246         if (from_end) {
   2247             char *data; size_t len, end;
   2248             if (read_all(fd, &data, &len) < 0) { perr("error reading '%s'", ops[i]); st = 1; if (fd) close(fd); continue; }
   2249             if (bytes) end = len > count ? len - count : 0;
   2250             else if (count == 0) end = len;
   2251             else {
   2252                 /* the newline at the very end doesn't start another line; the Nth one from the back ends what we keep */
   2253                 size_t q = len;
   2254                 unsigned long long seen = 0;
   2255                 if (len && data[len - 1] == sep) q = len - 1;
   2256                 end = 0;
   2257                 while (q > 0) {
   2258                     q--;
   2259                     if (data[q] == sep && ++seen == count) { end = q + 1; break; }
   2260                 }
   2261             }
   2262             if (write_all(1, data, end) < 0) { perr("error writing 'standard output'"); exit(1); }
   2263             free(data);
   2264         } else if (bytes) {
   2265             while (left && (n = read(fd, buf, left < sizeof buf ? left : sizeof buf)) != 0) {
   2266                 if (n < 0) { if (errno == EINTR) continue; perr("error reading '%s'", ops[i]); st = 1; break; }
   2267                 if (write_all(1, buf, n) < 0) { perr("error writing 'standard output'"); exit(1); }
   2268                 left -= n;
   2269             }
   2270         } else {
   2271             while (left && (n = read(fd, buf, sizeof buf)) != 0) {
   2272                 ssize_t k, upto = n;
   2273                 if (n < 0) { if (errno == EINTR) continue; perr("error reading '%s'", ops[i]); st = 1; break; }
   2274                 for (k = 0; k < n; k++)
   2275                     if (buf[k] == sep && --left == 0) { upto = k + 1; break; }
   2276                 if (write_all(1, buf, upto) < 0) { perr("error writing 'standard output'"); exit(1); }
   2277             }
   2278         }
   2279         if (fd) close(fd);
   2280     }
   2281     return st;
   2282 }
   2283 
   2284 struct follow { char *name; int fd; off_t pos; dev_t dev; ino_t ino; };
   2285 
   2286 static int t_tail(int argc, char **argv)
   2287 {
   2288     static const struct opt lo[] = {
   2289         { "bytes", 1, 'c' }, { "lines", 1, 'n' }, { "quiet", 0, 'q' }, { "silent", 0, 'q' }, { "verbose", 0, 'v' },
   2290         { "zero-terminated", 0, 'z' }, { "follow", 2, 'f' }, { "sleep-interval", 1, 's' },
   2291         { "pid", 1, 'p' }, { NULL, 0, 0 } };
   2292     int c, bytes = 0, quiet = 0, verbose = 0, i, st = 0, first = 1, sep = '\n', from_start = 0, follow = 0, byname = 0;
   2293     unsigned long long count = 10;
   2294     double interval = 0.25;
   2295     struct follow *fl;
   2296     argv = old_count_form(&argc, argv, "-n");
   2297     opts_reset();
   2298     while ((c = getopts(argc, argv, "c:n:qvzfFs:", lo)))
   2299         switch (c) {
   2300         case 'c': case 'n': {
   2301             const char *s = optarg;
   2302             bytes = c == 'c'; from_start = 0;
   2303             if (*s == '+') { from_start = 1; s++; } else if (*s == '-') s++;
   2304             if (!parse_size(s, &count)) die(1, "invalid number of %s: '%s'", bytes ? "bytes" : "lines", optarg);
   2305             break;
   2306         }
   2307         case 'q': quiet = 1; break;
   2308         case 'v': verbose = 1; break;
   2309         case 'z': sep = 0; break;
   2310         case 'f': follow = 1; if (optarg && !strcmp(optarg, "name")) byname = 1; break;
   2311         case 'F': follow = 1; byname = 1; break;
   2312         case 's': interval = strtod(optarg, NULL); if (interval <= 0) interval = 0.25; break;
   2313         default: break;
   2314         }
   2315     if (!nops) ops[nops++] = "-";
   2316     fl = xmalloc(nops * sizeof *fl);
   2317     for (i = 0; i < nops; i++) {
   2318         int fd = open_input(ops[i]);
   2319         struct stat sb;
   2320         char *data = NULL; size_t len = 0, start = 0;
   2321         fl[i].name = ops[i]; fl[i].fd = fd; fl[i].pos = 0; fl[i].dev = fl[i].ino = 0;
   2322         if (fd < 0) { perr("cannot open '%s' for reading", ops[i]); st = 1; continue; }
   2323         if (verbose || (!quiet && nops > 1)) print_header(ops[i], &first);
   2324         fflush(stdout);
   2325         if (fstat(fd, &sb) == 0) { fl[i].dev = sb.st_dev; fl[i].ino = sb.st_ino; }
   2326         if (fstat(fd, &sb) == 0 && S_ISREG(sb.st_mode) && !from_start) {
   2327             /* a file we can seek in: look backwards from the end */
   2328             off_t size = sb.st_size, pos = size;
   2329             if (bytes) start = size > (off_t)count ? size - count : 0;
   2330             else if (count == 0) start = size;
   2331             else {
   2332                 char blk[8192];
   2333                 unsigned long long seen = 0;
   2334                 int skip_last = 0;
   2335                 if (size > 0) { char lastc; if (pread(fd, &lastc, 1, size - 1) == 1 && lastc == sep) skip_last = 1; }
   2336                 start = 0;
   2337                 while (pos > 0) {
   2338                     off_t from = pos > (off_t)sizeof blk ? pos - sizeof blk : 0;
   2339                     ssize_t got = pread(fd, blk, pos - from, from), k;
   2340                     if (got <= 0) break;
   2341                     for (k = got - 1; k >= 0; k--) {
   2342                         if (from + k == size - 1 && skip_last) continue;
   2343                         if (blk[k] == sep && ++seen == count) { start = from + k + 1; goto found; }
   2344                     }
   2345                     pos = from;
   2346                 }
   2347 found:
   2348                 ;
   2349             }
   2350             lseek(fd, start, SEEK_SET);
   2351             fl[i].pos = start;
   2352             {
   2353                 char buf[1 << 16]; ssize_t n;
   2354                 while ((n = read(fd, buf, sizeof buf)) != 0) {
   2355                     if (n < 0) { if (errno == EINTR) continue; perr("error reading '%s'", ops[i]); st = 1; break; }
   2356                     if (write_all(1, buf, n) < 0) { perr("error writing 'standard output'"); exit(1); }
   2357                     fl[i].pos += n;
   2358                 }
   2359             }
   2360             continue;
   2361         }
   2362         if (read_all(fd, &data, &len) < 0) { perr("error reading '%s'", ops[i]); st = 1; continue; }
   2363         if (from_start) {
   2364             if (bytes) start = count > 1 ? (count - 1 < len ? count - 1 : len) : 0;
   2365             else {
   2366                 unsigned long long k = 1;
   2367                 while (k < count && start < len) { char *nl = memchr(data + start, sep, len - start); if (!nl) { start = len; break; } start = nl - data + 1; k++; }
   2368                 if (k < count) start = len;
   2369             }
   2370         } else if (bytes) start = len > count ? len - count : 0;
   2371         else if (count == 0) start = len;
   2372         else {
   2373             unsigned long long seen = 0;
   2374             size_t q = len;
   2375             int skip_last = len && data[len - 1] == sep;
   2376             start = 0;
   2377             while (q > 0) {
   2378                 q--;
   2379                 if (skip_last && q == len - 1) continue;
   2380                 if (data[q] == sep && ++seen == count) { start = q + 1; break; }
   2381             }
   2382         }
   2383         if (write_all(1, data + start, len - start) < 0) { perr("error writing 'standard output'"); exit(1); }
   2384         free(data);
   2385         fl[i].pos = len;
   2386     }
   2387     if (follow) {
   2388         int last = -1;
   2389         for (;;) {
   2390             struct timespec t;
   2391             for (i = 0; i < nops; i++) {
   2392                 struct stat sb, ps;
   2393                 char buf[1 << 16];
   2394                 ssize_t n;
   2395                 if (byname && stat(fl[i].name, &ps) == 0 && (fl[i].fd < 0 || ps.st_ino != fl[i].ino || ps.st_dev != fl[i].dev)) {
   2396                     int fd = open(fl[i].name, O_RDONLY);
   2397                     if (fd >= 0) {
   2398                         if (fl[i].fd > 0) close(fl[i].fd);
   2399                         if (fl[i].fd >= 0) say("'%s' has been replaced;  following new file", fl[i].name);
   2400                         else say("'%s' has appeared;  following new file", fl[i].name);
   2401                         fl[i].fd = fd; fl[i].pos = 0; fl[i].dev = ps.st_dev; fl[i].ino = ps.st_ino;
   2402                     }
   2403                 }
   2404                 if (fl[i].fd < 0) continue;
   2405                 if (fstat(fl[i].fd, &sb) == 0 && S_ISREG(sb.st_mode) && sb.st_size < fl[i].pos) {
   2406                     say("%s: file truncated", fl[i].name);
   2407                     lseek(fl[i].fd, 0, SEEK_SET); fl[i].pos = 0;
   2408                 }
   2409                 while ((n = read(fl[i].fd, buf, sizeof buf)) > 0) {
   2410                     if (nops > 1 && !quiet && last != i) print_header(fl[i].name, &first);
   2411                     last = i;
   2412                     if (write_all(1, buf, n) < 0) { perr("error writing 'standard output'"); exit(1); }
   2413                     fl[i].pos += n;
   2414                 }
   2415             }
   2416             fflush(stdout);
   2417             t.tv_sec = (long)interval; t.tv_nsec = (long)((interval - (double)t.tv_sec) * 1e9);
   2418             nanosleep(&t, NULL);
   2419         }
   2420     }
   2421     return st;
   2422 }
   2423 
   2424 /* ---- wc ---- */
   2425 
   2426 static int utf8_locale(void)
   2427 {
   2428     const char *v = getenv("LC_ALL");
   2429     if (!v || !*v) v = getenv("LC_CTYPE");
   2430     if (!v || !*v) v = getenv("LANG");
   2431     return v && (strstr(v, "UTF-8") || strstr(v, "utf8") || strstr(v, "UTF8") || strstr(v, "utf-8"));
   2432 }
   2433 
   2434 struct counts { unsigned long long lines, words, chars, bytes, maxlen; };
   2435 
   2436 static int wc_count(int fd, struct counts *c, int utf8)
   2437 {
   2438     static char buf[1 << 16];
   2439     ssize_t n;
   2440     int in_word = 0;
   2441     unsigned long long col = 0;
   2442     memset(c, 0, sizeof *c);
   2443     while ((n = read(fd, buf, sizeof buf)) != 0) {
   2444         ssize_t k;
   2445         if (n < 0) { if (errno == EINTR) continue; return -1; }
   2446         c->bytes += n;
   2447         for (k = 0; k < n; k++) {
   2448             unsigned char ch = buf[k];
   2449             if (utf8 && (ch & 0xc0) == 0x80) continue;
   2450             c->chars++;
   2451             if (ch == '\n') { c->lines++; if (col > c->maxlen) c->maxlen = col; col = 0; in_word = 0; continue; }
   2452             if (ch == '\t') col = (col / 8 + 1) * 8;
   2453             else if (ch == '\r' || ch == '\f') { if (col > c->maxlen) c->maxlen = col; col = 0; }
   2454             else if (ch >= 32 && ch != 127) col++;
   2455             if (isspace(ch)) in_word = 0;
   2456             else if (!in_word) { in_word = 1; c->words++; }
   2457         }
   2458     }
   2459     if (col > c->maxlen) c->maxlen = col;
   2460     return 0;
   2461 }
   2462 
   2463 static int t_wc(int argc, char **argv)
   2464 {
   2465     static const struct opt lo[] = {
   2466         { "bytes", 0, 'c' }, { "chars", 0, 'm' }, { "lines", 0, 'l' }, { "words", 0, 'w' }, { "max-line-length", 0, 'L' },
   2467         { "files0-from", 1, 'F' }, { "total", 1, 'T' }, { NULL, 0, 0 } };
   2468     int c, pl = 0, pw = 0, pc = 0, pb = 0, pL = 0, i, st = 0, ncols, width = 1, utf8 = utf8_locale();
   2469     int total_mode = 0;                     /* auto, always, only, never: 0 to 3 */
   2470     const char *from0 = NULL;
   2471     char **names; int nnames;
   2472     struct counts total;
   2473     unsigned long long reg_total = 0;
   2474     int stdin_only;
   2475     opts_reset();
   2476     while ((c = getopts(argc, argv, "cmlwL", lo)))
   2477         switch (c) {
   2478         case 'c': pb = 1; break; case 'm': pc = 1; break; case 'l': pl = 1; break; case 'w': pw = 1; break; case 'L': pL = 1; break;
   2479         case 'F': from0 = optarg; break;
   2480         case 'T':
   2481             if (!strcmp(optarg, "auto")) total_mode = 0; else if (!strcmp(optarg, "always")) total_mode = 1;
   2482             else if (!strcmp(optarg, "only")) total_mode = 2; else if (!strcmp(optarg, "never")) total_mode = 3;
   2483             else die(1, "invalid argument '%s' for '--total'", optarg);
   2484             break;
   2485         }
   2486     if (!(pl | pw | pc | pb | pL)) pl = pw = pb = 1;
   2487     ncols = pl + pw + pc + pb + pL;
   2488     if (from0) {
   2489         char *data; size_t len, k = 0;
   2490         int fd;
   2491         if (nops) { say("extra operand '%s'", ops[0]); fprintf(stderr, "file operands cannot be combined with --files0-from\n"); usage_error(); }
   2492         fd = open_input(from0);
   2493         if (fd < 0 || read_all(fd, &data, &len) < 0) die(1, "cannot open '%s' for reading: %s", from0, strerror(errno));
   2494         names = xmalloc((len + 2) * sizeof *names); nnames = 0;
   2495         while (k < len) { names[nnames++] = data + k; k += strlen(data + k) + 1; }
   2496     } else { names = ops; nnames = nops; }
   2497     stdin_only = nnames == 0;
   2498     if (stdin_only) { names = (char *[]){ "-", NULL }; nnames = 1; }
   2499     /* width as GNU does it: from the sizes of regular files, 7 if any input is something else (a pipe), 1 for one
   2500      * input with one column */
   2501     if (!(nnames <= 1 && ncols == 1) && total_mode != 2) {
   2502         for (i = 0; i < nnames; i++) {
   2503             struct stat sb;
   2504             int r = !strcmp(names[i], "-") ? fstat(0, &sb) : stat(names[i], &sb);
   2505             if (r < 0) continue;
   2506             if (S_ISREG(sb.st_mode)) reg_total += sb.st_size; else { width = 7; break; }
   2507         }
   2508         if (width != 7) for (; reg_total >= 10; reg_total /= 10) width++;
   2509     }
   2510     memset(&total, 0, sizeof total);
   2511 #define SHOW(flag, v) if (flag) { printf("%s%*llu", first_col ? "" : " ", width, v); first_col = 0; }
   2512     for (i = 0; i < nnames; i++) {
   2513         struct counts k;
   2514         int fd = open_input(names[i]), first_col = 1;
   2515         struct stat sb;
   2516         if (fd < 0) { perr("%s", names[i]); st = 1; continue; }
   2517         if (fstat(fd, &sb) == 0 && S_ISDIR(sb.st_mode)) {
   2518             memset(&k, 0, sizeof k);
   2519             if (total_mode != 2) {
   2520                 SHOW(pl, 0) SHOW(pw, 0) SHOW(pc, 0) SHOW(pb, 0) SHOW(pL, 0)
   2521                 if (!stdin_only) printf(" %s", names[i]);
   2522                 putchar('\n');
   2523             }
   2524             perr("%s", names[i]); st = 1; if (fd) close(fd);
   2525             continue;
   2526         }
   2527         if (wc_count(fd, &k, utf8) < 0) { perr("%s", names[i]); st = 1; if (fd) close(fd); continue; }
   2528         if (fd) close(fd);
   2529         total.lines += k.lines; total.words += k.words; total.chars += k.chars; total.bytes += k.bytes;
   2530         if (k.maxlen > total.maxlen) total.maxlen = k.maxlen;
   2531         if (total_mode == 2) continue;
   2532         SHOW(pl, k.lines) SHOW(pw, k.words) SHOW(pc, utf8 ? k.chars : k.bytes) SHOW(pb, k.bytes) SHOW(pL, k.maxlen)
   2533         if (!stdin_only) printf(" %s", names[i]);
   2534         putchar('\n');
   2535     }
   2536     if (total_mode == 1 || total_mode == 2 || (total_mode == 0 && nnames > 1)) {
   2537         int first_col = 1;
   2538         SHOW(pl, total.lines) SHOW(pw, total.words) SHOW(pc, utf8 ? total.chars : total.bytes) SHOW(pb, total.bytes) SHOW(pL, total.maxlen)
   2539         if (total_mode != 2) printf(" total");
   2540         putchar('\n');
   2541     }
   2542     return finish_stdout() ? 1 : st;
   2543 }
   2544 
   2545 /* ---- tee ---- */
   2546 
   2547 static int t_tee(int argc, char **argv)
   2548 {
   2549     static const struct opt lo[] = { { "append", 0, 'a' }, { "ignore-interrupts", 0, 'i' }, { "output-error", 2, 'e' }, { NULL, 0, 0 } };
   2550     int c, append = 0, i, n, st = 0;
   2551     int *fds;
   2552     static char buf[1 << 16];
   2553     ssize_t r;
   2554     opts_reset();
   2555     while ((c = getopts(argc, argv, "aip", lo)))
   2556         switch (c) { case 'a': append = 1; break; case 'i': signal(SIGINT, SIG_IGN); break; }
   2557     n = nops;
   2558     fds = xmalloc((n + 1) * sizeof *fds);
   2559     for (i = 0; i < n; i++) {
   2560         fds[i] = open(ops[i], O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0666);
   2561         if (fds[i] < 0) { perr("%s", ops[i]); st = 1; }
   2562     }
   2563     while ((r = read(0, buf, sizeof buf)) != 0) {
   2564         if (r < 0) { if (errno == EINTR) continue; perr("standard input"); st = 1; break; }
   2565         if (write_all(1, buf, r) < 0) { perr("standard output"); st = 1; break; }
   2566         for (i = 0; i < n; i++)
   2567             if (fds[i] >= 0 && write_all(fds[i], buf, r) < 0) { perr("%s", ops[i]); fds[i] = -1; st = 1; }
   2568     }
   2569     for (i = 0; i < n; i++) if (fds[i] > 1) close(fds[i]);
   2570     return st;
   2571 }
   2572 
   2573 /* ---- tr ---- */
   2574 
   2575 static int is_blank_c(int c) { return c == ' ' || c == '\t'; }
   2576 static int is_cntrl_c(int c) { return c < 32 || c == 127; }
   2577 static int is_graph_c(int c) { return c > 32 && c < 127; }
   2578 static int is_punct_c(int c) { return is_graph_c(c) && !isalnum(c); }
   2579 
   2580 static int tr_escape(const char **p)
   2581 {
   2582     int c = (unsigned char)**p;
   2583     if (c >= '0' && c <= '7') {
   2584         int v = 0, n = 0;
   2585         for (; n < 3 && **p >= '0' && **p <= '7'; n++, (*p)++) v = v * 8 + **p - '0';
   2586         return v & 255;
   2587     }
   2588     (*p)++;
   2589     switch (c) {
   2590     case 'a': return 7;
   2591     case 'b': return 8;
   2592     case 'f': return 12;
   2593     case 'n': return 10;
   2594     case 'r': return 13;
   2595     case 't': return 9;
   2596     case 'v': return 11;
   2597     case 0: (*p)--; return '\\';
   2598     }
   2599     return c;
   2600 }
   2601 
   2602 static int in_class(const char *name, int ch)
   2603 {
   2604     if (!strcmp(name, "alnum")) return isalnum(ch);
   2605     if (!strcmp(name, "alpha")) return isalpha(ch);
   2606     if (!strcmp(name, "blank")) return is_blank_c(ch);
   2607     if (!strcmp(name, "cntrl")) return is_cntrl_c(ch);
   2608     if (!strcmp(name, "digit")) return isdigit(ch);
   2609     if (!strcmp(name, "graph")) return is_graph_c(ch);
   2610     if (!strcmp(name, "lower")) return islower(ch);
   2611     if (!strcmp(name, "print")) return isprint(ch);
   2612     if (!strcmp(name, "punct")) return is_punct_c(ch);
   2613     if (!strcmp(name, "space")) return isspace(ch);
   2614     if (!strcmp(name, "upper")) return isupper(ch);
   2615     if (!strcmp(name, "xdigit")) return isxdigit(ch);
   2616     return -1;
   2617 }
   2618 
   2619 /* a tr SET as a list of bytes. a [c*] with no count has to stretch to fit the other set, so its place is
   2620  * returned in fill_at */
   2621 static unsigned char *tr_expand(const char *s, size_t *len, int *fill_at, int *fill_ch)
   2622 {
   2623     size_t cap = strlen(s) * 4 + 256, n = 0;
   2624     unsigned char *r = xmalloc(cap);
   2625     *fill_at = *fill_ch = -1;
   2626 #define PUSH(ch) do { if (n == cap) { cap *= 2; r = xrealloc(r, cap); } r[n++] = (ch); } while (0)
   2627     while (*s) {
   2628         const char *e;
   2629         if (s[0] == '[' && s[1] == ':' && (e = strstr(s + 2, ":]"))) {
   2630             char name[16];
   2631             int ch;
   2632             if ((size_t)(e - s - 2) >= sizeof name) die(1, "invalid character class '%.*s'", (int)(e - s - 2), s + 2);
   2633             memcpy(name, s + 2, e - s - 2);
   2634             name[e - s - 2] = 0;
   2635             if (in_class(name, 'a') < 0) die(1, "invalid character class '%s'", name);
   2636             for (ch = 0; ch < 256; ch++) if (in_class(name, ch)) PUSH(ch);
   2637             s = e + 2;
   2638             continue;
   2639         }
   2640         if (s[0] == '[' && s[1] == '=' && s[2] && !strncmp(s + 3, "=]", 2)) { PUSH((unsigned char)s[2]); s += 5; continue; }
   2641         if (s[0] == '[' && s[1]) {
   2642             const char *q = s + 1;
   2643             int ch;
   2644             if (*q == '\\') { q++; ch = tr_escape(&q); } else ch = (unsigned char)*q++;
   2645             if (*q == '*') {
   2646                 char *end;
   2647                 unsigned long cnt;
   2648                 if (q[1] == ']') { *fill_at = n; *fill_ch = ch; s = q + 2; continue; }
   2649                 cnt = strtoul(q + 1, &end, q[1] == '0' ? 8 : 10);
   2650                 if (end != q + 1 && *end == ']') { while (cnt--) PUSH(ch); s = end + 1; continue; }
   2651             }
   2652         }
   2653         {
   2654             int ch, hi;
   2655             if (*s == '\\') { s++; ch = tr_escape(&s); } else ch = (unsigned char)*s++;
   2656             if (*s == '-' && s[1]) {
   2657                 s++;
   2658                 if (*s == '\\') { s++; hi = tr_escape(&s); } else hi = (unsigned char)*s++;
   2659                 if (hi < ch) die(1, "range-endpoints of '%c-%c' are in reverse collating sequence order", ch, hi);
   2660                 for (; ch <= hi; ch++) PUSH(ch);
   2661             } else PUSH(ch);
   2662         }
   2663     }
   2664     *len = n;
   2665     return r;
   2666 }
   2667 
   2668 static int t_tr(int argc, char **argv)
   2669 {
   2670     static const struct opt lo[] = {
   2671         { "complement", 0, 'c' }, { "delete", 0, 'd' }, { "squeeze-repeats", 0, 's' }, { "truncate-set1", 0, 't' }, { NULL, 0, 0 } };
   2672     static unsigned char in[1 << 16], out[1 << 16];
   2673     unsigned char *s1, *s2 = NULL, map[256], inset[256], sqset[256];
   2674     size_t n1, n2 = 0, k;
   2675     int c, comp = 0, del = 0, sq = 0, trunc = 0, i, f1, c1, f2 = -1, c2 = -1, translate, prev = -1;
   2676     ssize_t r;
   2677     opts_reset();
   2678     while ((c = getopts(argc, argv, "cCdst", lo)))
   2679         switch (c) {
   2680         case 'c': case 'C': comp = 1; break;
   2681         case 'd': del = 1; break;
   2682         case 's': sq = 1; break;
   2683         case 't': trunc = 1; break;
   2684         }
   2685     if (!nops) missing_operand();
   2686     if (nops > 2) extra_operand(ops[2]);
   2687     if (nops == 1 && !del && !sq) {
   2688         say("missing operand after '%s'", ops[0]);
   2689         fprintf(stderr, "Two strings must be given when translating.\n");
   2690         usage_error();
   2691     }
   2692     if (nops == 2 && del && !sq) {
   2693         say("extra operand '%s'", ops[1]);
   2694         fprintf(stderr, "Only one string may be given when deleting without squeezing repeats.\n");
   2695         usage_error();
   2696     }
   2697     s1 = tr_expand(ops[0], &n1, &f1, &c1);
   2698     if (comp) {
   2699         unsigned char seen[256], *nw = xmalloc(256);
   2700         size_t m = 0;
   2701         memset(seen, 0, sizeof seen);
   2702         for (k = 0; k < n1; k++) seen[s1[k]] = 1;
   2703         for (i = 0; i < 256; i++) if (!seen[i]) nw[m++] = i;
   2704         free(s1); s1 = nw; n1 = m;
   2705     }
   2706     translate = !del && nops == 2;
   2707     if (nops == 2) s2 = tr_expand(ops[1], &n2, &f2, &c2);
   2708     memset(inset, 0, sizeof inset);
   2709     memset(sqset, 0, sizeof sqset);
   2710     for (i = 0; i < 256; i++) map[i] = i;
   2711     for (k = 0; k < n1; k++) inset[s1[k]] = 1;
   2712     if (translate) {
   2713         if (f2 >= 0 && n1 > n2) {
   2714             size_t want = n1 - n2;
   2715             unsigned char *g = xmalloc(n1 + 1);
   2716             memcpy(g, s2, f2);
   2717             memset(g + f2, c2, want);
   2718             memcpy(g + f2 + want, s2 + f2, n2 - f2);
   2719             free(s2); s2 = g; n2 = n1;
   2720         }
   2721         if (!n2 && !trunc) die(1, "when not truncating set1, string2 must be non-empty");
   2722         if (trunc && n1 > n2) n1 = n2;
   2723         for (k = 0; k < n1; k++) map[s1[k]] = k < n2 ? s2[k] : s2[n2 - 1];
   2724         if (sq) for (k = 0; k < n2; k++) sqset[s2[k]] = 1;
   2725     } else if (sq) {
   2726         if (nops == 2) for (k = 0; k < n2; k++) sqset[s2[k]] = 1;
   2727         else memcpy(sqset, inset, sizeof sqset);
   2728     }
   2729     while ((r = read(0, in, sizeof in)) != 0) {
   2730         size_t o = 0;
   2731         if (r < 0) { if (errno == EINTR) continue; perr("read error"); return 1; }
   2732         for (k = 0; k < (size_t)r; k++) {
   2733             int ch = in[k];
   2734             if (del && inset[ch]) continue;
   2735             if (translate) ch = map[ch];
   2736             if (sq && sqset[ch]) { if (ch == prev) continue; prev = ch; }
   2737             else prev = -1;
   2738             out[o++] = ch;
   2739         }
   2740         if (write_all(1, (char *)out, o) < 0) { perr("write error"); return 1; }
   2741     }
   2742     return 0;
   2743 }
   2744 
   2745 /* ---- seq ---- */
   2746 
   2747 static int all_digits(const char *s)
   2748 {
   2749     if (*s == '+' || *s == '-') s++;
   2750     if (!*s) return 0;
   2751     for (; *s; s++) if (!isdigit((unsigned char)*s)) return 0;
   2752     return 1;
   2753 }
   2754 
   2755 static int decimals(const char *s)
   2756 {
   2757     const char *dot = strchr(s, '.');
   2758     int n = 0;
   2759     if (strpbrk(s, "eE")) return -1;
   2760     if (dot) for (dot++; isdigit((unsigned char)*dot); dot++) n++;
   2761     return n;
   2762 }
   2763 
   2764 /* a number starting with - is an operand: seq -5 5 */
   2765 static void guard_negative(int *argc, char ***argv)
   2766 {
   2767     int i, j;
   2768     char **n;
   2769     for (i = 1; i < *argc; i++) {
   2770         const char *a = (*argv)[i];
   2771         if (!strcmp(a, "--")) return;
   2772         if (a[0] == '-' && (isdigit((unsigned char)a[1]) || a[1] == '.')) break;
   2773     }
   2774     if (i == *argc) return;
   2775     n = xmalloc((*argc + 2) * sizeof *n);
   2776     for (j = 0; j < i; j++) n[j] = (*argv)[j];
   2777     n[i] = "--";
   2778     for (j = i; j <= *argc; j++) n[j + 1] = (*argv)[j];
   2779     (*argc)++;
   2780     *argv = n;
   2781 }
   2782 
   2783 /* zeros between the sign and the digits, for -w */
   2784 static void put_padded(const char *t, size_t width)
   2785 {
   2786     size_t l = strlen(t), neg = t[0] == '-';
   2787     if (l < width) {
   2788         if (neg) putchar('-');
   2789         for (; l < width; l++) putchar('0');
   2790         fputs(t + neg, stdout);
   2791     } else fputs(t, stdout);
   2792 }
   2793 
   2794 static int t_seq(int argc, char **argv)
   2795 {
   2796     static const struct opt lo[] = { { "format", 1, 'f' }, { "separator", 1, 's' }, { "equal-width", 0, 'w' }, { NULL, 0, 0 } };
   2797     const char *fmt = NULL, *sep = "\n", *sf, *si, *sl;
   2798     char *end, t[512];
   2799     size_t width = 0;
   2800     int c, eq = 0;
   2801     guard_negative(&argc, &argv);
   2802     opts_reset();
   2803     while ((c = getopts(argc, argv, "f:s:w", lo)))
   2804         switch (c) {
   2805         case 'f': fmt = optarg; break;
   2806         case 's': sep = optarg; break;
   2807         case 'w': eq = 1; break;
   2808         }
   2809     if (!nops) missing_operand();
   2810     if (nops > 3) extra_operand(ops[3]);
   2811     sf = nops > 1 ? ops[0] : "1";
   2812     si = nops > 2 ? ops[1] : "1";
   2813     sl = ops[nops - 1];
   2814     if (all_digits(sf) && all_digits(si) && all_digits(sl) && !fmt) {
   2815         long long first = strtoll(sf, NULL, 10), inc = strtoll(si, NULL, 10), last = strtoll(sl, NULL, 10), v;
   2816         int started = 0;
   2817         if (!inc) die(1, "invalid Zero increment value: '%s'", si);
   2818         if (eq) {
   2819             size_t a = snprintf(t, sizeof t, "%lld", first), b = snprintf(t, sizeof t, "%lld", last);
   2820             width = a > b ? a : b;
   2821         }
   2822         for (v = first; inc > 0 ? v <= last : v >= last; v += inc) {
   2823             if (started) fputs(sep, stdout);
   2824             started = 1;
   2825             snprintf(t, sizeof t, "%lld", v);
   2826             put_padded(t, width);
   2827             if (inc > 0 ? v > last - inc : v < last - inc) break;
   2828         }
   2829         if (started) putchar('\n');
   2830     } else {
   2831         double first = strtod(sf, &end), inc, last;
   2832         int prec = 0, p, k, started = 0;
   2833         if (*end) die(1, "invalid floating point argument: '%s'", sf);
   2834         inc = strtod(si, &end);
   2835         if (*end) die(1, "invalid floating point argument: '%s'", si);
   2836         last = strtod(sl, &end);
   2837         if (*end) die(1, "invalid floating point argument: '%s'", sl);
   2838         if (inc == 0) die(1, "invalid Zero increment value: '%s'", si);
   2839         p = decimals(sf); if (p > prec) prec = p;
   2840         p = decimals(si); if (p > prec) prec = p;
   2841         p = decimals(sl); if (p > prec) prec = p;
   2842         if (prec < 0) prec = 6;
   2843         if (eq && !fmt) {
   2844             size_t a = snprintf(t, sizeof t, "%.*f", prec, first), b = snprintf(t, sizeof t, "%.*f", prec, last);
   2845             width = a > b ? a : b;
   2846         }
   2847         for (k = 0; ; k++) {
   2848             double v = first + k * inc;
   2849             if (inc > 0 ? v > last + inc * 1e-9 : v < last + inc * 1e-9) break;
   2850             if (started) fputs(sep, stdout);
   2851             started = 1;
   2852             if (fmt) snprintf(t, sizeof t, fmt, v);
   2853             else snprintf(t, sizeof t, "%.*f", prec, v);
   2854             put_padded(t, width);
   2855         }
   2856         if (started) putchar('\n');
   2857     }
   2858     return finish_stdout();
   2859 }
   2860 
   2861 /* ---- tac nl fold ---- */
   2862 
   2863 static int t_tac(int argc, char **argv)
   2864 {
   2865     static const struct opt lo[] = { { "before", 0, 'b' }, { "regex", 0, 'r' }, { "separator", 1, 's' }, { NULL, 0, 0 } };
   2866     const char *sep = "\n";
   2867     int c, before = 0, i, st = 0;
   2868     size_t sl;
   2869     opts_reset();
   2870     while ((c = getopts(argc, argv, "brs:", lo))) {
   2871         if (c == 'b') before = 1;
   2872         else if (c == 's') sep = optarg;
   2873     }
   2874     if (!*sep) die(1, "separator cannot be empty");
   2875     sl = strlen(sep);
   2876     if (!nops) ops[nops++] = "-";
   2877     for (i = 0; i < nops; i++) {
   2878         char *d;
   2879         size_t len, end, k;
   2880         int fd = open_input(ops[i]);
   2881         if (fd < 0) { perr("failed to open '%s' for reading", ops[i]); st = 1; continue; }
   2882         if (read_all(fd, &d, &len) < 0) { perr("%s: read error", ops[i]); st = 1; if (fd) close(fd); continue; }
   2883         if (fd) close(fd);
   2884         for (end = len; end; end = k) {
   2885             k = end;
   2886             if (before) {
   2887                 while (k >= sl && memcmp(d + k - sl, sep, sl)) k--;     /* back to a separator at the start of a record */
   2888                 k = k >= sl ? k - sl : 0;
   2889             } else {
   2890                 if (k >= sl && !memcmp(d + k - sl, sep, sl)) k -= sl;    /* this record's own separator */
   2891                 while (k >= sl && memcmp(d + k - sl, sep, sl)) k--;
   2892                 if (k < sl) k = 0;
   2893             }
   2894             if (write_all(1, d + k, end - k) < 0) { perr("write error"); return 1; }
   2895         }
   2896         free(d);
   2897     }
   2898     return st;
   2899 }
   2900 
   2901 static int t_nl(int argc, char **argv)
   2902 {
   2903     static const struct opt lo[] = {
   2904         { "body-numbering", 1, 'b' }, { "header-numbering", 1, 'h' }, { "footer-numbering", 1, 'f' }, { "number-format", 1, 'n' },
   2905         { "number-width", 1, 'w' }, { "number-separator", 1, 's' }, { "starting-line-number", 1, 'v' },
   2906         { "line-increment", 1, 'i' }, { "join-blank-lines", 1, 'l' }, { "no-renumber", 0, 'p' }, { "section-delimiter", 1, 'd' }, { NULL, 0, 0 } };
   2907     const char *style = "t", *fmt = "rn", *sep = "\t";
   2908     long long no = 1, inc = 1;
   2909     int c, i, st = 0, width = 6, join = 1;
   2910     opts_reset();
   2911     while ((c = getopts(argc, argv, "b:h:f:n:w:s:v:i:l:pd:", lo)))
   2912         switch (c) {
   2913         case 'b':
   2914             style = optarg;
   2915             if (strcmp(style, "a") && strcmp(style, "t") && strcmp(style, "n")) die(1, "invalid body numbering style: '%s'", style);
   2916             break;
   2917         case 'n':
   2918             fmt = optarg;
   2919             if (strcmp(fmt, "ln") && strcmp(fmt, "rn") && strcmp(fmt, "rz")) die(1, "invalid line numbering format: '%s'", fmt);
   2920             break;
   2921         case 'w': width = atoi(optarg); if (width < 1) die(1, "invalid line number field width: '%s'", optarg); break;
   2922         case 's': sep = optarg; break;
   2923         case 'v': no = atoll(optarg); break;
   2924         case 'i': inc = atoll(optarg); break;
   2925         case 'l': join = atoi(optarg); if (join < 1) die(1, "invalid line number of blank lines: '%s'", optarg); break;
   2926         }
   2927     if (nops > 1) extra_operand(ops[1]);
   2928     if (!nops) ops[nops++] = "-";
   2929     for (i = 0; i < nops; i++) {
   2930         char *d;
   2931         size_t len, p = 0;
   2932         int fd = open_input(ops[i]), blanks = 0;
   2933         if (fd < 0) { perr("%s", ops[i]); st = 1; continue; }
   2934         if (read_all(fd, &d, &len) < 0) { perr("%s", ops[i]); st = 1; if (fd) close(fd); continue; }
   2935         if (fd) close(fd);
   2936         while (p < len) {
   2937             char *nl = memchr(d + p, '\n', len - p);
   2938             size_t l = nl ? (size_t)(nl - d) - p : len - p;
   2939             int number = style[0] == 'a' || (style[0] == 't' && l > 0);
   2940             if (style[0] == 'a' && l == 0) {
   2941                 if (++blanks < join) number = 0;
   2942                 else blanks = 0;
   2943             } else if (l) blanks = 0;
   2944             if (number) {
   2945                 printf(!strcmp(fmt, "ln") ? "%-*lld" : !strcmp(fmt, "rz") ? "%0*lld" : "%*lld", width, no);
   2946                 fputs(sep, stdout);
   2947                 no += inc;
   2948             } else printf("%*s", width + (int)strlen(sep), "");
   2949             fwrite(d + p, 1, l, stdout);
   2950             putchar('\n');
   2951             p += l + !!nl;
   2952         }
   2953         free(d);
   2954     }
   2955     return finish_stdout() ? 1 : st;
   2956 }
   2957 
   2958 static unsigned long advance(unsigned long col, unsigned char ch, int bytes)
   2959 {
   2960     if (bytes) return col + 1;
   2961     if (ch == '\t') return (col / 8 + 1) * 8;
   2962     if (ch == '\b') return col ? col - 1 : 0;
   2963     if (ch == '\r') return 0;
   2964     return col + 1;
   2965 }
   2966 
   2967 static int t_fold(int argc, char **argv)
   2968 {
   2969     static const struct opt lo[] = { { "bytes", 0, 'b' }, { "spaces", 0, 's' }, { "width", 1, 'w' }, { NULL, 0, 0 } };
   2970     unsigned long width = 80;
   2971     char *line = NULL;
   2972     size_t cap = 0;
   2973     int c, bytes = 0, spaces = 0, i, st = 0;
   2974     argv = old_count_form(&argc, argv, "-w");
   2975     opts_reset();
   2976     while ((c = getopts(argc, argv, "bsw:", lo)))
   2977         switch (c) {
   2978         case 'b': bytes = 1; break;
   2979         case 's': spaces = 1; break;
   2980         case 'w': if (!parse_ulong(optarg, &width) || !width) die(1, "invalid number of columns: '%s'", optarg); break;
   2981         }
   2982     if (!nops) ops[nops++] = "-";
   2983     for (i = 0; i < nops; i++) {
   2984         char *d;
   2985         size_t len, k, n = 0;
   2986         unsigned long col = 0;
   2987         int fd = open_input(ops[i]);
   2988         if (fd < 0) { perr("%s", ops[i]); st = 1; continue; }
   2989         if (read_all(fd, &d, &len) < 0) { perr("%s", ops[i]); st = 1; if (fd) close(fd); continue; }
   2990         if (fd) close(fd);
   2991         for (k = 0; k < len; k++) {
   2992             unsigned char ch = d[k];
   2993             unsigned long next;
   2994             if (n + 2 > cap) { cap = cap ? cap * 2 : 256; line = xrealloc(line, cap); }
   2995             if (ch == '\n') { fwrite(line, 1, n, stdout); putchar('\n'); n = 0; col = 0; continue; }
   2996             next = advance(col, ch, bytes);
   2997             if (next > width && ch != '\b' && ch != '\r') {
   2998                 size_t cut = n, j;
   2999                 if (spaces) {
   3000                     for (j = n; j > 0 && line[j - 1] != ' ' && line[j - 1] != '\t'; j--) ;
   3001                     if (j) cut = j;
   3002                 }
   3003                 fwrite(line, 1, cut, stdout);
   3004                 putchar('\n');
   3005                 memmove(line, line + cut, n - cut);
   3006                 n -= cut;
   3007                 for (col = 0, j = 0; j < n; j++) col = advance(col, line[j], bytes);
   3008                 next = advance(col, ch, bytes);
   3009             }
   3010             line[n++] = ch;
   3011             col = next;
   3012         }
   3013         fwrite(line, 1, n, stdout);
   3014         free(d);
   3015     }
   3016     return finish_stdout() ? 1 : st;
   3017 }
   3018 
   3019 /* ---- cut paste ---- */
   3020 
   3021 /* lines of a buffer, cut at sep. the last one may have no terminator */
   3022 static size_t split_lines(char *d, size_t len, int sep, char ***out)
   3023 {
   3024     size_t n = 0, cap = 256, p = 0;
   3025     char **v = xmalloc(cap * sizeof *v);
   3026     while (p < len) {
   3027         char *e = memchr(d + p, sep, len - p);
   3028         if (n == cap) { cap *= 2; v = xrealloc(v, cap * sizeof *v); }
   3029         v[n++] = d + p;
   3030         if (!e) break;
   3031         *e = 0;
   3032         p = e - d + 1;
   3033     }
   3034     *out = v;
   3035     return n;
   3036 }
   3037 
   3038 struct ranges { unsigned char *sel; unsigned long limit, open_from; int complement; };
   3039 
   3040 static int selected(const struct ranges *r, unsigned long i)
   3041 {
   3042     int in = (i <= r->limit && r->sel[i]) || i >= r->open_from;
   3043     return in != r->complement;
   3044 }
   3045 
   3046 static void parse_list(const char *s, struct ranges *r, const char *what)
   3047 {
   3048     const char *p;
   3049     unsigned long max = 0;
   3050     r->open_from = ~0UL;
   3051     for (p = s; *p; ) {                                  /* first pass: how far do the numbers go */
   3052         char *e;
   3053         unsigned long lo = 0, hi = 0;
   3054         if (*p != '-') { lo = strtoul(p, &e, 10); if (e == p || !lo) goto bad; p = e; } else lo = 1;
   3055         if (*p == '-') {
   3056             p++;
   3057             if (isdigit((unsigned char)*p)) { hi = strtoul(p, &e, 10); p = e; if (hi < lo) die(1, "invalid decreasing range"); }
   3058             else hi = ~0UL;
   3059         } else hi = lo;
   3060         if (hi != ~0UL && hi > max) max = hi;
   3061         if (hi == ~0UL && lo > max) max = lo;
   3062         if (*p == ',' || *p == ' ') p++;
   3063         else if (*p) goto bad;
   3064     }
   3065     r->limit = max;
   3066     r->sel = xmalloc(max + 2);
   3067     memset(r->sel, 0, max + 2);
   3068     for (p = s; *p; ) {
   3069         char *e;
   3070         unsigned long lo = 1, hi, i;
   3071         if (*p != '-') { lo = strtoul(p, &e, 10); p = e; }
   3072         if (*p == '-') {
   3073             p++;
   3074             if (isdigit((unsigned char)*p)) { hi = strtoul(p, &e, 10); p = e; } else hi = ~0UL;
   3075         } else hi = lo;
   3076         if (hi == ~0UL) { if (lo < r->open_from) r->open_from = lo; }
   3077         else for (i = lo; i <= hi; i++) r->sel[i] = 1;
   3078         if (*p == ',' || *p == ' ') p++;
   3079     }
   3080     return;
   3081 bad:
   3082     die(1, "invalid %s list: '%s'", what, s);
   3083 }
   3084 
   3085 static int t_cut(int argc, char **argv)
   3086 {
   3087     static const struct opt lo[] = {
   3088         { "bytes", 1, 'b' }, { "characters", 1, 'c' }, { "fields", 1, 'f' }, { "delimiter", 1, 'd' }, { "only-delimited", 0, 's' },
   3089         { "complement", 0, 'C' }, { "output-delimiter", 1, 'O' }, { "zero-terminated", 0, 'z' }, { NULL, 0, 0 } };
   3090     struct ranges r = { NULL, 0, 0, 0 };
   3091     const char *list = NULL, *odelim = NULL;
   3092     int c, mode = 0, delim = '\t', onlydel = 0, sep = '\n', i, st = 0;
   3093     opts_reset();
   3094     while ((c = getopts(argc, argv, "b:c:f:d:nsz", lo)))
   3095         switch (c) {
   3096         case 'b': case 'c': case 'f':
   3097             if (mode && mode != c) die(1, "only one type of list may be specified");
   3098             mode = c; list = optarg;
   3099             break;
   3100         case 'd':
   3101             if (strlen(optarg) > 1) die(1, "the delimiter must be a single character");
   3102             delim = (unsigned char)optarg[0];
   3103             break;
   3104         case 's': onlydel = 1; break;
   3105         case 'C': r.complement = 1; break;
   3106         case 'O': odelim = optarg; break;
   3107         case 'z': sep = 0; break;
   3108         }
   3109     if (!mode) { say("you must specify a list of bytes, characters, or fields"); usage_error(); }
   3110     if (onlydel && mode != 'f') die(1, "suppressing non-delimited lines makes sense only when operating on fields");
   3111     parse_list(list, &r, mode == 'f' ? "field" : "byte/character position");
   3112     if (!nops) ops[nops++] = "-";
   3113     for (i = 0; i < nops; i++) {
   3114         char *d, **v;
   3115         size_t len, n, k;
   3116         int fd = open_input(ops[i]);
   3117         if (fd < 0) { perr("%s", ops[i]); st = 1; continue; }
   3118         if (read_all(fd, &d, &len) < 0) { perr("%s", ops[i]); st = 1; if (fd) close(fd); continue; }
   3119         if (fd) close(fd);
   3120         n = split_lines(d, len, sep, &v);
   3121         for (k = 0; k < n; k++) {
   3122             const char *line = v[k], *p;
   3123             size_t ll = strlen(line), j;
   3124             if (mode == 'f') {
   3125                 unsigned long f = 1;
   3126                 int printed = 0;
   3127                 if (!memchr(line, delim, ll)) {
   3128                     if (!onlydel) { fputs(line, stdout); putchar(sep); }
   3129                     continue;
   3130                 }
   3131                 for (p = line; ; f++) {
   3132                     const char *e = memchr(p, delim, line + ll - p);
   3133                     size_t fl = e ? (size_t)(e - p) : (size_t)(line + ll - p);
   3134                     if (selected(&r, f)) {
   3135                         if (printed) { if (odelim) fputs(odelim, stdout); else putchar(delim); }
   3136                         fwrite(p, 1, fl, stdout);
   3137                         printed = 1;
   3138                     }
   3139                     if (!e) break;
   3140                     p = e + 1;
   3141                 }
   3142                 putchar(sep);
   3143             } else {
   3144                 int printed = 0, gap = 0;
   3145                 for (j = 0; j < ll; j++) {
   3146                     if (selected(&r, j + 1)) {
   3147                         if (gap && printed && odelim) fputs(odelim, stdout);
   3148                         putchar(line[j]);
   3149                         printed = 1; gap = 0;
   3150                     } else gap = 1;
   3151                 }
   3152                 putchar(sep);
   3153             }
   3154         }
   3155         free(v); free(d);
   3156     }
   3157     return finish_stdout() ? 1 : st;
   3158 }
   3159 
   3160 struct reader { char *d; size_t len, pos; int ok; };
   3161 
   3162 static int next_line(struct reader *r, char **line, size_t *ll, int sep)
   3163 {
   3164     char *e;
   3165     if (r->pos >= r->len) return 0;
   3166     e = memchr(r->d + r->pos, sep, r->len - r->pos);
   3167     *line = r->d + r->pos;
   3168     *ll = e ? (size_t)(e - r->d) - r->pos : r->len - r->pos;
   3169     r->pos += *ll + (e != NULL);
   3170     return 1;
   3171 }
   3172 
   3173 static int t_paste(int argc, char **argv)
   3174 {
   3175     static const struct opt lo[] = { { "delimiters", 1, 'd' }, { "serial", 0, 's' }, { "zero-terminated", 0, 'z' }, { NULL, 0, 0 } };
   3176     char *delims = "\t", dl[256];
   3177     int c, serial = 0, sep = '\n', i, nd, st = 0;
   3178     struct reader *rd, stdin_rd;
   3179     int stdin_loaded = 0;
   3180     opts_reset();
   3181     while ((c = getopts(argc, argv, "d:sz", lo)))
   3182         switch (c) { case 'd': delims = optarg; break; case 's': serial = 1; break; case 'z': sep = 0; break; }
   3183     /* the delimiter list: \n \t \\ and \0 (nothing at all) are escapes */
   3184     {
   3185         const char *p = delims;
   3186         nd = 0;
   3187         for (; *p && nd < (int)sizeof dl; p++) {
   3188             if (*p == '\\' && p[1]) {
   3189                 p++;
   3190                 dl[nd++] = *p == 'n' ? '\n' : *p == 't' ? '\t' : *p == '0' ? 0 : *p == '\\' ? '\\' : *p;
   3191             } else if (*p == '\\') die(1, "delimiter list ends with an unescaped backslash: %s", delims);
   3192             else dl[nd++] = *p;
   3193         }
   3194         if (!nd) { dl[0] = 0; nd = 1; }
   3195     }
   3196     if (!nops) ops[nops++] = "-";
   3197     rd = xmalloc(nops * sizeof *rd);
   3198     for (i = 0; i < nops; i++) {
   3199         if (!strcmp(ops[i], "-")) {
   3200             if (!stdin_loaded) { if (read_all(0, &stdin_rd.d, &stdin_rd.len) < 0) { perr("standard input"); return 1; } stdin_rd.pos = 0; stdin_loaded = 1; }
   3201             rd[i] = stdin_rd;
   3202             rd[i].ok = 2;                                     /* shares stdin's position, see below */
   3203         } else {
   3204             int fd = open(ops[i], O_RDONLY);
   3205             rd[i].ok = 1; rd[i].d = ""; rd[i].len = rd[i].pos = 0;
   3206             if (fd < 0 || read_all(fd, &rd[i].d, &rd[i].len) < 0) { perr("%s", ops[i]); return 1; }
   3207             close(fd);
   3208         }
   3209     }
   3210 #define RD(i) (rd[i].ok == 2 ? &stdin_rd : &rd[i])
   3211     if (serial) {
   3212         for (i = 0; i < nops; i++) {
   3213             char *line; size_t ll; int first = 1; unsigned k = 0;
   3214             if (!rd[i].ok) continue;
   3215             while (next_line(RD(i), &line, &ll, sep)) {
   3216                 if (!first) { char ch = dl[k++ % nd]; if (ch) putchar(ch); }
   3217                 first = 0;
   3218                 fwrite(line, 1, ll, stdout);
   3219             }
   3220             putchar(sep);
   3221         }
   3222     } else {
   3223         for (;;) {
   3224             int any = 0;
   3225             for (i = 0; i < nops; i++) if (RD(i)->pos < RD(i)->len) any = 1;
   3226             if (!any) break;
   3227             for (i = 0; i < nops; i++) {
   3228                 char *line; size_t ll;
   3229                 if (next_line(RD(i), &line, &ll, sep)) fwrite(line, 1, ll, stdout);
   3230                 if (i + 1 < nops && dl[i % nd]) putchar(dl[i % nd]);
   3231             }
   3232             putchar(sep);
   3233         }
   3234     }
   3235     return finish_stdout() ? 1 : st;
   3236 }
   3237 
   3238 /* ---- uniq comm ---- */
   3239 
   3240 /* what uniq compares: past -f fields and -s characters, at most -w of them */
   3241 static const char *uniq_key(const char *s, size_t len, unsigned long skipf, unsigned long skips, unsigned long maxw, int has_w, size_t *kl)
   3242 {
   3243     const char *p = s, *end = s + len;
   3244     while (skipf-- && p < end) {
   3245         while (p < end && (*p == ' ' || *p == '\t')) p++;
   3246         while (p < end && *p != ' ' && *p != '\t') p++;
   3247     }
   3248     while (skips-- && p < end) p++;
   3249     *kl = end - p;
   3250     if (has_w && maxw < *kl) *kl = maxw;
   3251     return p;
   3252 }
   3253 
   3254 static int t_uniq(int argc, char **argv)
   3255 {
   3256     static const struct opt lo[] = {
   3257         { "count", 0, 'c' }, { "repeated", 0, 'd' }, { "all-repeated", 2, 'D' }, { "skip-fields", 1, 'f' }, { "ignore-case", 0, 'i' },
   3258         { "skip-chars", 1, 's' }, { "unique", 0, 'u' }, { "check-chars", 1, 'w' }, { "zero-terminated", 0, 'z' }, { NULL, 0, 0 } };
   3259     unsigned long skipf = 0, skips = 0, maxw = 0;
   3260     int c, count = 0, dup = 0, alldup = 0, uniq_only = 0, icase = 0, has_w = 0, sep = '\n';
   3261     char *d, **v;
   3262     size_t len, n, i, g;
   3263     int fd;
   3264     opts_reset();
   3265     while ((c = getopts(argc, argv, "cdDf:is:uw:z", lo)))
   3266         switch (c) {
   3267         case 'c': count = 1; break;
   3268         case 'd': dup = 1; break;
   3269         case 'D': alldup = 1; break;
   3270         case 'f': if (!parse_ulong(optarg, &skipf)) die(1, "%s: invalid number of fields to skip", optarg); break;
   3271         case 'i': icase = 1; break;
   3272         case 's': if (!parse_ulong(optarg, &skips)) die(1, "%s: invalid number of bytes to skip", optarg); break;
   3273         case 'u': uniq_only = 1; break;
   3274         case 'w': if (!parse_ulong(optarg, &maxw)) die(1, "%s: invalid number of bytes to compare", optarg); has_w = 1; break;
   3275         case 'z': sep = 0; break;
   3276         }
   3277     if (nops > 2) extra_operand(ops[2]);
   3278     fd = nops ? open_input(ops[0]) : 0;
   3279     if (fd < 0) { perr("%s", ops[0]); return 1; }
   3280     if (read_all(fd, &d, &len) < 0) { perr("%s", nops ? ops[0] : "standard input"); return 1; }
   3281     if (nops > 1 && strcmp(ops[1], "-") && !freopen(ops[1], "w", stdout)) { perr("%s", ops[1]); return 1; }
   3282     n = split_lines(d, len, sep, &v);
   3283     for (i = 0; i < n; i = g) {
   3284         size_t kl, kl2;
   3285         const char *k = uniq_key(v[i], strlen(v[i]), skipf, skips, maxw, has_w, &kl);
   3286         for (g = i + 1; g < n; g++) {
   3287             const char *k2 = uniq_key(v[g], strlen(v[g]), skipf, skips, maxw, has_w, &kl2);
   3288             if (kl != kl2 || (icase ? strncasecmp(k, k2, kl) : memcmp(k, k2, kl))) break;
   3289         }
   3290         {
   3291             size_t times = g - i, j;
   3292             if ((dup || alldup) && times < 2) continue;
   3293             if (uniq_only && times != 1) continue;
   3294             if (alldup) { for (j = i; j < g; j++) { fputs(v[j], stdout); putchar(sep); } continue; }
   3295             if (count) printf("%7lu ", (unsigned long)times);
   3296             fputs(v[i], stdout);
   3297             putchar(sep);
   3298         }
   3299     }
   3300     return finish_stdout();
   3301 }
   3302 
   3303 static int t_comm(int argc, char **argv)
   3304 {
   3305     static const struct opt lo[] = {
   3306         { "output-delimiter", 1, 'O' }, { "check-order", 0, 'k' }, { "nocheck-order", 0, 'n' }, { "total", 0, 't' },
   3307         { "zero-terminated", 0, 'z' }, { NULL, 0, 0 } };
   3308     const char *odel = "\t";
   3309     int c, h1 = 0, h2 = 0, h3 = 0, sep = '\n', total = 0, fd;
   3310     char *d1, *d2, **v1, **v2;
   3311     size_t l1, l2, n1, n2, i = 0, j = 0, t1 = 0, t2 = 0, t3 = 0;
   3312     opts_reset();
   3313     while ((c = getopts(argc, argv, "123z", lo)))
   3314         switch (c) {
   3315         case '1': h1 = 1; break;
   3316         case '2': h2 = 1; break;
   3317         case '3': h3 = 1; break;
   3318         case 'O': odel = optarg; break;
   3319         case 't': total = 1; break;
   3320         case 'z': sep = 0; break;
   3321         }
   3322     if (nops < 2) { if (!nops) missing_operand(); say("missing operand after '%s'", ops[0]); usage_error(); }
   3323     if (nops > 2) extra_operand(ops[2]);
   3324     fd = open_input(ops[0]);
   3325     if (fd < 0 || read_all(fd, &d1, &l1) < 0) die(1, "%s: %s", ops[0], strerror(errno));
   3326     if (fd) close(fd);
   3327     fd = open_input(ops[1]);
   3328     if (fd < 0 || read_all(fd, &d2, &l2) < 0) die(1, "%s: %s", ops[1], strerror(errno));
   3329     if (fd) close(fd);
   3330     n1 = split_lines(d1, l1, sep, &v1);
   3331     n2 = split_lines(d2, l2, sep, &v2);
   3332     while (i < n1 || j < n2) {
   3333         int cmp = i >= n1 ? 1 : j >= n2 ? -1 : strcmp(v1[i], v2[j]);
   3334         if (cmp < 0) { t1++; if (!h1) { fputs(v1[i], stdout); putchar(sep); } i++; }
   3335         else if (cmp > 0) {
   3336             t2++;
   3337             if (!h2) { if (!h1) fputs(odel, stdout); fputs(v2[j], stdout); putchar(sep); }
   3338             j++;
   3339         } else {
   3340             t3++;
   3341             if (!h3) { if (!h1) fputs(odel, stdout); if (!h2) fputs(odel, stdout); fputs(v1[i], stdout); putchar(sep); }
   3342             i++; j++;
   3343         }
   3344     }
   3345     if (total) printf("%lu%s%lu%s%lu%stotal\n", (unsigned long)t1, odel, (unsigned long)t2, odel, (unsigned long)t3, odel);
   3346     return finish_stdout();
   3347 }
   3348 
   3349 /* ---- sort ---- */
   3350 
   3351 struct sline { char *p; size_t len; };
   3352 
   3353 #define K_NUM 1
   3354 #define K_GEN 2
   3355 #define K_HUM 4
   3356 #define K_MON 8
   3357 #define K_VER 16
   3358 #define K_DICT 32
   3359 #define K_FOLD 64
   3360 #define K_IGN 128
   3361 #define K_REV 256
   3362 #define K_BLANK 512
   3363 #define K_RAND 1024
   3364 
   3365 struct skey {
   3366     unsigned long sword, schar, eword, echar;    /* sword ~0 is the start of the line, eword ~0 the end */
   3367     int flags, eblank;
   3368 };
   3369 
   3370 static struct skey keys[32];
   3371 static int nkeys, gflags, stable, unique, tabch = -1;
   3372 
   3373 static int is_blank(int c) { return c == ' ' || c == '\t'; }
   3374 
   3375 static const char *begfield(const struct sline *l, const struct skey *k)
   3376 {
   3377     const char *p = l->p, *lim = l->p + l->len;
   3378     unsigned long w = k->sword;
   3379     if (w == ~0UL) return p;
   3380     if (tabch >= 0) {
   3381         while (p < lim && w--) { while (p < lim && *p != tabch) p++; if (p < lim) p++; }
   3382     } else {
   3383         while (p < lim && w--) { while (p < lim && is_blank(*p)) p++; while (p < lim && !is_blank(*p)) p++; }
   3384     }
   3385     if (k->flags & K_BLANK) while (p < lim && is_blank(*p)) p++;
   3386     return k->schar < (unsigned long)(lim - p) ? p + k->schar : lim;
   3387 }
   3388 
   3389 static const char *limfield(const struct sline *l, const struct skey *k)
   3390 {
   3391     const char *p = l->p, *lim = l->p + l->len;
   3392     unsigned long w = k->eword, ec = k->echar;
   3393     if (w == ~0UL) return lim;
   3394     if (!ec) w++;
   3395     if (tabch >= 0) {
   3396         while (p < lim && w--) { while (p < lim && *p != tabch) p++; if (p < lim && (w | ec)) p++; }
   3397     } else {
   3398         while (p < lim && w--) { while (p < lim && is_blank(*p)) p++; while (p < lim && !is_blank(*p)) p++; }
   3399     }
   3400     if (ec) {
   3401         if (k->eblank) while (p < lim && is_blank(*p)) p++;
   3402         p = ec < (unsigned long)(lim - p) ? p + ec : lim;
   3403     }
   3404     return p;
   3405 }
   3406 
   3407 struct num { int neg; const char *ip, *fp; size_t il, fl; };
   3408 
   3409 static struct num parse_num(const char *s, size_t n)
   3410 {
   3411     struct num r = { 0, NULL, NULL, 0, 0 };
   3412     size_t k;
   3413     while (n && is_blank(*s)) s++, n--;
   3414     if (n && *s == '-') { r.neg = 1; s++; n--; }
   3415     while (n && *s == '0') s++, n--;
   3416     r.ip = s;
   3417     while (r.il < n && isdigit((unsigned char)s[r.il])) r.il++;
   3418     if (r.il < n && s[r.il] == '.') {
   3419         r.fp = s + r.il + 1;
   3420         while (r.il + 1 + r.fl < n && isdigit((unsigned char)r.fp[r.fl])) r.fl++;
   3421     }
   3422     for (k = 0; k < r.fl && r.fp[k] == '0'; k++) ;
   3423     if (!r.il && k == r.fl) r.neg = 0;                      /* -0 is 0 */
   3424     return r;
   3425 }
   3426 
   3427 static int numcmp(const char *a, size_t al, const char *b, size_t bl)
   3428 {
   3429     struct num x = parse_num(a, al), y = parse_num(b, bl);
   3430     size_t i, n;
   3431     int r = 0;
   3432     if (x.neg != y.neg) return x.neg ? -1 : 1;
   3433     if (x.il != y.il) r = x.il < y.il ? -1 : 1;
   3434     else if (x.il && (r = memcmp(x.ip, y.ip, x.il))) r = r < 0 ? -1 : 1;
   3435     else {
   3436         n = x.fl > y.fl ? x.fl : y.fl;
   3437         for (i = 0; i < n && !r; i++) {
   3438             int da = i < x.fl ? x.fp[i] : '0', db = i < y.fl ? y.fp[i] : '0';
   3439             r = da < db ? -1 : da > db;
   3440         }
   3441     }
   3442     return x.neg ? -r : r;
   3443 }
   3444 
   3445 static int gencmp(const char *a, size_t al, const char *b, size_t bl)
   3446 {
   3447     char ta[128], tb[128], *ea, *eb;
   3448     double x, y;
   3449     int va, vb;
   3450     snprintf(ta, sizeof ta, "%.*s", (int)(al < 127 ? al : 127), a);
   3451     snprintf(tb, sizeof tb, "%.*s", (int)(bl < 127 ? bl : 127), b);
   3452     x = strtod(ta, &ea); y = strtod(tb, &eb);
   3453     va = ea != ta; vb = eb != tb;
   3454     if (!va || !vb) return va == vb ? 0 : va ? 1 : -1;
   3455     if (x != x || y != y) return (x != x) == (y != y) ? 0 : x != x ? -1 : 1;
   3456     return x < y ? -1 : x > y;
   3457 }
   3458 
   3459 static int humcmp(const char *a, size_t al, const char *b, size_t bl)
   3460 {
   3461     const char *sfx = "KMGTPEZY";
   3462     size_t ia = 0, ib = 0;
   3463     int ua = 0, ub = 0;
   3464     while (al && is_blank(*a)) a++, al--;
   3465     while (bl && is_blank(*b)) b++, bl--;
   3466     while (ia < al && (isdigit((unsigned char)a[ia]) || a[ia] == '.' || (ia == 0 && a[ia] == '-'))) ia++;
   3467     while (ib < bl && (isdigit((unsigned char)b[ib]) || b[ib] == '.' || (ib == 0 && b[ib] == '-'))) ib++;
   3468     if (ia < al && strchr(sfx, toupper((unsigned char)a[ia]))) ua = strchr(sfx, toupper((unsigned char)a[ia])) - sfx + 1;
   3469     if (ib < bl && strchr(sfx, toupper((unsigned char)b[ib]))) ub = strchr(sfx, toupper((unsigned char)b[ib])) - sfx + 1;
   3470     {
   3471         int na = ia && a[0] == '-', nb = ib && b[0] == '-';
   3472         if (na != nb) return na ? -1 : 1;
   3473         if (ua != ub) return (ua < ub ? -1 : 1) * (na ? -1 : 1);
   3474     }
   3475     return numcmp(a, ia, b, ib);
   3476 }
   3477 
   3478 static int month_of(const char *s, size_t n)
   3479 {
   3480     static const char *m[] = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" };
   3481     int i;
   3482     while (n && is_blank(*s)) s++, n--;
   3483     if (n < 3) return 0;
   3484     for (i = 0; i < 12; i++) if (!strncasecmp(s, m[i], 3)) return i + 1;
   3485     return 0;
   3486 }
   3487 
   3488 static int vercmp(const char *a, size_t al, const char *b, size_t bl)
   3489 {
   3490     size_t i = 0, j = 0;
   3491     while (i < al || j < bl) {
   3492         int ca = i < al ? (unsigned char)a[i] : 0, cb = j < bl ? (unsigned char)b[j] : 0;
   3493         if (isdigit(ca) && isdigit(cb)) {
   3494             size_t si = i, sj = j, li, lj;
   3495             while (si < al && a[si] == '0') si++;
   3496             while (sj < bl && b[sj] == '0') sj++;
   3497             for (li = 0; si + li < al && isdigit((unsigned char)a[si + li]); li++) ;
   3498             for (lj = 0; sj + lj < bl && isdigit((unsigned char)b[sj + lj]); lj++) ;
   3499             if (li != lj) return li < lj ? -1 : 1;
   3500             if (memcmp(a + si, b + sj, li)) return memcmp(a + si, b + sj, li) < 0 ? -1 : 1;
   3501             i = si + li; j = sj + lj;
   3502             continue;
   3503         }
   3504         if (ca != cb) {
   3505             int oa = ca == '~' ? -1 : isalpha(ca) ? ca : ca ? ca + 256 : 0, ob = cb == '~' ? -1 : isalpha(cb) ? cb : cb ? cb + 256 : 0;
   3506             return oa < ob ? -1 : 1;
   3507         }
   3508         i++; j++;
   3509     }
   3510     return 0;
   3511 }
   3512 
   3513 /* plain text, skipping or folding as -d -f -i ask */
   3514 static int textcmp(const char *a, size_t al, const char *b, size_t bl, int flags)
   3515 {
   3516     size_t i = 0, j = 0;
   3517     for (;;) {
   3518         int ca = -1, cb = -1;
   3519         while (i < al) {
   3520             int c = (unsigned char)a[i];
   3521             if (((flags & K_DICT) && !isalnum(c) && !is_blank(c)) || ((flags & K_IGN) && !isprint(c))) { i++; continue; }
   3522             ca = (flags & K_FOLD) ? toupper(c) : c;
   3523             break;
   3524         }
   3525         while (j < bl) {
   3526             int c = (unsigned char)b[j];
   3527             if (((flags & K_DICT) && !isalnum(c) && !is_blank(c)) || ((flags & K_IGN) && !isprint(c))) { j++; continue; }
   3528             cb = (flags & K_FOLD) ? toupper(c) : c;
   3529             break;
   3530         }
   3531         if (ca < 0 || cb < 0) return ca == cb ? 0 : ca < 0 ? -1 : 1;
   3532         if (ca != cb) return ca < cb ? -1 : 1;
   3533         i++; j++;
   3534     }
   3535 }
   3536 
   3537 static int compare_keys(const struct sline *a, const struct sline *b)
   3538 {
   3539     int i, n = nkeys ? nkeys : 1;
   3540     for (i = 0; i < n; i++) {
   3541         struct skey whole = { ~0UL, 0, ~0UL, 0, gflags, 0 };
   3542         const struct skey *k = nkeys ? &keys[i] : &whole;
   3543         const char *pa = a->p, *pb = b->p, *ea = a->p + a->len, *eb = b->p + b->len;
   3544         int r, f = k->flags;
   3545         if (nkeys) { pa = begfield(a, k); ea = limfield(a, k); pb = begfield(b, k); eb = limfield(b, k); if (ea < pa) ea = pa; if (eb < pb) eb = pb; }
   3546         else if (f & K_BLANK) { while (pa < ea && is_blank(*pa)) pa++; while (pb < eb && is_blank(*pb)) pb++; }
   3547         if (f & K_NUM) r = numcmp(pa, ea - pa, pb, eb - pb);
   3548         else if (f & K_GEN) r = gencmp(pa, ea - pa, pb, eb - pb);
   3549         else if (f & K_HUM) r = humcmp(pa, ea - pa, pb, eb - pb);
   3550         else if (f & K_MON) { int x = month_of(pa, ea - pa), y = month_of(pb, eb - pb); r = x < y ? -1 : x > y; }
   3551         else if (f & K_VER) r = vercmp(pa, ea - pa, pb, eb - pb);
   3552         else if (f & (K_DICT | K_FOLD | K_IGN)) r = textcmp(pa, ea - pa, pb, eb - pb, f);
   3553         else {
   3554             size_t la = ea - pa, lb = eb - pb;
   3555             r = memcmp(pa, pb, la < lb ? la : lb);
   3556             if (!r) r = la < lb ? -1 : la > lb;
   3557             r = r < 0 ? -1 : r > 0;
   3558         }
   3559         if (r) return f & K_REV ? -r : r;
   3560     }
   3561     return 0;
   3562 }
   3563 
   3564 static int compare_lines(const struct sline *a, const struct sline *b)
   3565 {
   3566     int r = compare_keys(a, b);
   3567     if (r || stable || unique) return r;
   3568     {
   3569         size_t m = a->len < b->len ? a->len : b->len;
   3570         r = memcmp(a->p, b->p, m);
   3571         if (!r) r = a->len < b->len ? -1 : a->len > b->len;
   3572         r = r < 0 ? -1 : r > 0;
   3573     }
   3574     return gflags & K_REV ? -r : r;
   3575 }
   3576 
   3577 static void msort(struct sline *v, struct sline *tmp, size_t n)
   3578 {
   3579     size_t m = n / 2, i = 0, j = 0, k = 0;
   3580     if (n < 2) return;
   3581     msort(v, tmp, m);
   3582     msort(v + m, tmp, n - m);
   3583     while (i < m && j < n - m) tmp[k++] = compare_lines(&v[i], &v[m + j]) <= 0 ? v[i++] : v[m + j++];
   3584     while (i < m) tmp[k++] = v[i++];
   3585     while (j < n - m) tmp[k++] = v[m + j++];
   3586     memcpy(v, tmp, n * sizeof *v);
   3587 }
   3588 
   3589 /* F[.C][bdfghiMnRrV]: the field, the character in it (counted from 0 for a start), and the flags after them */
   3590 static unsigned long parse_pos(const char *s, const char **end, unsigned long *chr, int *blank, int *flags, int start)
   3591 {
   3592     char *e;
   3593     unsigned long w = strtoul(s, &e, 10);
   3594     *chr = 0;
   3595     if (e == s) die(2, "invalid number at field start: invalid count at start of '%s'", s);
   3596     if (*e == '.') {
   3597         s = e + 1;
   3598         *chr = strtoul(s, &e, 10);
   3599         if (e == s) die(2, "invalid number after '.'");
   3600         if (start) { if (!*chr) die(2, "character offset is zero: invalid field specification"); (*chr)--; }
   3601     }
   3602     for (; *e && *e != ','; e++) {
   3603         switch (*e) {
   3604         case 'b': *blank = 1; break;
   3605         case 'd': *flags |= K_DICT; break;
   3606         case 'f': *flags |= K_FOLD; break;
   3607         case 'g': *flags |= K_GEN; break;
   3608         case 'h': *flags |= K_HUM; break;
   3609         case 'i': *flags |= K_IGN; break;
   3610         case 'M': *flags |= K_MON; break;
   3611         case 'n': *flags |= K_NUM; break;
   3612         case 'R': *flags |= K_RAND; break;
   3613         case 'r': *flags |= K_REV; break;
   3614         case 'V': *flags |= K_VER; break;
   3615         default: die(2, "stray character in field spec: invalid field specification '%s'", s);
   3616         }
   3617     }
   3618     *end = e;
   3619     return w;
   3620 }
   3621 
   3622 static int t_sort(int argc, char **argv)
   3623 {
   3624     static const struct opt lo[] = {
   3625         { "ignore-leading-blanks", 0, 'b' }, { "dictionary-order", 0, 'd' }, { "ignore-case", 0, 'f' }, { "general-numeric-sort", 0, 'g' },
   3626         { "human-numeric-sort", 0, 'h' }, { "ignore-nonprinting", 0, 'i' }, { "key", 1, 'k' }, { "month-sort", 0, 'M' },
   3627         { "numeric-sort", 0, 'n' }, { "random-sort", 0, 'R' }, { "reverse", 0, 'r' }, { "version-sort", 0, 'V' },
   3628         { "check", 2, 'c' }, { "merge", 0, 'm' }, { "output", 1, 'o' }, { "stable", 0, 's' }, { "unique", 0, 'u' },
   3629         { "zero-terminated", 0, 'z' }, { "field-separator", 1, 't' }, { "buffer-size", 1, 'S' }, { "temporary-directory", 1, 'T' },
   3630         { "parallel", 1, 'P' }, { "batch-size", 1, 'B' }, { "compress-program", 1, 'X' }, { "sort", 1, 'W' }, { NULL, 0, 0 } };
   3631     const char *outfile = NULL;
   3632     int c, check = 0, merge = 0, sep = '\n', i, st = 0;
   3633     char *data = NULL;
   3634     size_t total = 0, n = 0, cap = 0, k, *foff, *fline;
   3635     struct sline *v = NULL, *tmp;
   3636     usage_status = 2;
   3637     opts_reset();
   3638     while ((c = getopts(argc, argv, "bdfghik:MnRrVcCmo:suzt:S:T:y", lo)))
   3639         switch (c) {
   3640         case 'b': gflags |= K_BLANK; break;
   3641         case 'd': gflags |= K_DICT; break;
   3642         case 'f': gflags |= K_FOLD; break;
   3643         case 'g': gflags |= K_GEN; break;
   3644         case 'h': gflags |= K_HUM; break;
   3645         case 'i': gflags |= K_IGN; break;
   3646         case 'M': gflags |= K_MON; break;
   3647         case 'n': gflags |= K_NUM; break;
   3648         case 'R': gflags |= K_RAND; break;
   3649         case 'r': gflags |= K_REV; break;
   3650         case 'V': gflags |= K_VER; break;
   3651         case 'c': case 'C': check = c == 'C' ? 2 : 1; break;
   3652         case 'o': outfile = optarg; break;
   3653         case 'm': merge = 1; break;
   3654         case 's': stable = 1; break;
   3655         case 'u': unique = 1; break;
   3656         case 'z': sep = 0; break;
   3657         case 't':
   3658             if (!strcmp(optarg, "\\0")) tabch = 0;
   3659             else if (strlen(optarg) != 1) die(2, "multi-character tab '%s'", optarg);
   3660             else tabch = (unsigned char)optarg[0];
   3661             break;
   3662         case 'W':
   3663             if (!strcmp(optarg, "numeric")) gflags |= K_NUM; else if (!strcmp(optarg, "general-numeric")) gflags |= K_GEN;
   3664             else if (!strcmp(optarg, "human-numeric")) gflags |= K_HUM; else if (!strcmp(optarg, "month")) gflags |= K_MON;
   3665             else if (!strcmp(optarg, "version")) gflags |= K_VER; else if (!strcmp(optarg, "random")) gflags |= K_RAND;
   3666             else die(2, "invalid argument '%s' for '--sort'", optarg);
   3667             break;
   3668         case 'k': {
   3669             struct skey *key;
   3670             const char *e;
   3671             unsigned long w, ew;
   3672             int sb = 0, eb = 0;
   3673             if (nkeys == 32) die(2, "too many keys");
   3674             key = &keys[nkeys++];
   3675             memset(key, 0, sizeof *key);
   3676             w = parse_pos(optarg, &e, &key->schar, &sb, &key->flags, 1);
   3677             if (!w) die(2, "field number is zero: invalid field specification '%s'", optarg);
   3678             key->sword = w - 1;
   3679             if (sb) key->flags |= K_BLANK;
   3680             if (!key->sword && !key->schar) key->sword = ~0UL;
   3681             if (*e == ',') {
   3682                 ew = parse_pos(e + 1, &e, &key->echar, &eb, &key->flags, 0);
   3683                 if (!ew) die(2, "field number is zero: invalid field specification '%s'", optarg);
   3684                 key->eword = ew - 1;
   3685                 key->eblank = eb;
   3686             } else key->eword = ~0UL;
   3687             break;
   3688         }
   3689         default: break;
   3690         }
   3691     for (i = 0; i < nkeys; i++)                                   /* a key with no flags of its own gets the global ones */
   3692         if (!keys[i].flags && !keys[i].eblank) keys[i].flags = gflags;
   3693     if (!nops) ops[nops++] = "-";
   3694     foff = xmalloc((nops + 1) * sizeof *foff);
   3695     fline = xmalloc((nops + 2) * sizeof *fline);
   3696     for (i = 0; i < nops; i++) {
   3697         char *d;
   3698         size_t len;
   3699         int fd = open_input(ops[i]);
   3700         if (fd < 0) { say("cannot read: %s: %s", ops[i], strerror(errno)); return 2; }
   3701         if (read_all(fd, &d, &len) < 0) { say("read failed: %s: %s", ops[i], strerror(errno)); return 2; }
   3702         if (fd) close(fd);
   3703         foff[i] = total;
   3704         data = xrealloc(data, total + len + 2);
   3705         memcpy(data + total, d, len);
   3706         total += len;
   3707         if (len && d[len - 1] != sep) data[total++] = sep;
   3708         free(d);
   3709     }
   3710     /* lines point into data, which can move while it grows: so cut it up only now */
   3711     for (k = 0, i = 0; k < total; ) {
   3712         char *e = memchr(data + k, sep, total - k);
   3713         while (i < nops && k >= foff[i]) fline[i++] = n;
   3714         if (n == cap) { cap = cap ? cap * 2 : 1024; v = xrealloc(v, cap * sizeof *v); }
   3715         v[n].p = data + k;
   3716         v[n].len = e ? (size_t)(e - (data + k)) : total - k;
   3717         n++;
   3718         k += v[n - 1].len + 1;
   3719     }
   3720     while (i <= nops) fline[i++] = n;
   3721     if (check) {
   3722         for (k = 1; k < n; k++) {
   3723             int r = compare_keys(&v[k - 1], &v[k]);
   3724             if (r > 0 || (unique && !r)) {
   3725                 if (check == 1) say("%s:%lu: disorder: %.*s", ops[0], (unsigned long)k + 1, (int)v[k].len, v[k].p);
   3726                 return 1;
   3727             }
   3728         }
   3729         return 0;
   3730     }
   3731     tmp = xmalloc((n + 1) * sizeof *tmp);
   3732     if (gflags & K_RAND) {                                       /* a shuffle, not grouped by key like GNU's */
   3733         for (k = n; k > 1; k--) {
   3734             unsigned long long r;
   3735             struct sline t;
   3736             size_t j;
   3737             getrandom(&r, sizeof r, 0);
   3738             j = r % k;
   3739             t = v[k - 1]; v[k - 1] = v[j]; v[j] = t;
   3740         }
   3741     } else if (merge) {
   3742         struct sline *m = xmalloc((n + 1) * sizeof *m);
   3743         size_t *head = xmalloc(nops * sizeof *head), cnt = 0;
   3744         for (i = 0; i < nops; i++) head[i] = fline[i];
   3745         for (;;) {
   3746             int best = -1;
   3747             for (i = 0; i < nops; i++)
   3748                 if (head[i] < fline[i + 1] && (best < 0 || compare_lines(&v[head[i]], &v[head[best]]) < 0)) best = i;
   3749             if (best < 0) break;
   3750             m[cnt++] = v[head[best]++];
   3751         }
   3752         v = m;
   3753     } else msort(v, tmp, n);
   3754     if (outfile && !freopen(outfile, "w", stdout)) { perr("open failed: %s", outfile); return 2; }
   3755     for (k = 0; k < n; k++) {
   3756         if (unique && k && !compare_keys(&v[k - 1], &v[k])) continue;
   3757         fwrite(v[k].p, 1, v[k].len, stdout);
   3758         putchar(sep);
   3759     }
   3760     return finish_stdout() ? 2 : st;
   3761 }
   3762 
   3763 /* ---- helpers for the later tools ---- */
   3764 
   3765 static int glob_match(const char *p, const char *s)
   3766 {
   3767     for (; *p; p++, s++) {
   3768         if (*p == '*') {
   3769             while (p[1] == '*') p++;
   3770             if (!p[1]) return 1;
   3771             for (; *s; s++) if (glob_match(p + 1, s)) return 1;
   3772             return glob_match(p + 1, s);
   3773         }
   3774         if (!*s) return 0;
   3775         if (*p == '?') continue;
   3776         if (*p == '[') {
   3777             int neg = p[1] == '!' || p[1] == '^', ok = 0;
   3778             const char *q = p + 1 + neg;
   3779             if (*q == ']') { if (*s == ']') ok = 1; q++; }
   3780             for (; *q && *q != ']'; q++) {
   3781                 if (q[1] == '-' && q[2] && q[2] != ']') { if ((unsigned char)*s >= (unsigned char)q[0] && (unsigned char)*s <= (unsigned char)q[2]) ok = 1; q += 2; }
   3782                 else if (*q == *s) ok = 1;
   3783             }
   3784             if (!*q || ok == neg) return 0;
   3785             p = q;
   3786             continue;
   3787         }
   3788         if (*p == '\\' && p[1]) p++;
   3789         if (*p != *s) return 0;
   3790     }
   3791     return !*s;
   3792 }
   3793 
   3794 /* ---- test [ ---- */
   3795 
   3796 static char **targv;
   3797 static int targc, tpos;
   3798 
   3799 static int test_or(void);
   3800 
   3801 static int t_binop(const char *s)
   3802 {
   3803     static const char *const names[] = { "=", "==", "!=", "<", ">", "-eq", "-ne", "-lt", "-le", "-gt", "-ge", "-nt", "-ot", "-ef", NULL };
   3804     int i;
   3805     for (i = 0; names[i]; i++) if (!strcmp(s, names[i])) return 1;
   3806     return 0;
   3807 }
   3808 
   3809 static long long t_int(const char *s)
   3810 {
   3811     char *e;
   3812     long long v;
   3813     while (isspace((unsigned char)*s)) s++;
   3814     errno = 0;
   3815     v = strtoll(s, &e, 10);
   3816     while (isspace((unsigned char)*e)) e++;
   3817     if (e == s || *e) die(2, "%s: integer expression expected", s);
   3818     return v;
   3819 }
   3820 
   3821 static int t_unary(const char *op, const char *a)
   3822 {
   3823     struct stat st;
   3824     int r;
   3825     if (!strcmp(op, "-n")) return *a != 0;
   3826     if (!strcmp(op, "-z")) return *a == 0;
   3827     if (!strcmp(op, "-t")) return isatty((int)t_int(a));
   3828     if (!strcmp(op, "-h") || !strcmp(op, "-L")) return lstat(a, &st) == 0 && S_ISLNK(st.st_mode);
   3829     r = stat(a, &st);
   3830     if (op[1] == 'r') return access(a, R_OK) == 0;
   3831     if (op[1] == 'w') return access(a, W_OK) == 0;
   3832     if (op[1] == 'x') return access(a, X_OK) == 0;
   3833     if (r < 0) return 0;
   3834     switch (op[1]) {
   3835     case 'e': return 1;
   3836     case 'f': return S_ISREG(st.st_mode);
   3837     case 'd': return S_ISDIR(st.st_mode);
   3838     case 'b': return S_ISBLK(st.st_mode);
   3839     case 'c': return S_ISCHR(st.st_mode);
   3840     case 'p': return S_ISFIFO(st.st_mode);
   3841     case 'S': return S_ISSOCK(st.st_mode);
   3842     case 's': return st.st_size > 0;
   3843     case 'u': return !!(st.st_mode & S_ISUID);
   3844     case 'g': return !!(st.st_mode & S_ISGID);
   3845     case 'k': return !!(st.st_mode & S_ISVTX);
   3846     case 'O': return st.st_uid == geteuid();
   3847     case 'G': return st.st_gid == getegid();
   3848     case 'N': return st.st_mtime > st.st_atime || (st.st_mtime == st.st_atime && st.st_mtime_nsec > st.st_atime_nsec);
   3849     }
   3850     return 0;
   3851 }
   3852 
   3853 static int t_isunary(const char *s)
   3854 {
   3855     return s[0] == '-' && s[1] && !s[2] && strchr("nzthLebcdfgkprsuwxOGNS", s[1]);
   3856 }
   3857 
   3858 static int t_binary(const char *a, const char *op, const char *b)
   3859 {
   3860     struct stat x, y;
   3861     if (!strcmp(op, "=") || !strcmp(op, "==")) return !strcmp(a, b);
   3862     if (!strcmp(op, "!=")) return strcmp(a, b) != 0;
   3863     if (!strcmp(op, "<")) return strcmp(a, b) < 0;
   3864     if (!strcmp(op, ">")) return strcmp(a, b) > 0;
   3865     if (!strcmp(op, "-nt") || !strcmp(op, "-ot")) {
   3866         int ha = stat(a, &x) == 0, hb = stat(b, &y) == 0, nt = op[1] == 'n';
   3867         if (!ha || !hb) return nt ? ha && !hb : hb && !ha;
   3868         if (x.st_mtime != y.st_mtime) return nt ? x.st_mtime > y.st_mtime : x.st_mtime < y.st_mtime;
   3869         return nt ? x.st_mtime_nsec > y.st_mtime_nsec : x.st_mtime_nsec < y.st_mtime_nsec;
   3870     }
   3871     if (!strcmp(op, "-ef")) return stat(a, &x) == 0 && stat(b, &y) == 0 && x.st_dev == y.st_dev && x.st_ino == y.st_ino;
   3872     {
   3873         long long l = t_int(a), r = t_int(b);
   3874         if (!strcmp(op, "-eq")) return l == r;
   3875         if (!strcmp(op, "-ne")) return l != r;
   3876         if (!strcmp(op, "-lt")) return l < r;
   3877         if (!strcmp(op, "-le")) return l <= r;
   3878         if (!strcmp(op, "-gt")) return l > r;
   3879         return l >= r;
   3880     }
   3881 }
   3882 
   3883 static int test_primary(void)
   3884 {
   3885     char *a;
   3886     if (tpos >= targc) die(2, "missing argument");
   3887     a = targv[tpos];
   3888     if (!strcmp(a, "(") && !(tpos + 2 < targc && t_binop(targv[tpos + 1]) && tpos + 3 >= targc)) {
   3889         int v;
   3890         tpos++;
   3891         v = test_or();
   3892         if (tpos >= targc || strcmp(targv[tpos], ")")) die(2, "expected ')'");
   3893         tpos++;
   3894         return v;
   3895     }
   3896     if (tpos + 2 < targc + 0 && t_binop(targv[tpos + 1])) {
   3897         int v = t_binary(a, targv[tpos + 1], targv[tpos + 2]);
   3898         tpos += 3;
   3899         return v;
   3900     }
   3901     if (t_isunary(a) && tpos + 1 < targc) {
   3902         int v = t_unary(a, targv[tpos + 1]);
   3903         tpos += 2;
   3904         return v;
   3905     }
   3906     tpos++;
   3907     return *a != 0;
   3908 }
   3909 
   3910 static int test_not(void)
   3911 {
   3912     if (tpos < targc && !strcmp(targv[tpos], "!") && tpos + 1 < targc) {
   3913         tpos++;
   3914         return !test_not();
   3915     }
   3916     return test_primary();
   3917 }
   3918 
   3919 static int test_and(void)
   3920 {
   3921     int v = test_not();
   3922     while (tpos < targc && !strcmp(targv[tpos], "-a")) { tpos++; v = test_not() && v; }
   3923     return v;
   3924 }
   3925 
   3926 static int test_or(void)
   3927 {
   3928     int v = test_and();
   3929     while (tpos < targc && !strcmp(targv[tpos], "-o")) { tpos++; v = test_and() || v; }
   3930     return v;
   3931 }
   3932 
   3933 static int t_test(int argc, char **argv)
   3934 {
   3935     int v;
   3936     targv = argv + 1; targc = argc - 1; tpos = 0;
   3937     if (!strcmp(prog, "[")) {
   3938         if (argc == 2 && !strcmp(argv[1], "--help")) { print_usage(); return 0; }
   3939         if (argc == 2 && !strcmp(argv[1], "--version")) { printf("[ (rifle) " VERSION "\n"); return 0; }
   3940         if (targc < 1 || strcmp(targv[targc - 1], "]")) die(2, "missing ']'");
   3941         targc--;
   3942     } else if (argc == 2 && !strcmp(argv[1], "--help")) { print_usage(); return 0; }
   3943     else if (argc == 2 && !strcmp(argv[1], "--version")) { printf("test (rifle) " VERSION "\n"); return 0; }
   3944     if (!targc) return 1;
   3945     v = test_or();
   3946     if (tpos < targc) die(2, "extra argument '%s'", targv[tpos]);
   3947     return !v;
   3948 }
   3949 
   3950 /* ---- printf ---- */
   3951 
   3952 static int pf_status;
   3953 
   3954 static unsigned pf_hex(const char *p, int max, int *n)
   3955 {
   3956     unsigned v = 0;
   3957     *n = 0;
   3958     while (*n < max && isxdigit((unsigned char)p[*n])) {
   3959         v = v * 16 + (isdigit((unsigned char)p[*n]) ? p[*n] - '0' : (p[*n] | 32) - 'a' + 10);
   3960         (*n)++;
   3961     }
   3962     return v;
   3963 }
   3964 
   3965 static void pf_utf8(unsigned c, char *out)
   3966 {
   3967     if (c < 0x80) { *out++ = c; }
   3968     else if (c < 0x800) { *out++ = 0xc0 | c >> 6; *out++ = 0x80 | (c & 63); }
   3969     else if (c < 0x10000) { *out++ = 0xe0 | c >> 12; *out++ = 0x80 | (c >> 6 & 63); *out++ = 0x80 | (c & 63); }
   3970     else { *out++ = 0xf0 | c >> 18; *out++ = 0x80 | (c >> 12 & 63); *out++ = 0x80 | (c >> 6 & 63); *out++ = 0x80 | (c & 63); }
   3971     *out = 0;
   3972 }
   3973 
   3974 /* p is just past the backslash. the bytes go to out, the return is how far we got, *stop is set by \c */
   3975 static const char *pf_esc(const char *p, int in_b, char *out, size_t *olen, int *stop)
   3976 {
   3977     int n, k;
   3978     unsigned v;
   3979     *olen = 1;
   3980     switch (*p) {
   3981     case 'a': out[0] = 7; return p + 1;
   3982     case 'b': out[0] = 8; return p + 1;
   3983     case 'f': out[0] = 12; return p + 1;
   3984     case 'n': out[0] = 10; return p + 1;
   3985     case 'r': out[0] = 13; return p + 1;
   3986     case 't': out[0] = 9; return p + 1;
   3987     case 'v': out[0] = 11; return p + 1;
   3988     case 'e': out[0] = 27; return p + 1;
   3989     case '\\': out[0] = '\\'; return p + 1;
   3990     case '"': if (!in_b) { out[0] = '"'; return p + 1; } break;
   3991     case 'c': *stop = 1; *olen = 0; return p + 1;
   3992     case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7':
   3993         v = 0; n = 0;
   3994         if (in_b && *p == '0') p++;
   3995         for (k = 0; k < 3 && p[n] >= '0' && p[n] <= '7'; k++, n++) v = v * 8 + p[n] - '0';
   3996         out[0] = v;
   3997         return p + n;
   3998     case 'x':
   3999         v = pf_hex(p + 1, 2, &n);
   4000         if (!n) break;
   4001         out[0] = v;
   4002         return p + 1 + n;
   4003     case 'u': case 'U':
   4004         v = pf_hex(p + 1, *p == 'u' ? 4 : 8, &n);
   4005         if (!n) break;
   4006         pf_utf8(v, out);
   4007         *olen = strlen(out);
   4008         return p + 1 + n;
   4009     }
   4010     out[0] = '\\';
   4011     *olen = 1;
   4012     return p;
   4013 }
   4014 
   4015 static long long pf_num(const char *s, int is_unsigned)
   4016 {
   4017     char *e;
   4018     long long v;
   4019     if (!s) return 0;
   4020     if (*s == '\'' || *s == '"') return (unsigned char)s[1];
   4021     errno = 0;
   4022     v = is_unsigned ? (long long)strtoull(s, &e, 0) : strtoll(s, &e, 0);
   4023     if (e == s) { say("'%s': expected a numeric value", s); pf_status = 1; return 0; }
   4024     if (*e) { say("'%s': value not completely converted", s); pf_status = 1; }
   4025     return v;
   4026 }
   4027 
   4028 static void pf_quote(const char *s)
   4029 {
   4030     int plain = 1;
   4031     const char *p;
   4032     if (!*s) { fputs("''", stdout); return; }
   4033     for (p = s; *p; p++) if (!isprint((unsigned char)*p)) plain = 0;
   4034     if (!plain) {
   4035         fputs("$'", stdout);
   4036         for (p = s; *p; p++) {
   4037             unsigned char c = *p;
   4038             if (c == '\n') fputs("\\n", stdout); else if (c == '\t') fputs("\\t", stdout);
   4039             else if (c == '\'' || c == '\\') printf("\\%c", c);
   4040             else if (c < 32 || c == 127) printf("\\%03o", c);
   4041             else putchar(c);
   4042         }
   4043         putchar('\'');
   4044         return;
   4045     }
   4046     for (p = s; *p; p++) if (!isalnum((unsigned char)*p) && !strchr("_-./:,%+=@~^", *p)) break;
   4047     if (!*p) { fputs(s, stdout); return; }
   4048     putchar('\'');
   4049     for (p = s; *p; p++) { if (*p == '\'') fputs("'\\''", stdout); else putchar(*p); }
   4050     putchar('\'');
   4051 }
   4052 
   4053 static int t_printf(int argc, char **argv)
   4054 {
   4055     const char *fmt;
   4056     char **args;
   4057     int nargs, ai = 0, a1 = 1;
   4058     if (argc == 2 && !strcmp(argv[1], "--help")) { print_usage(); return 0; }
   4059     if (argc == 2 && !strcmp(argv[1], "--version")) { printf("printf (rifle) " VERSION "\n"); return 0; }
   4060     if (argc > 1 && !strcmp(argv[1], "--")) a1 = 2;
   4061     if (a1 >= argc) { say("missing operand"); usage_error(); }
   4062     fmt = argv[a1];
   4063     args = argv + a1 + 1; nargs = argc - a1 - 1;
   4064     for (;;) {
   4065         const char *p = fmt;
   4066         int used = 0, stop = 0;
   4067         while (*p && !stop) {
   4068             if (*p == '\\') {
   4069                 char b[8];
   4070                 size_t n;
   4071                 p = pf_esc(p + 1, 0, b, &n, &stop);
   4072                 fwrite(b, 1, n, stdout);
   4073             } else if (*p != '%') putchar(*p++);
   4074             else {
   4075                 char spec[64], conv;
   4076                 int k = 0, wstar = 0, pstar = 0;
   4077                 const char *arg;
   4078                 long long w = 0, pr = -1;
   4079                 p++;
   4080                 if (*p == '%') { putchar('%'); p++; continue; }
   4081                 spec[k++] = '%';
   4082                 while (*p && strchr("-+ #0'", *p) && k < 20) { if (*p != '\'') spec[k++] = *p; p++; }
   4083                 if (*p == '*') { wstar = 1; p++; if (ai < nargs) w = pf_num(args[ai++], 0); used++; }
   4084                 else while (isdigit((unsigned char)*p) && k < 40) spec[k++] = *p++;
   4085                 if (*p == '.') {
   4086                     p++;
   4087                     if (*p == '*') { pstar = 1; p++; if (ai < nargs) pr = pf_num(args[ai++], 0); used++; }
   4088                     else { pr = 0; while (isdigit((unsigned char)*p)) pr = pr * 10 + *p++ - '0'; }
   4089                 }
   4090                 while (*p == 'l' || *p == 'h' || *p == 'L' || *p == 'j' || *p == 'z' || *p == 't') p++;
   4091                 conv = *p;
   4092                 if (!conv) { say("%.*s: invalid conversion specification", (int)(p - fmt), fmt); return 1; }
   4093                 p++;
   4094                 if (!strchr("diouxXeEfFgGaAcsbq", conv)) { say("%%%c: invalid conversion specification", conv); return 1; }
   4095                 used++;
   4096                 arg = ai < nargs ? args[ai++] : NULL;
   4097                 if (wstar) k += sprintf(spec + k, "%lld", w);
   4098                 if (pr >= 0 || pstar) { if (pr < 0) pr = 0; k += sprintf(spec + k, ".%lld", pr); }
   4099                 spec[k] = 0;
   4100                 if (strchr("di", conv)) { strcat(spec, "lld"); printf(spec, pf_num(arg, 0)); }
   4101                 else if (strchr("ouxX", conv)) { strcat(spec, "ll"); k = strlen(spec); spec[k] = conv; spec[k + 1] = 0; printf(spec, (unsigned long long)pf_num(arg, 1)); }
   4102                 else if (strchr("eEfFgGaA", conv)) {
   4103                     double d = 0;
   4104                     if (arg) {
   4105                         char *e;
   4106                         d = strtod(arg, &e);
   4107                         if (e == arg) { say("'%s': expected a numeric value", arg); pf_status = 1; }
   4108                         else if (*e) { say("'%s': value not completely converted", arg); pf_status = 1; }
   4109                     }
   4110                     k = strlen(spec); spec[k] = conv; spec[k + 1] = 0;
   4111                     printf(spec, d);
   4112                 } else if (conv == 'c') { strcat(spec, "c"); printf(spec, arg ? (unsigned char)arg[0] : 0); }
   4113                 else if (conv == 's') { strcat(spec, "s"); printf(spec, arg ? arg : ""); }
   4114                 else if (conv == 'q') pf_quote(arg ? arg : "");
   4115                 else {
   4116                     char *buf = xmalloc((arg ? strlen(arg) : 0) + 1), *o = buf;
   4117                     const char *s = arg ? arg : "";
   4118                     while (*s && !stop) {
   4119                         if (*s == '\\') { char b[8]; size_t n; s = pf_esc(s + 1, 1, b, &n, &stop); memcpy(o, b, n); o += n; }
   4120                         else *o++ = *s++;
   4121                     }
   4122                     *o = 0;
   4123                     strcat(spec, "s");
   4124                     printf(spec, buf);
   4125                     free(buf);
   4126                 }
   4127             }
   4128         }
   4129         if (stop || ai >= nargs || !used) break;
   4130     }
   4131     return finish_stdout() ? 1 : pf_status;
   4132 }
   4133 
   4134 /* ---- expr ---- */
   4135 
   4136 struct ev { int num; long long n; char *s; };
   4137 
   4138 static char **eargv;
   4139 static int eargc, epos;
   4140 
   4141 static int ev_true(const struct ev *v) { return v->num ? v->n != 0 : v->s[0] && !(strspn(v->s, "0") == strlen(v->s)); }
   4142 static void ev_str(struct ev *v) { if (v->num) { v->s = xmalloc(24); sprintf(v->s, "%lld", v->n); v->num = 0; } }
   4143 static int ev_isnum(struct ev *v)
   4144 {
   4145     char *e;
   4146     if (v->num) return 1;
   4147     if (!*v->s) return 0;
   4148     v->n = strtoll(v->s, &e, 10);
   4149     if (*e || (!isdigit((unsigned char)v->s[0]) && v->s[0] != '-' && v->s[0] != '+')) return 0;
   4150     return 1;
   4151 }
   4152 static long long ev_int(struct ev *v) { if (!ev_isnum(v)) die(2, "non-integer argument"); return v->n; }
   4153 
   4154 /* a small BRE: . * [] \( \) \{ \} \+ \? \| ^ $ and backtracking through groups */
   4155 struct re { const char *p; const char *start[10], *stop[10]; int ng; };
   4156 struct cont { const char *after, *body; struct cont *next; int g, count, min, max; const char *at; };
   4157 
   4158 static const char *re_close(const char *p)
   4159 {
   4160     int d = 0;
   4161     while (*p) {
   4162         if (p[0] == '\\' && p[1]) {
   4163             if (p[1] == '(') d++;
   4164             else if (p[1] == ')') { if (!d) return p; d--; }
   4165             p += 2;
   4166         } else p++;
   4167     }
   4168     return p;
   4169 }
   4170 
   4171 static const char *re_atom_end(const char *p)
   4172 {
   4173     if (*p == '\\' && p[1] == '(') return re_close(p + 2) + 2;
   4174     if (*p == '\\' && p[1]) return p + 2;
   4175     if (*p == '[') {
   4176         p++;
   4177         if (*p == '^') p++;
   4178         if (*p == ']') p++;
   4179         while (*p && *p != ']') {
   4180             if (*p == '[' && (p[1] == ':' || p[1] == '.' || p[1] == '=')) { const char *q = strstr(p + 2, p[1] == ':' ? ":]" : p[1] == '.' ? ".]" : "=]"); if (q) p = q + 1; }
   4181             p++;
   4182         }
   4183         return *p ? p + 1 : p;
   4184     }
   4185     return p + 1;
   4186 }
   4187 
   4188 static int re_class(const char *p, const char *end, int c)
   4189 {
   4190     int neg = 0, ok = 0;
   4191     p++;
   4192     if (*p == '^') { neg = 1; p++; }
   4193     for (; p < end - 1; p++) {
   4194         if (*p == '[' && p[1] == ':') {
   4195             const char *q = strstr(p + 2, ":]");
   4196             char name[16];
   4197             size_t l = q ? q - p - 2 : 0;
   4198             if (q && l < sizeof name) {
   4199                 memcpy(name, p + 2, l); name[l] = 0;
   4200                 if ((!strcmp(name, "alpha") && isalpha(c)) || (!strcmp(name, "digit") && isdigit(c)) || (!strcmp(name, "alnum") && isalnum(c)) ||
   4201                     (!strcmp(name, "upper") && isupper(c)) || (!strcmp(name, "lower") && islower(c)) || (!strcmp(name, "space") && isspace(c)) ||
   4202                     (!strcmp(name, "punct") && ispunct(c)) || (!strcmp(name, "xdigit") && isxdigit(c)) || (!strcmp(name, "print") && isprint(c)) ||
   4203                     (!strcmp(name, "blank") && (c == ' ' || c == '\t'))) ok = 1;
   4204                 p = q + 1;
   4205                 continue;
   4206             }
   4207         }
   4208         if (p[1] == '-' && p + 2 < end - 1) { if (c >= (unsigned char)p[0] && c <= (unsigned char)p[2]) ok = 1; p += 2; }
   4209         else if ((unsigned char)*p == c) ok = 1;
   4210     }
   4211     return ok != neg;
   4212 }
   4213 
   4214 static int re_one(const char *atom, const char *aend, int c)
   4215 {
   4216     if (!c) return 0;
   4217     if (*atom == '.') return 1;
   4218     if (*atom == '[') return re_class(atom, aend, c);
   4219     if (*atom == '\\') return (unsigned char)atom[1] == c;
   4220     return (unsigned char)*atom == c;
   4221 }
   4222 
   4223 static const char *re_m(struct re *r, const char *p, const char *s, struct cont *k);
   4224 
   4225 /* the next alternative of a group body, or NULL */
   4226 static const char *re_next_alt(const char *p)
   4227 {
   4228     int d = 0;
   4229     while (*p) {
   4230         if (p[0] == '\\' && p[1]) {
   4231             if (p[1] == '(') d++;
   4232             else if (p[1] == ')') { if (!d) return NULL; d--; }
   4233             else if (p[1] == '|' && !d) return p + 2;
   4234             p += 2;
   4235         } else p++;
   4236     }
   4237     return NULL;
   4238 }
   4239 
   4240 static const char *re_group(struct re *r, const char *body, const char *s, struct cont *k)
   4241 {
   4242     const char *alt;
   4243     for (alt = body; alt; alt = re_next_alt(alt)) {
   4244         const char *res = re_m(r, alt, s, k);
   4245         if (res) return res;
   4246     }
   4247     return NULL;
   4248 }
   4249 
   4250 static const char *re_m(struct re *r, const char *p, const char *s, struct cont *k)
   4251 {
   4252     const char *aend, *rest;
   4253     int min = 1, max = 1;
   4254     if (!*p || (p[0] == '\\' && p[1] == '|')) {
   4255         if (!k) return s;
   4256         p = re_close(p);
   4257     }
   4258     if (p[0] == '\\' && p[1] == ')') {
   4259         int cnt;
   4260         if (!k) return s;
   4261         cnt = k->count + 1;
   4262         r->stop[k->g] = s;
   4263         if (cnt < k->max && s != k->at) {
   4264             struct cont nk = *k;
   4265             const char *res, *os = r->start[k->g];
   4266             nk.count = cnt; nk.at = s;
   4267             r->start[k->g] = s;
   4268             res = re_group(r, k->body, s, &nk);
   4269             if (res) return res;
   4270             r->start[k->g] = os;
   4271         }
   4272         if (cnt >= k->min) return re_m(r, k->after, s, k->next);
   4273         return NULL;
   4274     }
   4275     if (*p == '$' && (!p[1] || (p[1] == '\\' && (p[2] == '|' || p[2] == ')')))) return *s ? NULL : re_m(r, p + 1, s, k);
   4276     if (*p == '^' && p == r->p) return re_m(r, p + 1, s, k);
   4277     aend = re_atom_end(p);
   4278     rest = aend;
   4279     if (*aend == '*') { min = 0; max = 1 << 30; rest = aend + 1; }
   4280     else if (aend[0] == '\\' && aend[1] == '+') { min = 1; max = 1 << 30; rest = aend + 2; }
   4281     else if (aend[0] == '\\' && aend[1] == '?') { min = 0; max = 1; rest = aend + 2; }
   4282     else if (aend[0] == '\\' && aend[1] == '{') {
   4283         char *e;
   4284         min = strtol(aend + 2, &e, 10); max = min;
   4285         if (*e == ',') { e++; max = isdigit((unsigned char)*e) ? (int)strtol(e, &e, 10) : 1 << 30; }
   4286         rest = e + 2;
   4287     }
   4288     if (p[0] == '\\' && p[1] == '(') {
   4289         struct cont nk;
   4290         const char *res;
   4291         nk.after = rest; nk.body = p + 2; nk.next = k; nk.g = ++r->ng; nk.count = 0; nk.min = min; nk.max = max; nk.at = s;
   4292         if (max > 0) {
   4293             r->start[nk.g] = s;
   4294             res = re_group(r, nk.body, s, &nk);
   4295             if (res) return res;
   4296         }
   4297         if (min == 0) return re_m(r, rest, s, k);
   4298         return NULL;
   4299     }
   4300     {
   4301         int n = 0;
   4302         while (n < max && re_one(p, aend, (unsigned char)s[n])) n++;
   4303         for (; n >= min; n--) {
   4304             const char *res = re_m(r, rest, s + n, k);
   4305             if (res) return res;
   4306         }
   4307     }
   4308     return NULL;
   4309 }
   4310 
   4311 static int re_match(const char *re, const char *s, struct ev *out)
   4312 {
   4313     struct re r;
   4314     const char *p = re, *e = NULL, *q;
   4315     int has = 0;
   4316     memset(&r, 0, sizeof r);
   4317     r.p = re;
   4318     for (;;) {
   4319         r.ng = 0;
   4320         e = re_m(&r, p, s, NULL);
   4321         if (e) break;
   4322         p = re_next_alt(p);
   4323         if (!p) break;
   4324     }
   4325     for (q = re; *q; q++) { if (q[0] == '\\' && q[1] == '(') { has = 1; break; } if (q[0] == '\\' && q[1]) q++; }
   4326     if (has) {
   4327         out->num = 0;
   4328         if (!e || !r.stop[1] || !r.start[1]) out->s = xstrdup("");
   4329         else { out->s = xmalloc(r.stop[1] - r.start[1] + 1); memcpy(out->s, r.start[1], r.stop[1] - r.start[1]); out->s[r.stop[1] - r.start[1]] = 0; }
   4330     } else { out->num = 1; out->n = e ? e - s : 0; }
   4331     return e != NULL;
   4332 }
   4333 
   4334 static struct ev ex_or(void);
   4335 
   4336 static int ex_tok(const char *t) { return epos < eargc && !strcmp(eargv[epos], t); }
   4337 
   4338 static struct ev ex_prim(void)
   4339 {
   4340     struct ev v;
   4341     if (epos >= eargc) die(2, "syntax error: missing argument");
   4342     if (ex_tok("(")) {
   4343         epos++;
   4344         v = ex_or();
   4345         if (!ex_tok(")")) die(2, epos >= eargc ? "syntax error: expecting ')' after '%s'" : "syntax error: expecting ')' instead of '%s'", eargv[epos < eargc ? epos : epos - 1]);
   4346         epos++;
   4347         return v;
   4348     }
   4349     if (ex_tok("match") && epos + 2 < eargc + 0) {
   4350         struct ev r; v.num = 0;
   4351         r.num = 0; r.s = eargv[epos + 1];
   4352         v.s = eargv[epos + 2]; epos += 3;
   4353         {
   4354             struct ev out;
   4355             re_match(v.s, r.s, &out);
   4356             return out;
   4357         }
   4358     }
   4359     if (ex_tok("substr") && epos + 3 < eargc + 0) {
   4360         long long pos = atoll(eargv[epos + 2]), len = atoll(eargv[epos + 3]);
   4361         const char *s = eargv[epos + 1];
   4362         long long sl = strlen(s);
   4363         v.num = 0;
   4364         if (pos < 1 || len < 1 || pos > sl) v.s = xstrdup("");
   4365         else { if (len > sl - pos + 1) len = sl - pos + 1; v.s = xmalloc(len + 1); memcpy(v.s, s + pos - 1, len); v.s[len] = 0; }
   4366         epos += 4;
   4367         return v;
   4368     }
   4369     if (ex_tok("index") && epos + 2 < eargc + 0) {
   4370         const char *s = eargv[epos + 1], *c = eargv[epos + 2], *f = s + strcspn(s, c);
   4371         v.num = 1; v.n = *f ? f - s + 1 : 0;
   4372         epos += 3;
   4373         return v;
   4374     }
   4375     if (ex_tok("length") && epos + 1 < eargc + 0) {
   4376         v.num = 1; v.n = strlen(eargv[epos + 1]);
   4377         epos += 2;
   4378         return v;
   4379     }
   4380     if (ex_tok("+") && epos + 1 < eargc) epos++;
   4381     v.num = 0; v.s = eargv[epos++];
   4382     return v;
   4383 }
   4384 
   4385 static struct ev ex_match(void)
   4386 {
   4387     struct ev l = ex_prim();
   4388     while (ex_tok(":")) {
   4389         struct ev r, out;
   4390         epos++;
   4391         r = ex_prim();
   4392         ev_str(&l); ev_str(&r);
   4393         re_match(r.s, l.s, &out);
   4394         l = out;
   4395     }
   4396     return l;
   4397 }
   4398 
   4399 static struct ev ex_mul(void)
   4400 {
   4401     struct ev l = ex_match();
   4402     while (ex_tok("*") || ex_tok("/") || ex_tok("%")) {
   4403         char op = eargv[epos++][0];
   4404         struct ev r = ex_match();
   4405         long long a = ev_int(&l), b = ev_int(&r);
   4406         if (op != '*' && !b) die(2, "division by zero");
   4407         l.num = 1;
   4408         l.n = op == '*' ? a * b : op == '/' ? a / b : a % b;
   4409     }
   4410     return l;
   4411 }
   4412 
   4413 static struct ev ex_add(void)
   4414 {
   4415     struct ev l = ex_mul();
   4416     while (ex_tok("+") || ex_tok("-")) {
   4417         char op = eargv[epos++][0];
   4418         struct ev r = ex_mul();
   4419         long long a = ev_int(&l), b = ev_int(&r);
   4420         l.num = 1;
   4421         l.n = op == '+' ? a + b : a - b;
   4422     }
   4423     return l;
   4424 }
   4425 
   4426 static struct ev ex_cmp(void)
   4427 {
   4428     struct ev l = ex_add();
   4429     while (ex_tok("=") || ex_tok("==") || ex_tok("!=") || ex_tok("<") || ex_tok("<=") || ex_tok(">") || ex_tok(">=")) {
   4430         const char *op = eargv[epos++];
   4431         struct ev r = ex_add();
   4432         int c;
   4433         if (ev_isnum(&l) && ev_isnum(&r)) c = l.n < r.n ? -1 : l.n > r.n;
   4434         else { ev_str(&l); ev_str(&r); c = strcoll(l.s, r.s); }
   4435         l.num = 1;
   4436         if (!strcmp(op, "=") || !strcmp(op, "==")) l.n = c == 0;
   4437         else if (!strcmp(op, "!=")) l.n = c != 0;
   4438         else if (!strcmp(op, "<")) l.n = c < 0;
   4439         else if (!strcmp(op, "<=")) l.n = c <= 0;
   4440         else if (!strcmp(op, ">")) l.n = c > 0;
   4441         else l.n = c >= 0;
   4442     }
   4443     return l;
   4444 }
   4445 
   4446 static struct ev ex_and(void)
   4447 {
   4448     struct ev l = ex_cmp();
   4449     while (ex_tok("&")) {
   4450         struct ev r;
   4451         epos++;
   4452         r = ex_cmp();
   4453         if (!ev_true(&l) || !ev_true(&r)) { l.num = 1; l.n = 0; }
   4454     }
   4455     return l;
   4456 }
   4457 
   4458 static struct ev ex_or(void)
   4459 {
   4460     struct ev l = ex_and();
   4461     while (ex_tok("|")) {
   4462         struct ev r;
   4463         epos++;
   4464         r = ex_and();
   4465         if (!ev_true(&l)) l = ev_true(&r) ? r : (struct ev){ 1, 0, NULL };
   4466     }
   4467     return l;
   4468 }
   4469 
   4470 static int t_expr(int argc, char **argv)
   4471 {
   4472     struct ev v;
   4473     if (argc == 2 && !strcmp(argv[1], "--help")) { print_usage(); return 0; }
   4474     if (argc == 2 && !strcmp(argv[1], "--version")) { printf("expr (rifle) " VERSION "\n"); return 0; }
   4475     if (argc < 2) { say("missing operand"); usage_error(); }
   4476     usage_status = 2;
   4477     eargv = argv + 1; eargc = argc - 1; epos = 0;
   4478     v = ex_or();
   4479     if (epos < eargc) die(2, "syntax error: unexpected argument '%s'", eargv[epos]);
   4480     if (v.num) printf("%lld\n", v.n); else printf("%s\n", v.s);
   4481     return finish_stdout() ? 1 : !ev_true(&v);
   4482 }
   4483 
   4484 /* ---- id groups ---- */
   4485 
   4486 static int t_id(int argc, char **argv)
   4487 {
   4488     static const struct opt lo[] = { { "user", 0, 'u' }, { "group", 0, 'g' }, { "groups", 0, 'G' }, { "name", 0, 'n' },
   4489         { "real", 0, 'r' }, { "zero", 0, 'z' }, { NULL, 0, 0 } };
   4490     int c, u = 0, g = 0, G = 0, n = 0, r = 0, z = 0, bad = 0, ngr, i, isgroups = !strcmp(prog, "groups");
   4491     uid_t ruid, euid, uid;
   4492     gid_t rgid, egid, gid, list[256];
   4493     struct passwd *pw = NULL;
   4494     opts_reset();
   4495     while ((c = getopts(argc, argv, isgroups ? "" : "ugGnrzaZ", lo)))
   4496         switch (c) {
   4497         case 'u': u = 1; break; case 'g': g = 1; break; case 'G': G = 1; break; case 'n': n = 1; break;
   4498         case 'r': r = 1; break; case 'z': z = 1; break; default: break;
   4499         }
   4500     if (isgroups) G = n = 1;
   4501     if (u + g + G > 1) die(1, "cannot print \"only\" of more than one choice");
   4502     if ((n || r) && !(u || g || G)) die(1, "cannot print only names or real IDs in default format");
   4503     if (z && !(u || g || G)) die(1, "option --zero not permitted in default format");
   4504     if (nops > 1 && !isgroups) extra_operand(ops[1]);
   4505     do {
   4506         const char *who = nops ? ops[isgroups ? bad : 0] : NULL;
   4507         if (who) {
   4508             pw = getpwnam(who);
   4509             if (!pw) {
   4510                 unsigned long v;
   4511                 if (parse_ulong(who, &v)) pw = getpwuid(v);
   4512             }
   4513             if (!pw) { say("'%s': no such user", who); return 1; }
   4514             ruid = euid = uid = pw->pw_uid; rgid = egid = gid = pw->pw_gid;
   4515             ngr = 0;
   4516             {
   4517                 FILE *gf = fopen("/etc/group", "r");
   4518                 char *gl = NULL;
   4519                 size_t gc = 0;
   4520                 list[ngr++] = gid;
   4521                 while (gf && getline(&gl, &gc, gf) > 0) {
   4522                     char *f[4], *q = gl;
   4523                     int k;
   4524                     for (k = 0; k < 3; k++) { f[k] = q; q = strchr(q, ':'); if (!q) break; *q++ = 0; }
   4525                     if (k < 3) continue;
   4526                     f[3] = q;
   4527                     q[strcspn(q, "\n")] = 0;
   4528                     for (; f[3]; f[3] = q) {
   4529                         q = strchr(f[3], ',');
   4530                         if (q) *q++ = 0;
   4531                         if (!strcmp(f[3], pw->pw_name) && ngr < 256 && (gid_t)atoi(f[2]) != gid) list[ngr++] = atoi(f[2]);
   4532                     }
   4533                 }
   4534                 if (gf) fclose(gf);
   4535             }
   4536         } else {
   4537             ruid = getuid(); euid = geteuid(); rgid = getgid(); egid = getegid();
   4538             uid = r ? ruid : euid; gid = r ? rgid : egid;
   4539             ngr = getgroups(256, list);
   4540             if (ngr < 0) ngr = 0;
   4541         }
   4542         if (isgroups && nops) printf("%s : ", who);
   4543         if (u) printf("%s", n ? user_name(uid) : (snprintf(NULL, 0, "") , ""));
   4544         if (u && !n) printf("%u", uid);
   4545         else if (g) { if (n) printf("%s", group_name(gid)); else printf("%u", gid); }
   4546         else if (G) {
   4547             int first = 1;
   4548             gid_t main_g = who ? gid : egid;
   4549             for (i = -1; i < ngr; i++) {
   4550                 gid_t x = i < 0 ? main_g : list[i];
   4551                 int j, dup = 0;
   4552                 if (i >= 0 && x == main_g) continue;
   4553                 for (j = 0; j < i; j++) if (list[j] == x) dup = 1;
   4554                 if (dup) continue;
   4555                 if (!first) putchar(isgroups || n ? ' ' : z ? 0 : ' ');
   4556                 first = 0;
   4557                 if (n) printf("%s", group_name(x)); else printf("%u", x);
   4558             }
   4559         } else if (!u) {
   4560             printf("uid=%u(%s) gid=%u(%s)", ruid, user_name(ruid), rgid, group_name(rgid));
   4561             if (euid != ruid) printf(" euid=%u(%s)", euid, user_name(euid));
   4562             if (egid != rgid) printf(" egid=%u(%s)", egid, group_name(egid));
   4563             printf(" groups=");
   4564             {
   4565                 int first = 1;
   4566                 gid_t main_g = who ? gid : egid;
   4567                 for (i = -1; i < ngr; i++) {
   4568                     gid_t x = i < 0 ? main_g : list[i];
   4569                     int j, dup = 0;
   4570                     if (i >= 0 && x == main_g) continue;
   4571                     for (j = 0; j < i; j++) if (list[j] == x) dup = 1;
   4572                     if (dup) continue;
   4573                     printf("%s%u(%s)", first ? "" : ",", x, group_name(x));
   4574                     first = 0;
   4575                 }
   4576             }
   4577         }
   4578         putchar(z ? 0 : '\n');
   4579         bad++;
   4580     } while (isgroups && bad < nops);
   4581     return finish_stdout() ? 1 : 0;
   4582 }
   4583 /* ---- md5sum sha*sum cksum sum ---- */
   4584 
   4585 enum { A_MD5, A_SHA1, A_SHA224, A_SHA256, A_SHA384, A_SHA512, A_B2 };
   4586 
   4587 static unsigned b2bits = 512;
   4588 
   4589 struct hash {
   4590     int alg;
   4591     uint32_t s[8];
   4592     uint64_t q[8];
   4593     uint64_t len;
   4594     unsigned char buf[128];
   4595     size_t n;
   4596 };
   4597 
   4598 #define ROL(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
   4599 #define ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
   4600 #define ROR64(x, n) (((x) >> (n)) | ((x) << (64 - (n))))
   4601 
   4602 static const uint32_t k256[64] = {
   4603     0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be,
   4604     0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
   4605     0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85,
   4606     0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
   4607     0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
   4608     0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 };
   4609 
   4610 static const uint64_t k512[80] = {
   4611     0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
   4612     0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
   4613     0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
   4614     0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
   4615     0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
   4616     0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
   4617     0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
   4618     0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
   4619     0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
   4620     0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
   4621     0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
   4622     0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
   4623     0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
   4624     0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL };
   4625 
   4626 static void md5_block(struct hash *h, const unsigned char *p)
   4627 {
   4628     static const int sh[64] = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
   4629         4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 };
   4630     static uint32_t k[64];
   4631     uint32_t m[16], a = h->s[0], b = h->s[1], c = h->s[2], d = h->s[3];
   4632     int i;
   4633     if (!k[0]) {
   4634         static const uint32_t t[64] = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
   4635             0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340,
   4636             0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
   4637             0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9,
   4638             0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
   4639             0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0,
   4640             0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 };
   4641         memcpy(k, t, sizeof k);
   4642     }
   4643     for (i = 0; i < 16; i++) m[i] = p[i * 4] | p[i * 4 + 1] << 8 | p[i * 4 + 2] << 16 | (uint32_t)p[i * 4 + 3] << 24;
   4644     for (i = 0; i < 64; i++) {
   4645         uint32_t f, t;
   4646         int g;
   4647         if (i < 16) { f = (b & c) | (~b & d); g = i; }
   4648         else if (i < 32) { f = (d & b) | (~d & c); g = (5 * i + 1) & 15; }
   4649         else if (i < 48) { f = b ^ c ^ d; g = (3 * i + 5) & 15; }
   4650         else { f = c ^ (b | ~d); g = (7 * i) & 15; }
   4651         t = d; d = c; c = b;
   4652         b = b + ROL(a + f + k[i] + m[g], sh[i]);
   4653         a = t;
   4654     }
   4655     h->s[0] += a; h->s[1] += b; h->s[2] += c; h->s[3] += d;
   4656 }
   4657 
   4658 static void sha1_block(struct hash *h, const unsigned char *p)
   4659 {
   4660     uint32_t w[80], a = h->s[0], b = h->s[1], c = h->s[2], d = h->s[3], e = h->s[4];
   4661     int i;
   4662     for (i = 0; i < 16; i++) w[i] = (uint32_t)p[i * 4] << 24 | p[i * 4 + 1] << 16 | p[i * 4 + 2] << 8 | p[i * 4 + 3];
   4663     for (i = 16; i < 80; i++) w[i] = ROL(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
   4664     for (i = 0; i < 80; i++) {
   4665         uint32_t f, k, t;
   4666         if (i < 20) { f = (b & c) | (~b & d); k = 0x5a827999; }
   4667         else if (i < 40) { f = b ^ c ^ d; k = 0x6ed9eba1; }
   4668         else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8f1bbcdc; }
   4669         else { f = b ^ c ^ d; k = 0xca62c1d6; }
   4670         t = ROL(a, 5) + f + e + k + w[i];
   4671         e = d; d = c; c = ROL(b, 30); b = a; a = t;
   4672     }
   4673     h->s[0] += a; h->s[1] += b; h->s[2] += c; h->s[3] += d; h->s[4] += e;
   4674 }
   4675 
   4676 static void sha256_block(struct hash *h, const unsigned char *p)
   4677 {
   4678     uint32_t w[64], v[8];
   4679     int i;
   4680     for (i = 0; i < 16; i++) w[i] = (uint32_t)p[i * 4] << 24 | p[i * 4 + 1] << 16 | p[i * 4 + 2] << 8 | p[i * 4 + 3];
   4681     for (i = 16; i < 64; i++) {
   4682         uint32_t s0 = ROR(w[i - 15], 7) ^ ROR(w[i - 15], 18) ^ (w[i - 15] >> 3), s1 = ROR(w[i - 2], 17) ^ ROR(w[i - 2], 19) ^ (w[i - 2] >> 10);
   4683         w[i] = w[i - 16] + s0 + w[i - 7] + s1;
   4684     }
   4685     memcpy(v, h->s, sizeof v);
   4686     for (i = 0; i < 64; i++) {
   4687         uint32_t t1 = v[7] + (ROR(v[4], 6) ^ ROR(v[4], 11) ^ ROR(v[4], 25)) + ((v[4] & v[5]) ^ (~v[4] & v[6])) + k256[i] + w[i];
   4688         uint32_t t2 = (ROR(v[0], 2) ^ ROR(v[0], 13) ^ ROR(v[0], 22)) + ((v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]));
   4689         v[7] = v[6]; v[6] = v[5]; v[5] = v[4]; v[4] = v[3] + t1; v[3] = v[2]; v[2] = v[1]; v[1] = v[0]; v[0] = t1 + t2;
   4690     }
   4691     for (i = 0; i < 8; i++) h->s[i] += v[i];
   4692 }
   4693 
   4694 static void sha512_block(struct hash *h, const unsigned char *p)
   4695 {
   4696     uint64_t w[80], v[8];
   4697     int i, j;
   4698     for (i = 0; i < 16; i++) { w[i] = 0; for (j = 0; j < 8; j++) w[i] = w[i] << 8 | p[i * 8 + j]; }
   4699     for (i = 16; i < 80; i++) {
   4700         uint64_t s0 = ROR64(w[i - 15], 1) ^ ROR64(w[i - 15], 8) ^ (w[i - 15] >> 7), s1 = ROR64(w[i - 2], 19) ^ ROR64(w[i - 2], 61) ^ (w[i - 2] >> 6);
   4701         w[i] = w[i - 16] + s0 + w[i - 7] + s1;
   4702     }
   4703     memcpy(v, h->q, sizeof v);
   4704     for (i = 0; i < 80; i++) {
   4705         uint64_t t1 = v[7] + (ROR64(v[4], 14) ^ ROR64(v[4], 18) ^ ROR64(v[4], 41)) + ((v[4] & v[5]) ^ (~v[4] & v[6])) + k512[i] + w[i];
   4706         uint64_t t2 = (ROR64(v[0], 28) ^ ROR64(v[0], 34) ^ ROR64(v[0], 39)) + ((v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]));
   4707         v[7] = v[6]; v[6] = v[5]; v[5] = v[4]; v[4] = v[3] + t1; v[3] = v[2]; v[2] = v[1]; v[1] = v[0]; v[0] = t1 + t2;
   4708     }
   4709     for (i = 0; i < 8; i++) h->q[i] += v[i];
   4710 }
   4711 
   4712 static const uint64_t b2iv[8] = { 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
   4713     0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL };
   4714 static const unsigned char b2sigma[10][16] = {
   4715     { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
   4716     { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
   4717     { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
   4718     { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
   4719     { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 } };
   4720 
   4721 static void b2_block(struct hash *h, const unsigned char *p, int last)
   4722 {
   4723     uint64_t m[16], v[16];
   4724     int i, r;
   4725     for (i = 0; i < 16; i++) { int k; m[i] = 0; for (k = 7; k >= 0; k--) m[i] = m[i] << 8 | p[i * 8 + k]; }
   4726     for (i = 0; i < 8; i++) { v[i] = h->q[i]; v[i + 8] = b2iv[i]; }
   4727     v[12] ^= h->len;
   4728     if (last) v[14] = ~v[14];
   4729 #define B2G(a, b, c, d, x, y) \
   4730     v[a] += v[b] + (x); v[d] = ROR64(v[d] ^ v[a], 32); v[c] += v[d]; v[b] = ROR64(v[b] ^ v[c], 24); \
   4731     v[a] += v[b] + (y); v[d] = ROR64(v[d] ^ v[a], 16); v[c] += v[d]; v[b] = ROR64(v[b] ^ v[c], 63);
   4732     for (r = 0; r < 12; r++) {
   4733         const unsigned char *s = b2sigma[r % 10];
   4734         B2G(0, 4, 8, 12, m[s[0]], m[s[1]]) B2G(1, 5, 9, 13, m[s[2]], m[s[3]]) B2G(2, 6, 10, 14, m[s[4]], m[s[5]]) B2G(3, 7, 11, 15, m[s[6]], m[s[7]])
   4735         B2G(0, 5, 10, 15, m[s[8]], m[s[9]]) B2G(1, 6, 11, 12, m[s[10]], m[s[11]]) B2G(2, 7, 8, 13, m[s[12]], m[s[13]]) B2G(3, 4, 9, 14, m[s[14]], m[s[15]])
   4736     }
   4737     for (i = 0; i < 8; i++) h->q[i] ^= v[i] ^ v[i + 8];
   4738 }
   4739 
   4740 static size_t hash_bsize(int alg) { return alg >= A_SHA384 ? 128 : 64; }
   4741 static size_t hash_size(int alg) { static const size_t n[] = { 16, 20, 28, 32, 48, 64 }; return alg == A_B2 ? b2bits / 8 : n[alg]; }
   4742 
   4743 static void hash_init(struct hash *h, int alg)
   4744 {
   4745     static const uint32_t i224[8] = { 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 };
   4746     static const uint32_t i256[8] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 };
   4747     static const uint64_t i384[8] = { 0xcbbb9d5dc1059ed8ULL, 0x629a292a367cd507ULL, 0x9159015a3070dd17ULL, 0x152fecd8f70e5939ULL,
   4748         0x67332667ffc00b31ULL, 0x8eb44a8768581511ULL, 0xdb0c2e0d64f98fa7ULL, 0x47b5481dbefa4fa4ULL };
   4749     static const uint64_t i512[8] = { 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
   4750         0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL };
   4751     memset(h, 0, sizeof *h);
   4752     h->alg = alg;
   4753     if (alg == A_MD5) { h->s[0] = 0x67452301; h->s[1] = 0xefcdab89; h->s[2] = 0x98badcfe; h->s[3] = 0x10325476; }
   4754     else if (alg == A_SHA1) { h->s[0] = 0x67452301; h->s[1] = 0xefcdab89; h->s[2] = 0x98badcfe; h->s[3] = 0x10325476; h->s[4] = 0xc3d2e1f0; }
   4755     else if (alg == A_SHA224) memcpy(h->s, i224, sizeof i224);
   4756     else if (alg == A_SHA256) memcpy(h->s, i256, sizeof i256);
   4757     else if (alg == A_SHA384) memcpy(h->q, i384, sizeof i384);
   4758     else if (alg == A_B2) { memcpy(h->q, b2iv, sizeof b2iv); h->q[0] ^= 0x01010000 ^ (b2bits / 8); }
   4759     else memcpy(h->q, i512, sizeof i512);
   4760 }
   4761 
   4762 static void hash_block(struct hash *h, const unsigned char *p)
   4763 {
   4764     switch (h->alg) {
   4765     case A_MD5: md5_block(h, p); break;
   4766     case A_SHA1: sha1_block(h, p); break;
   4767     case A_SHA224: case A_SHA256: sha256_block(h, p); break;
   4768     default: sha512_block(h, p); break;
   4769     }
   4770 }
   4771 
   4772 static void hash_add(struct hash *h, const void *data, size_t n)
   4773 {
   4774     const unsigned char *p = data;
   4775     size_t bs = hash_bsize(h->alg);
   4776     if (h->alg == A_B2) {
   4777         while (n) {
   4778             if (h->n == 128) { h->len += 128; b2_block(h, h->buf, 0); h->n = 0; }
   4779             { size_t take = 128 - h->n < n ? 128 - h->n : n; memcpy(h->buf + h->n, p, take); h->n += take; p += take; n -= take; }
   4780         }
   4781         return;
   4782     }
   4783     h->len += n;
   4784     if (h->n) {
   4785         size_t take = bs - h->n < n ? bs - h->n : n;
   4786         memcpy(h->buf + h->n, p, take);
   4787         h->n += take; p += take; n -= take;
   4788         if (h->n == bs) { hash_block(h, h->buf); h->n = 0; }
   4789     }
   4790     while (n >= bs) { hash_block(h, p); p += bs; n -= bs; }
   4791     if (n) { memcpy(h->buf, p, n); h->n = n; }
   4792 }
   4793 
   4794 static void hash_end(struct hash *h, unsigned char *out)
   4795 {
   4796     size_t bs = hash_bsize(h->alg), lenbytes = bs == 128 ? 16 : 8;
   4797     uint64_t bits = h->len * 8;
   4798     if (h->alg == A_B2) {
   4799         size_t i;
   4800         memset(h->buf + h->n, 0, 128 - h->n);
   4801         h->len += h->n;
   4802         b2_block(h, h->buf, 1);
   4803         for (i = 0; i < b2bits / 8; i++) out[i] = h->q[i / 8] >> (8 * (i % 8));
   4804         return;
   4805     }
   4806     unsigned char pad[144];
   4807     size_t padn = (h->n < bs - lenbytes ? bs - lenbytes - h->n : 2 * bs - lenbytes - h->n), i;
   4808     memset(pad, 0, sizeof pad);
   4809     pad[0] = 0x80;
   4810     for (i = 0; i < 8; i++) pad[padn + i + (lenbytes - 8)] = h->alg == A_MD5 ? bits >> (8 * i) : bits >> (56 - 8 * i);
   4811     hash_add(h, pad, padn + lenbytes);
   4812     {
   4813         size_t n = hash_size(h->alg);
   4814         for (i = 0; i < n; i++) {
   4815             if (h->alg == A_MD5) out[i] = h->s[i / 4] >> (8 * (i % 4));
   4816             else if (h->alg >= A_SHA384) out[i] = h->q[i / 8] >> (56 - 8 * (i % 8));
   4817             else out[i] = h->s[i / 4] >> (24 - 8 * (i % 4));
   4818         }
   4819     }
   4820 }
   4821 
   4822 static void hex_of(const unsigned char *d, size_t n, char *out)
   4823 {
   4824     size_t i;
   4825     for (i = 0; i < n; i++) sprintf(out + 2 * i, "%02x", d[i]);
   4826 }
   4827 
   4828 static int hash_fd(int fd, int alg, char *hex)
   4829 {
   4830     struct hash h;
   4831     unsigned char buf[65536], d[64];
   4832     ssize_t n;
   4833     hash_init(&h, alg);
   4834     while ((n = read(fd, buf, sizeof buf)) > 0) hash_add(&h, buf, n);
   4835     if (n < 0) return -1;
   4836     hash_end(&h, d);
   4837     hex_of(d, hash_size(alg), hex);
   4838     return 0;
   4839 }
   4840 
   4841 static const char *const alg_names[] = { "MD5", "SHA1", "SHA224", "SHA256", "SHA384", "SHA512", "BLAKE2b" };
   4842 
   4843 static const char *alg_tag(int alg, char *buf)
   4844 {
   4845     if (alg == A_B2 && b2bits != 512) { sprintf(buf, "BLAKE2b-%u", b2bits); return buf; }
   4846     return alg_names[alg];
   4847 }
   4848 
   4849 static int t_digest(int argc, char **argv)
   4850 {
   4851     static const struct opt lo[] = { { "binary", 0, 'b' }, { "text", 0, 't' }, { "check", 0, 'c' }, { "tag", 0, 'T' }, { "quiet", 0, 'q' },
   4852         { "status", 0, 's' }, { "warn", 0, 'w' }, { "strict", 0, 'S' }, { "ignore-missing", 0, 'I' }, { "zero", 0, 'z' }, { "untagged", 0, 'U' }, { "length", 1, 'l' }, { NULL, 0, 0 } };
   4853     int alg = !strcmp(prog, "b2sum") ? A_B2 : !strcmp(prog, "md5sum") ? A_MD5 : !strcmp(prog, "sha1sum") ? A_SHA1 : !strcmp(prog, "sha224sum") ? A_SHA224 :
   4854         !strcmp(prog, "sha256sum") ? A_SHA256 : !strcmp(prog, "sha384sum") ? A_SHA384 : A_SHA512;
   4855     int c, bin = 0, check = 0, tag = 0, quiet = 0, stat_only = 0, strict = 0, ignmiss = 0, zero = 0, bad = 0, i;
   4856     char hex[130];
   4857     opts_reset();
   4858     while ((c = getopts(argc, argv, alg == A_B2 ? "btczwl:" : "btczw", lo)))
   4859         switch (c) {
   4860         case 'l': {
   4861             unsigned long n;
   4862             if (!parse_ulong(optarg, &n)) die(1, "invalid length: '%s'", optarg);
   4863             if (n > 512) { say("invalid length: '%s'", optarg); die(1, "maximum digest length for 'BLAKE2b' is 512 bits"); }
   4864             if (n % 8) { say("invalid length: '%s'", optarg); die(1, "length is not a multiple of 8"); }
   4865             b2bits = n ? n : 512;
   4866             break;
   4867         }
   4868         case 'b': bin = 1; break; case 't': bin = 0; break; case 'c': check = 1; break; case 'T': tag = 1; break;
   4869         case 'q': quiet = 1; break; case 's': stat_only = 1; break; case 'S': strict = 1; break; case 'I': ignmiss = 1; break;
   4870         case 'z': zero = 1; break; default: break;
   4871         }
   4872     if (!nops) ops[nops++] = "-";
   4873     if (!check) {
   4874         for (i = 0; i < nops; i++) {
   4875             int fd = open_input(ops[i]);
   4876             const char *name = ops[i];
   4877             int esc = 0;
   4878             if (fd < 0 || hash_fd(fd, alg, hex) < 0) { perr("%s", ops[i]); bad = 1; if (fd > 0) close(fd); continue; }
   4879             if (fd) close(fd);
   4880             if (!zero) {
   4881                 const char *s;
   4882                 for (s = name; *s; s++) if (*s == '\\' || *s == '\n') esc = 1;
   4883                 if (esc) putchar('\\');
   4884             }
   4885             if (tag) {
   4886                 { char tb[24]; printf("%s (", alg_tag(alg, tb)); }
   4887                 if (esc) { const char *s; for (s = name; *s; s++) fputs(*s == '\\' ? "\\\\" : *s == '\n' ? "\\n" : (char[]){ *s, 0 }, stdout); }
   4888                 else fputs(name, stdout);
   4889                 printf(") = %s", hex);
   4890             } else {
   4891                 printf("%s %c", hex, bin ? '*' : ' ');
   4892                 if (esc) { const char *s; for (s = name; *s; s++) fputs(*s == '\\' ? "\\\\" : *s == '\n' ? "\\n" : (char[]){ *s, 0 }, stdout); }
   4893                 else fputs(name, stdout);
   4894             }
   4895             putchar(zero ? 0 : '\n');
   4896         }
   4897         return finish_stdout() ? 1 : bad;
   4898     }
   4899     {
   4900         long fail = 0, unread = 0, improper = 0;
   4901         for (i = 0; i < nops; i++) {
   4902             FILE *f = !strcmp(ops[i], "-") ? stdin : fopen(ops[i], "r");
   4903             char *line = NULL;
   4904             size_t cap = 0;
   4905             ssize_t n;
   4906             long found = 0;
   4907             if (!f) { perr("%s", ops[i]); bad = 1; continue; }
   4908             while ((n = getline(&line, &cap, f)) >= 0) {
   4909                 char *p = line, *name, *want;
   4910                 char got[130];
   4911                 int fd, esc = 0, t = alg;
   4912                 if (n && line[n - 1] == '\n') line[--n] = 0;
   4913                 if (*p == '\\') { esc = 1; p++; }
   4914                 if (!*p || *p == '#') continue;
   4915                 {
   4916                     int a;
   4917                     size_t l = 0;
   4918                     for (a = 0; a < 7; a++) {
   4919                         l = strlen(alg_names[a]);
   4920                         if (!strncmp(p, alg_names[a], l)) {
   4921                             if (a == A_B2 && p[l] == '-') { l += strspn(p + l + 1, "0123456789") + 1; }
   4922                             if (p[l] == ' ' && p[l + 1] == '(') { t = a; break; }
   4923                         }
   4924                     }
   4925                     if (a < 7 && a == alg) {
   4926                         char *close_p = strstr(p, ") = ");
   4927                         if (!close_p) { improper++; continue; }
   4928                         if (a == A_B2) { unsigned long nb = 512; if (p[7] == '-') nb = strtoul(p + 8, NULL, 10); if (nb > 512 || nb % 8 || !nb) { improper++; continue; } b2bits = nb; }
   4929                         name = p + l + 2; *close_p = 0; want = close_p + 4;
   4930                         goto have;
   4931                     }
   4932                 }
   4933                 {
   4934                     size_t hl = strspn(p, "0123456789abcdefABCDEF");
   4935                     if (alg == A_B2 && hl && hl % 2 == 0 && hl <= 128 && p[hl] == ' ') b2bits = hl * 4;
   4936                     if (hl != hash_size(alg) * 2 || p[hl] != ' ' || (p[hl + 1] != ' ' && p[hl + 1] != '*')) { improper++; continue; }
   4937                     p[hl] = 0; want = p; name = p + hl + 2;
   4938                 }
   4939 have:
   4940                 found++;
   4941                 if (esc) {
   4942                     char *r = name, *w = name;
   4943                     while (*r) { if (*r == '\\' && r[1] == 'n') { *w++ = '\n'; r += 2; } else if (*r == '\\' && r[1] == '\\') { *w++ = '\\'; r += 2; } else *w++ = *r++; }
   4944                     *w = 0;
   4945                 }
   4946                 fd = open_input(name);
   4947                 if (fd < 0) {
   4948                     if (ignmiss && errno == ENOENT) continue;
   4949                     fflush(stdout);
   4950                     fprintf(stderr, "%s: %s: %s\n", prog, name, strerror(errno));
   4951                     if (!stat_only) printf("%s: FAILED open or read\n", name);
   4952                     unread++; continue;
   4953                 }
   4954                 if (hash_fd(fd, t, got) < 0) { perr("%s", name); unread++; if (fd) close(fd); continue; }
   4955                 if (fd) close(fd);
   4956                 {
   4957                     size_t k;
   4958                     int same = strlen(want) == strlen(got);
   4959                     for (k = 0; same && got[k]; k++) if (tolower((unsigned char)want[k]) != got[k]) same = 0;
   4960                     if (same) { if (!quiet && !stat_only) printf("%s: OK\n", name); }
   4961                     else { fail++; if (!stat_only) printf("%s: FAILED\n", name); }
   4962                 }
   4963             }
   4964             free(line);
   4965             if (f != stdin) fclose(f);
   4966             if (!found) { if (!stat_only) say("%s: no properly formatted checksum lines found", ops[i]); bad = 1; }
   4967         }
   4968         fflush(stdout);
   4969         if (!stat_only) {
   4970             if (improper) say("WARNING: %ld line%s improperly formatted", improper, improper == 1 ? " is" : "s are");
   4971             if (unread) say("WARNING: %ld listed file%s could not be read", unread, unread == 1 ? "" : "s");
   4972             if (fail) say("WARNING: %ld computed checksum%s did NOT match", fail, fail == 1 ? "" : "s");
   4973         }
   4974         return finish_stdout() ? 1 : (bad || fail || unread || (strict && improper)) ? 1 : 0;
   4975     }
   4976 }
   4977 
   4978 static uint32_t crc_table[256];
   4979 
   4980 static void crc_init(void)
   4981 {
   4982     int i, j;
   4983     for (i = 0; i < 256; i++) {
   4984         uint32_t c = (uint32_t)i << 24;
   4985         for (j = 0; j < 8; j++) c = c & 0x80000000 ? c << 1 ^ 0x04c11db7 : c << 1;
   4986         crc_table[i] = c;
   4987     }
   4988 }
   4989 
   4990 static int t_cksum(int argc, char **argv)
   4991 {
   4992     static const struct opt lo[] = { { "algorithm", 1, 'a' }, { "tag", 0, 'T' }, { "untagged", 0, 'U' }, { "binary", 0, 'b' }, { "text", 0, 't' }, { NULL, 0, 0 } };
   4993     int c, bad = 0, i, mode = 0;
   4994     const char *al = "crc";
   4995     int issum = !strcmp(prog, "sum"), sysv = 0, implicit;
   4996     opts_reset();
   4997     while ((c = getopts(argc, argv, issum ? "rs" : "a:bt", lo)))
   4998         switch (c) {
   4999         case 'a': al = optarg; break; case 's': sysv = 1; break; default: break;
   5000         }
   5001     if (issum) al = sysv ? "sysv" : "bsd";
   5002     if (!strcmp(al, "crc")) mode = 0; else if (!strcmp(al, "sysv")) mode = 1; else if (!strcmp(al, "bsd")) mode = 2;
   5003     else {
   5004         int a;
   5005         for (a = 0; a < 6; a++) {
   5006             char low[16];
   5007             size_t k;
   5008             for (k = 0; alg_names[a][k]; k++) low[k] = tolower((unsigned char)alg_names[a][k]);
   5009             low[k] = 0;
   5010             if (!strcmp(al, low)) {
   5011                 char **nv = xmalloc((argc + 2) * sizeof *nv);
   5012                 int n = 0, j;
   5013                 static const char *const progs[] = { "md5sum", "sha1sum", "sha224sum", "sha256sum", "sha384sum", "sha512sum" };
   5014                 nv[n++] = (char *)progs[a]; nv[n++] = "--tag";
   5015                 for (j = 0; j < nops; j++) nv[n++] = ops[j];
   5016                 nv[n] = NULL;
   5017                 prog = progs[a];
   5018                 opts_reset();
   5019                 return t_digest(n, nv);
   5020             }
   5021         }
   5022         die(1, "invalid argument '%s' for '--algorithm'", al);
   5023     }
   5024     crc_init();
   5025     implicit = !nops;
   5026     if (!nops) ops[nops++] = "-";
   5027     for (i = 0; i < nops; i++) {
   5028         int fd = open_input(ops[i]);
   5029         unsigned char buf[65536];
   5030         ssize_t n, k;
   5031         uint32_t crc = 0;
   5032         unsigned long long len = 0, sum = 0;
   5033         unsigned bsd = 0;
   5034         if (fd < 0) { perr("%s", ops[i]); bad = 1; continue; }
   5035         while ((n = read(fd, buf, sizeof buf)) > 0) {
   5036             len += n;
   5037             for (k = 0; k < n; k++) {
   5038                 if (mode == 0) crc = crc << 8 ^ crc_table[(crc >> 24 ^ buf[k]) & 255];
   5039                 else if (mode == 1) sum += buf[k];
   5040                 else { bsd = (bsd >> 1) + ((bsd & 1) << 15); bsd = (bsd + buf[k]) & 0xffff; }
   5041             }
   5042         }
   5043         if (n < 0) { perr("%s", ops[i]); bad = 1; if (fd) close(fd); continue; }
   5044         if (fd) close(fd);
   5045         if (mode == 0) {
   5046             unsigned long long l = len;
   5047             for (; l; l >>= 8) crc = crc << 8 ^ crc_table[(crc >> 24 ^ (unsigned)(l & 255)) & 255];
   5048             crc = ~crc;
   5049             printf("%u %llu", crc, len);
   5050         } else if (mode == 1) {
   5051             unsigned r = (sum & 0xffff) + ((sum & 0xffffffff) >> 16);
   5052             r = (r & 0xffff) + (r >> 16);
   5053             printf("%u %llu", r, (len + (issum ? 511 : 511)) / 512);
   5054         } else printf("%05u %5llu", bsd, (len + 1023) / 1024);
   5055         if (!implicit && (!issum || nops > 1)) printf(" %s", ops[i]);
   5056         putchar('\n');
   5057     }
   5058     return finish_stdout() ? 1 : bad;
   5059 }
   5060 
   5061 /* ---- base64 base32 ---- */
   5062 
   5063 static const char *base_alpha;
   5064 static int base_b32 = -1;
   5065 
   5066 static int t_base(int argc, char **argv)
   5067 {
   5068     static const struct opt lo[] = { { "decode", 0, 'd' }, { "wrap", 1, 'w' }, { "ignore-garbage", 0, 'i' }, { NULL, 0, 0 } };
   5069     int b32 = base_b32 >= 0 ? base_b32 : !strcmp(prog, "base32"), c, dec = 0, ign = 0, bad = 0, col = 0;
   5070     unsigned long wrap = 76;
   5071     const char *alpha = base_alpha ? base_alpha : b32 ? "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
   5072     int bits = b32 ? 5 : 6, grp = b32 ? 5 : 3, outc = b32 ? 8 : 4;
   5073     unsigned char *d;
   5074     size_t len, i;
   5075     int fd;
   5076     opts_reset();
   5077     while ((c = getopts(argc, argv, "diw:", lo)))
   5078         switch (c) {
   5079         case 'd': dec = 1; break; case 'i': ign = 1; break;
   5080         case 'w': if (!parse_ulong(optarg, &wrap)) die(1, "invalid wrap size: '%s'", optarg); break;
   5081         default: break;
   5082         }
   5083     if (nops > 1) extra_operand(ops[1]);
   5084     fd = open_input(nops ? ops[0] : "-");
   5085     if (fd < 0) { perr("%s", ops[0]); return 1; }
   5086     if (read_all(fd, (char **)&d, &len) < 0) { perr("read error"); return 1; }
   5087     if (!dec) {
   5088         for (i = 0; i < len; i += grp) {
   5089             unsigned long long v = 0;
   5090             size_t have = len - i < (size_t)grp ? len - i : (size_t)grp;
   5091             int k, nchars = (int)((have * 8 + bits - 1) / bits);
   5092             for (k = 0; k < grp; k++) v = v << 8 | (k < (int)have ? d[i + k] : 0);
   5093             for (k = 0; k < outc; k++) {
   5094                 char ch = k < nchars ? alpha[(v >> ((outc - 1 - k) * bits)) & ((1 << bits) - 1)] : '=';
   5095                 if (wrap && col == (int)wrap) { putchar('\n'); col = 0; }
   5096                 putchar(ch); col++;
   5097             }
   5098         }
   5099         if (col && wrap) putchar('\n');
   5100     } else {
   5101         unsigned long long acc = 0;
   5102         int nb = 0, pad = 0;
   5103         for (i = 0; i < len && !bad; i++) {
   5104             const char *p;
   5105             int k;
   5106             if (d[i] == '\n') continue;
   5107             if (d[i] == '=') {
   5108                 pad++;
   5109                 if (!nb || nb + pad > outc) { bad = 1; pad = 0; continue; }
   5110                 if (nb + pad == outc) goto flush;
   5111                 continue;
   5112             }
   5113             p = d[i] ? strchr(alpha, d[i]) : NULL;
   5114             if (!p || pad) { if (ign) continue; bad = 1; break; }
   5115             acc = acc << bits | (p - alpha);
   5116             if (++nb == outc) {
   5117                 for (k = grp - 1; k >= 0; k--) putchar((acc >> (8 * k)) & 255);
   5118                 acc = 0; nb = 0;
   5119             }
   5120             continue;
   5121 flush:
   5122             {
   5123                 int bytes = nb * bits / 8, rem = nb * bits % 8;
   5124                 if (rem >= bits || (acc & ((1ULL << rem) - 1))) bad = 1;
   5125                 for (k = bytes - 1; k >= 0; k--) putchar((acc >> (rem + 8 * k)) & 255);
   5126                 acc = 0; nb = 0; pad = 0;
   5127             }
   5128         }
   5129         if (!bad && pad) bad = 1;
   5130         if (nb) {
   5131             int bytes = nb * bits / 8, rem = nb * bits % 8, k;
   5132             if (rem >= bits || (acc & ((1ULL << rem) - 1))) bad = 1;
   5133             for (k = bytes - 1; k >= 0; k--) putchar((acc >> (rem + 8 * k)) & 255);
   5134         }
   5135         if (bad) { fflush(stdout); say("invalid input"); return 1; }
   5136     }
   5137     return finish_stdout() ? 1 : 0;
   5138 }
   5139 
   5140 
   5141 /* ---- basenc ---- */
   5142 
   5143 static void bn_out(unsigned long wrap, int *col, int ch)
   5144 {
   5145     if (wrap && *col == (int)wrap) { putchar('\n'); *col = 0; }
   5146     putchar(ch);
   5147     (*col)++;
   5148 }
   5149 
   5150 static int t_basenc(int argc, char **argv)
   5151 {
   5152     static const struct opt lo[] = { { "base64", 0, 1 }, { "base64url", 0, 2 }, { "base32", 0, 3 }, { "base32hex", 0, 4 }, { "base16", 0, 5 },
   5153         { "base2msbf", 0, 6 }, { "base2lsbf", 0, 7 }, { "z85", 0, 8 }, { "decode", 0, 'd' }, { "wrap", 1, 'w' }, { "ignore-garbage", 0, 'i' }, { NULL, 0, 0 } };
   5154     static const char z85[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#";
   5155     int c, kind = 0, dec = 0, ign = 0, col = 0, fd, bad = 0;
   5156     unsigned long wrap = 76;
   5157     unsigned char *d;
   5158     size_t len, i;
   5159     opts_reset();
   5160     while ((c = getopts(argc, argv, "diw:", lo)))
   5161         switch (c) {
   5162         case 'd': dec = 1; break; case 'i': ign = 1; break;
   5163         case 'w': if (!parse_ulong(optarg, &wrap)) die(1, "invalid wrap size: '%s'", optarg); break;
   5164         default: if (c >= 1 && c <= 8) { kind = c; } break;
   5165         }
   5166     if (!kind) { say("missing encoding type"); usage_error(); }
   5167     if (nops > 1) extra_operand(ops[1]);
   5168     if (kind <= 4) {
   5169         static const char *const al[] = { NULL, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
   5170             "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "0123456789ABCDEFGHIJKLMNOPQRSTUV" };
   5171         char *nv[8];
   5172         int n = 0;
   5173         nv[n++] = argv[0];
   5174         if (dec) nv[n++] = "-d";
   5175         if (ign) nv[n++] = "-i";
   5176         { char w[24]; snprintf(w, sizeof w, "-w%lu", wrap); nv[n++] = strdup(w); }
   5177         if (nops) nv[n++] = ops[0];
   5178         nv[n] = NULL;
   5179         base_alpha = al[kind];
   5180         base_b32 = kind >= 3;
   5181         opts_reset();
   5182         return t_base(n, nv);
   5183     }
   5184     fd = open_input(nops ? ops[0] : "-");
   5185     if (fd < 0) { perr("%s", ops[0]); return 1; }
   5186     if (read_all(fd, (char **)&d, &len) < 0) { perr("read error"); return 1; }
   5187     if (!dec) {
   5188         if (kind == 8) {
   5189             if (len % 4) { say("invalid input (length must be multiple of 4 characters)"); return 1; }
   5190             for (i = 0; i < len; i += 4) {
   5191                 unsigned long v = (unsigned long)d[i] << 24 | d[i + 1] << 16 | d[i + 2] << 8 | d[i + 3];
   5192                 char t[5];
   5193                 int k;
   5194                 for (k = 4; k >= 0; k--) { t[k] = z85[v % 85]; v /= 85; }
   5195                 for (k = 0; k < 5; k++) bn_out(wrap, &col, t[k]);
   5196             }
   5197         } else for (i = 0; i < len; i++) {
   5198             int k;
   5199             if (kind == 5) { static const char hx[] = "0123456789ABCDEF"; bn_out(wrap, &col, hx[d[i] >> 4]); bn_out(wrap, &col, hx[d[i] & 15]); }
   5200             else for (k = 0; k < 8; k++) bn_out(wrap, &col, '0' + (kind == 6 ? d[i] >> (7 - k) & 1 : d[i] >> k & 1));
   5201         }
   5202         if (col && wrap) putchar('\n');
   5203         return finish_stdout() ? 1 : 0;
   5204     }
   5205     {
   5206         unsigned long acc = 0;
   5207         int nb = 0, per = kind == 5 ? 2 : kind == 8 ? 5 : 8;
   5208         for (i = 0; i < len && !bad; i++) {
   5209             int v = -1;
   5210             unsigned char ch = d[i];
   5211             if (ch == '\n') continue;
   5212             if (kind == 5) v = isdigit(ch) ? ch - '0' : ch >= 'A' && ch <= 'F' ? ch - 'A' + 10 : ch >= 'a' && ch <= 'f' ? ch - 'a' + 10 : -1;
   5213             else if (kind == 8) { const char *p = ch ? strchr(z85, ch) : NULL; v = p ? p - z85 : -1; }
   5214             else v = ch == '0' || ch == '1' ? ch - '0' : -1;
   5215             if (v < 0) { if (ign) continue; bad = 1; break; }
   5216             if (kind == 8) acc = acc * 85 + v; else if (kind == 5) acc = acc << 4 | v; else acc = kind == 6 ? acc << 1 | v : acc | (unsigned long)v << nb;
   5217             if (++nb == per) {
   5218                 if (kind == 8) { int k; for (k = 3; k >= 0; k--) putchar(acc >> (8 * k) & 255); }
   5219                 else putchar(acc & 255);
   5220                 acc = 0; nb = 0;
   5221             }
   5222         }
   5223         if (nb && !bad) bad = 1;
   5224         if (bad) { fflush(stdout); say("invalid input"); return 1; }
   5225     }
   5226     return finish_stdout() ? 1 : 0;
   5227 }
   5228 
   5229 /* ---- shred ---- */
   5230 
   5231 static void rnd_fill(unsigned char *b, size_t n)
   5232 {
   5233     static int fd = -2;
   5234     size_t got = 0;
   5235     if (fd == -2) fd = open("/dev/urandom", O_RDONLY);
   5236     while (fd >= 0 && got < n) { ssize_t r = read(fd, b + got, n - got); if (r <= 0) break; got += r; }
   5237     while (got < n) b[got++] = (unsigned char)rand();
   5238 }
   5239 
   5240 static int shred_pass(int fd, unsigned long long size, const unsigned char *pat, int plen, int rnd, int exact)
   5241 {
   5242     unsigned char buf[65536];
   5243     unsigned long long done = 0;
   5244     size_t i;
   5245     if (lseek(fd, 0, SEEK_SET) < 0) return -1;
   5246     while (done < size || (!exact && done == 0 && !size)) {
   5247         size_t n = size - done < sizeof buf ? size - done : sizeof buf;
   5248         if (!n) break;
   5249         if (rnd) rnd_fill(buf, n); else for (i = 0; i < n; i++) buf[i] = pat[(done + i) % plen];
   5250         if (write(fd, buf, n) != (ssize_t)n) return -1;
   5251         done += n;
   5252     }
   5253     return fsync(fd);
   5254 }
   5255 
   5256 static int t_shred(int argc, char **argv)
   5257 {
   5258     static const struct opt lo[] = { { "force", 0, 'f' }, { "iterations", 1, 'n' }, { "size", 1, 's' }, { "remove", 2, 'u' }, { "verbose", 0, 'v' },
   5259         { "exact", 0, 'x' }, { "zero", 0, 'z' }, { "random-source", 1, 1000 }, { NULL, 0, 0 } };
   5260     static const unsigned char pats[][3] = { { 0x55, 0x55, 0x55 }, { 0xaa, 0xaa, 0xaa }, { 0x92, 0x49, 0x24 }, { 0x49, 0x24, 0x92 }, { 0x24, 0x92, 0x49 },
   5261         { 0x6d, 0xb6, 0xdb }, { 0xb6, 0xdb, 0x6d }, { 0xdb, 0x6d, 0xb6 }, { 0x00, 0x00, 0x00 }, { 0xff, 0xff, 0xff }, { 0x11, 0x11, 0x11 },
   5262         { 0x22, 0x22, 0x22 }, { 0x33, 0x33, 0x33 }, { 0x44, 0x44, 0x44 }, { 0x66, 0x66, 0x66 }, { 0x77, 0x77, 0x77 }, { 0x88, 0x88, 0x88 },
   5263         { 0x99, 0x99, 0x99 }, { 0xbb, 0xbb, 0xbb }, { 0xcc, 0xcc, 0xcc }, { 0xdd, 0xdd, 0xdd }, { 0xee, 0xee, 0xee } };
   5264     int c, force = 0, remove_ = 0, verbose = 0, exact = 0, zero = 0, bad = 0, i;
   5265     unsigned long iters = 3;
   5266     long long fsize = -1;
   5267     opts_reset();
   5268     while ((c = getopts(argc, argv, "fn:s:uvxz", lo)))
   5269         switch (c) {
   5270         case 'f': force = 1; break; case 'v': verbose = 1; break; case 'x': exact = 1; break; case 'z': zero = 1; break; case 'u': remove_ = 1; break;
   5271         case 'n': if (!parse_ulong(optarg, &iters)) die(1, "invalid number of passes: '%s'", optarg); break;
   5272         case 's': { unsigned long n; char *e; n = strtoul(optarg, &e, 10); if (e == optarg) die(1, "invalid file size: '%s'", optarg);
   5273             if (*e == 'K') n *= 1024; else if (*e == 'M') n <<= 20; else if (*e == 'G') n <<= 30; else if (*e == 'k') n *= 1000; else if (*e && *e != 'c') die(1, "invalid file size: '%s'", optarg);
   5274             fsize = n; break; }
   5275         default: break;
   5276         }
   5277     if (!nops) { say("missing file operand"); usage_error(); }
   5278     for (i = 0; i < nops; i++) {
   5279         const char *f = ops[i];
   5280         int fd, p, total, isstd = !strcmp(f, "-");
   5281         struct stat st;
   5282         unsigned long long size;
   5283         if (isstd) fd = 1;
   5284         else {
   5285             fd = open(f, O_WRONLY);
   5286             if (fd < 0 && force && errno == EACCES) { chmod(f, 0600); fd = open(f, O_WRONLY); }
   5287             if (fd < 0) { say("%s: failed to open for writing: %s", f, strerror(errno)); bad = 1; continue; }
   5288         }
   5289         if (fstat(fd, &st) < 0) { perr("%s: failed to stat", f); bad = 1; continue; }
   5290         size = fsize >= 0 ? (unsigned long long)fsize : S_ISREG(st.st_mode) ? (unsigned long long)st.st_size : 0;
   5291         if (!exact && fsize < 0 && size % st.st_blksize) size += st.st_blksize - size % st.st_blksize;
   5292         total = iters + zero;
   5293         for (p = 1; p <= total; p++) {
   5294             int rnd = p <= (int)iters, zp = !rnd;
   5295             unsigned char z[3] = { 0, 0, 0 };
   5296             const char *label = rnd ? "random" : "000000";
   5297             unsigned char sel[3];
   5298             if (rnd && iters > 3 && p != 1 && p != (int)iters) { memcpy(sel, pats[(p * 7) % 22], 3); rnd = 0; { static char lb[8]; snprintf(lb, sizeof lb, "%02x%02x%02x", sel[0], sel[1], sel[2]); label = lb; } }
   5299             if (verbose) say("%s: pass %d/%d (%s)...", f, p, total, label);
   5300             if (shred_pass(fd, size, zp ? z : sel, 3, rnd, exact) < 0) { say("%s: error writing at offset %llu: %s", f, size, strerror(errno)); bad = 1; break; }
   5301         }
   5302         if (!isstd) close(fd);
   5303         if (remove_ && !isstd && !bad) {
   5304             char dir[PATH_MAX], *sl, nm[PATH_MAX];
   5305             size_t l;
   5306             int k;
   5307             if (verbose) say("%s: removing", f);
   5308             snprintf(dir, sizeof dir, "%s", f);
   5309             sl = strrchr(dir, '/');
   5310             if (sl) sl[1] = 0; else dir[0] = 0;
   5311             l = strlen(f) - (sl ? sl + 1 - dir : 0);
   5312             { const char *base = sl ? f + (sl + 1 - dir) : f; char cur[PATH_MAX]; snprintf(cur, sizeof cur, "%s", f);
   5313               for (; l > 0; l--) {
   5314                   snprintf(nm, sizeof nm, "%s", dir);
   5315                   for (k = 0; k < (int)l; k++) strcat(nm, "0");
   5316                   if (!rename(cur, nm)) {
   5317                       if (verbose) say("%s: renamed to %s", cur, nm);
   5318                       snprintf(cur, sizeof cur, "%s", nm);
   5319                   } else if (errno != EEXIST) break;
   5320               }
   5321               (void)base;
   5322               if (unlink(cur) < 0) { say("%s: failed to remove: %s", cur, strerror(errno)); bad = 1; }
   5323               else if (verbose) say("%s: removed", f); }
   5324         }
   5325     }
   5326     return bad;
   5327 }
   5328 
   5329 /* ---- dd ---- */
   5330 
   5331 static unsigned long long dd_num(const char *s)
   5332 {
   5333     unsigned long long v = 0, m;
   5334     char *e;
   5335     const char *x;
   5336     if (!isdigit((unsigned char)*s)) die(1, "invalid number: '%s'", s);
   5337     v = strtoull(s, &e, 10);
   5338     for (;;) {
   5339         m = 1;
   5340         switch (*e) {
   5341         case 'c': m = 1; e++; break; case 'w': m = 2; e++; break; case 'b': m = 512; e++; break;
   5342         case 'k': case 'K': m = 1024; e++; if (*e == 'B') { m = 1000; e++; } break;
   5343         case 'M': m = 1 << 20; e++; if (*e == 'B') { m = 1000000; e++; } break;
   5344         case 'G': m = 1ULL << 30; e++; if (*e == 'B') { m = 1000000000; e++; } break;
   5345         case 'T': m = 1ULL << 40; e++; break;
   5346         default: break;
   5347         }
   5348         v *= m;
   5349         if (*e == 'x') { x = e + 1; if (!isdigit((unsigned char)*x)) die(1, "invalid number: '%s'", s); v *= strtoull(x, &e, 10); continue; }
   5350         break;
   5351     }
   5352     if (*e) die(1, "invalid number: '%s'", s);
   5353     return v;
   5354 }
   5355 
   5356 static int t_dd(int argc, char **argv)
   5357 {
   5358     const char *in = NULL, *out = NULL;
   5359     unsigned long long ibs = 512, obs = 512, count = ~0ULL, skip = 0, seek = 0, rin = 0, pin = 0, rout = 0, pout = 0, bytes = 0;
   5360     int notrunc = 0, sync_ = 0, noerror = 0, ucase = 0, lcase = 0, swab = 0, excl = 0, nocreat = 0, status = 1, i, fi = 0, fo = 1;
   5361     unsigned char *buf, *ob;
   5362     size_t on = 0;
   5363     int rc = 0;
   5364     if (argc == 2 && !strcmp(argv[1], "--help")) { print_usage(); return 0; }
   5365     if (argc == 2 && !strcmp(argv[1], "--version")) { printf("dd (rifle) " VERSION "\n"); return 0; }
   5366     for (i = 1; i < argc; i++) {
   5367         char *a = argv[i], *v = strchr(a, '=');
   5368         if (!v) { say("unrecognized operand '%s'", a); usage_error(); }
   5369         *v++ = 0;
   5370         if (!strcmp(a, "if")) in = v; else if (!strcmp(a, "of")) out = v;
   5371         else if (!strcmp(a, "bs")) { ibs = obs = dd_num(v); }
   5372         else if (!strcmp(a, "ibs")) ibs = dd_num(v); else if (!strcmp(a, "obs")) obs = dd_num(v);
   5373         else if (!strcmp(a, "count")) count = dd_num(v); else if (!strcmp(a, "skip") || !strcmp(a, "iseek")) skip = dd_num(v);
   5374         else if (!strcmp(a, "seek") || !strcmp(a, "oseek")) seek = dd_num(v);
   5375         else if (!strcmp(a, "status")) status = !strcmp(v, "none") ? 0 : !strcmp(v, "noxfer") ? 2 : 1;
   5376         else if (!strcmp(a, "conv")) {
   5377             char *t = v, *e;
   5378             while (t) {
   5379                 e = strchr(t, ','); if (e) *e++ = 0;
   5380                 if (!strcmp(t, "notrunc")) notrunc = 1; else if (!strcmp(t, "sync")) sync_ = 1; else if (!strcmp(t, "noerror")) noerror = 1;
   5381                 else if (!strcmp(t, "ucase")) ucase = 1; else if (!strcmp(t, "lcase")) lcase = 1; else if (!strcmp(t, "swab")) swab = 1;
   5382                 else if (!strcmp(t, "excl")) excl = 1; else if (!strcmp(t, "nocreat")) nocreat = 1; else if (strcmp(t, "fsync") && strcmp(t, "fdatasync")) die(1, "invalid conversion: '%s'", t);
   5383                 t = e;
   5384             }
   5385         } else if (strcmp(a, "iflag") && strcmp(a, "oflag")) { say("unrecognized operand '%s=%s'", a, v); usage_error(); }
   5386     }
   5387     if (!ibs || !obs) die(1, "invalid number: '0'");
   5388     if (in) { fi = open(in, O_RDONLY); if (fi < 0) { perr("failed to open '%s'", in); return 1; } }
   5389     if (out) {
   5390         int fl = O_WRONLY | (nocreat ? 0 : O_CREAT) | (excl ? O_EXCL : 0) | (notrunc || seek ? 0 : O_TRUNC);
   5391         fo = open(out, fl, 0666);
   5392         if (fo < 0) { perr("failed to open '%s'", out); return 1; }
   5393     }
   5394     buf = xmalloc(ibs); ob = xmalloc(obs + ibs);
   5395     if (skip) {
   5396         if (lseek(fi, skip * ibs, SEEK_CUR) < 0) {
   5397             unsigned long long k;
   5398             for (k = 0; k < skip; k++) { ssize_t r = read(fi, buf, ibs); if (r <= 0) break; }
   5399         }
   5400     }
   5401     if (seek) {
   5402         if (lseek(fo, seek * obs, SEEK_SET) < 0) perr("cannot seek '%s'", out ? out : "standard output");
   5403     }
   5404     while (count == ~0ULL || rin + pin < count) {
   5405         ssize_t n = read(fi, buf, ibs);
   5406         size_t k;
   5407         if (n < 0) {
   5408             perr("error reading '%s'", in ? in : "standard input");
   5409             rc = 1;
   5410             if (!noerror) break;
   5411             if (status) { fprintf(stderr, "%llu+%llu records in\n%llu+%llu records out\n", rin, pin, rout, pout); }
   5412             n = 0;
   5413             if (sync_) n = 0;
   5414             if (!sync_) continue;
   5415         }
   5416         if (n == 0 && !(sync_ && rc)) break;
   5417         if ((unsigned long long)n < ibs) {
   5418             pin++;
   5419             if (sync_) { memset(buf + n, ucase || lcase ? ' ' : 0, ibs - n); n = ibs; }
   5420         } else rin++;
   5421         if (swab) for (k = 0; k + 1 < (size_t)n; k += 2) { unsigned char t = buf[k]; buf[k] = buf[k + 1]; buf[k + 1] = t; }
   5422         if (ucase) for (k = 0; k < (size_t)n; k++) buf[k] = toupper(buf[k]);
   5423         if (lcase) for (k = 0; k < (size_t)n; k++) buf[k] = tolower(buf[k]);
   5424         memcpy(ob + on, buf, n); on += n;
   5425         while (on >= obs) {
   5426             if (write_all(fo, (char *)ob, obs) < 0) { perr("error writing '%s'", out ? out : "standard output"); return 1; }
   5427             bytes += obs; rout++;
   5428             memmove(ob, ob + obs, on - obs); on -= obs;
   5429         }
   5430     }
   5431     if (on) {
   5432         if (write_all(fo, (char *)ob, on) < 0) { perr("error writing '%s'", out ? out : "standard output"); return 1; }
   5433         bytes += on; pout++;
   5434     }
   5435     if (out && !notrunc && seek) ftruncate(fo, seek * obs + bytes);
   5436     if (status) {
   5437         fprintf(stderr, "%llu+%llu records in\n%llu+%llu records out\n", rin, pin, rout, pout);
   5438         if (status == 1) fprintf(stderr, "%llu bytes copied\n", bytes);
   5439     }
   5440     if (out && close(fo) < 0) { perr("closing output file"); return 1; }
   5441     return rc;
   5442 }
   5443 
   5444 /* ---- od ---- */
   5445 
   5446 struct odfmt { char kind; int size; int width; };
   5447 
   5448 static const char *const od_names[] = { "nul", "soh", "stx", "etx", "eot", "enq", "ack", "bel", "bs", "ht", "nl", "vt", "ff", "cr", "so", "si",
   5449     "dle", "dc1", "dc2", "dc3", "dc4", "nak", "syn", "etb", "can", "em", "sub", "esc", "fs", "gs", "rs", "us", "sp" };
   5450 
   5451 static int od_spec(const char *s, struct odfmt *f, int max)
   5452 {
   5453     int n = 0;
   5454     while (*s) {
   5455         char k = *s++;
   5456         int size = 0;
   5457         if (n == max) die(1, "too many -t formats");
   5458         if (k == 'a' || k == 'c') { f[n].kind = k; f[n].size = 1; f[n].width = 3; n++; continue; }
   5459         if (!strchr("doux", k) && k != 'f') die(1, "invalid type string '%c'", k);
   5460         if (isdigit((unsigned char)*s)) { size = strtol(s, (char **)&s, 10); }
   5461         else if (*s == 'C') { size = 1; s++; } else if (*s == 'S') { size = 2; s++; } else if (*s == 'I') { size = 4; s++; } else if (*s == 'L') { size = 8; s++; }
   5462         else if (*s == 'F' || *s == 'D') { size = *s == 'F' ? 4 : 8; s++; }
   5463         else size = k == 'f' ? 8 : 4;
   5464         if (k == 'f') { if (size != 4 && size != 8) die(1, "invalid type string 'f%d'", size); }
   5465         else if (size != 1 && size != 2 && size != 4 && size != 8) die(1, "invalid type string '%c%d'", k, size);
   5466         f[n].kind = k; f[n].size = size;
   5467         if (k == 'f') f[n].width = size == 4 ? 15 : 24;
   5468         else if (k == 'o') f[n].width = size == 1 ? 3 : size == 2 ? 6 : size == 4 ? 11 : 22;
   5469         else if (k == 'x') f[n].width = size * 2;
   5470         else if (k == 'u') f[n].width = size == 1 ? 3 : size == 2 ? 5 : size == 4 ? 10 : 20;
   5471         else f[n].width = size == 1 ? 4 : size == 2 ? 6 : size == 4 ? 11 : 20;
   5472         n++;
   5473     }
   5474     return n;
   5475 }
   5476 
   5477 static void od_field(const struct odfmt *f, const unsigned char *p, size_t avail)
   5478 {
   5479     unsigned long long v = 0;
   5480     int i;
   5481     unsigned char tmp[8] = { 0 };
   5482     memcpy(tmp, p, avail < (size_t)f->size ? avail : (size_t)f->size);
   5483     for (i = f->size - 1; i >= 0; i--) v = v << 8 | tmp[i];
   5484     switch (f->kind) {
   5485     case 'a': { int c = tmp[0] & 127; printf(" %*s", 3, c < 33 ? od_names[c] : c == 127 ? "del" : (char[]){ c, 0 }); break; }
   5486     case 'c': {
   5487         int c = tmp[0];
   5488         char b[8];
   5489         switch (c) {
   5490         case 0: strcpy(b, "\\0"); break; case 7: strcpy(b, "\\a"); break; case 8: strcpy(b, "\\b"); break; case 12: strcpy(b, "\\f"); break;
   5491         case 10: strcpy(b, "\\n"); break; case 13: strcpy(b, "\\r"); break; case 9: strcpy(b, "\\t"); break; case 11: strcpy(b, "\\v"); break;
   5492         default: if (c >= 32 && c < 127) { b[0] = c; b[1] = 0; } else sprintf(b, "%03o", c);
   5493         }
   5494         printf(" %*s", 3, b);
   5495         break;
   5496     }
   5497     case 'o': printf(" %0*llo", f->width, v); break;
   5498     case 'x': printf(" %0*llx", f->width, v); break;
   5499     case 'u': printf(" %*llu", f->width, v); break;
   5500     case 'd': {
   5501         long long sv = f->size == 1 ? (signed char)v : f->size == 2 ? (short)v : f->size == 4 ? (int)v : (long long)v;
   5502         printf(" %*lld", f->width, sv);
   5503         break;
   5504     }
   5505     case 'f': {
   5506         if (f->size == 4) { float x; memcpy(&x, tmp, 4); printf(" %*.8g", f->width, (double)x); }
   5507         else { double x; memcpy(&x, tmp, 8); printf(" %*.17g", f->width, x); }
   5508         break;
   5509     }
   5510     }
   5511 }
   5512 
   5513 static int t_od(int argc, char **argv)
   5514 {
   5515     static const struct opt lo[] = { { "address-radix", 1, 'A' }, { "format", 1, 't' }, { "read-bytes", 1, 'N' }, { "skip-bytes", 1, 'j' },
   5516         { "output-duplicates", 0, 'v' }, { "width", 2, 'w' }, { NULL, 0, 0 } };
   5517     struct odfmt fm[16];
   5518     int nf = 0, c, radix = 'o', dups = 0, i, fd, bad = 0;
   5519     unsigned long width = 16, limit = ~0UL, skip = 0;
   5520     unsigned char *data, *prev = NULL;
   5521     size_t len = 0, pos;
   5522     int starred = 0, aw;
   5523     opts_reset();
   5524     while ((c = getopts(argc, argv, "A:t:N:j:vw::abcdfhilosxCDFIL", lo)))
   5525         switch (c) {
   5526         case 'A': if (!strchr("doxn", optarg[0]) || optarg[1]) die(1, "invalid output address radix '%s'; it must be one character from [doxn]", optarg); radix = optarg[0]; break;
   5527         case 't': nf += od_spec(optarg, fm + nf, 16 - nf); break;
   5528         case 'N': if (!parse_ulong(optarg, &limit)) die(1, "invalid -N argument '%s'", optarg); break;
   5529         case 'j': if (!parse_ulong(optarg, &skip)) die(1, "invalid -j argument '%s'", optarg); break;
   5530         case 'v': dups = 1; break;
   5531         case 'w': width = optarg ? strtoul(optarg, NULL, 10) : 32; if (!width) width = 16; break;
   5532         case 'a': nf += od_spec("a", fm + nf, 16 - nf); break;
   5533         case 'b': nf += od_spec("o1", fm + nf, 16 - nf); break;
   5534         case 'c': nf += od_spec("c", fm + nf, 16 - nf); break;
   5535         case 'd': nf += od_spec("u2", fm + nf, 16 - nf); break;
   5536         case 'f': nf += od_spec("f4", fm + nf, 16 - nf); break;
   5537         case 'h': case 'x': nf += od_spec("x2", fm + nf, 16 - nf); break;
   5538         case 'i': nf += od_spec("d2", fm + nf, 16 - nf); break;
   5539         case 'l': nf += od_spec("d8", fm + nf, 16 - nf); break;
   5540         case 'o': nf += od_spec("o2", fm + nf, 16 - nf); break;
   5541         case 's': nf += od_spec("d2", fm + nf, 16 - nf); break;
   5542         default: break;
   5543         }
   5544     if (!nf) nf = od_spec("o2", fm, 16);
   5545     {
   5546         size_t cap = 0, got = 0;
   5547         char *all = NULL;
   5548         int k;
   5549         if (!nops) ops[nops++] = "-";
   5550         for (k = 0; k < nops; k++) {
   5551             char *d;
   5552             size_t l;
   5553             fd = open_input(ops[k]);
   5554             if (fd < 0) { perr("%s", ops[k]); bad = 1; continue; }
   5555             if (read_all(fd, &d, &l) < 0) { perr("%s", ops[k]); bad = 1; continue; }
   5556             if (fd) close(fd);
   5557             if (got + l > cap) { cap = got + l; all = xrealloc(all, cap + 1); }
   5558             memcpy(all + got, d, l); got += l; free(d);
   5559         }
   5560         data = (unsigned char *)all; len = got;
   5561     }
   5562     if (skip) { if (skip > len) skip = len; data += skip; len -= skip; }
   5563     if (limit < len) len = limit;
   5564     aw = radix == 'd' ? 7 : radix == 'x' ? 6 : 7;
   5565     {
   5566         int maxs = 1;
   5567         for (i = 0; i < nf; i++) if (fm[i].size > maxs) maxs = fm[i].size;
   5568         if (width % maxs) width = (width / maxs + 1) * maxs;
   5569     }
   5570     for (pos = 0; pos < len; pos += width) {
   5571         size_t n = len - pos < width ? len - pos : width;
   5572         int first = 1;
   5573         if (!dups && prev && n == width && !memcmp(prev, data + pos, width)) {
   5574             if (!starred) { puts("*"); starred = 1; }
   5575             continue;
   5576         }
   5577         starred = 0;
   5578         prev = data + pos;
   5579         for (i = 0; i < nf; i++) {
   5580             size_t k;
   5581             if (first && radix != 'n') {
   5582                 if (radix == 'd') printf("%0*lu", aw, (unsigned long)(pos + skip));
   5583                 else if (radix == 'x') printf("%0*lx", aw, (unsigned long)(pos + skip));
   5584                 else printf("%0*lo", aw, (unsigned long)(pos + skip));
   5585             } else if (radix != 'n') printf("%*s", aw, "");
   5586             first = 0;
   5587             for (k = 0; k < n; k += fm[i].size) od_field(&fm[i], data + pos + k, n - k);
   5588             putchar('\n');
   5589         }
   5590     }
   5591     if (radix != 'n') {
   5592         unsigned long end = len + skip;
   5593         if (radix == 'd') printf("%0*lu\n", aw, end); else if (radix == 'x') printf("%0*lx\n", aw, end); else printf("%0*lo\n", aw, end);
   5594     }
   5595     return finish_stdout() ? 1 : bad;
   5596 }
   5597 /* ---- ls ---- */
   5598 
   5599 struct ent { char *name, *path, *link; struct stat st; int ok, linkok; struct stat lst; };
   5600 
   5601 static struct {
   5602     int all, almost, list, one, cols, across, comma, classify, slash, dir, inode, blocks, human, si, sortsz, sortt, sortu, sortc, rev, rec;
   5603     int deref, derefcmd, numeric, noown, nogrp, unsorted, ver, ext, quote, escape, dirfirst, kib, full, nolist;
   5604     int timestyle_iso, timestyle_long;
   5605     unsigned width;
   5606     const char *ignore[16]; int nignore;
   5607     const char *hide[16]; int nhide;
   5608 } L;
   5609 
   5610 static int ls_cmp(const void *a, const void *b)
   5611 {
   5612     const struct ent *x = a, *y = b;
   5613     int r = 0;
   5614     if (L.dirfirst) {
   5615         int dx = x->ok && S_ISDIR(x->st.st_mode), dy = y->ok && S_ISDIR(y->st.st_mode);
   5616         if (dx != dy) return dx ? -1 : 1;
   5617     }
   5618     if (L.sortsz) r = y->st.st_size < x->st.st_size ? -1 : y->st.st_size > x->st.st_size;
   5619     else if (L.sortt || L.sortu || L.sortc) {
   5620         long sx, nx, sy, ny;
   5621         if (L.sortu) { sx = x->st.st_atime; nx = x->st.st_atime_nsec; sy = y->st.st_atime; ny = y->st.st_atime_nsec; }
   5622         else if (L.sortc) { sx = x->st.st_ctime; nx = x->st.st_ctime_nsec; sy = y->st.st_ctime; ny = y->st.st_ctime_nsec; }
   5623         else { sx = x->st.st_mtime; nx = x->st.st_mtime_nsec; sy = y->st.st_mtime; ny = y->st.st_mtime_nsec; }
   5624         r = sy < sx ? -1 : sy > sx ? 1 : ny < nx ? -1 : ny > nx;
   5625     } else if (L.ver) r = vercmp(x->name, strlen(x->name), y->name, strlen(y->name));
   5626     else if (L.ext) {
   5627         const char *ex = strrchr(x->name, '.'), *ey = strrchr(y->name, '.');
   5628         r = strcmp(ex ? ex : "", ey ? ey : "");
   5629     }
   5630     if (!r) r = strcmp(x->name, y->name);
   5631     return L.rev ? -r : r;
   5632 }
   5633 
   5634 static const char *ls_human(unsigned long long n, char *buf)
   5635 {
   5636     static const char suf[] = " KMGTPE", sufsi[] = " kMGTPE";
   5637     unsigned long long base = L.si ? 1000 : 1024, v = n;
   5638     int i = 0;
   5639     if (n < base) { sprintf(buf, "%llu", n); return buf; }
   5640     while (v >= base && i < 6) { v /= base; i++; if (v < base) break; }
   5641     {
   5642         double d = (double)n;
   5643         int k;
   5644         for (k = 0; k < i; k++) d /= base;
   5645         if (d < 10) { unsigned t = (unsigned)(d * 10 + 0.9999999); sprintf(buf, "%u.%u%c", t / 10, t % 10, (L.si ? sufsi : suf)[i]); if (t >= 100) sprintf(buf, "%u%c", t / 10, (L.si ? sufsi : suf)[i]); }
   5646         else sprintf(buf, "%llu%c", (unsigned long long)(d + 0.9999999), (L.si ? sufsi : suf)[i]);
   5647     }
   5648     return buf;
   5649 }
   5650 
   5651 static char ls_type(mode_t m)
   5652 {
   5653     if (S_ISDIR(m)) return 'd'; if (S_ISLNK(m)) return 'l'; if (S_ISCHR(m)) return 'c'; if (S_ISBLK(m)) return 'b';
   5654     if (S_ISFIFO(m)) return 'p'; if (S_ISSOCK(m)) return 's';
   5655     return '-';
   5656 }
   5657 
   5658 static char ls_mark(const struct ent *e)
   5659 {
   5660     mode_t m = e->st.st_mode;
   5661     if (S_ISDIR(m)) return L.classify || L.slash ? '/' : 0;
   5662     if (!L.classify) return 0;
   5663     if (S_ISLNK(m)) return '@'; if (S_ISFIFO(m)) return '|'; if (S_ISSOCK(m)) return '='; if (m & 0111) return '*';
   5664     return 0;
   5665 }
   5666 
   5667 static void ls_putname(const char *n)
   5668 {
   5669     const char *p;
   5670     if (L.quote) {
   5671         putchar('"');
   5672         for (p = n; *p; p++) { if (*p == '"' || *p == '\\') putchar('\\'); putchar(*p); }
   5673         putchar('"');
   5674     } else if (L.escape) {
   5675         for (p = n; *p; p++) {
   5676             unsigned char c = *p;
   5677             if (c == ' ') fputs("\\ ", stdout); else if (c == '\\') fputs("\\\\", stdout); else if (c == '\n') fputs("\\n", stdout);
   5678             else if (c == '\t') fputs("\\t", stdout); else if (c < 32 || c == 127) printf("\\%03o", c); else putchar(c);
   5679         }
   5680     } else fputs(n, stdout);
   5681 }
   5682 
   5683 static size_t ls_namelen(const struct ent *e)
   5684 {
   5685     size_t n = strlen(e->name);
   5686     if (L.quote) n += 2;
   5687     if (ls_mark(e)) n++;
   5688     return n;
   5689 }
   5690 
   5691 static void ls_time(const struct stat *st, char *out)
   5692 {
   5693     time_t t = L.sortu ? st->st_atime : L.sortc ? st->st_ctime : st->st_mtime;
   5694     long ns = L.sortu ? st->st_atime_nsec : L.sortc ? st->st_ctime_nsec : st->st_mtime_nsec;
   5695     struct tm tm;
   5696     time_t now = time(NULL);
   5697     struct tm *g = gmtime(&t);
   5698     tm = *g;
   5699     if (L.full) strftime(out, 64, "%Y-%m-%d %H:%M:%S", &tm), sprintf(out + strlen(out), ".%09ld +0000", ns);
   5700     else if (L.timestyle_long) strftime(out, 64, "%Y-%m-%d %H:%M", &tm);
   5701     else if (L.timestyle_iso) strftime(out, 64, (t > now - 15778476 && t < now + 3600) ? "%m-%d %H:%M" : "%Y-%m-%d ", &tm);
   5702     else if (t > now - 15778476 && t < now + 3600) strftime(out, 64, "%b %e %H:%M", &tm);
   5703     else strftime(out, 64, "%b %e  %Y", &tm);
   5704 }
   5705 
   5706 static void ls_mode(mode_t m, char *s)
   5707 {
   5708     mode_string(m, s + 1);
   5709     s[0] = ls_type(m);
   5710 }
   5711 
   5712 static long long ls_blocks(const struct ent *e) { return e->st.st_blocks; }
   5713 
   5714 static void ls_show(struct ent *v, int n, int dirtotal)
   5715 {
   5716     int i;
   5717     if (L.list) {
   5718         size_t wl = 1, wu = 1, wg = 1, ws = 1, wi = 1, wb = 1;
   5719         char **us = xmalloc((n + 1) * sizeof *us), **gs = xmalloc((n + 1) * sizeof *gs), **sz = xmalloc((n + 1) * sizeof *sz);
   5720         long long total = 0;
   5721         char buf[64];
   5722         for (i = 0; i < n; i++) {
   5723             struct ent *e = &v[i];
   5724             size_t l;
   5725             us[i] = gs[i] = sz[i] = NULL;
   5726             if (!e->ok) continue;
   5727             total += ls_blocks(e);
   5728             l = snprintf(buf, sizeof buf, "%lu", (unsigned long)e->st.st_nlink); if (l > wl) wl = l;
   5729             us[i] = xstrdup(L.numeric ? (snprintf(buf, sizeof buf, "%u", e->st.st_uid), buf) : user_name(e->st.st_uid));
   5730             gs[i] = xstrdup(L.numeric ? (snprintf(buf, sizeof buf, "%u", e->st.st_gid), buf) : group_name(e->st.st_gid));
   5731             if (strlen(us[i]) > wu) wu = strlen(us[i]);
   5732             if (strlen(gs[i]) > wg) wg = strlen(gs[i]);
   5733             if (S_ISCHR(e->st.st_mode) || S_ISBLK(e->st.st_mode)) {
   5734                 unsigned long d = e->st.st_rdev;
   5735                 snprintf(buf, sizeof buf, "%lu, %lu", (d >> 8) & 0xfff, (d & 0xff) | ((d >> 12) & 0xfff00));
   5736             } else if (L.human) ls_human(e->st.st_size, buf);
   5737             else snprintf(buf, sizeof buf, "%lld", (long long)e->st.st_size);
   5738             sz[i] = xstrdup(buf);
   5739             if (strlen(buf) > ws) ws = strlen(buf);
   5740             l = snprintf(buf, sizeof buf, "%lu", (unsigned long)e->st.st_ino); if (l > wi) wi = l;
   5741             if (L.human) ls_human(ls_blocks(e) * 512, buf); else snprintf(buf, sizeof buf, "%lld", (ls_blocks(e) * 512 + (L.kib || 1 ? 1023 : 0)) / 1024);
   5742             l = strlen(buf); if (l > wb) wb = l;
   5743         }
   5744         if (dirtotal) {
   5745             if (L.human) { ls_human(total * 512, buf); printf("total %s\n", buf); }
   5746             else printf("total %lld\n", (total * 512 + 1023) / 1024);
   5747         }
   5748         for (i = 0; i < n; i++) {
   5749             struct ent *e = &v[i];
   5750             char mode[16], tm[64];
   5751             char mk;
   5752             if (!e->ok) { printf("? ?????????? ? ? ? ? ? %s\n", e->name); continue; }
   5753             if (L.inode) printf("%*lu ", (int)wi, (unsigned long)e->st.st_ino);
   5754             if (L.blocks) {
   5755                 if (L.human) ls_human(ls_blocks(e) * 512, buf); else snprintf(buf, sizeof buf, "%lld", (ls_blocks(e) * 512 + 1023) / 1024);
   5756                 printf("%*s ", (int)wb, buf);
   5757             }
   5758             ls_mode(e->st.st_mode, mode);
   5759             ls_time(&e->st, tm);
   5760             printf("%s %*lu", mode, (int)wl, (unsigned long)e->st.st_nlink);
   5761             if (!L.noown) printf(" %-*s", (int)wu, us[i]);
   5762             if (!L.nogrp) printf(" %-*s", (int)wg, gs[i]);
   5763             printf(" %*s %s ", (int)ws, sz[i], tm);
   5764             ls_putname(e->name);
   5765             mk = ls_mark(e);
   5766             if (mk && !S_ISLNK(e->st.st_mode)) putchar(mk);
   5767             if (S_ISLNK(e->st.st_mode) && e->link) { fputs(" -> ", stdout); fputs(e->link, stdout); if (L.classify && e->linkok) { struct ent t = *e; t.st = e->lst; if (ls_mark(&t)) putchar(ls_mark(&t)); } }
   5768             putchar('\n');
   5769             free(us[i]); free(gs[i]); free(sz[i]);
   5770         }
   5771         free(us); free(gs); free(sz);
   5772         return;
   5773     }
   5774     if (dirtotal && L.blocks) {
   5775         long long total = 0;
   5776         for (i = 0; i < n; i++) if (v[i].ok) total += ls_blocks(&v[i]);
   5777         printf("total %lld\n", (total * 512 + 1023) / 1024);
   5778     }
   5779     if (L.comma) {
   5780         size_t col = 0;
   5781         for (i = 0; i < n; i++) {
   5782             size_t l = ls_namelen(&v[i]) + 2;
   5783             if (i && col + l + 0 > L.width) { putchar('\n'); col = 0; }
   5784             if (i && col) putchar(' ');
   5785             ls_putname(v[i].name);
   5786             if (ls_mark(&v[i])) putchar(ls_mark(&v[i]));
   5787             col += l;
   5788             if (i + 1 < n) putchar(',');
   5789         }
   5790         if (n) putchar('\n');
   5791         return;
   5792     }
   5793     if (L.cols || L.across) {
   5794         size_t maxw = 0, ncols, nrows, r, c;
   5795         for (i = 0; i < n; i++) {
   5796             size_t l = ls_namelen(&v[i]) + (L.inode ? 8 : 0) + (L.blocks ? 5 : 0);
   5797             if (l > maxw) maxw = l;
   5798         }
   5799         ncols = L.width / (maxw + 2);
   5800         if (!ncols) ncols = 1;
   5801         {
   5802             size_t best = 1;
   5803             size_t cand;
   5804             for (cand = ncols < (size_t)n ? ncols : (size_t)n; cand >= 1; cand--) {
   5805                 size_t rows = (n + cand - 1) / cand, tot = 0, k, j;
   5806                 size_t *w = xmalloc(cand * sizeof *w);
   5807                 for (j = 0; j < cand; j++) w[j] = 0;
   5808                 for (k = 0; k < (size_t)n; k++) {
   5809                     size_t cc = L.across ? k % cand : k / rows;
   5810                     size_t l = ls_namelen(&v[k]) + (L.inode ? 8 : 0) + (L.blocks ? 5 : 0);
   5811                     if (l > w[cc]) w[cc] = l;
   5812                 }
   5813                 for (j = 0; j < cand; j++) tot += w[j] + (j + 1 < cand ? 2 : 0);
   5814                 free(w);
   5815                 if (tot <= L.width || cand == 1) { best = cand; break; }
   5816             }
   5817             ncols = best;
   5818         }
   5819         nrows = (n + ncols - 1) / ncols;
   5820         {
   5821             size_t *w = xmalloc(ncols * sizeof *w);
   5822             for (c = 0; c < ncols; c++) w[c] = 0;
   5823             for (i = 0; i < n; i++) {
   5824                 size_t cc = L.across ? (size_t)i % ncols : (size_t)i / nrows, l = ls_namelen(&v[i]) + (L.inode ? 8 : 0) + (L.blocks ? 5 : 0);
   5825                 if (l > w[cc]) w[cc] = l;
   5826             }
   5827             for (r = 0; r < nrows; r++) {
   5828                 for (c = 0; c < ncols; c++) {
   5829                     size_t idx = L.across ? r * ncols + c : c * nrows + r, used;
   5830                     char mk;
   5831                     if (idx >= (size_t)n) break;
   5832                     if (L.inode) printf("%7lu ", (unsigned long)v[idx].st.st_ino);
   5833                     if (L.blocks) printf("%4lld ", (ls_blocks(&v[idx]) * 512 + 1023) / 1024);
   5834                     ls_putname(v[idx].name);
   5835                     mk = ls_mark(&v[idx]);
   5836                     if (mk) putchar(mk);
   5837                     used = ls_namelen(&v[idx]) + (L.inode ? 8 : 0) + (L.blocks ? 5 : 0);
   5838                     if (c + 1 < ncols && (L.across ? idx + 1 : idx + nrows) < (size_t)n) printf("%*s", (int)(w[c] - used + 2), "");
   5839                 }
   5840                 putchar('\n');
   5841             }
   5842             free(w);
   5843         }
   5844         return;
   5845     }
   5846     for (i = 0; i < n; i++) {
   5847         char mk;
   5848         if (L.inode) printf("%lu ", (unsigned long)v[i].st.st_ino);
   5849         if (L.blocks) {
   5850             char buf[32];
   5851             if (L.human) ls_human(ls_blocks(&v[i]) * 512, buf); else snprintf(buf, sizeof buf, "%lld", (ls_blocks(&v[i]) * 512 + 1023) / 1024);
   5852             printf("%s ", buf);
   5853         }
   5854         ls_putname(v[i].name);
   5855         mk = ls_mark(&v[i]);
   5856         if (mk) putchar(mk);
   5857         putchar('\n');
   5858     }
   5859 }
   5860 
   5861 static int ls_ignored(const char *name)
   5862 {
   5863     int i;
   5864     for (i = 0; i < L.nignore; i++) if (glob_match(L.ignore[i], name)) return 1;
   5865     return 0;
   5866 }
   5867 
   5868 static void ls_stat(struct ent *e, int top)
   5869 {
   5870     int follow = L.deref || (top && L.derefcmd);
   5871     e->ok = (follow ? stat(e->path, &e->st) : lstat(e->path, &e->st)) == 0;
   5872     if (!e->ok && follow) e->ok = lstat(e->path, &e->st) == 0;
   5873     e->link = NULL; e->linkok = 0;
   5874     if (e->ok && S_ISLNK(e->st.st_mode)) {
   5875         char buf[PATH_MAX];
   5876         ssize_t n = readlink(e->path, buf, sizeof buf - 1);
   5877         if (n >= 0) { buf[n] = 0; e->link = xstrdup(buf); }
   5878         if (L.list && L.classify) e->linkok = stat(e->path, &e->lst) == 0;
   5879     }
   5880 }
   5881 
   5882 static int ls_dir(const char *path, int header, int *first);
   5883 
   5884 static int ls_dir(const char *path, int header, int *first)
   5885 {
   5886     DIR *d = opendir(path);
   5887     struct dirent *de;
   5888     struct ent *v = NULL;
   5889     int n = 0, cap = 0, i, bad = 0;
   5890     if (!d) { perr("cannot open directory '%s'", path); return 1; }
   5891     while ((de = readdir(d))) {
   5892         struct ent *e;
   5893         const char *nm = de->d_name;
   5894         if (!L.all && !L.almost && nm[0] == '.') continue;
   5895         if (L.almost && (!strcmp(nm, ".") || !strcmp(nm, ".."))) continue;
   5896         if (!L.all && ls_ignored(nm)) continue;
   5897         if (n == cap) { cap = cap ? cap * 2 : 64; v = xrealloc(v, cap * sizeof *v); }
   5898         e = &v[n++];
   5899         e->name = xstrdup(nm);
   5900         e->path = xmalloc(strlen(path) + strlen(nm) + 2);
   5901         sprintf(e->path, "%s%s%s", path, path[strlen(path) - 1] == '/' ? "" : "/", nm);
   5902         ls_stat(e, 0);
   5903         if (!e->ok) { perr("cannot access '%s'", e->path); bad = 1; }
   5904     }
   5905     closedir(d);
   5906     if (!L.unsorted) qsort(v, n, sizeof *v, ls_cmp);
   5907     if (header) { if (!*first) putchar('\n'); printf("%s:\n", path); }
   5908     *first = 0;
   5909     if (L.list || (L.blocks && 1)) ls_show(v, n, 1); else ls_show(v, n, 0);
   5910     if (L.rec)
   5911         for (i = 0; i < n; i++)
   5912             if (v[i].ok && S_ISDIR(v[i].st.st_mode) && !(S_ISLNK(v[i].st.st_mode)) && strcmp(v[i].name, ".") && strcmp(v[i].name, ".."))
   5913                 bad |= ls_dir(v[i].path, 1, first);
   5914     for (i = 0; i < n; i++) { free(v[i].name); free(v[i].path); free(v[i].link); }
   5915     free(v);
   5916     return bad;
   5917 }
   5918 
   5919 static int t_ls(int argc, char **argv)
   5920 {
   5921     static const struct opt lo[] = { { "all", 0, 'a' }, { "almost-all", 0, 'A' }, { "classify", 2, 'F' }, { "directory", 0, 'd' }, { "inode", 0, 'i' },
   5922         { "size", 0, 's' }, { "human-readable", 0, 'h' }, { "si", 0, 'H' + 256 }, { "reverse", 0, 'r' }, { "recursive", 0, 'R' }, { "dereference", 0, 'L' },
   5923         { "dereference-command-line", 0, 'H' }, { "numeric-uid-gid", 0, 'n' }, { "no-group", 0, 'G' }, { "color", 2, 'C' + 256 }, { "full-time", 0, 'T' + 256 },
   5924         { "group-directories-first", 0, 'g' + 256 }, { "sort", 1, 'o' + 256 }, { "time", 1, 't' + 256 }, { "ignore", 1, 'I' }, { "hide", 1, 'h' + 256 },
   5925         { "quote-name", 0, 'Q' }, { "escape", 0, 'b' }, { "hide-control-chars", 0, 'q' }, { "width", 1, 'w' }, { "format", 1, 'f' + 256 },
   5926         { "indicator-style", 1, 'i' + 256 }, { "time-style", 1, 'y' + 256 }, { "kibibytes", 0, 'k' }, { "file-type", 0, 'F' + 512 }, { NULL, 0, 0 } };
   5927     int c, i, first = 1, bad = 0, nfiles = 0, ndirs = 0, tty = isatty(1);
   5928     struct ent *files = NULL, *dirs = NULL;
   5929     memset(&L, 0, sizeof L);
   5930     L.width = 80;
   5931     {
   5932         const char *w = getenv("COLUMNS");
   5933         if (w && atoi(w) > 0) L.width = atoi(w);
   5934     }
   5935     L.one = !tty;
   5936     L.cols = tty;
   5937     opts_reset();
   5938     while ((c = getopts(argc, argv, "aAlCx1FpdisShrRLHnogGtuUcvXkmqQbfw:I:T:", lo)))
   5939         switch (c) {
   5940         case 'a': L.all = 1; break; case 'A': L.almost = 1; break;
   5941         case 'l': L.list = 1; L.cols = L.across = L.comma = 0; break;
   5942         case 'o': L.list = 1; L.nogrp = 1; L.cols = 0; break;
   5943         case 'g': L.list = 1; L.noown = 1; L.cols = 0; break;
   5944         case 'n': L.list = 1; L.numeric = 1; L.cols = 0; break;
   5945         case '1': L.one = 1; L.cols = L.across = L.comma = L.list = 0; break;
   5946         case 'C': L.cols = 1; L.across = L.comma = L.list = 0; break;
   5947         case 'x': L.across = 1; L.cols = 0; L.comma = 0; L.list = 0; break;
   5948         case 'm': L.comma = 1; L.cols = L.across = L.list = 0; break;
   5949         case 'F': L.classify = 1; break; case 'p': L.slash = 1; break; case 'd': L.dir = 1; break;
   5950         case 'i': L.inode = 1; break; case 's': L.blocks = 1; break; case 'S': L.sortsz = 1; break;
   5951         case 'h': L.human = 1; break; case 'H': L.derefcmd = 1; break; case 'H' + 256: L.human = L.si = 1; break;
   5952         case 'r': L.rev = 1; break; case 'R': L.rec = 1; break; case 'L': L.deref = 1; break;
   5953         case 'G': L.nogrp = 1; break; case 't': L.sortt = 1; break; case 'u': L.sortu = 1; break; case 'c': L.sortc = 1; break;
   5954         case 'U': L.unsorted = 1; break; case 'v': L.ver = 1; break; case 'X': L.ext = 1; break;
   5955         case 'k': L.kib = 1; break; case 'q': break; case 'Q': L.quote = 1; break; case 'b': L.escape = 1; break;
   5956         case 'f': L.all = 1; L.unsorted = 1; L.list = 0; break;
   5957         case 'w': L.width = strtoul(optarg, NULL, 10); break;
   5958         case 'I': if (L.nignore < 16) L.ignore[L.nignore++] = optarg; break;
   5959         case 'C' + 256: break;
   5960         case 'T' + 256: L.full = 1; L.list = 1; L.cols = 0; break;
   5961         case 'g' + 256: L.dirfirst = 1; break;
   5962         case 'h' + 256: if (L.nignore < 16) L.ignore[L.nignore++] = optarg; break;
   5963         case 'o' + 256:
   5964             if (!strcmp(optarg, "size")) L.sortsz = 1; else if (!strcmp(optarg, "time")) L.sortt = 1; else if (!strcmp(optarg, "none")) L.unsorted = 1;
   5965             else if (!strcmp(optarg, "version")) L.ver = 1; else if (!strcmp(optarg, "extension")) L.ext = 1; else if (strcmp(optarg, "name")) die(2, "invalid argument '%s' for '--sort'", optarg);
   5966             break;
   5967         case 't' + 256: if (!strcmp(optarg, "atime") || !strcmp(optarg, "access")) L.sortu = 1; else if (!strcmp(optarg, "ctime") || !strcmp(optarg, "status")) L.sortc = 1; break;
   5968         case 'y' + 256: L.timestyle_iso = !strcmp(optarg, "iso"); L.timestyle_long = !strcmp(optarg, "long-iso"); if (!strcmp(optarg, "full-iso")) L.full = 1; break;
   5969         case 'f' + 256:
   5970             if (!strcmp(optarg, "long") || !strcmp(optarg, "verbose")) { L.list = 1; L.cols = 0; }
   5971             else if (!strcmp(optarg, "commas")) { L.comma = 1; L.cols = 0; } else if (!strcmp(optarg, "across") || !strcmp(optarg, "horizontal")) { L.across = 1; L.cols = 0; }
   5972             else if (!strcmp(optarg, "single-column")) { L.one = 1; L.cols = 0; } else if (!strcmp(optarg, "vertical")) L.cols = 1;
   5973             break;
   5974         case 'i' + 256: if (!strcmp(optarg, "slash")) L.slash = 1; else if (!strcmp(optarg, "classify")) L.classify = 1; break;
   5975         case 'F' + 512: L.classify = 1; break;
   5976         default: break;
   5977         }
   5978     if (L.list) L.one = 0;
   5979     if (!nops) ops[nops++] = ".";
   5980     for (i = 0; i < nops; i++) {
   5981         struct ent e;
   5982         e.name = ops[i]; e.path = ops[i];
   5983         ls_stat(&e, 1);
   5984         if (!e.ok) { perr("cannot access '%s'", ops[i]); bad = 2; continue; }
   5985         if (S_ISDIR(e.st.st_mode) && !L.dir) { dirs = xrealloc(dirs, (ndirs + 1) * sizeof *dirs); dirs[ndirs++] = e; }
   5986         else { files = xrealloc(files, (nfiles + 1) * sizeof *files); files[nfiles++] = e; }
   5987     }
   5988     if (!L.unsorted) { qsort(files, nfiles, sizeof *files, ls_cmp); qsort(dirs, ndirs, sizeof *dirs, ls_cmp); }
   5989     if (nfiles) { ls_show(files, nfiles, 0); first = 0; }
   5990     for (i = 0; i < ndirs; i++) {
   5991         int r = ls_dir(dirs[i].path, nops > 1 || L.rec, &first);
   5992         if (r && !bad) bad = 1;
   5993         if (r && bad < 2) bad = r;
   5994     }
   5995     return finish_stdout() ? 2 : bad;
   5996 }
   5997 
   5998 /* ---- stat ---- */
   5999 
   6000 static const char *st_kind(mode_t m)
   6001 {
   6002     if (S_ISREG(m)) return "regular file"; if (S_ISDIR(m)) return "directory"; if (S_ISLNK(m)) return "symbolic link";
   6003     if (S_ISCHR(m)) return "character special file"; if (S_ISBLK(m)) return "block special file"; if (S_ISFIFO(m)) return "fifo";
   6004     if (S_ISSOCK(m)) return "socket";
   6005     return "weird file";
   6006 }
   6007 
   6008 static void st_time(char *out, time_t t, long ns)
   6009 {
   6010     struct tm *g = gmtime(&t);
   6011     strftime(out, 48, "%Y-%m-%d %H:%M:%S", g);
   6012     sprintf(out + strlen(out), ".%09ld +0000", ns);
   6013 }
   6014 
   6015 static void st_perm(mode_t m, char *s) { mode_string(m, s + 1); s[0] = ls_type(m); }
   6016 
   6017 static void st_quote(const char *s)
   6018 {
   6019     const char *p;
   6020     for (p = s; *p; p++) if (!isalnum((unsigned char)*p) && !strchr("_-./:,%+=@~^", *p)) break;
   6021     if (!*p && *s) { fputs(s, stdout); return; }
   6022     putchar('\'');
   6023     for (p = s; *p; p++) { if (*p == '\'') fputs("'\\''", stdout); else putchar(*p); }
   6024     putchar('\'');
   6025 }
   6026 
   6027 static void st_format(const char *fmt, const char *name, const struct stat *st, int deref, int esc)
   6028 {
   6029     const char *p;
   6030     char b[64];
   6031     for (p = fmt; *p; p++) {
   6032         char flag = 0;
   6033         int width = 0;
   6034         if (esc && *p == '\\') {
   6035             char eb[8];
   6036             size_t en;
   6037             int stop = 0;
   6038             p = pf_esc(p + 1, 0, eb, &en, &stop) - 1;
   6039             fwrite(eb, 1, en, stdout);
   6040             continue;
   6041         }
   6042         if (*p != '%') { putchar(*p); continue; }
   6043         p++;
   6044         if (*p == '-' || *p == '0' || *p == '+' || *p == ' ' || *p == '#') flag = *p++;
   6045         while (isdigit((unsigned char)*p)) width = width * 10 + *p++ - '0';
   6046         switch (*p) {
   6047         case '%': putchar('%'); break;
   6048         case 'a': snprintf(b, sizeof b, "%o", st->st_mode & 07777); break;
   6049         case 'A': st_perm(st->st_mode, b); break;
   6050         case 'b': snprintf(b, sizeof b, "%lld", (long long)st->st_blocks); break;
   6051         case 'B': strcpy(b, "512"); break;
   6052         case 'd': snprintf(b, sizeof b, "%lu", (unsigned long)st->st_dev); break;
   6053         case 'D': snprintf(b, sizeof b, "%lx", (unsigned long)st->st_dev); break;
   6054         case 'f': snprintf(b, sizeof b, "%x", st->st_mode); break;
   6055         case 'F': snprintf(b, sizeof b, "%s", st_kind(st->st_mode)); break;
   6056         case 'g': snprintf(b, sizeof b, "%u", st->st_gid); break;
   6057         case 'G': snprintf(b, sizeof b, "%s", group_name(st->st_gid)); break;
   6058         case 'h': snprintf(b, sizeof b, "%lu", (unsigned long)st->st_nlink); break;
   6059         case 'i': snprintf(b, sizeof b, "%lu", (unsigned long)st->st_ino); break;
   6060         case 'm': strcpy(b, "/"); break;
   6061         case 'n': snprintf(b, sizeof b, "%s", name); break;
   6062         case 'N': {
   6063             if (S_ISLNK(st->st_mode) && !deref) {
   6064                 char t[PATH_MAX];
   6065                 ssize_t n = readlink(name, t, sizeof t - 1);
   6066                 if (n >= 0) { t[n] = 0; st_quote(name); fputs(" -> ", stdout); st_quote(t); b[0] = 0; width = 0; break; }
   6067             }
   6068             st_quote(name); b[0] = 0; width = 0;
   6069             break;
   6070         }
   6071         case 'o': strcpy(b, "4096"); break;
   6072         case 's': snprintf(b, sizeof b, "%lld", (long long)st->st_size); break;
   6073         case 't': snprintf(b, sizeof b, "%lx", (unsigned long)((st->st_rdev >> 8) & 0xfff)); break;
   6074         case 'T': snprintf(b, sizeof b, "%lx", (unsigned long)((st->st_rdev & 0xff) | ((st->st_rdev >> 12) & 0xfff00))); break;
   6075         case 'u': snprintf(b, sizeof b, "%u", st->st_uid); break;
   6076         case 'U': snprintf(b, sizeof b, "%s", user_name(st->st_uid)); break;
   6077         case 'w': strcpy(b, "-"); break;
   6078         case 'W': strcpy(b, "0"); break;
   6079         case 'x': st_time(b, st->st_atime, st->st_atime_nsec); break;
   6080         case 'y': st_time(b, st->st_mtime, st->st_mtime_nsec); break;
   6081         case 'z': st_time(b, st->st_ctime, st->st_ctime_nsec); break;
   6082         case 'X': snprintf(b, sizeof b, "%ld", (long)st->st_atime); break;
   6083         case 'Y': snprintf(b, sizeof b, "%ld", (long)st->st_mtime); break;
   6084         case 'Z': snprintf(b, sizeof b, "%ld", (long)st->st_ctime); break;
   6085         default: putchar('?'); b[0] = 0; width = 0; break;
   6086         }
   6087         if (b[0] || width) {
   6088             if (flag == '-') printf("%-*s", width, b);
   6089             else if (flag == '0' && strchr("abdDfghiosTtuWXYZ", *p)) printf("%0*s", width, b);
   6090             else printf("%*s", width, b);
   6091         }
   6092         b[0] = 0;
   6093     }
   6094 }
   6095 
   6096 static int t_stat(int argc, char **argv)
   6097 {
   6098     static const struct opt lo[] = { { "dereference", 0, 'L' }, { "format", 1, 'c' }, { "printf", 1, 'p' }, { "terse", 0, 't' }, { "file-system", 0, 'f' }, { NULL, 0, 0 } };
   6099     int c, deref = 0, terse = 0, fsys = 0, i, bad = 0, nl = 1, esc = 0;
   6100     const char *fmt = NULL;
   6101     opts_reset();
   6102     while ((c = getopts(argc, argv, "Lc:tf", lo)))
   6103         switch (c) {
   6104         case 'L': deref = 1; break; case 'c': fmt = optarg; break; case 'p': fmt = optarg; nl = 0; esc = 1; break;
   6105         case 't': terse = 1; break; case 'f': fsys = 1; break; default: break;
   6106         }
   6107     if (!nops) missing_operand();
   6108     for (i = 0; i < nops; i++) {
   6109         struct stat st;
   6110         if ((deref ? stat(ops[i], &st) : lstat(ops[i], &st)) < 0) { perr("cannot statx '%s'", ops[i]); bad = 1; continue; }
   6111         if (fsys) {
   6112             struct statfs f;
   6113             if (statfs(ops[i], &f) < 0) { perr("cannot read file system information for '%s'", ops[i]); bad = 1; continue; }
   6114             printf("  File: \"%s\"\n    ID: %lx Namelen: %ld     Type: ext2/ext3\nBlock size: %ld      Fundamental block size: %ld\nBlocks: Total: %lu   Free: %lu   Available: %lu\nInodes: Total: %lu   Free: %lu\n",
   6115                    ops[i], 0UL, (long)f.f_namelen, (long)f.f_bsize, (long)f.f_bsize, (unsigned long)f.f_blocks, (unsigned long)f.f_bfree, (unsigned long)f.f_bavail,
   6116                    (unsigned long)f.f_files, (unsigned long)f.f_ffree);
   6117             continue;
   6118         }
   6119         if (fmt) { st_format(fmt, ops[i], &st, deref, esc); if (nl) putchar('\n'); continue; }
   6120         if (terse) {
   6121             printf("%s %lld %lld %x %u %u %lx %lu %lu %lx %lx %ld %ld %ld %d 4096\n", ops[i], (long long)st.st_size, (long long)st.st_blocks, st.st_mode, st.st_uid, st.st_gid,
   6122                    (unsigned long)st.st_dev, (unsigned long)st.st_ino, (unsigned long)st.st_nlink, (unsigned long)((st.st_rdev >> 8) & 0xfff),
   6123                    (unsigned long)((st.st_rdev & 0xff) | ((st.st_rdev >> 12) & 0xfff00)), (long)st.st_atime, (long)st.st_mtime, (long)st.st_ctime, 0);
   6124             continue;
   6125         }
   6126         {
   6127             char perm[16], a[48], m[48], ch[48];
   6128             st_perm(st.st_mode, perm);
   6129             st_time(a, st.st_atime, st.st_atime_nsec); st_time(m, st.st_mtime, st.st_mtime_nsec); st_time(ch, st.st_ctime, st.st_ctime_nsec);
   6130             printf("  File: ");
   6131             st_format("%N", ops[i], &st, deref, 0);
   6132             printf("\n  Size: %-10lld\tBlocks: %-10lld IO Block: %-6d %s\n", (long long)st.st_size, (long long)st.st_blocks, 4096, st_kind(st.st_mode));
   6133             printf("Device: %lu,%lu\tInode: %-10lu  Links: %lu", (unsigned long)(st.st_dev >> 8), (unsigned long)(st.st_dev & 255), (unsigned long)st.st_ino, (unsigned long)st.st_nlink);
   6134             if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) printf("     Device type: %lx,%lx", (unsigned long)((st.st_rdev >> 8) & 0xfff), (unsigned long)(st.st_rdev & 0xff));
   6135             printf("\nAccess: (%04o/%s)  Uid: (%5u/%8s)   Gid: (%5u/%8s)\n", st.st_mode & 07777, perm, st.st_uid, user_name(st.st_uid), st.st_gid, group_name(st.st_gid));
   6136             printf("Access: %s\nModify: %s\nChange: %s\n Birth: -\n", a, m, ch);
   6137         }
   6138     }
   6139     return finish_stdout() ? 1 : bad;
   6140 }
   6141 
   6142 /* ---- du ---- */
   6143 
   6144 struct du { int all, human, si, sum, total, apparent, xdev, deref, zero, null; long depth; unsigned long long blk; dev_t dev; };
   6145 struct seen { dev_t d; ino_t i; };
   6146 static struct seen *du_seen;
   6147 static size_t du_nseen, du_cap;
   6148 
   6149 static int du_hard(const struct stat *st)
   6150 {
   6151     size_t i;
   6152     if (st->st_nlink < 2) return 0;
   6153     for (i = 0; i < du_nseen; i++) if (du_seen[i].d == st->st_dev && du_seen[i].i == st->st_ino) return 1;
   6154     if (du_nseen == du_cap) { du_cap = du_cap ? du_cap * 2 : 256; du_seen = xrealloc(du_seen, du_cap * sizeof *du_seen); }
   6155     du_seen[du_nseen].d = st->st_dev; du_seen[du_nseen].i = st->st_ino; du_nseen++;
   6156     return 0;
   6157 }
   6158 
   6159 static void du_print(const struct du *o, unsigned long long bytes, const char *name)
   6160 {
   6161     char buf[32];
   6162     if (o->human) { L.si = o->si; ls_human(bytes, buf); }
   6163     else sprintf(buf, "%llu", o->blk == 1 ? bytes : (bytes + o->blk - 1) / o->blk);
   6164     printf("%s\t%s%c", buf, name, o->null ? 0 : '\n');
   6165 }
   6166 
   6167 static int du_walk(const struct du *o, const char *path, int level, int top, unsigned long long *out, int *bad)
   6168 {
   6169     struct stat st;
   6170     unsigned long long mine, sub = 0;
   6171     if ((o->deref ? stat(path, &st) : lstat(path, &st)) < 0) { perr("cannot access '%s'", path); *bad = 1; return 0; }
   6172     if (o->xdev && !top && st.st_dev != o->dev) return 0;
   6173     if (du_hard(&st)) return 0;
   6174     mine = o->apparent ? (S_ISDIR(st.st_mode) ? 0 : (unsigned long long)st.st_size) : (unsigned long long)st.st_blocks * 512;
   6175     if (S_ISDIR(st.st_mode)) {
   6176         DIR *d = opendir(path);
   6177         struct dirent *e;
   6178         if (!d) { perr("cannot read directory '%s'", path); *bad = 1; }
   6179         else {
   6180             char **names = NULL;
   6181             int n = 0, cap = 0, i;
   6182             while ((e = readdir(d))) {
   6183                 if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
   6184                 if (n == cap) { cap = cap ? cap * 2 : 32; names = xrealloc(names, cap * sizeof *names); }
   6185                 names[n++] = xstrdup(e->d_name);
   6186             }
   6187             closedir(d);
   6188             for (i = 0; i < n; i++) {
   6189                 char *child = xmalloc(strlen(path) + strlen(names[i]) + 2);
   6190                 unsigned long long got = 0;
   6191                 sprintf(child, "%s%s%s", path, path[strlen(path) - 1] == '/' ? "" : "/", names[i]);
   6192                 du_walk(o, child, level + 1, 0, &got, bad);
   6193                 sub += got;
   6194                 free(child); free(names[i]);
   6195             }
   6196             free(names);
   6197         }
   6198     }
   6199     *out = mine + sub;
   6200     if ((S_ISDIR(st.st_mode) ? 1 : o->all || top) && !o->sum && (o->depth < 0 || level <= o->depth)) du_print(o, *out, path);
   6201     else if (o->sum && top) du_print(o, *out, path);
   6202     return 0;
   6203 }
   6204 
   6205 static int t_du(int argc, char **argv)
   6206 {
   6207     static const struct opt lo[] = { { "all", 0, 'a' }, { "human-readable", 0, 'h' }, { "si", 0, 'H' }, { "summarize", 0, 's' }, { "total", 0, 'c' },
   6208         { "apparent-size", 0, 'A' }, { "bytes", 0, 'b' }, { "max-depth", 1, 'd' }, { "one-file-system", 0, 'x' }, { "dereference", 0, 'L' },
   6209         { "block-size", 1, 'B' }, { "null", 0, '0' }, { "separate-dirs", 0, 'S' }, { NULL, 0, 0 } };
   6210     struct du o;
   6211     int c, i, bad = 0;
   6212     unsigned long long grand = 0;
   6213     memset(&o, 0, sizeof o);
   6214     o.depth = -1; o.blk = 1024;
   6215     opts_reset();
   6216     while ((c = getopts(argc, argv, "ahsckmbd:xLPB:0SH", lo)))
   6217         switch (c) {
   6218         case 'a': o.all = 1; break; case 'h': o.human = 1; break; case 'H': o.human = o.si = 1; break; case 's': o.sum = 1; break;
   6219         case 'c': o.total = 1; break; case 'A': o.apparent = 1; break; case 'b': o.apparent = 1; o.blk = 1; break;
   6220         case 'k': o.blk = 1024; break; case 'm': o.blk = 1 << 20; break; case 'x': o.xdev = 1; break; case 'L': o.deref = 1; break;
   6221         case '0': o.null = 1; break;
   6222         case 'd': o.depth = atol(optarg); break;
   6223         case 'B': { unsigned long long v; if (parse_size(optarg, &v) < 0) die(1, "invalid -B argument '%s'", optarg); o.blk = v; break; }
   6224         default: break;
   6225         }
   6226     if (!nops) ops[nops++] = ".";
   6227     for (i = 0; i < nops; i++) {
   6228         struct stat st;
   6229         unsigned long long got = 0;
   6230         if (o.xdev && stat(ops[i], &st) == 0) o.dev = st.st_dev;
   6231         du_walk(&o, ops[i], 0, 1, &got, &bad);
   6232         grand += got;
   6233     }
   6234     if (o.total) du_print(&o, grand, "total");
   6235     return finish_stdout() ? 1 : bad;
   6236 }
   6237 
   6238 /* ---- df ---- */
   6239 
   6240 static int t_df(int argc, char **argv)
   6241 {
   6242     static const struct opt lo[] = { { "human-readable", 0, 'h' }, { "si", 0, 'H' }, { "print-type", 0, 'T' }, { "all", 0, 'a' }, { "portability", 0, 'P' },
   6243         { "block-size", 1, 'B' }, { "local", 0, 'l' }, { "inodes", 0, 'i' }, { "total", 0, 't' + 256 }, { NULL, 0, 0 } };
   6244     int c, human = 0, kind = 0, all = 0, inodes = 0, bad = 0, any = 0, i;
   6245     unsigned long long blk = 1024;
   6246     FILE *f;
   6247     char *line = NULL;
   6248     size_t cap = 0;
   6249     char **dev = NULL, **mnt = NULL, **typ = NULL;
   6250     int n = 0, m = 0;
   6251     opts_reset();
   6252     while ((c = getopts(argc, argv, "hHTaPkB:lit", lo)))
   6253         switch (c) {
   6254         case 'h': human = 1; break; case 'H': human = 2; break; case 'T': kind = 1; break; case 'a': all = 1; break; case 'P': break;
   6255         case 'k': blk = 1024; break; case 'l': break; case 'i': inodes = 1; break;
   6256         case 'B': { unsigned long long v; if (parse_size(optarg, &v) < 0) die(1, "invalid --block-size argument '%s'", optarg); blk = v; break; }
   6257         default: break;
   6258         }
   6259     f = fopen("/proc/self/mounts", "r");
   6260     if (!f) { perr("cannot read table of mounted file systems"); return 1; }
   6261     while (getline(&line, &cap, f) > 0) {
   6262         char d[256], mp[256], t[64];
   6263         {
   6264             char *a = line, *b, *e;
   6265             b = strchr(a, ' '); if (!b) continue; *b++ = 0;
   6266             e = strchr(b, ' '); if (!e) continue; *e++ = 0;
   6267             strncpy(d, a, 255); d[255] = 0; strncpy(mp, b, 255); mp[255] = 0;
   6268             a = e; b = strchr(a, ' '); if (b) *b = 0;
   6269             strncpy(t, a, 63); t[63] = 0;
   6270         }
   6271         if (m == n) { m = m ? m * 2 : 32; dev = xrealloc(dev, m * sizeof *dev); mnt = xrealloc(mnt, m * sizeof *mnt); typ = xrealloc(typ, m * sizeof *typ); }
   6272         {
   6273             char *o = mp, *w = mp;
   6274             while (*o) { if (o[0] == '\\' && isdigit((unsigned char)o[1]) && isdigit((unsigned char)o[2]) && isdigit((unsigned char)o[3])) { *w++ = ((o[1] - '0') << 6) | ((o[2] - '0') << 3) | (o[3] - '0'); o += 4; } else *w++ = *o++; }
   6275             *w = 0;
   6276         }
   6277         dev[n] = xstrdup(d); mnt[n] = xstrdup(mp); typ[n] = xstrdup(t); n++;
   6278     }
   6279     fclose(f);
   6280     {
   6281         int j, count = nops ? nops : n;
   6282         for (j = 0; j < count; j++) {
   6283             int idx = -1;
   6284             struct statfs s;
   6285             struct stat st;
   6286             char sz[3][32], pct[8];
   6287             if (nops) {
   6288                 struct stat ms;
   6289                 if (stat(ops[j], &st) < 0) { perr("%s", ops[j]); bad = 1; continue; }
   6290                 for (i = 0; i < n; i++) if (stat(mnt[i], &ms) == 0 && ms.st_dev == st.st_dev) idx = i;
   6291                 if (idx < 0) { say("%s: can't find mount point", ops[j]); bad = 1; continue; }
   6292             } else idx = j;
   6293             if (statfs(mnt[idx], &s) < 0) continue;
   6294             if (!nops && !all && (s.f_blocks == 0 || !strcmp(typ[idx], "autofs"))) continue;
   6295             if (!nops && !all) {
   6296                 int dup = 0, k;
   6297                 for (k = 0; k < idx; k++) if (!strcmp(dev[k], dev[idx]) && dev[idx][0] == '/') dup = 1;
   6298                 if (dup) continue;
   6299             }
   6300             if (!any) {
   6301                 if (inodes) printf("%-14s%s %9s %9s %9s %4s %s\n", "Filesystem", kind ? "Type          " : "", "Inodes", "IUsed", "IFree", "IUse%", "Mounted on");
   6302                 else if (human) printf("%-14s%s %5s %5s %5s %4s %s\n", "Filesystem", kind ? "Type          " : "", "Size", "Used", "Avail", "Use%", "Mounted on");
   6303                 else printf("%-14s%s %9s %9s %9s %4s %s\n", "Filesystem", kind ? "Type          " : "", blk == 1024 ? "1K-blocks" : "Blocks", "Used", "Available", "Use%", "Mounted on");
   6304             }
   6305             any = 1;
   6306             if (inodes) {
   6307                 unsigned long long tot = s.f_files, fr = s.f_ffree, us = tot - fr;
   6308                 sprintf(pct, tot ? "%llu%%" : "-", tot ? (us * 100 + tot - 1) / tot : 0);
   6309                 printf("%-14s%s%s %9llu %9llu %9llu %4s %s\n", dev[idx], kind ? " " : "", kind ? typ[idx] : "", tot, us, fr, pct, mnt[idx]);
   6310                 continue;
   6311             }
   6312             {
   6313                 unsigned long long bs = s.f_bsize, tot = s.f_blocks * bs, fr = s.f_bfree * bs, av = s.f_bavail * bs, us = tot - fr;
   6314                 unsigned long long usedp = us + av ? (us * 100 + (us + av) - 1) / (us + av) : 0;
   6315                 if (human) {
   6316                     L.si = human == 2;
   6317                     ls_human(tot, sz[0]); ls_human(us, sz[1]); ls_human(av, sz[2]);
   6318                 } else {
   6319                     sprintf(sz[0], "%llu", (tot + blk - 1) / blk); sprintf(sz[1], "%llu", (us + blk - 1) / blk); sprintf(sz[2], "%llu", av / blk);
   6320                 }
   6321                 if (tot) sprintf(pct, "%llu%%", usedp); else strcpy(pct, "-");
   6322                 if (kind) printf("%-14s %-13s", dev[idx], typ[idx]); else printf("%-14s", dev[idx]);
   6323                 if (human) printf(" %5s %5s %5s %4s %s\n", sz[0], sz[1], sz[2], pct, mnt[idx]);
   6324                 else printf(" %9s %9s %9s %4s %s\n", sz[0], sz[1], sz[2], pct, mnt[idx]);
   6325             }
   6326         }
   6327     }
   6328     return finish_stdout() ? 1 : bad;
   6329 }
   6330 
   6331 /* ---- date ---- */
   6332 
   6333 static int t_date(int argc, char **argv)
   6334 {
   6335     static const struct opt lo[] = { { "date", 1, 'd' }, { "utc", 0, 'u' }, { "universal", 0, 'u' }, { "reference", 1, 'r' }, { "iso-8601", 2, 'I' },
   6336         { "rfc-email", 0, 'R' }, { "rfc-2822", 0, 'R' }, { "set", 1, 's' }, { NULL, 0, 0 } };
   6337     int c;
   6338     const char *ds = NULL, *ref = NULL, *iso = NULL, *fmt = "%a %b %e %H:%M:%S %Z %Y";
   6339     int rfc = 0, haveiso = 0;
   6340     struct timespec ts;
   6341     struct tm tm;
   6342     char out[512], f2[512], *o;
   6343     const char *p;
   6344     opts_reset();
   6345     while ((c = getopts(argc, argv, "d:ur:I::Rs:", lo)))
   6346         switch (c) {
   6347         case 'd': ds = optarg; break; case 'r': ref = optarg; break; case 'u': break;
   6348         case 'I': haveiso = 1; iso = optarg; break; case 'R': rfc = 1; break;
   6349         case 's': die(1, "cannot set date: Operation not permitted"); break;
   6350         default: break;
   6351         }
   6352     if (nops > 1) extra_operand(ops[1]);
   6353     if (nops && ops[0][0] == '+') fmt = ops[0] + 1;
   6354     else if (nops) die(1, "invalid date '%s'", ops[0]);
   6355     if (ref) {
   6356         struct stat st;
   6357         if (stat(ref, &st) < 0) { perr("%s", ref); return 1; }
   6358         ts.tv_sec = st.st_mtime; ts.tv_nsec = st.st_mtime_nsec;
   6359     } else if (ds) {
   6360         if (parse_date(ds, &ts) < 0) die(1, "invalid date '%s'", ds);
   6361     } else clock_gettime(0, &ts);
   6362     if (rfc) fmt = "%a, %d %b %Y %H:%M:%S %z";
   6363     if (haveiso) {
   6364         if (!iso || !strcmp(iso, "date")) fmt = "%Y-%m-%d";
   6365         else if (!strcmp(iso, "hours")) fmt = "%Y-%m-%dT%H%z";
   6366         else if (!strcmp(iso, "minutes")) fmt = "%Y-%m-%dT%H:%M%z";
   6367         else if (!strcmp(iso, "seconds")) fmt = "%Y-%m-%dT%H:%M:%S%z";
   6368         else if (!strcmp(iso, "ns")) fmt = "%Y-%m-%dT%H:%M:%S,%N%z";
   6369         else die(1, "invalid argument '%s' for '--iso-8601'", iso);
   6370     }
   6371     tm = *gmtime(&ts.tv_sec);
   6372     o = f2;
   6373     for (p = fmt; *p && o < f2 + sizeof f2 - 24; p++) {
   6374         if (p[0] == '%' && p[1] == 'N') { o += sprintf(o, "%09ld", ts.tv_nsec); p++; }
   6375         else if (p[0] == '%' && p[1] == '%') { *o++ = '%'; *o++ = '%'; p++; }
   6376         else if (p[0] == '%' && p[1] == ':' && p[2] == 'z') { o += sprintf(o, "+00:00"); p += 2; }
   6377         else if (p[0] == '%' && p[1] == 'z' && haveiso) { o += sprintf(o, "+00:00"); p++; }
   6378         else if (p[0] == '%' && p[1] == 'U') { o += sprintf(o, "%02d", (tm.tm_yday + 7 - tm.tm_wday) / 7); p++; }
   6379         else if (p[0] == '%' && p[1] == 'W') { o += sprintf(o, "%02d", (tm.tm_yday + 7 - (tm.tm_wday + 6) % 7) / 7); p++; }
   6380         else *o++ = *p;
   6381     }
   6382     *o = 0;
   6383     if (!strftime(out, sizeof out, f2, &tm)) out[0] = 0;
   6384     puts(out);
   6385     return finish_stdout() ? 1 : 0;
   6386 }
   6387 /* ---- install ---- */
   6388 
   6389 static int make_dirs(const char *path, mode_t mode, int verbose, int leaf_only_mode)
   6390 {
   6391     char *p = xstrdup(path), *s;
   6392     int r = 0;
   6393     size_t n = strlen(p);
   6394     while (n > 1 && p[n - 1] == '/') p[--n] = 0;
   6395     for (s = p + 1; *s; s++) {
   6396         if (*s != '/') continue;
   6397         *s = 0;
   6398         if (mkdir(p, 0777 & ~current_umask()) == 0 && verbose) printf("%s: creating directory '%s'\n", prog, p);
   6399         *s = '/';
   6400     }
   6401     if (mkdir(p, mode) == 0) { if (verbose) printf("%s: creating directory '%s'\n", prog, p); if (leaf_only_mode) chmod(p, mode); }
   6402     else if (errno != EEXIST) { perr("cannot create directory '%s'", p); r = 1; }
   6403     free(p);
   6404     return r;
   6405 }
   6406 
   6407 static int t_install(int argc, char **argv)
   6408 {
   6409     static const struct opt lo[] = { { "directory", 0, 'd' }, { "mode", 1, 'm' }, { "owner", 1, 'o' }, { "group", 1, 'g' }, { "verbose", 0, 'v' },
   6410         { "preserve-timestamps", 0, 'p' }, { "target-directory", 1, 't' }, { "no-target-directory", 0, 'T' }, { "compare", 0, 'C' }, { "strip", 0, 's' }, { NULL, 0, 0 } };
   6411     int c, dirmode = 0, mkparents = 0, verbose = 0, preserve = 0, notdir = 0, bad = 0, i, nsrc;
   6412     mode_t mode = 0755;
   6413     uid_t uid = -1; gid_t gid = -1;
   6414     const char *tdir = NULL;
   6415     char **srcs;
   6416     opts_reset();
   6417     while ((c = getopts(argc, argv, "dDm:o:g:cvpt:TCsb", lo)))
   6418         switch (c) {
   6419         case 'd': dirmode = 1; break; case 'D': mkparents = 1; break;
   6420         case 'm': {
   6421             struct change *ch = mode_compile(optarg);
   6422             if (!ch) die(1, "invalid mode '%s'", optarg);
   6423             mode = mode_apply(0, 0, 0, ch);
   6424             break;
   6425         }
   6426         case 'o': if (lookup_user(optarg, &uid) < 0) die(1, "invalid user '%s'", optarg); break;
   6427         case 'g': if (lookup_group(optarg, &gid) < 0) die(1, "invalid group '%s'", optarg); break;
   6428         case 'v': verbose = 1; break; case 'p': preserve = 1; break; case 't': tdir = optarg; break; case 'T': notdir = 1; break;
   6429         default: break;
   6430         }
   6431     if (dirmode) {
   6432         if (!nops) { say("missing file operand"); usage_error(); }
   6433         for (i = 0; i < nops; i++) {
   6434             bad |= make_dirs(ops[i], mode, verbose, 1);
   6435             if (uid != (uid_t)-1 || gid != (gid_t)-1) chown(ops[i], uid, gid);
   6436         }
   6437         return finish_stdout() ? 1 : bad;
   6438     }
   6439     if (!nops) { say("missing file operand"); usage_error(); }
   6440     if (!tdir && nops == 1) { say("missing destination file operand after '%s'", ops[0]); usage_error(); }
   6441     plan_dest(tdir, notdir, 1, &tdir, &srcs, &nsrc);
   6442     for (i = 0; i < nsrc; i++) {
   6443         struct cp o;
   6444         char *dest = tdir ? dest_in(tdir, srcs[i]) : xstrdup(ops[nops - 1]), *dir;
   6445         struct stat st;
   6446         memset(&o, 0, sizeof o);
   6447         o.follow_all = o.follow_top = 1; o.verbose = verbose; o.preserve = preserve; o.um = 0;
   6448         if (stat(srcs[i], &st) < 0) { perr("cannot stat '%s'", srcs[i]); bad = 1; free(dest); continue; }
   6449         if (S_ISDIR(st.st_mode)) { say("omitting directory '%s'", srcs[i]); bad = 1; free(dest); continue; }
   6450         if (mkparents) {
   6451             dir = xstrdup(dest);
   6452             { char *sl = strrchr(dir, '/'); if (sl && sl != dir) { *sl = 0; bad |= make_dirs(dir, 0755, verbose, 0); } }
   6453             free(dir);
   6454         }
   6455         unlink(dest);
   6456         if (cp_one(&o, srcs[i], dest, 1)) { bad = 1; free(dest); continue; }
   6457         if (chmod(dest, mode) < 0) { perr("cannot set permissions of '%s'", dest); bad = 1; }
   6458         if ((uid != (uid_t)-1 || gid != (gid_t)-1) && chown(dest, uid, gid) < 0) { perr("cannot change ownership of '%s'", dest); bad = 1; }
   6459         free(dest);
   6460     }
   6461     return finish_stdout() ? 1 : bad;
   6462 }
   6463 
   6464 /* ---- timeout nice nohup chroot ---- */
   6465 
   6466 static int sig_number(const char *s);
   6467 
   6468 
   6469 static int parse_secs(const char *s, double *out)
   6470 {
   6471     char *e;
   6472     double v;
   6473     if (!(isdigit((unsigned char)*s) || *s == '.')) return -1;
   6474     v = strtod(s, &e);
   6475     if (e == s) return -1;
   6476     if (*e == 's') e++; else if (*e == 'm') { v *= 60; e++; } else if (*e == 'h') { v *= 3600; e++; } else if (*e == 'd') { v *= 86400; e++; }
   6477     if (*e) return -1;
   6478     *out = v;
   6479     return 0;
   6480 }
   6481 
   6482 static double mono(void)
   6483 {
   6484     struct timespec t;
   6485     clock_gettime(1, &t);
   6486     return t.tv_sec + t.tv_nsec / 1e9;
   6487 }
   6488 
   6489 static int t_timeout(int argc, char **argv)
   6490 {
   6491     static const struct opt lo[] = { { "signal", 1, 's' }, { "kill-after", 1, 'k' }, { "preserve-status", 0, 'p' }, { "foreground", 0, 'f' }, { "verbose", 0, 'v' }, { NULL, 0, 0 } };
   6492     int c, sig = 15, keep = 0, verbose = 0, st = 0, killed_by_us = 0;
   6493     double dur, kill_after = 0;
   6494     pid_t pid;
   6495     double start, limit;
   6496     usage_status = 125;
   6497     opts_reset();
   6498     while ((c = getopts(argc, argv, "+s:k:pfv", lo)))
   6499         switch (c) {
   6500         case 's': sig = sig_number(optarg); if (sig < 0) die(125, "%s: invalid signal", optarg); break;
   6501         case 'k': if (parse_secs(optarg, &kill_after) < 0) die(125, "invalid time interval '%s'", optarg); break;
   6502         case 'p': keep = 1; break; case 'v': verbose = 1; break; default: break;
   6503         }
   6504     if (nops < 1) { say("missing operand"); usage_error(); }
   6505     if (nops < 2) { say("missing operand after '%s'", ops[0]); usage_error(); }
   6506     if (parse_secs(ops[0], &dur) < 0) die(125, "invalid time interval '%s'", ops[0]);
   6507     fflush(stdout);
   6508     pid = fork();
   6509     if (pid < 0) die(125, "fork system call failed: %s", strerror(errno));
   6510     if (!pid) {
   6511         execvp(ops[1], ops + 1);
   6512         fprintf(stderr, "%s: failed to run command '%s': %s\n", prog, ops[1], strerror(errno));
   6513         _exit(errno == ENOENT ? 127 : 126);
   6514     }
   6515     start = mono();
   6516     limit = dur ? start + dur : 0;
   6517     for (;;) {
   6518         pid_t r = waitpid(pid, &st, 1);
   6519         if (r == pid) break;
   6520         if (r < 0 && errno != EINTR) die(125, "waitpid: %s", strerror(errno));
   6521         if (limit && mono() >= limit) {
   6522             if (!killed_by_us) {
   6523                 if (verbose) fprintf(stderr, "%s: sending signal %d to command '%s'\n", prog, sig, ops[1]);
   6524                 kill(pid, sig);
   6525                 if (sig != 9 && sig != 19) kill(pid, 18);
   6526                 killed_by_us = 1;
   6527                 if (kill_after > 0) limit = mono() + kill_after; else limit = 0;
   6528             } else {
   6529                 kill(pid, 9);
   6530                 killed_by_us = 2;
   6531                 limit = 0;
   6532             }
   6533         }
   6534         {
   6535             struct timespec ts = { 0, 2000000 };
   6536             nanosleep(&ts, NULL);
   6537         }
   6538     }
   6539     if ((st & 0x7f) == 0) {
   6540         int code = (st >> 8) & 255;
   6541         if (killed_by_us && !keep) return 124;
   6542         return code;
   6543     }
   6544     {
   6545         int s = st & 0x7f;
   6546         if (killed_by_us == 2) return keep ? 128 + s : 137;
   6547         if (killed_by_us && !keep && s != 9) return 124;
   6548         return 128 + s;
   6549     }
   6550 }
   6551 
   6552 static int t_nice(int argc, char **argv)
   6553 {
   6554     int adj = 10, i = 1, cur;
   6555     usage_status = 125;
   6556     if (argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "--version"))) {
   6557         if (argv[1][2] == 'h') print_usage(); else printf("nice (rifle) " VERSION "\n");
   6558         return 0;
   6559     }
   6560     if (i < argc && (!strcmp(argv[i], "-n") || !strcmp(argv[i], "--adjustment"))) {
   6561         if (i + 1 >= argc) die(125, "option requires an argument -- 'n'");
   6562         adj = atoi(argv[i + 1]); i += 2;
   6563     } else if (i < argc && !strncmp(argv[i], "--adjustment=", 13)) { adj = atoi(argv[i] + 13); i++; }
   6564     else if (i < argc && !strncmp(argv[i], "-n", 2) && argv[i][2]) { adj = atoi(argv[i] + 2); i++; }
   6565     else if (i < argc && argv[i][0] == '-' && (isdigit((unsigned char)argv[i][1]) || (argv[i][1] == '-' && isdigit((unsigned char)argv[i][2])))) {
   6566         adj = argv[i][1] == '-' ? -atoi(argv[i] + 2) : atoi(argv[i] + 1);
   6567         if (argv[i][1] != '-') adj = atoi(argv[i] + 1);
   6568         i++;
   6569     } else if (i < argc && argv[i][0] == '-' && argv[i][1] == '-' && !argv[i][2]) i++;
   6570     cur = getpriority(0, 0);
   6571     if (i >= argc) {
   6572         if (adj != 10 || argc > 1) { say("a command must be given with an adjustment"); usage_error(); }
   6573         printf("%d\n", 20 - cur);
   6574         return finish_stdout() ? 125 : 0;
   6575     }
   6576     {
   6577         int want = 20 - cur + adj;
   6578         if (want > 19) want = 19;
   6579         if (want < -20) want = -20;
   6580         if (setpriority(0, 0, want) < 0) fprintf(stderr, "%s: cannot set niceness: %s\n", prog, strerror(errno));
   6581     }
   6582     execvp(argv[i], argv + i);
   6583     fprintf(stderr, "%s: '%s': %s\n", prog, argv[i], strerror(errno));
   6584     return errno == ENOENT ? 127 : 126;
   6585 }
   6586 
   6587 static int t_nohup(int argc, char **argv)
   6588 {
   6589     int ign_in = isatty(0), ign_out = isatty(1), ign_err = isatty(2), saved = 0;
   6590     usage_status = 125;
   6591     if (argc == 2 && !strcmp(argv[1], "--help")) { print_usage(); return 0; }
   6592     if (argc == 2 && !strcmp(argv[1], "--version")) { printf("nohup (rifle) " VERSION "\n"); return 0; }
   6593     if (argc > 1 && !strcmp(argv[1], "--")) { argv++; argc--; }
   6594     if (argc < 2) { say("missing operand"); usage_error(); }
   6595     if (ign_in) {
   6596         int fd = open("/dev/null", O_RDONLY);
   6597         if (fd >= 0) { dup2(fd, 0); if (fd) close(fd); }
   6598     }
   6599     if (ign_out) {
   6600         int fd = open("nohup.out", O_WRONLY | O_CREAT | O_APPEND, 0600);
   6601         if (fd < 0) {
   6602             char *home = getenv("HOME");
   6603             if (home) {
   6604                 char p[PATH_MAX];
   6605                 snprintf(p, sizeof p, "%s/nohup.out", home);
   6606                 fd = open(p, O_WRONLY | O_CREAT | O_APPEND, 0600);
   6607             }
   6608         }
   6609         if (fd < 0) { fprintf(stderr, "%s: failed to open 'nohup.out': %s\n", prog, strerror(errno)); return 125; }
   6610         dup2(fd, 1); if (fd != 1) close(fd);
   6611         saved = 1;
   6612     }
   6613     if (ign_err) dup2(1, 2);
   6614     if (ign_in || ign_out || ign_err) {
   6615         fprintf(stderr, "%s: %s\n", prog, ign_in && saved ? "ignoring input and appending output to 'nohup.out'" :
   6616             ign_in && ign_err && !ign_out ? "ignoring input and redirecting stderr to stdout" : ign_in ? "ignoring input" :
   6617             saved ? "appending output to 'nohup.out'" : "redirecting stderr to stdout");
   6618     }
   6619     signal(SIGHUP, SIG_IGN);
   6620     execvp(argv[1], argv + 1);
   6621     fprintf(stderr, "%s: failed to run command '%s': %s\n", prog, argv[1], strerror(errno));
   6622     return errno == ENOENT ? 127 : 126;
   6623 }
   6624 
   6625 static int t_chroot(int argc, char **argv)
   6626 {
   6627     static const struct opt lo[] = { { "skip-chdir", 0, 's' }, { "userspec", 1, 'u' }, { "groups", 1, 'g' }, { NULL, 0, 0 } };
   6628     int c, skip = 0;
   6629     usage_status = 125;
   6630     opts_reset();
   6631     while ((c = getopts(argc, argv, "+", lo))) if (c == 's') skip = 1;
   6632     if (!nops) { say("missing operand"); usage_error(); }
   6633     if (chroot(ops[0]) < 0) { fprintf(stderr, "%s: cannot change root directory to '%s': %s\n", prog, ops[0], strerror(errno)); return 125; }
   6634     if (!skip && chdir("/") < 0) { fprintf(stderr, "%s: cannot chdir to root directory: %s\n", prog, strerror(errno)); return 125; }
   6635     if (nops > 1) execvp(ops[1], ops + 1);
   6636     else {
   6637         char *sh = getenv("SHELL");
   6638         char *av[] = { sh ? sh : "/bin/sh", "-i", NULL };
   6639         execvp(av[0], av);
   6640     }
   6641     fprintf(stderr, "%s: failed to run command '%s': %s\n", prog, nops > 1 ? ops[1] : "/bin/sh", strerror(errno));
   6642     return errno == ENOENT ? 127 : 126;
   6643 }
   6644 
   6645 /* ---- truncate ---- */
   6646 
   6647 static int t_truncate(int argc, char **argv)
   6648 {
   6649     static const struct opt lo[] = { { "size", 1, 's' }, { "no-create", 0, 'c' }, { "reference", 1, 'r' }, { "io-blocks", 0, 'o' }, { NULL, 0, 0 } };
   6650     int c, nocreate = 0, bad = 0, i;
   6651     const char *sz = NULL, *ref = NULL;
   6652     opts_reset();
   6653     while ((c = getopts(argc, argv, "s:cr:o", lo)))
   6654         switch (c) { case 's': sz = optarg; break; case 'c': nocreate = 1; break; case 'r': ref = optarg; break; case 'o': break; default: break; }
   6655     if (!sz && !ref) { say("you must specify either '--size' or '--reference'"); usage_error(); }
   6656     if (!nops) { say("missing file operand"); usage_error(); }
   6657     for (i = 0; i < nops; i++) {
   6658         struct stat st;
   6659         long long cur = 0, want = 0;
   6660         int fd = open(ops[i], O_WRONLY | (nocreate ? 0 : O_CREAT), 0666);
   6661         char op = 0;
   6662         const char *s = sz;
   6663         if (fd < 0) { if (nocreate && errno == ENOENT) continue; perr("cannot open '%s' for writing", ops[i]); bad = 1; continue; }
   6664         if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) cur = st.st_size;
   6665         if (ref) {
   6666             struct stat rs;
   6667             if (stat(ref, &rs) < 0) { perr("cannot stat '%s'", ref); return 1; }
   6668             want = rs.st_size;
   6669         }
   6670         if (s) {
   6671             unsigned long long n;
   6672             if (*s == '+' || *s == '-' || *s == '<' || *s == '>' || *s == '/' || *s == '%') op = *s++;
   6673             if (parse_size(s, &n) < 0) die(1, "Invalid number: '%s'", sz);
   6674             want = ref ? want : (long long)n;
   6675             if (ref) {
   6676                 if (op == '+') want = cur + n; else if (op == '-') want = cur - n;
   6677             } else switch (op) {
   6678             case '+': want = cur + n; break; case '-': want = cur - n; break; case '<': want = cur < (long long)n ? cur : (long long)n; break;
   6679             case '>': want = cur > (long long)n ? cur : (long long)n; break;
   6680             case '/': want = n ? cur / n * n : cur; break; case '%': want = n ? (cur + n - 1) / n * n : cur; break;
   6681             }
   6682         }
   6683         if (want < 0) want = 0;
   6684         if (ftruncate(fd, want) < 0) { perr("failed to truncate '%s' at %lld bytes", ops[i], want); bad = 1; }
   6685         close(fd);
   6686     }
   6687     return bad;
   6688 }
   6689 
   6690 /* ---- split ---- */
   6691 
   6692 static void split_name(char *out, const char *prefix, const char *add, unsigned long k, int numeric, unsigned long fixed)
   6693 {
   6694     unsigned long base = numeric ? 10 : 26, w, i, cap;
   6695     size_t n = strlen(prefix);
   6696     int zs = 0;
   6697     strcpy(out, prefix);
   6698     if (fixed) {
   6699         w = fixed;
   6700         for (cap = 1, i = 0; i < w; i++) cap *= base;
   6701         if (k >= cap && w < 20) die(1, "output file suffixes exhausted");
   6702     } else {
   6703         w = 2;
   6704         for (;;) {
   6705             for (cap = base - 1, i = 1; i < w; i++) cap *= base;
   6706             if (k < cap) break;
   6707             k -= cap; zs++; w++;
   6708         }
   6709     }
   6710     for (i = 0; i < (unsigned long)zs; i++) out[n++] = numeric ? '9' : 'z';
   6711     for (i = w; i-- > 0; ) { out[n + i] = (numeric ? '0' : 'a') + k % base; k /= base; }
   6712     out[n + w] = 0;
   6713     strcat(out, add);
   6714 }
   6715 
   6716 static int t_split(int argc, char **argv)
   6717 {
   6718     static const struct opt lo[] = { { "lines", 1, 'l' }, { "bytes", 1, 'b' }, { "number", 1, 'n' }, { "suffix-length", 1, 'a' }, { "numeric-suffixes", 2, 'd' },
   6719         { "additional-suffix", 1, 'x' + 256 }, { "verbose", 0, 'v' }, { "line-bytes", 1, 'C' }, { "elide-empty-files", 0, 'e' }, { NULL, 0, 0 } };
   6720     int c, numeric = 0, verbose = 0, fd, fdo = -1, elide = 0, autolen = 1;
   6721     unsigned long suflen = 2, lines = 1000;
   6722     unsigned long long bytes = 0, chunks = 0, lb = 0;
   6723     const char *prefix = "x", *add = "";
   6724     unsigned long idx = 0;
   6725     char *buf, *name = NULL;
   6726     size_t len, i;
   6727     int mode = 0;
   6728     opts_reset();
   6729     while ((c = getopts(argc, argv, "l:b:n:a:d::C:ev", lo)))
   6730         switch (c) {
   6731         case 'l': if (!parse_ulong(optarg, &lines) || !lines) die(1, "invalid number of lines: '%s'", optarg); mode = 0; break;
   6732         case 'b': if (parse_size(optarg, &bytes) < 0 || !bytes) die(1, "invalid number of bytes: '%s'", optarg); mode = 1; break;
   6733         case 'C': if (parse_size(optarg, &lb) < 0 || !lb) die(1, "invalid number of bytes: '%s'", optarg); mode = 2; break;
   6734         case 'n': { unsigned long v; if (!parse_ulong(optarg, &v) || !v) die(1, "invalid number of chunks: '%s'", optarg); chunks = v; mode = 3; break; }
   6735         case 'a': if (!parse_ulong(optarg, &suflen) || !suflen) die(1, "invalid suffix length: '%s'", optarg); autolen = 0; break;
   6736         case 'd': numeric = 1; break; case 'v': verbose = 1; break; case 'e': elide = 1; break;
   6737         case 'x' + 256: add = optarg; break;
   6738         default: break;
   6739         }
   6740     if (nops > 2) extra_operand(ops[2]);
   6741     if (nops == 2) prefix = ops[1];
   6742     fd = open_input(nops ? ops[0] : "-");
   6743     if (fd < 0) { perr("cannot open '%s' for reading", ops[0]); return 1; }
   6744     if (read_all(fd, &buf, &len) < 0) { perr("read error"); return 1; }
   6745     name = xmalloc(strlen(prefix) + strlen(add) + 128 + suflen);
   6746 #define OPEN_NEXT() do { \
   6747         if (fdo >= 0) close(fdo); \
   6748         split_name(name, prefix, add, idx++, numeric, autolen ? 0 : suflen); \
   6749         if (verbose) printf("creating file '%s'\n", name); \
   6750         fdo = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666); \
   6751         if (fdo < 0) { perr("%s", name); exit(1); } } while (0)
   6752     if (mode == 3) {
   6753         unsigned long long k, base = len / chunks, extra = len % chunks, pos = 0;
   6754         for (k = 0; k < chunks; k++) {
   6755             unsigned long long n = base + (k < extra);
   6756             if (elide && !n) continue;
   6757             OPEN_NEXT();
   6758             write_all(fdo, buf + pos, n);
   6759             pos += n;
   6760         }
   6761     } else if (mode == 1) {
   6762         for (i = 0; i < len; i += bytes) {
   6763             size_t n = len - i < bytes ? len - i : bytes;
   6764             OPEN_NEXT();
   6765             write_all(fdo, buf + i, n);
   6766         }
   6767     } else if (mode == 2) {
   6768         size_t start = 0;
   6769         while (start < len) {
   6770             size_t end = start, lastnl = 0;
   6771             int found = 0;
   6772             while (end < len && end - start < lb) { if (buf[end] == '\n') { lastnl = end + 1; found = 1; } end++; }
   6773             if (end < len && found) end = lastnl;
   6774             OPEN_NEXT();
   6775             write_all(fdo, buf + start, end - start);
   6776             start = end;
   6777         }
   6778     } else {
   6779         unsigned long long n = 0;
   6780         for (i = 0; i < len; i++) {
   6781             if (fdo < 0 || n == 0) { OPEN_NEXT(); }
   6782             {
   6783                 size_t e = i;
   6784                 while (e < len && buf[e] != '\n') e++;
   6785                 if (e < len) e++;
   6786                 write_all(fdo, buf + i, e - i);
   6787                 i = e - 1;
   6788             }
   6789             if (++n == lines) { n = 0; if (i + 1 < len) { close(fdo); fdo = -1; } }
   6790         }
   6791     }
   6792     if (fdo >= 0) close(fdo);
   6793     return finish_stdout() ? 1 : 0;
   6794 }
   6795 
   6796 /* ---- expand unexpand ---- */
   6797 
   6798 static int t_expand(int argc, char **argv)
   6799 {
   6800     static const struct opt lo[] = { { "tabs", 1, 't' }, { "initial", 0, 'i' }, { "all", 0, 'a' }, { "first-only", 0, 'i' + 256 }, { NULL, 0, 0 } };
   6801     int un = !strcmp(prog, "unexpand"), c, init = 0, all = 0, i, bad = 0;
   6802     int tabs[128], ntabs = 0, step = 8;
   6803     opts_reset();
   6804     while ((c = getopts(argc, argv, un ? "at:" : "it:", lo)))
   6805         switch (c) {
   6806         case 'i': init = 1; break; case 'a': all = 1; break;
   6807         case 't': {
   6808             char *s = optarg, *e;
   6809             ntabs = 0;
   6810             while (*s) {
   6811                 long v = strtol(s, &e, 10);
   6812                 if (e == s || v < 0 || ((*e) && *e != ',' && *e != ' ')) die(1, "tab size contains invalid character(s): '%s'", s);
   6813                 if (ntabs && v <= tabs[ntabs - 1]) die(1, "tab sizes must be ascending");
   6814                 if (ntabs < 128) tabs[ntabs++] = v;
   6815                 s = *e ? e + 1 : e;
   6816             }
   6817             if (ntabs == 1) { step = tabs[0]; if (!step) die(1, "tab size cannot be 0"); ntabs = 0; }
   6818             if (un) all = 1;
   6819             break;
   6820         }
   6821         default: break;
   6822         }
   6823     if (!nops) ops[nops++] = "-";
   6824     for (i = 0; i < nops; i++) {
   6825         FILE *f = !strcmp(ops[i], "-") ? stdin : fopen(ops[i], "r");
   6826         int ch, col = 0, blank = 1;
   6827         if (!f) { perr("%s", ops[i]); bad = 1; continue; }
   6828         {
   6829 #define NEXT_STOP(col) (ntabs ? ({ int t_ = 0, k_; for (k_ = 0; k_ < ntabs; k_++) if (tabs[k_] > (col)) { t_ = tabs[k_]; break; } t_ ? t_ : (col) + 1; }) : ((col) / step + 1) * step)
   6830             if (!un) {
   6831                 while ((ch = getc(f)) != EOF) {
   6832                     if (ch == '\t' && !(init && !blank)) { int nx = NEXT_STOP(col); while (col < nx) { putchar(' '); col++; } }
   6833                     else {
   6834                         putchar(ch);
   6835                         if (ch == '\n') { col = 0; blank = 1; } else if (ch == '\b') { if (col) col--; } else { col++; if (ch != ' ' && ch != '\t') blank = 0; }
   6836                         if (ch == '\t') col = NEXT_STOP(col - 1 > 0 ? col - 1 : 0);
   6837                     }
   6838                 }
   6839             } else {
   6840                 char *line = NULL;
   6841                 size_t cap = 0;
   6842                 ssize_t n;
   6843                 while ((n = getline(&line, &cap, f)) >= 0) {
   6844                     ssize_t k = 0;
   6845                     int c2 = 0, pend = 0, pstart = 0;
   6846                     int leading = 1;
   6847                     for (k = 0; k < n; k++) {
   6848                         char x = line[k];
   6849                         if ((x == ' ' || x == '\t') && (all || leading)) {
   6850                             if (!pend) { pstart = c2; pend = 1; }
   6851                             if (x == '\t') c2 = NEXT_STOP(c2); else c2++;
   6852                             continue;
   6853                         }
   6854                         if (pend) {
   6855                             int cc = pstart;
   6856                             while (1) {
   6857                                 int nx = NEXT_STOP(cc);
   6858                                 if (nx <= c2 && nx - cc > 1) { putchar('\t'); cc = nx; }
   6859                                 else break;
   6860                             }
   6861                             while (cc < c2) { putchar(' '); cc++; }
   6862                             pend = 0;
   6863                         }
   6864                         putchar(x);
   6865                         if (x == '\b') { if (c2) c2--; } else c2++;
   6866                         leading = 0;
   6867                     }
   6868                     if (pend) {
   6869                         int cc = pstart;
   6870                         while (1) { int nx = NEXT_STOP(cc); if (nx <= c2 && nx - cc > 1) { putchar('\t'); cc = nx; } else break; }
   6871                         while (cc < c2) { putchar(' '); cc++; }
   6872                     }
   6873                 }
   6874                 free(line);
   6875             }
   6876         }
   6877         if (f != stdin) fclose(f);
   6878     }
   6879     return finish_stdout() ? 1 : bad;
   6880 }
   6881 
   6882 /* ---- shuf ---- */
   6883 
   6884 static unsigned long long rnd64(void)
   6885 {
   6886     unsigned long long v;
   6887     if (getrandom(&v, sizeof v, 0) != (ssize_t)sizeof v) v = (unsigned long long)time(NULL) * 6364136223846793005ULL;
   6888     return v;
   6889 }
   6890 
   6891 static unsigned long long rnd_below(unsigned long long n)
   6892 {
   6893     unsigned long long lim = ~0ULL - (~0ULL % n), v;
   6894     do v = rnd64(); while (v >= lim);
   6895     return v % n;
   6896 }
   6897 
   6898 static int t_shuf(int argc, char **argv)
   6899 {
   6900     static const struct opt lo[] = { { "echo", 0, 'e' }, { "input-range", 1, 'i' }, { "head-count", 1, 'n' }, { "repeat", 0, 'r' }, { "zero-terminated", 0, 'z' },
   6901         { "output", 1, 'o' }, { "random-source", 1, 'R' }, { NULL, 0, 0 } };
   6902     int c, echo = 0, rep = 0, zero = 0;
   6903     unsigned long long lo_ = 0, hi_ = 0, count = ~0ULL;
   6904     int haverange = 0;
   6905     char **items = NULL, *data = NULL;
   6906     size_t n = 0, i;
   6907     const char *outf = NULL;
   6908     FILE *out = stdout;
   6909     int sep;
   6910     opts_reset();
   6911     while ((c = getopts(argc, argv, "ei:n:rzo:", lo)))
   6912         switch (c) {
   6913         case 'e': echo = 1; break;
   6914         case 'i': {
   6915             char *dash = strchr(optarg, '-');
   6916             if (!dash) die(1, "invalid input range: '%s'", optarg);
   6917             lo_ = strtoull(optarg, NULL, 10); hi_ = strtoull(dash + 1, NULL, 10);
   6918             if (hi_ + 1 < lo_) die(1, "invalid input range: '%s'", optarg);
   6919             haverange = 1;
   6920             break;
   6921         }
   6922         case 'n': { unsigned long v; if (!parse_ulong(optarg, &v)) die(1, "invalid line count: '%s'", optarg); if (v < count) count = v; break; }
   6923         case 'r': rep = 1; break; case 'z': zero = 1; break; case 'o': outf = optarg; break;
   6924         default: break;
   6925         }
   6926     sep = zero ? 0 : '\n';
   6927     if (outf) { out = fopen(outf, "w"); if (!out) { perr("%s", outf); return 1; } }
   6928     if (haverange) {
   6929         unsigned long long k, total = hi_ - lo_ + 1;
   6930         unsigned long long *v;
   6931         if (rep) {
   6932             if (!total) die(1, "no lines to repeat");
   6933             for (k = 0; k < count; k++) fprintf(out, "%llu%c", lo_ + rnd_below(total), sep);
   6934         } else {
   6935             v = xmalloc((total ? total : 1) * sizeof *v);
   6936             for (k = 0; k < total; k++) v[k] = lo_ + k;
   6937             for (k = 0; k < total && k < count; k++) {
   6938                 unsigned long long j = k + rnd_below(total - k), t = v[k];
   6939                 v[k] = v[j]; v[j] = t;
   6940                 fprintf(out, "%llu%c", v[k], sep);
   6941             }
   6942         }
   6943         return finish_stdout() ? 1 : 0;
   6944     }
   6945     if (echo) { items = ops; n = nops; }
   6946     else {
   6947         size_t len, cap = 0, start = 0;
   6948         int fd;
   6949         if (nops > 1) extra_operand(ops[1]);
   6950         fd = open_input(nops ? ops[0] : "-");
   6951         if (fd < 0) { perr("%s", ops[0]); return 1; }
   6952         if (read_all(fd, &data, &len) < 0) { perr("read error"); return 1; }
   6953         for (i = 0; i < len; i++) {
   6954             if ((unsigned char)data[i] == (unsigned)sep || (i + 1 == len)) {
   6955                 if (n == cap) { cap = cap ? cap * 2 : 64; items = xrealloc(items, cap * sizeof *items); }
   6956                 items[n++] = data + start;
   6957                 if ((unsigned char)data[i] == (unsigned)sep) data[i] = 0; else { data = xrealloc(data, len + 1); data[len] = 0; items[n - 1] = data + start; }
   6958                 start = i + 1;
   6959             }
   6960         }
   6961     }
   6962     if (rep) {
   6963         unsigned long long k;
   6964         if (!n) die(1, "no lines to repeat");
   6965         for (k = 0; k < count; k++) fprintf(out, "%s%c", items[rnd_below(n)], sep);
   6966     } else {
   6967         size_t k;
   6968         for (k = 0; k < n && k < count; k++) {
   6969             size_t j = k + rnd_below(n - k);
   6970             char *t = items[k];
   6971             items[k] = items[j]; items[j] = t;
   6972             fprintf(out, "%s%c", items[k], sep);
   6973         }
   6974     }
   6975     if (outf) fclose(out);
   6976     return finish_stdout() ? 1 : 0;
   6977 }
   6978 
   6979 /* ---- join ---- */
   6980 
   6981 struct jl { char *line; char **f; int nf; };
   6982 
   6983 static int jtab = -1, jicase;
   6984 static const char *jempty = "";
   6985 
   6986 static void j_split(struct jl *l)
   6987 {
   6988     char *p = l->line, **f = NULL;
   6989     int n = 0, cap = 0;
   6990     for (;;) {
   6991         char *s;
   6992         if (jtab < 0) while (*p == ' ' || *p == '\t') p++;
   6993         s = p;
   6994         if (jtab < 0) while (*p && *p != ' ' && *p != '\t') p++; else while (*p && *p != jtab) p++;
   6995         if (n == cap) { cap = cap ? cap * 2 : 8; f = xrealloc(f, cap * sizeof *f); }
   6996         f[n++] = xmalloc(p - s + 1);
   6997         memcpy(f[n - 1], s, p - s); f[n - 1][p - s] = 0;
   6998         if (!*p) break;
   6999         if (jtab >= 0) p++;
   7000         else { while (*p == ' ' || *p == '\t') p++; if (!*p) break; }
   7001     }
   7002     l->f = f; l->nf = n;
   7003 }
   7004 
   7005 static int j_cmp(const char *a, const char *b) { return jicase ? strcasecmp(a, b) : strcmp(a, b); }
   7006 
   7007 static int j_read(const char *name, struct jl **out)
   7008 {
   7009     int fd = open_input(name);
   7010     char *d;
   7011     size_t len, i, start = 0;
   7012     int n = 0, cap = 0;
   7013     struct jl *v = NULL;
   7014     if (fd < 0) { perr("%s", name); exit(1); }
   7015     if (read_all(fd, &d, &len) < 0) { perr("%s", name); exit(1); }
   7016     for (i = 0; i < len; i++) {
   7017         if (d[i] == '\n' || i + 1 == len) {
   7018             size_t e = d[i] == '\n' ? i : i + 1;
   7019             if (n == cap) { cap = cap ? cap * 2 : 64; v = xrealloc(v, cap * sizeof *v); }
   7020             v[n].line = xmalloc(e - start + 1);
   7021             memcpy(v[n].line, d + start, e - start); v[n].line[e - start] = 0;
   7022             j_split(&v[n]);
   7023             n++;
   7024             start = i + 1;
   7025         }
   7026     }
   7027     *out = v;
   7028     return n;
   7029 }
   7030 
   7031 static int t_join(int argc, char **argv)
   7032 {
   7033     static const struct opt lo[] = { { "ignore-case", 0, 'i' }, { NULL, 0, 0 } };
   7034     int c, k1 = 1, k2 = 1, a1 = 0, a2 = 0, v1 = 0, v2 = 0, nf1, nf2, i1 = 0, i2 = 0, nout = 0;
   7035     struct jl *l1, *l2;
   7036     struct { int file, field; } outf[64];
   7037     int useout = 0;
   7038     opts_reset();
   7039     while ((c = getopts(argc, argv, "1:2:j:t:a:v:e:o:i", lo)))
   7040         switch (c) {
   7041         case '1': k1 = atoi(optarg); break; case '2': k2 = atoi(optarg); break; case 'j': k1 = k2 = atoi(optarg); break;
   7042         case 't': jtab = optarg[0]; break; case 'i': jicase = 1; break; case 'e': jempty = optarg; break;
   7043         case 'a': if (atoi(optarg) == 1) a1 = 1; else if (atoi(optarg) == 2) a2 = 1; else die(1, "invalid file number: '%s'", optarg); break;
   7044         case 'v': if (atoi(optarg) == 1) { v1 = 1; a1 = 1; } else if (atoi(optarg) == 2) { v2 = 1; a2 = 1; } else die(1, "invalid file number: '%s'", optarg); break;
   7045         case 'o': {
   7046             char *s = optarg;
   7047             useout = 1;
   7048             while (*s) {
   7049                 if (!strncmp(s, "0", 1) && (s[1] == ',' || s[1] == ' ' || !s[1])) { outf[nout].file = 0; outf[nout].field = 0; nout++; s++; }
   7050                 else {
   7051                     outf[nout].file = atoi(s); s += strspn(s, "0123456789");
   7052                     if (*s != '.') die(1, "invalid field specifier: '%s'", optarg);
   7053                     outf[nout].field = atoi(s + 1); s += 1 + strspn(s + 1, "0123456789"); nout++;
   7054                 }
   7055                 while (*s == ',' || *s == ' ') s++;
   7056             }
   7057             break;
   7058         }
   7059         default: break;
   7060         }
   7061     if (nops != 2) { if (nops < 2) { say("missing operand after '%s'", nops ? ops[nops - 1] : argv[0]); } else extra_operand(ops[2]); usage_error(); }
   7062     nf1 = j_read(ops[0], &l1);
   7063     nf2 = j_read(ops[1], &l2);
   7064 #define EMIT_KEY(l, k) (((k) <= (l)->nf && (l)->f[(k) - 1][0]) ? (l)->f[(k) - 1] : jempty)
   7065     {
   7066         char sep = jtab >= 0 ? jtab : ' ';
   7067         while (i1 < nf1 || i2 < nf2) {
   7068             int r;
   7069             const char *ka = i1 < nf1 ? EMIT_KEY(&l1[i1], k1) : NULL, *kb = i2 < nf2 ? EMIT_KEY(&l2[i2], k2) : NULL;
   7070             if (!ka) r = 1; else if (!kb) r = -1; else r = j_cmp(ka, kb);
   7071             if (r < 0) {
   7072                 if (a1) {
   7073                     struct jl *l = &l1[i1];
   7074                     int f;
   7075                     if (useout) { for (f = 0; f < nout; f++) { if (f) putchar(sep); if (outf[f].file == 0) fputs(ka, stdout); else if (outf[f].file == 1) fputs(outf[f].field <= l->nf ? l->f[outf[f].field - 1] : jempty, stdout); else fputs(jempty, stdout); } }
   7076                     else { fputs(ka, stdout); for (f = 0; f < l->nf; f++) if (f != k1 - 1) { putchar(sep); fputs(l->f[f], stdout); } }
   7077                     putchar('\n');
   7078                 }
   7079                 i1++;
   7080             } else if (r > 0) {
   7081                 if (a2) {
   7082                     struct jl *l = &l2[i2];
   7083                     int f;
   7084                     if (useout) { for (f = 0; f < nout; f++) { if (f) putchar(sep); if (outf[f].file == 0) fputs(kb, stdout); else if (outf[f].file == 2) fputs(outf[f].field <= l->nf ? l->f[outf[f].field - 1] : jempty, stdout); else fputs(jempty, stdout); } }
   7085                     else { fputs(kb, stdout); for (f = 0; f < l->nf; f++) if (f != k2 - 1) { putchar(sep); fputs(l->f[f], stdout); } }
   7086                     putchar('\n');
   7087                 }
   7088                 i2++;
   7089             } else {
   7090                 int e1 = i1, e2 = i2, x, y;
   7091                 while (e1 < nf1 && !j_cmp(EMIT_KEY(&l1[e1], k1), ka)) e1++;
   7092                 while (e2 < nf2 && !j_cmp(EMIT_KEY(&l2[e2], k2), kb)) e2++;
   7093                 if (!v1 && !v2)
   7094                     for (x = i1; x < e1; x++)
   7095                         for (y = i2; y < e2; y++) {
   7096                             struct jl *a = &l1[x], *b = &l2[y];
   7097                             int f;
   7098                             if (useout) {
   7099                                 for (f = 0; f < nout; f++) {
   7100                                     if (f) putchar(sep);
   7101                                     if (outf[f].file == 0) fputs(ka, stdout);
   7102                                     else { struct jl *l = outf[f].file == 1 ? a : b; fputs(outf[f].field <= l->nf && outf[f].field > 0 ? l->f[outf[f].field - 1] : jempty, stdout); }
   7103                                 }
   7104                             } else {
   7105                                 fputs(ka, stdout);
   7106                                 for (f = 0; f < a->nf; f++) if (f != k1 - 1) { putchar(sep); fputs(a->f[f], stdout); }
   7107                                 for (f = 0; f < b->nf; f++) if (f != k2 - 1) { putchar(sep); fputs(b->f[f], stdout); }
   7108                             }
   7109                             putchar('\n');
   7110                         }
   7111                 i1 = e1; i2 = e2;
   7112             }
   7113         }
   7114     }
   7115     return finish_stdout() ? 1 : 0;
   7116 }
   7117 
   7118 /* ---- tsort ---- */
   7119 
   7120 static int t_tsort(int argc, char **argv)
   7121 {
   7122     char *d, **names = NULL, *tok;
   7123     size_t len;
   7124     int fd, n = 0, cap = 0, ne = 0, ecap = 0, *ef = NULL, *et = NULL, *indeg, *done, *queue, qh = 0, qt = 0, bad = 0, emitted = 0, k;
   7125     opts_reset();
   7126     while (getopts(argc, argv, "", NULL)) {}
   7127     if (nops > 1) extra_operand(ops[1]);
   7128     fd = open_input(nops ? ops[0] : "-");
   7129     if (fd < 0) { perr("%s", ops[0]); return 1; }
   7130     if (read_all(fd, &d, &len) < 0) { perr("read error"); return 1; }
   7131     {
   7132         int pending = -1;
   7133         size_t p = 0;
   7134         d = xrealloc(d, len + 1); d[len] = 0;
   7135         while (p < len) {
   7136             int id = -1;
   7137             while (p < len && isspace((unsigned char)d[p])) p++;
   7138             if (p >= len) break;
   7139             tok = d + p;
   7140             while (p < len && !isspace((unsigned char)d[p])) p++;
   7141             d[p] = 0; p++;
   7142             for (k = 0; k < n; k++) if (!strcmp(names[k], tok)) { id = k; break; }
   7143             if (id < 0) { if (n == cap) { cap = cap ? cap * 2 : 64; names = xrealloc(names, cap * sizeof *names); } names[n] = tok; id = n++; }
   7144             if (pending < 0) pending = id;
   7145             else {
   7146                 if (ne == ecap) { ecap = ecap ? ecap * 2 : 64; ef = xrealloc(ef, ecap * sizeof *ef); et = xrealloc(et, ecap * sizeof *et); }
   7147                 ef[ne] = pending; et[ne] = id; ne++;
   7148                 pending = -1;
   7149             }
   7150         }
   7151         if (pending >= 0) die(1, "%s: input contains an odd number of tokens", nops ? ops[0] : "-");
   7152     }
   7153     indeg = xmalloc((n + 1) * sizeof *indeg); done = xmalloc((n + 1) * sizeof *done); queue = xmalloc((n + 1) * sizeof *queue);
   7154     for (k = 0; k < n; k++) { indeg[k] = 0; done[k] = 0; }
   7155     for (k = 0; k < ne; k++) if (ef[k] != et[k]) indeg[et[k]]++;
   7156     for (k = 0; k < n; k++) if (!indeg[k]) queue[qt++] = k;
   7157     while (emitted < n) {
   7158         while (qh < qt) {
   7159             int u = queue[qh++];
   7160             done[u] = 1; emitted++;
   7161             puts(names[u]);
   7162             for (k = 0; k < ne; k++) if (ef[k] == u && et[k] != u && !--indeg[et[k]]) queue[qt++] = et[k];
   7163         }
   7164         if (emitted < n) {
   7165             int first = -1;
   7166             for (k = 0; k < n; k++) if (!done[k]) { if (first < 0) first = k; }
   7167             fflush(stdout);
   7168             say("%s: input contains a loop:", nops ? ops[0] : "-");
   7169             for (k = 0; k < n; k++) if (!done[k] && indeg[k]) fprintf(stderr, "%s: %s\n", prog, names[k]);
   7170             bad = 1;
   7171             indeg[first] = 0;
   7172             queue[qt++] = first;
   7173         }
   7174     }
   7175     return finish_stdout() ? 1 : bad;
   7176 }
   7177 
   7178 /* ---- factor ---- */
   7179 
   7180 typedef unsigned long long u64;
   7181 
   7182 #ifdef __i386__
   7183 static u64 mulmod(u64 a, u64 b, u64 m)
   7184 {
   7185     u64 r = 0;
   7186     a %= m;
   7187     while (b) {
   7188         if (b & 1) r = r >= m - a ? r - (m - a) : r + a;
   7189         a = a >= m - a ? a - (m - a) : a + a;
   7190         b >>= 1;
   7191     }
   7192     return r;
   7193 }
   7194 #else
   7195 static u64 mulmod(u64 a, u64 b, u64 m)
   7196 {
   7197     u64 r;
   7198     __asm__("mulq %2\n divq %3" : "=&d"(r), "+a"(a) : "r"(b), "r"(m) : "cc");
   7199     return r;
   7200 }
   7201 #endif
   7202 
   7203 static u64 powmod(u64 b, u64 e, u64 m)
   7204 {
   7205     u64 r = 1;
   7206     b %= m;
   7207     while (e) { if (e & 1) r = mulmod(r, b, m); b = mulmod(b, b, m); e >>= 1; }
   7208     return r;
   7209 }
   7210 
   7211 static int is_prime(u64 n)
   7212 {
   7213     static const u64 bases[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 };
   7214     u64 d = n - 1;
   7215     int s = 0, i;
   7216     if (n < 2) return 0;
   7217     for (i = 0; i < 12; i++) { if (n == bases[i]) return 1; if (n % bases[i] == 0) return 0; }
   7218     while (!(d & 1)) { d >>= 1; s++; }
   7219     for (i = 0; i < 12; i++) {
   7220         u64 x = powmod(bases[i], d, n);
   7221         int r;
   7222         if (x == 1 || x == n - 1) continue;
   7223         for (r = 1; r < s; r++) { x = mulmod(x, x, n); if (x == n - 1) break; }
   7224         if (r == s) return 0;
   7225     }
   7226     return 1;
   7227 }
   7228 
   7229 static u64 gcd64(u64 a, u64 b) { while (b) { u64 t = a % b; a = b; b = t; } return a; }
   7230 
   7231 static u64 rho(u64 n)
   7232 {
   7233     u64 c;
   7234     for (c = 1;; c++) {
   7235         u64 x = 2, y = 2, d = 1;
   7236         while (d == 1) {
   7237             x = (mulmod(x, x, n) + c) % n;
   7238             y = (mulmod(y, y, n) + c) % n;
   7239             y = (mulmod(y, y, n) + c) % n;
   7240             d = gcd64(x > y ? x - y : y - x, n);
   7241         }
   7242         if (d != n) return d;
   7243     }
   7244 }
   7245 
   7246 static void factor_into(u64 n, u64 *out, int *cnt)
   7247 {
   7248     if (n == 1) return;
   7249     if (is_prime(n)) { out[(*cnt)++] = n; return; }
   7250     {
   7251         u64 d = rho(n);
   7252         factor_into(d, out, cnt);
   7253         factor_into(n / d, out, cnt);
   7254     }
   7255 }
   7256 
   7257 static int factor_one(const char *s)
   7258 {
   7259     char *e;
   7260     u64 n, f[64];
   7261     int cnt = 0, i, j;
   7262     const char *p = s;
   7263     while (isspace((unsigned char)*p)) p++;
   7264     if (*p == '+') p++;
   7265     if (!isdigit((unsigned char)*p)) { say("'%s' is not a valid positive integer", s); return 1; }
   7266     for (n = 0, e = (char *)p; isdigit((unsigned char)*e); e++) {
   7267         if (n > (~0ULL - (*e - '0')) / 10) { say("'%s' is too large for rifle's factor", s); return 1; }
   7268         n = n * 10 + (*e - '0');
   7269     }
   7270     if (*e) { say("'%s' is not a valid positive integer", s); return 1; }
   7271     printf("%llu:", n);
   7272     if (n > 1) {
   7273         u64 q;
   7274         for (q = 2; q < 1000 && q * q <= n; q++) while (n % q == 0) { f[cnt++] = q; n /= q; }
   7275         factor_into(n, f, &cnt);
   7276     }
   7277     for (i = 0; i < cnt; i++) for (j = i + 1; j < cnt; j++) if (f[j] < f[i]) { u64 t = f[i]; f[i] = f[j]; f[j] = t; }
   7278     for (i = 0; i < cnt; i++) printf(" %llu", f[i]);
   7279     putchar('\n');
   7280     return 0;
   7281 }
   7282 
   7283 static int t_factor(int argc, char **argv)
   7284 {
   7285     int i, bad = 0;
   7286     opts_reset();
   7287     while (getopts(argc, argv, "", NULL)) {}
   7288     if (nops) { for (i = 0; i < nops; i++) bad |= factor_one(ops[i]); }
   7289     else {
   7290         char tok[64];
   7291         int c, k = 0;
   7292         while ((c = getchar()) != EOF) {
   7293             if (isspace(c)) { if (k) { tok[k] = 0; bad |= factor_one(tok); k = 0; } }
   7294             else if (k < 63) tok[k++] = c;
   7295         }
   7296         if (k) { tok[k] = 0; bad |= factor_one(tok); }
   7297     }
   7298     return finish_stdout() ? 1 : bad;
   7299 }
   7300 /* ---- regex ----
   7301  * BRE and ERE read the way GNU reads them (\w \< \b \+ \| work in a BRE too), on bytes. a pattern becomes a node tree,
   7302  * the tree a short program, and a backtracking machine runs that, keeping the longest match from the leftmost start.
   7303  * grep and sed both use it */
   7304 
   7305 enum { R_CHAR, R_ANY, R_SET, R_SPLIT, R_JMP, R_SAVE, R_BOL, R_EOL, R_WB, R_NWB, R_WBEG, R_WEND, R_BEFORE, R_AFTER,
   7306        R_BREF, R_MARK, R_PROG, R_BOS, R_EOS, R_MATCH };
   7307 enum { N_EMPTY, N_CHAR, N_ANY, N_SET, N_CAT, N_ALT, N_REP, N_GRP, N_ASSERT, N_BREF };
   7308 
   7309 struct rinst { int op, x, y, id; };
   7310 struct rnode { int t, c, min, max; struct rnode *a, *b; };
   7311 struct regex {
   7312     struct rinst *prog; int n, cap, ngrp, nslot, nsplit, nmark, backref, icase, ml, first;
   7313     unsigned char (*sets)[32]; int nsets;
   7314 };
   7315 struct rparse { const char *p, *e; int ere, sed, depth, local; struct regex *re; };
   7316 
   7317 static int re_exit = 2;
   7318 #define RE_DUP_MAX 32767
   7319 
   7320 static __attribute__((noreturn)) void re_die(const char *m) { die(re_exit, "%s", m); }
   7321 
   7322 static struct rnode *rn(int t, struct rnode *a, struct rnode *b)
   7323 {
   7324     struct rnode *n = xmalloc(sizeof *n);
   7325     memset(n, 0, sizeof *n);
   7326     n->t = t; n->a = a; n->b = b;
   7327     return n;
   7328 }
   7329 static struct rnode *rn_cat(struct rnode *a, struct rnode *b) { return a ? rn(N_CAT, a, b) : b; }
   7330 
   7331 static struct regex *re_new(int icase)
   7332 {
   7333     struct regex *re = xmalloc(sizeof *re);
   7334     memset(re, 0, sizeof *re);
   7335     re->icase = icase; re->first = -1;
   7336     return re;
   7337 }
   7338 
   7339 static int re_newset(struct regex *re)
   7340 {
   7341     re->sets = xrealloc(re->sets, (re->nsets + 1) * sizeof *re->sets);
   7342     memset(re->sets[re->nsets], 0, 32);
   7343     return re->nsets++;
   7344 }
   7345 #define SET_ADD(s, c) ((s)[(unsigned char)(c) >> 3] |= 1 << ((c) & 7))
   7346 #define SET_HAS(s, c) ((s)[(unsigned char)(c) >> 3] >> ((c) & 7) & 1)
   7347 
   7348 static void set_fold(unsigned char *s)
   7349 {
   7350     int c;
   7351     for (c = 'a'; c <= 'z'; c++) {
   7352         if (SET_HAS(s, c) || SET_HAS(s, c - 32)) { SET_ADD(s, c); SET_ADD(s, c - 32); }
   7353     }
   7354 }
   7355 
   7356 static struct rnode *re_ch(struct rparse *ps, int c)
   7357 {
   7358     struct rnode *n;
   7359     if (ps->re->icase && isalpha(c)) {
   7360         n = rn(N_SET, NULL, NULL);
   7361         n->c = re_newset(ps->re);
   7362         SET_ADD(ps->re->sets[n->c], c); SET_ADD(ps->re->sets[n->c], c ^ 32);
   7363         return n;
   7364     }
   7365     n = rn(N_CHAR, NULL, NULL);
   7366     n->c = c;
   7367     return n;
   7368 }
   7369 
   7370 static int class_has(const char *name, size_t l, int c)
   7371 {
   7372     static const char *names[] = { "alpha", "digit", "alnum", "upper", "lower", "space", "blank", "punct", "print", "graph", "cntrl", "xdigit" };
   7373     int k;
   7374     for (k = 0; k < 12; k++) if (strlen(names[k]) == l && !strncmp(names[k], name, l)) break;
   7375     switch (k) {
   7376     case 0: return isalpha(c);
   7377     case 1: return isdigit(c);
   7378     case 2: return isalnum(c);
   7379     case 3: return isupper(c);
   7380     case 4: return islower(c);
   7381     case 5: return isspace(c);
   7382     case 6: return c == ' ' || c == '\t';
   7383     case 7: return ispunct(c);
   7384     case 8: return c >= 32 && c < 127;
   7385     case 9: return c > 32 && c < 127;
   7386     case 10: return c < 32 || c == 127;
   7387     case 11: return isxdigit(c);
   7388     }
   7389     return -1;
   7390 }
   7391 
   7392 static int class_name_ok(const char *name, size_t l) { return class_has(name, l, 'a') >= 0; }
   7393 
   7394 static void class_add(unsigned char *set, const char *name, size_t l)
   7395 {
   7396     int c;
   7397     for (c = 0; c < 256; c++) if (class_has(name, l, c) > 0) SET_ADD(set, c);
   7398 }
   7399 
   7400 static int re_bchar(struct rparse *ps, const char **pp)
   7401 {
   7402     const char *p = *pp;
   7403     int c = (unsigned char)*p++;
   7404     if (c == '[' && p < ps->e && *p == '.') {
   7405         if (p + 3 >= ps->e || p[2] != '.' || p[3] != ']') re_die("Invalid collation character");
   7406         c = (unsigned char)p[1]; p += 4;
   7407     } else if (ps->sed && c == '\\' && p < ps->e && (*p == 'n' || *p == 't')) c = *p++ == 'n' ? '\n' : '\t';
   7408     *pp = p;
   7409     return c;
   7410 }
   7411 
   7412 /* after the [ */
   7413 static struct rnode *re_bracket(struct rparse *ps)
   7414 {
   7415     struct regex *re = ps->re;
   7416     int idx = re_newset(re), neg = 0, first = 1, c, k;
   7417     const char *p = ps->p, *start;
   7418     if (p < ps->e && *p == '^') { neg = 1; p++; }
   7419     start = p;
   7420     for (;; first = 0) {
   7421         int lo;
   7422         if (p >= ps->e) re_die("Unmatched [, [^, [:, [., or [=");
   7423         if (*p == ']' && !first) { p++; break; }
   7424         if (*p == '[' && p + 1 < ps->e && (p[1] == ':' || p[1] == '=')) {
   7425             const char *q = p + 2;
   7426             while (q + 1 < ps->e && !(*q == p[1] && q[1] == ']')) q++;
   7427             if (q + 1 >= ps->e) re_die("Unmatched [, [^, [:, [., or [=");
   7428             if (p[1] == ':') {
   7429                 if (!class_name_ok(p + 2, q - p - 2)) re_die("Invalid character class name");
   7430                 class_add(re->sets[idx], p + 2, q - p - 2);
   7431             } else {
   7432                 if (q - p != 3) re_die("Invalid collation character");
   7433                 SET_ADD(re->sets[idx], p[2]);
   7434             }
   7435             p = q + 2;
   7436             continue;
   7437         }
   7438         lo = re_bchar(ps, &p);
   7439         if (p + 1 < ps->e && *p == '-' && p[1] != ']') {
   7440             int hi;
   7441             p++;
   7442             hi = re_bchar(ps, &p);
   7443             if (hi < lo) re_die("Invalid range end");
   7444             for (c = lo; c <= hi; c++) SET_ADD(re->sets[idx], c);
   7445         } else SET_ADD(re->sets[idx], lo);
   7446     }
   7447     if (p - start >= 3 && *start == ':' && p[-2] == ':') re_die("character class syntax is [[:space:]], not [:space:]");
   7448     ps->p = p;
   7449     if (re->icase) set_fold(re->sets[idx]);
   7450     if (neg) for (k = 0; k < 32; k++) re->sets[idx][k] = ~re->sets[idx][k];
   7451     {
   7452         struct rnode *n = rn(N_SET, NULL, NULL);
   7453         n->c = idx;
   7454         return n;
   7455     }
   7456 }
   7457 
   7458 static struct rnode *re_alt(struct rparse *ps);
   7459 
   7460 static struct rnode *re_assert(int op)
   7461 {
   7462     struct rnode *n = rn(N_ASSERT, NULL, NULL);
   7463     n->c = op;
   7464     return n;
   7465 }
   7466 
   7467 static struct rnode *re_shorthand(struct rparse *ps, int c)
   7468 {
   7469     struct rnode *n = rn(N_SET, NULL, NULL);
   7470     unsigned char *s;
   7471     int k;
   7472     n->c = re_newset(ps->re);
   7473     s = ps->re->sets[n->c];
   7474     for (k = 0; k < 256; k++) {
   7475         int w = isalnum(k) || k == '_', sp = isspace(k);
   7476         if (c == 'w' ? w : c == 'W' ? !w : c == 's' ? sp : !sp) SET_ADD(s, k);
   7477     }
   7478     return n;
   7479 }
   7480 
   7481 /* the {m,n} after a brace. in an ERE a brace that doesn't make an interval is only a brace, in a BRE it is an error */
   7482 static int re_interval(struct rparse *ps, int *mn, int *mx)
   7483 {
   7484     const char *p = ps->p;
   7485     long a = -1, b = -1;
   7486     int comma = 0;
   7487     while (p < ps->e && isdigit((unsigned char)*p)) { a = (a < 0 ? 0 : a) * 10 + *p++ - '0'; if (a > RE_DUP_MAX + 1) a = RE_DUP_MAX + 1; }
   7488     if (p < ps->e && *p == ',') {
   7489         comma = 1; p++;
   7490         while (p < ps->e && isdigit((unsigned char)*p)) { b = (b < 0 ? 0 : b) * 10 + *p++ - '0'; if (b > RE_DUP_MAX + 1) b = RE_DUP_MAX + 1; }
   7491     }
   7492     if (ps->ere ? !(p < ps->e && *p == '}') : !(p + 1 < ps->e && p[0] == '\\' && p[1] == '}')) {
   7493         if (ps->ere) return 0;
   7494         re_die(p >= ps->e ? "Unmatched \\{" : "Invalid content of \\{\\}");
   7495     }
   7496     if (a < 0 && !comma) { if (ps->ere) return 0; re_die("Invalid content of \\{\\}"); }
   7497     p += ps->ere ? 1 : 2;
   7498     if (a < 0) a = 0;
   7499     if (!comma) b = a;
   7500     if (b >= 0 && a > b) re_die("Invalid content of \\{\\}");
   7501     if (a > RE_DUP_MAX || b > RE_DUP_MAX) re_die("Regular expression too big");
   7502     *mn = a; *mx = b;
   7503     ps->p = p;
   7504     return 1;
   7505 }
   7506 
   7507 /* one atom, no repetition. *anchor says it was the ^ of a BRE, after which a * is still an ordinary character */
   7508 static struct rnode *re_atom(struct rparse *ps, int start, int *anchor)
   7509 {
   7510     const char *p = ps->p;
   7511     int c = (unsigned char)*p++, ere = ps->ere;
   7512     *anchor = 0;
   7513     if (c == '\\') {
   7514         if (p >= ps->e) re_die("Trailing backslash");
   7515         c = (unsigned char)*p++;
   7516         if (!ere && c == '(') goto group;
   7517         switch (c) {
   7518         case 'w': case 'W': case 's': case 'S': ps->p = p; return re_shorthand(ps, c);
   7519         case 'b': ps->p = p; return re_assert(R_WB);
   7520         case 'B': ps->p = p; return re_assert(R_NWB);
   7521         case '<': ps->p = p; return re_assert(R_WBEG);
   7522         case '>': ps->p = p; return re_assert(R_WEND);
   7523         case '`': ps->p = p; return re_assert(R_BOS);
   7524         case '\'': ps->p = p; return re_assert(R_EOS);
   7525         }
   7526         if (c >= '1' && c <= '9') {
   7527             struct rnode *n;
   7528             if (c - '0' > ps->local) re_die("Invalid back reference");
   7529             n = rn(N_BREF, NULL, NULL);
   7530             n->c = ps->re->ngrp - ps->local + c - '0';
   7531             ps->re->backref = 1;
   7532             ps->p = p;
   7533             return n;
   7534         }
   7535         if (ps->sed) {
   7536             int v = c == 'n' ? '\n' : c == 't' ? '\t' : c == 'f' ? '\f' : c == 'v' ? '\v' : c == 'a' ? 7 : c == 'r' ? '\r' : -1;
   7537             if (c == 'x' && p + 1 < ps->e && isxdigit((unsigned char)p[0]) && isxdigit((unsigned char)p[1])) {
   7538                 v = (isdigit((unsigned char)p[0]) ? p[0] - '0' : (p[0] | 32) - 'a' + 10) * 16 + (isdigit((unsigned char)p[1]) ? p[1] - '0' : (p[1] | 32) - 'a' + 10);
   7539                 p += 2;
   7540             }
   7541             if (v >= 0) c = v;
   7542         }
   7543         ps->p = p;
   7544         return re_ch(ps, c);
   7545     }
   7546     if (ere && c == '(') {
   7547     group:
   7548         {
   7549             struct rnode *g = rn(N_GRP, NULL, NULL);
   7550             g->c = ++ps->re->ngrp; ps->local++;
   7551             ps->p = p; ps->depth++;
   7552             g->a = re_alt(ps);
   7553             ps->depth--;
   7554             if (ps->ere ? !(ps->p < ps->e && *ps->p == ')') : !(ps->p + 1 < ps->e && ps->p[0] == '\\' && ps->p[1] == ')'))
   7555                 re_die("Unmatched ( or \\(");
   7556             ps->p += ps->ere ? 1 : 2;
   7557             return g;
   7558         }
   7559     }
   7560     ps->p = p;
   7561     switch (c) {
   7562     case '.': return rn(N_ANY, NULL, NULL);
   7563     case '[': return re_bracket(ps);
   7564     case '^':
   7565         if (ere) return re_assert(R_BOL);
   7566         if (start) { *anchor = 1; return re_assert(R_BOL); }
   7567         break;
   7568     case '$':
   7569         if (ere || p >= ps->e || (p + 1 < ps->e && p[0] == '\\' && (p[1] == ')' || p[1] == '|'))) return re_assert(R_EOL);
   7570         break;
   7571     }
   7572     return re_ch(ps, c);
   7573 }
   7574 
   7575 /* is there a repetition operator next? */
   7576 static int re_op(struct rparse *ps, int *mn, int *mx)
   7577 {
   7578     const char *p = ps->p;
   7579     int bs = 0;
   7580     if (p >= ps->e) return 0;
   7581     if (!ps->ere && *p == '\\') { if (p + 1 >= ps->e) return 0; bs = 1; p++; }
   7582     if (!bs && *p == '*') { *mn = 0; *mx = -1; ps->p = p + 1; return 1; }
   7583     if (bs == ps->ere) return 0;
   7584     if (*p == '+') { *mn = 1; *mx = -1; ps->p = p + 1; return 1; }
   7585     if (*p == '?') { *mn = 0; *mx = 1; ps->p = p + 1; return 1; }
   7586     if (*p == '{') { const char *save = ps->p; ps->p = p + 1; if (re_interval(ps, mn, mx)) return 1; ps->p = save; }
   7587     return 0;
   7588 }
   7589 
   7590 static struct rnode *re_cat(struct rparse *ps)
   7591 {
   7592     struct rnode *head = NULL;
   7593     int start = 1;
   7594     while (ps->p < ps->e) {
   7595         struct rnode *n;
   7596         int anchor, mn, mx;
   7597         if (ps->ere) {
   7598             if (*ps->p == '|' || (*ps->p == ')' && ps->depth)) break;
   7599         } else if (*ps->p == '\\' && ps->p + 1 < ps->e && (ps->p[1] == '|' || ps->p[1] == ')')) {
   7600             if (ps->p[1] == ')' && !ps->depth) re_die("Unmatched ) or \\)");
   7601             break;
   7602         }
   7603         if (start && ps->ere && re_op(ps, &mn, &mx)) continue;
   7604         n = re_atom(ps, start, &anchor);
   7605         start = anchor;
   7606         if (!anchor)
   7607             while (re_op(ps, &mn, &mx)) {
   7608                 struct rnode *r = rn(N_REP, n, NULL);
   7609                 r->min = mn; r->max = mx;
   7610                 n = r;
   7611             }
   7612         head = head ? rn(N_CAT, head, n) : n;
   7613     }
   7614     return head ? head : rn(N_EMPTY, NULL, NULL);
   7615 }
   7616 
   7617 static struct rnode *re_alt(struct rparse *ps)
   7618 {
   7619     struct rnode *n = re_cat(ps);
   7620     while (ps->p < ps->e && (ps->ere ? *ps->p == '|' : (*ps->p == '\\' && ps->p + 1 < ps->e && ps->p[1] == '|'))) {
   7621         ps->p += ps->ere ? 1 : 2;
   7622         n = rn(N_ALT, n, re_cat(ps));
   7623     }
   7624     return n;
   7625 }
   7626 
   7627 static struct rnode *re_parse(struct regex *re, const char *pat, size_t len, int ere, int sed)
   7628 {
   7629     struct rparse ps = { pat, pat + len, ere, sed, 0, 0, re };
   7630     return re_alt(&ps);
   7631 }
   7632 
   7633 static struct rnode *re_literal(struct regex *re, const char *pat, size_t len)
   7634 {
   7635     struct rparse ps = { pat, pat + len, 0, 0, 0, 0, re };
   7636     struct rnode *n = NULL;
   7637     size_t i;
   7638     for (i = 0; i < len; i++) n = rn_cat(n, re_ch(&ps, (unsigned char)pat[i]));
   7639     return n ? n : rn(N_EMPTY, NULL, NULL);
   7640 }
   7641 
   7642 static int re_put(struct regex *re, int op, int x, int y)
   7643 {
   7644     if (re->n == re->cap) {
   7645         if (re->cap > (1 << 22)) re_die("Regular expression too big");
   7646         re->cap = re->cap ? re->cap * 2 : 64;
   7647         re->prog = xrealloc(re->prog, re->cap * sizeof *re->prog);
   7648     }
   7649     re->prog[re->n].op = op; re->prog[re->n].x = x; re->prog[re->n].y = y; re->prog[re->n].id = 0;
   7650     return re->n++;
   7651 }
   7652 static int re_split(struct regex *re)
   7653 {
   7654     int j = re_put(re, R_SPLIT, 0, 0);
   7655     re->prog[j].x = re->n; re->prog[j].id = re->nsplit++;
   7656     return j;
   7657 }
   7658 
   7659 static int re_nullable(const struct rnode *n)
   7660 {
   7661     switch (n->t) {
   7662     case N_CHAR: case N_ANY: case N_SET: return 0;
   7663     case N_CAT: return re_nullable(n->a) && re_nullable(n->b);
   7664     case N_ALT: return re_nullable(n->a) || re_nullable(n->b);
   7665     case N_REP: return !n->min || re_nullable(n->a);
   7666     case N_GRP: return re_nullable(n->a);
   7667     }
   7668     return 1;
   7669 }
   7670 
   7671 static void re_emit(struct regex *re, const struct rnode *n)
   7672 {
   7673     int i, j, k;
   7674     switch (n->t) {
   7675     case N_CHAR: re_put(re, R_CHAR, n->c, 0); break;
   7676     case N_ANY: re_put(re, R_ANY, 0, 0); break;
   7677     case N_SET: re_put(re, R_SET, n->c, 0); break;
   7678     case N_ASSERT: re_put(re, n->c, 0, 0); break;
   7679     case N_BREF: re_put(re, R_BREF, n->c, 0); break;
   7680     case N_CAT: re_emit(re, n->a); re_emit(re, n->b); break;
   7681     case N_GRP:
   7682         re_put(re, R_SAVE, 2 * n->c, 0);
   7683         re_emit(re, n->a);
   7684         re_put(re, R_SAVE, 2 * n->c + 1, 0);
   7685         break;
   7686     case N_ALT:
   7687         j = re_split(re);
   7688         re_emit(re, n->a);
   7689         k = re_put(re, R_JMP, 0, 0);
   7690         re->prog[j].y = re->n;
   7691         re_emit(re, n->b);
   7692         re->prog[k].x = re->n;
   7693         break;
   7694     case N_REP:
   7695         for (i = 0; i < n->min; i++) re_emit(re, n->a);
   7696         if (n->max < 0) {
   7697             int mk = re_nullable(n->a) ? re->nmark++ : -1;
   7698             j = re_split(re);
   7699             if (mk >= 0) re_put(re, R_MARK, mk, 0);
   7700             re_emit(re, n->a);
   7701             if (mk >= 0) re_put(re, R_PROG, mk, 0);
   7702             re_put(re, R_JMP, j, 0);
   7703             re->prog[j].y = re->n;
   7704         } else if (n->max > n->min) {
   7705             int *js = xmalloc((n->max - n->min) * sizeof *js);
   7706             for (i = 0; i < n->max - n->min; i++) { js[i] = re_split(re); re_emit(re, n->a); }
   7707             for (i = 0; i < n->max - n->min; i++) re->prog[js[i]].y = re->n;
   7708             free(js);
   7709         }
   7710         break;
   7711     }
   7712 }
   7713 
   7714 /* the program for a tree. the group slots come first, then one slot for each loop that could match nothing */
   7715 static void re_finish(struct regex *re, struct rnode *n)
   7716 {
   7717     int i;
   7718     re_emit(re, n);
   7719     re_put(re, R_MATCH, 0, 0);
   7720     for (i = 0; i < re->n; i++) if (re->prog[i].op == R_MARK || re->prog[i].op == R_PROG) re->prog[i].x += 2 * (re->ngrp + 1);
   7721     re->nslot = 2 * (re->ngrp + 1) + re->nmark;
   7722     if (re->prog[0].op == R_CHAR) re->first = re->prog[0].x;
   7723 }
   7724 
   7725 static int word_at(const char *s, size_t len, long i) { return i >= 0 && (size_t)i < len && (isalnum((unsigned char)s[i]) || s[i] == '_'); }
   7726 
   7727 struct rframe { int pc, slot; long v; };
   7728 
   7729 /* the leftmost match at or after start. caps gets 2 * (ngrp + 1) offsets, -1 for a group that didn't take part.
   7730  * longest 0 stops at the first way to match, which is all a yes-or-no question needs */
   7731 static int re_exec(const struct regex *re, const char *s, size_t len, size_t start, int longest, long *caps)
   7732 {
   7733     static struct rframe *stk;
   7734     static size_t stkcap;
   7735     static long *work;
   7736     static size_t workcap;
   7737     static uint32_t *seen, gen;
   7738     static size_t seencap;
   7739     size_t st, stride = len + 1, need = (size_t)re->nsplit * stride;
   7740     int memo = !re->backref && need && need <= (1u << 26), ncap = 2 * (re->ngrp + 1);
   7741     const struct rinst *prog = re->prog;
   7742     if (workcap < (size_t)re->nslot) { workcap = re->nslot; work = xrealloc(work, workcap * sizeof *work); }
   7743     if (memo) {
   7744         if (seencap < need) { seencap = need; seen = xrealloc(seen, seencap * sizeof *seen); memset(seen, 0, seencap * sizeof *seen); gen = 0; }
   7745         if (++gen == 0) { memset(seen, 0, seencap * sizeof *seen); gen = 1; }
   7746     }
   7747     for (st = start; st <= len; st++) {
   7748         long best = -1;
   7749         size_t sp = 0;
   7750         int pc = 0, i;
   7751         long pos = st;
   7752         if (re->first >= 0) {
   7753             const char *q = memchr(s + st, re->first, len - st);
   7754             if (!q) return 0;
   7755             st = pos = q - s;
   7756         }
   7757         for (i = 0; i < re->nslot; i++) work[i] = -1;
   7758         for (;;) {
   7759             const struct rinst *in = &prog[pc];
   7760             switch (in->op) {
   7761             case R_CHAR: if ((size_t)pos < len && (unsigned char)s[pos] == in->x) { pos++; pc++; continue; } goto fail;
   7762             case R_ANY: if ((size_t)pos < len) { pos++; pc++; continue; } goto fail;
   7763             case R_SET: if ((size_t)pos < len && SET_HAS(re->sets[in->x], s[pos])) { pos++; pc++; continue; } goto fail;
   7764             case R_SPLIT:
   7765                 if (memo) {
   7766                     uint32_t *m = &seen[(size_t)in->id * stride + pos];
   7767                     if (*m == gen) goto fail;
   7768                     *m = gen;
   7769                 }
   7770                 if (sp == stkcap) { stkcap = stkcap ? stkcap * 2 : 256; stk = xrealloc(stk, stkcap * sizeof *stk); }
   7771                 stk[sp].pc = in->y; stk[sp].v = pos; sp++;
   7772                 pc = in->x;
   7773                 continue;
   7774             case R_JMP: pc = in->x; continue;
   7775             case R_SAVE: case R_MARK:
   7776                 if (sp == stkcap) { stkcap = stkcap ? stkcap * 2 : 256; stk = xrealloc(stk, stkcap * sizeof *stk); }
   7777                 stk[sp].slot = in->x; stk[sp].pc = -1; stk[sp].v = work[in->x]; sp++;
   7778                 work[in->x] = pos; pc++;
   7779                 continue;
   7780             case R_PROG: if (work[in->x] == pos) goto fail; pc++; continue;
   7781             case R_BOL: if (pos == 0 || (re->ml && s[pos - 1] == '\n')) { pc++; continue; } goto fail;
   7782             case R_EOL: if ((size_t)pos == len || (re->ml && s[pos] == '\n')) { pc++; continue; } goto fail;
   7783             case R_BOS: if (pos == 0) { pc++; continue; } goto fail;
   7784             case R_EOS: if ((size_t)pos == len) { pc++; continue; } goto fail;
   7785             case R_WB: if (word_at(s, len, pos - 1) != word_at(s, len, pos)) { pc++; continue; } goto fail;
   7786             case R_NWB: if (word_at(s, len, pos - 1) == word_at(s, len, pos)) { pc++; continue; } goto fail;
   7787             case R_WBEG: if (!word_at(s, len, pos - 1) && word_at(s, len, pos)) { pc++; continue; } goto fail;
   7788             case R_WEND: if (word_at(s, len, pos - 1) && !word_at(s, len, pos)) { pc++; continue; } goto fail;
   7789             case R_BEFORE: if (!word_at(s, len, pos - 1)) { pc++; continue; } goto fail;
   7790             case R_AFTER: if (!word_at(s, len, pos)) { pc++; continue; } goto fail;
   7791             case R_BREF: {
   7792                 long a = work[2 * in->x], b = work[2 * in->x + 1], n;
   7793                 if (a < 0 || b < 0) goto fail;
   7794                 n = b - a;
   7795                 if ((size_t)(pos + n) > len || (re->icase ? strncasecmp(s + a, s + pos, n) : memcmp(s + a, s + pos, n))) goto fail;
   7796                 pos += n; pc++;
   7797                 continue;
   7798             }
   7799             case R_MATCH:
   7800                 if (pos > best) {
   7801                     best = pos;
   7802                     if (caps) { memcpy(caps, work, ncap * sizeof *caps); caps[0] = st; caps[1] = pos; }
   7803                 }
   7804                 if (!longest || (size_t)pos == len) return 1;
   7805                 goto fail;
   7806             }
   7807         fail:
   7808             for (;;) {
   7809                 if (!sp) goto done;
   7810                 sp--;
   7811                 if (stk[sp].pc < 0) work[stk[sp].slot] = stk[sp].v;
   7812                 else { pc = stk[sp].pc; pos = stk[sp].v; break; }
   7813             }
   7814         }
   7815     done:
   7816         if (best >= 0) return 1;
   7817     }
   7818     return 0;
   7819 }
   7820 
   7821 /* ---- reading lines ----
   7822  * a chunk at a time, so grep and sed can start answering while a pipe is still filling. a line is good until the next call */
   7823 
   7824 struct lr { int fd, eof, err, binary; char *buf; size_t cap, pos, end, scan; };
   7825 
   7826 static void lr_init(struct lr *r, int fd) { memset(r, 0, sizeof *r); r->fd = fd; }
   7827 
   7828 static int lr_fill(struct lr *r)
   7829 {
   7830     ssize_t n;
   7831     if (r->pos) {
   7832         memmove(r->buf, r->buf + r->pos, r->end - r->pos);
   7833         r->scan -= r->pos; r->end -= r->pos; r->pos = 0;
   7834     }
   7835     if (r->end == r->cap) { r->cap = r->cap ? r->cap * 2 : 65536; r->buf = xrealloc(r->buf, r->cap); }
   7836     do n = read(r->fd, r->buf + r->end, r->cap - r->end); while (n < 0 && errno == EINTR);
   7837     if (n <= 0) { if (n < 0) r->err = errno; r->eof = 1; return 0; }
   7838     if (memchr(r->buf + r->end, 0, n)) r->binary = 1;
   7839     r->end += n;
   7840     return 1;
   7841 }
   7842 
   7843 static int lr_line(struct lr *r, char **s, size_t *len, int *nl)
   7844 {
   7845     for (;;) {
   7846         char *e = r->end > r->scan ? memchr(r->buf + r->scan, '\n', r->end - r->scan) : NULL;
   7847         if (e) {
   7848             *s = r->buf + r->pos; *len = e - *s; *nl = 1;
   7849             r->pos = r->scan = e - r->buf + 1;
   7850             return 1;
   7851         }
   7852         r->scan = r->end;
   7853         if (r->eof) {
   7854             if (r->pos == r->end) return 0;
   7855             *s = r->buf + r->pos; *len = r->end - r->pos; *nl = 0;
   7856             r->pos = r->end;
   7857             return 1;
   7858         }
   7859         lr_fill(r);
   7860     }
   7861 }
   7862 
   7863 /* is there more after the line just read? sed needs it for $. a line from before is gone once this reads */
   7864 static int lr_more(struct lr *r) { return r->pos < r->end || (!r->eof && lr_fill(r)); }
   7865 
   7866 /* ---- grep ---- */
   7867 
   7868 static struct regex *g_re;
   7869 static int g_invert, g_count, g_list, g_nolist, g_num, g_name, g_only, g_quiet, g_nomsg, g_byte, g_null, g_text, g_recurse,
   7870     g_dirs, g_ctx, g_lbuf, g_any, g_err, g_printed;
   7871 static long g_after, g_before, g_max = -1, *g_caps;
   7872 static char **g_inc, **g_exc, **g_excd;
   7873 static int g_ninc, g_nexc, g_nexcd;
   7874 static const char *g_label = "(standard input)";
   7875 static const char *gf_name;
   7876 static int gf_show;
   7877 static long gf_last;
   7878 
   7879 static void g_prefix(long no, long off, int sep)
   7880 {
   7881     if (gf_show) { fputs(gf_name, stdout); putchar(g_null ? 0 : sep); }
   7882     if (g_num) printf("%ld%c", no, sep);
   7883     if (g_byte) printf("%ld%c", off, sep);
   7884 }
   7885 
   7886 static void g_line(long no, long off, const char *s, size_t len, int sep)
   7887 {
   7888     if (g_ctx && g_printed && !(gf_last >= 0 && no == gf_last + 1)) puts("--");
   7889     g_printed = 1; gf_last = no;
   7890     if (g_only) {
   7891         size_t st = 0;
   7892         if (sep != ':' || g_invert) return;
   7893         while (st <= len && re_exec(g_re, s, len, st, 1, g_caps)) {
   7894             if (g_caps[1] == g_caps[0]) { st = g_caps[1] + 1; continue; }
   7895             g_prefix(no, off + g_caps[0], sep);
   7896             fwrite(s + g_caps[0], 1, g_caps[1] - g_caps[0], stdout);
   7897             putchar('\n');
   7898             st = g_caps[1];
   7899         }
   7900     } else {
   7901         g_prefix(no, off, sep);
   7902         fwrite(s, 1, len, stdout);
   7903         putchar('\n');
   7904     }
   7905     if (g_lbuf) fflush(stdout);
   7906 }
   7907 
   7908 struct held { char *s; size_t len, cap; long no, off; };
   7909 
   7910 static long grep_fd(int fd)
   7911 {
   7912     struct lr r;
   7913     struct held *ring = NULL;
   7914     char *s;
   7915     size_t len;
   7916     int nl, done = 0;
   7917     long no = 0, off = 0, count = 0, left = 0, j;
   7918     lr_init(&r, fd);
   7919     gf_last = -1;
   7920     if (g_before) { ring = xmalloc(g_before * sizeof *ring); memset(ring, 0, g_before * sizeof *ring); }
   7921     while (lr_line(&r, &s, &len, &nl)) {
   7922         int sel;
   7923         no++;
   7924         if (r.binary && g_text == 2) { count = 0; break; }
   7925         if (done) {
   7926             if (left-- <= 0) break;
   7927             g_line(no, off, s, len, '-');
   7928         } else if ((sel = re_exec(g_re, s, len, 0, 0, NULL) != g_invert)) {
   7929             count++; g_any = 1;
   7930             if (g_quiet) exit(0);
   7931             if (g_list || g_nolist) break;
   7932             if (!g_count) {
   7933                 if (r.binary && !g_text) { say("%s: binary file matches", gf_name); break; }
   7934                 for (j = no - g_before; j < no; j++)
   7935                     if (j >= 1 && j > gf_last && ring[j % g_before].no == j) g_line(j, ring[j % g_before].off, ring[j % g_before].s, ring[j % g_before].len, '-');
   7936                 g_line(no, off, s, len, ':');
   7937                 left = g_after;
   7938             }
   7939             if (g_max >= 0 && count >= g_max) { done = 1; if (g_count || !left) break; }
   7940         } else if (!g_count && !g_list && !g_nolist) {
   7941             if (left > 0) { left--; g_line(no, off, s, len, '-'); }
   7942             else if (g_before) {
   7943                 struct held *h = &ring[no % g_before];
   7944                 if (h->cap < len) { h->cap = len + 64; h->s = xrealloc(h->s, h->cap); }
   7945                 memcpy(h->s, s, len); h->len = len; h->no = no; h->off = off;
   7946             }
   7947         }
   7948         off += len + nl;
   7949     }
   7950     if (r.err) { if (!g_nomsg) { errno = r.err; perr("%s", gf_name); } g_err = 1; }
   7951     free(r.buf);
   7952     if (ring) { for (j = 0; j < g_before; j++) free(ring[j].s); free(ring); }
   7953     return count;
   7954 }
   7955 
   7956 static int name_listed(char **v, int n, const char *path)
   7957 {
   7958     const char *b = base_of(path);
   7959     int i;
   7960     for (i = 0; i < n; i++) if (glob_match(v[i], b) || glob_match(v[i], path)) return 1;
   7961     return 0;
   7962 }
   7963 
   7964 static int cmp_names(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
   7965 
   7966 static const char g_dot[] = ".";
   7967 
   7968 static void grep_path(const char *path, int top)
   7969 {
   7970     struct stat st;
   7971     int fd;
   7972     long count;
   7973     const char *shown = path;
   7974     if (top && !strcmp(path, "-")) { fd = 0; shown = g_label; goto go; }
   7975     if (g_recurse || g_dirs) {
   7976         if ((top || g_recurse == 2 ? stat(path, &st) : lstat(path, &st)) < 0) {
   7977             if (!g_nomsg) perr("%s", path);
   7978             g_err = 1;
   7979             return;
   7980         }
   7981         if (S_ISLNK(st.st_mode)) return;
   7982         if (S_ISDIR(st.st_mode)) {
   7983             if (g_dirs == 1 || (g_nexcd && strcmp(path, ".") && name_listed(g_excd, g_nexcd, path))) return;
   7984             if (g_recurse) {
   7985                 DIR *d = opendir(path);
   7986                 struct dirent *e;
   7987                 char **v = NULL;
   7988                 int n = 0, cap = 0, i;
   7989                 if (!d) { if (!g_nomsg) perr("%s", path); g_err = 1; return; }
   7990                 while ((e = readdir(d))) {
   7991                     if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
   7992                     if (n == cap) { cap = cap ? cap * 2 : 32; v = xrealloc(v, cap * sizeof *v); }
   7993                     v[n++] = xstrdup(e->d_name);
   7994                 }
   7995                 closedir(d);
   7996                 qsort(v, n, sizeof *v, cmp_names);
   7997                 for (i = 0; i < n; i++) {
   7998                     size_t pl = path == g_dot ? 0 : strlen(path);
   7999                     char *child = xmalloc(pl + strlen(v[i]) + 2);
   8000                     memcpy(child, path, pl);
   8001                     if (pl && path[pl - 1] != '/') child[pl++] = '/';
   8002                     strcpy(child + pl, v[i]);
   8003                     grep_path(child, 0);
   8004                     free(child); free(v[i]);
   8005                 }
   8006                 free(v);
   8007                 return;
   8008             }
   8009         } else if (!top && !S_ISREG(st.st_mode)) return;
   8010     }
   8011     if ((g_ninc && !name_listed(g_inc, g_ninc, path)) || (g_nexc && name_listed(g_exc, g_nexc, path))) return;
   8012     fd = open(path, O_RDONLY);
   8013     if (fd < 0) { if (!g_nomsg) perr("%s", path); g_err = 1; return; }
   8014 go:
   8015     gf_name = shown;
   8016     gf_show = g_name > 0 || (g_name < 0 && !top);
   8017     count = grep_fd(fd);
   8018     if (fd) close(fd);
   8019     if (g_count) {
   8020         if (gf_show) { fputs(shown, stdout); putchar(g_null ? 0 : ':'); }
   8021         printf("%ld\n", count);
   8022     }
   8023     if ((g_list && count) || (g_nolist && !count)) { fputs(shown, stdout); putchar(g_null ? 0 : '\n'); }
   8024 }
   8025 
   8026 static int t_grep(int argc, char **argv)
   8027 {
   8028     static const struct opt lo[] = {
   8029         { "extended-regexp", 0, 'E' }, { "fixed-strings", 0, 'F' }, { "basic-regexp", 0, 'G' }, { "perl-regexp", 0, 'P' },
   8030         { "regexp", 1, 'e' }, { "file", 1, 'f' }, { "ignore-case", 0, 'i' }, { "no-ignore-case", 0, 'j' }, { "invert-match", 0, 'v' },
   8031         { "word-regexp", 0, 'w' }, { "line-regexp", 0, 'x' }, { "count", 0, 'c' }, { "color", 2, 'k' }, { "colour", 2, 'k' },
   8032         { "files-without-match", 0, 'L' }, { "files-with-matches", 0, 'l' }, { "max-count", 1, 'm' }, { "only-matching", 0, 'o' },
   8033         { "quiet", 0, 'q' }, { "silent", 0, 'q' }, { "no-messages", 0, 's' }, { "byte-offset", 0, 'b' }, { "with-filename", 0, 'H' },
   8034         { "no-filename", 0, 'h' }, { "label", 1, 300 }, { "line-number", 0, 'n' }, { "null", 0, 'Z' }, { "text", 0, 'a' },
   8035         { "binary-files", 1, 301 }, { "directories", 1, 'd' }, { "devices", 1, 'D' }, { "recursive", 0, 'r' },
   8036         { "dereference-recursive", 0, 'R' }, { "include", 1, 'N' }, { "exclude", 1, 'X' }, { "exclude-dir", 1, 'Y' },
   8037         { "after-context", 1, 'A' }, { "before-context", 1, 'B' }, { "context", 1, 'C' }, { "line-buffered", 0, 'u' },
   8038         { "binary", 0, 'U' }, { "initial-tab", 0, 'T' }, { NULL, 0, 0 } };
   8039     int c, ere = 0, fixed = 0, icase = 0, w = 0, x = 0, havepat = 0, digits = 0, mode = 0;
   8040     char *pbuf = NULL;
   8041     size_t plen = 0;
   8042     struct rnode *all = NULL;
   8043     const char *p, *e;
   8044     usage_status = 2;
   8045     if (!strcmp(prog, "egrep")) ere = 1;
   8046     if (!strcmp(prog, "fgrep")) fixed = 1;
   8047     g_name = -2;
   8048     opts_reset();
   8049     while ((c = getopts(argc, argv, "EFGPe:f:iyvwxcLlm:oqsbHhnZaIUTd:D:rRA:B:C:V0123456789", lo))) {
   8050         if (c >= '0' && c <= '9') {
   8051             g_after = g_before = (digits ? g_after * 10 : 0) + c - '0';
   8052             g_ctx = digits = 1;
   8053             continue;
   8054         }
   8055         digits = 0;
   8056         switch (c) {
   8057         case 'E': case 'F': case 'G':
   8058             if (mode && mode != c) die(2, "conflicting matchers specified");
   8059             mode = c; ere = c == 'E'; fixed = c == 'F';
   8060             break;
   8061         case 'P': die(2, "Perl matching not supported in a --disable-perl-regexp build");
   8062         case 'e': case 'f': {
   8063             const char *add = optarg;
   8064             size_t al = strlen(optarg);
   8065             char *fb = NULL;
   8066             havepat = 1;
   8067             if (c == 'f') {
   8068                 int fd = open_input(optarg);
   8069                 if (fd < 0 || read_all(fd, &fb, &al) < 0) die(2, "%s: %s", optarg, strerror(errno));
   8070                 if (fd) close(fd);
   8071                 add = fb;
   8072             }
   8073             pbuf = xrealloc(pbuf, plen + al + 2);
   8074             memcpy(pbuf + plen, add, al); plen += al;
   8075             if (c == 'e' || (al && add[al - 1] != '\n')) pbuf[plen++] = '\n';
   8076             free(fb);
   8077             break;
   8078         }
   8079         case 'i': case 'y': icase = 1; break;
   8080         case 'j': icase = 0; break;
   8081         case 'v': g_invert = 1; break;
   8082         case 'w': w = 1; break;
   8083         case 'x': x = 1; break;
   8084         case 'c': g_count = 1; break;
   8085         case 'L': g_nolist = 1; g_list = 0; break;
   8086         case 'l': g_list = 1; g_nolist = 0; break;
   8087         case 'm': { unsigned long m; if (!parse_ulong(optarg, &m)) die(2, "invalid max count"); g_max = m; break; }
   8088         case 'o': g_only = 1; break;
   8089         case 'q': g_quiet = 1; break;
   8090         case 's': g_nomsg = 1; break;
   8091         case 'b': g_byte = 1; break;
   8092         case 'H': g_name = 1; break;
   8093         case 'h': g_name = 0; break;
   8094         case 'n': g_num = 1; break;
   8095         case 'Z': g_null = 1; break;
   8096         case 'a': g_text = 1; break;
   8097         case 'I': g_text = 2; break;
   8098         case 300: g_label = optarg; break;
   8099         case 301: g_text = !strcmp(optarg, "text") ? 1 : !strcmp(optarg, "without-match") ? 2 : !strcmp(optarg, "binary") ? 0 : (die(2, "unknown binary-files type"), 0); break;
   8100         case 'd':
   8101             if (!strcmp(optarg, "recurse")) g_recurse = 1;
   8102             else if (strcmp(optarg, "read") && !(g_dirs = !strcmp(optarg, "skip"))) die(2, "invalid argument '%s' for '--directories'", optarg);
   8103             break;
   8104         case 'r': g_recurse = 1; break;
   8105         case 'R': g_recurse = 2; break;
   8106         case 'N': g_inc = xrealloc(g_inc, (g_ninc + 1) * sizeof *g_inc); g_inc[g_ninc++] = optarg; break;
   8107         case 'X': g_exc = xrealloc(g_exc, (g_nexc + 1) * sizeof *g_exc); g_exc[g_nexc++] = optarg; break;
   8108         case 'Y': g_excd = xrealloc(g_excd, (g_nexcd + 1) * sizeof *g_excd); g_excd[g_nexcd++] = optarg; break;
   8109         case 'A': case 'B': case 'C': {
   8110             unsigned long n;
   8111             if (!parse_ulong(optarg, &n)) die(2, "%s: invalid context length argument", optarg);
   8112             if (c != 'B') g_after = n;
   8113             if (c != 'A') g_before = n;
   8114             g_ctx = 1;
   8115             break;
   8116         }
   8117         case 'u': g_lbuf = 1; break;
   8118         case 'V': printf("grep (rifle) " VERSION "\n"); return 0;
   8119         }
   8120     }
   8121     if (!havepat) {
   8122         if (!nops) { say("no pattern given"); usage_error(); }
   8123         p = ops[0];
   8124         pbuf = xmalloc(strlen(p) + 2);
   8125         plen = strlen(p);
   8126         memcpy(pbuf, p, plen); pbuf[plen++] = '\n';
   8127         ops++; nops--;
   8128     }
   8129     g_re = re_new(icase);
   8130     for (p = pbuf; p < pbuf + plen; p = e + 1) {
   8131         struct rnode *n;
   8132         e = memchr(p, '\n', pbuf + plen - p);
   8133         n = fixed ? re_literal(g_re, p, e - p) : re_parse(g_re, p, e - p, ere, 0);
   8134         all = all ? rn(N_ALT, all, n) : n;
   8135     }
   8136     if (!all) { all = rn(N_SET, NULL, NULL); all->c = re_newset(g_re); }
   8137     if (x) all = rn(N_CAT, re_assert(R_BOL), rn(N_CAT, all, re_assert(R_EOL)));
   8138     else if (w) all = rn(N_CAT, re_assert(R_BEFORE), rn(N_CAT, all, re_assert(R_AFTER)));
   8139     re_finish(g_re, all);
   8140     g_caps = xmalloc(2 * (g_re->ngrp + 1) * sizeof *g_caps);
   8141     if (g_name == -2) g_name = nops > 1 ? 1 : g_recurse ? -1 : 0;
   8142     if (g_max == 0) return 1;
   8143     if (!nops) {
   8144         grep_path(g_recurse ? g_dot : "-", 1);
   8145     } else {
   8146         int i;
   8147         for (i = 0; i < nops; i++) grep_path(ops[i], 1);
   8148     }
   8149     if (finish_stdout()) return 2;
   8150     return g_err ? 2 : g_any ? 0 : 1;
   8151 }
   8152 
   8153 /* ---- sed ---- */
   8154 
   8155 struct saddr { int t; long n, step; struct regex *re; };   /* t: 0 none, n line, $ last, r regex, ~ first~step, + addr1,+N, % addr1,~N */
   8156 struct srep { int kind; char *s; size_t len; int n; };      /* kind: 0 text, 1 group, 2 case change \U \L \u \l \E */
   8157 struct scmd {
   8158     struct saddr a1, a2;
   8159     int c, neg, active, jump, wf, nrep, g, p, nth;
   8160     long end, num;
   8161     char *text; size_t tlen;
   8162     struct regex *re;
   8163     struct srep *rep;
   8164 };
   8165 struct sbuf { char *p; size_t len, cap; int chomped; };
   8166 struct sout { FILE *f; int missing; };
   8167 struct sfile { char *name; struct sout o; };
   8168 
   8169 static struct scmd *sc;
   8170 static int nsc, nflag, sep_files, ere_sed, inplace, quit_now, replaced;
   8171 static const char *inplace_suffix;
   8172 static long s_lineno, s_wrap = 70;
   8173 static int s_status, s_next, s_end, s_open;
   8174 static char **s_files;
   8175 static const char *s_fname = "-";
   8176 static struct lr s_lr;
   8177 static struct sbuf s_ps, s_hs;
   8178 static struct sout s_stdout, *s_out;
   8179 static struct sfile *s_wfiles;
   8180 static int s_nwfiles;
   8181 static struct { int kind; char *s; size_t len; } *s_app;
   8182 static int s_napp;
   8183 static struct regex *s_lastre;
   8184 static long *s_caps;
   8185 static int s_ncaps;
   8186 
   8187 static void sb_add(struct sbuf *b, const char *s, size_t n)
   8188 {
   8189     if (b->len + n + 1 > b->cap) { b->cap = (b->len + n + 1) * 2; b->p = xrealloc(b->p, b->cap); }
   8190     memcpy(b->p + b->len, s, n);
   8191     b->len += n;
   8192 }
   8193 
   8194 static void s_put(struct sout *o, const char *p, size_t n, int nl)
   8195 {
   8196     if (o->missing) { putc('\n', o->f); o->missing = 0; }
   8197     fwrite(p, 1, n, o->f);
   8198     if (nl) putc('\n', o->f); else o->missing = 1;
   8199 }
   8200 static void s_raw(struct sout *o, const char *p, size_t n)
   8201 {
   8202     if (o->missing) { putc('\n', o->f); o->missing = 0; }
   8203     fwrite(p, 1, n, o->f);
   8204 }
   8205 
   8206 /* ---- reading the script ---- */
   8207 
   8208 static const char *sp, *se, *sstart;
   8209 static __attribute__((noreturn)) void sdie(const char *m) { die(1, "-e expression #1, char %ld: %s", (long)(sp - sstart), m); }
   8210 
   8211 static void s_skip(void) { while (sp < se && (*sp == ' ' || *sp == '\t')) sp++; }
   8212 static void s_skipall(void) { while (sp < se && (isspace((unsigned char)*sp) || *sp == ';')) sp++; }
   8213 
   8214 static long s_num(void)
   8215 {
   8216     long n = 0;
   8217     while (sp < se && isdigit((unsigned char)*sp)) n = n * 10 + *sp++ - '0';
   8218     return n;
   8219 }
   8220 
   8221 /* up to the next unescaped delimiter. \delim is the delimiter itself, the rest of the escapes stay for whoever reads them */
   8222 static char *s_slash(int delim, size_t *len, int regex)
   8223 {
   8224     char *b = xmalloc(se - sp + 1);
   8225     size_t n = 0;
   8226     while (sp < se) {
   8227         int c = *sp++;
   8228         if (c == delim) { *len = n; b[n] = 0; return b; }
   8229         if (c == '\\' && sp < se) {
   8230             if (*sp == delim) { b[n++] = *sp++; continue; }
   8231             if (*sp == '\n' && regex) { b[n++] = '\n'; sp++; continue; }
   8232             b[n++] = c; b[n++] = *sp++;
   8233             continue;
   8234         }
   8235         if (c == '\n' && regex) break;
   8236         b[n++] = c;
   8237         if (c == '[' && regex) { /* the delimiter means nothing inside [...], as in s:[[:space:]]:: */
   8238             const char *q = sp;
   8239             if (q < se && *q == '^') q++;
   8240             if (q < se && *q == ']') q++;
   8241             while (q < se && *q != ']' && *q != '\n') {
   8242                 if (*q == '[' && q + 1 < se && strchr(":.=", q[1])) {
   8243                     const char *e = q + 2;
   8244                     while (e + 1 < se && !(e[0] == q[1] && e[1] == ']')) e++;
   8245                     if (e + 1 >= se) break;
   8246                     q = e + 2;
   8247                 } else q++;
   8248             }
   8249             if (q < se && *q == ']') { while (sp <= q) b[n++] = *sp++; }
   8250         }
   8251     }
   8252     sdie("unterminated `s' command");
   8253 }
   8254 
   8255 static struct regex *s_regex(const char *pat, size_t len, int icase, int ml)
   8256 {
   8257     struct regex *re;
   8258     struct rnode *n;
   8259     if (!len) return NULL;
   8260     re = re_new(icase);
   8261     re->ml = ml;
   8262     n = re_parse(re, pat, len, ere_sed, 1);
   8263     re_finish(re, n);
   8264     if (re->ngrp + 1 > s_ncaps) { s_ncaps = re->ngrp + 1; s_caps = xrealloc(s_caps, 2 * s_ncaps * sizeof *s_caps); }
   8265     return re;
   8266 }
   8267 
   8268 static int s_addr(struct saddr *a)
   8269 {
   8270     memset(a, 0, sizeof *a);
   8271     if (sp >= se) return 0;
   8272     if (isdigit((unsigned char)*sp)) {
   8273         a->n = s_num();
   8274         if (sp < se && *sp == '~') { sp++; a->t = '~'; a->step = s_num(); }
   8275         else a->t = 'n';
   8276     } else if (*sp == '$') { sp++; a->t = '$'; }
   8277     else if (*sp == '/' || *sp == '\\') {
   8278         int d = '/', icase = 0, ml = 0;
   8279         char *pat;
   8280         size_t l;
   8281         if (*sp == '\\') { sp++; if (sp >= se) sdie("unexpected `,'"); d = *sp; }
   8282         sp++;
   8283         pat = s_slash(d, &l, 1);
   8284         for (; sp < se; sp++) { if (*sp == 'I') icase = 1; else if (*sp == 'M') ml = 1; else break; }
   8285         a->t = 'r';
   8286         a->re = s_regex(pat, l, icase, ml);
   8287     } else return 0;
   8288     return 1;
   8289 }
   8290 
   8291 static struct sout *s_wfile(const char *name)
   8292 {
   8293     int i;
   8294     if (!strcmp(name, "/dev/stdout")) return &s_stdout;
   8295     for (i = 0; i < s_nwfiles; i++) if (!strcmp(s_wfiles[i].name, name)) return &s_wfiles[i].o;
   8296     s_wfiles = xrealloc(s_wfiles, (s_nwfiles + 1) * sizeof *s_wfiles);
   8297     s_wfiles[s_nwfiles].name = xstrdup(name);
   8298     s_wfiles[s_nwfiles].o.missing = 0;
   8299     s_wfiles[s_nwfiles].o.f = !strcmp(name, "/dev/stderr") ? stderr : fopen(name, "w");
   8300     if (!s_wfiles[s_nwfiles].o.f) die(4, "couldn't open file %s: %s", name, strerror(errno));
   8301     return &s_wfiles[s_nwfiles++].o;
   8302 }
   8303 
   8304 static char *s_rest(void)
   8305 {
   8306     const char *b;
   8307     char *r;
   8308     s_skip();
   8309     b = sp;
   8310     while (sp < se && *sp != '\n') sp++;
   8311     if (b == sp) sdie("missing filename in r/R/w/W commands");
   8312     r = xmalloc(sp - b + 1);
   8313     memcpy(r, b, sp - b); r[sp - b] = 0;
   8314     return r;
   8315 }
   8316 
   8317 static int s_hex(int c) { return isdigit(c) ? c - '0' : (c | 32) - 'a' + 10; }
   8318 
   8319 /* the text of a, i and c: a one-liner, or a backslash and a newline first, a backslash before a newline carries on */
   8320 static void s_text(struct scmd *c)
   8321 {
   8322     struct sbuf b = { 0 };
   8323     s_skip();
   8324     if (sp < se && *sp == '\\') {
   8325         const char *after = ++sp;
   8326         s_skip();
   8327         if (sp < se && *sp == '\n') sp++;
   8328         else sp = after;
   8329     }
   8330     if (sp >= se) sdie("expected \\ after `a', `c' or `i'");
   8331     while (sp < se && *sp != '\n') {
   8332         char ch = *sp++, e;
   8333         if (ch == '\\' && sp < se) {
   8334             e = *sp++;
   8335             if (e == 'n') ch = '\n';
   8336             else if (e == 't') ch = '\t';
   8337             else if (e == 'f') ch = '\f';
   8338             else if (e == 'v') ch = '\v';
   8339             else if (e == 'a') ch = 7;
   8340             else if (e == 'r') ch = '\r';
   8341             else if (e == 'x' && sp + 1 < se && isxdigit((unsigned char)sp[0]) && isxdigit((unsigned char)sp[1])) { ch = s_hex(sp[0]) * 16 + s_hex(sp[1]); sp += 2; }
   8342             else ch = e;
   8343         }
   8344         sb_add(&b, &ch, 1);
   8345     }
   8346     sb_add(&b, "\n", 1);
   8347     c->text = b.p; c->tlen = b.len;
   8348 }
   8349 
   8350 static void s_replacement(struct scmd *c, const char *s, size_t n)
   8351 {
   8352     struct sbuf lit = { 0 };
   8353     size_t i;
   8354     int cap = 0;
   8355     c->rep = NULL; c->nrep = 0;
   8356 #define S_LIT() do { if (lit.len) { c->rep = xrealloc(c->rep, (c->nrep + 1) * sizeof *c->rep); c->rep[c->nrep].kind = 0; c->rep[c->nrep].s = lit.p; c->rep[c->nrep].len = lit.len; c->nrep++; memset(&lit, 0, sizeof lit); } } while (0)
   8357 #define S_PUSH(k, v) do { S_LIT(); c->rep = xrealloc(c->rep, (c->nrep + 1) * sizeof *c->rep); c->rep[c->nrep].kind = (k); c->rep[c->nrep].n = (v); c->nrep++; } while (0)
   8358     for (i = 0; i < n; i++) {
   8359         char ch = s[i];
   8360         if (ch == '&') { S_PUSH(1, 0); continue; }
   8361         if (ch == '\\' && i + 1 < n) {
   8362             ch = s[++i];
   8363             if (isdigit((unsigned char)ch)) { S_PUSH(1, ch - '0'); cap = cap > ch - '0' ? cap : ch - '0'; continue; }
   8364             if (ch == 'U' || ch == 'L' || ch == 'u' || ch == 'l' || ch == 'E') { S_PUSH(2, ch); continue; }
   8365             if (ch == 'n') ch = '\n';
   8366             else if (ch == 't') ch = '\t';
   8367             else if (ch == 'f') ch = '\f';
   8368             else if (ch == 'v') ch = '\v';
   8369             else if (ch == 'a') ch = 7;
   8370             else if (ch == 'r') ch = '\r';
   8371             else if (ch == 'x' && i + 2 < n && isxdigit((unsigned char)s[i + 1]) && isxdigit((unsigned char)s[i + 2])) { ch = s_hex(s[i + 1]) * 16 + s_hex(s[i + 2]); i += 2; }
   8372         }
   8373         sb_add(&lit, &ch, 1);
   8374     }
   8375     S_LIT();
   8376     if (c->re && cap > c->re->ngrp) die(1, "invalid reference \\%d on `s' command's RHS", cap);
   8377 }
   8378 
   8379 static void s_end_of_cmd(void)
   8380 {
   8381     s_skip();
   8382     if (sp >= se || *sp == '\n' || *sp == ';') { if (sp < se) sp++; return; }
   8383     if (*sp == '}' || *sp == '#') return;
   8384     sdie("extra characters after command");
   8385 }
   8386 
   8387 static void s_label(struct scmd *c, int jump)
   8388 {
   8389     const char *b;
   8390     s_skip();
   8391     b = sp;
   8392     while (sp < se && !isspace((unsigned char)*sp) && *sp != ';' && !(jump && *sp == '}')) sp++;
   8393     c->text = xmalloc(sp - b + 1);
   8394     memcpy(c->text, b, sp - b); c->text[sp - b] = 0;
   8395 }
   8396 
   8397 static void s_parse(const char *script, size_t len)
   8398 {
   8399     int *stack = xmalloc((len + 1) * sizeof *stack), depth = 0, i;
   8400     sp = sstart = script; se = script + len;
   8401     for (;;) {
   8402         struct scmd *c;
   8403         s_skipall();
   8404         if (sp >= se) break;
   8405         if (*sp == '#') { while (sp < se && *sp != '\n') sp++; continue; }
   8406         sc = xrealloc(sc, (nsc + 1) * sizeof *sc);
   8407         c = &sc[nsc];
   8408         memset(c, 0, sizeof *c);
   8409         c->jump = -1; c->wf = -1;
   8410         if (s_addr(&c->a1)) {
   8411             s_skip();
   8412             if (sp < se && *sp == ',') {
   8413                 sp++; s_skip();
   8414                 if (sp < se && (*sp == '+' || *sp == '~') && sp + 1 < se && isdigit((unsigned char)sp[1])) {
   8415                     c->a2.t = *sp == '+' ? '+' : '%'; sp++; c->a2.n = s_num();
   8416                 } else if (!s_addr(&c->a2)) sdie("unexpected `,'");
   8417                 else if (c->a2.t == '~') sdie("unexpected `,'");
   8418             }
   8419             if (c->a1.t == 'n' && c->a1.n == 0 && c->a2.t != 'r') sdie("invalid usage of line address 0");
   8420         }
   8421         s_skip();
   8422         while (sp < se && *sp == '!') { c->neg = 1; sp++; s_skip(); }
   8423         if (sp >= se) sdie("missing command");
   8424         c->c = *sp++;
   8425         switch (c->c) {
   8426         case '{': stack[depth++] = nsc; nsc++; continue;
   8427         case '}':
   8428             if (!depth) sdie("unexpected `}'");
   8429             if (c->a1.t) sdie("} doesn't want any addresses");
   8430             sc[stack[--depth]].jump = nsc;
   8431             nsc++;
   8432             s_end_of_cmd();
   8433             continue;
   8434         case ':':
   8435             if (c->a1.t) sdie(": doesn't want any addresses");
   8436             s_label(c, 0);
   8437             if (!*c->text) sdie("\":\" lacks a label");
   8438             break;
   8439         case 'b': case 't': case 'T': s_label(c, 1); s_end_of_cmd(); break;
   8440         case 'a': case 'i': case 'c': s_text(c); break;
   8441         case 'r': c->text = s_rest(); break;
   8442         case 'w': c->text = s_rest(); c->wf = 0; s_wfile(c->text); break;
   8443         case 'q': case 'Q': case 'l': case 'L':
   8444             s_skip();
   8445             c->num = -1;
   8446             if (sp < se && isdigit((unsigned char)*sp)) c->num = s_num();
   8447             s_end_of_cmd();
   8448             break;
   8449         case '=': case 'd': case 'D': case 'g': case 'G': case 'h': case 'H': case 'n': case 'N': case 'p': case 'P': case 'x': case 'z': case 'F':
   8450             s_end_of_cmd();
   8451             break;
   8452         case 'y': {
   8453             char *a, *b;
   8454             size_t la, lb, k, m = 0;
   8455             int d;
   8456             unsigned char map[256];
   8457             if (sp >= se) sdie("unterminated `y' command");
   8458             d = *sp++;
   8459             a = s_slash(d, &la, 0); b = s_slash(d, &lb, 0);
   8460             for (k = 0; k < 256; k++) map[k] = k;
   8461             {
   8462                 char *x = xmalloc(la + 1), *y = xmalloc(lb + 1);
   8463                 size_t nx = 0, ny = 0;
   8464                 for (k = 0; k < la; k++) { if (a[k] == '\\' && k + 1 < la) { k++; x[nx++] = a[k] == 'n' ? '\n' : a[k] == 't' ? '\t' : a[k]; } else x[nx++] = a[k]; }
   8465                 for (k = 0; k < lb; k++) { if (b[k] == '\\' && k + 1 < lb) { k++; y[ny++] = b[k] == 'n' ? '\n' : b[k] == 't' ? '\t' : b[k]; } else y[ny++] = b[k]; }
   8466                 if (nx != ny) sdie("strings for `y' command are different lengths");
   8467                 for (; m < nx; m++) map[(unsigned char)x[m]] = y[m];
   8468             }
   8469             c->text = xmalloc(256); memcpy(c->text, map, 256);
   8470             s_end_of_cmd();
   8471             break;
   8472         }
   8473         case 's': {
   8474             char *pat, *rep;
   8475             size_t lp, lr;
   8476             int d, icase = 0, ml = 0;
   8477             if (sp >= se) sdie("unterminated `s' command");
   8478             d = *sp++;
   8479             pat = s_slash(d, &lp, 1);
   8480             rep = s_slash(d, &lr, 0);
   8481             for (; sp < se; sp++) {
   8482                 if (*sp == 'g' && !c->g) c->g = 1;
   8483                 else if (*sp == 'p' && !c->p) c->p = 1;
   8484                 else if (*sp == 'i' || *sp == 'I') icase = 1;
   8485                 else if (*sp == 'm' || *sp == 'M') ml = 1;
   8486                 else if (isdigit((unsigned char)*sp)) { c->nth = s_num(); sp--; if (!c->nth) sdie("number option to `s' command may not be zero"); }
   8487                 else if (*sp == 'w') { sp++; c->text = s_rest(); c->wf = 0; s_wfile(c->text); break; }
   8488                 else break;
   8489             }
   8490             c->re = s_regex(pat, lp, icase, ml);
   8491             s_replacement(c, rep, lr);
   8492             s_end_of_cmd();
   8493             break;
   8494         }
   8495         default: sdie("unknown command");
   8496         }
   8497         nsc++;
   8498     }
   8499     if (depth) sdie("unmatched `{'");
   8500     for (i = 0; i < nsc; i++) {
   8501         struct scmd *c = &sc[i];
   8502         int k;
   8503         if (c->c != 'b' && c->c != 't' && c->c != 'T') continue;
   8504         if (!*c->text) { c->jump = nsc; continue; }
   8505         for (k = 0; k < nsc; k++) if (sc[k].c == ':' && !strcmp(sc[k].text, c->text)) break;
   8506         if (k == nsc) die(4, "-e expression #1, char 0: can't find label for jump to `%s'", c->text);
   8507         c->jump = k;
   8508     }
   8509     free(stack);
   8510 }
   8511 
   8512 /* ---- running it ---- */
   8513 
   8514 static int s_open_next(void)
   8515 {
   8516     int fd;
   8517     while (s_next < s_end) {
   8518         const char *f = s_files[s_next++];
   8519         fd = open_input(f);
   8520         if (fd < 0) { say("can't read %s: %s", f, strerror(errno)); s_status = 2; continue; }
   8521         lr_init(&s_lr, fd);
   8522         s_open = 1; s_fname = f;
   8523         return 1;
   8524     }
   8525     return 0;
   8526 }
   8527 static void s_close(void) { if (s_lr.fd) close(s_lr.fd); free(s_lr.buf); s_open = 0; }
   8528 
   8529 static int s_getline(void)
   8530 {
   8531     char *s; size_t len; int nl;
   8532     for (;;) {
   8533         if (s_open) {
   8534             if (lr_line(&s_lr, &s, &len, &nl)) {
   8535                 s_ps.len = 0; sb_add(&s_ps, s, len);
   8536                 s_ps.chomped = nl; s_lineno++; replaced = 0;
   8537                 return 1;
   8538             }
   8539             s_close();
   8540         }
   8541         if (!s_open_next()) return 0;
   8542     }
   8543 }
   8544 
   8545 static int s_islast(void)
   8546 {
   8547     for (;;) {
   8548         if (s_open) { if (lr_more(&s_lr)) return 0; s_close(); }
   8549         if (!s_open_next()) return 1;
   8550     }
   8551 }
   8552 
   8553 static int s_match1(struct saddr *a)
   8554 {
   8555     switch (a->t) {
   8556     case 'n': return s_lineno == a->n;
   8557     case '$': return s_islast();
   8558     case '~': return s_lineno >= a->n && (a->step ? (s_lineno - a->n) % a->step == 0 : s_lineno == a->n);
   8559     case 'r': {
   8560         struct regex *re = a->re ? a->re : s_lastre;
   8561         if (!re) die(1, "no previous regular expression");
   8562         s_lastre = re;
   8563         return re_exec(re, s_ps.p, s_ps.len, 0, 0, NULL);
   8564     }
   8565     }
   8566     return 1;
   8567 }
   8568 
   8569 static int s_match(struct scmd *c)
   8570 {
   8571     if (!c->a1.t) return 1;
   8572     if (!c->a2.t) return s_match1(&c->a1);
   8573     if (c->active) {
   8574         if (c->a2.t == 'n' || c->a2.t == '+' || c->a2.t == '%') {
   8575             if (s_lineno >= c->end) c->active = 0;
   8576             return s_lineno <= c->end;
   8577         }
   8578         if (s_match1(&c->a2)) c->active = 0;
   8579         return 1;
   8580     }
   8581     if (!s_match1(&c->a1)) return 0;
   8582     switch (c->a2.t) {
   8583     case 'n': c->end = c->a2.n; break;
   8584     case '+': c->end = s_lineno + c->a2.n; break;
   8585     case '%': c->end = c->a2.n > 0 ? s_lineno + c->a2.n - s_lineno % c->a2.n : s_lineno; break;
   8586     default: c->active = 1; return 1;
   8587     }
   8588     c->active = s_lineno < c->end;
   8589     return 1;
   8590 }
   8591 
   8592 static void s_flush_app(void)
   8593 {
   8594     int i;
   8595     for (i = 0; i < s_napp; i++) {
   8596         if (s_app[i].kind == 0) s_raw(s_out, s_app[i].s, s_app[i].len);
   8597         else {
   8598             int fd = open(s_app[i].s, O_RDONLY);
   8599             char *d; size_t n;
   8600             if (fd >= 0) { if (read_all(fd, &d, &n) == 0) { s_raw(s_out, d, n); free(d); } close(fd); }
   8601         }
   8602     }
   8603     s_napp = 0;
   8604 }
   8605 static void s_queue(int kind, char *s, size_t len)
   8606 {
   8607     s_app = xrealloc(s_app, (s_napp + 1) * sizeof *s_app);
   8608     s_app[s_napp].kind = kind; s_app[s_napp].s = s; s_app[s_napp].len = len; s_napp++;
   8609 }
   8610 
   8611 static void s_list(long width)
   8612 {
   8613     size_t i;
   8614     long col = 0;
   8615     for (i = 0; i < s_ps.len; i++) {
   8616         unsigned char ch = s_ps.p[i];
   8617         char b[8];
   8618         int n;
   8619         switch (ch) {
   8620         case '\\': strcpy(b, "\\\\"); break;
   8621         case 7: strcpy(b, "\\a"); break;
   8622         case '\b': strcpy(b, "\\b"); break;
   8623         case '\f': strcpy(b, "\\f"); break;
   8624         case '\n': strcpy(b, "\\n"); break;
   8625         case '\r': strcpy(b, "\\r"); break;
   8626         case '\t': strcpy(b, "\\t"); break;
   8627         case '\v': strcpy(b, "\\v"); break;
   8628         default:
   8629             if (ch >= 32 && ch < 127) { b[0] = ch; b[1] = 0; }
   8630             else snprintf(b, sizeof b, "\\%03o", ch);
   8631         }
   8632         n = strlen(b);
   8633         if (width > 0 && col + n > width - 1) { s_raw(s_out, "\\\n", 2); col = 0; }
   8634         s_raw(s_out, b, n);
   8635         col += n;
   8636     }
   8637     s_raw(s_out, "$\n", 2);
   8638 }
   8639 
   8640 static void s_case(struct sbuf *b, const char *s, size_t n, int *mode, int *once)
   8641 {
   8642     size_t i;
   8643     for (i = 0; i < n; i++) {
   8644         unsigned char ch = s[i];
   8645         if (*once) { ch = *once == 'u' ? toupper(ch) : tolower(ch); *once = 0; }
   8646         else if (*mode) ch = *mode == 'U' ? toupper(ch) : tolower(ch);
   8647         sb_add(b, (char *)&ch, 1);
   8648     }
   8649 }
   8650 
   8651 static int s_subst(struct scmd *c)
   8652 {
   8653     struct regex *re = c->re ? c->re : s_lastre;
   8654     struct sbuf out = { 0 };
   8655     size_t pos = 0, copied = 0;
   8656     long prev = -1, count = 0;
   8657     int did = 0, nth = c->nth ? c->nth : 1;
   8658     if (!re) die(1, "no previous regular expression");
   8659     s_lastre = re;
   8660     while (pos <= s_ps.len && re_exec(re, s_ps.p, s_ps.len, pos, 1, s_caps)) {
   8661         long ms = s_caps[0], me = s_caps[1];
   8662         int i, mode = 0, once = 0;
   8663         if (me == ms && ms == prev) {
   8664             if ((size_t)ms >= s_ps.len) break;
   8665             pos = ms + 1;
   8666             continue;
   8667         }
   8668         count++;
   8669         if (count >= nth) {
   8670             sb_add(&out, s_ps.p + copied, ms - copied);
   8671             for (i = 0; i < c->nrep; i++) {
   8672                 struct srep *r = &c->rep[i];
   8673                 if (r->kind == 0) s_case(&out, r->s, r->len, &mode, &once);
   8674                 else if (r->kind == 1) {
   8675                     if (r->n <= re->ngrp && s_caps[2 * r->n] >= 0) s_case(&out, s_ps.p + s_caps[2 * r->n], s_caps[2 * r->n + 1] - s_caps[2 * r->n], &mode, &once);
   8676                 } else if (r->n == 'E') mode = once = 0;
   8677                 else if (r->n == 'U' || r->n == 'L') mode = r->n;
   8678                 else once = r->n;
   8679             }
   8680             copied = me; did = 1;
   8681             if (!c->g) break;
   8682         }
   8683         prev = me;
   8684         if (me == ms) { if ((size_t)ms >= s_ps.len) break; pos = me + 1; } else pos = me;
   8685     }
   8686     if (!did) { free(out.p); return 0; }
   8687     sb_add(&out, s_ps.p + copied, s_ps.len - copied);
   8688     out.chomped = s_ps.chomped;
   8689     free(s_ps.p);
   8690     s_ps = out;
   8691     return 1;
   8692 }
   8693 
   8694 static void s_print(struct sbuf *b) { s_put(s_out, b->p, b->len, b->chomped); }
   8695 
   8696 /* one pass of the script over the pattern space. returns 1 to go on with the next line, 0 once sed should stop */
   8697 static int s_cycle(void)
   8698 {
   8699     int pc = 0, replay;
   8700     do {
   8701         replay = 0;
   8702         pc = 0;
   8703         while (pc < nsc) {
   8704             struct scmd *c = &sc[pc];
   8705             int hit = s_match(c) != c->neg;
   8706             if (!hit) { pc = c->c == '{' ? c->jump + 1 : pc + 1; continue; }
   8707             pc++;
   8708             switch (c->c) {
   8709             case '{': case '}': case ':': break;
   8710             case '=': { char b[24]; int n = snprintf(b, sizeof b, "%ld\n", s_lineno); s_raw(s_out, b, n); break; }
   8711             case 'a': s_queue(0, c->text, c->tlen); break;
   8712             case 'i': s_raw(s_out, c->text, c->tlen); break;
   8713             case 'c':
   8714                 if (!c->a2.t || c->neg || !c->active) s_raw(s_out, c->text, c->tlen);
   8715                 goto delete;
   8716             case 'b': pc = c->jump; break;
   8717             case 't': if (replaced) { replaced = 0; pc = c->jump; } break;
   8718             case 'T': if (!replaced) pc = c->jump; else replaced = 0; break;
   8719             case 'd': delete: s_ps.len = 0; s_flush_app(); return 1;
   8720             case 'D': {
   8721                 char *nlp = memchr(s_ps.p, '\n', s_ps.len);
   8722                 if (!nlp) goto delete;
   8723                 s_ps.len -= nlp + 1 - s_ps.p;
   8724                 memmove(s_ps.p, nlp + 1, s_ps.len);
   8725                 s_flush_app();
   8726                 replay = 1;
   8727                 pc = nsc;
   8728                 break;
   8729             }
   8730             case 'F': s_put(s_out, s_fname, strlen(s_fname), 1); break;
   8731             case 'g': s_ps.len = 0; sb_add(&s_ps, s_hs.p, s_hs.len); s_ps.chomped = s_hs.chomped; break;
   8732             case 'G': sb_add(&s_ps, "\n", 1); sb_add(&s_ps, s_hs.p, s_hs.len); s_ps.chomped = s_hs.chomped; break;
   8733             case 'h': s_hs.len = 0; sb_add(&s_hs, s_ps.p, s_ps.len); s_hs.chomped = s_ps.chomped; break;
   8734             case 'H': sb_add(&s_hs, "\n", 1); sb_add(&s_hs, s_ps.p, s_ps.len); s_hs.chomped = s_ps.chomped; break;
   8735             case 'x': { struct sbuf t = s_ps; s_ps = s_hs; s_hs = t; break; }
   8736             case 'l': s_list(c->num >= 0 ? c->num : s_wrap); break;
   8737             case 'n':
   8738                 if (s_islast()) { if (!nflag) s_print(&s_ps); s_flush_app(); return 0; }
   8739                 if (!nflag) s_print(&s_ps);
   8740                 s_flush_app();
   8741                 s_getline();
   8742                 break;
   8743             case 'N':
   8744                 if (s_islast()) { if (!nflag) s_print(&s_ps); s_flush_app(); return 0; }
   8745                 s_flush_app();
   8746                 {
   8747                     struct sbuf keep = s_ps;
   8748                     memset(&s_ps, 0, sizeof s_ps);
   8749                     s_getline();
   8750                     sb_add(&keep, "\n", 1);
   8751                     sb_add(&keep, s_ps.p, s_ps.len);
   8752                     keep.chomped = s_ps.chomped;
   8753                     free(s_ps.p);
   8754                     s_ps = keep;
   8755                 }
   8756                 break;
   8757             case 'p': s_print(&s_ps); break;
   8758             case 'P': { char *nlp = memchr(s_ps.p, '\n', s_ps.len); s_put(s_out, s_ps.p, nlp ? (size_t)(nlp - s_ps.p) : s_ps.len, 1); break; }
   8759             case 'q': if (!nflag) s_print(&s_ps); s_flush_app(); quit_now = 1; s_status = c->num >= 0 ? c->num : s_status; return 0;
   8760             case 'Q': quit_now = 1; s_status = c->num >= 0 ? c->num : s_status; return 0;
   8761             case 'r': s_queue(1, c->text, 0); break;
   8762             case 's':
   8763                 if (s_subst(c)) {
   8764                     replaced = 1;
   8765                     if (c->p) s_print(&s_ps);
   8766                     if (c->wf >= 0) { struct sout *o = s_wfile(c->text); s_put(o, s_ps.p, s_ps.len, s_ps.chomped); }
   8767                 }
   8768                 break;
   8769             case 'w': { struct sout *o = s_wfile(c->text); s_put(o, s_ps.p, s_ps.len, s_ps.chomped); break; }
   8770             case 'y': { size_t i; for (i = 0; i < s_ps.len; i++) s_ps.p[i] = c->text[(unsigned char)s_ps.p[i]]; break; }
   8771             case 'z': s_ps.len = 0; break;
   8772             }
   8773         }
   8774     } while (replay);
   8775     if (!nflag) s_print(&s_ps);
   8776     s_flush_app();
   8777     return 1;
   8778 }
   8779 
   8780 static void s_run(void)
   8781 {
   8782     int i;
   8783     for (i = 0; i < nsc; i++) sc[i].active = sc[i].a1.t == 'n' && sc[i].a1.n == 0 && sc[i].a2.t == 'r';
   8784     s_lineno = 0;
   8785     while (s_getline()) if (!s_cycle()) break;
   8786 }
   8787 
   8788 /* -i: the output goes to a file beside the original, which is then replaced by it */
   8789 static char *s_ip_tmp;
   8790 static struct sout s_ip_o;
   8791 
   8792 static int s_inplace_open(const char *name)
   8793 {
   8794     struct stat st;
   8795     const char *slash = strrchr(name, '/');
   8796     size_t dl = slash ? slash - name + 1 : 0;
   8797     int fd;
   8798     if (stat(name, &st) < 0) { say("can't read %s: %s", name, strerror(errno)); s_status = 2; return 1; }
   8799     if (!S_ISREG(st.st_mode)) { say("couldn't edit %s: not a regular file", name); s_status = 4; return 1; }
   8800     s_ip_tmp = xmalloc(dl + 32);
   8801     memcpy(s_ip_tmp, name, dl);
   8802     snprintf(s_ip_tmp + dl, 32, "sed%ld", (long)getpid());
   8803     fd = open(s_ip_tmp, O_WRONLY | O_CREAT | O_TRUNC, 0600);
   8804     if (fd < 0) die(4, "couldn't open temporary file %s: %s", s_ip_tmp, strerror(errno));
   8805     fchmod(fd, st.st_mode & 07777);
   8806     fchown(fd, st.st_uid, st.st_gid);
   8807     s_ip_o.f = fdopen(fd, "w"); s_ip_o.missing = 0;
   8808     s_out = &s_ip_o;
   8809     return 0;
   8810 }
   8811 
   8812 static void s_inplace_close(const char *name)
   8813 {
   8814     if (fclose(s_ip_o.f)) die(4, "couldn't flush %s: %s", s_ip_tmp, strerror(errno));
   8815     if (inplace_suffix && *inplace_suffix) {
   8816         const char *base = base_of(name), *p;
   8817         size_t dl = base - name;
   8818         char *bak = xmalloc(dl + strlen(inplace_suffix) * (strlen(base) + 1) + strlen(base) + 2), *o = bak;
   8819         if (!strchr(inplace_suffix, '/')) { memcpy(o, name, dl); o += dl; }
   8820         if (strchr(inplace_suffix, '*')) {
   8821             for (p = inplace_suffix; *p; p++) { if (*p == '*') { strcpy(o, base); o += strlen(base); } else *o++ = *p; }
   8822             *o = 0;
   8823         } else sprintf(o, "%s%s", base, inplace_suffix);
   8824         if (rename(name, bak) < 0) die(4, "cannot rename %s: %s", name, strerror(errno));
   8825     }
   8826     if (rename(s_ip_tmp, name) < 0) die(4, "cannot rename %s: %s", s_ip_tmp, strerror(errno));
   8827     free(s_ip_tmp);
   8828     s_out = &s_stdout;
   8829 }
   8830 
   8831 static int t_sed(int argc, char **argv)
   8832 {
   8833     static const struct opt lo[] = {
   8834         { "quiet", 0, 'n' }, { "silent", 0, 'n' }, { "expression", 1, 'e' }, { "file", 1, 'f' }, { "regexp-extended", 0, 'E' },
   8835         { "in-place", 2, 'i' }, { "separate", 0, 's' }, { "line-length", 1, 'l' }, { "unbuffered", 0, 'u' }, { "posix", 0, 'u' },
   8836         { "binary", 0, 'u' }, { "follow-symlinks", 0, 'u' }, { "sandbox", 0, 'u' }, { NULL, 0, 0 } };
   8837     int c, have = 0;
   8838     struct sbuf script = { 0 };
   8839     opts_reset();
   8840     while ((c = getopts(argc, argv, "nEre:f:i::sl:u", lo)))
   8841         switch (c) {
   8842         case 'n': nflag = 1; break;
   8843         case 'E': case 'r': ere_sed = 1; break;
   8844         case 'e': sb_add(&script, optarg, strlen(optarg)); sb_add(&script, "\n", 1); have = 1; break;
   8845         case 'f': {
   8846             int fd = open_input(optarg);
   8847             char *d; size_t n;
   8848             if (fd < 0 || read_all(fd, &d, &n) < 0) die(1, "couldn't open file %s: %s", optarg, strerror(errno));
   8849             if (fd) close(fd);
   8850             sb_add(&script, d, n);
   8851             if (n && d[n - 1] != '\n') sb_add(&script, "\n", 1);
   8852             free(d);
   8853             have = 1;
   8854             break;
   8855         }
   8856         case 'i': inplace = sep_files = 1; inplace_suffix = optarg; break;
   8857         case 's': sep_files = 1; break;
   8858         case 'l': { unsigned long w; if (!parse_ulong(optarg, &w)) die(1, "invalid line length"); s_wrap = w; break; }
   8859         }
   8860     if (!have) {
   8861         if (!nops) { fputs("Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]...\n", stderr); return 1; }
   8862         sb_add(&script, ops[0], strlen(ops[0]));
   8863         ops++; nops--;
   8864     }
   8865     re_exit = 1;
   8866     if (script.len >= 2 && script.p[0] == '#' && script.p[1] == 'n' && (script.len == 2 || script.p[2] == '\n')) nflag = 1;
   8867     s_parse(script.p ? script.p : "", script.len);
   8868     s_stdout.f = stdout;
   8869     s_hs.chomped = 1;
   8870     s_out = &s_stdout;
   8871     if (!nops) { static char *dash[] = { "-", NULL }; if (inplace) die(4, "no input files"); s_files = dash; s_next = 0; s_end = 1; }
   8872     else { s_files = ops; s_next = 0; s_end = nops; }
   8873     if (!sep_files) s_run();
   8874     else {
   8875         int i, n = s_end;
   8876         for (i = 0; i < n && !quit_now; i++) {
   8877             s_next = i; s_end = i + 1;
   8878             if (inplace && s_inplace_open(s_files[i])) continue;
   8879             s_run();
   8880             if (inplace) s_inplace_close(s_files[i]);
   8881         }
   8882     }
   8883     {
   8884         int i;
   8885         for (i = 0; i < s_nwfiles; i++) if (s_wfiles[i].o.f != stderr) fclose(s_wfiles[i].o.f);
   8886     }
   8887     return finish_stdout() ? 4 : s_status;
   8888 }
   8889 
   8890 /* ---- find ---- */
   8891 
   8892 enum { F_AND, F_OR, F_NOT, F_COMMA, F_TRUE, F_FALSE, F_NAME, F_INAME, F_PATH, F_IPATH, F_TYPE, F_XTYPE, F_SIZE, F_TIME, F_NEWER, F_PERM,
   8893        F_USER, F_GROUP, F_UID, F_GID, F_EMPTY, F_LINKS, F_INUM, F_ACCESS, F_NOUSER, F_NOGROUP, F_PRUNE, F_QUIT, F_PRINT, F_PRINT0,
   8894        F_PRINTF, F_DELETE, F_EXEC, F_LNAME };
   8895 
   8896 struct fnode {
   8897     int op, cmp, kind, plus, argc, nbatch, batchcap;
   8898     struct fnode *a, *b;
   8899     char *s, **argv, **batch;
   8900     long n;
   8901     unsigned long long unit;
   8902     mode_t mode;
   8903     struct timespec ref;
   8904     size_t blen;
   8905 };
   8906 struct fctx { const char *path; const struct stat *st; int prune; };
   8907 
   8908 static char **fa;
   8909 static int fi, fn_, f_depth, f_given_depth, f_xdev, f_follow, f_status, f_quit;
   8910 static long f_min = 0, f_max = 1 << 30;
   8911 static time_t f_now;
   8912 static struct fnode **f_plus;
   8913 static int f_nplus;
   8914 
   8915 static __attribute__((noreturn)) void fdie(const char *fmt, ...)
   8916 {
   8917     va_list ap;
   8918     fprintf(stderr, "find: ");
   8919     va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap);
   8920     fputc('\n', stderr);
   8921     exit(1);
   8922 }
   8923 
   8924 static struct fnode *fnew(int op, struct fnode *a, struct fnode *b)
   8925 {
   8926     struct fnode *n = xmalloc(sizeof *n);
   8927     memset(n, 0, sizeof *n);
   8928     n->op = op; n->a = a; n->b = b;
   8929     return n;
   8930 }
   8931 
   8932 static char *farg(const char *name)
   8933 {
   8934     if (fi >= fn_) fdie("missing argument to `%s'", name);
   8935     return fa[fi++];
   8936 }
   8937 
   8938 static int fcmp(const char **s)
   8939 {
   8940     int cmp = 0;
   8941     if (**s == '+') { cmp = 1; (*s)++; } else if (**s == '-') { cmp = -1; (*s)++; }
   8942     return cmp;
   8943 }
   8944 static long fnum(const char *s, const char *name)
   8945 {
   8946     char *end;
   8947     long v = strtol(s, &end, 10);
   8948     if (!isdigit((unsigned char)*s) || *end) fdie("invalid argument `%s' to " "%s", s, name);
   8949     return v;
   8950 }
   8951 
   8952 static struct fnode *f_or(void);
   8953 
   8954 static struct fnode *f_primary(void)
   8955 {
   8956     const char *t, *a;
   8957     struct fnode *n;
   8958     if (fi >= fn_) fdie("invalid expression; expected an expression after `%s'", fi ? fa[fi - 1] : "find");
   8959     t = fa[fi++];
   8960     if (!strcmp(t, "(")) {
   8961         n = f_or();
   8962         if (fi >= fn_ || strcmp(fa[fi], ")")) fdie("invalid expression; I was expecting to find a ')' somewhere but did not see one.");
   8963         fi++;
   8964         return n;
   8965     }
   8966     if (!strcmp(t, "!") || !strcmp(t, "-not")) { n = f_primary(); return fnew(F_NOT, n, NULL); }
   8967     if (!strcmp(t, "-true")) return fnew(F_TRUE, NULL, NULL);
   8968     if (!strcmp(t, "-false")) return fnew(F_FALSE, NULL, NULL);
   8969     if (!strcmp(t, "-name") || !strcmp(t, "-iname") || !strcmp(t, "-path") || !strcmp(t, "-ipath") || !strcmp(t, "-wholename") || !strcmp(t, "-iwholename") || !strcmp(t, "-lname")) {
   8970         int ic = t[1] == 'i';
   8971         n = fnew(!strcmp(t, "-lname") ? F_LNAME : t[1 + ic] == 'n' ? (ic ? F_INAME : F_NAME) : (ic ? F_IPATH : F_PATH), NULL, NULL);
   8972         n->s = xstrdup(farg(t));
   8973         if (ic) { char *p; for (p = n->s; *p; p++) *p = tolower((unsigned char)*p); }
   8974         return n;
   8975     }
   8976     if (!strcmp(t, "-type") || !strcmp(t, "-xtype")) {
   8977         n = fnew(t[1] == 'x' ? F_XTYPE : F_TYPE, NULL, NULL);
   8978         n->s = xstrdup(farg(t));
   8979         for (a = n->s; *a; a++) {
   8980             if (!strchr("bcdpfls", *a)) fdie("Unknown argument to -type: %s", a);
   8981             if (a[1] && a[1] != ',') fdie("Must separate multiple arguments to -type using: ','");
   8982             if (a[1]) a++;
   8983         }
   8984         return n;
   8985     }
   8986     if (!strcmp(t, "-size")) {
   8987         const char *s = farg(t);
   8988         char *end;
   8989         n = fnew(F_SIZE, NULL, NULL);
   8990         n->cmp = fcmp(&s);
   8991         if (!isdigit((unsigned char)*s)) fdie("invalid argument `%s' to -size", s);
   8992         n->n = strtol(s, &end, 10);
   8993         n->unit = 512;
   8994         if (*end) {
   8995             if (end[1]) fdie("invalid -size type `%s'", end);
   8996             switch (*end) {
   8997             case 'c': n->unit = 1; break; case 'w': n->unit = 2; break; case 'b': n->unit = 512; break;
   8998             case 'k': n->unit = 1024; break; case 'M': n->unit = 1 << 20; break; case 'G': n->unit = 1 << 30; break;
   8999             default: fdie("invalid -size type `%s'", end);
   9000             }
   9001         }
   9002         return n;
   9003     }
   9004     if (t[0] == '-' && (!strcmp(t + 2, "time") || !strcmp(t + 2, "min")) && strchr("mac", t[1])) {
   9005         const char *s = farg(t);
   9006         n = fnew(F_TIME, NULL, NULL);
   9007         n->kind = t[1];
   9008         n->unit = t[2] == 't' ? 86400 : 60;
   9009         n->cmp = fcmp(&s);
   9010         n->n = fnum(s, t);
   9011         return n;
   9012     }
   9013     if (!strcmp(t, "-newer") || !strcmp(t, "-anewer") || !strcmp(t, "-cnewer")) {
   9014         struct stat st;
   9015         const char *f = farg(t);
   9016         n = fnew(F_NEWER, NULL, NULL);
   9017         n->kind = t[1] == 'n' ? 'm' : t[1];
   9018         if ((f_follow ? stat(f, &st) : lstat(f, &st)) < 0) { fprintf(stderr, "find: '%s': %s\n", f, strerror(errno)); exit(1); }
   9019         n->ref.tv_sec = st.st_mtime;
   9020         n->ref.tv_nsec = st.st_mtime_nsec;
   9021         return n;
   9022     }
   9023     if (!strcmp(t, "-perm")) {
   9024         const char *s = farg(t);
   9025         struct change *ch;
   9026         n = fnew(F_PERM, NULL, NULL);
   9027         if (*s == '-') { n->cmp = 1; s++; } else if (*s == '/' || *s == '+') { n->cmp = 2; s++; }
   9028         if (!(ch = mode_compile(s))) fdie("invalid mode `%s'", s);
   9029         n->mode = mode_apply(0, 0, 0, ch) & MODE_BITS;
   9030         return n;
   9031     }
   9032     if (!strcmp(t, "-user") || !strcmp(t, "-group") || !strcmp(t, "-uid") || !strcmp(t, "-gid")) {
   9033         const char *s = farg(t);
   9034         n = fnew(t[1] == 'u' ? (t[2] == 's' ? F_USER : F_UID) : (t[2] == 'r' ? F_GROUP : F_GID), NULL, NULL);
   9035         if (n->op == F_USER) { uid_t u; if (lookup_user(s, &u) < 0) fdie("`%s' is not the name of a known user", s); n->n = u; }
   9036         else if (n->op == F_GROUP) { gid_t g; if (lookup_group(s, &g) < 0) fdie("`%s' is not the name of an existing group", s); n->n = g; }
   9037         else { n->cmp = fcmp(&s); n->n = fnum(s, t); }
   9038         return n;
   9039     }
   9040     if (!strcmp(t, "-nouser")) return fnew(F_NOUSER, NULL, NULL);
   9041     if (!strcmp(t, "-nogroup")) return fnew(F_NOGROUP, NULL, NULL);
   9042     if (!strcmp(t, "-empty")) return fnew(F_EMPTY, NULL, NULL);
   9043     if (!strcmp(t, "-links") || !strcmp(t, "-inum")) {
   9044         const char *s = farg(t);
   9045         n = fnew(t[1] == 'l' ? F_LINKS : F_INUM, NULL, NULL);
   9046         n->cmp = fcmp(&s);
   9047         n->n = fnum(s, t);
   9048         return n;
   9049     }
   9050     if (!strcmp(t, "-readable") || !strcmp(t, "-writable") || !strcmp(t, "-executable")) {
   9051         n = fnew(F_ACCESS, NULL, NULL);
   9052         n->kind = t[1] == 'r' ? 4 : t[1] == 'w' ? 2 : 1;
   9053         return n;
   9054     }
   9055     if (!strcmp(t, "-prune")) return fnew(F_PRUNE, NULL, NULL);
   9056     if (!strcmp(t, "-quit")) return fnew(F_QUIT, NULL, NULL);
   9057     if (!strcmp(t, "-print") || !strcmp(t, "-print0")) return fnew(t[6] ? F_PRINT0 : F_PRINT, NULL, NULL);
   9058     if (!strcmp(t, "-printf")) { n = fnew(F_PRINTF, NULL, NULL); n->s = xstrdup(farg(t)); return n; }
   9059     if (!strcmp(t, "-delete")) { f_depth = 1; return fnew(F_DELETE, NULL, NULL); }
   9060     if (!strcmp(t, "-exec")) {
   9061         int start = fi;
   9062         n = fnew(F_EXEC, NULL, NULL);
   9063         while (fi < fn_ && strcmp(fa[fi], ";") && !(fi > start && !strcmp(fa[fi], "+") && !strcmp(fa[fi - 1], "{}"))) fi++;
   9064         if (fi >= fn_ || fi == start) fdie("missing argument to `-exec'");
   9065         n->plus = fa[fi][0] == '+';
   9066         n->argc = fi - start - n->plus;
   9067         n->argv = xmalloc((n->argc + 1) * sizeof *n->argv);
   9068         memcpy(n->argv, fa + start, n->argc * sizeof *n->argv);
   9069         n->argv[n->argc] = NULL;
   9070         fi++;
   9071         if (n->plus) { f_plus = xrealloc(f_plus, (f_nplus + 1) * sizeof *f_plus); f_plus[f_nplus++] = n; }
   9072         return n;
   9073     }
   9074     if (!strcmp(t, "-maxdepth") || !strcmp(t, "-mindepth")) {
   9075         long v = fnum(farg(t), t);
   9076         if (t[2] == 'a') f_max = v; else f_min = v;
   9077         return fnew(F_TRUE, NULL, NULL);
   9078     }
   9079     if (!strcmp(t, "-depth") || !strcmp(t, "-d")) { f_depth = f_given_depth = 1; return fnew(F_TRUE, NULL, NULL); }
   9080     if (!strcmp(t, "-xdev") || !strcmp(t, "-mount")) { f_xdev = 1; return fnew(F_TRUE, NULL, NULL); }
   9081     if (!strcmp(t, "-follow")) { f_follow = 2; return fnew(F_TRUE, NULL, NULL); }
   9082     if (!strcmp(t, "-noleaf") || !strcmp(t, "-ignore_readdir_race") || !strcmp(t, "-nowarn") || !strcmp(t, "-warn")) return fnew(F_TRUE, NULL, NULL);
   9083     if (t[0] == '-') fdie("unknown predicate `%s'", t);
   9084     fdie("paths must precede expression: `%s'", t);
   9085 }
   9086 
   9087 static struct fnode *f_and(void)
   9088 {
   9089     struct fnode *n = f_primary();
   9090     for (;;) {
   9091         if (fi >= fn_ || !strcmp(fa[fi], "-o") || !strcmp(fa[fi], "-or") || !strcmp(fa[fi], ")") || !strcmp(fa[fi], ",")) return n;
   9092         if (!strcmp(fa[fi], "-a") || !strcmp(fa[fi], "-and")) fi++;
   9093         n = fnew(F_AND, n, f_primary());
   9094     }
   9095 }
   9096 static struct fnode *f_or(void)
   9097 {
   9098     struct fnode *n = f_and();
   9099     for (;;) {
   9100         if (fi < fn_ && (!strcmp(fa[fi], "-o") || !strcmp(fa[fi], "-or"))) { fi++; n = fnew(F_OR, n, f_and()); }
   9101         else if (fi < fn_ && !strcmp(fa[fi], ",")) { fi++; n = fnew(F_COMMA, n, f_and()); }
   9102         else return n;
   9103     }
   9104 }
   9105 
   9106 static int f_has(struct fnode *n, int op)
   9107 {
   9108     if (!n) return 0;
   9109     if (op < 0 ? (n->op == F_PRINT || n->op == F_PRINT0 || n->op == F_PRINTF || n->op == F_DELETE || n->op == F_EXEC) : n->op == op) return 1;
   9110     return f_has(n->a, op) || f_has(n->b, op);
   9111 }
   9112 
   9113 static int f_run(char **argv)
   9114 {
   9115     int st;
   9116     pid_t pid;
   9117     fflush(stdout);
   9118     pid = fork();
   9119     if (pid < 0) { perr("cannot fork"); return -1; }
   9120     if (!pid) {
   9121         execvp(argv[0], argv);
   9122         fprintf(stderr, "find: '%s': %s\n", argv[0], strerror(errno));
   9123         _exit(127);
   9124     }
   9125     while (waitpid(pid, &st, 0) < 0) if (errno != EINTR) return -1;
   9126     return (st & 0x7f) ? -1 : (st >> 8) & 255;
   9127 }
   9128 
   9129 static void f_flush(struct fnode *n)
   9130 {
   9131     char **v;
   9132     int i;
   9133     if (!n->nbatch) return;
   9134     v = xmalloc((n->argc + n->nbatch + 1) * sizeof *v);
   9135     for (i = 0; i < n->argc; i++) v[i] = n->argv[i];
   9136     for (i = 0; i < n->nbatch; i++) v[n->argc + i] = n->batch[i];
   9137     v[n->argc + n->nbatch] = NULL;
   9138     if (f_run(v) != 0) f_status = 1;
   9139     for (i = 0; i < n->nbatch; i++) free(n->batch[i]);
   9140     n->nbatch = 0; n->blen = 0;
   9141     free(v);
   9142 }
   9143 
   9144 static char *f_subst(const char *arg, const char *path)
   9145 {
   9146     size_t pl = strlen(path), n = 0;
   9147     const char *p;
   9148     char *r, *o;
   9149     for (p = arg; *p; p++) if (p[0] == '{' && p[1] == '}') { n++; p++; }
   9150     r = o = xmalloc(strlen(arg) + n * pl + 1);
   9151     for (p = arg; *p; p++) {
   9152         if (p[0] == '{' && p[1] == '}') { memcpy(o, path, pl); o += pl; p++; }
   9153         else *o++ = *p;
   9154     }
   9155     *o = 0;
   9156     return r;
   9157 }
   9158 
   9159 static void f_printf(const char *fmt, const char *path, const struct stat *st, const char *start_path)
   9160 {
   9161     const char *p;
   9162     for (p = fmt; *p; p++) {
   9163         if (*p == '\\' && p[1]) {
   9164             p++;
   9165             switch (*p) {
   9166             case 'n': putchar('\n'); break; case 't': putchar('\t'); break; case '\\': putchar('\\'); break;
   9167             case '0': putchar(0); break; case 'r': putchar('\r'); break; case 'a': putchar(7); break; case 'f': putchar('\f'); break;
   9168             case 'v': putchar('\v'); break; case 'b': putchar('\b'); break;
   9169             default: putchar('\\'); putchar(*p);
   9170             }
   9171         } else if (*p == '%' && p[1]) {
   9172             const char *b = base_of(path);
   9173             p++;
   9174             switch (*p) {
   9175             case '%': putchar('%'); break;
   9176             case 'p': fputs(path, stdout); break;
   9177             case 'f': fputs(b, stdout); break;
   9178             case 'h': { const char *sl = strrchr(path, '/'); if (!sl) fputs(".", stdout); else if (sl == path) fputs("/", stdout); else fwrite(path, 1, sl - path, stdout); break; }
   9179             case 'P': { size_t l = strlen(start_path); const char *r = path + l; if (!strncmp(path, start_path, l)) { while (*r == '/') r++; fputs(r, stdout); } break; }
   9180             case 's': printf("%lld", (long long)st->st_size); break;
   9181             case 'm': printf("%o", (unsigned)(st->st_mode & 07777)); break;
   9182             case 'M': { char m[11]; st_perm(st->st_mode, m); fputs(m, stdout); break; }
   9183             case 'n': printf("%lu", (unsigned long)st->st_nlink); break;
   9184             case 'i': printf("%lu", (unsigned long)st->st_ino); break;
   9185             case 'u': fputs(user_name(st->st_uid), stdout); break;
   9186             case 'g': fputs(group_name(st->st_gid), stdout); break;
   9187             case 'U': printf("%u", (unsigned)st->st_uid); break;
   9188             case 'G': printf("%u", (unsigned)st->st_gid); break;
   9189             case 'y': putchar(S_ISDIR(st->st_mode) ? 'd' : S_ISLNK(st->st_mode) ? 'l' : S_ISREG(st->st_mode) ? 'f' : S_ISBLK(st->st_mode) ? 'b' : S_ISCHR(st->st_mode) ? 'c' : S_ISFIFO(st->st_mode) ? 'p' : 's'); break;
   9190             default: putchar('%'); putchar(*p);
   9191             }
   9192         } else putchar(*p);
   9193     }
   9194 }
   9195 
   9196 static const char *f_start;
   9197 
   9198 static int f_eval(struct fnode *n, struct fctx *x)
   9199 {
   9200     const struct stat *st = x->st;
   9201     switch (n->op) {
   9202     case F_AND: return f_eval(n->a, x) && !f_quit && f_eval(n->b, x);
   9203     case F_OR: return f_eval(n->a, x) || (!f_quit && f_eval(n->b, x));
   9204     case F_COMMA: f_eval(n->a, x); return f_eval(n->b, x);
   9205     case F_NOT: return !f_eval(n->a, x);
   9206     case F_TRUE: return 1;
   9207     case F_FALSE: return 0;
   9208     case F_NAME: case F_INAME: case F_PATH: case F_IPATH: {
   9209         const char *subject = n->op == F_NAME || n->op == F_INAME ? base_of(x->path) : x->path;
   9210         char *tmp = NULL;
   9211         int r;
   9212         if (n->op == F_INAME || n->op == F_IPATH) {
   9213             char *p;
   9214             tmp = xstrdup(subject);
   9215             for (p = tmp; *p; p++) *p = tolower((unsigned char)*p);
   9216             subject = tmp;
   9217         }
   9218         r = glob_match(n->s, subject);
   9219         free(tmp);
   9220         return r;
   9221     }
   9222     case F_LNAME: {
   9223         char buf[PATH_MAX];
   9224         ssize_t k;
   9225         if (!S_ISLNK(st->st_mode) || (k = readlink(x->path, buf, sizeof buf - 1)) < 0) return 0;
   9226         buf[k] = 0;
   9227         return glob_match(n->s, buf);
   9228     }
   9229     case F_TYPE: case F_XTYPE: {
   9230         struct stat t = *st;
   9231         const char *a;
   9232         int ty;
   9233         if (n->op == F_XTYPE && S_ISLNK(t.st_mode) && stat(x->path, &t) < 0) lstat(x->path, &t);
   9234         ty = S_ISDIR(t.st_mode) ? 'd' : S_ISREG(t.st_mode) ? 'f' : S_ISLNK(t.st_mode) ? 'l' : S_ISBLK(t.st_mode) ? 'b' : S_ISCHR(t.st_mode) ? 'c' : S_ISFIFO(t.st_mode) ? 'p' : 's';
   9235         for (a = n->s; *a; a++) if (*a == ty) return 1;
   9236         return 0;
   9237     }
   9238     case F_SIZE: {
   9239         long long blocks = n->unit == 1 ? st->st_size : (st->st_size + n->unit - 1) / n->unit;
   9240         return n->cmp > 0 ? blocks > n->n : n->cmp < 0 ? blocks < n->n : blocks == n->n;
   9241     }
   9242     case F_TIME: {
   9243         long long t = n->kind == 'a' ? st->st_atime : n->kind == 'c' ? st->st_ctime : st->st_mtime, age = f_now - t;
   9244         if (n->unit == 86400) {
   9245             long long d = age / 86400;
   9246             return n->cmp > 0 ? d > n->n : n->cmp < 0 ? d < n->n : d == n->n;
   9247         }
   9248         return n->cmp > 0 ? age > n->n * 60 : n->cmp < 0 ? age < n->n * 60 : (age > (n->n - 1) * 60 && age <= n->n * 60);
   9249     }
   9250     case F_NEWER: {
   9251         long s = n->kind == 'a' ? st->st_atime : n->kind == 'c' ? st->st_ctime : st->st_mtime;
   9252         long ns = n->kind == 'a' ? st->st_atime_nsec : n->kind == 'c' ? st->st_ctime_nsec : st->st_mtime_nsec;
   9253         return s > n->ref.tv_sec || (s == n->ref.tv_sec && ns > n->ref.tv_nsec);
   9254     }
   9255     case F_PERM: {
   9256         mode_t m = st->st_mode & MODE_BITS;
   9257         return n->cmp == 0 ? m == n->mode : n->cmp == 1 ? (m & n->mode) == n->mode : (!n->mode || (m & n->mode));
   9258     }
   9259     case F_USER: return st->st_uid == (uid_t)n->n;
   9260     case F_GROUP: return st->st_gid == (gid_t)n->n;
   9261     case F_UID: return n->cmp > 0 ? (long)st->st_uid > n->n : n->cmp < 0 ? (long)st->st_uid < n->n : (long)st->st_uid == n->n;
   9262     case F_GID: return n->cmp > 0 ? (long)st->st_gid > n->n : n->cmp < 0 ? (long)st->st_gid < n->n : (long)st->st_gid == n->n;
   9263     case F_NOUSER: return !getpwuid(st->st_uid);
   9264     case F_NOGROUP: return !getgrgid(st->st_gid);
   9265     case F_LINKS: return n->cmp > 0 ? (long)st->st_nlink > n->n : n->cmp < 0 ? (long)st->st_nlink < n->n : (long)st->st_nlink == n->n;
   9266     case F_INUM: return n->cmp > 0 ? (long)st->st_ino > n->n : n->cmp < 0 ? (long)st->st_ino < n->n : (long)st->st_ino == n->n;
   9267     case F_ACCESS: return access(x->path, n->kind) == 0;
   9268     case F_EMPTY:
   9269         if (S_ISREG(st->st_mode)) return st->st_size == 0;
   9270         if (S_ISDIR(st->st_mode)) {
   9271             DIR *d = opendir(x->path);
   9272             struct dirent *e;
   9273             int empty = 1;
   9274             if (!d) return 0;
   9275             while ((e = readdir(d))) if (strcmp(e->d_name, ".") && strcmp(e->d_name, "..")) { empty = 0; break; }
   9276             closedir(d);
   9277             return empty;
   9278         }
   9279         return 0;
   9280     case F_PRUNE: x->prune = 1; return 1;
   9281     case F_QUIT: f_quit = 1; return 1;
   9282     case F_PRINT: puts(x->path); return 1;
   9283     case F_PRINT0: fputs(x->path, stdout); putchar(0); return 1;
   9284     case F_PRINTF: f_printf(n->s, x->path, st, f_start); return 1;
   9285     case F_DELETE:
   9286         if (!strcmp(x->path, ".")) return 1;
   9287         if (S_ISDIR(st->st_mode) ? rmdir(x->path) : unlink(x->path)) { fprintf(stderr, "find: cannot delete '%s': %s\n", x->path, strerror(errno)); f_status = 1; return 0; }
   9288         return 1;
   9289     case F_EXEC:
   9290         if (n->plus) {
   9291             if (n->nbatch == n->batchcap) { n->batchcap = n->batchcap ? n->batchcap * 2 : 64; n->batch = xrealloc(n->batch, n->batchcap * sizeof *n->batch); }
   9292             n->batch[n->nbatch++] = xstrdup(x->path);
   9293             n->blen += strlen(x->path) + 1;
   9294             if (n->blen > 65536) f_flush(n);
   9295             return 1;
   9296         } else {
   9297             char **v = xmalloc((n->argc + 1) * sizeof *v);
   9298             int i, r;
   9299             for (i = 0; i < n->argc; i++) v[i] = f_subst(n->argv[i], x->path);
   9300             v[n->argc] = NULL;
   9301             r = f_run(v);
   9302             for (i = 0; i < n->argc; i++) free(v[i]);
   9303             free(v);
   9304             return r == 0;
   9305         }
   9306     }
   9307     return 0;
   9308 }
   9309 
   9310 static struct fnode *f_root;
   9311 
   9312 static void f_walk(const char *path, int level, dev_t topdev)
   9313 {
   9314     struct stat st;
   9315     struct fctx x;
   9316     int isdir;
   9317     if (f_quit) return;
   9318     if ((f_follow == 2 || (f_follow == 1 && !level) ? stat(path, &st) : lstat(path, &st)) < 0) {
   9319         if (f_follow && lstat(path, &st) == 0) goto ok;
   9320         fprintf(stderr, "find: '%s': %s\n", path, strerror(errno));
   9321         f_status = 1;
   9322         return;
   9323     }
   9324 ok:
   9325     x.path = path; x.st = &st; x.prune = 0;
   9326     isdir = S_ISDIR(st.st_mode);
   9327     if (!f_depth && level >= f_min) f_eval(f_root, &x);
   9328     if (isdir && !x.prune && level < f_max && !f_quit && !(f_xdev && level && st.st_dev != topdev)) {
   9329         DIR *d = opendir(path);
   9330         if (!d) { fprintf(stderr, "find: '%s': %s\n", path, strerror(errno)); f_status = 1; }
   9331         else {
   9332             struct dirent *e;
   9333             char **v = NULL;
   9334             int n = 0, cap = 0, i;
   9335             while ((e = readdir(d))) {
   9336                 if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
   9337                 if (n == cap) { cap = cap ? cap * 2 : 32; v = xrealloc(v, cap * sizeof *v); }
   9338                 v[n++] = xstrdup(e->d_name);
   9339             }
   9340             closedir(d);
   9341             for (i = 0; i < n; i++) {
   9342                 size_t pl = strlen(path);
   9343                 char *child = xmalloc(pl + strlen(v[i]) + 2);
   9344                 memcpy(child, path, pl);
   9345                 if (pl && path[pl - 1] != '/') child[pl++] = '/';
   9346                 strcpy(child + pl, v[i]);
   9347                 f_walk(child, level + 1, topdev);
   9348                 free(child); free(v[i]);
   9349             }
   9350             free(v);
   9351         }
   9352     }
   9353     if (f_depth && level >= f_min && !f_quit) f_eval(f_root, &x);
   9354 }
   9355 
   9356 static int t_find(int argc, char **argv)
   9357 {
   9358     int i, first, pend;
   9359     fa = argv; fn_ = argc; fi = 1;
   9360     while (fi < fn_ && (!strcmp(fa[fi], "-H") || !strcmp(fa[fi], "-L") || !strcmp(fa[fi], "-P"))) { f_follow = fa[fi][1] == 'L' ? 2 : fa[fi][1] == 'H'; fi++; }
   9361     first = fi;
   9362     while (fi < fn_ && (fa[fi][0] != '-' || !fa[fi][1]) && strcmp(fa[fi], "(") && strcmp(fa[fi], "!") && strcmp(fa[fi], ")") && strcmp(fa[fi], ",")) fi++;
   9363     pend = fi;
   9364     char **from = NULL; size_t nfrom = 0;
   9365     if (fi < fn_ && !strcmp(fa[fi], "-files0-from")) { /* the starting points come from a file, each ended by a NUL */
   9366         char *d; size_t dl, k;
   9367         int fd;
   9368         if (fi + 1 >= fn_) fdie("missing argument to `-files0-from'");
   9369         if (pend != first) fdie("extra operand `%s'", fa[first]);
   9370         if ((fd = open_input(fa[fi + 1])) < 0 || read_all(fd, &d, &dl) < 0) fdie("cannot read %s: %s", fa[fi + 1], strerror(errno));
   9371         if (fd) close(fd);
   9372         from = xmalloc((dl + 1) * sizeof *from);
   9373         for (k = 0; k < dl; k += strlen(d + k) + 1)
   9374             if (d[k]) from[nfrom++] = d + k;
   9375         fi += 2;
   9376     }
   9377     if (fi < fn_ && !strcmp(fa[fi], "--help")) { print_usage(); return 0; }
   9378     if (fi < fn_) {
   9379         f_root = f_or();
   9380         if (fi < fn_) fdie("unexpected extra predicate `%s'", fa[fi]);
   9381         if (f_has(f_root, F_DELETE) && f_has(f_root, F_PRUNE) && !f_given_depth) fdie("The -delete action automatically turns on -depth, but -prune does nothing when -depth is in effect.  If you want to carry on anyway, just explicitly use the -depth option.");
   9382         if (!f_has(f_root, -1)) f_root = fnew(F_AND, f_root, fnew(F_PRINT, NULL, NULL));
   9383     } else f_root = fnew(F_PRINT, NULL, NULL);
   9384     f_now = time(NULL);
   9385     if (!from) { from = fa + first; nfrom = pend - first; if (!nfrom) from = (char *[]){ "." }, nfrom = 1; }
   9386     for (i = 0; i < (int)nfrom && !f_quit; i++) {
   9387         struct stat st;
   9388         f_start = from[i];
   9389         if (stat(from[i], &st) < 0 && lstat(from[i], &st) < 0) st.st_dev = 0;
   9390         f_walk(from[i], 0, st.st_dev);
   9391     }
   9392     for (i = 0; i < f_nplus; i++) f_flush(f_plus[i]);
   9393     return finish_stdout() ? 1 : f_status;
   9394 }
   9395 
   9396 /* ---- xargs ---- */
   9397 
   9398 struct xitem { char *s; int eol; };
   9399 
   9400 /* the input as items. by default blanks and newlines separate them, quotes and backslashes group, and a line that ends
   9401  * in a blank carries on into the next one. with -I only newlines separate. -0 and -d split at one byte and nothing else */
   9402 static size_t x_items(char *d, size_t len, int delim, int onlynl, struct xitem **out, int *badquote)
   9403 {
   9404     struct xitem *v = NULL;
   9405     size_t n = 0, cap = 0, i = 0;
   9406     char *b = xmalloc(len + 1);
   9407     while (i < len) {
   9408         size_t bl = 0;
   9409         int quote = 0, eol = 0;
   9410         if (delim >= 0) {
   9411             while (i < len && d[i] != delim) b[bl++] = d[i++];
   9412             i++;
   9413             eol = 1;
   9414         } else {
   9415             while (i < len && (d[i] == '\n' || d[i] == ' ' || d[i] == '\t')) i++;
   9416             if (i >= len) break;
   9417             while (i < len) {
   9418                 char c = d[i];
   9419                 if (quote) {
   9420                     if (c == '\n') break;
   9421                     if (c == quote) quote = 0; else b[bl++] = c;
   9422                     i++;
   9423                     continue;
   9424                 }
   9425                 if (c == '\n') { eol = 1; i++; break; }
   9426                 if (!onlynl && (c == ' ' || c == '\t')) {
   9427                     while (i < len && (d[i] == ' ' || d[i] == '\t')) i++;
   9428                     if (i < len && d[i] == '\n') i++;
   9429                     break;
   9430                 }
   9431                 if (c == '\'' || c == '"') { quote = c; i++; continue; }
   9432                 if (c == '\\' && i + 1 < len) { b[bl++] = d[i + 1]; i += 2; continue; }
   9433                 b[bl++] = c; i++;
   9434             }
   9435             if (quote) { *badquote = quote; break; }
   9436             if (i >= len) eol = 1;
   9437         }
   9438         if (*badquote) break;
   9439         if (n == cap) { cap = cap ? cap * 2 : 64; v = xrealloc(v, cap * sizeof *v); }
   9440         b[bl] = 0;
   9441         v[n].s = xstrdup(b); v[n].eol = eol; n++;
   9442     }
   9443     free(b);
   9444     *out = v;
   9445     return n;
   9446 }
   9447 
   9448 static void xq_die(int quote)
   9449 {
   9450     die(1, "unmatched %s quote; by default quotes are special to xargs unless you use the -0 option", quote == '"' ? "double" : "single");
   9451 }
   9452 
   9453 static int x_exec(char **argv, int verbose)
   9454 {
   9455     int st, i;
   9456     pid_t pid;
   9457     if (verbose) { for (i = 0; argv[i]; i++) fprintf(stderr, "%s%s", i ? " " : "", argv[i]); fputc('\n', stderr); }
   9458     fflush(stdout);
   9459     pid = fork();
   9460     if (pid < 0) die(1, "cannot fork: %s", strerror(errno));
   9461     if (!pid) {
   9462         execvp(argv[0], argv);
   9463         fprintf(stderr, "%s: failed to run command '%s': %s\n", prog, argv[0], strerror(errno));
   9464         _exit(errno == ENOENT ? 127 : 126);
   9465     }
   9466     while (waitpid(pid, &st, 0) < 0) if (errno != EINTR) die(1, "waitpid: %s", strerror(errno));
   9467     if (st & 0x7f) die(125, "%s: terminated by signal %d", argv[0], st & 0x7f);
   9468     st = (st >> 8) & 255;
   9469     if (st == 126 || st == 127) exit(st);
   9470     if (st == 255) die(124, "%s: exited with status 255; aborting", argv[0]);
   9471     return st;
   9472 }
   9473 
   9474 static int t_xargs(int argc, char **argv)
   9475 {
   9476     static const struct opt lo[] = {
   9477         { "null", 0, '0' }, { "arg-file", 1, 'a' }, { "delimiter", 1, 'd' }, { "eof", 2, 'e' }, { "replace", 2, 'i' }, { "max-lines", 2, 'l' },
   9478         { "max-args", 1, 'n' }, { "max-procs", 1, 'P' }, { "no-run-if-empty", 0, 'r' }, { "max-chars", 1, 's' }, { "verbose", 0, 't' },
   9479         { "exit", 0, 'x' }, { NULL, 0, 0 } };
   9480     int c, delim = -1, norun = 0, verbose = 0, exitbig = 0, fd = 0, status = 0, ncmd, i, badquote = 0;
   9481     const char *repl = NULL, *eofs = NULL;
   9482     unsigned long maxargs = 0, maxlines = 0, maxchars = 131072, v;
   9483     char **cmd, *d;
   9484     size_t len, n, k, cmdsize = 0;
   9485     struct xitem *it;
   9486     usage_status = 1;
   9487     opts_reset();
   9488     while ((c = getopts(argc, argv, "+0a:d:E:e::I:i::L:l::n:P:rs:tx", lo)))
   9489         switch (c) {
   9490         case '0': delim = 0; break;
   9491         case 'a': fd = open(optarg, O_RDONLY); if (fd < 0) die(1, "Cannot open input file '%s': %s", optarg, strerror(errno)); break;
   9492         case 'd':
   9493             if (!strcmp(optarg, "\\n")) delim = '\n'; else if (!strcmp(optarg, "\\t")) delim = '\t'; else if (!strcmp(optarg, "\\0")) delim = 0;
   9494             else if (!strcmp(optarg, "\\\\")) delim = '\\'; else if (strlen(optarg) == 1) delim = (unsigned char)optarg[0];
   9495             else die(1, "Invalid input delimiter specification %s: the delimiter must be either a single character or an escape sequence starting with \\", optarg);
   9496             break;
   9497         case 'E': eofs = optarg; break;
   9498         case 'e': eofs = optarg && *optarg ? optarg : NULL; break;
   9499         case 'I': repl = optarg; maxlines = 1; maxargs = 0; break;
   9500         case 'i': repl = optarg ? optarg : "{}"; maxlines = 1; maxargs = 0; break;
   9501         case 'L': case 'l':
   9502             if (optarg) { if (!parse_ulong(optarg, &v) || !v) die(1, "invalid number for -%c option", c); maxlines = v; } else maxlines = 1;
   9503             maxargs = 0; repl = NULL;
   9504             break;
   9505         case 'n': if (!parse_ulong(optarg, &v) || !v) die(1, "invalid number for -n option"); maxargs = v; maxlines = 0; repl = NULL; break;
   9506         case 's': if (!parse_ulong(optarg, &maxchars)) die(1, "invalid number for -s option"); break;
   9507         case 'r': norun = 1; break;
   9508         case 't': verbose = 1; break;
   9509         case 'x': exitbig = 1; break;
   9510         case 'P': break;
   9511         }
   9512     ncmd = nops ? nops : 1;
   9513     cmd = xmalloc((ncmd + 2) * sizeof *cmd);
   9514     if (nops) memcpy(cmd, ops, nops * sizeof *cmd); else cmd[0] = "echo";
   9515     for (i = 0; i < ncmd; i++) cmdsize += strlen(cmd[i]) + 1;
   9516     if (read_all(fd, &d, &len) < 0) die(1, "%s", strerror(errno));
   9517     n = x_items(d, len, delim, repl != NULL, &it, &badquote);
   9518     if (eofs && delim < 0) for (k = 0; k < n; k++) if (!strcmp(it[k].s, eofs)) { n = k; break; }
   9519     if (repl) {
   9520         for (k = 0; k < n; k++) {
   9521             char **av = xmalloc((ncmd + 1) * sizeof *av);
   9522             for (i = 0; i < ncmd; i++) {
   9523                 const char *p = cmd[i], *hit;
   9524                 struct sbuf b = { 0 };
   9525                 size_t rl = strlen(repl);
   9526                 while (*repl && (hit = strstr(p, repl))) { sb_add(&b, p, hit - p); sb_add(&b, it[k].s, strlen(it[k].s)); p = hit + rl; }
   9527                 sb_add(&b, p, strlen(p));
   9528                 sb_add(&b, "", 1);
   9529                 av[i] = b.p;
   9530             }
   9531             av[ncmd] = NULL;
   9532             if (x_exec(av, verbose)) status = 123;
   9533         }
   9534         if (badquote) xq_die(badquote);
   9535         return status;
   9536     }
   9537     {
   9538         char **batch = xmalloc((ncmd + n + 1) * sizeof *batch);
   9539         size_t nb = 0, size = cmdsize, lines = 0;
   9540         memcpy(batch, cmd, ncmd * sizeof *batch);
   9541         if (cmdsize > maxchars) die(1, "can not fit single argument within argument list size limit");
   9542         for (k = 0; k < n; k++) {
   9543             size_t l = strlen(it[k].s) + 1;
   9544             if (nb && size + l > maxchars) {
   9545                 if (exitbig && (maxargs || maxlines)) die(1, "argument line too long");
   9546                 batch[ncmd + nb] = NULL;
   9547                 if (x_exec(batch, verbose)) status = 123;
   9548                 nb = 0; size = cmdsize; lines = 0;
   9549             }
   9550             if (size + l > maxchars) die(1, "can not fit single argument within argument list size limit");
   9551             batch[ncmd + nb++] = it[k].s;
   9552             size += l;
   9553             if (it[k].eol) lines++;
   9554             if ((maxargs && nb >= maxargs) || (maxlines && lines >= maxlines)) {
   9555                 batch[ncmd + nb] = NULL;
   9556                 if (x_exec(batch, verbose)) status = 123;
   9557                 nb = 0; size = cmdsize; lines = 0;
   9558             }
   9559         }
   9560         if (nb || (!n && !norun && !badquote)) {
   9561             batch[ncmd + nb] = NULL;
   9562             if (x_exec(batch, verbose)) status = 123;
   9563         }
   9564     }
   9565     if (badquote) xq_die(badquote);
   9566     return status;
   9567 }
   9568 
   9569 /* ---- dir vdir ---- */
   9570 
   9571 static int t_dir(int argc, char **argv)
   9572 {
   9573     char **v = xmalloc((argc + 4) * sizeof *v);
   9574     int i, n = 0;
   9575     v[n++] = argv[0];
   9576     v[n++] = !strcmp(prog, "vdir") ? "-l" : "-C";
   9577     v[n++] = "-b";
   9578     for (i = 1; i < argc; i++) v[n++] = argv[i];
   9579     v[n] = NULL;
   9580     return t_ls(n, v);
   9581 }
   9582 
   9583 /* ---- kill ---- */
   9584 
   9585 static const char *const signames[] = { NULL, "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "BUS", "FPE", "KILL", "USR1", "SEGV", "USR2", "PIPE",
   9586     "ALRM", "TERM", "STKFLT", "CHLD", "CONT", "STOP", "TSTP", "TTIN", "TTOU", "URG", "XCPU", "XFSZ", "VTALRM", "PROF", "WINCH", "POLL", "PWR", "SYS" };
   9587 #define NSIGNAMES ((int)(sizeof signames / sizeof signames[0]))
   9588 
   9589 static int sig_number(const char *s)
   9590 {
   9591     unsigned long n;
   9592     int i;
   9593     if (parse_ulong(s, &n)) return n < 65 ? (int)n : -1;
   9594     if (!strncasecmp(s, "SIG", 3)) s += 3;
   9595     for (i = 1; i < NSIGNAMES; i++) if (!strcasecmp(s, signames[i])) return i;
   9596     if (!strcasecmp(s, "EXIT")) return 0;
   9597     if (!strcasecmp(s, "IO")) return 29;
   9598     if (!strcasecmp(s, "CLD")) return 17;
   9599     if (!strcasecmp(s, "IOT")) return 6;
   9600     if (!strcasecmp(s, "RTMIN")) return 34;
   9601     if (!strcasecmp(s, "RTMAX")) return 64;
   9602     if (!strncasecmp(s, "RTMIN+", 6) && parse_ulong(s + 6, &n) && n < 31) return 34 + n;
   9603     if (!strncasecmp(s, "RTMAX-", 6) && parse_ulong(s + 6, &n) && n < 31) return 64 - n;
   9604     return -1;
   9605 }
   9606 
   9607 static const char *sig_name(int n, char *buf)
   9608 {
   9609     if (n > 0 && n < NSIGNAMES) return signames[n];
   9610     if (n == 34) return "RTMIN";
   9611     if (n == 64) return "RTMAX";
   9612     if (n > 34 && n < 49) { sprintf(buf, "RTMIN+%d", n - 34); return buf; }
   9613     if (n > 49 && n < 64) { sprintf(buf, "RTMAX-%d", 64 - n); return buf; }
   9614     return NULL;
   9615 }
   9616 
   9617 static int t_kill(int argc, char **argv)
   9618 {
   9619     int sig = SIGTERM, i = 1, bad = 0;
   9620     char nb[16];
   9621     if (argc > 1 && (!strcmp(argv[1], "-l") || !strcmp(argv[1], "--list") || !strcmp(argv[1], "-t") || !strcmp(argv[1], "--table"))) {
   9622         int table = argv[1][1] == 't' || argv[1][2] == 't';
   9623         if (argc == 2) {
   9624             int n, col = 0, w;
   9625             for (n = 1; n < 65; n++) {
   9626                 const char *s = sig_name(n, nb);
   9627                 if (!s) continue;
   9628                 if (table) { printf("%2d %-8s%s", n, s, ++col % 4 ? "" : "\n"); continue; }
   9629                 w = strlen(s) + 1;
   9630                 if (col && col + w > 80) { putchar('\n'); col = 0; }
   9631                 printf("%s%s", col ? " " : "", s);
   9632                 col += w;
   9633             }
   9634             if (!table || col % 4) putchar('\n');
   9635             return finish_stdout() ? 1 : 0;
   9636         }
   9637         for (i = 2; i < argc; i++) {
   9638             int n = sig_number(argv[i]);
   9639             unsigned long v;
   9640             if (parse_ulong(argv[i], &v)) { if (v > 128) v &= 127; n = (int)v; const char *s = sig_name(n, nb); if (!s) { say("%s: invalid signal", argv[i]); bad = 1; } else puts(s); }
   9641             else if (n < 0) { say("%s: invalid signal", argv[i]); bad = 1; }
   9642             else if (table) printf("%2d %s\n", n, sig_name(n, nb));
   9643             else printf("%d\n", n);
   9644         }
   9645         return finish_stdout() ? 1 : bad;
   9646     }
   9647     if (argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h"))) { print_usage(); return 0; }
   9648     if (argc > 1 && (!strcmp(argv[1], "-s") || !strcmp(argv[1], "--signal") || !strcmp(argv[1], "-n"))) {
   9649         if (argc < 3) { say("option requires an argument -- 's'"); usage_error(); }
   9650         if ((sig = sig_number(argv[2])) < 0) die(1, "invalid signal '%s'", argv[2]);
   9651         i = 3;
   9652     } else if (argc > 1 && !strncmp(argv[1], "--signal=", 9)) {
   9653         if ((sig = sig_number(argv[1] + 9)) < 0) die(1, "invalid signal '%s'", argv[1] + 9);
   9654         i = 2;
   9655     } else if (argc > 1 && argv[1][0] == '-' && argv[1][1] && strcmp(argv[1], "--")) {
   9656         if ((sig = sig_number(argv[1] + 1)) < 0) die(1, "invalid signal '%s'", argv[1] + 1);
   9657         i = 2;
   9658     }
   9659     if (i < argc && !strcmp(argv[i], "--")) i++;
   9660     if (i >= argc) { say("not enough arguments"); usage_error(); }
   9661     for (; i < argc; i++) {
   9662         long pid;
   9663         char *end;
   9664         errno = 0;
   9665         pid = strtol(argv[i], &end, 10);
   9666         if (!*argv[i] || *end) { say("failed to parse argument: '%s'", argv[i]); bad = 1; continue; }
   9667         if (kill((pid_t)pid, sig) < 0) { say("(%ld): %s", pid, strerror(errno)); bad = 1; }
   9668     }
   9669     return bad;
   9670 }
   9671 
   9672 /* ---- pathchk ---- */
   9673 
   9674 static int t_pathchk(int argc, char **argv)
   9675 {
   9676     static const struct opt lo[] = { { "portability", 0, 'P' }, { NULL, 0, 0 } };
   9677     int c, posix = 0, extra = 0, bad = 0, i;
   9678     opts_reset();
   9679     while ((c = getopts(argc, argv, "pP", lo)))
   9680         switch (c) { case 'p': posix = 1; break; case 'P': extra = 1; break; case 'P' + 1: break; default: break; }
   9681     if (!nops) { say("missing operand"); usage_error(); }
   9682     for (i = 0; i < nops; i++) {
   9683         const char *path = ops[i], *p, *start;
   9684         size_t plen = strlen(path), maxpath = posix ? 256 : PATH_MAX, maxname = posix ? 14 : 255;
   9685         int ok = 1;
   9686         if (extra || posix) {
   9687             if (!plen) { say("empty file name"); bad = 1; continue; }
   9688         }
   9689         if (!extra && !posix && !plen) { say("'': No such file or directory"); bad = 1; continue; }
   9690         if (plen >= maxpath || (posix && plen > 255)) {
   9691             say("limit %lu exceeded by length %lu of file name '%s'", (unsigned long)(posix ? 255 : maxpath - 1), (unsigned long)plen, path);
   9692             bad = 1; continue;
   9693         }
   9694         if (extra) {
   9695             for (p = path; *p; p++) if (*p == '-' && (p == path || p[-1] == '/')) { say("leading '-' in a component of file name '%s'", path); ok = 0; break; }
   9696             if (!ok) { bad = 1; continue; }
   9697         }
   9698         for (start = p = path; ok; p++) {
   9699             if (*p == '/' || !*p) {
   9700                 size_t l = p - start;
   9701                 if (l > maxname) { say("limit %lu exceeded by length %lu of file name component '%.*s'", (unsigned long)maxname, (unsigned long)l, (int)l, start); ok = 0; break; }
   9702                 if (!*p) break;
   9703                 start = p + 1;
   9704             } else if (posix || extra) {
   9705                 if (!(isalnum((unsigned char)*p) || strchr("._-", *p))) { say("non-portable character '%c' in file name '%s'", *p, path); ok = 0; }
   9706             }
   9707         }
   9708         if (!ok) bad = 1;
   9709     }
   9710     return bad;
   9711 }
   9712 
   9713 /* ---- who users pinky uptime ---- */
   9714 
   9715 enum { UT_EMPTY, UT_RUN_LVL, UT_BOOT_TIME, UT_NEW_TIME, UT_OLD_TIME, UT_INIT, UT_LOGIN, UT_USER, UT_DEAD, UT_ACCT };
   9716 
   9717 struct ut { int type, pid, term, exit; long sec; char line[33], id[5], user[33], host[257]; };
   9718 
   9719 static int ut_read(const char *file, struct ut **out)
   9720 {
   9721     unsigned char rec[384];
   9722     struct ut *v = NULL;
   9723     int n = 0, fd = open(file ? file : "/var/run/utmp", O_RDONLY);
   9724     if (fd < 0 && !file) fd = open("/run/utmp", O_RDONLY);
   9725     if (fd < 0) { perr("%s", file ? file : "/var/run/utmp"); return -1; }
   9726     while (read(fd, rec, sizeof rec) == (ssize_t)sizeof rec) {
   9727         struct ut *u;
   9728         int32_t i32;
   9729         int16_t i16;
   9730         v = xrealloc(v, (n + 1) * sizeof *v);
   9731         u = &v[n++];
   9732         memset(u, 0, sizeof *u);
   9733         memcpy(&i16, rec, 2); u->type = i16;
   9734         memcpy(&i32, rec + 4, 4); u->pid = i32;
   9735         memcpy(u->line, rec + 8, 32); memcpy(u->id, rec + 40, 4); memcpy(u->user, rec + 44, 32); memcpy(u->host, rec + 76, 256);
   9736         memcpy(&i16, rec + 332, 2); u->term = i16;
   9737         memcpy(&i16, rec + 334, 2); u->exit = i16;
   9738         memcpy(&i32, rec + 340, 4); u->sec = i32;
   9739     }
   9740     close(fd);
   9741     *out = v;
   9742     return n;
   9743 }
   9744 
   9745 /* a login that has no process left is stale, the way gnulib's read_utmp drops it */
   9746 static int ut_alive(const struct ut *u)
   9747 {
   9748     return u->pid <= 0 || kill(u->pid, 0) == 0 || errno != ESRCH;
   9749 }
   9750 static int ut_isuser(const struct ut *u) { return u->user[0] && u->type == UT_USER && ut_alive(u); }
   9751 
   9752 static int ut_cmp_name(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
   9753 
   9754 static int t_users(int argc, char **argv)
   9755 {
   9756     struct ut *v;
   9757     char **names;
   9758     int n, i, k = 0;
   9759     opts_reset();
   9760     while (getopts(argc, argv, "", NULL)) ;
   9761     if (nops > 1) extra_operand(ops[1]);
   9762     if ((n = ut_read(nops ? ops[0] : NULL, &v)) < 0) return 1;
   9763     names = xmalloc((n + 1) * sizeof *names);
   9764     for (i = 0; i < n; i++) if (v[i].type == UT_USER && v[i].user[0] && (nops || ut_alive(&v[i]))) names[k++] = v[i].user;
   9765     qsort(names, k, sizeof *names, ut_cmp_name);
   9766     for (i = 0; i < k; i++) printf("%s%s", i ? " " : "", names[i]);
   9767     if (k) putchar('\n');
   9768     return finish_stdout() ? 1 : 0;
   9769 }
   9770 
   9771 static void ut_time(long sec, char *buf, size_t cap)
   9772 {
   9773     time_t t = sec;
   9774     strftime(buf, cap, "%b %e %H:%M", localtime(&t));
   9775 }
   9776 
   9777 /* whether the tty takes messages, and how long since it was touched */
   9778 static void ut_tty(const char *line, char *mesg, long *idle)
   9779 {
   9780     char path[64];
   9781     struct stat st;
   9782     snprintf(path, sizeof path, "/dev/%s", line);
   9783     if (stat(path, &st) < 0) { *mesg = '?'; *idle = -1; return; }
   9784     *mesg = st.st_mode & S_IWGRP ? '+' : '-';
   9785     *idle = time(NULL) - st.st_atime;
   9786 }
   9787 
   9788 struct whocols { int mesg, idle, pid, exit; };
   9789 
   9790 static void who_row(const struct whocols *c, char mesg, const char *user, const char *line, long sec, const char *idle, int pid, const char *comment)
   9791 {
   9792     char buf[600], tm[32];
   9793     int n = snprintf(buf, sizeof buf, "%-8s", user);
   9794     if (c->mesg) n += snprintf(buf + n, sizeof buf - n, " %c", mesg);
   9795     ut_time(sec, tm, sizeof tm);
   9796     n += snprintf(buf + n, sizeof buf - n, " %-12s %s", line, tm);
   9797     if (c->idle) n += snprintf(buf + n, sizeof buf - n, " %-6s", idle);
   9798     if (c->pid) {
   9799         if (pid > 0) n += snprintf(buf + n, sizeof buf - n, " %10d", pid);
   9800         else n += snprintf(buf + n, sizeof buf - n, " %10s", "");
   9801     }
   9802     if (*comment) n += snprintf(buf + n, sizeof buf - n, " %s", comment);
   9803     while (n > 0 && buf[n - 1] == ' ') buf[--n] = 0;
   9804     puts(buf);
   9805 }
   9806 
   9807 static int t_who(int argc, char **argv)
   9808 {
   9809     static const struct opt lo[] = { { "all", 0, 'a' }, { "boot", 0, 'b' }, { "dead", 0, 'd' }, { "heading", 0, 'H' }, { "login", 0, 'l' }, { "lookup", 0, 1000 },
   9810         { "only-current-tty", 0, 'm' }, { "process", 0, 'p' }, { "count", 0, 'q' }, { "runlevel", 0, 'r' }, { "short", 0, 's' }, { "time", 0, 't' },
   9811         { "mesg", 0, 'T' }, { "message", 0, 'T' }, { "writable", 0, 'T' }, { "users", 0, 'u' }, { "ips", 0, 1001 }, { NULL, 0, 0 } };
   9812     int c, all = 0, boot = 0, dead = 0, head = 0, login = 0, cur = 0, proc = 0, count = 0, runl = 0, tim = 0, mesg = 0, users = 0, i, n, sel;
   9813     struct whocols col;
   9814     struct ut *v;
   9815     const char *file = NULL, *me = NULL;
   9816     opts_reset();
   9817     while ((c = getopts(argc, argv, "abdHlmpqrstTuw", lo)))
   9818         switch (c) {
   9819         case 'a': all = 1; break; case 'b': boot = 1; break; case 'd': dead = 1; break; case 'H': head = 1; break; case 'l': login = 1; break;
   9820         case 'm': cur = 1; break; case 'p': proc = 1; break; case 'q': count = 1; break; case 'r': runl = 1; break; case 't': tim = 1; break;
   9821         case 'T': mesg = 1; break; case 'u': users = 1; break; default: break;
   9822         }
   9823     if (all) boot = dead = login = proc = runl = tim = mesg = users = 1;
   9824     if (nops == 2 && !strcasecmp(ops[0], "am") && !strcasecmp(ops[1], "i")) { cur = 1; nops = 0; }
   9825     else if (nops > 1) extra_operand(ops[1]);
   9826     if (nops) file = ops[0];
   9827     sel = boot || dead || login || proc || runl || tim;
   9828     if ((n = ut_read(file, &v)) < 0) return 1;
   9829     if (cur) { const char *t = ttyname(0); if (!t || strncmp(t, "/dev/", 5)) return 0; me = t + 5; }
   9830     if (count) {
   9831         int k = 0;
   9832         for (i = 0; i < n; i++) if (v[i].type == UT_USER && v[i].user[0] && (file || ut_alive(&v[i]))) { printf("%s%s", k ? " " : "", v[i].user); k++; }
   9833         printf("%s# users=%d\n", k ? "\n" : "", k);
   9834         return finish_stdout() ? 1 : 0;
   9835     }
   9836     col.mesg = mesg;
   9837     col.idle = users || dead || login || runl;
   9838     col.pid = users || sel;
   9839     col.exit = dead;
   9840     if (head) {
   9841         char buf[200];
   9842         int m = snprintf(buf, sizeof buf, "%-8s", "NAME");
   9843         if (col.mesg) m += snprintf(buf + m, sizeof buf - m, "  ");
   9844         m += snprintf(buf + m, sizeof buf - m, " %-12s %-12s", "LINE", "TIME");
   9845         if (col.idle) m += snprintf(buf + m, sizeof buf - m, " %-6s", "IDLE");
   9846         if (col.pid) m += snprintf(buf + m, sizeof buf - m, " %10s", "PID");
   9847         m += snprintf(buf + m, sizeof buf - m, " COMMENT");
   9848         if (col.exit) snprintf(buf + m, sizeof buf - m, "  EXIT");
   9849         puts(buf);
   9850     }
   9851     for (i = 0; i < n; i++) {
   9852         struct ut *u = &v[i];
   9853         char comment[300] = "", idle[16] = "", name[40], m = ' ';
   9854         long id = -1;
   9855         if (me && strcmp(u->line, me)) continue;
   9856         switch (u->type) {
   9857         case UT_USER:
   9858             if (sel && !users) continue;
   9859             if (!u->user[0] || (!file && !ut_alive(u))) continue;
   9860             ut_tty(u->line, &m, &id);
   9861             if (!mesg) m = ' ';
   9862             if (col.idle) { if (id < 0) strcpy(idle, "  ?"); else if (id < 60) strcpy(idle, "  .  "); else if (id < 24 * 3600) snprintf(idle, sizeof idle, "%02ld:%02ld", id / 3600, id / 60 % 60); else strcpy(idle, " old "); }
   9863             if (u->host[0]) snprintf(comment, sizeof comment, "(%s)", u->host);
   9864             who_row(&col, m, u->user, u->line, u->sec, idle, col.pid ? u->pid : 0, comment);
   9865             break;
   9866         case UT_BOOT_TIME: if (boot) who_row(&col, ' ', "", "system boot", u->sec, "", 0, ""); break;
   9867         case UT_RUN_LVL:
   9868             if (!runl) break;
   9869             snprintf(name, sizeof name, "run-level %c", u->pid & 255 ? u->pid & 255 : ' ');
   9870             snprintf(comment, sizeof comment, "last=%c", u->pid >> 8 & 255 ? u->pid >> 8 & 255 : 'S');
   9871             who_row(&col, ' ', "", name, u->sec, "", 0, comment);
   9872             break;
   9873         case UT_LOGIN: if (login) { snprintf(comment, sizeof comment, "id=%s", u->id); who_row(&col, ' ', "LOGIN", u->line, u->sec, "", u->pid, comment); } break;
   9874         case UT_INIT: if (proc) { snprintf(comment, sizeof comment, "id=%s", u->id); who_row(&col, ' ', "", u->line, u->sec, "", u->pid, comment); } break;
   9875         case UT_DEAD: if (dead) { snprintf(comment, sizeof comment, "id=%-4s  term=%d exit=%d", u->id, u->term, u->exit); who_row(&col, ' ', "", u->line, u->sec, "", u->pid, comment); } break;
   9876         case UT_NEW_TIME: if (tim) who_row(&col, ' ', "", "new time", u->sec, "", 0, ""); break;
   9877         case UT_OLD_TIME: if (tim) who_row(&col, ' ', "", "old time", u->sec, "", 0, ""); break;
   9878         default: break;
   9879         }
   9880     }
   9881     return finish_stdout() ? 1 : 0;
   9882 }
   9883 
   9884 static int t_pinky(int argc, char **argv)
   9885 {
   9886     int c, longf = 0, nohead = 0, noname = 0, nohost = 0, noidle = 0, nodir = 0, i, n, m;
   9887     struct ut *v;
   9888     char hdr[200];
   9889     opts_reset();
   9890     while ((c = getopts(argc, argv, "lbhpswfiq", NULL)))
   9891         switch (c) {
   9892         case 'l': longf = 1; break; case 'f': nohead = 1; break; case 'b': nodir = 1; break; case 'w': noname = 1; break;
   9893         case 'i': noname = nohost = 1; break; case 'q': noname = nohost = noidle = 1; break; default: break;
   9894         }
   9895     if (longf) {
   9896         if (!nops) { say("no username specified; at least one must be specified when using -l"); usage_error(); }
   9897         for (i = 0; i < nops; i++) {
   9898             struct passwd *p = getpwnam(ops[i]);
   9899             char name[128], *comma;
   9900             if (!p) { printf("Login name: %-28sIn real life:  ???\n", ops[i]); continue; }
   9901             snprintf(name, sizeof name, "%s", p->pw_gecos ? p->pw_gecos : "");
   9902             if ((comma = strchr(name, ','))) *comma = 0;
   9903             printf("Login name: %-28sIn real life:  %s\n", p->pw_name, name);
   9904             if (!nodir) printf("Directory: %-29sShell:  %s\n", p->pw_dir, p->pw_shell);
   9905             putchar('\n');
   9906         }
   9907         return finish_stdout() ? 1 : 0;
   9908     }
   9909     if ((n = ut_read(NULL, &v)) < 0) return 1;
   9910     if (!nohead) {
   9911         m = snprintf(hdr, sizeof hdr, "%-8s", "Login");
   9912         if (!noname) m += snprintf(hdr + m, sizeof hdr - m, " %-19s", "Name");
   9913         m += snprintf(hdr + m, sizeof hdr - m, "  %-8s", "TTY");
   9914         if (!noidle) m += snprintf(hdr + m, sizeof hdr - m, " %-6s", "Idle");
   9915         m += snprintf(hdr + m, sizeof hdr - m, " %-12s", "When");
   9916         if (!nohost) snprintf(hdr + m, sizeof hdr - m, " Where");
   9917         puts(hdr);
   9918     }
   9919     for (i = 0; i < n; i++) {
   9920         struct ut *u = &v[i];
   9921         struct passwd *p;
   9922         char real[128] = "", tm[32], m1, idle[16] = "", line[600];
   9923         long id;
   9924         int len, j, want = nops == 0;
   9925         if (!ut_isuser(u)) continue;
   9926         for (j = 0; j < nops; j++) if (!strncmp(ops[j], u->user, 32)) want = 1;
   9927         if (!want) continue;
   9928         if ((p = getpwnam(u->user)) && p->pw_gecos) {
   9929             char *comma;
   9930             snprintf(real, sizeof real, "%s", p->pw_gecos);
   9931             if ((comma = strchr(real, ','))) *comma = 0;
   9932         }
   9933         ut_tty(u->line, &m1, &id);
   9934         if (id >= 60) { if (id < 24 * 3600) snprintf(idle, sizeof idle, "%02ld:%02ld", id / 3600, id / 60 % 60); else strcpy(idle, "old"); }
   9935         ut_time(u->sec, tm, sizeof tm);
   9936         len = snprintf(line, sizeof line, "%-8s", u->user);
   9937         if (!noname) len += snprintf(line + len, sizeof line - len, " %-19.19s", real);
   9938         len += snprintf(line + len, sizeof line - len, " %c%-8s", m1 == '+' ? ' ' : '*', u->line);
   9939         if (!noidle) len += snprintf(line + len, sizeof line - len, " %-6s", idle);
   9940         len += snprintf(line + len, sizeof line - len, " %s", tm);
   9941         if (!nohost && u->host[0]) len += snprintf(line + len, sizeof line - len, " %s", u->host);
   9942         while (len > 0 && line[len - 1] == ' ') line[--len] = 0;
   9943         puts(line);
   9944     }
   9945     return finish_stdout() ? 1 : 0;
   9946 }
   9947 
   9948 static int t_uptime(int argc, char **argv)
   9949 {
   9950     struct ut *v;
   9951     FILE *f;
   9952     double la[3] = { 0, 0, 0 }, up = 0;
   9953     long secs, days, hours, mins;
   9954     int users = 0, n, i;
   9955     time_t now = time(NULL);
   9956     struct tm *tm;
   9957     char buf[160];
   9958     int len;
   9959     opts_reset();
   9960     while (getopts(argc, argv, "", NULL)) ;
   9961     if (nops > 1) extra_operand(ops[1]);
   9962     if ((n = ut_read(nops ? ops[0] : NULL, &v)) < 0 && nops) return 1;
   9963     for (i = 0; i < n; i++) if (ut_isuser(&v[i])) users++;
   9964     if (nops) { for (i = 0; i < n; i++) if (v[i].type == UT_BOOT_TIME) up = now - v[i].sec; }
   9965     else if ((f = fopen("/proc/uptime", "r"))) { { char l[64]; up = fgets(l, sizeof l, f) ? strtod(l, NULL) : 0; } fclose(f); }
   9966     if ((f = fopen("/proc/loadavg", "r"))) { { char l[96], *e = l; if (fgets(l, sizeof l, f)) { int k; for (k = 0; k < 3; k++) { la[k] = strtod(e, &e); } } } fclose(f); }
   9967     tm = localtime(&now);
   9968     secs = (long)up; days = secs / 86400; hours = secs % 86400 / 3600; mins = secs % 3600 / 60;
   9969     len = snprintf(buf, sizeof buf, " %2d:%02d:%02d up ", tm->tm_hour, tm->tm_min, tm->tm_sec);
   9970     if (days > 0) len += snprintf(buf + len, sizeof buf - len, "%ld day%s, ", days, days == 1 ? "" : "s");
   9971     if (days || hours) len += snprintf(buf + len, sizeof buf - len, "%2ld:%02ld", hours, mins);
   9972     else len += snprintf(buf + len, sizeof buf - len, "%ld min", mins);
   9973     snprintf(buf + len, sizeof buf - len, ",  %d user%s,  load average: %.2f, %.2f, %.2f", users, users == 1 ? "" : "s", la[0], la[1], la[2]);
   9974     puts(buf);
   9975     return finish_stdout() ? 1 : 0;
   9976 }
   9977 
   9978 /* ---- stdbuf ---- */
   9979 
   9980 static int stdbuf_mode(const char *s, const char *name, char *out, size_t cap)
   9981 {
   9982     char *end;
   9983     unsigned long long v;
   9984     if (!strcmp(s, "L")) { if (name[0] == 'i') return -1; snprintf(out, cap, "L"); return 0; }
   9985     errno = 0;
   9986     v = strtoull(s, &end, 10);
   9987     if (end == s || errno) return -1;
   9988     if (*end) {
   9989         static const char suf[] = "KMGTPEZY";
   9990         const char *p;
   9991         int b = 1024;
   9992         if (end[1] == 'B' && !end[2]) b = 1000, end++;
   9993         else if (end[1]) return -1;
   9994         else if (end[0] == 'B') { end++; goto done; }
   9995         if (!(p = strchr(suf, *end)) || !*end) return -1;
   9996         { int k; for (k = 0; k <= p - suf; k++) v *= b; }
   9997     }
   9998 done:
   9999     snprintf(out, cap, "%llu", v);
  10000     return 0;
  10001 }
  10002 
  10003 static int t_stdbuf(int argc, char **argv)
  10004 {
  10005     static const struct opt lo[] = { { "input", 1, 'i' }, { "output", 1, 'o' }, { "error", 1, 'e' }, { NULL, 0, 0 } };
  10006     static const char *const libs[] = { "/usr/libexec/coreutils/libstdbuf.so", "/usr/lib/coreutils/libstdbuf.so", "/usr/local/libexec/coreutils/libstdbuf.so", NULL };
  10007     int c, i;
  10008     char val[32], preload[PATH_MAX + 32];
  10009     const char *lib = NULL, *old;
  10010     opts_reset();
  10011     while ((c = getopts(argc, argv, "+i:o:e:", lo))) {
  10012         const char *var = c == 'i' ? "_STDBUF_I" : c == 'o' ? "_STDBUF_O" : c == 'e' ? "_STDBUF_E" : NULL;
  10013         if (!var) continue;
  10014         if (stdbuf_mode(optarg, c == 'i' ? "input" : c == 'o' ? "output" : "error", val, sizeof val) < 0) die(125, "invalid mode '%s'", optarg);
  10015         setenv(var, val, 1);
  10016         i = 1;
  10017     }
  10018     if (!nops) { say("missing operand"); usage_status = 125; usage_error(); }
  10019     for (i = 0; libs[i]; i++) if (!access(libs[i], R_OK)) { lib = libs[i]; break; }
  10020     if (!lib) die(125, "failed to find libstdbuf.so");
  10021     old = getenv("LD_PRELOAD");
  10022     snprintf(preload, sizeof preload, "%s%s%s", old ? old : "", old ? ":" : "", lib);
  10023     setenv("LD_PRELOAD", preload, 1);
  10024     execvp(ops[0], ops);
  10025     say("failed to run command '%s': %s", ops[0], strerror(errno));
  10026     return errno == ENOENT ? 127 : 126;
  10027 }
  10028 
  10029 /* ---- chcon runcon ---- */
  10030 
  10031 static int t_runcon(int argc, char **argv)
  10032 {
  10033     opts_reset();
  10034     while (getopts(argc, argv, "+", NULL)) ;
  10035     if (!nops) { say("missing operand"); usage_status = 125; usage_error(); }
  10036     die(125, "runcon may be used only on a SELinux kernel");
  10037 }
  10038 
  10039 static int t_chcon(int argc, char **argv)
  10040 {
  10041     static const struct opt lo[] = { { "reference", 1, 1003 }, { "recursive", 0, 'R' }, { "verbose", 0, 'v' }, { "user", 1, 'u' }, { "role", 1, 'l' },
  10042         { "type", 1, 't' }, { "range", 1, 'z' }, { "no-dereference", 0, 'h' }, { "dereference", 0, 1000 }, { "preserve-root", 0, 1001 }, { "no-preserve-root", 0, 1002 }, { NULL, 0, 0 } };
  10043     int c, i, first = 0, parts = 0, bad = 0;
  10044     const char *ref = NULL, *ctx = NULL;
  10045     opts_reset();
  10046     while ((c = getopts(argc, argv, "RHLPhvu:r:l:t:", lo)))
  10047         switch (c) { case 'u': case 'l': case 't': case 'z': parts = 1; break; default: break; }
  10048     (void)ref;
  10049     if (!parts) first = 1;
  10050     if (!parts && nops < 2) { if (!nops) missing_operand(); say("missing operand after '%s'", ops[0]); usage_error(); }
  10051     if (parts && !nops) missing_operand();
  10052     if (!parts) ctx = ops[0];
  10053     for (i = first; i < nops; i++) {
  10054         say("failed to change context of '%s' to '%s': Operation not supported", ops[i], ctx ? ctx : "");
  10055         bad = 1;
  10056     }
  10057     return bad;
  10058 }
  10059 
  10060 /* ---- csplit ---- */
  10061 
  10062 struct cspat { int kind; /* 0 line, 1 regex, 2 skip */ long n, off, rep; int inf; struct regex *re; char *text; };
  10063 
  10064 static char **cs_names;
  10065 static int cs_nfiles;
  10066 static const char *cs_prefix = "xx", *cs_fmt = "%02d";
  10067 static int cs_keep, cs_quiet, cs_elide, cs_suppress, cs_open_fail;
  10068 static char *cs_sizes;
  10069 static size_t cs_nsz;
  10070 
  10071 static char *cs_name(int n)
  10072 {
  10073     char *b = xmalloc(strlen(cs_prefix) + 64), *p;
  10074     strcpy(b, cs_prefix);
  10075     p = b + strlen(b);
  10076     snprintf(p, 64, cs_fmt, n);
  10077     return b;
  10078 }
  10079 
  10080 static char cs_conv(const char *f)
  10081 {
  10082     int n = 0;
  10083     char last = 0;
  10084     for (; *f; f++) {
  10085         if (*f != '%') continue;
  10086         if (f[1] == '%') { f++; continue; }
  10087         f++;
  10088         while (strchr("#0+- '", *f)) f++;
  10089         while (isdigit((unsigned char)*f)) f++;
  10090         if (*f == '.') { f++; while (isdigit((unsigned char)*f)) f++; }
  10091         if (!*f) die(1, "missing conversion specifier in suffix");
  10092         if (!strchr("diuoxX", *f)) die(1, "invalid conversion specifier in suffix: %c", *f);
  10093         if (++n > 1) die(1, "too many %% conversion specifications in suffix");
  10094         last = *f;
  10095     }
  10096     if (!n) die(1, "missing conversion specifier in suffix");
  10097     return last;
  10098 }
  10099 
  10100 /* write lines [from, to) as the next file, a size line for it unless -s */
  10101 static int cs_write(const char *buf, const long *ls, long from, long to, long total)
  10102 {
  10103     size_t a = from < total ? ls[from] : ls[total], b = to < total ? ls[to] : ls[total], len = b - a;
  10104     char *name;
  10105     int fd;
  10106     if (cs_elide && !len) return 0;
  10107     name = cs_name(cs_nfiles);
  10108     fd = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  10109     if (fd < 0) { say("%s: %s", name, strerror(errno)); cs_open_fail = 1; return -1; }
  10110     if (len && write(fd, buf + a, len) != (ssize_t)len) { say("write error for '%s': %s", name, strerror(errno)); close(fd); return -1; }
  10111     close(fd);
  10112     cs_names = xrealloc(cs_names, (cs_nfiles + 1) * sizeof *cs_names);
  10113     cs_names[cs_nfiles++] = name;
  10114     if (!cs_quiet) { char t[32]; snprintf(t, sizeof t, "%zu\n", len); cs_sizes = xrealloc(cs_sizes, cs_nsz + strlen(t) + 1); strcpy(cs_sizes + cs_nsz, t); cs_nsz += strlen(t); }
  10115     return 0;
  10116 }
  10117 
  10118 static void cs_cleanup(void)
  10119 {
  10120     int i;
  10121     if (!cs_keep) for (i = 0; i < cs_nfiles; i++) unlink(cs_names[i]);
  10122 }
  10123 
  10124 static int t_csplit(int argc, char **argv)
  10125 {
  10126     static const struct opt lo[] = { { "suffix-format", 1, 'b' }, { "prefix", 1, 'f' }, { "keep-files", 0, 'k' }, { "digits", 1, 'n' }, { "quiet", 0, 's' },
  10127         { "silent", 0, 's' }, { "elide-empty-files", 0, 'z' }, { "suppress-matched", 0, 1000 }, { NULL, 0, 0 } };
  10128     int c, i, np = 0, fd, ndig = 2, havefmt = 0;
  10129     struct cspat *pats = NULL;
  10130     char *buf;
  10131     size_t len, k;
  10132     long *ls, total = 0, cur = 0, lastmatch = -1, prevn = 0, p, rep;
  10133     int skipfail = 0;
  10134     const char *file;
  10135     opts_reset();
  10136     while ((c = getopts(argc, argv, "b:f:kn:sqz", lo)))
  10137         switch (c) {
  10138         case 'b': cs_fmt = optarg; havefmt = 1; break; case 'f': cs_prefix = optarg; break; case 'k': cs_keep = 1; break;
  10139         case 'n': { unsigned long n; if (!parse_ulong(optarg, &n)) die(1, "%s: invalid number", optarg); ndig = n; break; }
  10140         case 's': case 'q': cs_quiet = 1; break; case 'z': cs_elide = 1; break; case 1000: cs_suppress = 1; break; default: break;
  10141         }
  10142     if (!nops) { say("missing operand"); usage_error(); }
  10143     if (nops < 2) { say("missing operand after '%s'", ops[0]); usage_error(); }
  10144     file = ops[0];
  10145     if (havefmt) cs_conv(cs_fmt);
  10146     else { char *f = xmalloc(24); snprintf(f, 24, "%%0%ud", ndig); cs_fmt = f; }
  10147     for (i = 1; i < nops; i++) {
  10148         const char *s = ops[i];
  10149         struct cspat *pt;
  10150         if (*s == '{') {
  10151             char *e;
  10152             struct cspat *prev = np ? &pats[np - 1] : NULL;
  10153             if (!prev || prev->rep || prev->inf) die(1, "'%s': invalid pattern", s);
  10154             if (!strcmp(s, "{*}")) { prev->inf = 1; continue; }
  10155             prev->rep = strtol(s + 1, &e, 10);
  10156             if (e == s + 1 || *e != '}' || e[1]) die(1, "'%.*s'}: integer required between '{' and '}'", (int)strlen(s) - 1, s);
  10157             continue;
  10158         }
  10159         pats = xrealloc(pats, (np + 1) * sizeof *pats);
  10160         pt = &pats[np++];
  10161         memset(pt, 0, sizeof *pt);
  10162         pt->text = (char *)s;
  10163         if (*s == '/' || *s == '%') {
  10164             char d = *s, *e = strrchr(s + 1, d), *tail;
  10165             struct rnode *nd;
  10166             if (!e) die(1, "%s: closing delimiter '%c' missing", s, d);
  10167             pt->kind = d == '/' ? 1 : 2;
  10168             tail = e + 1;
  10169             if (*tail == '+' || *tail == '-') {
  10170                 char *q;
  10171                 pt->off = strtol(tail, &q, 10);
  10172                 if (*q || q == tail + 1) die(1, "'%s': integer expected after delimiter", s);
  10173             } else if (*tail) die(1, "'%s': integer expected after delimiter", s);
  10174             pt->re = re_new(0);
  10175             nd = re_parse(pt->re, s + 1, e - s - 1, 0, 0);
  10176             re_finish(pt->re, nd);
  10177         } else if (isdigit((unsigned char)*s)) {
  10178             char *e;
  10179             pt->n = strtol(s, &e, 10);
  10180             if (*e) die(1, "'%s': invalid pattern", s);
  10181             if (!pt->n) die(1, "%s: line number must be greater than zero", s);
  10182             if (pt->n < prevn) die(1, "line number '%s' is smaller than preceding line number, %ld", s, prevn);
  10183             if (pt->n == prevn) say("warning: line number '%s' is the same as preceding line number", s);
  10184             prevn = pt->n;
  10185         } else die(1, "'%s': invalid pattern", s);
  10186     }
  10187     fd = open_input(file);
  10188     if (fd < 0) { say("cannot open '%s' for reading: %s", file, strerror(errno)); return 1; }
  10189     if (read_all(fd, &buf, &len) < 0) { perr("read error"); return 1; }
  10190     ls = xmalloc((len + 2) * sizeof *ls);
  10191     for (k = 0; k < len; ) {
  10192         const char *nl = memchr(buf + k, '\n', len - k);
  10193         ls[total++] = k;
  10194         k = nl ? (size_t)(nl - buf) + 1 : len;
  10195     }
  10196     ls[total] = len;
  10197     for (p = 0; p < np; p++) {
  10198         struct cspat *pt = &pats[p];
  10199         long nrep = pt->inf ? -1 : pt->rep;
  10200         skipfail = pt->kind == 2;
  10201         for (rep = 0; nrep < 0 || rep <= nrep; rep++) {
  10202             long split;
  10203             const char *what = pt->text;
  10204             char where[64];
  10205             where[0] = 0;
  10206             if (rep) snprintf(where, sizeof where, " on repetition %ld", rep);
  10207             if (pt->kind == 0) {
  10208                 long target = pt->n * (rep + 1);
  10209                 if (target > total || target < 1) { say("'%s': line number out of range%s", what, where); goto fail_rest; }
  10210                 split = target - 1;
  10211                 if (split < cur) { say("'%s': line number out of range%s", what, where); goto fail_rest; }
  10212                 if (cs_write(buf, ls, cur, split, total) < 0) goto fail_rest;
  10213                 cur = split; lastmatch = -1;
  10214                 if (cs_suppress && cur < total) cur++;
  10215             } else {
  10216                 long m = -1, start = cur > lastmatch + 1 ? cur : lastmatch + 1, j;
  10217                 for (j = start; j < total; j++) {
  10218                     size_t l = ls[j + 1] - ls[j];
  10219                     if (l && buf[ls[j] + l - 1] == '\n') l--;
  10220                     if (re_exec(pt->re, buf + ls[j], l, 0, 0, NULL)) { m = j; break; }
  10221                 }
  10222                 if (m < 0) {
  10223                     if (pt->inf && rep) goto done_inf;
  10224                     say("'%s': match not found%s", what, where);
  10225                     goto fail_rest;
  10226                 }
  10227                 split = m + pt->off;
  10228                 if (split < cur) { say("'%s': line number out of range%s", what, where); cur = total; goto fail_rest; }
  10229                 if (split > total) { say("'%s': line number out of range%s", what, where); goto fail_rest; }
  10230                 if (pt->kind == 1) { if (cs_write(buf, ls, cur, split, total) < 0) goto fail_rest; }
  10231                 cur = split; lastmatch = m;
  10232                 if (cs_suppress && pt->kind == 1 && cur < total) cur++;
  10233             }
  10234         }
  10235         continue;
  10236 done_inf:
  10237         goto finish;
  10238     }
  10239 finish:
  10240     if (cs_write(buf, ls, cur, total, total) < 0) { cs_cleanup(); return 1; }
  10241     if (cs_sizes) fputs(cs_sizes, stdout);
  10242     return finish_stdout() ? 1 : 0;
  10243 fail_rest:
  10244     if (!skipfail) cs_write(buf, ls, cur, total, total);
  10245     if (cs_sizes) fputs(cs_sizes, stdout);
  10246     cs_cleanup();
  10247     finish_stdout();
  10248     return 1;
  10249 }
  10250 
  10251 /* ---- numfmt ---- */
  10252 
  10253 enum { NF_NONE, NF_SI, NF_IEC, NF_IECI, NF_AUTO };
  10254 enum { RD_UP, RD_DOWN, RD_FROM_ZERO, RD_TOWARDS_ZERO, RD_NEAREST };
  10255 enum { IV_ABORT, IV_FAIL, IV_WARN, IV_IGNORE };
  10256 
  10257 static int nf_term = '\n', nf_from, nf_to, nf_round = RD_FROM_ZERO, nf_invalid, nf_pad, nf_haspad, nf_zeroflag, nf_left, nf_fw, nf_hasfw, nf_prec = -1, nf_status;
  10258 static double nf_fromunit = 1, nf_tounit = 1;
  10259 static const char *nf_suffix = "", *nf_fpre = "", *nf_fpost = "";
  10260 
  10261 static const char nf_letters[] = "KMGTPEZYRQ";
  10262 
  10263 static double nf_rnd(double x)
  10264 {
  10265     switch (nf_round) {
  10266     case RD_UP: return ceil(x);
  10267     case RD_DOWN: return floor(x);
  10268     case RD_FROM_ZERO: return x < 0 ? floor(x) : ceil(x);
  10269     case RD_TOWARDS_ZERO: return x < 0 ? ceil(x) : floor(x);
  10270     default: return x < 0 ? ceil(x - 0.5) : floor(x + 0.5);
  10271     }
  10272 }
  10273 
  10274 static double nf_round_to(double x, int prec)
  10275 {
  10276     double m = 1;
  10277     int i;
  10278     for (i = 0; i < prec; i++) m *= 10;
  10279     return nf_rnd(x * m) / m;
  10280 }
  10281 
  10282 static double nf_unit_arg(const char *s)
  10283 {
  10284     char *e;
  10285     double v = strtod(s, &e), m = 1;
  10286     if (e == s || v < 1 || v != floor(v)) die(1, "invalid unit size: '%s'", s);
  10287     if (*e) {
  10288         const char *q = strchr(nf_letters, *e);
  10289         int base = 1000, p;
  10290         if (!q) die(1, "invalid unit size: '%s'", s);
  10291         if (e[1] == 'i') { base = 1024; e++; }
  10292         if (e[1]) die(1, "invalid unit size: '%s'", s);
  10293         for (p = 0; p <= q - nf_letters; p++) m *= base;
  10294     }
  10295     return v * m;
  10296 }
  10297 
  10298 static char nf_orig[160];
  10299 
  10300 static int nf_parse(const char *tok0, double *val, int *decimals, int *scaled, char *err, size_t cap)
  10301 {
  10302     const char *tok = tok0, *p, *q, *dot;
  10303     char buf[512], *e;
  10304     size_t sl = strlen(nf_suffix), tl;
  10305     int digits = 0, hasdot = 0, seen_i = 0;
  10306     double mult = 1;
  10307     while (*tok == ' ' || *tok == '\t') tok++;
  10308     p = tok;
  10309     snprintf(buf, sizeof buf, "%s", p);
  10310     tl = strlen(buf);
  10311     while (tl && (buf[tl - 1] == ' ' || buf[tl - 1] == '\t')) buf[--tl] = 0;
  10312     if (sl && tl >= sl && !strcmp(buf + tl - sl, nf_suffix)) buf[tl - sl] = 0;
  10313     q = buf;
  10314     if (*q == '-') q++;
  10315     while (isdigit((unsigned char)*q) || (*q == '.' && !hasdot)) {
  10316         if (*q == '.') { hasdot = 1; if (!isdigit((unsigned char)q[1])) { digits = 0; break; } }
  10317         else digits++;
  10318         q++;
  10319     }
  10320     if (!digits) { snprintf(err, cap, "invalid number: '%s'", tok); return -1; }
  10321     dot = strchr(buf, '.');
  10322     *decimals = dot && dot < q ? (int)(q - dot - 1) : 0;
  10323     *val = strtod(buf, &e);
  10324     { size_t ol = q - buf; if (ol >= sizeof nf_orig) ol = sizeof nf_orig - 1; memcpy(nf_orig, buf, ol); nf_orig[ol] = 0; }
  10325     *scaled = 0;
  10326     if (*q) {
  10327         const char *l = isalpha((unsigned char)*q) ? strchr(nf_letters, toupper((unsigned char)*q)) : NULL;
  10328         if (!l || (islower((unsigned char)*q) && *q != 'k')) { snprintf(err, cap, "invalid suffix in input: '%s'", tok); return -1; }
  10329         if (nf_from == NF_NONE) { snprintf(err, cap, "rejecting suffix in input: '%s' (consider using --from)", tok); return -1; }
  10330         seen_i = q[1] == 'i';
  10331         if (seen_i && (nf_from == NF_SI || nf_from == NF_IEC)) { snprintf(err, cap, "invalid suffix in input '%s': 'i'", tok); return -1; }
  10332         if (q[1 + seen_i]) { snprintf(err, cap, "invalid suffix in input: '%s'", tok); return -1; }
  10333         if (nf_from == NF_IECI && !seen_i) { snprintf(err, cap, "missing 'i' suffix in input: '%s' (e.g Ki/Mi/Gi)", tok); return -1; }
  10334         { int base = nf_from == NF_SI ? 1000 : nf_from == NF_IEC ? 1024 : seen_i ? 1024 : 1000, k; for (k = 0; k <= l - nf_letters; k++) mult *= base; }
  10335         *scaled = 1;
  10336     }
  10337     *val = *val * mult * nf_fromunit;
  10338     if (nf_fromunit != 1) *scaled = 1;
  10339     return 0;
  10340 }
  10341 
  10342 static int nf_format(char *out, size_t cap, double v, int decimals, int scaled, char *err, size_t ecap)
  10343 {
  10344     char num[160], suf[16] = "", tail[64];
  10345     int prec = nf_prec, base = nf_to == NF_SI ? 1000 : 1024, power = 0, useorig = 0;
  10346     double x = v / nf_tounit;
  10347     if (nf_to == NF_NONE) {
  10348         if (prec >= 0) x = nf_round_to(x, prec);
  10349         else if (scaled || nf_tounit != 1) { x = nf_rnd(x); prec = 0; }
  10350         else { prec = decimals; useorig = 1; }
  10351         if (fabs(x) >= 1e19) { snprintf(err, ecap, "value too large to be printed: '%g' (consider using --to)", x); return -1; }
  10352         if (useorig) {
  10353             const char *o = nf_orig, *z;
  10354             int neg = *o == '-';
  10355             if (neg) o++;
  10356             while (o[0] == '0' && isdigit((unsigned char)o[1])) o++;
  10357             for (z = o; *z == '0' || *z == '.'; z++) ;
  10358             neg = neg && *z;
  10359             snprintf(num, sizeof num, "%s%s", neg ? "-" : "", o);
  10360         } else {
  10361             snprintf(num, sizeof num, "%.*f", prec, x);
  10362             if (x == 0 && num[0] == '-') memmove(num, num + 1, strlen(num));
  10363         }
  10364     } else {
  10365         double ax = fabs(x), r, sx;
  10366         int pp;
  10367         while (ax >= base && power < 10) { ax /= base; power++; }
  10368         sx = x < 0 ? -ax : ax;
  10369         if (!power && prec < 0 && ax < 10) {
  10370             double f = floor(ax), d = ax - f, e = d > 0.5 ? f + 1 : d < 0.5 ? f : fmod(f, 2) == 0 ? f : f + 1;
  10371             snprintf(num, sizeof num, "%s%.0f", x < 0 ? "-" : "", e);
  10372         } else if (!power && prec < 0 && fabs(r = nf_round_to(sx, 0)) < base) snprintf(num, sizeof num, "%.0f", r);
  10373         else if (!power && prec >= 0 && fabs(r = nf_round_to(sx, prec)) < base) snprintf(num, sizeof num, "%.*f", prec, r);
  10374         else {
  10375             if (!power) { sx /= base; ax /= base; power = 1; }
  10376             pp = prec >= 0 ? prec : (ax < 10 ? 1 : 0);
  10377             r = nf_round_to(sx, pp);
  10378             if (fabs(r) >= base && power < 10) { r /= base; power++; if (prec < 0) pp = fabs(r) < 10 ? 1 : 0; }
  10379             else if (prec < 0) pp = fabs(r) < 10 ? 1 : 0;
  10380             if (fabs(r) >= base) { snprintf(err, ecap, "value too large to be printed: '%g' (cannot handle values > 999Q)", v); return -1; }
  10381             snprintf(num, sizeof num, "%.*f", pp, r);
  10382             snprintf(suf, sizeof suf, "%c%s", power == 1 && nf_to == NF_SI ? 'k' : nf_letters[power - 1], nf_to == NF_IECI ? "i" : "");
  10383         }
  10384     }
  10385     snprintf(tail, sizeof tail, "%s%s", suf, nf_suffix);
  10386     {
  10387         int len = strlen(num), tl = strlen(tail), pad = nf_fw - len - tl;
  10388         char *r = out;
  10389         r += snprintf(r, cap, "%s", nf_fpre);
  10390         if (nf_hasfw && nf_zeroflag && !nf_left) {
  10391             pad = nf_fw - len;
  10392             while (pad-- > 0) *r++ = '0';
  10393             r += sprintf(r, "%s%s", num, tail);
  10394         } else {
  10395             if (nf_hasfw && !nf_left) while (pad-- > 0) *r++ = ' ';
  10396             r += sprintf(r, "%s%s", num, tail);
  10397             if (nf_hasfw && nf_left) while (pad-- > 0) *r++ = ' ';
  10398         }
  10399         strcpy(r, nf_fpost);
  10400     }
  10401     return 0;
  10402 }
  10403 
  10404 struct nfrange { long lo, hi; };
  10405 
  10406 static int nf_in(const struct nfrange *r, int n, long k)
  10407 {
  10408     int i;
  10409     for (i = 0; i < n; i++) if (k >= r[i].lo && k <= r[i].hi) return 1;
  10410     return 0;
  10411 }
  10412 
  10413 /* converts one field; the text that goes in its place lands in out */
  10414 static int nf_field(const char *fld, int wsmode, int first, char *out, size_t cap, char *err, size_t ecap)
  10415 {
  10416     double v;
  10417     int dec, scaled, lead = 0;
  10418     const char *p = fld;
  10419     char body[640];
  10420     while (*p == ' ' || *p == '\t') { p++; lead++; }
  10421     if (nf_parse(fld, &v, &dec, &scaled, err, ecap) < 0) return -1;
  10422     if (nf_format(body, sizeof body, v, dec, scaled, err, ecap) < 0) return -1;
  10423     if (nf_haspad && !nf_hasfw) {
  10424         int w = nf_pad < 0 ? -nf_pad : nf_pad, l = strlen(body), pad = w > l ? w - l : 0;
  10425         char *r = out;
  10426         if (wsmode && !first && lead) *r++ = ' ';
  10427         if (nf_pad >= 0) { while (pad-- > 0) *r++ = ' '; strcpy(r, body); }
  10428         else { strcpy(r, body); r += l; while (pad-- > 0) *r++ = ' '; *r = 0; }
  10429     } else if (wsmode && lead) {
  10430         int w = lead + (int)strlen(p), l = strlen(body), pad = w > l ? w - l : 0;
  10431         char *r = out;
  10432         while (pad-- > 0) *r++ = ' ';
  10433         strcpy(r, body);
  10434     } else snprintf(out, cap, "%s", body);
  10435     return 0;
  10436 }
  10437 
  10438 static void nf_line(const char *line, int delim, struct nfrange *rg, int nr)
  10439 {
  10440     char out[8192], err[700];
  10441     size_t o = 0, printed = 0;
  10442     int ws = delim < 0;
  10443     const char *p = line;
  10444     long k = 0;
  10445     if (!*p && nf_in(rg, nr, 1)) {
  10446         if (nf_field("", ws, 1, out, sizeof out, err, sizeof err) < 0) {
  10447             if (nf_invalid != IV_IGNORE) { fflush(stdout); say("%s", err); }
  10448             if (nf_invalid != IV_WARN && nf_invalid != IV_IGNORE) nf_status = 2;
  10449             if (nf_invalid == IV_ABORT) { finish_stdout(); exit(2); }
  10450         }
  10451         fputs(line, stdout); putchar(nf_term);
  10452         return;
  10453     }
  10454     out[0] = 0;
  10455     for (;;) {
  10456         const char *s = p, *e;
  10457         char fld[2048];
  10458         size_t fl;
  10459         k++;
  10460         if (ws) {
  10461             const char *t = p;
  10462             while (*t == ' ' || *t == '\t') t++;
  10463             if (!*t) { /* nothing left but blanks */ o += snprintf(out + o, sizeof out - o, "%s", p); break; }
  10464             while (*t && *t != ' ' && *t != '\t') t++;
  10465             e = t;
  10466         } else {
  10467             e = strchr(p, delim);
  10468             if (!e) e = p + strlen(p);
  10469         }
  10470         fl = e - s;
  10471         if (fl >= sizeof fld) fl = sizeof fld - 1;
  10472         memcpy(fld, s, fl);
  10473         fld[fl] = 0;
  10474         if (nf_in(rg, nr, k)) {
  10475             char conv[1024];
  10476             if (nf_field(fld, ws, k == 1, conv, sizeof conv, err, sizeof err) < 0) {
  10477                 size_t skip = ws && (*s == ' ' || *s == '\t');
  10478                 if (nf_invalid != IV_IGNORE) {
  10479                     fwrite(out + printed, 1, o - printed, stdout);
  10480                     if (skip) putchar(*s);
  10481                     printed = o + skip;
  10482                     fflush(stdout);
  10483                     say("%s", err);
  10484                 }
  10485                 if (nf_invalid != IV_WARN && nf_invalid != IV_IGNORE) nf_status = 2;
  10486                 if (nf_invalid == IV_ABORT) { finish_stdout(); exit(2); }
  10487                 if (printed > o) { o += snprintf(out + o, sizeof out - o, "%s", fld + skip); printed = o - strlen(fld + skip); }
  10488                 else o += snprintf(out + o, sizeof out - o, "%s", fld);
  10489             } else o += snprintf(out + o, sizeof out - o, "%s", conv);
  10490         } else o += snprintf(out + o, sizeof out - o, "%s", fld);
  10491         if (!*e) break;
  10492         if (!ws) { out[o++] = delim; out[o] = 0; }
  10493         p = ws ? e : e + 1;
  10494         if (ws && !*p) break;
  10495     }
  10496     fputs(out + printed, stdout); putchar(nf_term);
  10497 }
  10498 
  10499 static const char *nf_q(const char *s)
  10500 {
  10501     char *b = xmalloc(strlen(s) * 2 + 3), *p = b;
  10502     *p++ = '\'';
  10503     for (; *s; s++) { if (*s == '\'') *p++ = '\\'; *p++ = *s; }
  10504     *p++ = '\'';
  10505     *p = 0;
  10506     return b;
  10507 }
  10508 
  10509 static int nf_choice(const char *name, const char *arg, const char *const *list, int n)
  10510 {
  10511     int i, hit = -1;
  10512     for (i = 0; i < n; i++) {
  10513         if (!strcmp(list[i], arg)) return i;
  10514         if (!strncmp(list[i], arg, strlen(arg))) hit = hit == -1 ? i : -2;
  10515     }
  10516     if (hit >= 0) return hit;
  10517     say("invalid argument '%s' for '--%s'", arg, name);
  10518     fprintf(stderr, "Valid arguments are:\n");
  10519     for (i = 0; i < n; i++) fprintf(stderr, "  - '%s'\n", list[i]);
  10520     usage_error();
  10521     return 0;
  10522 }
  10523 
  10524 static int t_numfmt(int argc, char **argv)
  10525 {
  10526     static const struct opt lo[] = { { "from", 1, 1 }, { "to", 1, 2 }, { "from-unit", 1, 3 }, { "to-unit", 1, 4 }, { "round", 1, 5 }, { "suffix", 1, 6 },
  10527         { "padding", 1, 7 }, { "format", 1, 8 }, { "field", 1, 9 }, { "delimiter", 1, 'd' }, { "header", 2, 10 }, { "invalid", 1, 11 },
  10528         { "zero-terminated", 0, 'z' }, { "grouping", 0, 12 }, { "debug", 0, 13 }, { NULL, 0, 0 } };
  10529     static const char *const units[] = { "none", "si", "iec", "iec-i", "auto" };
  10530     static const char *const rounds[] = { "up", "down", "from-zero", "towards-zero", "nearest" };
  10531     static const char *const invs[] = { "abort", "fail", "warn", "ignore" };
  10532     int c, delim = -1, zero = 0, header = 0, nr = 0, group = 0, i;
  10533     const char *fmt = NULL, *fields = "1";
  10534     struct nfrange rg[64];
  10535     char *line = NULL;
  10536     size_t cap = 0;
  10537     ssize_t n;
  10538     opts_reset();
  10539     while ((c = getopts(argc, argv, "d:z", lo)))
  10540         switch (c) {
  10541         case 1: nf_from = nf_choice("from", optarg, units, 5); break;
  10542         case 2: nf_to = nf_choice("to", optarg, units, 4); break;
  10543         case 3: nf_fromunit = nf_unit_arg(optarg); break;
  10544         case 4: nf_tounit = nf_unit_arg(optarg); break;
  10545         case 5: nf_round = nf_choice("round", optarg, rounds, 5); break;
  10546         case 6: nf_suffix = optarg; break;
  10547         case 7: { char *e; long v = strtol(optarg, &e, 10); if (*e || !v) die(1, "invalid padding value '%s'", optarg); nf_pad = v; nf_haspad = 1; break; }
  10548         case 8: fmt = optarg; break;
  10549         case 9: fields = optarg; break;
  10550         case 'd': if (optarg[0] && optarg[1]) die(1, "the delimiter must be a single character"); delim = (unsigned char)optarg[0]; break;
  10551         case 10: if (optarg) { char *e; long v = strtol(optarg, &e, 10); if (*e || v < 1) die(1, "invalid header value '%s'", optarg); header = v; } else header = 1; break;
  10552         case 11: nf_invalid = nf_choice("invalid", optarg, invs, 4); break;
  10553         case 'z': zero = 1; break;
  10554         case 12: group = 1; break;
  10555         default: break;
  10556         }
  10557     if (fmt) {
  10558         const char *p = fmt;
  10559         int found = 0;
  10560         for (; *p; p++) {
  10561             const char *d;
  10562             if (*p != '%') continue;
  10563             if (p[1] == '%') { p++; continue; }
  10564             if (found) die(1, "format %s has too many %% directives", nf_q(fmt));
  10565             found = 1;
  10566             d = p + 1;
  10567             if (*d == '0') { nf_zeroflag = 1; d++; }
  10568             if (*d == '\'') { group = 1; d++; }
  10569             if (*d == '-') { nf_left = 1; d++; }
  10570             if (isdigit((unsigned char)*d)) { nf_fw = 0; nf_hasfw = 1; while (isdigit((unsigned char)*d)) nf_fw = nf_fw * 10 + *d++ - '0'; }
  10571             if (*d == '.') { d++; nf_prec = 0; while (isdigit((unsigned char)*d)) nf_prec = nf_prec * 10 + *d++ - '0'; }
  10572             if (*d != 'f') die(1, "invalid format %s, directive must be %%[0]['][-][N][.][N]f", nf_q(fmt));
  10573             { char *pre = xmalloc(p - fmt + 1); memcpy(pre, fmt, p - fmt); pre[p - fmt] = 0; nf_fpre = pre; }
  10574             nf_fpost = d + 1;
  10575             p = d;
  10576         }
  10577         if (!found) die(1, "format %s has no %% directive", nf_q(fmt));
  10578     }
  10579     if (group && nf_to != NF_NONE) die(1, "grouping cannot be combined with --to");
  10580     {
  10581         const char *p = fields;
  10582         while (*p) {
  10583             char *e;
  10584             long lo_ = 1, hi = 1000000;
  10585             if (*p == '-') { p++; hi = isdigit((unsigned char)*p) ? strtol(p, &e, 10) : 1000000; if (!isdigit((unsigned char)*p)) e = (char *)p; }
  10586             else {
  10587                 lo_ = strtol(p, &e, 10);
  10588                 if (e == p || lo_ < 1) die(1, "invalid field value '%s'", fields);
  10589                 hi = lo_;
  10590                 if (*e == '-') { p = e + 1; if (isdigit((unsigned char)*p)) hi = strtol(p, &e, 10); else { hi = 1000000; e = (char *)p; } }
  10591             }
  10592             p = e;
  10593             if (nr == 64) die(1, "too many fields");
  10594             rg[nr].lo = lo_; rg[nr].hi = hi; nr++;
  10595             if (*p == ',') p++; else if (*p) die(1, "invalid field value '%s'", fields);
  10596         }
  10597     }
  10598     if (zero) nf_term = 0;
  10599     if (nops) {
  10600         for (i = 0; i < nops; i++) nf_line(ops[i], delim, rg, nr);
  10601     } else {
  10602         long ln = 0;
  10603         while ((n = getdelim(&line, &cap, zero ? 0 : '\n', stdin)) >= 0) {
  10604             if (n && line[n - 1] == (zero ? 0 : '\n')) line[--n] = 0;
  10605             if (++ln <= header) { fputs(line, stdout); putchar(nf_term); continue; }
  10606             nf_line(line, delim, rg, nr);
  10607         }
  10608     }
  10609     return finish_stdout() ? 1 : nf_status;
  10610 }
  10611 
  10612 static const char *const dc_db[] = {
  10613     "# colors for ls --color, in the dircolors format\n",
  10614     "# TERM and COLORTERM lines say which terminals the lines after them are for\n",
  10615     "\n",
  10616     "COLORTERM ?*\n",
  10617     "TERM Eterm\n",
  10618     "TERM ansi\n",
  10619     "TERM *color*\n",
  10620     "TERM con[0-9]*x[0-9]*\n",
  10621     "TERM cons25\n",
  10622     "TERM console\n",
  10623     "TERM cygwin\n",
  10624     "TERM *direct*\n",
  10625     "TERM dtterm\n",
  10626     "TERM gnome\n",
  10627     "TERM hurd\n",
  10628     "TERM jfbterm\n",
  10629     "TERM konsole\n",
  10630     "TERM kterm\n",
  10631     "TERM linux\n",
  10632     "TERM linux-c\n",
  10633     "TERM mlterm\n",
  10634     "TERM putty\n",
  10635     "TERM rxvt*\n",
  10636     "TERM screen*\n",
  10637     "TERM st\n",
  10638     "TERM terminator\n",
  10639     "TERM tmux*\n",
  10640     "TERM vt100\n",
  10641     "TERM vt220\n",
  10642     "TERM xterm*\n",
  10643     "\n",
  10644     "# file types\n",
  10645     "RESET 0\n",
  10646     "DIR 01;34\n",
  10647     "LINK 01;36\n",
  10648     "MULTIHARDLINK 00\n",
  10649     "FIFO 40;33\n",
  10650     "SOCK 01;35\n",
  10651     "DOOR 01;35\n",
  10652     "BLK 40;33;01\n",
  10653     "CHR 40;33;01\n",
  10654     "ORPHAN 01;05;37;41\n",
  10655     "MISSING 01;05;37;41\n",
  10656     "SETUID 37;41\n",
  10657     "SETGID 30;43\n",
  10658     "CAPABILITY 00\n",
  10659     "STICKY_OTHER_WRITABLE 30;42\n",
  10660     "OTHER_WRITABLE 34;42\n",
  10661     "STICKY 37;44\n",
  10662     "EXEC 01;32\n",
  10663     "\n",
  10664     "# file name endings\n",
  10665     ".7z 01;31\n",
  10666     ".ace 01;31\n",
  10667     ".alz 01;31\n",
  10668     ".apk 01;31\n",
  10669     ".arc 01;31\n",
  10670     ".arj 01;31\n",
  10671     ".bz 01;31\n",
  10672     ".bz2 01;31\n",
  10673     ".cab 01;31\n",
  10674     ".cpio 01;31\n",
  10675     ".crate 01;31\n",
  10676     ".deb 01;31\n",
  10677     ".drpm 01;31\n",
  10678     ".dwm 01;31\n",
  10679     ".dz 01;31\n",
  10680     ".ear 01;31\n",
  10681     ".egg 01;31\n",
  10682     ".esd 01;31\n",
  10683     ".gz 01;31\n",
  10684     ".jar 01;31\n",
  10685     ".lha 01;31\n",
  10686     ".lrz 01;31\n",
  10687     ".lz 01;31\n",
  10688     ".lz4 01;31\n",
  10689     ".lzh 01;31\n",
  10690     ".lzma 01;31\n",
  10691     ".lzo 01;31\n",
  10692     ".pyz 01;31\n",
  10693     ".rar 01;31\n",
  10694     ".rpm 01;31\n",
  10695     ".rz 01;31\n",
  10696     ".sar 01;31\n",
  10697     ".swm 01;31\n",
  10698     ".t7z 01;31\n",
  10699     ".tar 01;31\n",
  10700     ".taz 01;31\n",
  10701     ".tbz 01;31\n",
  10702     ".tbz2 01;31\n",
  10703     ".tgz 01;31\n",
  10704     ".tlz 01;31\n",
  10705     ".txz 01;31\n",
  10706     ".tz 01;31\n",
  10707     ".tzo 01;31\n",
  10708     ".tzst 01;31\n",
  10709     ".udeb 01;31\n",
  10710     ".war 01;31\n",
  10711     ".whl 01;31\n",
  10712     ".wim 01;31\n",
  10713     ".xz 01;31\n",
  10714     ".z 01;31\n",
  10715     ".zip 01;31\n",
  10716     ".zoo 01;31\n",
  10717     ".zst 01;31\n",
  10718     ".avif 01;35\n",
  10719     ".jpg 01;35\n",
  10720     ".jpeg 01;35\n",
  10721     ".jxl 01;35\n",
  10722     ".mjpg 01;35\n",
  10723     ".mjpeg 01;35\n",
  10724     ".gif 01;35\n",
  10725     ".bmp 01;35\n",
  10726     ".pbm 01;35\n",
  10727     ".pgm 01;35\n",
  10728     ".ppm 01;35\n",
  10729     ".tga 01;35\n",
  10730     ".xbm 01;35\n",
  10731     ".xpm 01;35\n",
  10732     ".tif 01;35\n",
  10733     ".tiff 01;35\n",
  10734     ".png 01;35\n",
  10735     ".svg 01;35\n",
  10736     ".svgz 01;35\n",
  10737     ".mng 01;35\n",
  10738     ".pcx 01;35\n",
  10739     ".mov 01;35\n",
  10740     ".mpg 01;35\n",
  10741     ".mpeg 01;35\n",
  10742     ".m2v 01;35\n",
  10743     ".mkv 01;35\n",
  10744     ".webm 01;35\n",
  10745     ".webp 01;35\n",
  10746     ".ogm 01;35\n",
  10747     ".mp4 01;35\n",
  10748     ".m4v 01;35\n",
  10749     ".mp4v 01;35\n",
  10750     ".vob 01;35\n",
  10751     ".qt 01;35\n",
  10752     ".nuv 01;35\n",
  10753     ".wmv 01;35\n",
  10754     ".asf 01;35\n",
  10755     ".rm 01;35\n",
  10756     ".rmvb 01;35\n",
  10757     ".flc 01;35\n",
  10758     ".avi 01;35\n",
  10759     ".fli 01;35\n",
  10760     ".flv 01;35\n",
  10761     ".gl 01;35\n",
  10762     ".dl 01;35\n",
  10763     ".xcf 01;35\n",
  10764     ".xwd 01;35\n",
  10765     ".yuv 01;35\n",
  10766     ".cgm 01;35\n",
  10767     ".emf 01;35\n",
  10768     ".ogv 01;35\n",
  10769     ".ogx 01;35\n",
  10770     ".cfg 00;32\n",
  10771     ".conf 00;32\n",
  10772     ".diff 00;32\n",
  10773     ".doc 00;32\n",
  10774     ".ini 00;32\n",
  10775     ".log 00;32\n",
  10776     ".patch 00;32\n",
  10777     ".pdf 00;32\n",
  10778     ".ps 00;32\n",
  10779     ".tex 00;32\n",
  10780     ".txt 00;32\n",
  10781     ".aac 00;36\n",
  10782     ".au 00;36\n",
  10783     ".flac 00;36\n",
  10784     ".m4a 00;36\n",
  10785     ".mid 00;36\n",
  10786     ".midi 00;36\n",
  10787     ".mka 00;36\n",
  10788     ".mp3 00;36\n",
  10789     ".mpc 00;36\n",
  10790     ".ogg 00;36\n",
  10791     ".ra 00;36\n",
  10792     ".wav 00;36\n",
  10793     ".oga 00;36\n",
  10794     ".opus 00;36\n",
  10795     ".spx 00;36\n",
  10796     ".xspf 00;36\n",
  10797     "*~ 00;90\n",
  10798     "*# 00;90\n",
  10799     ".bak 00;90\n",
  10800     ".crdownload 00;90\n",
  10801     ".dpkg-dist 00;90\n",
  10802     ".dpkg-new 00;90\n",
  10803     ".dpkg-old 00;90\n",
  10804     ".dpkg-tmp 00;90\n",
  10805     ".old 00;90\n",
  10806     ".orig 00;90\n",
  10807     ".part 00;90\n",
  10808     ".rej 00;90\n",
  10809     ".rpmnew 00;90\n",
  10810     ".rpmorig 00;90\n",
  10811     ".rpmsave 00;90\n",
  10812     ".swp 00;90\n",
  10813     ".tmp 00;90\n",
  10814     ".ucf-dist 00;90\n",
  10815     ".ucf-new 00;90\n",
  10816     ".ucf-old 00;90\n",
  10817     NULL };
  10818 
  10819 static const struct { const char *kw, *key; } dc_keys[] = {
  10820     { "RESET", "rs" }, { "NORMAL", "no" }, { "NORM", "no" }, { "FILE", "fi" }, { "DIR", "di" }, { "LNK", "ln" }, { "LINK", "ln" }, { "SYMLINK", "ln" },
  10821     { "ORPHAN", "or" }, { "MISSING", "mi" }, { "FIFO", "pi" }, { "PIPE", "pi" }, { "SOCK", "so" }, { "BLK", "bd" }, { "BLOCK", "bd" }, { "CHR", "cd" },
  10822     { "CHAR", "cd" }, { "DOOR", "do" }, { "EXEC", "ex" }, { "LEFT", "lc" }, { "LEFTCODE", "lc" }, { "RIGHT", "rc" }, { "RIGHTCODE", "rc" },
  10823     { "END", "ec" }, { "ENDCODE", "ec" }, { "SUID", "su" }, { "SETUID", "su" }, { "SGID", "sg" }, { "SETGID", "sg" }, { "STICKY", "st" },
  10824     { "OTHER_WRITABLE", "ow" }, { "OWR", "ow" }, { "STICKY_OTHER_WRITABLE", "tw" }, { "OWT", "tw" }, { "CAPABILITY", "ca" }, { "MULTIHARDLINK", "mh" },
  10825     { "CLRTOEOL", "cl" }, { NULL, NULL } };
  10826 
  10827 static void dc_quote(char **buf, size_t *len, size_t *cap, const char *s, size_t n)
  10828 {
  10829     size_t i;
  10830     for (i = 0; i < n; i++) {
  10831         char t[8];
  10832         int k;
  10833         if (s[i] == '\'') memcpy(t, "'\\''", k = 4);
  10834         else if (s[i] == ':' || s[i] == '=') { t[0] = '\\'; t[1] = s[i]; k = 2; }
  10835         else { t[0] = s[i]; k = 1; }
  10836         if (*len + k + 1 > *cap) { *cap = *cap * 2 + 64; *buf = xrealloc(*buf, *cap); }
  10837         memcpy(*buf + *len, t, k);
  10838         *len += k;
  10839     }
  10840 }
  10841 
  10842 static void dc_add(char **buf, size_t *len, size_t *cap, const char *s, size_t n)
  10843 {
  10844     if (*len + n + 1 > *cap) { *cap = *cap * 2 + n + 64; *buf = xrealloc(*buf, *cap); }
  10845     memcpy(*buf + *len, s, n);
  10846     *len += n;
  10847 }
  10848 
  10849 static int t_dircolors(int argc, char **argv)
  10850 {
  10851     static const struct opt lo[] = { { "bourne-shell", 0, 'b' }, { "sh", 0, 'b' }, { "csh", 0, 'c' }, { "c-shell", 0, 'c' }, { "print-database", 0, 'p' },
  10852         { "print-ls-colors", 0, 1000 }, { NULL, 0, 0 } };
  10853     int c, shell = 0, print = 0, lscolors = 0, ok = 1, state = 0, i;
  10854     const char *term = getenv("TERM"), *cterm = getenv("COLORTERM");
  10855     char *buf = NULL;
  10856     size_t len = 0, cap = 0, lineno = 0;
  10857     FILE *f = NULL;
  10858     char *line = NULL, *lp;
  10859     size_t lcap = 0;
  10860     const char *file = NULL;
  10861     opts_reset();
  10862     while ((c = getopts(argc, argv, "bcp", lo)))
  10863         switch (c) { case 'b': shell = 1; break; case 'c': shell = 2; break; case 'p': print = 1; break; case 1000: lscolors = 1; break; default: break; }
  10864     if (nops > 1) extra_operand(ops[1]);
  10865     if (print && nops) {
  10866         say("extra operand '%s'", ops[0]);
  10867         fprintf(stderr, "file operands cannot be combined with --print-database (-p)\n");
  10868         usage_error();
  10869     }
  10870     if (print && shell) { say("the options to output non shell syntax,\nand to select a shell syntax are mutually exclusive"); usage_error(); }
  10871     if (print) {
  10872         for (i = 0; dc_db[i]; i++) fputs(dc_db[i], stdout);
  10873         return finish_stdout() ? 1 : 0;
  10874     }
  10875     if (!shell && !lscolors) {
  10876         const char *sh = getenv("SHELL");
  10877         size_t l;
  10878         if (!sh || !*sh) die(1, "no SHELL environment variable, and no shell type option given");
  10879         l = strlen(sh);
  10880         shell = (l >= 3 && !strcmp(sh + l - 3, "csh")) ? 2 : 1;
  10881     }
  10882     file = nops ? ops[0] : NULL;
  10883     if (file) {
  10884         f = !strcmp(file, "-") ? stdin : fopen(file, "r");
  10885         if (!f) { perr("%s", file); return 1; }
  10886     }
  10887     if (!term) term = "none";
  10888     i = 0;
  10889     for (;;) {
  10890         char *kw, *arg, *e;
  10891         size_t kl;
  10892         int k;
  10893         if (f) { ssize_t n = getline(&line, &lcap, f); if (n < 0) break; lp = line; }
  10894         else { if (!dc_db[i]) break; lcap = strlen(dc_db[i]) + 1; line = xrealloc(line, lcap); strcpy(line, dc_db[i++]); lp = line; }
  10895         lineno++;
  10896         while (*lp == ' ' || *lp == '\t') lp++;
  10897         if (!*lp || *lp == '#' || *lp == '\n') continue;
  10898         e = lp + strlen(lp);
  10899         while (e > lp && (e[-1] == '\n' || e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r')) *--e = 0;
  10900         kw = lp;
  10901         while (*lp && *lp != ' ' && *lp != '\t') lp++;
  10902         kl = lp - kw;
  10903         if (*lp) *lp++ = 0;
  10904         while (*lp == ' ' || *lp == '\t') lp++;
  10905         if (!*lp || *lp == '#') { say("%s:%zu: invalid line;  missing second token", file ? file : "<internal>", lineno); ok = 0; continue; }
  10906         arg = lp;
  10907         while (*lp && *lp != ' ' && *lp != '\t') lp++;
  10908         *lp = 0;
  10909         if (!strcasecmp(kw, "TERM") || !strcasecmp(kw, "COLORTERM")) {
  10910             const char *env = kw[0] == 'T' || kw[0] == 't' ? term : cterm;
  10911             if (env && glob_match(arg, env)) state = 3;
  10912             else if (state != 3) state = 1;
  10913             continue;
  10914         }
  10915         if (state == 3) state = 2;
  10916         if (state == 1) continue;
  10917         if (!strcasecmp(kw, "COLOR") || !strcasecmp(kw, "OPTIONS") || !strcasecmp(kw, "EIGHTBIT")) continue;
  10918         if (*kw == '*' || *kw == '.') {
  10919             if (*kw == '.') dc_add(&buf, &len, &cap, "*", 1);
  10920             dc_quote(&buf, &len, &cap, kw, kl);
  10921             dc_add(&buf, &len, &cap, "=", 1);
  10922         } else {
  10923             for (k = 0; dc_keys[k].kw; k++) if (!strcasecmp(kw, dc_keys[k].kw)) break;
  10924             if (!dc_keys[k].kw) { say("%s:%zu: unrecognized keyword %s", file ? file : "<internal>", lineno, kw); ok = 0; continue; }
  10925             dc_add(&buf, &len, &cap, dc_keys[k].key, 2);
  10926             dc_add(&buf, &len, &cap, "=", 1);
  10927         }
  10928         dc_quote(&buf, &len, &cap, arg, strlen(arg));
  10929         dc_add(&buf, &len, &cap, ":", 1);
  10930     }
  10931     if (f && f != stdin) fclose(f);
  10932     if (!ok) return 1;
  10933     if (!buf) buf = xstrdup("");
  10934     buf[len] = 0;
  10935     if (lscolors) {
  10936         char *p = buf;
  10937         while (*p) {
  10938             char *v = NULL, *q = p, key[256], val[256];
  10939             size_t kn = 0, vn = 0;
  10940             while (*q && *q != ':') {
  10941                 if (!strncmp(q, "'\\''", 4)) { if (v) { if (vn < sizeof val - 1) val[vn++] = '\''; } else if (kn < sizeof key - 1) key[kn++] = '\''; q += 4; continue; }
  10942                 if (*q == '\\' && q[1]) q++;
  10943                 if (*q == '=' && !v && q[-1] != '\\') { v = q + 1; q++; continue; }
  10944                 if (v) { if (vn < sizeof val - 1) val[vn++] = *q; } else if (kn < sizeof key - 1) key[kn++] = *q;
  10945                 q++;
  10946             }
  10947             key[kn] = val[vn] = 0;
  10948             printf("\033[%sm%s\t%s\033[0m\n", val, key, val);
  10949             p = *q ? q + 1 : q;
  10950         }
  10951         return finish_stdout() ? 1 : 0;
  10952     }
  10953     if (shell == 2) printf("setenv LS_COLORS '%s'\n", buf);
  10954     else printf("LS_COLORS='%s';\nexport LS_COLORS\n", buf);
  10955     return finish_stdout() ? 1 : 0;
  10956 }
  10957 
  10958 /* ---- stty ---- */
  10959 
  10960 struct ktermios { unsigned iflag, oflag, cflag, lflag; unsigned char line, cc[19]; unsigned ispeed, ospeed; };
  10961 
  10962 enum { SM_I, SM_O, SM_C, SM_L };
  10963 
  10964 struct stmode { const char *name; int type; unsigned bits, mask; int sane; };
  10965 /* sane: 1 is set by sane, 2 is cleared by it, 0 is left alone */
  10966 static const struct stmode st_modes[] = {
  10967     { "parenb", SM_C, 0x100, 0x100, 2 }, { "parodd", SM_C, 0x200, 0x200, 2 }, { "cmspar", SM_C, 0x40000000, 0x40000000, 2 },
  10968     { "cs5", SM_C, 0, 0x30, 0 }, { "cs6", SM_C, 0x10, 0x30, 0 }, { "cs7", SM_C, 0x20, 0x30, 0 }, { "cs8", SM_C, 0x30, 0x30, 1 },
  10969     { "hupcl", SM_C, 0x400, 0x400, 0 }, { "hup", SM_C, 0x400, 0x400, 0 }, { "cstopb", SM_C, 0x40, 0x40, 2 }, { "cread", SM_C, 0x80, 0x80, 1 },
  10970     { "clocal", SM_C, 0x800, 0x800, 2 }, { "crtscts", SM_C, 0x80000000, 0x80000000, 2 },
  10971     { "ignbrk", SM_I, 1, 1, 2 }, { "brkint", SM_I, 2, 2, 1 }, { "ignpar", SM_I, 4, 4, 0 }, { "parmrk", SM_I, 8, 8, 0 }, { "inpck", SM_I, 0x10, 0x10, 0 },
  10972     { "istrip", SM_I, 0x20, 0x20, 0 }, { "inlcr", SM_I, 0x40, 0x40, 2 }, { "igncr", SM_I, 0x80, 0x80, 2 }, { "icrnl", SM_I, 0x100, 0x100, 1 },
  10973     { "ixon", SM_I, 0x400, 0x400, 0 }, { "ixoff", SM_I, 0x1000, 0x1000, 2 }, { "tandem", SM_I, 0x1000, 0x1000, 2 }, { "iuclc", SM_I, 0x200, 0x200, 2 },
  10974     { "ixany", SM_I, 0x800, 0x800, 2 }, { "imaxbel", SM_I, 0x2000, 0x2000, 1 }, { "iutf8", SM_I, 0x4000, 0x4000, 2 },
  10975     { "opost", SM_O, 1, 1, 1 }, { "olcuc", SM_O, 2, 2, 2 }, { "ocrnl", SM_O, 8, 8, 2 }, { "onlcr", SM_O, 4, 4, 1 }, { "onocr", SM_O, 0x10, 0x10, 2 },
  10976     { "onlret", SM_O, 0x20, 0x20, 2 }, { "ofill", SM_O, 0x40, 0x40, 2 }, { "ofdel", SM_O, 0x80, 0x80, 2 },
  10977     { "nl0", SM_O, 0, 0x100, 1 }, { "nl1", SM_O, 0x100, 0x100, 0 }, { "cr0", SM_O, 0, 0x600, 1 }, { "cr1", SM_O, 0x200, 0x600, 0 },
  10978     { "cr2", SM_O, 0x400, 0x600, 0 }, { "cr3", SM_O, 0x600, 0x600, 0 }, { "tab0", SM_O, 0, 0x1800, 1 }, { "tab1", SM_O, 0x800, 0x1800, 0 },
  10979     { "tab2", SM_O, 0x1000, 0x1800, 0 }, { "tab3", SM_O, 0x1800, 0x1800, 0 }, { "bs0", SM_O, 0, 0x2000, 1 }, { "bs1", SM_O, 0x2000, 0x2000, 0 },
  10980     { "vt0", SM_O, 0, 0x4000, 1 }, { "vt1", SM_O, 0x4000, 0x4000, 0 }, { "ff0", SM_O, 0, 0x8000, 1 }, { "ff1", SM_O, 0x8000, 0x8000, 0 },
  10981     { "isig", SM_L, 1, 1, 1 }, { "icanon", SM_L, 2, 2, 1 }, { "iexten", SM_L, 0x8000, 0x8000, 1 }, { "echo", SM_L, 8, 8, 1 }, { "echoe", SM_L, 0x10, 0x10, 1 },
  10982     { "crterase", SM_L, 0x10, 0x10, 1 }, { "echok", SM_L, 0x20, 0x20, 1 }, { "echonl", SM_L, 0x40, 0x40, 2 }, { "noflsh", SM_L, 0x80, 0x80, 2 },
  10983     { "xcase", SM_L, 4, 4, 2 }, { "tostop", SM_L, 0x100, 0x100, 2 }, { "echoprt", SM_L, 0x400, 0x400, 2 }, { "prterase", SM_L, 0x400, 0x400, 2 },
  10984     { "echoctl", SM_L, 0x200, 0x200, 1 }, { "ctlecho", SM_L, 0x200, 0x200, 1 }, { "echoke", SM_L, 0x800, 0x800, 1 }, { "crtkill", SM_L, 0x800, 0x800, 1 },
  10985     { "flusho", SM_L, 0x1000, 0x1000, 2 }, { "extproc", SM_L, 0x10000, 0x10000, 2 }, { NULL, 0, 0, 0, 0 } };
  10986 
  10987 /* the order -a lists them in, a group per line. a mask with several names is one choice among them */
  10988 static const char *const st_show[4][32] = {
  10989     { "parenb", "parodd", "cmspar", "cs", "hupcl", "cstopb", "cread", "clocal", "crtscts", NULL },
  10990     { "ignbrk", "brkint", "ignpar", "parmrk", "inpck", "istrip", "inlcr", "igncr", "icrnl", "ixon", "ixoff", "iuclc", "ixany", "imaxbel", "iutf8", NULL },
  10991     { "opost", "olcuc", "ocrnl", "onlcr", "onocr", "onlret", "ofill", "ofdel", "nl", "cr", "tab", "bs", "vt", "ff", NULL },
  10992     { "isig", "icanon", "iexten", "echo", "echoe", "echok", "echonl", "noflsh", "xcase", "tostop", "echoprt", "echoctl", "echoke", "flusho", "extproc", NULL } };
  10993 
  10994 static const struct { const char *name; int idx; unsigned char def; } st_chars[] = {
  10995     { "intr", 0, 3 }, { "quit", 1, 28 }, { "erase", 2, 127 }, { "kill", 3, 21 }, { "eof", 4, 4 }, { "eol", 11, 0 }, { "eol2", 16, 0 }, { "swtch", 7, 0 },
  10996     { "start", 8, 17 }, { "stop", 9, 19 }, { "susp", 10, 26 }, { "rprnt", 12, 18 }, { "werase", 14, 23 }, { "lnext", 15, 22 }, { "discard", 13, 15 },
  10997     { NULL, 0, 0 } };
  10998 
  10999 static const struct { unsigned code; long speed; } st_speeds[] = { { 0, 0 }, { 1, 50 }, { 2, 75 }, { 3, 110 }, { 4, 134 }, { 5, 150 }, { 6, 200 }, { 7, 300 },
  11000     { 8, 600 }, { 9, 1200 }, { 10, 1800 }, { 11, 2400 }, { 12, 4800 }, { 13, 9600 }, { 14, 19200 }, { 15, 38400 }, { 0x1001, 57600 }, { 0x1002, 115200 },
  11001     { 0x1003, 230400 }, { 0x1004, 460800 }, { 0x1005, 500000 }, { 0x1006, 576000 }, { 0x1007, 921600 }, { 0x1008, 1000000 }, { 0x1009, 1152000 },
  11002     { 0x100a, 1500000 }, { 0x100b, 2000000 }, { 0x100c, 2500000 }, { 0x100d, 3000000 }, { 0x100e, 3500000 }, { 0x100f, 4000000 }, { 0, -1 } };
  11003 
  11004 static int st_col, st_max = 80;
  11005 
  11006 static void st_wrap(const char *fmt, ...)
  11007 {
  11008     char buf[200];
  11009     va_list ap;
  11010     int n;
  11011     va_start(ap, fmt);
  11012     vsnprintf(buf, sizeof buf, fmt, ap);
  11013     va_end(ap);
  11014     n = strlen(buf);
  11015     if (st_col > 0) {
  11016         if (st_col + n + 1 >= st_max) { putchar('\n'); st_col = 0; }
  11017         else { putchar(' '); st_col++; }
  11018     }
  11019     fputs(buf, stdout);
  11020     st_col += n;
  11021 }
  11022 
  11023 static void st_nl(void) { if (st_col) putchar('\n'); st_col = 0; }
  11024 
  11025 static unsigned *st_field(struct ktermios *t, int type) { return type == SM_I ? &t->iflag : type == SM_O ? &t->oflag : type == SM_C ? &t->cflag : &t->lflag; }
  11026 
  11027 static const char *st_char(unsigned char c, char *buf)
  11028 {
  11029     char *p = buf;
  11030     if (!c) return "<undef>";
  11031     if (c >= 128) { *p++ = 'M'; *p++ = '-'; c -= 128; }
  11032     if (c < 32) { *p++ = '^'; *p++ = c + 64; }
  11033     else if (c == 127) { *p++ = '^'; *p++ = '?'; }
  11034     else *p++ = c;
  11035     *p = 0;
  11036     return buf;
  11037 }
  11038 
  11039 static void st_norm(struct ktermios *t)
  11040 {
  11041     int j;
  11042     if (t->cflag & 0x100f0000u) return;
  11043     for (j = 0; st_speeds[j].speed >= 0; j++)
  11044         if (st_speeds[j].speed == (long)t->ispeed) { t->cflag |= (st_speeds[j].code & 0xf) << 16 | (st_speeds[j].code & 0x1000) << 16; return; }
  11045     t->cflag |= 0x10000000u;
  11046 }
  11047 
  11048 static int st_find(const char *name)
  11049 {
  11050     int i;
  11051     for (i = 0; st_modes[i].name; i++) if (!strcmp(st_modes[i].name, name)) return i;
  11052     return -1;
  11053 }
  11054 
  11055 static int st_on(const struct ktermios *t, const struct stmode *m)
  11056 {
  11057     unsigned v = m->type == SM_I ? t->iflag : m->type == SM_O ? t->oflag : m->type == SM_C ? t->cflag : t->lflag;
  11058     return (v & m->mask) == m->bits;
  11059 }
  11060 
  11061 static void st_set(struct ktermios *t, const char *name, int on)
  11062 {
  11063     int i = st_find(name);
  11064     unsigned *f;
  11065     if (i < 0) return;
  11066     f = st_field(t, st_modes[i].type);
  11067     if (on) *f = (*f & ~st_modes[i].mask) | st_modes[i].bits;
  11068     else *f &= ~st_modes[i].mask;
  11069 }
  11070 
  11071 static void st_sane(struct ktermios *t)
  11072 {
  11073     int i;
  11074     for (i = 0; st_modes[i].name; i++) {
  11075         if (st_modes[i].sane == 1) st_set(t, st_modes[i].name, 1);
  11076         else if (st_modes[i].sane == 2) st_set(t, st_modes[i].name, 0);
  11077     }
  11078     for (i = 0; st_chars[i].name; i++) t->cc[st_chars[i].idx] = st_chars[i].def;
  11079     t->cc[6] = 1; t->cc[5] = 0;
  11080 }
  11081 
  11082 static void st_print(const struct ktermios *t, int all, int ws_rows, int ws_cols, int havews)
  11083 {
  11084     int g, i;
  11085     long ibaud = t->ispeed, obaud = t->ospeed;
  11086     char cb[8];
  11087     st_col = 0;
  11088     {
  11089         const char *c = getenv("COLUMNS");
  11090         char *e;
  11091         long v = c ? strtol(c, &e, 10) : 0;
  11092         st_max = c && *c && !*e && v > 0 ? (int)v : 80;
  11093     }
  11094     if (ibaud && ibaud != obaud) { st_wrap("ispeed %ld baud;", ibaud); st_wrap("ospeed %ld baud;", obaud); }
  11095     else st_wrap("speed %ld baud;", obaud);
  11096     if (all && havews) { st_wrap("rows %d;", ws_rows); st_wrap("columns %d;", ws_cols); }
  11097     st_wrap("line = %d;", t->line);
  11098     st_nl();
  11099     for (i = 0; st_chars[i].name; i++) {
  11100         unsigned char c = t->cc[st_chars[i].idx];
  11101         if (all || c != st_chars[i].def) st_wrap("%s = %s;", st_chars[i].name, st_char(c, cb));
  11102     }
  11103     if (all || !(t->lflag & 2)) { st_wrap("min = %d;", t->cc[6]); st_wrap("time = %d;", t->cc[5]); }
  11104     st_nl();
  11105     for (g = 0; g < 4; g++) {
  11106         for (i = 0; st_show[g][i]; i++) {
  11107             const char *n = st_show[g][i];
  11108             int k;
  11109             if (!strcmp(n, "cs") || !strcmp(n, "nl") || !strcmp(n, "cr") || !strcmp(n, "tab") || !strcmp(n, "bs") || !strcmp(n, "vt") || !strcmp(n, "ff")) {
  11110                 char nm[8];
  11111                 int j, best = -1;
  11112                 for (j = 0; j < 8; j++) {
  11113                     snprintf(nm, sizeof nm, "%s%d", n, !strcmp(n, "cs") ? j + 5 : j);
  11114                     k = st_find(nm);
  11115                     if (k >= 0 && st_on(t, &st_modes[k])) { best = k; break; }
  11116                 }
  11117                 if (best >= 0 && (all || st_modes[best].sane != 1 ? 0 : 0)) { }
  11118                 if (best >= 0) {
  11119                     int saneval = 0;
  11120                     for (k = 0; st_modes[k].name; k++) if (!strncmp(st_modes[k].name, n, strlen(n)) && st_modes[k].mask == st_modes[best].mask && st_modes[k].sane == 1) saneval = k;
  11121                     if (all || best != saneval) st_wrap("%s", st_modes[best].name);
  11122                 }
  11123                 continue;
  11124             }
  11125             k = st_find(n);
  11126             if (k < 0) continue;
  11127             {
  11128                 int on = st_on(t, &st_modes[k]);
  11129                 if (all) st_wrap("%s%s", on ? "" : "-", n);
  11130                 else if (st_modes[k].sane == 1 && !on) st_wrap("-%s", n);
  11131                 else if (st_modes[k].sane == 2 && on) st_wrap("%s", n);
  11132             }
  11133         }
  11134         st_nl();
  11135     }
  11136 }
  11137 
  11138 static int st_charval(const char *s, unsigned char *out)
  11139 {
  11140     char *e;
  11141     if (!strcmp(s, "^-") || !strcmp(s, "undef")) { *out = 0; return 0; }
  11142     if (s[0] == '^' && s[1] && !s[2]) { *out = s[1] == '?' ? 127 : (s[1] & 31); return 0; }
  11143     if (s[0] && !s[1]) { *out = (unsigned char)s[0]; return 0; }
  11144     { long v = strtol(s, &e, 0); if (*e || v < 0 || v > 255) return -1; *out = v; return 0; }
  11145 }
  11146 
  11147 static int t_stty(int argc, char **argv)
  11148 {
  11149     struct ktermios t, orig;
  11150     int i, fd = 0, all = 0, save = 0, nset = 0, havews = 0;
  11151     const char *dev = NULL;
  11152     struct { unsigned short r, c, x, y; } ws = { 0, 0, 0, 0 };
  11153     int a;
  11154     char **sv = xmalloc((argc + 1) * sizeof *sv);
  11155     int ns = 0;
  11156     for (a = 1; a < argc; a++) {
  11157         const char *s = argv[a];
  11158         if (!strcmp(s, "-a") || !strcmp(s, "--all")) all = 1;
  11159         else if (!strcmp(s, "-g") || !strcmp(s, "--save")) save = 1;
  11160         else if (!strcmp(s, "-F") || !strcmp(s, "--file")) { if (a + 1 >= argc) { say("option requires an argument -- 'F'"); usage_error(); } dev = argv[++a]; }
  11161         else if (!strncmp(s, "--file=", 7)) dev = s + 7;
  11162         else if (!strncmp(s, "-F", 2) && s[2]) dev = s + 2;
  11163         else if (!strcmp(s, "--help")) { print_usage(); return 0; }
  11164         else if (!strcmp(s, "--version")) { printf("stty (rifle) " VERSION "\n"); return 0; }
  11165         else sv[ns++] = argv[a];
  11166     }
  11167     if (dev) { fd = open(dev, O_RDONLY | O_NONBLOCK); if (fd < 0) { perr("%s", dev); return 1; } }
  11168     if (ioctl(fd, 0x802c542a, &t) < 0) { say("%s: %s", dev ? dev : "'standard input'", strerror(errno)); return 1; }
  11169     st_norm(&t);
  11170     orig = t;
  11171     if (ioctl(fd, 0x5413, &ws) == 0) havews = 1;
  11172     if ((all || save) && ns) die(1, "when specifying an output style, modes may not be set");
  11173     if (all && save) die(1, "the options for verbose and stty-readable output styles are\nmutually exclusive");
  11174     if (save) {
  11175         int k;
  11176         printf("%x:%x:%x:%x", t.iflag, t.oflag, t.cflag, t.lflag);
  11177         for (k = 0; k < 32; k++) printf(":%x", k < 19 ? t.cc[k] : 0);
  11178         putchar('\n');
  11179         return finish_stdout() ? 1 : 0;
  11180     }
  11181     if (!ns) { st_print(&t, all, ws.r, ws.c, havews); return finish_stdout() ? 1 : 0; }
  11182     for (i = 0; i < ns; i++) {
  11183         const char *s = sv[i];
  11184         int neg = s[0] == '-' && s[1], k;
  11185         const char *name = neg ? s + 1 : s;
  11186         char *e;
  11187         if (!strcmp(s, "size")) { if (!havews) die(1, "%s: %s", dev ? dev : "standard input", strerror(ENOTTY)); printf("%d %d\n", ws.r, ws.c); continue; }
  11188         if (!strcmp(s, "speed")) { printf("%u\n", t.ospeed); continue; }
  11189         if (!strcmp(s, "sane")) { st_sane(&t); nset = 1; continue; }
  11190         if (!strcmp(name, "raw") || !strcmp(name, "cooked")) {
  11191             int raw = (!strcmp(name, "raw")) != neg;
  11192             static const char *const off[] = { "ignbrk", "brkint", "ignpar", "parmrk", "inpck", "istrip", "inlcr", "igncr", "icrnl", "ixon", "ixoff", "icanon", "opost", "isig", "iuclc", "ixany", "imaxbel", "xcase", NULL };
  11193             static const char *const on[] = { "brkint", "ignpar", "istrip", "icrnl", "ixon", "opost", "isig", "icanon", NULL };
  11194             int j;
  11195             if (raw) { for (j = 0; off[j]; j++) st_set(&t, off[j], 0); t.cc[6] = 1; t.cc[5] = 0; }
  11196             else { for (j = 0; on[j]; j++) st_set(&t, on[j], 1); t.cc[4] = 4; t.cc[11] = 0; }
  11197             nset = 1; continue;
  11198         }
  11199         if (!strcmp(name, "cbreak")) { st_set(&t, "icanon", neg); nset = 1; continue; }
  11200         if (!strcmp(name, "evenp") || !strcmp(name, "parity")) { if (neg) { st_set(&t, "parenb", 0); st_set(&t, "cs8", 1); } else { st_set(&t, "parenb", 1); st_set(&t, "parodd", 0); st_set(&t, "cs7", 1); } nset = 1; continue; }
  11201         if (!strcmp(name, "oddp")) { if (neg) { st_set(&t, "parenb", 0); st_set(&t, "cs8", 1); } else { st_set(&t, "parenb", 1); st_set(&t, "parodd", 1); st_set(&t, "cs7", 1); } nset = 1; continue; }
  11202         if (!strcmp(name, "pass8")) { if (neg) { st_set(&t, "parenb", 1); st_set(&t, "istrip", 1); st_set(&t, "cs7", 1); } else { st_set(&t, "parenb", 0); st_set(&t, "istrip", 0); st_set(&t, "cs8", 1); } nset = 1; continue; }
  11203         if (!strcmp(name, "litout")) { if (neg) { st_set(&t, "parenb", 1); st_set(&t, "istrip", 1); st_set(&t, "opost", 1); st_set(&t, "cs7", 1); } else { st_set(&t, "parenb", 0); st_set(&t, "istrip", 0); st_set(&t, "opost", 0); st_set(&t, "cs8", 1); } nset = 1; continue; }
  11204         if (!strcmp(name, "nl")) { if (neg) { st_set(&t, "icrnl", 1); st_set(&t, "inlcr", 0); st_set(&t, "igncr", 0); st_set(&t, "onlcr", 1); st_set(&t, "ocrnl", 0); st_set(&t, "onlret", 0); } else { st_set(&t, "icrnl", 0); st_set(&t, "onlcr", 0); } nset = 1; continue; }
  11205         if (!strcmp(s, "ek")) { t.cc[2] = 127; t.cc[3] = 21; nset = 1; continue; }
  11206         if (!strcmp(name, "crt")) { st_set(&t, "echoe", 1); st_set(&t, "echoctl", 1); st_set(&t, "echoke", 1); nset = 1; continue; }
  11207         if (!strcmp(s, "dec")) { st_set(&t, "echoe", 1); st_set(&t, "echoctl", 1); st_set(&t, "echoke", 1); st_set(&t, "ixany", 0); t.cc[0] = 3; t.cc[2] = 127; t.cc[3] = 21; nset = 1; continue; }
  11208         if (!strcmp(name, "decctlq")) { st_set(&t, "ixany", neg); nset = 1; continue; }
  11209         if (!strcmp(name, "tabs")) { if (neg) st_set(&t, "tab3", 1); else st_set(&t, "tab0", 1); nset = 1; continue; }
  11210         if (!strcmp(name, "lcase") || !strcmp(name, "LCASE")) { st_set(&t, "xcase", !neg); st_set(&t, "iuclc", !neg); st_set(&t, "olcuc", !neg); nset = 1; continue; }
  11211         if ((k = st_find(name)) >= 0 && (!neg || st_modes[k].mask != st_modes[k].bits || st_modes[k].type == SM_C || 1)) {
  11212             if (neg && (!strncmp(name, "cs", 2) || !strncmp(name, "nl", 2) || !strncmp(name, "cr", 2) || !strncmp(name, "tab", 3) || !strncmp(name, "bs", 2) || !strncmp(name, "vt", 2) || !strncmp(name, "ff", 2)) && isdigit((unsigned char)name[strlen(name) - 1]))
  11213                 { say("invalid argument '%s'", s); usage_error(); }
  11214             st_set(&t, name, !neg);
  11215             nset = 1;
  11216             continue;
  11217         }
  11218         if (!neg) {
  11219             int j, ch = -1;
  11220             for (j = 0; st_chars[j].name; j++) if (!strcmp(st_chars[j].name, s)) ch = st_chars[j].idx;
  11221             if (ch >= 0 || !strcmp(s, "min") || !strcmp(s, "time")) {
  11222                 unsigned char v;
  11223                 if (i + 1 >= ns) { say("missing argument to '%s'", s); usage_error(); }
  11224                 i++;
  11225                 if (ch < 0) { long n = strtol(sv[i], &e, 0); if (*e || n < 0 || n > 255) die(1, "invalid integer argument: '%s'", sv[i]); v = n; ch = s[1] == 'i' && s[0] == 'm' ? 6 : 5; if (!strcmp(s, "min")) ch = 6; else ch = 5; }
  11226                 else if (st_charval(sv[i], &v) < 0) die(1, "invalid integer argument: '%s'", sv[i]);
  11227                 t.cc[ch] = v; nset = 1; continue;
  11228             }
  11229             if (!strcmp(s, "rows") || !strcmp(s, "cols") || !strcmp(s, "columns")) {
  11230                 long n;
  11231                 if (i + 1 >= ns) { say("missing argument to '%s'", s); usage_error(); }
  11232                 n = strtol(sv[++i], &e, 0);
  11233                 if (*e || n < 0) die(1, "invalid integer argument: '%s'", sv[i]);
  11234                 if (s[0] == 'r') ws.r = n; else ws.c = n;
  11235                 ioctl(fd, 0x5414, &ws);
  11236                 continue;
  11237             }
  11238             if (!strcmp(s, "line")) {
  11239                 long n;
  11240                 if (i + 1 >= ns) { say("missing argument to '%s'", s); usage_error(); }
  11241                 n = strtol(sv[++i], &e, 0);
  11242                 if (*e || n < 0 || n > 255) die(1, "invalid integer argument: '%s'", sv[i]);
  11243                 t.line = n; nset = 1; continue;
  11244             }
  11245             if (!strcmp(s, "ispeed") || !strcmp(s, "ospeed") || (isdigit((unsigned char)s[0]) && !strchr(s, ':'))) {
  11246                 const char *v = isdigit((unsigned char)s[0]) ? s : (i + 1 < ns ? sv[++i] : NULL);
  11247                 int j, found = -1;
  11248                 long sp;
  11249                 if (!v) { say("missing argument to '%s'", s); usage_error(); }
  11250                 sp = strtol(v, &e, 10);
  11251                 if (*e) die(1, "invalid %s speed '%s'", !strcmp(s, "ispeed") ? "input" : !strcmp(s, "ospeed") ? "output" : "output", v);
  11252                 for (j = 0; st_speeds[j].speed >= 0; j++) if (st_speeds[j].speed == sp) found = j;
  11253                 {
  11254                     unsigned code = found >= 0 ? st_speeds[found].code : 0x1000;
  11255                     int setin = strcmp(s, "ospeed"), setout = strcmp(s, "ispeed");
  11256                     if (setout) { t.cflag = (t.cflag & ~0x100fu) | code; t.ospeed = sp; }
  11257                     if (setin) { t.cflag = (t.cflag & ~0x100f0000u) | (code & 0xf) << 16 | (code & 0x1000) << 16; t.ispeed = sp; }
  11258                 }
  11259                 nset = 1; continue;
  11260             }
  11261             if (strchr(s, ':')) {
  11262                 unsigned long v4[4];
  11263                 int n = 0, k2, j2;
  11264                 char *p = (char *)s;
  11265                 unsigned long cc[32];
  11266                 for (j2 = 0; j2 < 4; j2++) {
  11267                     char *e2;
  11268                     v4[j2] = strtoul(p, &e2, 16);
  11269                     if (e2 == p || (j2 < 3 && *e2 != ':')) { say("invalid argument '%s'", s); usage_error(); }
  11270                     p = e2;
  11271                     if (j2 < 3) p++;
  11272                 }
  11273                 for (k2 = 0; k2 < 32 && *p == ':'; k2++) { cc[k2] = strtoul(p + 1, &p, 16); n++; }
  11274                 if (n != 32 || *p) { say("invalid argument '%s'", s); usage_error(); }
  11275                 t.iflag = v4[0]; t.oflag = v4[1]; t.cflag = v4[2]; t.lflag = v4[3];
  11276                 for (k2 = 0; k2 < 19 && k2 < n; k2++) t.cc[k2] = cc[k2];
  11277                 nset = 1; continue;
  11278             }
  11279         }
  11280         { say("invalid argument '%s'", s); usage_error(); }
  11281     }
  11282     if (nset && memcmp(&t, &orig, sizeof t) != 0) {
  11283         struct ktermios back;
  11284         if (ioctl(fd, 0x402c542b, &t) < 0) { say("%s: %s", dev ? dev : "'standard input'", strerror(errno)); return 1; }
  11285         if (ioctl(fd, 0x802c542a, &back) < 0 || (st_norm(&back), 0) || back.iflag != t.iflag || back.oflag != t.oflag || (back.cflag & ~0xf0000000u) != (t.cflag & ~0xf0000000u) || back.lflag != t.lflag || memcmp(back.cc, t.cc, 19))
  11286             die(1, "%s: unable to perform all requested operations", dev ? dev : "'standard input'");
  11287     }
  11288     return finish_stdout() ? 1 : 0;
  11289 }
  11290 
  11291 /* ---- pr ---- */
  11292 
  11293 struct prfile { char **ln; size_t n; const char *name; time_t mtime; };
  11294 
  11295 static int pr_cols = 1, pr_across, pr_ctl, pr_double, pr_ff, pr_join, pr_merge, pr_nohead, pr_number, pr_numw = 5, pr_ctlv, pr_offset, pr_plen = 66,
  11296     pr_pwidth = 72, pr_trunc, pr_expand, pr_ecnt = 8, pr_ichar, pr_iwidth = 8, pr_sepset, pr_ssep, pr_wset;
  11297 static char pr_echar = '\t', pr_nsep = '\t';
  11298 static const char *pr_sepstr, *pr_header, *pr_datefmt = "%Y-%m-%d %H:%M";
  11299 static long pr_first = 1, pr_last = 0, pr_nstart = 1;
  11300 
  11301 static void pr_read(struct prfile *f, int fd)
  11302 {
  11303     char *buf;
  11304     size_t len, i, start = 0, cap = 0;
  11305     f->n = 0; f->ln = NULL;
  11306     if (read_all(fd, &buf, &len) < 0) return;
  11307     for (i = 0; i <= len; i++) {
  11308         if (i == len ? i > start : buf[i] == '\n') {
  11309             if (f->n == cap) { cap = cap ? cap * 2 : 64; f->ln = xrealloc(f->ln, cap * sizeof *f->ln); }
  11310             f->ln[f->n] = xmalloc(i - start + 1);
  11311             memcpy(f->ln[f->n], buf + start, i - start);
  11312             f->ln[f->n][i - start] = 0;
  11313             f->n++;
  11314             start = i + 1;
  11315         }
  11316     }
  11317 }
  11318 
  11319 static int pr_dispw(const char *s, int col)
  11320 {
  11321     for (; *s; s++) col = *s == '\t' ? col + 8 - col % 8 : col + 1;
  11322     return col;
  11323 }
  11324 
  11325 /* the text of one line as it will be shown: -e tabs expanded, controls made visible */
  11326 static char *pr_text(const char *s)
  11327 {
  11328     size_t cap = strlen(s) * 4 + 16, o = 0;
  11329     char *out = xmalloc(cap);
  11330     int col = 0;
  11331     for (; *s; s++) {
  11332         unsigned char c = *s;
  11333         if (o + 8 > cap) { cap *= 2; out = xrealloc(out, cap); }
  11334         if (pr_expand && (c == (unsigned char)pr_echar || c == '\t')) { int w = pr_ecnt - col % pr_ecnt; while (w--) { out[o++] = ' '; col++; } continue; }
  11335         if (pr_ctl && c < 32 && c != '\t') { out[o++] = '^'; out[o++] = c + 64; col += 2; continue; }
  11336         if (pr_ctl && c == 127) { out[o++] = '^'; out[o++] = '?'; col += 2; continue; }
  11337         if ((pr_ctl || pr_ctlv) && c >= 128) { o += sprintf(out + o, "\\%03o", c); col += 4; continue; }
  11338         if (pr_ctlv && c < 32 && c != '\t') { o += sprintf(out + o, "\\%03o", c); col += 4; continue; }
  11339         out[o++] = c;
  11340         col = c == '\t' ? col + 8 - col % 8 : col + 1;
  11341     }
  11342     out[o] = 0;
  11343     return out;
  11344 }
  11345 
  11346 static void pr_pad(char **buf, size_t *o, size_t *cap, int from, int to)
  11347 {
  11348     while (*o + (size_t)(to - from) + 8 > *cap) { *cap = *cap * 2 + 64; *buf = xrealloc(*buf, *cap); }
  11349     if (!pr_sepset) while (from / 8 < to / 8) { (*buf)[(*o)++] = '\t'; from = (from / 8 + 1) * 8; }
  11350     while (from < to) { (*buf)[(*o)++] = ' '; from++; }
  11351 }
  11352 
  11353 static void pr_compress(char *line)
  11354 {
  11355     char *out = xmalloc(strlen(line) + 1), *p = line, *o = out;
  11356     int col = 0;
  11357     while (*p) {
  11358         if (*p == ' ') {
  11359             const char *q = p;
  11360             int c2 = col;
  11361             while (*q == ' ') { q++; c2++; }
  11362             while (col / pr_iwidth < c2 / pr_iwidth) {
  11363                 int next = (col / pr_iwidth + 1) * pr_iwidth;
  11364                 if (next > c2) break;
  11365                 if (next - col < 2) break;
  11366                 *o++ = pr_ichar;
  11367                 col = next;
  11368             }
  11369             while (col < c2) { *o++ = ' '; col++; }
  11370             p = (char *)q;
  11371         } else { *o++ = *p; col = *p == '\t' ? col + 8 - col % 8 : col + 1; p++; }
  11372     }
  11373     *o = 0;
  11374     strcpy(line, out);
  11375     free(out);
  11376 }
  11377 
  11378 static void pr_header_lines(const char *hdr, time_t mt, long page)
  11379 {
  11380     char date[128], pg[32], line[1024];
  11381     int avail, hl = strlen(hdr), lhs, rhs, i;
  11382     struct tm *tm = localtime(&mt);
  11383     strftime(date, sizeof date, pr_datefmt, tm);
  11384     snprintf(pg, sizeof pg, "Page %ld", page);
  11385     avail = pr_pwidth - (int)strlen(date) - (int)strlen(pg);
  11386     lhs = (avail - hl) / 2;
  11387     if (lhs < 1) lhs = 1;
  11388     rhs = avail - hl - lhs;
  11389     if (rhs < 1) rhs = 1;
  11390     snprintf(line, sizeof line, "%s%*s%s%*s%s", date, lhs, "", hdr, rhs, "", pg);
  11391     for (i = 0; i < pr_offset; i++) putchar(' ');
  11392     putchar('\n');
  11393     putchar('\n');
  11394     for (i = 0; i < pr_offset; i++) putchar(' ');
  11395     puts(line);
  11396     putchar('\n');
  11397     putchar('\n');
  11398 }
  11399 
  11400 /* the numbered, cut-to-fit text of one cell. tabstart says whether a tab after the number stays a tab */
  11401 static char *pr_cell(const char *s, long num, int limit, int keeptab)
  11402 {
  11403     char *t = pr_text(s), *r;
  11404     size_t cap = strlen(t) + 64;
  11405     int o = 0;
  11406     r = xmalloc(cap);
  11407     if (num >= 0) {
  11408         o = sprintf(r, "%*ld", pr_numw, num);
  11409         if (pr_nsep == '\t' && !keeptab) { int w = 8 - pr_numw % 8; while (w--) r[o++] = ' '; }
  11410         else r[o++] = pr_nsep;
  11411     }
  11412     snprintf(r + o, cap - o, "%s", t);
  11413     free(t);
  11414     if (limit > 0) {
  11415         int col = 0;
  11416         char *p = r;
  11417         for (; *p; p++) {
  11418             int nc = *p == '\t' ? col + 8 - col % 8 : col + 1;
  11419             if (nc > limit) { *p = 0; break; }
  11420             col = nc;
  11421         }
  11422     }
  11423     return r;
  11424 }
  11425 
  11426 static int t_pr(int argc, char **argv)
  11427 {
  11428     static const struct opt lo[] = { { "across", 0, 'a' }, { "show-control-characters", 0, 'c' }, { "double-space", 0, 'd' }, { "date-format", 1, 'D' },
  11429         { "expand-tabs", 2, 'e' }, { "form-feed", 0, 'F' }, { "header", 1, 'h' }, { "output-tabs", 2, 'i' }, { "join-lines", 0, 'J' }, { "length", 1, 'l' },
  11430         { "merge", 0, 'm' }, { "number-lines", 2, 'n' }, { "first-line-number", 1, 'N' }, { "indent", 1, 'o' }, { "no-file-warnings", 0, 'r' },
  11431         { "separator", 2, 's' }, { "sep-string", 2, 'S' }, { "omit-header", 0, 't' }, { "omit-pagination", 0, 'T' }, { "show-nonprinting", 0, 'v' },
  11432         { "width", 1, 'w' }, { "page-width", 1, 'W' }, { "columns", 1, 1000 }, { NULL, 0, 0 } };
  11433     int c, i, nf = 0, lastdig = 0, hdrset = 0, ncolsarg = 0;
  11434     struct prfile *files;
  11435     unsigned long v;
  11436     opts_reset();
  11437     while ((c = getopts(argc, argv, "0123456789acdD:e::fFh:i::Jl:mn::N:o:rs::S::tTvw:W:", lo))) {
  11438         if (c >= '0' && c <= '9') { pr_cols = lastdig ? pr_cols * 10 + (c - '0') : c - '0'; lastdig = 1; ncolsarg = 1; continue; }
  11439         lastdig = 0;
  11440         switch (c) {
  11441         case 1000: if (!parse_ulong(optarg, &v) || !v) die(1, "invalid number of columns: '%s'", optarg); pr_cols = v; ncolsarg = 1; break;
  11442         case 'a': pr_across = 1; break; case 'c': pr_ctl = 1; break; case 'd': pr_double = 1; break; case 'D': pr_datefmt = optarg; break;
  11443         case 'e': pr_expand = 1; if (optarg && *optarg) { if (!isdigit((unsigned char)optarg[0])) { pr_echar = optarg[0]; optarg++; } if (*optarg) pr_ecnt = atoi(optarg); } break;
  11444         case 'f': case 'F': pr_ff = 1; break; case 'h': pr_header = optarg; hdrset = 1; break;
  11445         case 'i': pr_ichar = '\t'; if (optarg && *optarg) { if (!isdigit((unsigned char)optarg[0])) { pr_ichar = optarg[0]; optarg++; } if (*optarg) pr_iwidth = atoi(optarg); } break;
  11446         case 'J': pr_join = 1; break;
  11447         case 'l': if (!parse_ulong(optarg, &v) || !v) die(1, "'-l PAGE_LENGTH' invalid number of lines: '%s': Numerical result out of range", optarg); pr_plen = v; break;
  11448         case 'm': pr_merge = 1; break;
  11449         case 'n': pr_number = 1; if (optarg && *optarg) { if (!isdigit((unsigned char)optarg[0])) { pr_nsep = optarg[0]; optarg++; } if (*optarg) pr_numw = atoi(optarg); } break;
  11450         case 'N': { char *e; pr_nstart = strtol(optarg, &e, 10); if (*e) die(1, "invalid line number field width: '%s'", optarg); break; }
  11451         case 'o': if (!parse_ulong(optarg, &v)) die(1, "'-o MARGIN' invalid line offset: '%s'", optarg); pr_offset = v; break;
  11452         case 's': pr_sepset = 1; pr_sepstr = optarg && *optarg ? optarg : "\t"; break;
  11453         case 'S': pr_ssep = 1; pr_sepstr = optarg && *optarg ? optarg : " "; break;
  11454         case 't': pr_nohead = 1; break; case 'T': pr_nohead = 1; break; case 'v': pr_ctlv = 1; break;
  11455         case 'w': if (!parse_ulong(optarg, &v) || !v) die(1, "'-w PAGE_WIDTH' invalid number of characters: '%s': Numerical result out of range", optarg); pr_pwidth = v; pr_wset = 1; break;
  11456         case 'W': if (!parse_ulong(optarg, &v) || !v) die(1, "'-W PAGE_WIDTH' invalid number of characters: '%s': Numerical result out of range", optarg); pr_pwidth = v; pr_trunc = 1; pr_wset = 1; break;
  11457         default: break;
  11458         }
  11459     }
  11460     if (pr_merge && ncolsarg && pr_cols > 1) die(1, "cannot specify number of columns when printing in parallel");
  11461     if (pr_merge && pr_across) die(1, "cannot specify both printing across and printing in parallel");
  11462     files = xmalloc((nops + 2) * sizeof *files);
  11463     for (i = 0; i < nops; i++) {
  11464         if (ops[i][0] == '+') {
  11465             char *e;
  11466             pr_first = strtol(ops[i] + 1, &e, 10);
  11467             if (*e == ':') pr_last = strtol(e + 1, &e, 10);
  11468             if (*e || pr_first < 1) die(1, "invalid page range '%s'", ops[i]);
  11469             continue;
  11470         }
  11471         {
  11472             int fd = open_input(ops[i]);
  11473             struct stat st;
  11474             if (fd < 0) { say("%s: %s", ops[i], strerror(errno)); return 1; }
  11475             files[nf].name = ops[i];
  11476             files[nf].mtime = !strcmp(ops[i], "-") || fstat(fd, &st) < 0 || !S_ISREG(st.st_mode) ? time(NULL) : st.st_mtime;
  11477             pr_read(&files[nf], fd);
  11478             if (fd) close(fd);
  11479             nf++;
  11480         }
  11481     }
  11482     if (!nf) {
  11483         files[0].name = "-"; files[0].mtime = time(NULL);
  11484         pr_read(&files[0], 0);
  11485         nf = 1;
  11486     }
  11487     {
  11488         int hdr_lines = pr_nohead || pr_plen <= 10 ? 0 : 5, body = hdr_lines ? pr_plen - 10 : pr_plen;
  11489         int ncol = pr_merge ? nf : pr_cols, width, sepw = (pr_ssep || pr_sepset) ? (int)strlen(pr_sepstr) : 0;
  11490         int fi, nrun = pr_merge ? 1 : nf;
  11491         long page_no;
  11492         if (ncol < 1) ncol = 1;
  11493         width = (pr_pwidth - sepw * (ncol - 1)) / ncol;
  11494         if (pr_double) body = (body + 1) / 2;
  11495         for (fi = 0; fi < nrun; fi++) {
  11496             struct prfile *f = &files[fi];
  11497             long pos = 0, total = pr_merge ? 0 : (long)f->n, line_no = pr_nstart;
  11498             int npages = 0;
  11499             size_t j;
  11500             if (pr_merge) { for (j = 0; j < (size_t)nf; j++) if ((long)files[j].n > total) total = files[j].n; }
  11501             if (!total) { if (pr_first > 1) say("starting page number %ld exceeds page count 1", pr_first); continue; }
  11502             {
  11503                 long per = ncol > 1 && !pr_merge ? (long)body * ncol : body;
  11504                 npages = (total + per - 1) / per;
  11505                 if (pr_first > npages) { say("starting page number %ld exceeds page count %d", pr_first, npages); }
  11506             }
  11507             for (page_no = 1; pos < total; page_no++) {
  11508                 int cnt, cc, r, heights[64];
  11509                 long chunk, per;
  11510                 char **rows;
  11511                 int nrows = 0, show = page_no >= pr_first && (!pr_last || page_no <= pr_last);
  11512                 per = ncol > 1 && !pr_merge ? (long)body * ncol : body;
  11513                 chunk = total - pos < per ? total - pos : per;
  11514                 cnt = pr_merge || ncol == 1 ? (int)chunk : pr_across ? (int)((chunk + ncol - 1) / ncol) : (int)(chunk / ncol + (chunk % ncol ? 1 : 0));
  11515                 if (ncol <= 64) for (cc = 0; cc < ncol; cc++) heights[cc] = (int)(chunk / ncol) + (cc < chunk % ncol);
  11516                 rows = xmalloc((body + 1) * sizeof *rows);
  11517                 for (r = 0; r < cnt; r++) {
  11518                     char *buf = xmalloc(256);
  11519                     size_t o = 0, cap = 256;
  11520                     int curcol = pr_offset;
  11521                     buf[0] = 0;
  11522                     for (cc = 0; cc < ncol; cc++) {
  11523                         long idx = -1;
  11524                         const char *src = NULL;
  11525                         long num = -1;
  11526                         char *cell;
  11527                         int target = pr_offset + cc * (width + sepw), keeptab = cc == 0 || pr_across || pr_merge;
  11528                         if (pr_merge) { idx = pos + r; if (idx < (long)files[cc].n) { src = files[cc].ln[idx]; num = pr_number && cc == 0 ? line_no + r : -1; } }
  11529                         else if (ncol == 1) { idx = pos + r; src = f->ln[idx]; num = pr_number ? line_no + r : -1; }
  11530                         else if (pr_across) { idx = pos + (long)r * ncol + cc; if (idx < pos + chunk) { src = f->ln[idx]; num = pr_number ? line_no + (idx - pos) : -1; } }
  11531                         else {
  11532                             long start = 0, k;
  11533                             for (k = 0; k < cc; k++) start += heights[k];
  11534                             if (r < heights[cc]) { idx = pos + start + r; src = f->ln[idx]; num = pr_number ? line_no + (idx - pos) : -1; }
  11535                         }
  11536                         if (!src) {
  11537                             if (pr_merge) src = "";
  11538                             else continue;
  11539                         }
  11540                         cell = pr_cell(src, num, ncol > 1 && !pr_join && !pr_sepset && !(pr_ssep && cc == ncol - 1) ? width - (pr_ssep ? 0 : 1) : (ncol == 1 && pr_trunc && !pr_join ? pr_pwidth : 0), keeptab);
  11541                         if (cc > 0) {
  11542                             if (pr_join) { size_t sl = strlen(pr_sepstr ? pr_sepstr : "\t"); const char *sp = pr_sepstr ? pr_sepstr : "\t"; while (o + sl + 1 > cap) { cap *= 2; buf = xrealloc(buf, cap); } memcpy(buf + o, sp, sl); o += sl; curcol = pr_dispw(sp, curcol); }
  11543                             else if (pr_sepset) { size_t sl = strlen(pr_sepstr); while (o + sl + 1 > cap) { cap *= 2; buf = xrealloc(buf, cap); } memcpy(buf + o, pr_sepstr, sl); o += sl; curcol += sl; }
  11544                             else if (pr_ssep) { size_t sl = strlen(pr_sepstr); pr_pad(&buf, &o, &cap, curcol, target - sepw); while (o + sl + 1 > cap) { cap *= 2; buf = xrealloc(buf, cap); } memcpy(buf + o, pr_sepstr, sl); o += sl; curcol = target; }
  11545                             else { pr_pad(&buf, &o, &cap, curcol, target); curcol = target; }
  11546                         }
  11547                         {
  11548                             size_t cl = strlen(cell);
  11549                             while (o + cl + 1 > cap) { cap *= 2; buf = xrealloc(buf, cap); }
  11550                             memcpy(buf + o, cell, cl);
  11551                             o += cl;
  11552                             buf[o] = 0;
  11553                             curcol = pr_dispw(cell, curcol);
  11554                         }
  11555                         free(cell);
  11556                     }
  11557                     buf[o] = 0;
  11558                     if (pr_ichar) pr_compress(buf);
  11559                     rows[nrows++] = buf;
  11560                 }
  11561                 if (show) {
  11562                     int printed = 0;
  11563                     if (hdr_lines) pr_header_lines(pr_merge && !hdrset ? "" : hdrset ? pr_header : (!strcmp(f->name, "-") ? "" : f->name), pr_merge ? time(NULL) : f->mtime, page_no);
  11564                     for (r = 0; r < nrows; r++) {
  11565                         int k;
  11566                         for (k = 0; k < pr_offset; k++) putchar(' ');
  11567                         fputs(rows[r], stdout);
  11568                         putchar('\n');
  11569                         printed++;
  11570                         if (pr_double) { putchar('\n'); printed++; }
  11571                     }
  11572                     if (hdr_lines) {
  11573                         if (pr_ff) putchar('\f');
  11574                         else { int full = pr_double ? body * 2 : body; for (; printed < full; printed++) putchar('\n'); for (r = 0; r < 5; r++) putchar('\n'); }
  11575                     }
  11576                 }
  11577                 for (r = 0; r < nrows; r++) free(rows[r]);
  11578                 free(rows);
  11579                 pos += chunk;
  11580                 line_no += chunk;
  11581             }
  11582         }
  11583     }
  11584     return finish_stdout() ? 1 : 0;
  11585 }
  11586 
  11587 /* ---- fmt ---- */
  11588 
  11589 struct fword { char *text; int len, space, period, final, punct, paren, nspace; long best; int brk, line_len; };
  11590 
  11591 static int fm_width = 75, fm_goal, fm_crown, fm_tagged, fm_split, fm_uniform, fm_tabs;
  11592 static const char *fm_prefix = "";
  11593 static int fm_plen;
  11594 
  11595 #define FM_SQR(n) ((long)(n) * (long)(n))
  11596 #define FM_EQUIV(n) FM_SQR(n)
  11597 #define FM_SHORT(n) FM_EQUIV((n) * 10)
  11598 #define FM_RAGGED(n) (FM_SHORT(n) / 2)
  11599 #define FM_LINE FM_EQUIV(70)
  11600 #define FM_WIDOW(n) (FM_EQUIV(200) / ((n) + 2))
  11601 #define FM_ORPHAN(n) (FM_EQUIV(150) / ((n) + 2))
  11602 #define FM_SENTENCE FM_EQUIV(50)
  11603 #define FM_NOBREAK FM_EQUIV(600)
  11604 #define FM_PUNCT FM_EQUIV(40)
  11605 #define FM_PAREN FM_EQUIV(40)
  11606 
  11607 static long fm_base_cost(struct fword *w, struct fword *first)
  11608 {
  11609     long cost = FM_LINE;
  11610     if (w > first) {
  11611         if (w[-1].period) {
  11612             if (w[-1].final) cost -= FM_SENTENCE;
  11613             else cost += FM_NOBREAK;
  11614         } else if (w[-1].punct) cost -= FM_PUNCT;
  11615         else if (w > first + 1 && w[-2].final) cost += FM_WIDOW(w[-1].len);
  11616     }
  11617     if (w->paren) cost -= FM_PAREN;
  11618     else if (w->final) cost += FM_ORPHAN(w->len);
  11619     return cost;
  11620 }
  11621 
  11622 static void fm_put_space(int *col, int n)
  11623 {
  11624     int target = *col + n;
  11625     if (fm_tabs) {
  11626         int tab = target / 8 * 8;
  11627         if (*col + 1 < tab) while (*col < tab) { putchar('\t'); *col = (*col / 8 + 1) * 8; }
  11628     }
  11629     while (*col < target) { putchar(' '); (*col)++; }
  11630 }
  11631 
  11632 static void fm_para(struct fword *w, int n, int first_indent, int other_indent, int pfx_indent)
  11633 {
  11634     int i, width = fm_width - fm_plen + 1, goal = fm_goal - fm_plen, col;
  11635     long *bestc = xmalloc((n + 1) * sizeof *bestc);
  11636     int *nb = xmalloc((n + 1) * sizeof *nb), *ll = xmalloc((n + 1) * sizeof *ll);
  11637     int start;
  11638     if (n == 0) { free(bestc); free(nb); free(ll); return; }
  11639     bestc[n] = 0; nb[n] = n; ll[n] = 0;
  11640     for (start = n - 1; start >= 0; start--) {
  11641         long best = (long)(~0UL >> 1);
  11642         int len = start == 0 ? first_indent : other_indent, k = start;
  11643         len += w[k].len;
  11644         do {
  11645             int next = k + 1;
  11646             long wc;
  11647             if (next == n) wc = 0 + bestc[next];
  11648             else {
  11649                 wc = FM_SHORT(goal - len);
  11650                 if (nb[next] != n) wc += FM_RAGGED(len - ll[next]);
  11651                 wc += bestc[next];
  11652             }
  11653             if (wc < best) { best = wc; nb[start] = next; ll[start] = len; }
  11654             if (next == n) break;
  11655             len += w[k].space + w[next].len;
  11656             k = next;
  11657         } while (len < width);
  11658         bestc[start] = best + fm_base_cost(&w[start], w);
  11659     }
  11660         col = 0;
  11661     for (i = 0; i < n; ) {
  11662         int j, ind = i == 0 ? first_indent : other_indent;
  11663         col = 0;
  11664         fm_put_space(&col, pfx_indent);
  11665         fputs(fm_prefix, stdout);
  11666         col += fm_plen;
  11667         fm_put_space(&col, ind);
  11668         for (j = i; j < nb[i]; j++) {
  11669             fputs(w[j].text, stdout);
  11670             col += w[j].len;
  11671             if (j + 1 < nb[i]) fm_put_space(&col, w[j].space);
  11672         }
  11673         putchar('\n');
  11674         i = nb[i];
  11675     }
  11676     free(bestc); free(nb); free(ll);
  11677 }
  11678 
  11679 static int fm_indent(const char *s, int *chars)
  11680 {
  11681     int col = 0, i = 0;
  11682     for (; s[i] == ' ' || s[i] == '\t'; i++) { if (s[i] == '\t') { fm_tabs = 1; col = col / 8 * 8 + 8; } else col++; }
  11683     *chars = i;
  11684     return col;
  11685 }
  11686 
  11687 static int t_fmt(int argc, char **argv)
  11688 {
  11689     static const struct opt lo[] = { { "crown-margin", 0, 'c' }, { "tagged-paragraph", 0, 't' }, { "split-only", 0, 's' }, { "uniform-spacing", 0, 'u' },
  11690         { "prefix", 1, 'p' }, { "width", 1, 'w' }, { "goal", 1, 'g' }, { NULL, 0, 0 } };
  11691     int c, i, goalset = 0, bad = 0, lastdig = 0, wd = 0;
  11692     unsigned long v;
  11693     opts_reset();
  11694     while ((c = getopts(argc, argv, "0123456789ctsup:w:g:", lo))) {
  11695         if (c >= '0' && c <= '9') { wd = lastdig ? wd * 10 + c - '0' : c - '0'; lastdig = 1; fm_width = wd; continue; }
  11696         lastdig = 0;
  11697         switch (c) {
  11698         case 'c': fm_crown = 1; break; case 't': fm_tagged = 1; break; case 's': fm_split = 1; break; case 'u': fm_uniform = 1; break;
  11699         case 'p': fm_prefix = optarg; fm_plen = strlen(optarg); break;
  11700         case 'w': if (!parse_ulong(optarg, &v)) die(1, "invalid width: '%s'", optarg); fm_width = v; break;
  11701         case 'g': if (!parse_ulong(optarg, &v)) die(1, "invalid width: '%s'", optarg); fm_goal = v; goalset = 1; break;
  11702         default: break;
  11703         }
  11704     }
  11705     if (!goalset) fm_goal = fm_width * 187 / 200;
  11706     else if (fm_goal > fm_width) die(1, "invalid width: '%d': Value too large for defined data type", fm_goal);
  11707     if (fm_goal > fm_width) fm_goal = fm_width;
  11708     if (!nops) ops[nops++] = "-";
  11709     for (i = 0; i < nops; i++) {
  11710         FILE *f = !strcmp(ops[i], "-") ? stdin : fopen(ops[i], "r");
  11711         char *line = NULL;
  11712         size_t cap = 0;
  11713         ssize_t n;
  11714         struct fword *w = NULL;
  11715         int wcol0 = 0, nw = 0, cw = 0, first_indent = 0, other_indent = 0, nlines = 0, pindent = 0;
  11716         if (!f) { perr("cannot open '%s' for reading", ops[i]); bad = 1; continue; }
  11717         for (;;) {
  11718             char *p;
  11719             int ch, ind, blank, matched = 1, end = 0;
  11720             n = getline(&line, &cap, f);
  11721             if (n < 0) end = 1;
  11722             else {
  11723                 if (n && line[n - 1] == '\n') line[--n] = 0;
  11724                 p = line;
  11725                 if (fm_plen) { matched = !strncmp(p, fm_prefix, fm_plen); if (matched) p += fm_plen; }
  11726                 ind = fm_indent(p, &ch);
  11727                 blank = matched && !p[ch];
  11728             }
  11729             if (end || !matched || blank) {
  11730                 if (nw) { if (fm_tagged && nlines == 1) other_indent = first_indent ? 0 : 3; fm_para(w, nw, first_indent, other_indent, pindent); nw = 0; nlines = 0; }
  11731                 if (end) break;
  11732                 if (!matched) puts(line); else putchar('\n');
  11733                 continue;
  11734             }
  11735             if (nw) {
  11736                 int cont = 1;
  11737                 if (fm_split) cont = 0;
  11738                 else if (fm_crown || fm_tagged) {
  11739                     if (nlines == 1) { if (fm_tagged && ind == first_indent) cont = 0; else other_indent = ind; }
  11740                     else if (ind != other_indent) cont = 0;
  11741                 } else if (ind != first_indent) cont = 0;
  11742                 if (!cont) { if (fm_tagged && nlines == 1) other_indent = first_indent ? 0 : 3; fm_para(w, nw, first_indent, other_indent, pindent); nw = 0; nlines = 0; }
  11743             }
  11744             if (!nw) { first_indent = other_indent = ind; pindent = 0; nlines = 0; }
  11745             nlines++;
  11746             p += ch;
  11747             wcol0 = ind;
  11748             while (*p) {
  11749                 char *s = p;
  11750                 int sp = 0, len, wcol;
  11751                 struct fword *x;
  11752                 while (*p && *p != ' ' && *p != '\t') p++;
  11753                 len = p - s;
  11754                 wcol = (wcol0 += len);
  11755                 while (*p == ' ' || *p == '\t') { if (*p == '\t') { fm_tabs = 1; sp += 8 - (wcol + sp) % 8; } else sp++; p++; }
  11756                 wcol0 += sp;
  11757                 if (nw == cw) { cw = cw ? cw * 2 : 64; w = xrealloc(w, cw * sizeof *w); }
  11758                 x = &w[nw++];
  11759                 memset(x, 0, sizeof *x);
  11760                 x->text = xmalloc(len + 1); memcpy(x->text, s, len); x->text[len] = 0;
  11761                 x->len = len;
  11762                 {
  11763                     int k = len - 1;
  11764                     while (k > 0 && strchr("\")']", s[k])) k--;
  11765                     x->period = strchr(".?!", s[k]) != NULL;
  11766                     x->punct = !x->period && ispunct((unsigned char)s[len - 1]);
  11767                     x->paren = strchr("([{", s[0]) != NULL;
  11768                 }
  11769                 if (!*p) { x->space = 1; x->final = x->period; if (x->period) x->space = 2; }
  11770                 else { x->space = sp; x->final = x->period && sp > 1; }
  11771                 if (fm_uniform) x->space = x->final ? 2 : 1;
  11772             }
  11773             if (n >= 0 && nw) { }
  11774         }
  11775         if (f != stdin) fclose(f);
  11776     }
  11777     return finish_stdout() ? 1 : bad;
  11778 }
  11779 
  11780 /* ---- cmp and diff ---- */
  11781 
  11782 static void cmp_ch(unsigned char c, char *o)
  11783 {
  11784     int i = 0;
  11785     if (c >= 128) { o[i++] = 'M'; o[i++] = '-'; c -= 128; }
  11786     if (c < 32) { o[i++] = '^'; o[i++] = c + 64; } else if (c == 127) { o[i++] = '^'; o[i++] = '?'; } else o[i++] = c;
  11787     o[i] = 0;
  11788 }
  11789 
  11790 static int t_cmp(int argc, char **argv)
  11791 {
  11792     static const struct opt lo[] = { { "print-bytes", 0, 'b' }, { "ignore-initial", 1, 'i' }, { "verbose", 0, 'l' }, { "bytes", 1, 'n' }, { "quiet", 0, 's' }, { "silent", 0, 's' }, { NULL, 0, 0 } };
  11793     int c, pb = 0, verbose = 0, quiet = 0, fa, fb, differ = 0, width = 1;
  11794     unsigned long skip1 = 0, skip2 = 0, limit = ~0UL, v, line = 1, t;
  11795     char *ba, *bb, c1[8], c2[8];
  11796     size_t la, lb, i, n;
  11797     usage_status = 2;
  11798     opts_reset();
  11799     while ((c = getopts(argc, argv, "bi:ln:s", lo))) {
  11800         switch (c) {
  11801         case 'b': pb = 1; break; case 'l': verbose = 1; break; case 's': quiet = 1; break;
  11802         case 'i': { char *e; skip1 = strtoul(optarg, &e, 10); skip2 = skip1; if (*e == ':') skip2 = strtoul(e + 1, &e, 10); if (*e) die(2, "invalid --ignore-initial value '%s'", optarg); break; }
  11803         case 'n': if (!parse_ulong(optarg, &v)) die(2, "invalid --bytes value '%s'", optarg); limit = v; break;
  11804         default: break;
  11805         }
  11806     }
  11807     if (nops < 2) { if (!nops) missing_operand(); say("missing operand after '%s'", ops[0]); usage_error(); }
  11808     if (nops > 2) extra_operand(ops[2]);
  11809     if (!strcmp(ops[0], "-") && !strcmp(ops[1], "-")) return 0;
  11810     fa = open_input(ops[0]);
  11811     if (fa < 0) { if (!quiet) perr("%s", ops[0]); return 2; }
  11812     fb = open_input(ops[1]);
  11813     if (fb < 0) { if (!quiet) perr("%s", ops[1]); return 2; }
  11814     if (read_all(fa, &ba, &la) < 0 || read_all(fb, &bb, &lb) < 0) { if (!quiet) perr("read error"); return 2; }
  11815     if (skip1 > la) skip1 = la;
  11816     if (skip2 > lb) skip2 = lb;
  11817     ba += skip1; la -= skip1; bb += skip2; lb -= skip2;
  11818     n = la < lb ? la : lb;
  11819     if (n > limit) n = limit;
  11820     for (t = n; t >= 10; t /= 10) width++;
  11821     for (i = 0; i < n; i++) {
  11822         if (ba[i] != bb[i]) {
  11823             if (!verbose) {
  11824                 if (!quiet) {
  11825                     printf("%s %s differ: %s %lu, line %lu", ops[0], ops[1], pb ? "byte" : "char", (unsigned long)i + 1, line);
  11826                     if (pb) { cmp_ch(ba[i], c1); cmp_ch(bb[i], c2); printf(" is %3o %s %3o %s", (unsigned char)ba[i], c1, (unsigned char)bb[i], c2); }
  11827                     putchar('\n');
  11828                 }
  11829                 return finish_stdout() ? 2 : 1;
  11830             }
  11831             differ = 1;
  11832             if (pb) { cmp_ch(ba[i], c1); cmp_ch(bb[i], c2); printf("%*lu %3o %-4s %3o %s", width, (unsigned long)i + 1, (unsigned char)ba[i], c1, (unsigned char)bb[i], c2); }
  11833             else printf("%*lu %3o %3o", width, (unsigned long)i + 1, (unsigned char)ba[i], (unsigned char)bb[i]);
  11834             putchar('\n');
  11835         }
  11836         if (ba[i] == '\n') line++;
  11837     }
  11838     if (n == limit && limit != ~0UL) return finish_stdout() ? 2 : differ;
  11839     if (la != lb) {
  11840         const char *sh = la < lb ? ops[0] : ops[1];
  11841         if (!quiet) {
  11842             if (!n) fprintf(stderr, "cmp: EOF on '%s' which is empty\n", sh);
  11843             else if (verbose) fprintf(stderr, "cmp: EOF on '%s' after byte %lu\n", sh, (unsigned long)n);
  11844             else fprintf(stderr, "cmp: EOF on '%s' after byte %lu, line %lu\n", sh, (unsigned long)n, line - 1);
  11845         }
  11846         finish_stdout();
  11847         return 1;
  11848     }
  11849     return finish_stdout() ? 2 : differ;
  11850 }
  11851 
  11852 struct dline { const char *s; size_t len; int nonl; };
  11853 struct dfile { struct dline *l; long n; char *buf; int binary; };
  11854 struct dchg { long as, an, bs, bn; };
  11855 
  11856 static int df_fold, df_ws, df_blank, df_ctx = 3, df_mode, df_brief, df_same, df_rec, df_newf, df_text;
  11857 static const char *df_lab[2];
  11858 static const char *df_cmdline, *df_hdr_a, *df_hdr_b;
  11859 static char **df_excl;
  11860 static int df_nexcl;
  11861 
  11862 static int df_read(const char *path, struct dfile *f)
  11863 {
  11864     int fd;
  11865     size_t len, i, st = 0;
  11866     long cap = 0;
  11867     f->l = NULL; f->n = 0; f->binary = 0;
  11868     fd = open_input(path);
  11869     if (fd < 0) return -1;
  11870     if (read_all(fd, &f->buf, &len) < 0) { if (fd) close(fd); return -1; }
  11871     if (fd) close(fd);
  11872     for (i = 0; i < len && i < 8192; i++) if (!f->buf[i]) { f->binary = 1; break; }
  11873     for (i = 0; i < len; i++) {
  11874         if (f->buf[i] == '\n') {
  11875             if (f->n == cap) { cap = cap ? cap * 2 : 128; f->l = xrealloc(f->l, cap * sizeof *f->l); }
  11876             f->l[f->n].s = f->buf + st; f->l[f->n].len = i - st; f->l[f->n].nonl = 0; f->n++;
  11877             st = i + 1;
  11878         }
  11879     }
  11880     if (st < len) {
  11881         if (f->n == cap) { cap = cap ? cap * 2 : 128; f->l = xrealloc(f->l, cap * sizeof *f->l); }
  11882         f->l[f->n].s = f->buf + st; f->l[f->n].len = len - st; f->l[f->n].nonl = 1; f->n++;
  11883     }
  11884     return 0;
  11885 }
  11886 
  11887 static char *df_key(const struct dline *l)
  11888 {
  11889     char *k = xmalloc(l->len + 2);
  11890     size_t i, o = 0;
  11891     int sp = 0;
  11892     for (i = 0; i < l->len; i++) {
  11893         unsigned char c = l->s[i];
  11894         if (df_ws && (c == ' ' || c == '\t' || c == '\r' || c == '\v' || c == '\f')) continue;
  11895         if (df_blank && (c == ' ' || c == '\t')) { if (!sp) k[o++] = ' '; sp = 1; continue; }
  11896         sp = 0;
  11897         k[o++] = df_fold ? tolower(c) : c;
  11898     }
  11899     if (df_blank && o && k[o - 1] == ' ') o--;
  11900     k[o++] = l->nonl && !df_ws && !df_blank ? 1 : 2;
  11901     k[o] = 0;
  11902     return k;
  11903 }
  11904 
  11905 struct dkey { char *k; long idx; };
  11906 static int df_kcmp(const void *a, const void *b) { return strcmp(((const struct dkey *)a)->k, ((const struct dkey *)b)->k); }
  11907 
  11908 /* ids[i] equal for equal lines; returns edit flags */
  11909 static void df_edit(struct dfile *a, struct dfile *b, char **da, char **ib)
  11910 {
  11911     long n = a->n, m = b->n, i, id = 0, s, e, N, M, D = 0, d, k, x, y, off;
  11912     int *ia = xmalloc((n + 1) * sizeof(int)), *ibb = xmalloc((m + 1) * sizeof(int)), **trace, *V;
  11913     struct dkey *ks = xmalloc((n + m + 1) * sizeof *ks);
  11914     char *dd = xmalloc(n + 1), *ii = xmalloc(m + 1);
  11915     memset(dd, 0, n + 1); memset(ii, 0, m + 1);
  11916     for (i = 0; i < n; i++) { ks[i].k = df_key(&a->l[i]); ks[i].idx = i; }
  11917     for (i = 0; i < m; i++) { ks[n + i].k = df_key(&b->l[i]); ks[n + i].idx = n + i; }
  11918     qsort(ks, n + m, sizeof *ks, df_kcmp);
  11919     for (i = 0; i < n + m; i++) {
  11920         if (i && strcmp(ks[i].k, ks[i - 1].k)) id++;
  11921         if (ks[i].idx < n) ia[ks[i].idx] = id; else ibb[ks[i].idx - n] = id;
  11922     }
  11923     for (s = 0; s < n && s < m && ia[s] == ibb[s]; s++) ;
  11924     for (e = 0; e < n - s && e < m - s && ia[n - 1 - e] == ibb[m - 1 - e]; e++) ;
  11925     N = n - s - e; M = m - s - e;
  11926     if (N || M) {
  11927         int *A = ia + s, *B = ibb + s;
  11928         long max = N + M, found = 0;
  11929         off = max;
  11930         V = xmalloc((2 * max + 2) * sizeof(int));
  11931         trace = xmalloc((max + 2) * sizeof *trace);
  11932         V[off + 1] = 0;
  11933         for (d = 0; d <= max && !found; d++) {
  11934             trace[d] = xmalloc((2 * d + 3) * sizeof(int));
  11935             for (k = -d; k <= d; k += 2) {
  11936                 if (k == -d || (k != d && V[off + k - 1] < V[off + k + 1])) x = V[off + k + 1]; else x = V[off + k - 1] + 1;
  11937                 y = x - k;
  11938                 while (x < N && y < M && A[x] == B[y]) { x++; y++; }
  11939                 V[off + k] = x;
  11940                 if (x >= N && y >= M) { found = 1; D = d; break; }
  11941             }
  11942             for (k = -d; k <= d; k++) trace[d][k + d] = V[off + k];
  11943         }
  11944         x = N; y = M;
  11945         for (d = D; d > 0; d--) {
  11946             int *pv = trace[d - 1];
  11947             long pk, px, py;
  11948             k = x - y;
  11949             if (k == -d || (k != d && pv[k - 1 + d - 1] < pv[k + 1 + d - 1])) pk = k + 1; else pk = k - 1;
  11950             px = pv[pk + d - 1]; py = px - pk;
  11951             if (pk == k + 1) ii[s + py] = 1; else dd[s + px] = 1;
  11952             x = px; y = py;
  11953         }
  11954     }
  11955     *da = dd; *ib = ii;
  11956 }
  11957 
  11958 static void df_print(struct dfile *f, long i, const char *pre)
  11959 {
  11960     fputs(pre, stdout);
  11961     fwrite(f->l[i].s, 1, f->l[i].len, stdout);
  11962     putchar('\n');
  11963     if (f->l[i].nonl) puts("\\ No newline at end of file");
  11964 }
  11965 
  11966 static void df_stamp(const char *path, const char *lab, const char *pre)
  11967 {
  11968     struct stat st;
  11969     char tb[64], tz[16];
  11970     time_t t;
  11971     struct tm *tm;
  11972     if (lab) { printf("%s %s\n", pre, lab); return; }
  11973     if (pre[0] == '*' || pre[0] == '-' && pre[1] == 'C') {
  11974         if (stat(path, &st) < 0) { printf("%s %s\n", pre, path); return; }
  11975         t = st.st_mtime; tm = localtime(&t);
  11976         strftime(tb, sizeof tb, "%a %b %e %H:%M:%S %Y", tm);
  11977         printf("%s %s\t%s\n", pre[0] == '*' ? "***" : "---", path, tb);
  11978         return;
  11979     }
  11980     if (stat(path, &st) < 0) { printf("%s %s\n", pre, path); return; }
  11981     t = st.st_mtime; tm = localtime(&t);
  11982     strftime(tb, sizeof tb, "%Y-%m-%d %H:%M:%S", tm);
  11983     strftime(tz, sizeof tz, "%z", tm);
  11984     if (!strcmp(tz, "+0000")) tz[0] = '-';
  11985     printf("%s %s\t%s.%09lu %s\n", pre, path, tb, (unsigned long)st.st_mtime_nsec, tz);
  11986 }
  11987 
  11988 static void df_range(long first, long len, char *out)
  11989 {
  11990     if (len == 1) sprintf(out, "%ld", first + 1);
  11991     else if (len == 0) sprintf(out, "%ld,0", first);
  11992     else sprintf(out, "%ld,%ld", first + 1, first + len);
  11993 }
  11994 
  11995 static int df_files(const char *pa, const char *pb, const char *la, const char *lb)
  11996 {
  11997     struct dfile a, b;
  11998     char *da, *ib;
  11999     struct dchg *ch = NULL;
  12000     long nch = 0, cap = 0, i, j, g;
  12001     int ra = 0, rb = 0;
  12002     if (pa) ra = df_read(pa, &a); else { a.l = NULL; a.n = 0; a.binary = 0; }
  12003     if (pb) rb = df_read(pb, &b); else { b.l = NULL; b.n = 0; b.binary = 0; }
  12004     if (ra < 0) { perr("%s", pa); return 2; }
  12005     if (rb < 0) { perr("%s", pb); return 2; }
  12006     if ((a.binary || b.binary) && !df_text) {
  12007         if (a.n == b.n && a.n >= 0) {
  12008             long k; int same = 1;
  12009             if (a.n == b.n) { for (k = 0; k < a.n && same; k++) same = a.l[k].len == b.l[k].len && !memcmp(a.l[k].s, b.l[k].s, a.l[k].len) && a.l[k].nonl == b.l[k].nonl; }
  12010             else same = 0;
  12011             if (same) { if (df_same) printf("Files %s and %s are identical\n", la, lb); return 0; }
  12012         }
  12013         if (df_hdr_a && !df_brief) { printf("diff%s %s %s\n", df_cmdline, df_hdr_a, df_hdr_b); df_hdr_a = NULL; }
  12014         printf(df_brief ? "Files %s and %s differ\n" : "Binary files %s and %s differ\n", la, lb);
  12015         return 1;
  12016     }
  12017     df_edit(&a, &b, &da, &ib);
  12018     if (df_hdr_a) { int any = 0; for (i = 0; i < a.n; i++) if (da[i]) any = 1; for (i = 0; i < b.n; i++) if (ib[i]) any = 1; if (any && !df_brief) { printf("diff%s %s %s\n", df_cmdline, df_hdr_a, df_hdr_b); df_hdr_a = NULL; } }
  12019     for (i = 0, j = 0; i < a.n || j < b.n; ) {
  12020         if (i < a.n && da[i]) {
  12021             long as = i, bs = j;
  12022             while (i < a.n && da[i]) i++;
  12023             while (j < b.n && ib[j]) j++;
  12024             if (nch == cap) { cap = cap ? cap * 2 : 16; ch = xrealloc(ch, cap * sizeof *ch); }
  12025             ch[nch].as = as; ch[nch].an = i - as; ch[nch].bs = bs; ch[nch].bn = j - bs; nch++;
  12026         } else if (j < b.n && ib[j]) {
  12027             long bs = j, as = i;
  12028             while (j < b.n && ib[j]) j++;
  12029             if (nch == cap) { cap = cap ? cap * 2 : 16; ch = xrealloc(ch, cap * sizeof *ch); }
  12030             ch[nch].as = as; ch[nch].an = 0; ch[nch].bs = bs; ch[nch].bn = j - bs; nch++;
  12031         } else { i++; j++; }
  12032     }
  12033     if (!nch) { if (df_same) printf("Files %s and %s are identical\n", la, lb); return 0; }
  12034     if (df_brief) { printf("Files %s and %s differ\n", la, lb); return 1; }
  12035     if (df_mode == 'u' || df_mode == 'c') {
  12036         int u = df_mode == 'u';
  12037         df_stamp(pa ? pa : "/dev/null", df_lab[0], u ? "---" : "***");
  12038         df_stamp(pb ? pb : "/dev/null", df_lab[1], u ? "+++" : "-C-");
  12039         for (g = 0; g < nch; ) {
  12040             long h = g, af, al, bf, bl, pos, k;
  12041             while (h + 1 < nch && ch[h + 1].as - (ch[h].as + ch[h].an) <= 2 * df_ctx) h++;
  12042             af = ch[g].as - df_ctx; if (af < 0) af = 0;
  12043             al = ch[h].as + ch[h].an + df_ctx; if (al > a.n) al = a.n;
  12044             bf = ch[g].bs - (ch[g].as - af);
  12045             bl = ch[h].bs + ch[h].bn + (al - (ch[h].as + ch[h].an));
  12046             if (u) {
  12047                 char ra_[48], rb_[48];
  12048                 long an_ = al - af, bn_ = bl - bf;
  12049                 if (an_ == 1) sprintf(ra_, "%ld", af + 1); else sprintf(ra_, "%ld,%ld", an_ ? af + 1 : af, an_);
  12050                 if (bn_ == 1) sprintf(rb_, "%ld", bf + 1); else sprintf(rb_, "%ld,%ld", bn_ ? bf + 1 : bf, bn_);
  12051                 printf("@@ -%s +%s @@\n", ra_, rb_);
  12052                 pos = af;
  12053                 for (k = g; k <= h; k++) {
  12054                     long x;
  12055                     for (x = pos; x < ch[k].as; x++) df_print(&a, x, " ");
  12056                     for (x = 0; x < ch[k].an; x++) df_print(&a, ch[k].as + x, "-");
  12057                     for (x = 0; x < ch[k].bn; x++) df_print(&b, ch[k].bs + x, "+");
  12058                     pos = ch[k].as + ch[k].an;
  12059                 }
  12060                 for (; pos < al; pos++) df_print(&a, pos, " ");
  12061             } else {
  12062                 int hasa = 0, hasb = 0;
  12063                 char r1[48], r2[48];
  12064                 long x;
  12065                 for (k = g; k <= h; k++) { if (ch[k].an) hasa = 1; if (ch[k].bn) hasb = 1; }
  12066                 puts("***************");
  12067                 if (al - af == 0) sprintf(r1, "%ld", af); else if (al - af == 1) sprintf(r1, "%ld", af + 1); else sprintf(r1, "%ld,%ld", af + 1, al);
  12068                 printf("*** %s ****\n", r1);
  12069                 if (hasa) {
  12070                     pos = af;
  12071                     for (k = g; k <= h; k++) {
  12072                         for (x = pos; x < ch[k].as; x++) df_print(&a, x, "  ");
  12073                         for (x = 0; x < ch[k].an; x++) df_print(&a, ch[k].as + x, ch[k].bn ? "! " : "- ");
  12074                         pos = ch[k].as + ch[k].an;
  12075                     }
  12076                     for (; pos < al; pos++) df_print(&a, pos, "  ");
  12077                 }
  12078                 if (bl - bf == 0) sprintf(r2, "%ld", bf); else if (bl - bf == 1) sprintf(r2, "%ld", bf + 1); else sprintf(r2, "%ld,%ld", bf + 1, bl);
  12079                 printf("--- %s ----\n", r2);
  12080                 if (hasb) {
  12081                     pos = af;
  12082                     for (k = g; k <= h; k++) {
  12083                         for (x = pos; x < ch[k].as; x++) df_print(&a, x, "  ");
  12084                         for (x = 0; x < ch[k].bn; x++) df_print(&b, ch[k].bs + x, ch[k].an ? "! " : "+ ");
  12085                         pos = ch[k].as + ch[k].an;
  12086                     }
  12087                     for (; pos < al; pos++) df_print(&a, pos, "  ");
  12088                 }
  12089             }
  12090             g = h + 1;
  12091         }
  12092         return 1;
  12093     }
  12094     for (g = 0; g < nch; g++) {
  12095         char r1[48], r2[48];
  12096         long x;
  12097         if (ch[g].an) df_range(ch[g].as, ch[g].an, r1); else sprintf(r1, "%ld", ch[g].as);
  12098         if (ch[g].bn) df_range(ch[g].bs, ch[g].bn, r2); else sprintf(r2, "%ld", ch[g].bs);
  12099         printf("%s%c%s\n", r1, !ch[g].an ? 'a' : !ch[g].bn ? 'd' : 'c', r2);
  12100         for (x = 0; x < ch[g].an; x++) df_print(&a, ch[g].as + x, "< ");
  12101         if (ch[g].an && ch[g].bn) puts("---");
  12102         for (x = 0; x < ch[g].bn; x++) df_print(&b, ch[g].bs + x, "> ");
  12103     }
  12104     return 1;
  12105 }
  12106 
  12107 static int df_name_cmp(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
  12108 
  12109 static int df_excluded(const char *name)
  12110 {
  12111     int i;
  12112     for (i = 0; i < df_nexcl; i++) if (glob_match(df_excl[i], name)) return 1;
  12113     return 0;
  12114 }
  12115 
  12116 static char **df_list(const char *dir, int *n)
  12117 {
  12118     DIR *d = opendir(dir);
  12119     struct dirent *e;
  12120     char **v = NULL;
  12121     int cap = 0;
  12122     *n = 0;
  12123     if (!d) return NULL;
  12124     while ((e = readdir(d))) {
  12125         if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..") || df_excluded(e->d_name)) continue;
  12126         if (*n == cap) { cap = cap ? cap * 2 : 32; v = xrealloc(v, cap * sizeof *v); }
  12127         v[(*n)++] = xstrdup(e->d_name);
  12128     }
  12129     closedir(d);
  12130     qsort(v, *n, sizeof *v, df_name_cmp);
  12131     return v;
  12132 }
  12133 
  12134 static char *df_join(const char *d, const char *n)
  12135 {
  12136     size_t dl = strlen(d);
  12137     char *r = xmalloc(dl + strlen(n) + 2);
  12138     sprintf(r, "%s%s%s", d, dl && d[dl - 1] == '/' ? "" : "/", n);
  12139     return r;
  12140 }
  12141 
  12142 
  12143 
  12144 static int df_pair(const char *pa, const char *pb, int top)
  12145 {
  12146     struct stat sa, sb;
  12147     int ea = pa ? stat(pa, &sa) : -1, eb = pb ? stat(pb, &sb) : -1, r = 0;
  12148     if (pa && ea < 0 && !df_newf) { perr("%s", pa); return 2; }
  12149     if (pb && eb < 0 && !df_newf) { perr("%s", pb); return 2; }
  12150     if (ea == 0 && eb == 0 && S_ISDIR(sa.st_mode) && S_ISDIR(sb.st_mode)) {
  12151         int na, nb, i = 0, j = 0;
  12152         char **va = df_list(pa, &na), **vb = df_list(pb, &nb);
  12153         while (i < na || j < nb) {
  12154             int c = i >= na ? 1 : j >= nb ? -1 : strcmp(va[i], vb[j]);
  12155             char *x = NULL, *y = NULL;
  12156             int rr;
  12157             if (c < 0 && !df_newf) { printf("Only in %s: %s\n", pa, va[i]); r = r < 1 ? 1 : r; i++; continue; }
  12158             if (c > 0 && !df_newf) { printf("Only in %s: %s\n", pb, vb[j]); r = r < 1 ? 1 : r; j++; continue; }
  12159             if (c <= 0) x = df_join(pa, va[i]);
  12160             if (c >= 0) y = df_join(pb, vb[j]);
  12161             {
  12162                 struct stat t;
  12163                 int isdir = (x && stat(x, &t) == 0 && S_ISDIR(t.st_mode)) || (y && stat(y, &t) == 0 && S_ISDIR(t.st_mode));
  12164                 if (isdir && !df_rec) { printf("Common subdirectories: %s and %s\n", x, y); rr = 0; }
  12165                 else {
  12166                     if (!isdir) { df_hdr_a = x ? x : df_join(pa, vb[j]); df_hdr_b = y ? y : df_join(pb, va[i]); }
  12167                     rr = df_pair(x ? x : NULL, y ? y : NULL, 0);
  12168                     df_hdr_a = NULL;
  12169                 }
  12170                 if (!x || !y) { }
  12171             }
  12172             if (rr > r) r = rr;
  12173             if (c <= 0) i++;
  12174             if (c >= 0) j++;
  12175         }
  12176         return r;
  12177     }
  12178     if (ea == 0 && S_ISDIR(sa.st_mode) && !(eb == 0 && S_ISDIR(sb.st_mode))) {
  12179         if (eb == 0 && pb) { char *base = strrchr(pb, '/'); (void)base; }
  12180         if (eb < 0 && df_newf) { if (!df_rec) return 2; }
  12181         { const char *bn = strrchr(pb ? pb : "", '/'); char *np = df_join(pa, bn ? bn + 1 : pb); return df_pair(np, pb, 0); }
  12182     }
  12183     if (eb == 0 && S_ISDIR(sb.st_mode) && !(ea == 0 && S_ISDIR(sa.st_mode))) {
  12184         const char *bn = strrchr(pa ? pa : "", '/'); char *np = df_join(pb, bn ? bn + 1 : pa);
  12185         return df_pair(pa, np, 0);
  12186     }
  12187     if (ea == 0 && eb == 0 && S_ISREG(sa.st_mode) && S_ISREG(sb.st_mode) && sa.st_dev == sb.st_dev && sa.st_ino == sb.st_ino) {
  12188         if (df_same) printf("Files %s and %s are identical\n", pa, pb);
  12189         return 0;
  12190     }
  12191     (void)top;
  12192     return df_files(ea == 0 ? pa : NULL, eb == 0 ? pb : NULL, pa ? pa : "/dev/null", pb ? pb : "/dev/null");
  12193 }
  12194 
  12195 static int t_diff(int argc, char **argv)
  12196 {
  12197     static const struct opt lo[] = { { "brief", 0, 'q' }, { "report-identical-files", 0, 's' }, { "recursive", 0, 'r' }, { "new-file", 0, 'N' }, { "text", 0, 'a' },
  12198         { "ignore-case", 0, 'i' }, { "ignore-all-space", 0, 'w' }, { "ignore-space-change", 0, 'b' }, { "ignore-blank-lines", 0, 'B' }, { "unified", 2, 'U' },
  12199         { "context", 2, 'C' }, { "label", 1, 1000 }, { "exclude", 1, 'x' }, { "show-c-function", 0, 'p' }, { "expand-tabs", 0, 't' }, { "initial-tab", 0, 'T' },
  12200         { "normal", 0, 1001 }, { NULL, 0, 0 } };
  12201     int c, i, r, nl = 0;
  12202     unsigned long v;
  12203     static char cl[512];
  12204     usage_status = 2;
  12205     opts_reset();
  12206     while ((c = getopts(argc, argv, "qsrNaiwbBu::c::U:C:x:ptTy", lo))) {
  12207         switch (c) {
  12208         case 'q': df_brief = 1; break; case 's': df_same = 1; break; case 'r': df_rec = 1; break; case 'N': df_newf = 1; break; case 'a': df_text = 1; break;
  12209         case 'i': df_fold = 1; break; case 'w': df_ws = 1; break; case 'b': df_blank = 1; break; case 'B': break;
  12210         case 'u': df_mode = 'u'; if (optarg && parse_ulong(optarg, &v)) df_ctx = v; break;
  12211         case 'c': df_mode = 'c'; if (optarg && parse_ulong(optarg, &v)) df_ctx = v; break;
  12212         case 'U': if (!parse_ulong(optarg, &v)) die(2, "invalid context length '%s'", optarg); df_mode = 'u'; df_ctx = v; break;
  12213         case 'C': if (!parse_ulong(optarg, &v)) die(2, "invalid context length '%s'", optarg); df_mode = 'c'; df_ctx = v; break;
  12214         case 'x': df_excl = xrealloc(df_excl, (df_nexcl + 1) * sizeof *df_excl); df_excl[df_nexcl++] = optarg; break;
  12215         case 1000: if (nl < 2) df_lab[nl++] = optarg; break;
  12216         case 1001: df_mode = 0; break;
  12217         default: break;
  12218         }
  12219     }
  12220     if (nops < 2) { if (!nops) { say("missing operand after '%s'", argv[argc - 1]); } else say("missing operand after '%s'", ops[0]); usage_error(); }
  12221     if (nops > 2) extra_operand(ops[2]);
  12222     for (i = 1; i < argc; i++) {
  12223         int isop = 0, k;
  12224         for (k = 0; k < nops; k++) if (argv[i] == ops[k]) isop = 1;
  12225         if (!isop) { strcat(cl, " "); strncat(cl, argv[i], 60); }
  12226     }
  12227     df_cmdline = cl;
  12228     r = df_pair(ops[0], ops[1], 1);
  12229     if (finish_stdout()) return 2;
  12230     return r;
  12231 }
  12232 
  12233 /* ---- which ---- */
  12234 static int t_which(int argc, char **argv)
  12235 {
  12236     static const struct opt lo[] = { { "all", 0, 'a' }, { NULL, 0, 0 } };
  12237     int c, all = 0, i, bad = 0;
  12238     const char *path;
  12239     char buf[PATH_MAX];
  12240     opts_reset();
  12241     while ((c = getopts(argc, argv, "a", lo))) if (c == 'a') all = 1;
  12242     if (!nops) return 1;
  12243     path = getenv("PATH");
  12244     if (!path || !*path) path = "/usr/bin:/bin";
  12245     for (i = 0; i < nops; i++) {
  12246         int found = 0;
  12247         if (strchr(ops[i], '/')) {
  12248             if (!access(ops[i], X_OK)) { puts(ops[i]); found = 1; }
  12249         } else {
  12250             char *ps = xstrdup(path), *dir, *nx;
  12251             for (dir = ps; dir; dir = nx) {
  12252                 nx = strchr(dir, ':');
  12253                 if (nx) *nx++ = 0;
  12254                 snprintf(buf, sizeof buf, "%s/%s", *dir ? dir : ".", ops[i]);
  12255                 if (!access(buf, X_OK)) { puts(buf); found = 1; if (!all) break; }
  12256             }
  12257             free(ps);
  12258         }
  12259         if (!found) bad = 1;
  12260     }
  12261     return finish_stdout() ? 2 : bad;
  12262 }
  12263 
  12264 /* ---- rev ---- */
  12265 static int rev_file(FILE *f, const char *name)
  12266 {
  12267     char *line = NULL;
  12268     size_t cap = 0;
  12269     ssize_t n;
  12270     while ((n = getline(&line, &cap, f)) > 0) {
  12271         ssize_t j;
  12272         int nl = line[n - 1] == '\n';
  12273         if (nl) n--;
  12274         for (j = n - 1; j >= 0; j--) putchar(line[j]);
  12275         if (nl) putchar('\n');
  12276     }
  12277     free(line);
  12278     if (ferror(f)) { perr("%s: read error", name); return 1; }
  12279     return 0;
  12280 }
  12281 static int t_rev(int argc, char **argv)
  12282 {
  12283     int i, rc = 0;
  12284     opts_reset();
  12285     while (getopts(argc, argv, "", NULL)) ;
  12286     if (!nops) rc = rev_file(stdin, "standard input");
  12287     else for (i = 0; i < nops; i++) {
  12288         FILE *f = strcmp(ops[i], "-") ? fopen(ops[i], "r") : stdin;
  12289         if (!f) { perr("%s: %s", ops[i], strerror(errno)); rc = 1; continue; }
  12290         if (rev_file(f, ops[i])) rc = 1;
  12291         if (f != stdin) fclose(f);
  12292     }
  12293     return finish_stdout() ? 1 : rc;
  12294 }
  12295 
  12296 /* ---- strings ---- */
  12297 static void strings_file(FILE *f, int min, const char *name, int pfn)
  12298 {
  12299     int c, n = 0;
  12300     size_t cap = 256;
  12301     char *b = xmalloc(cap);
  12302     for (;;) {
  12303         c = getc(f);
  12304         if (c == '\t' || (c >= 0x20 && c < 0x7f)) {
  12305             if ((size_t)n + 1 >= cap) b = xrealloc(b, cap *= 2);
  12306             b[n++] = c;
  12307             continue;
  12308         }
  12309         if (n >= min) { b[n] = 0; if (pfn) printf("%s: ", name); puts(b); }
  12310         n = 0;
  12311         if (c == EOF) break;
  12312     }
  12313     free(b);
  12314 }
  12315 static int t_strings(int argc, char **argv)
  12316 {
  12317     static const struct opt lo[] = { { "bytes", 1, 'n' }, { "print-file-name", 0, 'f' }, { NULL, 0, 0 } };
  12318     int c, min = 4, pfn = 0, i, rc = 0;
  12319     opts_reset();
  12320     while ((c = getopts(argc, argv, "n:f", lo)))
  12321         switch (c) {
  12322         case 'n': min = atoi(optarg); if (min < 1) die(1, "invalid minimum string length '%s'", optarg); break;
  12323         case 'f': pfn = 1; break;
  12324         }
  12325     if (!nops) strings_file(stdin, min, "{standard input}", pfn);
  12326     else for (i = 0; i < nops; i++) {
  12327         FILE *f = strcmp(ops[i], "-") ? fopen(ops[i], "rb") : stdin;
  12328         if (!f) { perr("'%s': %s", ops[i], strerror(errno)); rc = 1; continue; }
  12329         strings_file(f, min, ops[i], pfn);
  12330         if (f != stdin) fclose(f);
  12331     }
  12332     return finish_stdout() ? 1 : rc;
  12333 }
  12334 
  12335 /* ---- clear ---- */
  12336 static int t_clear(int argc, char **argv)
  12337 {
  12338     opts_reset();
  12339     while (getopts(argc, argv, "", NULL)) ;
  12340     fputs("\033[3J\033[H\033[2J", stdout);
  12341     return finish_stdout() ? 1 : 0;
  12342 }
  12343 
  12344 /* ---- free ---- */
  12345 static long meminfo_kb(const char *buf, const char *key)
  12346 {
  12347     const char *p = strstr(buf, key);
  12348     return p ? atol(p + strlen(key)) : 0;
  12349 }
  12350 static int t_free(int argc, char **argv)
  12351 {
  12352     static const struct opt lo[] = { { "human", 0, 'h' }, { "kibi", 0, 'k' }, { "mebi", 0, 'm' }, { "gibi", 0, 'g' }, { "total", 0, 't' }, { NULL, 0, 0 } };
  12353     static const char *const u[] = { "B", "K", "M", "G", "T" };
  12354     int c, human = 0, want_t = 0, fd, i;
  12355     long div = 1024;   /* meminfo is in kB; mebibytes by default, the number people read */
  12356     char buf[8192];
  12357     long total, mfree, avail, buffers, cached, srecl, shmem, used, bc, stotal, sfree;
  12358     struct row { const char *name; long v[6]; int n; } rows[2];
  12359     long mv[6], sv[6];
  12360     int r;
  12361     opts_reset();
  12362     while ((c = getopts(argc, argv, "hkmgt", lo)))
  12363         switch (c) {
  12364         case 'h': human = 1; break;
  12365         case 'k': div = 1; break;
  12366         case 'm': div = 1024; break;
  12367         case 'g': div = 1024L * 1024; break;
  12368         case 't': want_t = 1; break;
  12369         }
  12370     if ((fd = open("/proc/meminfo", O_RDONLY)) < 0) die(1, "/proc/meminfo: %s", strerror(errno));
  12371     i = read(fd, buf, sizeof buf - 1);
  12372     close(fd);
  12373     if (i <= 0) die(1, "cannot read /proc/meminfo");
  12374     buf[i] = 0;
  12375     total = meminfo_kb(buf, "MemTotal:");
  12376     mfree = meminfo_kb(buf, "MemFree:");
  12377     avail = meminfo_kb(buf, "MemAvailable:");
  12378     buffers = meminfo_kb(buf, "Buffers:");
  12379     cached = meminfo_kb(buf, "Cached:");
  12380     srecl = meminfo_kb(buf, "SReclaimable:");
  12381     shmem = meminfo_kb(buf, "Shmem:");
  12382     stotal = meminfo_kb(buf, "SwapTotal:");
  12383     sfree = meminfo_kb(buf, "SwapFree:");
  12384     bc = buffers + cached + srecl;
  12385     used = total - mfree - bc;
  12386     if (used < 0) used = total - mfree;
  12387     printf("%15s%12s%12s%12s%12s%12s\n", "total", "used", "free", "shared", "buff/cache", "available");
  12388     mv[0] = total; mv[1] = used; mv[2] = mfree; mv[3] = shmem; mv[4] = bc; mv[5] = avail;
  12389     sv[0] = stotal; sv[1] = stotal - sfree; sv[2] = sfree; sv[3] = sv[4] = sv[5] = 0;
  12390     rows[0].name = "Mem:"; memcpy(rows[0].v, mv, sizeof mv); rows[0].n = 6;
  12391     rows[1].name = "Swap:"; memcpy(rows[1].v, sv, sizeof sv); rows[1].n = 3;
  12392     for (r = 0; r < 2; r++) {
  12393         printf("%-7s", rows[r].name);
  12394         for (i = 0; i < rows[r].n; i++) {
  12395             long kb = rows[r].v[i];
  12396             if (human) {
  12397                 double d = kb * 1024.0;
  12398                 int k = 0;
  12399                 while (d >= 1024 && k < 4) { d /= 1024; k++; }
  12400                 printf("%11.1f%s", d, u[k]);
  12401             } else
  12402                 printf("%12ld", kb / div);
  12403         }
  12404         putchar('\n');
  12405     }
  12406     if (want_t)
  12407         printf("%-7s%12ld%12ld%12ld\n", "Total:", (total + stotal) / div, (used + stotal - sfree) / div, (mfree + sfree) / div);
  12408     return finish_stdout() ? 1 : 0;
  12409 }
  12410 
  12411 /* ---- cal ---- */
  12412 static int cal_dow(int y, int m, int d)   /* Sakamoto: 0 is Sunday */
  12413 {
  12414     static const int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
  12415     if (m < 3) y--;
  12416     return (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;
  12417 }
  12418 static int t_cal(int argc, char **argv)
  12419 {
  12420     static const char *const mon[] = { "January", "February", "March", "April", "May", "June",
  12421         "July", "August", "September", "October", "November", "December" };
  12422     int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  12423     int c, y, m, d, first, len, col, pad;
  12424     time_t now;
  12425     struct tm *tm;
  12426     char head[32];
  12427     opts_reset();
  12428     while ((c = getopts(argc, argv, "", NULL))) ;
  12429     now = time(NULL);
  12430     tm = localtime(&now);
  12431     y = tm->tm_year + 1900;
  12432     m = tm->tm_mon + 1;
  12433     d = tm->tm_mday;
  12434     if (nops >= 2) { m = atoi(ops[0]); y = atoi(ops[1]); d = 0; }
  12435     else if (nops == 1) { y = atoi(ops[0]); d = 0; }
  12436     if (m < 1 || m > 12) m = tm->tm_mon + 1;
  12437     if (!(y % 4) && (y % 100 || !(y % 400))) days[1] = 29;
  12438     len = days[m - 1];
  12439     first = cal_dow(y, m, 1);
  12440     snprintf(head, sizeof head, "%s %d", mon[m - 1], y);
  12441     pad = (20 - (int)strlen(head)) / 2;
  12442     printf("%*s%s\n", pad, "", head);
  12443     fputs("Su Mo Tu We Th Fr Sa\n", stdout);
  12444     for (col = 0; col < first; col++) fputs("   ", stdout);
  12445     for (c = 1; c <= len; c++) {
  12446         if (c == d) printf("\033[7m%2d\033[0m ", c); else printf("%2d ", c);
  12447         if (++col == 7 && c != len) { putchar('\n'); col = 0; }
  12448     }
  12449     putchar('\n');
  12450     return finish_stdout() ? 1 : 0;
  12451 }
  12452 
  12453 /* ---- tree ---- */
  12454 static long tree_dirs, tree_files;
  12455 static int tree_all, tree_donly, tree_max;
  12456 static int tree_cmp(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
  12457 static void tree_walk(const char *path, const char *prefix, int depth)
  12458 {
  12459     DIR *dp = opendir(path);
  12460     struct dirent *e;
  12461     char **names = NULL;
  12462     int n = 0, i;
  12463     if (!dp) { printf("%s [error opening dir]\n", path); return; }
  12464     while ((e = readdir(dp))) {
  12465         if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
  12466         if (!tree_all && e->d_name[0] == '.') continue;
  12467         names = xrealloc(names, (n + 1) * sizeof *names);
  12468         names[n++] = xstrdup(e->d_name);
  12469     }
  12470     closedir(dp);
  12471     qsort(names, n, sizeof *names, tree_cmp);
  12472     for (i = 0; i < n; i++) {
  12473         char *full = xmalloc(strlen(path) + strlen(names[i]) + 2);
  12474         struct stat st;
  12475         int isdir, last = i == n - 1;
  12476         sprintf(full, "%s/%s", path, names[i]);
  12477         isdir = lstat(full, &st) == 0 && S_ISDIR(st.st_mode);
  12478         if (!tree_donly || isdir) {
  12479             printf("%s%s%s\n", prefix, last ? "\\-- " : "|-- ", names[i]);
  12480             if (isdir) tree_dirs++; else tree_files++;
  12481         }
  12482         if (isdir && (!tree_max || depth < tree_max)) {
  12483             char *np = xmalloc(strlen(prefix) + 5);
  12484             sprintf(np, "%s%s", prefix, last ? "    " : "|   ");
  12485             tree_walk(full, np, depth + 1);
  12486             free(np);
  12487         }
  12488         free(full); free(names[i]);
  12489     }
  12490     free(names);
  12491 }
  12492 static int t_tree(int argc, char **argv)
  12493 {
  12494     static const struct opt lo[] = { { "all", 0, 'a' }, { NULL, 0, 0 } };
  12495     int c, i;
  12496     opts_reset();
  12497     tree_all = tree_donly = tree_max = 0;
  12498     tree_dirs = tree_files = 0;
  12499     while ((c = getopts(argc, argv, "adL:", lo)))
  12500         switch (c) {
  12501         case 'a': tree_all = 1; break;
  12502         case 'd': tree_donly = 1; break;
  12503         case 'L': tree_max = atoi(optarg); if (tree_max < 1) die(1, "invalid level, must be greater than 0"); break;
  12504         }
  12505     if (!nops) { puts("."); tree_walk(".", "", 1); }
  12506     else for (i = 0; i < nops; i++) { puts(ops[i]); tree_walk(ops[i], "", 1); }
  12507     printf("\n%ld director%s, %ld file%s\n", tree_dirs, tree_dirs == 1 ? "y" : "ies", tree_files, tree_files == 1 ? "" : "s");
  12508     return finish_stdout() ? 1 : 0;
  12509 }
  12510 
  12511 /* ---- the table and main ---- */
  12512 
  12513 struct applet { const char *name; int (*fn)(int, char **); const char *usage; const char *about; };
  12514 
  12515 static const struct applet applets[] = {
  12516     { "[", t_test, "EXPRESSION ]", "Check file types and compare values." },
  12517     { "arch", t_uname, "[OPTION]...", "Print the machine hardware name." },
  12518     { "base32", t_base, "[OPTION]... [FILE]", "Base32 encode or decode FILE." },
  12519     { "basenc", t_basenc, "[OPTION]... [FILE]", "Encode or decode FILE with one of several encodings." },
  12520     { "base64", t_base, "[OPTION]... [FILE]", "Base64 encode or decode FILE." },
  12521     { "basename", t_basename, "NAME [SUFFIX] | OPTION... NAME...", "Print NAME without any leading directory components, and SUFFIX if it ends the name." },
  12522     { "cal", t_cal, "[[MONTH] YEAR]", "Print a calendar for the month." },
  12523     { "cat", t_cat, "[OPTION]... [FILE]...", "Concatenate FILE(s) to standard output." },
  12524     { "chcon", t_chcon, "[OPTION]... CONTEXT FILE...", "Change the SELinux security context of each FILE to CONTEXT." },
  12525     { "chgrp", t_chown, "[OPTION]... GROUP FILE...", "Change the group of each FILE to GROUP." },
  12526     { "chmod", t_chmod, "[OPTION]... MODE[,MODE]... FILE...", "Change the mode of each FILE to MODE." },
  12527     { "chown", t_chown, "[OPTION]... [OWNER][:[GROUP]] FILE...", "Change the owner and/or group of each FILE." },
  12528     { "chroot", t_chroot, "[OPTION] NEWROOT [COMMAND [ARG]...]", "Run COMMAND with root directory set to NEWROOT." },
  12529     { "cksum", t_cksum, "[OPTION]... [FILE]...", "Print CRC checksum and byte counts of each FILE." },
  12530     { "clear", t_clear, "", "Clear the terminal screen." },
  12531     { "comm", t_comm, "[OPTION]... FILE1 FILE2", "Compare sorted files FILE1 and FILE2 line by line." },
  12532     { "cp", t_cp, "[OPTION]... SOURCE... DEST", "Copy SOURCE to DEST, or several SOURCEs to a DIRECTORY." },
  12533     { "cut", t_cut, "OPTION... [FILE]...", "Print selected parts of lines from each FILE." },
  12534     { "date", t_date, "[OPTION]... [+FORMAT]", "Print the system date and time." },
  12535     { "dd", t_dd, "[OPERAND]...", "Copy a file, converting and formatting according to the operands." },
  12536     { "df", t_df, "[OPTION]... [FILE]...", "Show information about the file system on which each FILE resides." },
  12537     { "shred", t_shred, "[OPTION]... FILE...", "Overwrite a file repeatedly to hide its contents, and optionally delete it." },
  12538     { "csplit", t_csplit, "[OPTION]... FILE PATTERN...", "Split FILE into context-determined pieces." },
  12539     { "numfmt", t_numfmt, "[OPTION]... [NUMBER]...", "Reformat numbers, scaling them to or from SI and IEC units." },
  12540     { "dircolors", t_dircolors, "[OPTION]... [FILE]", "Output commands to set the LS_COLORS environment variable." },
  12541     { "stty", t_stty, "[-F DEVICE] [--file=DEVICE] [SETTING]...", "Print or change terminal characteristics." },
  12542     { "pr", t_pr, "[OPTION]... [FILE]...", "Paginate or columnate FILE(s) for printing." },
  12543     { "fmt", t_fmt, "[-WIDTH] [OPTION]... [FILE]...", "Reformat each paragraph in the FILE(s), writing to standard output." },
  12544     { "cmp", t_cmp, "[OPTION]... FILE1 [FILE2 [SKIP1 [SKIP2]]]", "Compare two files byte by byte." },
  12545     { "diff", t_diff, "[OPTION]... FILES", "Compare FILES line by line." },
  12546     { "dir", t_dir, "[OPTION]... [FILE]...", "List directory contents in columns, with C-style escapes." },
  12547     { "dirname", t_dirname, "[OPTION] NAME...", "Print NAME with its last component removed." },
  12548     { "du", t_du, "[OPTION]... [FILE]...", "Summarize device usage of the set of FILEs, recursively for directories." },
  12549     { "echo", t_echo, "[-neE] [STRING]...", "Print the STRINGs, separated by spaces." },
  12550     { "egrep", t_grep, "[OPTION]... PATTERNS [FILE]...", "Search for PATTERNS in each FILE." },
  12551     { "env", t_env, "[OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]", "Run COMMAND in a changed environment, or print the environment." },
  12552     { "expand", t_expand, "[OPTION]... [FILE]...", "Convert tabs in each FILE to spaces." },
  12553     { "expr", t_expr, "EXPRESSION", "Print the value of EXPRESSION to standard output." },
  12554     { "factor", t_factor, "[NUMBER]...", "Print the prime factors of each NUMBER." },
  12555     { "false", t_true, "", "Do nothing, unsuccessfully." },
  12556     { "fgrep", t_grep, "[OPTION]... PATTERNS [FILE]...", "Search for PATTERNS in each FILE." },
  12557     { "find", t_find, "[-H] [-L] [-P] [PATH...] [EXPRESSION]", "Search for files in a directory hierarchy." },
  12558     { "fold", t_fold, "[OPTION]... [FILE]...", "Wrap each input line to fit in a given width." },
  12559     { "free", t_free, "[-hkmgt]", "Show how much memory and swap is used and free." },
  12560     { "grep", t_grep, "[OPTION]... PATTERNS [FILE]...", "Search for PATTERNS in each FILE." },
  12561     { "groups", t_id, "[OPTION]... [USERNAME]...", "Print the groups a user is in." },
  12562     { "head", t_head, "[OPTION]... [FILE]...", "Print the first 10 lines of each FILE." },
  12563     { "hostid", t_hostid, "", "Print the numeric identifier of this machine." },
  12564     { "hostname", t_hostname, "[NAME]", "Print the name of this machine, or set it to NAME." },
  12565     { "id", t_id, "[OPTION]... [USER]", "Print user and group information for the specified USER, or for the current user." },
  12566     { "install", t_install, "[OPTION]... SOURCE... DIRECTORY", "Copy files and set attributes." },
  12567     { "join", t_join, "[OPTION]... FILE1 FILE2", "For each pair of input lines with identical join fields, write a line to standard output." },
  12568     { "kill", t_kill, "[-s SIGNAL | -SIGNAL] PID...", "Send a signal to processes, or list the signal names with -l." },
  12569     { "link", t_link, "FILE1 FILE2", "Make a hard link named FILE2 to FILE1." },
  12570     { "ln", t_ln, "[OPTION]... TARGET [LINK_NAME]", "Make links between files." },
  12571     { "logname", t_logname, "", "Print the name of the user who logged in." },
  12572     { "ls", t_ls, "[OPTION]... [FILE]...", "List information about the FILEs (the current directory by default)." },
  12573     { "b2sum", t_digest, "[OPTION]... [FILE]...", "Print or check BLAKE2b (512-bit) checksums." },
  12574     { "md5sum", t_digest, "[OPTION]... [FILE]...", "Print or check MD5 (128-bit) checksums." },
  12575     { "mkdir", t_mkdir, "[OPTION]... DIRECTORY...", "Create the DIRECTORY(ies), if they do not already exist." },
  12576     { "mkfifo", t_mkfifo, "[OPTION]... NAME...", "Create named pipes (FIFOs) with the given NAMEs." },
  12577     { "mknod", t_mknod, "[OPTION]... NAME TYPE [MAJOR MINOR]", "Create the special file NAME of the given TYPE." },
  12578     { "mktemp", t_mktemp, "[OPTION]... [TEMPLATE]", "Create a temporary file or directory and print its name." },
  12579     { "mv", t_mv, "[OPTION]... SOURCE... DEST", "Rename SOURCE to DEST, or move SOURCEs to a DIRECTORY." },
  12580     { "nice", t_nice, "[OPTION] [COMMAND [ARG]...]", "Run COMMAND with an adjusted niceness." },
  12581     { "nl", t_nl, "[OPTION]... [FILE]", "Number the lines of FILE." },
  12582     { "nohup", t_nohup, "COMMAND [ARG]...", "Run COMMAND, ignoring hangup signals." },
  12583     { "nproc", t_nproc, "[OPTION]...", "Print the number of processing units available." },
  12584     { "od", t_od, "[OPTION]... [FILE]...", "Write an unambiguous representation, octal bytes by default, of FILE to standard output." },
  12585     { "paste", t_paste, "[OPTION]... [FILE]...", "Merge lines of files side by side." },
  12586     { "pathchk", t_pathchk, "[OPTION]... NAME...", "Check whether file names are valid or portable." },
  12587     { "pinky", t_pinky, "[OPTION]... [USER]...", "Print brief information about logged-in users." },
  12588     { "printenv", t_printenv, "[OPTION]... [VARIABLE]...", "Print the values of the given environment VARIABLEs, or all of them." },
  12589     { "printf", t_printf, "FORMAT [ARGUMENT]...", "Print ARGUMENT(s) according to FORMAT." },
  12590     { "pwd", t_pwd, "[OPTION]...", "Print the name of the current working directory." },
  12591     { "readlink", t_readlink, "[OPTION]... FILE...", "Print the value of a symbolic link, or a file's canonical name." },
  12592     { "realpath", t_realpath, "[OPTION]... FILE...", "Print the resolved absolute file name." },
  12593     { "rev", t_rev, "[FILE]...", "Reverse the characters of each line." },
  12594     { "rm", t_rm, "[OPTION]... [FILE]...", "Remove (unlink) the FILE(s)." },
  12595     { "rmdir", t_rmdir, "[OPTION]... DIRECTORY...", "Remove the DIRECTORY(ies), if they are empty." },
  12596     { "runcon", t_runcon, "CONTEXT COMMAND [ARG]...", "Run COMMAND with a SELinux security context." },
  12597     { "sed", t_sed, "[OPTION]... {script-only-if-no-other-script} [input-file]...", "Edit streams of text, line by line." },
  12598     { "seq", t_seq, "[OPTION]... [FIRST [INCREMENT]] LAST", "Print numbers from FIRST to LAST in steps of INCREMENT." },
  12599     { "sha1sum", t_digest, "[OPTION]... [FILE]...", "Print or check SHA1 (160-bit) checksums." },
  12600     { "sha224sum", t_digest, "[OPTION]... [FILE]...", "Print or check SHA224 (224-bit) checksums." },
  12601     { "sha256sum", t_digest, "[OPTION]... [FILE]...", "Print or check SHA256 (256-bit) checksums." },
  12602     { "sha384sum", t_digest, "[OPTION]... [FILE]...", "Print or check SHA384 (384-bit) checksums." },
  12603     { "sha512sum", t_digest, "[OPTION]... [FILE]...", "Print or check SHA512 (512-bit) checksums." },
  12604     { "shuf", t_shuf, "[OPTION]... [FILE]", "Write a random permutation of the input lines to standard output." },
  12605     { "sleep", t_sleep, "NUMBER[SUFFIX]...", "Pause for NUMBER seconds. SUFFIX may be s, m, h or d." },
  12606     { "sort", t_sort, "[OPTION]... [FILE]...", "Write the sorted concatenation of all FILEs to standard output." },
  12607     { "split", t_split, "[OPTION]... [FILE [PREFIX]]", "Output pieces of FILE to PREFIXaa, PREFIXab, ..." },
  12608     { "stat", t_stat, "[OPTION]... FILE...", "Display file or file system status." },
  12609     { "stdbuf", t_stdbuf, "OPTION... COMMAND", "Run COMMAND with modified buffering for its standard streams." },
  12610     { "strings", t_strings, "[-f] [-n MIN] [FILE]...", "Print the printable strings in FILE(s)." },
  12611     { "sum", t_cksum, "[OPTION]... [FILE]...", "Print checksum and block counts for each FILE." },
  12612     { "sync", t_sync, "[OPTION] [FILE]...", "Flush file system buffers." },
  12613     { "tac", t_tac, "[OPTION]... [FILE]...", "Print each FILE last line first." },
  12614     { "tail", t_tail, "[OPTION]... [FILE]...", "Print the last 10 lines of each FILE." },
  12615     { "tee", t_tee, "[OPTION]... [FILE]...", "Copy standard input to each FILE, and also to standard output." },
  12616     { "test", t_test, "EXPRESSION", "Check file types and compare values." },
  12617     { "timeout", t_timeout, "[OPTION] DURATION COMMAND [ARG]...", "Start COMMAND, and kill it if still running after DURATION." },
  12618     { "touch", t_touch, "[OPTION]... FILE...", "Update the access and modification times of each FILE." },
  12619     { "tr", t_tr, "[OPTION]... SET1 [SET2]", "Translate, squeeze, and/or delete characters from standard input." },
  12620     { "tree", t_tree, "[-ad] [-L LEVEL] [DIR]...", "List the contents of a directory as a tree." },
  12621     { "true", t_true, "", "Do nothing, successfully." },
  12622     { "truncate", t_truncate, "OPTION... FILE...", "Shrink or extend the size of each FILE to the specified size." },
  12623     { "tsort", t_tsort, "[OPTION] [FILE]", "Write totally ordered list consistent with the partial ordering in FILE." },
  12624     { "tty", t_tty, "[OPTION]...", "Print the file name of the terminal connected to standard input." },
  12625     { "uname", t_uname, "[OPTION]...", "Print system information." },
  12626     { "unexpand", t_expand, "[OPTION]... [FILE]...", "Convert spaces in each FILE to tabs." },
  12627     { "uniq", t_uniq, "[OPTION]... [INPUT [OUTPUT]]", "Filter adjacent matching lines." },
  12628     { "unlink", t_unlink, "FILE", "Remove FILE with the unlink call." },
  12629     { "uptime", t_uptime, "[OPTION]... [FILE]", "Tell how long the system has been running." },
  12630     { "users", t_users, "[FILE]", "Print the user names of users currently logged in." },
  12631     { "vdir", t_dir, "[OPTION]... [FILE]...", "List directory contents in long format, with C-style escapes." },
  12632     { "wc", t_wc, "[OPTION]... [FILE]...", "Print newline, word, and byte counts for each FILE." },
  12633     { "which", t_which, "[-a] NAME...", "Show the full path of a command, the way the shell would find it." },
  12634     { "who", t_who, "[OPTION]... [FILE] [am i]", "Print information about users who are currently logged in." },
  12635     { "whoami", t_whoami, "", "Print the user name for the current effective user ID." },
  12636     { "xargs", t_xargs, "[OPTION]... COMMAND [INITIAL-ARGS]...", "Build and execute command lines from standard input." },
  12637     { "yes", t_yes, "[STRING]...", "Repeatedly output a line with all specified STRING(s), or 'y'." },
  12638 };
  12639 #define NAPPLETS ((int)(sizeof applets / sizeof applets[0]))
  12640 
  12641 static const struct applet *find_applet(const char *name)
  12642 {
  12643     int i;
  12644     for (i = 0; i < NAPPLETS; i++) if (!strcmp(applets[i].name, name)) return &applets[i];
  12645     return NULL;
  12646 }
  12647 
  12648 /* rifle --install DIR: a link to this program for every tool, relative if it lives in DIR too */
  12649 static int install_links(const char *dir)
  12650 {
  12651     char exe[PATH_MAX], target[PATH_MAX], link_path[PATH_MAX], *slash;
  12652     ssize_t n = readlink("/proc/self/exe", exe, sizeof exe - 1);
  12653     int i, st = 0;
  12654     if (n < 0) { perr("cannot find myself"); return 1; }
  12655     exe[n] = 0;
  12656     slash = strrchr(exe, '/');
  12657     {
  12658         char want[PATH_MAX];
  12659         realpath(dir, want);
  12660         if (slash && (size_t)(slash - exe) == strlen(want) && !strncmp(exe, want, slash - exe)) snprintf(target, sizeof target, "%s", slash + 1);
  12661         else snprintf(target, sizeof target, "%s", exe);
  12662     }
  12663     for (i = 0; i < NAPPLETS; i++) {
  12664         snprintf(link_path, sizeof link_path, "%s/%s", dir, applets[i].name);
  12665         unlink(link_path);
  12666         if (symlink(target, link_path) < 0) { perr("cannot make '%s'", link_path); st = 1; }
  12667     }
  12668     return st;
  12669 }
  12670 
  12671 int main(int argc, char **argv)
  12672 {
  12673     const char *name = base_of(argv[0]);
  12674     const struct applet *a;
  12675     int rc;
  12676     if (!strcmp(name, "rifle")) {
  12677         /* run as itself, not through a link: a few things of its own, and "rifle tool args" for trying one out */
  12678         if (argc >= 2 && !strcmp(argv[1], "--list")) { int i; for (i = 0; i < NAPPLETS; i++) puts(applets[i].name); return finish_stdout(); }
  12679         if (argc >= 3 && !strcmp(argv[1], "--install")) return install_links(argv[2]);
  12680         if (argc >= 2 && !strcmp(argv[1], "--version")) { puts("rifle " VERSION); return finish_stdout(); }
  12681         if (argc < 2 || !strcmp(argv[1], "--help")) {
  12682             puts("rifle " VERSION ": coreutils in one program. cat, ls and the rest are links to it.\n"
  12683                  "  rifle --install DIR    make the links in DIR\n"
  12684                  "  rifle --list           the tools in here");
  12685             return finish_stdout();
  12686         }
  12687         argv++; argc--;
  12688         name = base_of(argv[0]);
  12689     }
  12690     if (!(a = find_applet(name))) { prog = name; die(127, "not a tool in rifle"); }
  12691     prog = a->name; tool_usage = a->usage; tool_about = a->about;
  12692     argv[0] = (char *)a->name;
  12693     rc = a->fn(argc, argv);
  12694     if (finish_stdout()) rc = rc ? rc : 1;
  12695     return rc;
  12696 }