aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

pax.c (64182B)


      1 
      2 
      3 /* taken from: https:// github.com/michaelforney/pax */
      4 #ifndef _GNU_SOURCE
      5 #define _GNU_SOURCE /* needed for major/minor (non-posix) */
      6 #endif
      7 
      8 #include "arg.h"
      9 #include "filesystem.h"
     10 
     11 #include <assert.h>
     12 #include <cpio.h>
     13 #include <ctype.h>
     14 #include <dirent.h>
     15 #include <errno.h>
     16 #include <fcntl.h>
     17 #include <fnmatch.h>
     18 #include <grp.h>
     19 #include <limits.h>
     20 #include <pwd.h>
     21 #include <regex.h>
     22 #include <spawn.h>
     23 #include <stdarg.h>
     24 #include <stdint.h>
     25 #include <stdio.h>
     26 #include <stdlib.h>
     27 #include <string.h>
     28 #include <sys/stat.h>
     29 #include <sys/types.h>
     30 #include <sys/uio.h>
     31 #include <sys/wait.h>
     32 #include <tar.h>
     33 #include <time.h>
     34 #include <unistd.h>
     35 
     36 #ifndef O_SEARCH /* not present on some bsds */
     37 #define O_SEARCH 0
     38 #endif
     39 
     40 #ifndef HAVE_REALLOCARRAY
     41 static void *
     42 pax_reallocarray(void *p, size_t n, size_t m)
     43 {
     44   if (m && n > SIZE_MAX / m) {
     45     errno = ENOMEM;
     46     return NULL;
     47   }
     48   return realloc(p, n * m);
     49 }
     50 #undef reallocarray
     51 #define reallocarray pax_reallocarray
     52 #endif
     53 
     54 #ifndef HAVE_PIPE2
     55 static int
     56 pax_pipe2(int fd[2], int flag)
     57 {
     58   assert((flag | O_CLOEXEC) == O_CLOEXEC);
     59   if (pipe(fd) != 0)
     60     return -1;
     61   if (flag & O_CLOEXEC
     62       && (fcntl(fd[0], F_SETFD, FD_CLOEXEC) != 0 || fcntl(fd[1], F_SETFD, FD_CLOEXEC) != 0))
     63     return -1;
     64   return 0;
     65 }
     66 #undef pipe2
     67 #define pipe2 pax_pipe2
     68 #endif
     69 
     70 #define LEN(a)        (sizeof(a) / sizeof *(a))
     71 #define ROUNDUP(x, a) (((x) + ((a) - 1)) & ~((a) - 1))
     72 #define MAXTIME       077777777777
     73 #define MAXSIZE       077777777777
     74 #define MAXUGID       07777777
     75 
     76 enum mode {
     77   LIST,
     78   READ,
     79   WRITE,
     80   COPY,
     81 };
     82 
     83 enum format {
     84   CPIO,
     85   PAX,
     86   USTAR,
     87   GNUTAR,
     88   V7,
     89 };
     90 
     91 enum field {
     92   ATIME    = 1 << 0,
     93   CTIME    = 1 << 1,
     94   GID      = 1 << 2,
     95   GNAME    = 1 << 3,
     96   LINKPATH = 1 << 4,
     97   MODE     = 1 << 5,
     98   MTIME    = 1 << 6,
     99   PATH     = 1 << 7,
    100   SIZE     = 1 << 8,
    101   UID      = 1 << 9,
    102   UNAME    = 1 << 10,
    103 };
    104 
    105 struct keyword {
    106   const char *name;
    107   enum field  field;
    108 };
    109 
    110 struct strbuf {
    111   char  *str;
    112   size_t len, cap;
    113 };
    114 
    115 struct header {
    116   /* keywords present in this header */
    117   enum field fields;
    118   /* keywords ignored because they were overridden by an option */
    119   enum field delete;
    120 
    121   char type;
    122 
    123   char           *path;
    124   size_t          pathlen;
    125   dev_t           dev;
    126   ino_t           ino;
    127   mode_t          mode;
    128   uid_t           uid;
    129   gid_t           gid;
    130   nlink_t         nlink;
    131   dev_t           rdev;
    132   off_t           size;
    133   struct timespec atime, mtime, ctime;
    134   char           *link;
    135   size_t          linklen;
    136   char           *uname;
    137   char           *gname;
    138 
    139   struct strbuf pathbuf;
    140   struct strbuf linkbuf;
    141   struct strbuf unamebuf;
    142   struct strbuf gnamebuf;
    143 
    144   /* tar-specific, pre-calculated split point between name and prefix */
    145   char *slash;
    146   /* read this data instead of stdin */
    147   char *data;
    148   /* source file path and flags for hard link (-l flag) */
    149   char           *file;
    150   struct timespec fileatime;
    151   int             flag;
    152 };
    153 
    154 struct account {
    155   char      *name;
    156   enum field type;
    157   uid_t      uid;
    158   gid_t      gid;
    159 };
    160 
    161 struct bufio {
    162   int   fd, err;
    163   off_t off;
    164   char  buf[64 * 1024];
    165   char *pos, *end;
    166 };
    167 
    168 struct replstr {
    169   regex_t old;
    170   char *new;
    171   int             global;
    172   int             print;
    173   int             symlink;
    174   struct replstr *next;
    175 };
    176 
    177 struct file {
    178   size_t       namelen;
    179   size_t       pathlen;
    180   dev_t        dev;
    181   struct file *next;
    182   char         name[];
    183 };
    184 
    185 struct filelist {
    186   FILE        *input;
    187   struct file *pending;
    188 };
    189 
    190 typedef int  readfn(struct bufio *, struct header *);
    191 typedef void writefn(FILE *, struct header *);
    192 
    193 static int                  exitstatus;
    194 static int                  aflag;
    195 static int                  cflag;
    196 static int                  dflag;
    197 static int                  iflag;
    198 static int                  kflag;
    199 static int                  lflag;
    200 static int                  nflag;
    201 static int                  tflag;
    202 static int                  uflag;
    203 static int                  vflag;
    204 static int                  Xflag;
    205 static int                  follow;
    206 static int                  preserve   = ATIME | MTIME;
    207 static const struct keyword keywords[] = {
    208     {"atime", ATIME},
    209     {"ctime", CTIME},
    210     {"gid", GID},
    211     {"gname", GNAME},
    212     {"linkpath", LINKPATH},
    213     {"mtime", MTIME},
    214     {"path", PATH},
    215     {"size", SIZE},
    216     {"uid", UID},
    217     {"uname", UNAME},
    218 };
    219 static struct {
    220   enum field delete;
    221   int         linkdata;
    222   const char *listopt;
    223   const char *exthdrname;
    224   const char *globexthdrname;
    225   const char *invalid;
    226   int         times;
    227 } opt;
    228 static struct header   exthdr, globexthdr;
    229 static struct replstr *replstr;
    230 static time_t          curtime;
    231 static char          **pats;
    232 static size_t          patslen;
    233 static int            *patsused;
    234 static struct filelist files;
    235 static struct bufio    bioin;
    236 static char           *dest   = "";
    237 static int             destfd = AT_FDCWD;
    238 
    239 static void
    240 fatal(const char *fmt, ...)
    241 {
    242   va_list ap;
    243 
    244   if (fmt) {
    245     va_start(ap, fmt);
    246     vfprintf(stderr, fmt, ap);
    247     va_end(ap);
    248     if (fmt[0] && fmt[strlen(fmt) - 1] == ':') {
    249       fputc(' ', stderr);
    250       perror(NULL);
    251     } else {
    252       fputc('\n', stderr);
    253     }
    254   } else {
    255     perror(NULL);
    256   }
    257   exit(1);
    258 }
    259 
    260 static char *
    261 sbufalloc(struct strbuf *b, size_t n, size_t a)
    262 {
    263   char *s;
    264 
    265   if (n > b->cap - b->len) {
    266     if (n > SIZE_MAX - a || n + a > SIZE_MAX - b->len)
    267       fatal("path is too long");
    268     b->cap = ROUNDUP(n, a);
    269     s      = malloc(b->cap);
    270     if (!s)
    271       fatal(NULL);
    272     if (b->len)
    273       memcpy(s, b->str, b->len);
    274     free(b->str);
    275     b->str = s;
    276   }
    277   return b->str + b->len;
    278 }
    279 
    280 static int
    281 sbuffmtv(struct strbuf *b, size_t a, const char *fmt, va_list ap)
    282 {
    283   va_list aptmp;
    284   int     n;
    285 
    286   va_copy(aptmp, ap);
    287   n = vsnprintf(b->str ? b->str + b->len : NULL, b->cap - b->len, fmt, aptmp);
    288   va_end(aptmp);
    289   if (n < 0)
    290     fatal("vsnprintf:");
    291   if ((size_t)n >= b->cap - b->len) {
    292     sbufalloc(b, (size_t)n + 1, a);
    293     n = vsnprintf(b->str + b->len, b->cap - b->len, fmt, ap);
    294     if (n < 0)
    295       fatal("vsnprintf:");
    296     if ((size_t)n >= b->cap - b->len)
    297       fatal("vsnprintf: formatted size changed");
    298   }
    299   b->len += n;
    300   return n;
    301 }
    302 
    303 static int
    304 sbuffmt(struct strbuf *b, size_t a, const char *fmt, ...)
    305 {
    306   va_list ap;
    307   int     n;
    308 
    309   va_start(ap, fmt);
    310   n = sbuffmtv(b, a, fmt, ap);
    311   va_end(ap);
    312   return n;
    313 }
    314 
    315 static void
    316 sbufcat(struct strbuf *b, const char *s, size_t n, size_t a)
    317 {
    318   char *d;
    319 
    320   d = sbufalloc(b, n + 1, a);
    321   memcpy(d, s, n);
    322   d[n] = 0;
    323   b->len += n;
    324 }
    325 
    326 static void
    327 bioinit(struct bufio *f, int fd)
    328 {
    329   f->fd  = fd;
    330   f->pos = f->end = f->buf;
    331   f->off          = 0;
    332 }
    333 
    334 static size_t
    335 bioread(struct bufio *f, void *p, size_t n)
    336 {
    337   size_t         l;
    338   unsigned char *d;
    339   struct iovec   iov[2];
    340   ssize_t        r;
    341 
    342   d = p;
    343   if (f->pos != f->end) {
    344     l = f->end - f->pos;
    345     if (n < l)
    346       l = n;
    347     memcpy(d, f->pos, l);
    348     f->pos += l;
    349     n -= l;
    350     d += l;
    351   }
    352   iov[1].iov_base = f->buf;
    353   iov[1].iov_len  = sizeof f->buf;
    354   for (; n > 0; n -= r, d += r) {
    355     iov[0].iov_base = d;
    356     iov[0].iov_len  = n;
    357     r               = readv(f->fd, iov, 2);
    358     if (r < 0)
    359       f->err = errno;
    360     if (r <= 0)
    361       break;
    362     if ((size_t)r >= n) {
    363       f->pos = f->buf;
    364       f->end = f->buf + (r - n);
    365       r      = n;
    366     }
    367   }
    368   l = d - (unsigned char *)p;
    369   f->off += l;
    370   return l;
    371 }
    372 
    373 static int
    374 bioskip(struct bufio *f, off_t n)
    375 {
    376   static int seekfail;
    377   size_t     l;
    378   ssize_t    r;
    379 
    380   if (f->pos != f->end) {
    381     l = f->end - f->pos;
    382     if (n < (off_t)l) {
    383       f->pos += n;
    384       return 0;
    385     }
    386     n -= l;
    387     f->pos = f->end = f->buf;
    388   }
    389   if (!seekfail) {
    390     if (n == 0 || lseek(f->fd, n, SEEK_CUR) >= 0)
    391       return 0;
    392     seekfail = 1;
    393   }
    394   for (; n > 0; n -= r) {
    395     l = sizeof f->buf;
    396     if (n < (off_t)l)
    397       l = n;
    398     r = read(f->fd, f->buf, l);
    399     if (r <= 0)
    400       return -1;
    401   }
    402   return 0;
    403 }
    404 
    405 static void
    406 copyblock(char *b, struct bufio *r, size_t nr, FILE *w, size_t nw)
    407 {
    408   if (bioread(r, b, nr) != nr) {
    409     if (r->err)
    410       fatal("read: %s", strerror(r->err));
    411     fatal("archive truncated");
    412   }
    413   if (nw > nr)
    414     memset(b + nr, 0, nw - nr);
    415   if (nw && fwrite(b, 1, nw, w) != nw)
    416     fatal("write:");
    417 }
    418 
    419 /* nr and nw must differ by at most 8192 */
    420 static void
    421 copy(struct bufio *r, off_t nr, FILE *w, off_t nw)
    422 {
    423   char b[8192];
    424 
    425   assert(nr - nw <= (off_t)sizeof b || nw - nr <= (off_t)sizeof b);
    426   for (; nr > (off_t)sizeof b && nw > (off_t)sizeof b; nr -= (off_t)sizeof b, nw -= (off_t)sizeof b)
    427     copyblock(b, r, sizeof b, w, sizeof b);
    428   copyblock(b, r, nr, w, nw);
    429 }
    430 
    431 static struct account *
    432 findaccount(const char *name, uid_t uid, gid_t gid)
    433 {
    434   static struct account *accts;
    435   static size_t          acctslen;
    436   struct account        *a;
    437 
    438   for (a = accts; a < accts + acctslen; ++a) {
    439     if ((uid == (uid_t)-1 || uid == a->uid) && (gid == (gid_t)-1 || gid == a->gid)
    440         && (!name || (a->name && strcmp(a->name, name) == 0)))
    441       return a;
    442   }
    443   if ((acctslen & (acctslen - 1)) == 0) {
    444     accts = reallocarray(accts, acctslen ? acctslen * 2 : 16, sizeof *accts);
    445     if (!accts)
    446       fatal(NULL);
    447   }
    448   a       = &accts[acctslen++];
    449   a->name = NULL;
    450   a->type = 0;
    451   a->uid  = -1;
    452   a->gid  = -1;
    453   if (name) {
    454     a->name = strdup(name);
    455     if (!a->name)
    456       fatal(NULL);
    457   }
    458   return a;
    459 }
    460 
    461 static uid_t
    462 unametouid(const char *uname, uid_t fallback)
    463 {
    464   struct account *a;
    465   struct passwd  *pw;
    466 
    467   if (!*uname)
    468     return fallback;
    469   a = findaccount(uname, (uid_t)-1, (gid_t)-1);
    470   if (~a->type & UID) {
    471     a->type |= UID;
    472     pw     = getpwnam(uname);
    473     a->uid = pw ? pw->pw_uid : (uid_t)-1;
    474   }
    475   return a->uid != (uid_t)-1 ? a->uid : fallback;
    476 }
    477 
    478 static gid_t
    479 gnametogid(const char *gname, gid_t fallback)
    480 {
    481   struct account *a;
    482   struct group   *gr;
    483 
    484   if (!*gname)
    485     return fallback;
    486   a = findaccount(gname, (uid_t)-1, (gid_t)-1);
    487   if (~a->type & GID) {
    488     a->type |= GID;
    489     gr     = getgrnam(gname);
    490     a->gid = gr ? gr->gr_gid : (gid_t)-1;
    491   }
    492   return a->gid != (gid_t)-1 ? a->gid : fallback;
    493 }
    494 
    495 static char *
    496 uidtouname(uid_t uid, char *fallback)
    497 {
    498   struct account *a;
    499   struct passwd  *pw;
    500 
    501   a = findaccount(NULL, uid, (gid_t)-1);
    502   if (~a->type & UID) {
    503     a->type |= UID;
    504     a->uid = uid;
    505     assert(!a->name);
    506     pw = getpwuid(uid);
    507     if (pw) {
    508       a->name = strdup(pw->pw_name);
    509       if (!a->name)
    510         fatal(NULL);
    511     }
    512   }
    513   return a->name ? a->name : fallback;
    514 }
    515 
    516 static char *
    517 gidtogname(gid_t gid, char *fallback)
    518 {
    519   struct account *a;
    520   struct group   *gr;
    521 
    522   a = findaccount(NULL, (uid_t)-1, gid);
    523   if (~a->type & GID) {
    524     a->type |= GID;
    525     a->gid = gid;
    526     assert(!a->name);
    527     gr = getgrgid(gid);
    528     if (gr) {
    529       a->name = strdup(gr->gr_name);
    530       if (!a->name)
    531         fatal(NULL);
    532     }
    533   }
    534   return a->name ? a->name : fallback;
    535 }
    536 
    537 static unsigned long long
    538 octnum(const char *str, size_t len)
    539 {
    540   const char        *end;
    541   unsigned           c;
    542   unsigned long long n;
    543 
    544   n   = 0;
    545   end = str + len;
    546   /* some archives have leading spaces, so skip them */
    547   for (; str != end && *str == ' '; ++str)
    548     ;
    549   for (; str != end; ++str) {
    550     c = *str;
    551     if (c == ' ' || c == '\0')
    552       break;
    553     c -= '0';
    554     if (c > 7)
    555       fatal("invalid number field");
    556     n = n * 8 + c;
    557   }
    558   return n;
    559 }
    560 
    561 static unsigned long long
    562 decnum(const char *str, size_t len, char **pos)
    563 {
    564   const char        *end;
    565   unsigned           c;
    566   unsigned long long n;
    567 
    568   n   = 0;
    569   end = str + len;
    570   for (; str != end; ++str) {
    571     c = *str - '0';
    572     if (c > 9)
    573       break;
    574     n = n * 10 + c;
    575   }
    576   if (pos)
    577     *pos = (char *)str;
    578   return n;
    579 }
    580 
    581 static int
    582 readustar(struct bufio *f, struct header *h)
    583 {
    584   static char   buf[512];
    585   static off_t  end;
    586   size_t        namelen, prefixlen, linklen;
    587   unsigned long sum;
    588   int           i;
    589   enum format   format;
    590 
    591   assert(bioin.off <= end);
    592   if (bioskip(f, end - bioin.off) != 0 || bioread(f, buf, sizeof buf) != sizeof buf) {
    593     if (f->err)
    594       fatal("read: %s", strerror(f->err));
    595     fatal("archive truncated");
    596   }
    597   sum = 0;
    598   for (i = 0; i < 512; ++i)
    599     sum += ((unsigned char *)buf)[i];
    600   if (sum == 0)
    601     return 0;
    602   for (i = 148; i < 156; ++i)
    603     sum += ' ' - ((unsigned char *)buf)[i];
    604   if (sum != octnum(buf + 148, 8))
    605     fatal("invalid tar header: bad checksum");
    606   if (memcmp(
    607           buf + 257,
    608           "ustar\0"
    609           "00",
    610           8
    611       )
    612       == 0)
    613     format = USTAR;
    614   else if (memcmp(buf + 257, "ustar  ", 8) == 0)
    615     format = GNUTAR;
    616   else
    617     format = V7;
    618   h->fields = PATH | UID | GID | SIZE;
    619   namelen   = strnlen(buf, 100);
    620   prefixlen = format == USTAR ? strnlen(buf + 345, 155) : 0;
    621   if (namelen == 100 || prefixlen > 0) {
    622     h->pathbuf.len = 0;
    623     if (prefixlen > 0) {
    624       sbufcat(&h->pathbuf, buf + 345, prefixlen, 1024);
    625       sbufcat(&h->pathbuf, "/", 1, 1024);
    626     }
    627     sbufcat(&h->pathbuf, buf, namelen, 1024);
    628     h->path    = h->pathbuf.str;
    629     h->pathlen = h->pathbuf.len;
    630   } else {
    631     h->path    = buf;
    632     h->pathlen = namelen;
    633   }
    634   h->dev   = 0;
    635   h->ino   = 0;
    636   h->mode  = octnum(buf + 100, 8);
    637   h->uid   = octnum(buf + 108, 8);
    638   h->gid   = octnum(buf + 116, 8);
    639   h->nlink = 1;
    640   h->size  = octnum(buf + 124, 12);
    641   end      = bioin.off + ROUNDUP(h->size, 512);
    642   h->mtime = (struct timespec){.tv_sec = octnum(buf + 136, 12)};
    643   if (format == GNUTAR) {
    644     h->fields |= ATIME | CTIME;
    645     h->atime = (struct timespec){.tv_sec = octnum(buf + 345, 12)};
    646     h->ctime = (struct timespec){.tv_sec = octnum(buf + 357, 12)};
    647   }
    648   h->type = buf[156];
    649   if (h->type == AREGTYPE)
    650     h->type = REGTYPE;
    651 
    652   linklen = strnlen(buf + 157, 100);
    653   if (linklen > 0)
    654     h->fields |= LINKPATH;
    655   if (linklen == 100) {
    656     h->linkbuf.len = 0;
    657     sbufcat(&h->linkbuf, buf + 157, 100, 1024);
    658     h->link    = h->linkbuf.str;
    659     h->linklen = h->linkbuf.len;
    660   } else {
    661     h->link = buf + 157;
    662   }
    663   h->linklen = linklen;
    664   if (format == V7) {
    665     h->uname = "";
    666     h->gname = "";
    667   } else {
    668     h->fields |= UNAME | GNAME;
    669     h->uname = buf + 265;
    670     if (!memchr(h->uname, '\0', 32))
    671       fatal("uname is not NUL-terminated");
    672     h->gname = buf + 297;
    673     if (!memchr(h->gname, '\0', 32))
    674       fatal("gname is not NUL-terminated");
    675     if (h->type == CHRTYPE || h->type == BLKTYPE) {
    676       unsigned major, minor;
    677 
    678       major   = octnum(buf + 329, 8);
    679       minor   = octnum(buf + 337, 8);
    680       h->rdev = fs_makedev(major, minor);
    681     }
    682   }
    683   return 1;
    684 }
    685 
    686 static void
    687 parsetime(struct timespec *ts, const char *field, const char *str, size_t len)
    688 {
    689   const char        *end = str + len;
    690   char              *pos;
    691   unsigned long long subsec;
    692   size_t             sublen;
    693 
    694   ts->tv_sec = decnum(str, len, &pos);
    695   if (*pos == '.') {
    696     str    = ++pos;
    697     subsec = decnum(str, end - str, &pos);
    698     for (sublen = pos - str; sublen < 9; ++sublen)
    699       subsec *= 10;
    700     ts->tv_nsec = subsec % 1000000000;
    701   }
    702   if (pos != end)
    703     fatal("invalid extended header: bad %s", field);
    704 }
    705 
    706 static void
    707 extkeyval(struct header *h, const char *key, const char *val, size_t vallen)
    708 {
    709   enum field            field;
    710   char                 *end;
    711   const struct keyword *kw;
    712 
    713   field = 0;
    714   for (kw = keywords; kw != keywords + LEN(keywords); ++kw) {
    715     if (strcmp(key, kw->name) == 0) {
    716       field = kw->field;
    717       break;
    718     }
    719   }
    720   if (!field) {
    721     if (strcmp(key, "charset") == 0) {
    722     } else if (strcmp(key, "comment") == 0) {
    723       /* ignore */
    724     } else if (strcmp(key, "hdrcharset") == 0) {
    725     } else if (strncmp(key, "realtime.", 9) == 0) {
    726     } else if (strncmp(key, "security.", 9) == 0) {
    727     } else {
    728       fprintf(stderr, "ignoring unknown keyword '%s'\n", key);
    729     }
    730     return;
    731   }
    732   if ((h->delete | opt.delete) & field)
    733     return;
    734 
    735   switch (field) {
    736     case ATIME:
    737       parsetime(&h->atime, "atime", val, vallen);
    738       break;
    739     case CTIME:
    740       parsetime(&h->ctime, "ctime", val, vallen);
    741       break;
    742     case GID:
    743       h->gid = decnum(val, vallen, &end);
    744       if (end != val + vallen)
    745         fatal("invalid extended header: bad gid");
    746       break;
    747     case GNAME:
    748       h->gnamebuf.len = 0;
    749       sbufcat(&h->gnamebuf, val, vallen, 256);
    750       h->gname = h->gnamebuf.str;
    751       break;
    752     case LINKPATH:
    753       h->linkbuf.len = 0;
    754       sbufcat(&h->linkbuf, val, vallen, 1024);
    755       h->link    = h->linkbuf.str;
    756       h->linklen = h->linkbuf.len;
    757       break;
    758     case MTIME:
    759       parsetime(&h->mtime, "mtime", val, vallen);
    760       break;
    761     case PATH:
    762       h->pathbuf.len = 0;
    763       sbufcat(&h->pathbuf, val, vallen, 1024);
    764       h->path    = h->pathbuf.str;
    765       h->pathlen = h->pathbuf.len;
    766       break;
    767     case SIZE:
    768       h->size = decnum(val, vallen, &end);
    769       if (end != val + vallen)
    770         fatal("invalid extended header: bad size");
    771       break;
    772     case UID:
    773       h->uid = decnum(val, vallen, &end);
    774       if (end != val + vallen)
    775         fatal("invalid extended header: bad uid");
    776       break;
    777     case UNAME:
    778       h->unamebuf.len = 0;
    779       sbufcat(&h->unamebuf, val, vallen, 256);
    780       h->uname = h->unamebuf.str;
    781       break;
    782     default:
    783       return;
    784   }
    785   h->fields |= field;
    786 }
    787 
    788 static void
    789 readexthdr(struct bufio *f, struct header *h, off_t len)
    790 {
    791   static struct strbuf buf;
    792   size_t               reclen, vallen;
    793   char                *rec, *end, *key, *val;
    794 
    795   if (len > (off_t)SIZE_MAX)
    796     fatal("extended header is too large");
    797   buf.len = 0;
    798   sbufalloc(&buf, (size_t)len, 8192);
    799   if (bioread(f, buf.str, (size_t)len) != (size_t)len) {
    800     if (f->err)
    801       fatal("read: %s", strerror(f->err));
    802     fatal("archive truncated");
    803   }
    804   rec = buf.str;
    805   while (len > 0) {
    806     end = memchr(rec, '\n', len);
    807     if (!end)
    808       fatal(
    809           "invalid extended header: record is missing "
    810           "newline"
    811       );
    812     *end   = '\0';
    813     reclen = decnum(rec, (size_t)(end - rec), &key);
    814     if (*key != ' ' || reclen != (unsigned long long)(end - rec + 1))
    815       fatal("invalid extended header: invalid record");
    816     ++key;
    817     val = strchr(key, '=');
    818     if (!val)
    819       fatal("invalid extended header: record has no '='");
    820     *val++ = '\0';
    821     vallen = end - val;
    822     extkeyval(h, key, val, vallen);
    823     len -= reclen;
    824     rec += reclen;
    825   }
    826 }
    827 
    828 static void
    829 readgnuhdr(struct bufio *f, struct strbuf *b, off_t len)
    830 {
    831   if (len > (off_t)(SIZE_MAX - 1))
    832     fatal("GNU header is too large");
    833   b->len = 0;
    834   sbufalloc(b, (size_t)(len + 1), 1024);
    835   if (bioread(f, b->str, (size_t)len) != (size_t)len) {
    836     if (f->err)
    837       fatal("read: %s", strerror(f->err));
    838     fatal("archive truncated");
    839   }
    840   b->str[len] = '\0';
    841   b->len      = len;
    842 }
    843 
    844 static int
    845 readpax(struct bufio *f, struct header *h)
    846 {
    847   exthdr.fields = exthdr.delete;
    848   while (readustar(f, h)) {
    849     switch (h->type) {
    850       case 'g':
    851         readexthdr(f, &globexthdr, h->size);
    852         break;
    853       case 'x':
    854         readexthdr(f, &exthdr, h->size);
    855         break;
    856       case 'L':
    857         if ((exthdr.delete | opt.delete) & PATH)
    858           break;
    859         readgnuhdr(f, &exthdr.pathbuf, h->size);
    860         exthdr.path    = exthdr.pathbuf.str;
    861         exthdr.pathlen = exthdr.pathbuf.len;
    862         exthdr.fields |= PATH;
    863         break;
    864       case 'K':
    865         if ((exthdr.delete | opt.delete) & LINKPATH)
    866           break;
    867         readgnuhdr(f, &exthdr.linkbuf, h->size);
    868         exthdr.link    = exthdr.linkbuf.str;
    869         exthdr.linklen = exthdr.linkbuf.len;
    870         exthdr.fields |= LINKPATH;
    871         break;
    872       default:
    873         return 1;
    874     }
    875   }
    876   return 0;
    877 }
    878 
    879 static int
    880 readcpio(struct bufio *f, struct header *h)
    881 {
    882   static off_t  end;
    883   unsigned long type;
    884   char          buf[76];
    885 
    886   if (bioskip(f, end - bioin.off) != 0 || bioread(f, buf, sizeof buf) != sizeof buf) {
    887     if (f->err)
    888       fatal("read: %s", strerror(f->err));
    889     fatal("archive truncated");
    890   }
    891   if (memcmp(buf, "070707", 6) != 0)
    892     fatal("invalid cpio header: bad magic");
    893   h->pathlen = octnum(buf + 59, 6);
    894   if (h->pathlen == 0)
    895     fatal("invalid cpio header: c_namesize is 0");
    896   h->pathbuf.len = 0;
    897   sbufalloc(&h->pathbuf, h->pathlen, 1024);
    898   h->path = h->pathbuf.str;
    899   if (bioread(f, h->path, h->pathlen) != h->pathlen) {
    900     if (f->err)
    901       fatal("read: %s", strerror(f->err));
    902     fatal("archive truncated");
    903   }
    904   if (h->path[--h->pathlen] != '\0')
    905     fatal("invalid cpio header: name is not NUL-terminated");
    906   if (strcmp(h->path, "TRAILER!!!") == 0)
    907     return 0;
    908 
    909   h->fields = PATH | MODE | UID | GID | MTIME | SIZE;
    910   h->dev    = octnum(buf + 6, 6);
    911   h->ino    = octnum(buf + 12, 6);
    912   type      = octnum(buf + 18, 6);
    913   h->mode   = type & 07777;
    914   type &= ~07777;
    915   switch (type) {
    916     case C_ISDIR:
    917       h->type = DIRTYPE;
    918       break;
    919     case C_ISFIFO:
    920       h->type = FIFOTYPE;
    921       break;
    922     case C_ISREG:
    923       h->type = REGTYPE;
    924       break;
    925     case C_ISLNK:
    926       h->type = SYMTYPE;
    927       break;
    928     case C_ISBLK:
    929       h->type = BLKTYPE;
    930       break;
    931     case C_ISCHR:
    932       h->type = CHRTYPE;
    933       break;
    934     default:
    935       fatal(
    936           "invalid cpio header: invalid or unsupported file type: "
    937           "%#o",
    938           type
    939       );
    940   }
    941   h->uid   = octnum(buf + 24, 6);
    942   h->gid   = octnum(buf + 30, 6);
    943   h->nlink = octnum(buf + 36, 6);
    944   h->rdev  = octnum(buf + 42, 6);
    945   h->mtime = (struct timespec){.tv_sec = octnum(buf + 48, 11)};
    946   h->size  = octnum(buf + 65, 11);
    947   h->uname = "";
    948   h->gname = "";
    949   if (h->type == SYMTYPE) {
    950     if (h->size > (off_t)(SIZE_MAX - 1))
    951       fatal("symlink target is too long");
    952     h->linklen     = h->size;
    953     h->linkbuf.len = 0;
    954     h->link        = sbufalloc(&h->linkbuf, h->linklen + 1, 1024);
    955     if (bioread(f, h->link, h->linklen) != h->linklen) {
    956       if (f->err)
    957         fatal("read: %s", strerror(f->err));
    958       fatal("archive truncated");
    959     }
    960     h->link[h->linklen] = '\0';
    961     h->size             = 0;
    962     h->fields |= LINKPATH;
    963   } else {
    964     h->link    = "";
    965     h->linklen = 0;
    966   }
    967   end = bioin.off + h->size;
    968   return 1;
    969 }
    970 
    971 static int
    972 decompress(const char *algo, int fd, pid_t *pid)
    973 {
    974   extern char              **environ;
    975   posix_spawn_file_actions_t fa;
    976   int                        p[2], err;
    977   char                      *argv[3];
    978 
    979   if (!algo)
    980     return fd;
    981   argv[0] = (char *)algo;
    982   argv[1] = "-dc";
    983   argv[2] = NULL;
    984   if (pipe2(p, O_CLOEXEC) != 0)
    985     fatal("pipe2:");
    986   err = posix_spawn_file_actions_init(&fa);
    987   if (err)
    988     fatal("posix_spawn_file_actions_init: %s", strerror(errno));
    989   err = posix_spawn_file_actions_adddup2(&fa, fd, 0);
    990   if (err)
    991     fatal("posix_spawn_file_actions_adddup2: %s", strerror(errno));
    992   err = posix_spawn_file_actions_adddup2(&fa, p[1], 1);
    993   if (err)
    994     fatal("posix_spawn_file_actions_adddup2: %s", strerror(errno));
    995   err = posix_spawnp(pid, algo, &fa, NULL, argv, environ);
    996   if (err)
    997     fatal("posix_spawnp %s: %s", algo, strerror(errno));
    998   close(p[1]);
    999   return p[0];
   1000 }
   1001 
   1002 static readfn *
   1003 detectformat(struct bufio *f, const char *algo, pid_t *pid)
   1004 {
   1005   size_t         l, i;
   1006   ssize_t        n;
   1007   unsigned char *b;
   1008 
   1009 again:
   1010   f->fd = decompress(algo, f->fd, pid);
   1011   b     = (unsigned char *)f->buf;
   1012   for (l = 0; l < 512; l += n) {
   1013     n = read(f->fd, b + l, 512 - l);
   1014     if (n < 0)
   1015       fatal("read:");
   1016     if (n == 0)
   1017       break;
   1018   }
   1019   f->pos = f->buf;
   1020   f->end = f->buf + l;
   1021   if (l == 512) {
   1022     unsigned long sum, hdrsum;
   1023 
   1024     sum = 0;
   1025     for (i = 0; i < 512; ++i)
   1026       sum += b[i];
   1027     if (sum == 0)
   1028       return readpax;
   1029     hdrsum = 0;
   1030     for (i = 148; i < 156; ++i) {
   1031       sum += ' ' - b[i];
   1032       if (b[i] >= '0' && b[i] <= '9')
   1033         hdrsum = hdrsum * 8 + (b[i] - '0');
   1034     }
   1035     if (sum == hdrsum)
   1036       return readpax;
   1037   }
   1038   if (l >= 76) {
   1039     if (memcmp(b, "070707", 6) == 0)
   1040       return readcpio;
   1041   }
   1042   if (!algo) {
   1043     static const struct command {
   1044       char          algo[6];
   1045       unsigned char magiclen;
   1046       unsigned char magic[6];
   1047     } cmds[] = {
   1048         {"gzip", 2, {0x1F, 0x8B}},
   1049         {"bzip2", 2, {'B', 'Z'}},
   1050         {"xz", 6, {0xFD, '7', 'z', 'X', 'Z', 0x00}},
   1051         {"zstd", 4, {0x28, 0xB5, 0x2F, 0xFD}},
   1052         {"lzip", 4, {'L', 'Z', 'I', 'P'}},
   1053     };
   1054     const struct command *c;
   1055 
   1056     for (c = cmds; c < cmds + LEN(cmds); ++c) {
   1057       if (l >= c->magiclen && memcmp(b, c->magic, c->magiclen) == 0) {
   1058         if (lseek(f->fd, 0, SEEK_SET) != 0)
   1059           fatal(
   1060               "compression detection requires "
   1061               "seekable input"
   1062           );
   1063         algo = c->algo;
   1064         goto again;
   1065       }
   1066     }
   1067   }
   1068   return NULL;
   1069 }
   1070 
   1071 static FILE *
   1072 compress(const char *algo, const char *name, pid_t *pid)
   1073 {
   1074   extern char              **environ;
   1075   FILE                      *f;
   1076   int                        fd, p[2], err;
   1077   posix_spawn_file_actions_t fa;
   1078   char                      *argv[3];
   1079 
   1080   if (!algo) {
   1081     if (name && !freopen(name, aflag ? "r+" : "w", stdout))
   1082       fatal("open %s:");
   1083     if (aflag && name) {
   1084       if (fseek(stdout, 0, SEEK_END) != 0)
   1085         fatal("fseek %s:");
   1086     }
   1087     return stdout;
   1088   }
   1089   argv[0] = (char *)algo;
   1090   argv[1] = "-c";
   1091   argv[2] = NULL;
   1092   if (name) {
   1093     fd = open(name, O_WRONLY | O_CREAT, 0666);
   1094     if (fd < 0)
   1095       fatal("open %s:");
   1096   } else {
   1097     fd = 1;
   1098   }
   1099   if (pipe2(p, O_CLOEXEC) != 0)
   1100     fatal("pipe2:");
   1101   f = fdopen(p[1], "w");
   1102   if (!f)
   1103     fatal("fdopen:");
   1104   err = posix_spawn_file_actions_init(&fa);
   1105   if (err)
   1106     fatal("posix_spawn_file_actions_init: %s", strerror(errno));
   1107   err = posix_spawn_file_actions_adddup2(&fa, p[0], 0);
   1108   if (err)
   1109     fatal("posix_spawn_file_actions_adddup2: %s", strerror(errno));
   1110   err = posix_spawn_file_actions_adddup2(&fa, fd, 1);
   1111   if (err)
   1112     fatal("posix_spawn_file_actions_adddup2: %s", strerror(errno));
   1113   err = posix_spawnp(pid, algo, &fa, NULL, argv, environ);
   1114   if (err)
   1115     fatal("posix_spawnp %s: %s", algo, strerror(errno));
   1116   close(fd);
   1117   close(p[0]);
   1118   return f;
   1119 }
   1120 
   1121 static char *
   1122 splitname(char *name, size_t namelen)
   1123 {
   1124   char *slash;
   1125 
   1126   if (namelen > 256)
   1127     return NULL;
   1128   slash = memchr(name + namelen - 100, '/', 100);
   1129   if (!slash || slash - name > 155)
   1130     return NULL;
   1131   return slash;
   1132 }
   1133 
   1134 static void
   1135 openfile(struct header *h)
   1136 {
   1137   int fd;
   1138 
   1139   if (h->file) {
   1140     fd = open(h->file, O_RDONLY);
   1141     if (fd < 0)
   1142       fatal("open %s:", h->file);
   1143     bioinit(&bioin, fd);
   1144   }
   1145 }
   1146 
   1147 static void
   1148 closefile(struct header *h)
   1149 {
   1150   if (h->file) {
   1151     if (tflag)
   1152       futimens(bioin.fd, (struct timespec[2]){h->fileatime, {.tv_nsec = UTIME_OMIT}});
   1153     close(bioin.fd);
   1154   }
   1155 }
   1156 
   1157 static void
   1158 closeustar(FILE *f)
   1159 {
   1160   char pad[512];
   1161 
   1162   memset(pad, 0, 512);
   1163   if (fwrite(pad, 512, 1, f) != 1)
   1164     fatal("write:");
   1165   if (fwrite(pad, 512, 1, f) != 1)
   1166     fatal("write:");
   1167 }
   1168 
   1169 static void
   1170 writeustar(FILE *f, struct header *h)
   1171 {
   1172   char          buf[512], *slash, tmp[32];
   1173   unsigned long sum;
   1174   int           i;
   1175 
   1176   if (!h) {
   1177     closeustar(f);
   1178     return;
   1179   }
   1180   slash = h->slash;
   1181   if (!slash && h->pathlen > 100) {
   1182     slash = splitname(h->path, h->pathlen);
   1183     if (!slash)
   1184       fatal("path is too long: %s\n", h->path);
   1185   }
   1186   if (slash) {
   1187     size_t len;
   1188 
   1189     strncpy(buf, slash + 1, 100);
   1190     len = slash - h->path;
   1191     memcpy(buf + 345, h->path, len);
   1192     memset(buf + 345 + len, 0, 155 - len);
   1193   } else {
   1194     strncpy(buf, h->path, 100);
   1195     memset(buf + 345, 0, 155);
   1196   }
   1197   if (h->mode > 07777777)
   1198     fatal("mode is too large: %ju", (uintmax_t)h->mode);
   1199   snprintf(tmp, sizeof(tmp), "%.7lo", (unsigned long)h->mode & 07777777);
   1200   memcpy(buf + 100, tmp, 8);
   1201   if (h->uid > MAXUGID)
   1202     fatal("uid is too large: %ju", (uintmax_t)h->uid);
   1203   snprintf(tmp, sizeof(tmp), "%.7lo", (unsigned long)h->uid & 07777777);
   1204   memcpy(buf + 108, tmp, 8);
   1205   if (h->gid > MAXUGID)
   1206     fatal("gid is too large: %ju", (uintmax_t)h->gid);
   1207   snprintf(tmp, sizeof(tmp), "%.7lo", (unsigned long)h->gid & 07777777);
   1208   memcpy(buf + 116, tmp, 8);
   1209   if (h->size < 0 || h->size > MAXSIZE)
   1210     fatal("size is too large: %ju", (uintmax_t)h->size);
   1211   snprintf(buf + 124, 12, "%.11llo", (unsigned long long)h->size);
   1212   if (h->mtime.tv_sec < 0 || h->mtime.tv_sec > MAXTIME)
   1213     fatal("mtime is too large: %ju", (uintmax_t)h->mtime.tv_sec);
   1214   snprintf(buf + 136, 12, "%.11llo", (unsigned long long)h->mtime.tv_sec);
   1215   memset(buf + 148, ' ', 8);
   1216   buf[156] = h->type;
   1217   if (h->linklen > 100)
   1218     fatal("link name is too long: %s\n", h->link);
   1219   strncpy(buf + 157, h->link, 100);
   1220   memcpy(buf + 257, "ustar", 6);
   1221   memcpy(buf + 263, "00", 2);
   1222   if (strlen(h->uname) > 31)
   1223     fatal("user name is too long: %s\n", h->uname);
   1224   strncpy(buf + 265, h->uname, 32);
   1225   if (strlen(h->gname) > 31)
   1226     fatal("group name is too long: %s\n", h->gname);
   1227   strncpy(buf + 297, h->gname, 32);
   1228   if (fs_devmajor(h->rdev) > 07777777)
   1229     fatal("device major is too large: %ju\n", (uintmax_t)fs_devmajor(h->rdev));
   1230   snprintf(tmp, sizeof(tmp), "%.7lo", (unsigned long)fs_devmajor(h->rdev) & 07777777);
   1231   memcpy(buf + 329, tmp, 8);
   1232   if (fs_devminor(h->rdev) > 07777777)
   1233     fatal("device minor is too large: %ju\n", (uintmax_t)fs_devminor(h->rdev));
   1234   snprintf(tmp, sizeof(tmp), "%.7lo", (unsigned long)fs_devminor(h->rdev) & 07777777);
   1235   memcpy(buf + 337, tmp, 8);
   1236   memset(buf + 500, 0, 12);
   1237   sum = 0;
   1238   for (i = 0; i < 512; ++i)
   1239     sum += ((unsigned char *)buf)[i];
   1240   snprintf(tmp, sizeof(tmp), "%.7lo", sum & 07777777);
   1241   memcpy(buf + 148, tmp, 8);
   1242   if (fwrite(buf, 512, 1, f) != 1)
   1243     fatal("write:");
   1244   if (h->data) {
   1245     size_t pad;
   1246 
   1247     if (fwrite(h->data, 1, (size_t)h->size, f) != (size_t)h->size)
   1248       fatal("write:");
   1249     pad = (size_t)(ROUNDUP(h->size, 512) - h->size);
   1250     memset(bioin.buf, 0, pad);
   1251     if (fwrite(bioin.buf, 1, pad, f) != pad)
   1252       fatal("write:");
   1253   } else if (h->size > 0) {
   1254     openfile(h);
   1255     copy(&bioin, h->size, f, ROUNDUP(h->size, 512));
   1256     closefile(h);
   1257   }
   1258 }
   1259 
   1260 static void
   1261 writerec(struct strbuf *ext, const char *fmt, ...)
   1262 {
   1263   static struct strbuf buf;
   1264   va_list              ap;
   1265   int                  d, n, m, l;
   1266 
   1267   buf.len = 0;
   1268   va_start(ap, fmt);
   1269   l = sbuffmtv(&buf, 256, fmt, ap);
   1270   va_end(ap);
   1271 
   1272   d = 0;
   1273   m = 1;
   1274   for (n = l; n > 0; n /= 10) {
   1275     m *= 10;
   1276     ++d;
   1277   }
   1278   n = d + 1 + l + 1;
   1279   if (n >= m)
   1280     ++n;
   1281   sbuffmt(ext, 256, "%d %.*s\n", n, l, buf.str);
   1282 }
   1283 
   1284 static void
   1285 writetimerec(struct strbuf *ext, char *kw, struct timespec *ts)
   1286 {
   1287   if (ts->tv_nsec != 0)
   1288     writerec(ext, "%s=%ju.%.9ld", kw, (uintmax_t)ts->tv_sec, ts->tv_nsec % 1000000000);
   1289   else
   1290     writerec(ext, "%s=%ju", kw, (uintmax_t)ts->tv_sec);
   1291 }
   1292 
   1293 static void
   1294 writeexthdr(FILE *f, int type, struct header *h)
   1295 {
   1296   static struct strbuf ext;
   1297   struct header        exthdr;
   1298 
   1299   ext.len = 0;
   1300   if (h->fields & PATH)
   1301     writerec(&ext, "path=%s", h->path);
   1302   if (h->fields & UID)
   1303     writerec(&ext, "uid=%ju", (uintmax_t)h->uid);
   1304   if (h->fields & GID)
   1305     writerec(&ext, "gid=%ju", (uintmax_t)h->gid);
   1306   if (h->fields & SIZE)
   1307     writerec(&ext, "size=%ju", (uintmax_t)h->size);
   1308   if (h->fields & MTIME)
   1309     writetimerec(&ext, "mtime", &h->mtime);
   1310   if (h->fields & ATIME)
   1311     writetimerec(&ext, "atime", &h->atime);
   1312   if (h->fields & CTIME)
   1313     writetimerec(&ext, "ctime", &h->ctime);
   1314   if (h->fields & UNAME)
   1315     writerec(&ext, "uname=%s", h->uname);
   1316   if (h->fields & GNAME)
   1317     writerec(&ext, "gname=%s", h->gname);
   1318   if (ext.len > 0) {
   1319     memset(&exthdr, 0, sizeof exthdr);
   1320     exthdr.path    = "pax_extended_header";
   1321     exthdr.pathlen = 20;
   1322     exthdr.mode    = 0600;
   1323     exthdr.link    = "";
   1324     exthdr.uname   = "";
   1325     exthdr.gname   = "";
   1326     exthdr.size    = ext.len;
   1327     exthdr.type    = type;
   1328     exthdr.data    = ext.str;
   1329     writeustar(f, &exthdr);
   1330   }
   1331 }
   1332 
   1333 static void
   1334 mergehdr(struct header *dst, struct header *src, enum field fields)
   1335 {
   1336   fields &= src->fields;
   1337   if (fields & PATH) {
   1338     dst->path    = src->path;
   1339     dst->pathlen = src->pathlen;
   1340   }
   1341   if (fields & UID)
   1342     dst->uid = src->uid;
   1343   if (fields & GID)
   1344     dst->gid = src->gid;
   1345   if (fields & SIZE)
   1346     dst->size = src->size;
   1347   if (fields & MTIME)
   1348     dst->mtime = src->mtime;
   1349   if (fields & ATIME)
   1350     dst->atime = src->atime;
   1351   if (fields & CTIME)
   1352     dst->ctime = src->ctime;
   1353   if (fields & UNAME)
   1354     dst->uname = src->uname;
   1355   if (fields & GNAME)
   1356     dst->gname = src->gname;
   1357   if (fields & LINKPATH) {
   1358     dst->link    = src->link;
   1359     dst->linklen = src->linklen;
   1360   }
   1361   dst->fields |= fields;
   1362 }
   1363 
   1364 static void
   1365 writepax(FILE *f, struct header *h)
   1366 {
   1367   enum field fields;
   1368 
   1369   if (!h) {
   1370     closeustar(f);
   1371     return;
   1372   }
   1373   if (vflag)
   1374     fprintf(stderr, "%s\n", h->path);
   1375   fields = 0;
   1376   if (h->pathlen > 100) {
   1377     h->slash = splitname(h->path, h->pathlen);
   1378     if (!h->slash)
   1379       fields |= PATH;
   1380   }
   1381   if (h->uid > MAXUGID)
   1382     fields |= UID;
   1383   if (h->gid > MAXUGID)
   1384     fields |= GID;
   1385   if (h->size > MAXSIZE)
   1386     fields |= SIZE;
   1387   if (h->mtime.tv_sec > MAXTIME || h->mtime.tv_nsec != 0)
   1388     fields |= MTIME;
   1389   if (opt.times)
   1390     fields |= ATIME | CTIME;
   1391   if (strlen(h->uname) > 31)
   1392     fields |= UNAME;
   1393   if (strlen(h->gname) > 31)
   1394     fields |= GNAME;
   1395   if (h->linklen > 100)
   1396     fields |= LINKPATH;
   1397   fields &= ~(exthdr.fields | opt.delete);
   1398   mergehdr(&exthdr, h, fields);
   1399   writeexthdr(f, 'x', &exthdr);
   1400 
   1401   /* reset fields merged into extended header */
   1402   if (fields & PATH)
   1403     h->path = "", h->pathlen = 0;
   1404   if (fields & UID)
   1405     h->uid = 0;
   1406   if (fields & GID)
   1407     h->gid = 0;
   1408   if (fields & SIZE)
   1409     h->size = 0;
   1410   if (fields & MTIME) {
   1411     if (h->mtime.tv_sec > MAXTIME)
   1412       h->mtime.tv_sec = MAXTIME;
   1413     h->mtime.tv_nsec = 0;
   1414   }
   1415   if (fields & ATIME) {
   1416     if (h->atime.tv_sec > MAXTIME)
   1417       h->atime.tv_sec = MAXTIME;
   1418     h->atime.tv_nsec = 0;
   1419   }
   1420   if (fields & CTIME) {
   1421     if (h->ctime.tv_sec > MAXTIME)
   1422       h->ctime.tv_sec = MAXTIME;
   1423     h->ctime.tv_nsec = 0;
   1424   }
   1425   if (fields & UNAME)
   1426     h->uname = "";
   1427   if (fields & GNAME)
   1428     h->gname = "";
   1429   if (fields & LINKPATH)
   1430     h->link = "", h->linklen = 0;
   1431   h->fields &= ~fields;
   1432   writeustar(f, h);
   1433 }
   1434 
   1435 static void
   1436 writecpio(FILE *f, struct header *h)
   1437 {
   1438   static unsigned long ino;
   1439   char                 buf[77];
   1440   unsigned long        mode;
   1441   uintmax_t            size;
   1442   size_t               namesize;
   1443   int                  len;
   1444 
   1445   if (!h) {
   1446     memcpy(buf, "070707", 6);
   1447     memset(buf + 6, '0', 70);
   1448     memcpy(buf + 59, "000013", 6);
   1449     if (fwrite(buf, 1, 76, f) != 76)
   1450       fatal("write:");
   1451     if (fwrite("TRAILER!!!", 1, 11, f) != 11)
   1452       fatal("write:");
   1453     return;
   1454   }
   1455   if (vflag)
   1456     fprintf(stderr, "%s\n", h->path);
   1457   mode = h->mode;
   1458   switch (h->type) {
   1459     case DIRTYPE:
   1460       mode |= S_IFDIR;
   1461       break;
   1462     case FIFOTYPE:
   1463       mode |= S_IFIFO;
   1464       break;
   1465     case REGTYPE:
   1466       mode |= S_IFREG;
   1467       break;
   1468     case SYMTYPE:
   1469       mode |= S_IFLNK;
   1470       break;
   1471     case BLKTYPE:
   1472       mode |= S_IFBLK;
   1473       break;
   1474     case CHRTYPE:
   1475       mode |= S_IFCHR;
   1476       break;
   1477     default:
   1478       fatal("unknown or unsupported header type");
   1479   }
   1480   if (h->dev > 0777777)
   1481     fatal("device is too large: %ju", (uintmax_t)h->dev);
   1482   if (++ino > 0777777)
   1483     fatal("inode is too large: %lu", ino);
   1484   if (mode > 0777777)
   1485     fatal("mode is too large: %lu", mode);
   1486   if (h->uid > MAXUGID)
   1487     fatal("uid is too large: %ju", (uintmax_t)h->uid);
   1488   if (h->gid > MAXUGID)
   1489     fatal("gid is too large: %ju", (uintmax_t)h->gid);
   1490   if (h->nlink > 0777777)
   1491     fatal("nlink is too large: %ju", (uintmax_t)h->nlink);
   1492   if (h->rdev > 0777777)
   1493     fatal("device is too large: %ju", (uintmax_t)h->rdev);
   1494   if (h->mtime.tv_sec > MAXTIME)
   1495     fatal("mtime is too large: %ju", (uintmax_t)h->mtime.tv_sec);
   1496   namesize = h->pathlen;
   1497   if (namesize > 0 && h->path[namesize - 1] == '/')
   1498     --namesize;
   1499   if (namesize > 077777777777 - 1)
   1500     fatal("path is too large: %ju", (uintmax_t)h->pathlen + 1);
   1501   size = h->type == SYMTYPE ? (uintmax_t)h->linklen : (uintmax_t)h->size;
   1502   if (size > MAXSIZE)
   1503     fatal("size is too large: %ju", h->size);
   1504   len = snprintf(
   1505       buf,
   1506       sizeof buf,
   1507       "070707%.6lo%.6lo%.6lo%.6lo%.6lo%.6lo%.6lo%.11llo%.6lo%.11jo",
   1508       (unsigned long)h->dev,
   1509       ino,
   1510       mode,
   1511       (unsigned long)h->uid,
   1512       (unsigned long)h->gid,
   1513       (unsigned long)h->nlink,
   1514       (unsigned long)h->rdev,
   1515       (unsigned long long)h->mtime.tv_sec,
   1516       (unsigned long)namesize + 1,
   1517       size
   1518   );
   1519   assert(len == 76);
   1520   if (fwrite(buf, 1, 76, f) != 76)
   1521     fatal("write:");
   1522   if (fwrite(h->path, 1, namesize, f) != namesize || fputc('\0', f) == EOF)
   1523     fatal("write:");
   1524   switch (h->type) {
   1525     case SYMTYPE:
   1526       if (fwrite(h->link, 1, h->linklen, f) != h->linklen)
   1527         fatal("write:");
   1528       break;
   1529     case REGTYPE:
   1530       openfile(h);
   1531       copy(&bioin, h->size, f, h->size);
   1532       closefile(h);
   1533       break;
   1534     default:
   1535       break;
   1536   }
   1537 }
   1538 
   1539 static void
   1540 filepush(struct filelist *files, const char *name, size_t pathlen, dev_t dev)
   1541 {
   1542   struct file *f;
   1543   size_t       namelen;
   1544 
   1545   namelen = strlen(name);
   1546   f       = malloc(sizeof *f + namelen + 1);
   1547   if (!f)
   1548     fatal(NULL);
   1549   memcpy(f->name, name, namelen + 1);
   1550   f->namelen     = namelen;
   1551   f->pathlen     = pathlen;
   1552   f->dev         = dev;
   1553   f->next        = files->pending;
   1554   files->pending = f;
   1555 }
   1556 
   1557 static int
   1558 readfile(struct bufio *f, struct header *h)
   1559 {
   1560   /* use our own path buffer, since we use it for traversal */
   1561   static struct strbuf path;
   1562   struct stat          st;
   1563   int                  flag;
   1564   DIR                 *dir;
   1565   struct dirent       *d;
   1566   ssize_t              ret;
   1567   dev_t                dev;
   1568 
   1569   (void)f;
   1570 
   1571 next:
   1572   flag = follow == 'L' ? 0 : AT_SYMLINK_NOFOLLOW;
   1573   if (files.pending) {
   1574     struct file *f;
   1575 
   1576     f             = files.pending;
   1577     files.pending = f->next;
   1578     assert(f->pathlen <= path.len);
   1579     path.len = f->pathlen;
   1580     sbufcat(&path, f->name, f->namelen, 1024);
   1581     if (follow == 'H' && f->pathlen > 0)
   1582       flag &= ~AT_SYMLINK_NOFOLLOW;
   1583     dev = f->dev;
   1584     free(f);
   1585   } else {
   1586     if (!files.input)
   1587       return 0;
   1588     ret = getline(&path.str, &path.cap, files.input);
   1589     if (ret < 0) {
   1590       if (ferror(files.input))
   1591         fatal("getline:");
   1592       return 0;
   1593     }
   1594     if (ret > 0 && path.str[ret - 1] == '\n')
   1595       path.str[--ret] = '\0';
   1596     path.len = ret;
   1597     dev      = 0;
   1598   }
   1599 
   1600   if (fstatat(AT_FDCWD, path.str, &st, flag) != 0)
   1601     fatal("stat %s:", path.str);
   1602   if (Xflag && dev && st.st_dev != dev)
   1603     goto next;
   1604   if (S_ISDIR(st.st_mode) && path.str[path.len - 1] != '/')
   1605     sbufcat(&path, "/", 1, 1024);
   1606   h->fields    = PATH | UID | GID | ATIME | MTIME | CTIME;
   1607   h->path      = path.str;
   1608   h->pathlen   = path.len;
   1609   h->dev       = st.st_dev;
   1610   h->ino       = st.st_ino;
   1611   h->mode      = st.st_mode & ~S_IFMT;
   1612   h->uid       = st.st_uid;
   1613   h->gid       = st.st_gid;
   1614   h->nlink     = st.st_nlink;
   1615   h->rdev      = 0;
   1616   h->size      = 0;
   1617   h->atime     = st.st_atim;
   1618   h->mtime     = st.st_mtim;
   1619   h->ctime     = st.st_ctim;
   1620   h->uname     = uidtouname(st.st_uid, "");
   1621   h->gname     = gidtogname(st.st_gid, "");
   1622   h->link      = "";
   1623   h->linklen   = 0;
   1624   h->slash     = NULL;
   1625   h->data      = NULL;
   1626   h->file      = h->path;
   1627   h->fileatime = st.st_atim;
   1628   h->flag      = flag;
   1629   switch (st.st_mode & S_IFMT) {
   1630     case S_IFREG:
   1631       h->type = REGTYPE;
   1632       h->size = st.st_size;
   1633       break;
   1634     case S_IFLNK:
   1635       h->type        = SYMTYPE;
   1636       h->linkbuf.len = 0;
   1637       sbufalloc(&h->linkbuf, 1024, 1024);
   1638       for (;;) {
   1639         ret = readlink(h->path, h->linkbuf.str, h->linkbuf.cap - 1);
   1640         if (ret < 0)
   1641           fatal("readlink %s:", h->path);
   1642         if ((size_t)ret < h->linkbuf.cap)
   1643           break;
   1644         if (h->linkbuf.cap > (size_t)SSIZE_MAX / 2)
   1645           fatal("symlink target is too long");
   1646         sbufalloc(&h->linkbuf, h->linkbuf.cap * 2, 1024);
   1647       }
   1648       h->linkbuf.str[ret] = '\0';
   1649       h->linkbuf.len      = ret;
   1650       h->link             = h->linkbuf.str;
   1651       h->linklen          = h->linkbuf.len;
   1652       break;
   1653     case S_IFCHR:
   1654       h->type = CHRTYPE;
   1655       h->rdev = st.st_rdev;
   1656       break;
   1657     case S_IFBLK:
   1658       h->type = BLKTYPE;
   1659       h->rdev = st.st_rdev;
   1660       break;
   1661     case S_IFDIR:
   1662       h->type = DIRTYPE;
   1663       dir     = opendir(h->path);
   1664       if (!dir)
   1665         fatal("opendir %s:", h->path);
   1666       for (;;) {
   1667         errno = 0;
   1668         d     = readdir(dir);
   1669         if (!d)
   1670           break;
   1671         if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0)
   1672           continue;
   1673         filepush(&files, d->d_name, path.len, st.st_dev);
   1674       }
   1675       if (errno != 0)
   1676         fatal("readdir %s:", h->path);
   1677       closedir(dir);
   1678       break;
   1679     case S_IFIFO:
   1680       h->type = FIFOTYPE;
   1681       break;
   1682   }
   1683   return 1;
   1684 }
   1685 
   1686 static void
   1687 usage(void)
   1688 {
   1689   fprintf(stderr, "usage: pax\n");
   1690   exit(2);
   1691 }
   1692 
   1693 static void
   1694 print_listopt(struct header *h)
   1695 {
   1696   const char *s;
   1697   size_t      len;
   1698 
   1699   s = opt.listopt;
   1700   while (*s) {
   1701     if (*s == '%') {
   1702       s++;
   1703       if (*s == '%') {
   1704         putchar('%');
   1705         s++;
   1706       } else {
   1707         len = 0;
   1708         while (s[len] && isalnum((unsigned char)s[len]))
   1709           len++;
   1710         if (len > 0) {
   1711           if (strncmp(s, "path", len) == 0 && len == 4)
   1712             printf("%s", h->path);
   1713           else if (strncmp(s, "size", len) == 0 && len == 4)
   1714             printf("%ju", (uintmax_t)h->size);
   1715           else if (strncmp(s, "uid", len) == 0 && len == 3)
   1716             printf("%ju", (uintmax_t)h->uid);
   1717           else if (strncmp(s, "gid", len) == 0 && len == 3)
   1718             printf("%ju", (uintmax_t)h->gid);
   1719           else if (strncmp(s, "uname", len) == 0 && len == 5)
   1720             printf("%s", h->uname);
   1721           else if (strncmp(s, "gname", len) == 0 && len == 5)
   1722             printf("%s", h->gname);
   1723           else if (strncmp(s, "mode", len) == 0 && len == 4)
   1724             printf("%04o", (unsigned int)(h->mode & 07777));
   1725           else if (strncmp(s, "mtime", len) == 0 && len == 5)
   1726             printf("%ju", (uintmax_t)h->mtime.tv_sec);
   1727           else if (strncmp(s, "atime", len) == 0 && len == 5)
   1728             printf("%ju", (uintmax_t)h->atime.tv_sec);
   1729           else if (strncmp(s, "ctime", len) == 0 && len == 5)
   1730             printf("%ju", (uintmax_t)h->ctime.tv_sec);
   1731           else if (strncmp(s, "linkpath", len) == 0 && len == 8)
   1732             printf("%s", h->link);
   1733           else {
   1734             putchar('%');
   1735             fwrite(s, 1, len, stdout);
   1736           }
   1737           s += len;
   1738         } else {
   1739           putchar('%');
   1740         }
   1741       }
   1742     } else if (*s == '\\') {
   1743       s++;
   1744       if (*s == 'n') {
   1745         putchar('\n');
   1746         s++;
   1747       } else if (*s == 't') {
   1748         putchar('\t');
   1749         s++;
   1750       } else if (*s == '\\') {
   1751         putchar('\\');
   1752         s++;
   1753       } else if (*s) {
   1754         putchar(*s);
   1755         s++;
   1756       }
   1757     } else {
   1758       putchar(*s);
   1759       s++;
   1760     }
   1761   }
   1762   putchar('\n');
   1763 }
   1764 
   1765 static void
   1766 parseopts(char *s)
   1767 {
   1768   char *key, *val, *end, *d;
   1769   int   ext;
   1770 
   1771   for (;;) {
   1772     s += strspn(s, " \t\n\v\f\r");
   1773     if (!*s)
   1774       break;
   1775     key = s;
   1776     while (*s && *s != ',' && *s != '=')
   1777       ++s;
   1778     val = NULL;
   1779     end = NULL, ext = 0; /* silence gcc uninitialized warning */
   1780     if (*s == '=') {
   1781       ext     = s > key && s[-1] == ':';
   1782       s[-ext] = '\0';
   1783       val     = ++s;
   1784       for (d = s; *s && *s != ','; ++s, ++d) {
   1785         if (*s == '\\')
   1786           ++s;
   1787         if (d < s)
   1788           *d = *s;
   1789       }
   1790       end = d;
   1791     }
   1792     if (*s == ',')
   1793       *s++ = '\0';
   1794     if (strcmp(key, "linkdata") == 0) {
   1795       if (val)
   1796         fatal(
   1797             "option 'linkdata' must not have a "
   1798             "value"
   1799         );
   1800       opt.linkdata = 1;
   1801     } else if (strcmp(key, "times") == 0) {
   1802       if (val)
   1803         fatal("option 'times' must not have a value");
   1804       opt.times = 1;
   1805     } else if (!val) {
   1806       fatal("option '%s' must have a value", key);
   1807     } else if (strcmp(key, "delete") == 0) {
   1808       const struct keyword *kw;
   1809 
   1810       for (kw = keywords; kw != keywords + LEN(keywords); ++kw) {
   1811         switch (fnmatch(val, kw->name, 0)) {
   1812           case 0:
   1813             opt.delete |= kw->field;
   1814             break;
   1815           case FNM_NOMATCH:
   1816             break;
   1817           default:
   1818             fatal("fnmatch error");
   1819         }
   1820       }
   1821     } else if (strcmp(key, "exthdr.name") == 0) {
   1822       opt.exthdrname = val;
   1823     } else if (strcmp(key, "globexthdr.name") == 0) {
   1824       opt.globexthdrname = val;
   1825     } else if (strcmp(key, "invalid") == 0) {
   1826       if (strcmp(val, "bypass") != 0 && strcmp(val, "rename") != 0 && strcmp(val, "UTF-8") != 0
   1827           && strcmp(val, "write") != 0) {
   1828         fatal(
   1829             "invalid action '%s' for option "
   1830             "'invalid'",
   1831             val
   1832         );
   1833       }
   1834       opt.invalid = val;
   1835     } else if (strcmp(key, "listopt") == 0) {
   1836       opt.listopt = val;
   1837     } else {
   1838       extkeyval(ext ? &exthdr : &globexthdr, key, val, end - val);
   1839     }
   1840   }
   1841 }
   1842 
   1843 static void
   1844 listhdr(FILE *f, struct header *h)
   1845 {
   1846   char        mode[11], time[13], info[23];
   1847   char        unamebuf[(sizeof(uid_t) * CHAR_BIT + 2) / 3 + 1];
   1848   char        gnamebuf[(sizeof(gid_t) * CHAR_BIT + 2) / 3 + 1];
   1849   const char *uname, *gname, *timefmt;
   1850   struct tm  *tm;
   1851 
   1852   if (!h)
   1853     return;
   1854   (void)f;
   1855   if (opt.listopt) {
   1856     print_listopt(h);
   1857     return;
   1858   }
   1859   if (!vflag) {
   1860     printf("%s\n", h->path);
   1861     return;
   1862   }
   1863   memset(mode, '-', sizeof mode - 1);
   1864   mode[10] = '\0';
   1865   switch (h->type) {
   1866     case SYMTYPE:
   1867       mode[0] = 'l';
   1868       break;
   1869     case CHRTYPE:
   1870       mode[0] = 'c';
   1871       break;
   1872     case BLKTYPE:
   1873       mode[0] = 'b';
   1874       break;
   1875     case DIRTYPE:
   1876       mode[0] = 'd';
   1877       break;
   1878     case FIFOTYPE:
   1879       mode[0] = 'p';
   1880       break;
   1881   }
   1882   if (h->mode & S_IRUSR)
   1883     mode[1] = 'r';
   1884   if (h->mode & S_IWUSR)
   1885     mode[2] = 'w';
   1886   if (h->mode & S_IXUSR)
   1887     mode[3] = 'x';
   1888   if (h->mode & S_IRGRP)
   1889     mode[4] = 'r';
   1890   if (h->mode & S_IWGRP)
   1891     mode[5] = 'w';
   1892   if (h->mode & S_IXGRP)
   1893     mode[6] = 'x';
   1894   if (h->mode & S_IROTH)
   1895     mode[7] = 'r';
   1896   if (h->mode & S_IWOTH)
   1897     mode[8] = 'w';
   1898   if (h->mode & S_IXOTH)
   1899     mode[9] = 'x';
   1900   if (h->mode & S_ISUID)
   1901     mode[3] = mode[3] == 'x' ? 's' : 'S';
   1902   if (h->mode & S_ISGID)
   1903     mode[3] = mode[6] == 'x' ? 's' : 'S';
   1904   if (h->mode & S_ISVTX)
   1905     mode[9] = mode[9] == 'x' ? 't' : 'T';
   1906   uname = h->uname;
   1907   if (!uname[0]) {
   1908     snprintf(unamebuf, sizeof unamebuf, "%ju", (uintmax_t)h->uid);
   1909     uname = unamebuf;
   1910   }
   1911   gname = h->gname;
   1912   if (!gname[0]) {
   1913     snprintf(gnamebuf, sizeof gnamebuf, "%ju", (uintmax_t)h->gid);
   1914     gname = gnamebuf;
   1915   }
   1916   timefmt = h->mtime.tv_sec + 15780000 < curtime || h->mtime.tv_sec > curtime ? "%b %e  %Y"
   1917                                                                               : "%b %e %H:%M";
   1918   tm      = localtime(&h->mtime.tv_sec);
   1919   if (!tm)
   1920     fatal("localtime:");
   1921   strftime(time, sizeof time, timefmt, tm);
   1922   if (h->type == CHRTYPE || h->type == BLKTYPE)
   1923     snprintf(info, sizeof info, "%u, %u", fs_devmajor(h->rdev), fs_devminor(h->rdev));
   1924   else
   1925     snprintf(info, sizeof info, "%ju", (uintmax_t)h->size);
   1926   printf(
   1927       "%s %2ju %-8s %-8s %9s %s %s", mode, (uintmax_t)h->nlink, uname, gname, info, time, h->path
   1928   );
   1929   switch (h->type) {
   1930     case LNKTYPE:
   1931       printf(" == %s", h->link);
   1932       break;
   1933     case SYMTYPE:
   1934       printf(" -> %s", h->link);
   1935       break;
   1936   }
   1937   putchar('\n');
   1938 }
   1939 
   1940 static void
   1941 mkdirp(int fd, char *name, size_t len)
   1942 {
   1943   char *p;
   1944 
   1945   if (len == 0)
   1946     return;
   1947   for (p = name + 1; p < name + len - 1; ++p) {
   1948     if (*p != '/')
   1949       continue;
   1950     *p = 0;
   1951     if (mkdirat(fd, name, 0777) != 0 && errno != EEXIST)
   1952       fatal("mkdir %s:", name);
   1953     *p = '/';
   1954   }
   1955 }
   1956 
   1957 static void
   1958 writefile(FILE *unused, struct header *h)
   1959 {
   1960   FILE       *f;
   1961   int         fd, retry, flags;
   1962   struct stat st;
   1963   mode_t      mode;
   1964 
   1965   (void)unused;
   1966   if (!h)
   1967     return;
   1968   if (uflag && fstatat(destfd, h->path, &st, 0) == 0) {
   1969     if (h->mtime.tv_sec < st.st_mtime
   1970         || (h->mtime.tv_sec == st.st_mtime && h->mtime.tv_nsec < st.st_mtim.tv_nsec))
   1971       return;
   1972   }
   1973   if (vflag)
   1974     fprintf(stderr, "%s\n", h->path);
   1975   if (lflag && h->file && h->type != DIRTYPE) {
   1976     if (linkat(AT_FDCWD, h->file, destfd, h->path, h->flag) == 0)
   1977       return;
   1978   }
   1979   retry = 1;
   1980   if (0) {
   1981   retry:
   1982     retry = 0;
   1983     mkdirp(destfd, h->path, h->pathlen);
   1984   }
   1985   mode = h->mode & ~(S_ISUID | S_ISGID);
   1986   switch (h->type) {
   1987     case REGTYPE:
   1988       flags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC;
   1989       if (kflag)
   1990         flags |= O_EXCL;
   1991       fd = openat(destfd, h->path, flags, mode);
   1992       if (fd < 0) {
   1993         if (retry && errno == ENOENT)
   1994           goto retry;
   1995         fatal("open %s%s:", dest, h->path);
   1996       }
   1997       f = fdopen(fd, "w");
   1998       if (!f)
   1999         fatal("open %s:", h->path);
   2000       openfile(h);
   2001       copy(&bioin, h->size, f, h->size);
   2002       closefile(h);
   2003       fclose(f);
   2004       break;
   2005     case LNKTYPE:
   2006       if (linkat(destfd, h->link, destfd, h->path, 0) != 0) {
   2007         if (retry && errno == ENOENT)
   2008           goto retry;
   2009         fatal("link %s%s:", dest, h->path);
   2010       }
   2011       break;
   2012     case SYMTYPE:
   2013       if (symlinkat(h->link, destfd, h->path) != 0) {
   2014         if (retry && errno == ENOENT)
   2015           goto retry;
   2016         fatal("symlink %s%s:", dest, h->path);
   2017       }
   2018       break;
   2019     case CHRTYPE:
   2020     case BLKTYPE:
   2021       mode |= h->type == CHRTYPE ? S_IFCHR : S_IFBLK;
   2022       if (mknodat(destfd, h->path, mode, h->rdev) != 0) {
   2023         if (retry && errno == ENOENT)
   2024           goto retry;
   2025         fatal("mknod %s%s:", dest, h->path);
   2026       }
   2027       break;
   2028     case DIRTYPE:
   2029       if (mkdirat(destfd, h->path, mode) != 0) {
   2030         if (retry && errno == ENOENT)
   2031           goto retry;
   2032         if (errno == EEXIST) {
   2033           if (fstatat(destfd, h->path, &st, 0) == 0 && S_ISDIR(st.st_mode))
   2034             break;
   2035           errno = EEXIST;
   2036         }
   2037         fatal("mkdir %s%s:", dest, h->path);
   2038       }
   2039       break;
   2040     case FIFOTYPE:
   2041       if (mkfifoat(destfd, h->path, mode) != 0) {
   2042         if (retry && errno == ENOENT)
   2043           goto retry;
   2044         if (errno == EEXIST) {
   2045           if (fstatat(destfd, h->path, &st, 0) == 0 && S_ISFIFO(st.st_mode))
   2046             break;
   2047           errno = EEXIST;
   2048         }
   2049         fatal("mkfifo %s%s:", dest, h->path);
   2050       }
   2051       break;
   2052   }
   2053   if (preserve & (ATIME | MTIME)) {
   2054     struct timespec ts[2];
   2055 
   2056     ts[0] = preserve & ATIME ? h->atime : (struct timespec){.tv_nsec = UTIME_OMIT};
   2057     ts[1] = preserve & MTIME ? h->mtime : (struct timespec){.tv_nsec = UTIME_OMIT};
   2058     if (utimensat(destfd, h->path, ts, AT_SYMLINK_NOFOLLOW) != 0) {
   2059       fprintf(stderr, "utimens %s%s: %s\n", dest, h->path, strerror(errno));
   2060       exitstatus = 1;
   2061     }
   2062   }
   2063   if (preserve & (UID | GID)) {
   2064     uid_t uid;
   2065     gid_t gid;
   2066 
   2067     uid = preserve & UID ? unametouid(h->uname, h->uid) : (uid_t)-1;
   2068     gid = preserve & GID ? gnametogid(h->gname, h->gid) : (gid_t)-1;
   2069     if (fchownat(destfd, h->path, uid, gid, 0) != 0) {
   2070       fprintf(stderr, "chown %s%s: %s\n", dest, h->path, strerror(errno));
   2071       exitstatus = 1;
   2072     } else {
   2073       /* add back setuid/setgid bits if we preserved the
   2074        * uid/gid */
   2075       mode = h->mode;
   2076     }
   2077   }
   2078   if (preserve & MODE && h->type != SYMTYPE) {
   2079     if (fchmodat(destfd, h->path, mode, 0) != 0) {
   2080       fprintf(stderr, "chmod %s%s: %s\n", dest, h->path, strerror(errno));
   2081       exitstatus = 1;
   2082     }
   2083   }
   2084 }
   2085 
   2086 static int
   2087 match(struct header *h)
   2088 {
   2089   static struct dir {
   2090     char  *path;
   2091     size_t pathlen;
   2092   }            *dirs;
   2093   static size_t dirslen;
   2094   size_t        i;
   2095 
   2096   if (patslen == 0)
   2097     return 1;
   2098   if (!dflag) {
   2099     struct dir *d;
   2100 
   2101     for (d = dirs; d < dirs + dirslen; ++d) {
   2102       if (h->pathlen >= d->pathlen && memcmp(h->path, d->path, d->pathlen) == 0)
   2103         return !cflag;
   2104     }
   2105   }
   2106   for (i = 0; i < patslen; ++i) {
   2107     if (nflag && patsused[i])
   2108       continue;
   2109     switch (fnmatch(pats[i], h->path, FNM_PATHNAME | FNM_PERIOD)) {
   2110       case 0:
   2111         patsused[i] = 1;
   2112         if (!dflag && h->type == DIRTYPE) {
   2113           struct dir *d;
   2114 
   2115           if ((dirslen & (dirslen - 1)) == 0) {
   2116             dirs = reallocarray(dirs, dirslen ? dirslen * 2 : 32, sizeof *dirs);
   2117             if (!dirs)
   2118               fatal(NULL);
   2119           }
   2120           d          = &dirs[dirslen++];
   2121           d->pathlen = h->pathlen;
   2122           d->path    = malloc(d->pathlen + 1);
   2123           if (!d->path)
   2124             fatal(NULL);
   2125           memcpy(d->path, h->path, h->pathlen);
   2126           /* add trailing slash if not already present */
   2127           if (d->path[d->pathlen - 1] != '/')
   2128             d->path[d->pathlen++] = '/';
   2129         }
   2130         return !cflag;
   2131       case FNM_NOMATCH:
   2132         break;
   2133       default:
   2134         fatal("fnmatch error");
   2135     }
   2136   }
   2137   return cflag;
   2138 }
   2139 
   2140 static void
   2141 parsereplstr(char *str)
   2142 {
   2143   static struct replstr **end = &replstr;
   2144   struct replstr         *r;
   2145   char                   *old, *new, delim;
   2146   int                     err;
   2147 
   2148   delim = str[0];
   2149   if (!delim)
   2150     usage();
   2151   old = str + 1;
   2152   str = strchr(old, delim);
   2153   if (!str)
   2154     usage();
   2155   *str = 0;
   2156   new  = str + 1;
   2157   str  = strchr(new, delim);
   2158   if (!str)
   2159     usage();
   2160   *str = 0;
   2161 
   2162   r = malloc(sizeof *r);
   2163   if (!r)
   2164     fatal(NULL);
   2165   r->next    = NULL;
   2166   r->global  = 0;
   2167   r->print   = 0;
   2168   r->symlink = 0;
   2169   for (;;) {
   2170     switch (*++str) {
   2171       case 'g':
   2172         r->global = 1;
   2173         break;
   2174       case 'p':
   2175         r->print = 1;
   2176         break;
   2177       case 's':
   2178         r->symlink = 0;
   2179         break;
   2180       case 'S':
   2181         r->symlink = 1;
   2182         break;
   2183       case 0:
   2184         goto done;
   2185     }
   2186   }
   2187 done:
   2188   err = regcomp(&r->old, old, REG_NEWLINE);
   2189   if (err != 0) {
   2190     char errbuf[256];
   2191 
   2192     regerror(err, &r->old, errbuf, sizeof errbuf);
   2193     fatal("invalid regular expression: %s", errbuf);
   2194   }
   2195   r->new = new;
   2196   *end   = r;
   2197   end    = &r->next;
   2198 }
   2199 
   2200 static int
   2201 applyrepl(struct replstr *r, struct strbuf *b, const char *old, size_t oldlen)
   2202 {
   2203   regmatch_t  match[10];
   2204   size_t      i, n, l;
   2205   const char *s, *p;
   2206   char       *d;
   2207   int         flags;
   2208 
   2209   flags  = 0;
   2210   b->len = 0;
   2211   p      = old;
   2212   while (regexec(&r->old, p, LEN(match), match, flags) == 0) {
   2213     n = match[0].rm_so;
   2214     for (s = r->new; *s; ++s) {
   2215       switch (*s) {
   2216         case '&':
   2217           i = 0;
   2218           break;
   2219         case '\\':
   2220           i = *++s - '0';
   2221           break;
   2222         default:
   2223           i = -1;
   2224           break;
   2225       }
   2226       n += i <= 9 ? match[i].rm_eo - match[i].rm_so : 1;
   2227     }
   2228     d = sbufalloc(b, n + 1, 1024);
   2229     b->len += n;
   2230     memcpy(d, p, match[0].rm_so);
   2231     d += match[0].rm_so;
   2232     for (s = r->new; *s; ++s) {
   2233       switch (*s) {
   2234         case '&':
   2235           i = 0;
   2236           break;
   2237         case '\\':
   2238           i = *++s - '0';
   2239           break;
   2240         default:
   2241           i = -1;
   2242           break;
   2243       }
   2244       if (i <= 9) {
   2245         l = match[i].rm_eo - match[i].rm_so;
   2246         memcpy(d, p + match[i].rm_so, l);
   2247         d += l;
   2248       } else {
   2249         *d++ = *s;
   2250       }
   2251     }
   2252     flags |= REG_NOTBOL;
   2253     p += match[0].rm_eo;
   2254     if (!r->global)
   2255       break;
   2256   }
   2257   if (flags == 0)
   2258     return 0;
   2259   sbufcat(b, p, oldlen - (p - old), 1024);
   2260   if (r->print)
   2261     fprintf(stderr, "%s >> %s\n", old, b->str);
   2262   return 1;
   2263 }
   2264 
   2265 static void
   2266 replace(struct header *h)
   2267 {
   2268   static struct strbuf path, link;
   2269   struct replstr      *r;
   2270 
   2271   for (r = replstr; r; r = r->next) {
   2272     if (applyrepl(r, &path, h->path, h->pathlen)) {
   2273       h->path    = path.str;
   2274       h->pathlen = path.len;
   2275       break;
   2276     }
   2277   }
   2278   if (h->type != LNKTYPE && h->type != SYMTYPE)
   2279     return;
   2280   for (r = replstr; r; r = r->next) {
   2281     if (h->type == SYMTYPE && !r->symlink)
   2282       continue;
   2283     if (applyrepl(r, &link, h->link, h->linklen)) {
   2284       h->link    = link.str;
   2285       h->linklen = link.len;
   2286       break;
   2287     }
   2288   }
   2289 }
   2290 
   2291 static int
   2292 is_invalid_name(const char *name)
   2293 {
   2294   unsigned char c;
   2295 
   2296   if (!name || !*name)
   2297     return 1;
   2298   for (; *name; name++) {
   2299     c = (unsigned char)*name;
   2300     if (c < 32 || c >= 127)
   2301       return 1;
   2302   }
   2303   return 0;
   2304 }
   2305 
   2306 static void
   2307 interactiverename(struct header *h)
   2308 {
   2309   static FILE *ttyfp = NULL;
   2310   static char  ttybuf[1024];
   2311   char        *res;
   2312 
   2313   if (!iflag)
   2314     return;
   2315 
   2316   if (!ttyfp) {
   2317     ttyfp = fopen("/dev/tty", "r+");
   2318     if (!ttyfp)
   2319       ttyfp = stdin;
   2320   }
   2321 
   2322   fprintf(stderr, "rename %s? ", h->path);
   2323   fflush(stderr);
   2324 
   2325   if (ttyfp == stdin)
   2326     res = fgets(ttybuf, sizeof(ttybuf), stdin);
   2327   else
   2328     res = fgets(ttybuf, sizeof(ttybuf), ttyfp);
   2329 
   2330   if (!res) {
   2331     h->path    = "";
   2332     h->pathlen = 0;
   2333     return;
   2334   }
   2335 
   2336   ttybuf[strcspn(ttybuf, "\n")] = '\0';
   2337 
   2338   if (ttybuf[0] == '\0')
   2339     return;
   2340 
   2341   if (strcmp(ttybuf, ".") == 0) {
   2342     h->path    = "";
   2343     h->pathlen = 0;
   2344     return;
   2345   }
   2346 
   2347   h->pathbuf.len = 0;
   2348   sbufcat(&h->pathbuf, ttybuf, strlen(ttybuf), 1024);
   2349   h->path    = h->pathbuf.str;
   2350   h->pathlen = h->pathbuf.len;
   2351 }
   2352 
   2353 static void
   2354 checkinvalid(struct header *h)
   2355 {
   2356   int saved_iflag;
   2357 
   2358   if (!opt.invalid)
   2359     return;
   2360   if (is_invalid_name(h->path)) {
   2361     if (strcmp(opt.invalid, "bypass") == 0) {
   2362       h->path    = "";
   2363       h->pathlen = 0;
   2364     } else if (strcmp(opt.invalid, "rename") == 0) {
   2365       saved_iflag = iflag;
   2366       iflag       = 1;
   2367       interactiverename(h);
   2368       iflag = saved_iflag;
   2369     }
   2370   }
   2371 }
   2372 
   2373 static off_t
   2374 locate_tar_end(const char *filename)
   2375 {
   2376   char    buf[512];
   2377   off_t   offset      = 0;
   2378   int     zero_blocks = 0;
   2379   int     fd, i, is_zero;
   2380   ssize_t r;
   2381 
   2382   fd = open(filename, O_RDONLY);
   2383   if (fd < 0) {
   2384     if (errno == ENOENT)
   2385       return 0;
   2386     fatal("open %s for append check:", filename);
   2387   }
   2388 
   2389   while ((r = read(fd, buf, 512)) == 512) {
   2390     is_zero = 1;
   2391     for (i = 0; i < 512; i++) {
   2392       if (buf[i] != 0) {
   2393         is_zero = 0;
   2394         break;
   2395       }
   2396     }
   2397     if (is_zero) {
   2398       zero_blocks++;
   2399       if (zero_blocks == 2) {
   2400         close(fd);
   2401         return offset;
   2402       }
   2403     } else {
   2404       zero_blocks = 0;
   2405     }
   2406     offset += 512;
   2407   }
   2408 
   2409   close(fd);
   2410   return offset;
   2411 }
   2412 
   2413 static void
   2414 handle_append(const char *filename, const char *algo, const char *format)
   2415 {
   2416   off_t offset;
   2417   int   fd;
   2418 
   2419   if (!aflag)
   2420     return;
   2421   if (algo)
   2422     fatal("cannot append to compressed archives");
   2423   if (strcmp(format, "ustar") != 0 && strcmp(format, "pax") != 0)
   2424     fatal("append is only supported for ustar and pax formats");
   2425 
   2426   if (filename) {
   2427     offset = locate_tar_end(filename);
   2428     if (offset > 0) {
   2429       fd = open(filename, O_RDWR);
   2430       if (fd >= 0) {
   2431         if (ftruncate(fd, offset) != 0)
   2432           fatal("ftruncate %s for append:", filename);
   2433         close(fd);
   2434       }
   2435     }
   2436   }
   2437 }
   2438 
   2439 // ?man pax: portable archive interchange
   2440 // ?man read, write, and list member files of archive files
   2441 int
   2442 main(int argc, char *argv[])
   2443 {
   2444   const char   *name = NULL, *arg, *format = "pax";
   2445   const char   *algo = NULL;
   2446   enum mode     mode = LIST;
   2447   struct header hdr;
   2448   readfn       *readhdr  = NULL;
   2449   writefn      *writehdr = listhdr;
   2450   FILE         *out      = NULL;
   2451   pid_t         pid      = -1;
   2452   int           i;
   2453   size_t        l;
   2454 
   2455   ARGBEGIN
   2456   {
   2457     case 'a':
   2458       aflag = 1;
   2459       break;
   2460     // ?man -b:str: specify block size or base directory
   2461     case 'b':
   2462       EARGF(usage());
   2463       break;
   2464     // ?man -c: print count or perform stdout action
   2465     case 'c':
   2466       cflag = 1;
   2467       break;
   2468     // ?man -d: specify directory
   2469     case 'd':
   2470       dflag = 1;
   2471       break;
   2472     // ?man -f:str: force the operation
   2473     case 'f':
   2474       name = EARGF(usage());
   2475       break;
   2476     // ?man -H: specify option flag
   2477     case 'H':
   2478       follow = 'H';
   2479       break;
   2480     // ?man -i: interactive mode or prompt for confirmation
   2481     case 'i':
   2482       iflag = 1;
   2483       break;
   2484     // ?man -j: specify option flag
   2485     case 'j':
   2486       algo = "bzip2";
   2487       break;
   2488     // ?man -J: specify option flag
   2489     case 'J':
   2490       algo = "xz";
   2491       break;
   2492     // ?man -k: specify option flag
   2493     case 'k':
   2494       kflag = 1;
   2495       break;
   2496     // ?man -l: list in long format
   2497     case 'l':
   2498       lflag = 1;
   2499       break;
   2500     // ?man -L: specify option flag
   2501     case 'L':
   2502       follow = 'L';
   2503       break;
   2504     // ?man -n: print line numbers or counts
   2505     case 'n':
   2506       nflag = 1;
   2507       break;
   2508     // ?man -o:str: specify output file
   2509     case 'o':
   2510       parseopts(EARGF(usage()));
   2511       break;
   2512     case 'p':
   2513       for (arg = EARGF(usage()); *arg; ++arg) {
   2514         switch (*arg) {
   2515           // ?man -a: print or show all entries
   2516           case 'a':
   2517             preserve &= ~ATIME;
   2518             break;
   2519           // ?man -e: specify expression or pattern
   2520           case 'e':
   2521             preserve = ~0;
   2522             break;
   2523           // ?man -m: specify mode or limit
   2524           case 'm':
   2525             preserve &= ~MTIME;
   2526             break;
   2527           case 'o':
   2528             preserve |= UID | GID;
   2529             break;
   2530             // ?man -p:str: preserve file attributes
   2531           case 'p':
   2532             preserve |= MODE;
   2533             break;
   2534           default:
   2535             fatal("unknown -p option");
   2536         }
   2537       }
   2538       break;
   2539     // ?man -r: operate recursively
   2540     case 'r':
   2541       mode |= READ;
   2542       break;
   2543     // ?man -s:str: silent mode or print summary
   2544     case 's':
   2545       parsereplstr(EARGF(usage()));
   2546       break;
   2547     // ?man -t: sort or specify timestamp
   2548     case 't':
   2549       tflag = 1;
   2550       break;
   2551     // ?man -u: unbuffered output
   2552     case 'u':
   2553       uflag = 1;
   2554       break;
   2555     // ?man -v: verbose mode; show progress
   2556     case 'v':
   2557       vflag = 1;
   2558       break;
   2559     // ?man -w: wait for completion
   2560     case 'w':
   2561       mode |= WRITE;
   2562       break;
   2563     // ?man -x:str: hex format or match whole lines
   2564     case 'x':
   2565       format = EARGF(usage());
   2566       break;
   2567     // ?man -X: specify option flag
   2568     case 'X':
   2569       Xflag = 1;
   2570       break;
   2571     // ?man -z: specify option flag
   2572     case 'z':
   2573       algo = "gzip";
   2574       break;
   2575     default:
   2576       usage();
   2577   }
   2578   ARGEND;
   2579 
   2580   curtime = time(NULL);
   2581   if (curtime == (time_t)-1)
   2582     fatal("time:");
   2583   exthdr.fields &= ~opt.delete;
   2584   exthdr.delete = exthdr.fields;
   2585   globexthdr.fields &= ~opt.delete;
   2586   globexthdr.delete = globexthdr.fields;
   2587   if ((exthdr.fields | globexthdr.fields | opt.delete) & SIZE)
   2588     fatal("field 'size' cannot be overridden or deleted");
   2589 
   2590   switch (mode) {
   2591     case READ:
   2592       writehdr = writefile;
   2593       /* fallthrough */
   2594     case LIST:
   2595       if (name && strcmp(name, "-") != 0) {
   2596         bioin.fd = open(name, O_RDONLY);
   2597         if (bioin.fd < 0)
   2598           fatal("open %s:", name);
   2599       }
   2600       readhdr = detectformat(&bioin, algo, &pid);
   2601       if (!readhdr)
   2602         fatal("could not detect archive format");
   2603       if (argc) {
   2604         pats     = argv;
   2605         patslen  = argc;
   2606         patsused = calloc(1, argc);
   2607         if (!patsused)
   2608           fatal(NULL);
   2609       }
   2610       break;
   2611     case WRITE:
   2612       if (name && strcmp(name, "-") == 0)
   2613         name = NULL;
   2614       handle_append(name, algo, format);
   2615       out = compress(algo, name, &pid);
   2616       if (strcmp(format, "ustar") == 0) {
   2617         writehdr = writeustar;
   2618       } else if (strcmp(format, "pax") == 0) {
   2619         writehdr = writepax;
   2620         if (globexthdr.fields)
   2621           writeexthdr(stdout, 'g', &globexthdr);
   2622       } else if (strcmp(format, "cpio") == 0) {
   2623         writehdr = writecpio;
   2624       } else {
   2625         fatal("unsupported archive format '%s'", format);
   2626       }
   2627       break;
   2628     case COPY:
   2629       if (name || argc == 0)
   2630         usage();
   2631       l    = strlen(argv[--argc]);
   2632       dest = malloc(l + 2);
   2633       if (!dest)
   2634         fatal(NULL);
   2635       memcpy(dest, argv[argc], l);
   2636       memcpy(dest + l, "/", 2);
   2637       destfd = open(dest, O_SEARCH | O_DIRECTORY);
   2638       if (destfd < 0)
   2639         fatal("open %s:", dest);
   2640       writehdr = writefile;
   2641       break;
   2642   }
   2643   if (mode & WRITE) {
   2644     readhdr  = readfile;
   2645     bioin.fd = -1;
   2646     for (i = 0; i < argc; ++i)
   2647       filepush(&files, argv[i], 0, 0);
   2648     if (argc == 0)
   2649       files.input = stdin;
   2650   }
   2651 
   2652   memset(&hdr, 0, sizeof hdr);
   2653   while (readhdr(&bioin, &hdr)) {
   2654     mergehdr(&hdr, &exthdr, ~0);
   2655     mergehdr(&hdr, &globexthdr, ~exthdr.fields);
   2656     if (match(&hdr)) {
   2657       replace(&hdr);
   2658       checkinvalid(&hdr);
   2659       interactiverename(&hdr);
   2660       if (*hdr.path)
   2661         writehdr(out, &hdr);
   2662     }
   2663   }
   2664   writehdr(out, NULL);
   2665   if (out) {
   2666     if (fflush(out) != 0)
   2667       fatal("write:");
   2668     fclose(out);
   2669   }
   2670   for (i = 0; i < (int)patslen; ++i) {
   2671     if (!patsused[i])
   2672       fatal("pattern not matched: %s", pats[i]);
   2673   }
   2674 
   2675   if (pid != -1) {
   2676     int st;
   2677 
   2678     if (waitpid(pid, &st, 0) == -1)
   2679       fatal("waitpid:");
   2680     if (WIFEXITED(st) && WEXITSTATUS(st) != 0)
   2681       fatal("child exited with status %d", WEXITSTATUS(st));
   2682     if (WIFSIGNALED(st))
   2683       fatal("child terminated by signal %d", WTERMSIG(st));
   2684   }
   2685   return exitstatus;
   2686 }