aruu

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

tar.c (26655B)


      1 
      2 
      3 #if FEATURE_MKNOD
      4 #ifndef _DEFAULT_SOURCE
      5 #define _DEFAULT_SOURCE
      6 #endif
      7 #endif
      8 
      9 #include "config.h"
     10 #include "filesystem.h"
     11 #include "fs.h"
     12 #include "utf.h"
     13 #include "util.h"
     14 #include "wexec.h"
     15 
     16 #include <assert.h>
     17 #include <errno.h>
     18 #include <fcntl.h>
     19 #include <fnmatch.h>
     20 #include <grp.h>
     21 #include <libgen.h>
     22 #include <pwd.h>
     23 #include <stdio.h>
     24 #include <stdlib.h>
     25 #include <string.h>
     26 #include <sys/stat.h>
     27 #include <sys/time.h>
     28 #include <sys/types.h>
     29 #include <unistd.h>
     30 
     31 #if FEATURE_TAR_TTY_SAFE
     32 static void
     33 safe_puts(const char *s)
     34 {
     35   Rune r;
     36   int  n;
     37 
     38   if (isatty(1)) {
     39     while (*s) {
     40       n = chartorune(&r, s);
     41       if (r == Runeerror) {
     42         putchar('?');
     43         s++;
     44       } else if (isprintrune(r)) {
     45         fputrune(&r, stdout);
     46         s += n;
     47       } else {
     48         putchar('?');
     49         s += n;
     50       }
     51     }
     52     putchar('\n');
     53   } else {
     54     puts(s);
     55   }
     56 }
     57 #else
     58 #define safe_puts(s) puts(s)
     59 #endif
     60 
     61 #define BLKSIZ (sizeof(struct header)) /* must equal 512 bytes */
     62 
     63 enum Type {
     64   REG       = '0',
     65   AREG      = '\0',
     66   HARDLINK  = '1',
     67   SYMLINK   = '2',
     68   CHARDEV   = '3',
     69   BLOCKDEV  = '4',
     70   DIRECTORY = '5',
     71   FIFO      = '6',
     72   RESERVED  = '7'
     73 };
     74 
     75 struct header {
     76   char name[100];
     77   char mode[8];
     78   char uid[8];
     79   char gid[8];
     80   char size[12];
     81   char mtime[12];
     82   char chksum[8];
     83   char type;
     84   char linkname[100];
     85   char magic[6];
     86   char version[2];
     87   char uname[32];
     88   char gname[32];
     89   char major[8];
     90   char minor[8];
     91   char prefix[155];
     92   char padding[12];
     93 };
     94 
     95 static struct dirtime {
     96   char  *name;
     97   time_t mtime;
     98 } *dirtimes;
     99 
    100 static size_t dirtimeslen;
    101 
    102 static int   tarfd;
    103 static ino_t tarinode;
    104 static dev_t tardev;
    105 
    106 static int mflag, vflag, no_same_owner;
    107 static int filtermode;
    108 
    109 #if FEATURE_TAR_EXCLUDE
    110 static char **excludes     = NULL;
    111 static size_t excludes_cnt = 0;
    112 
    113 static void
    114 add_exclude(const char *pattern)
    115 {
    116   excludes                 = ereallocarray(excludes, excludes_cnt + 1, sizeof(*excludes));
    117   excludes[excludes_cnt++] = estrdup(pattern);
    118 }
    119 
    120 static int
    121 is_excluded(const char *path)
    122 {
    123   size_t      i;
    124   const char *base = strrchr(path, '/');
    125   base             = base ? base + 1 : path;
    126 
    127   for (i = 0; i < excludes_cnt; i++) {
    128     if (fnmatch(excludes[i], path, 0) == 0 || fnmatch(excludes[i], base, 0) == 0)
    129       return 1;
    130   }
    131   return 0;
    132 }
    133 #endif
    134 static const char *filtertool;
    135 
    136 static const char *filtertools[] = {
    137     ['J'] = "xz",
    138     ['Z'] = "compress",
    139     ['a'] = "lzma",
    140     ['j'] = "bzip2",
    141     ['z'] = "gzip",
    142 };
    143 
    144 #if FEATURE_TAR_TO_STDOUT
    145 static int Oflag_stdout = 0;
    146 #else
    147 #define Oflag_stdout 0
    148 #endif
    149 
    150 #if FEATURE_TAR_KEEP_OLD
    151 static int kflag_keep = 0;
    152 #else
    153 #define kflag_keep 0
    154 #endif
    155 
    156 #if FEATURE_TAR_STRIP_COMPONENTS
    157 static int strip_components_count = 0;
    158 
    159 static char *
    160 strip_components(char *path, int count)
    161 {
    162   char *p = path;
    163   int   i;
    164 
    165   for (i = 0; i < count; i++) {
    166     p = strchr(p, '/');
    167     if (!p)
    168       return NULL;
    169     while (*p == '/')
    170       p++;
    171   }
    172   return p;
    173 }
    174 #else
    175 #define strip_components_count 0
    176 #endif
    177 
    178 #if FEATURE_TAR_FILES_FROM
    179 static char **files_from     = NULL;
    180 static size_t files_from_cnt = 0;
    181 
    182 static void
    183 add_files_from(const char *path)
    184 {
    185   files_from                   = ereallocarray(files_from, files_from_cnt + 1, sizeof(*files_from));
    186   files_from[files_from_cnt++] = estrdup(path);
    187 }
    188 
    189 static void
    190 load_files_from_file(const char *path)
    191 {
    192   FILE *fp = fopen(path, "r");
    193   char  line[PATH_MAX];
    194 
    195   if (!fp)
    196     eprintf("open %s:", path);
    197   while (fgets(line, sizeof(line), fp)) {
    198     size_t len = strlen(line);
    199     while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r'))
    200       len--;
    201     line[len] = '\0';
    202     if (len > 0)
    203       add_files_from(line);
    204   }
    205   fclose(fp);
    206 }
    207 #else
    208 #define files_from_cnt 0
    209 #endif
    210 
    211 #if FEATURE_TAR_EXCLUDE_FROM
    212 static void
    213 load_excludes_from_file(const char *path)
    214 {
    215   FILE *fp = fopen(path, "r");
    216   char  line[PATH_MAX];
    217 
    218   if (!fp)
    219     eprintf("open %s:", path);
    220   while (fgets(line, sizeof(line), fp)) {
    221     size_t len = strlen(line);
    222     while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r'))
    223       len--;
    224     line[len] = '\0';
    225     if (len > 0) {
    226 #if FEATURE_TAR_EXCLUDE
    227       add_exclude(line);
    228 #else
    229       (void)line;
    230 #endif
    231     }
    232   }
    233   fclose(fp);
    234 }
    235 #endif
    236 
    237 static void
    238 pushdirtime(char *name, time_t mtime)
    239 {
    240   dirtimes                    = ereallocarray(dirtimes, dirtimeslen + 1, sizeof(*dirtimes));
    241   dirtimes[dirtimeslen].name  = estrdup(name);
    242   dirtimes[dirtimeslen].mtime = mtime;
    243   dirtimeslen++;
    244 }
    245 
    246 static struct dirtime *
    247 popdirtime(void)
    248 {
    249   if (dirtimeslen) {
    250     dirtimeslen--;
    251     return &dirtimes[dirtimeslen];
    252   }
    253   return NULL;
    254 }
    255 
    256 static int
    257 comp(int fd, const char *tool, const char *flags)
    258 {
    259   int fds[2];
    260 
    261   if (pipe(fds) < 0)
    262     eprintf("pipe:");
    263 
    264   switch (fork()) {
    265     case -1:
    266       eprintf("fork:");
    267       /* fallthrough */
    268     case 0:
    269       dup2(fd, 1);
    270       dup2(fds[0], 0);
    271       close(fds[0]);
    272       close(fds[1]);
    273 
    274       {
    275         char *tar_argv[3];
    276         tar_argv[0] = (char *)tool;
    277         tar_argv[1] = (char *)flags;
    278         tar_argv[2] = NULL;
    279         wexecvp_self(tool, tar_argv);
    280       }
    281       weprintf("wexecvp %s:", tool);
    282       _exit(1);
    283   }
    284   close(fds[0]);
    285   return fds[1];
    286 }
    287 
    288 static int
    289 decomp(int fd, const char *tool, const char *flags)
    290 {
    291   int fds[2];
    292 
    293   if (pipe(fds) < 0)
    294     eprintf("pipe:");
    295 
    296   switch (fork()) {
    297     case -1:
    298       eprintf("fork:");
    299       /* fallthrough */
    300     case 0:
    301       dup2(fd, 0);
    302       dup2(fds[1], 1);
    303       close(fds[0]);
    304       close(fds[1]);
    305 
    306       {
    307         char *tar_argv[3];
    308         tar_argv[0] = (char *)tool;
    309         tar_argv[1] = (char *)flags;
    310         tar_argv[2] = NULL;
    311         wexecvp_self(tool, tar_argv);
    312       }
    313       weprintf("wexecvp %s:", tool);
    314       _exit(1);
    315   }
    316   close(fds[1]);
    317   return fds[0];
    318 }
    319 
    320 /* fills buf unless the input ends first: a pipe from a decompressor hands
    321  * back whatever it has, and a short block would put every later header
    322  * at the wrong offset */
    323 static ssize_t
    324 eread(int fd, void *buf, size_t n)
    325 {
    326   size_t  got = 0;
    327   ssize_t r;
    328 
    329   while (got < n) {
    330     r = read(fd, (char *)buf + got, n - got);
    331     if (r < 0) {
    332       if (errno == EINTR)
    333         continue;
    334       eprintf("read:");
    335     }
    336     if (r == 0)
    337       break;
    338     got += (size_t)r;
    339   }
    340   return (ssize_t)got;
    341 }
    342 
    343 static ssize_t
    344 ewrite(int fd, const void *buf, size_t n)
    345 {
    346   ssize_t r;
    347 
    348   if ((r = write(fd, buf, n)) < 0 || (size_t)r != n)
    349     eprintf("write:");
    350   return r;
    351 }
    352 
    353 static unsigned
    354 chksum(struct header *h)
    355 {
    356   unsigned sum, i;
    357 
    358   memset(h->chksum, ' ', sizeof(h->chksum));
    359   for (i = 0, sum = 0, assert(BLKSIZ == 512); i < BLKSIZ; i++)
    360     sum += *((unsigned char *)h + i);
    361   return sum;
    362 }
    363 
    364 #if FEATURE_TAR_CREATE
    365 static void
    366 putoctal(char *dst, unsigned num, int size)
    367 {
    368   if (snprintf(dst, size, "%.*o", size - 1, num) >= size)
    369     eprintf("putoctal: input number '%o' too large\n", num);
    370 }
    371 
    372 static int
    373 archive(const char *path)
    374 {
    375   static const struct header blank = {
    376       .name     = "././@LongLink",
    377       .mode     = "0000600",
    378       .uid      = "0000000",
    379       .gid      = "0000000",
    380       .size     = "00000000000",
    381       .mtime    = "00000000000",
    382       .chksum   = "       ",
    383       .type     = AREG,
    384       .linkname = "",
    385       .magic    = "ustar",
    386       .version  = {'0', '0'}
    387   };
    388   char           b[BLKSIZ + BLKSIZ], *p;
    389   struct header *h = (struct header *)b;
    390   struct group  *gr;
    391   struct passwd *pw;
    392   struct stat    st;
    393   ssize_t        l, n, r;
    394   int            fd = -1;
    395 
    396   if (lstat(path, &st) < 0) {
    397     weprintf("lstat %s:", path);
    398     return 0;
    399   } else if (st.st_ino == tarinode && st.st_dev == tardev) {
    400     weprintf("ignoring %s\n", path);
    401     return 0;
    402   }
    403   pw = getpwuid(st.st_uid);
    404   gr = getgrgid(st.st_gid);
    405 
    406   *h = blank;
    407   n  = strlcpy(h->name, path, sizeof(h->name));
    408   if ((size_t)n >= sizeof(h->name)) {
    409     *++h    = blank;
    410     h->type = 'L';
    411     putoctal(h->size, n, sizeof(h->size));
    412     putoctal(h->chksum, chksum(h), sizeof(h->chksum));
    413     ewrite(tarfd, (char *)h, BLKSIZ);
    414 
    415     for (p = (char *)path; n > 0; n -= BLKSIZ, p += BLKSIZ) {
    416       if ((size_t)n < BLKSIZ) {
    417         p = memcpy(h--, p, n);
    418         memset(p + n, 0, BLKSIZ - (size_t)n);
    419       }
    420       ewrite(tarfd, p, BLKSIZ);
    421     }
    422   }
    423 
    424   putoctal(h->mode, (unsigned)st.st_mode & 07777, sizeof(h->mode));
    425   putoctal(h->uid, (unsigned)st.st_uid, sizeof(h->uid));
    426   putoctal(h->gid, (unsigned)st.st_gid, sizeof(h->gid));
    427   putoctal(h->mtime, (unsigned)st.st_mtime, sizeof(h->mtime));
    428   estrlcpy(h->uname, pw ? pw->pw_name : "", sizeof(h->uname));
    429   estrlcpy(h->gname, gr ? gr->gr_name : "", sizeof(h->gname));
    430 
    431   if (S_ISREG(st.st_mode)) {
    432     h->type = REG;
    433     putoctal(h->size, st.st_size, sizeof(h->size));
    434     fd = open(path, O_RDONLY);
    435     if (fd < 0)
    436       eprintf("open %s:", path);
    437   } else if (S_ISDIR(st.st_mode)) {
    438     h->type = DIRECTORY;
    439   } else if (S_ISLNK(st.st_mode)) {
    440     h->type = SYMLINK;
    441     if ((r = readlink(path, h->linkname, sizeof(h->linkname) - 1)) < 0)
    442       eprintf("readlink %s:", path);
    443     h->linkname[r] = '\0';
    444   } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
    445     h->type = S_ISCHR(st.st_mode) ? CHARDEV : BLOCKDEV;
    446     putoctal(h->major, (unsigned)fs_devmajor(st.st_dev), sizeof(h->major));
    447     putoctal(h->minor, (unsigned)fs_devminor(st.st_dev), sizeof(h->minor));
    448   } else if (S_ISFIFO(st.st_mode)) {
    449     h->type = FIFO;
    450   }
    451 
    452   putoctal(h->chksum, chksum(h), sizeof(h->chksum));
    453   ewrite(tarfd, b, BLKSIZ);
    454 
    455   if (fd != -1) {
    456     while ((l = eread(fd, b, BLKSIZ)) > 0) {
    457       if ((size_t)l < BLKSIZ)
    458         memset(b + l, 0, BLKSIZ - (size_t)l);
    459       ewrite(tarfd, b, BLKSIZ);
    460     }
    461     close(fd);
    462   }
    463 
    464   return 0;
    465 }
    466 #endif
    467 
    468 static void
    469 skipblk(ssize_t l)
    470 {
    471   char b[BLKSIZ];
    472 
    473   for (; l > 0; l -= BLKSIZ)
    474     if (!eread(tarfd, b, BLKSIZ))
    475       break;
    476 }
    477 
    478 static int
    479 unarchive(char *fname, ssize_t l, char b[BLKSIZ])
    480 {
    481   struct header  *h = (struct header *)b;
    482   struct timespec times[2];
    483   struct stat     st;
    484   char            lname[101], *tmp, *p;
    485   long            mode, major, minor, type, mtime, uid, gid;
    486   int             fd = -1, lnk = h->type == SYMLINK;
    487 
    488   if (kflag_keep && !Oflag_stdout) {
    489     if (lstat(fname, &st) == 0) {
    490       skipblk(l);
    491       return 0;
    492     }
    493   }
    494 
    495   if (!mflag && ((mtime = strtol(h->mtime, &p, 8)) < 0 || *p != '\0'))
    496     eprintf("strtol %s: invalid mtime\n", h->mtime);
    497 
    498   if (Oflag_stdout) {
    499     if (h->type == REG || h->type == AREG || h->type == RESERVED) {
    500       fd = 1;
    501     } else {
    502       return 0;
    503     }
    504   } else {
    505     if (h->type != DIRECTORY && strcmp(fname, ".") && strcmp(fname, "./") && remove(fname) < 0)
    506       if (errno != ENOENT)
    507         weprintf("remove %s:", fname);
    508 
    509     tmp = estrdup(fname);
    510     mkdirp(dirname(tmp), 0777, 0777);
    511     free(tmp);
    512 
    513     switch (h->type) {
    514       case REG:
    515       case AREG:
    516       case RESERVED:
    517         if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0')
    518           eprintf("strtol %s: invalid mode\n", h->mode);
    519 #if FEATURE_TAR_NOFOLLOW
    520         fd = open(fname, O_WRONLY | O_TRUNC | O_CREAT | O_NOFOLLOW, 0600);
    521 #else
    522         fd = open(fname, O_WRONLY | O_TRUNC | O_CREAT, 0600);
    523 #endif
    524         if (fd < 0)
    525           eprintf("open %s:", fname);
    526         break;
    527       case HARDLINK:
    528       case SYMLINK:
    529         snprintf(lname, sizeof(lname), "%.*s", (int)sizeof(h->linkname), h->linkname);
    530         if ((lnk ? symlink : link)(lname, fname) < 0)
    531           eprintf("%s %s -> %s:", lnk ? "symlink" : "link", fname, lname);
    532         lnk++;
    533         break;
    534       case DIRECTORY:
    535         if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0')
    536           eprintf("strtol %s: invalid mode\n", h->mode);
    537         if (mkdir(fname, (mode_t)mode) < 0 && errno != EEXIST)
    538           eprintf("mkdir %s:", fname);
    539         pushdirtime(fname, mtime);
    540         break;
    541       case CHARDEV:
    542       case BLOCKDEV:
    543 #if FEATURE_MKNOD
    544         if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0')
    545           eprintf("strtol %s: invalid mode\n", h->mode);
    546         if ((major = strtol(h->major, &p, 8)) < 0 || *p != '\0')
    547           eprintf("strtol %s: invalid major device\n", h->major);
    548         if ((minor = strtol(h->minor, &p, 8)) < 0 || *p != '\0')
    549           eprintf("strtol %s: invalid minor device\n", h->minor);
    550         type = (h->type == CHARDEV) ? S_IFCHR : S_IFBLK;
    551         if (mknod(fname, type | mode, fs_makedev(major, minor)) < 0)
    552           eprintf("mknod %s:", fname);
    553 #else
    554         eprintf("tar: device extraction not supported\n");
    555 #endif
    556         break;
    557       case FIFO:
    558 #if FEATURE_MKNOD
    559         if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0')
    560           eprintf("strtol %s: invalid mode\n", h->mode);
    561         if (mknod(fname, S_IFIFO | mode, 0) < 0)
    562           eprintf("mknod %s:", fname);
    563 #else
    564         eprintf("tar: fifo extraction not supported\n");
    565 #endif
    566         break;
    567       default:
    568         eprintf("unsupported tar-filetype %c\n", h->type);
    569     }
    570   }
    571 
    572   if (!Oflag_stdout) {
    573     if ((uid = strtol(h->uid, &p, 8)) < 0 || *p != '\0')
    574       eprintf("strtol %s: invalid uid\n", h->uid);
    575     if ((gid = strtol(h->gid, &p, 8)) < 0 || *p != '\0')
    576       eprintf("strtol %s: invalid gid\n", h->gid);
    577   }
    578 
    579   if (fd != -1) {
    580     for (; l > 0; l -= BLKSIZ)
    581       if (eread(tarfd, b, BLKSIZ) > 0)
    582         ewrite(fd, b, MIN(l, (ssize_t)BLKSIZ));
    583     if (fd != 1)
    584       close(fd);
    585   }
    586 
    587   if (Oflag_stdout)
    588     return 0;
    589 
    590   if (lnk == 1)
    591     return 0;
    592 
    593   times[0].tv_sec = times[1].tv_sec = mtime;
    594   times[0].tv_nsec = times[1].tv_nsec = 0;
    595   if (!mflag && utimensat(AT_FDCWD, fname, times, AT_SYMLINK_NOFOLLOW) < 0)
    596     weprintf("utimensat %s:", fname);
    597   if (lnk) {
    598     if (!no_same_owner && !getuid() && lchown(fname, uid, gid))
    599       weprintf("lchown %s:", fname);
    600   } else {
    601     if (!no_same_owner && !getuid() && chown(fname, uid, gid))
    602       weprintf("chown %s:", fname);
    603     if (chmod(fname, mode) < 0)
    604       eprintf("fchmod %s:", fname);
    605   }
    606 
    607   return 0;
    608 }
    609 
    610 static int
    611 print(char *fname, ssize_t l, char b[BLKSIZ])
    612 {
    613   (void)b;
    614   safe_puts(fname);
    615   skipblk(l);
    616   return 0;
    617 }
    618 
    619 #if FEATURE_TAR_CREATE
    620 static void
    621 c(int dirfd, const char *name, struct stat *st, void *data, struct recursor *r)
    622 {
    623   (void)data;
    624 #if FEATURE_TAR_EXCLUDE
    625   if (is_excluded(r->path))
    626     return;
    627 #endif
    628   archive(r->path);
    629   if (vflag)
    630     safe_puts(r->path);
    631 
    632   if (S_ISDIR(st->st_mode))
    633     recurse(dirfd, name, NULL, r);
    634 }
    635 #endif
    636 
    637 static void
    638 sanitize(struct header *h)
    639 {
    640   size_t i, j, l;
    641   struct {
    642     char  *f;
    643     size_t l;
    644   } fields[] = {
    645       {h->mode, sizeof(h->mode)},
    646       {h->uid, sizeof(h->uid)},
    647       {h->gid, sizeof(h->gid)},
    648       {h->size, sizeof(h->size)},
    649       {h->mtime, sizeof(h->mtime)},
    650       {h->chksum, sizeof(h->chksum)},
    651       {h->major, sizeof(h->major)},
    652       {h->minor, sizeof(h->minor)}
    653   };
    654 
    655   /* numeric fields can be terminated with spaces instead of
    656    * nuls as per the ustar specification. patch all of them to
    657    * use nuls so we can perform string operations on them */
    658   for (i = 0; i < LEN(fields); i++) {
    659     j = 0, l = fields[i].l - 1;
    660     for (; j < l && fields[i].f[j] == ' '; j++)
    661       ;
    662     for (; j <= l; j++)
    663       if (fields[i].f[j] == ' ')
    664         fields[i].f[j] = '\0';
    665     if (fields[i].f[l])
    666       eprintf(
    667           "numeric field #%d (%.*s) is not null or space "
    668           "terminated\n",
    669           i,
    670           l + 1,
    671           fields[i].f
    672       );
    673   }
    674 }
    675 
    676 static void
    677 chktar(struct header *h)
    678 {
    679   const char *reason;
    680   char        tmp[sizeof h->chksum], *err;
    681   long        sum, i;
    682 
    683   if (h->prefix[0] == '\0' && h->name[0] == '\0') {
    684     reason = "empty filename";
    685     goto bad;
    686   }
    687   if (h->magic[0] && strncmp("ustar", h->magic, 5)) {
    688     reason = "not ustar format";
    689     goto bad;
    690   }
    691   memcpy(tmp, h->chksum, sizeof(tmp));
    692   for (i = sizeof(tmp) - 1; i > 0 && tmp[i] == ' '; i--) {
    693     tmp[i] = '\0';
    694   }
    695   sum = strtol(tmp, &err, 8);
    696   if (sum < 0 || sum >= (long)(BLKSIZ * 256) || *err != '\0') {
    697     reason = "invalid checksum";
    698     goto bad;
    699   }
    700   if (sum != chksum(h)) {
    701     reason = "incorrect checksum";
    702     goto bad;
    703   }
    704   memcpy(h->chksum, tmp, sizeof(tmp));
    705   return;
    706 bad:
    707   eprintf("malformed tar archive: %s\n", reason);
    708 }
    709 
    710 static void
    711 xt(int argc, char *argv[], int mode)
    712 {
    713   long size;
    714   char b[BLKSIZ], fname[PATH_MAX + 1], *p, *q = NULL, *stripped;
    715   int  i, m, n, match;
    716   int (*fn)(char *, ssize_t, char[BLKSIZ]) = (mode == 'x') ? unarchive : print;
    717   struct timespec times[2];
    718   struct header  *h = (struct header *)b;
    719   struct dirtime *dirtime;
    720 #if FEATURE_TAR_FILES_FROM
    721   size_t idx;
    722 #endif
    723 
    724   while (eread(tarfd, b, BLKSIZ) > 0 && (h->name[0] || h->prefix[0])) {
    725     chktar(h);
    726     sanitize(h);
    727 
    728     if ((size = strtol(h->size, &p, 8)) < 0 || *p != '\0')
    729       eprintf("strtol %s: invalid size\n", h->size);
    730 
    731     /* long file path is read directly into fname */
    732     if (h->type == 'L' || h->type == 'x' || h->type == 'g') {
    733       /* read header only up to size of fname buffer */
    734       for (q = fname; q < fname + size; q += BLKSIZ) {
    735         if (q + BLKSIZ >= fname + sizeof fname)
    736           eprintf("name exceeds buffer: %.*s\n", q - fname, fname);
    737         eread(tarfd, q, BLKSIZ);
    738       }
    739 
    740       /* convert pax x header with 'path=' field into l header
    741        */
    742       if (h->type == 'x')
    743         for (q = fname; q < fname + size - 16; q += n) {
    744           if ((n = strtol(q, &p, 10)) < 0 || *p != ' ')
    745             eprintf(
    746                 "strtol %.*s: invalid "
    747                 "number\n",
    748                 p + 1 - q,
    749                 q
    750             );
    751           if (n && strncmp(p + 1, "path=", 5) == 0) {
    752             memmove(fname, p + 6, size = q + n - p - 6 - 1);
    753             h->type = 'L';
    754             break;
    755           }
    756         }
    757       fname[size] = '\0';
    758 
    759       /* non l-like header (eg. pax 'g') is skipped by setting
    760        * q=null */
    761       if (h->type != 'L')
    762         q = NULL;
    763       continue;
    764     }
    765 
    766     /* ustar path is copied into fname if no l header (ie: q is
    767      * NULL) */
    768     if (!q) {
    769       m = sizeof h->prefix, n = sizeof h->name;
    770       p = h->prefix[0] ? "/" : "";
    771       snprintf(fname, sizeof fname, "%.*s%s%.*s", m, h->prefix, p, n, h->name);
    772     }
    773     q = NULL;
    774 
    775     /* if argc > 0 or files_from_cnt > 0 then only extract the
    776      * matching files/dirs */
    777     if (argc || files_from_cnt) {
    778       match = 0;
    779       for (i = 0; i < argc; i++) {
    780         if (strncmp(argv[i], fname, n = strlen(argv[i])) == 0) {
    781           if (strchr("/", fname[n]) || argv[i][n - 1] == '/') {
    782             match = 1;
    783             break;
    784           }
    785         }
    786       }
    787 #if FEATURE_TAR_FILES_FROM
    788       if (!match) {
    789         for (idx = 0; idx < files_from_cnt; idx++) {
    790           if (strncmp(files_from[idx], fname, n = strlen(files_from[idx])) == 0) {
    791             if (strchr("/", fname[n]) || files_from[idx][n - 1] == '/') {
    792               match = 1;
    793               break;
    794             }
    795           }
    796         }
    797       }
    798 #endif
    799       if (!match) {
    800         skipblk(size);
    801         continue;
    802       }
    803     }
    804 
    805     stripped = fname;
    806 #if FEATURE_TAR_STRIP_COMPONENTS
    807     if (mode == 'x' && strip_components_count > 0) {
    808       stripped = strip_components(fname, strip_components_count);
    809       if (!stripped || *stripped == '\0') {
    810         skipblk(size);
    811         continue;
    812       }
    813     }
    814 #endif
    815 
    816     fn(stripped, size, b);
    817     if (vflag && mode != 't')
    818       safe_puts(fname);
    819   }
    820 
    821   if (mode == 'x' && !mflag) {
    822     while ((dirtime = popdirtime())) {
    823       times[0].tv_sec = times[1].tv_sec = dirtime->mtime;
    824       times[0].tv_nsec = times[1].tv_nsec = 0;
    825       if (utimensat(AT_FDCWD, dirtime->name, times, 0) < 0)
    826         eprintf("utimensat %s:", fname);
    827       free(dirtime->name);
    828     }
    829     free(dirtimes);
    830     dirtimes = NULL;
    831   }
    832 }
    833 
    834 char **args;
    835 int    argn;
    836 
    837 static void
    838 usage(void)
    839 {
    840 #if FEATURE_TAR_CREATE
    841   eprintf(
    842       "usage: %s [x | t | -x | -t] [-C dir] [-J | -Z | -a | -j | -z] "
    843       "[-m] [-p] "
    844       "[-f file] [file ...]\n"
    845       "       %s [c | -c] [-C dir] [-J | -Z | -a | -j | -z] [-h] "
    846       "path ... "
    847       "[-f file]\n",
    848       argv0,
    849       argv0
    850   );
    851 #else
    852   eprintf(
    853       "usage: %s [x | t | -x | -t] [-C dir] [-J | -Z | -a | -j | -z] "
    854       "[-m] [-p] "
    855       "[-f file] [file ...]\n",
    856       argv0
    857   );
    858 #endif
    859 }
    860 
    861 // ?man tar: tape archiver
    862 // ?man arguments: [x | t | -x | -t] [file ...]
    863 // ?man tar [c | -c] [-C dir] [-J | -Z | -a | -j | -z] [-h] [-T file] [-X file] path ... [-f file]
    864 // ?man manipulate tape archive files
    865 int
    866 main(int argc, char *argv[])
    867 {
    868 #if FEATURE_TAR_CREATE
    869   struct recursor r = {.fn = c, .follow = 'P', .flags = DIRFIRST};
    870 #endif
    871   struct stat st;
    872   char       *file = NULL, *dir = ".", mode = '\0';
    873   int         fd;
    874   size_t      i;
    875 
    876   argv0 = argv[0];
    877 #if FEATURE_TAR_CREATE
    878   if (argc > 1 && strchr("cxt", mode = *argv[1]))
    879 #else
    880   if (argc > 1 && strchr("xt", mode = *argv[1]))
    881 #endif
    882     *(argv[1] + 1) ? *argv[1] = '-' : (*++argv = argv0, --argc);
    883 
    884   ARGBEGIN
    885   {
    886     // ?man -x: extract files from an archive
    887     case 'x':
    888 #if FEATURE_TAR_CREATE
    889     // ?man -c: create a new archive
    890     case 'c':
    891 #endif
    892     // ?man -t: list the contents of an archive
    893     case 't':
    894       mode = ARGC();
    895       break;
    896     // ?man -C:dir: specify option flag
    897     case 'C':
    898       dir = EARGF(usage());
    899       break;
    900     // ?man -f:file: specify archive file
    901     case 'f':
    902       file = EARGF(usage());
    903       break;
    904     // ?man -m: specify mode or limit
    905     case 'm':
    906       mflag = 1;
    907       break;
    908     // ?man -J: specify option flag
    909     case 'J':
    910     // ?man -Z: specify option flag
    911     case 'Z':
    912     // ?man -a: print or show all entries
    913     case 'a':
    914     // ?man -j: specify option flag
    915     case 'j':
    916     // ?man -z: specify option flag
    917     case 'z':
    918       filtermode = ARGC();
    919       filtertool = filtertools[filtermode];
    920       break;
    921     // ?man -h: suppress headers or print help
    922     case 'h':
    923 #if FEATURE_TAR_CREATE
    924       r.follow = 'L';
    925 #endif
    926       break;
    927     // ?man -v: verbosely list files processed
    928     case 'v':
    929       vflag = 1;
    930       break;
    931     // ?man -p: preserve file attributes
    932     case 'p':
    933       break; /* do nothing as already default behaviour */
    934 #if FEATURE_TAR_TO_STDOUT
    935     // ?man -O: extract files to stdout
    936     case 'O':
    937       Oflag_stdout = 1;
    938       break;
    939 #endif
    940 #if FEATURE_TAR_KEEP_OLD
    941     // ?man -k: keep existing files, do not overwrite
    942     case 'k':
    943       kflag_keep = 1;
    944       break;
    945 #endif
    946 #if FEATURE_TAR_FILES_FROM
    947     // ?man -T:file: -T file: read filenames from file
    948     case 'T':
    949       load_files_from_file(EARGF(usage()));
    950       break;
    951 #endif
    952 #if FEATURE_TAR_EXCLUDE_FROM
    953     // ?man -X:file: -X file: exclude patterns in file
    954     case 'X':
    955       load_excludes_from_file(EARGF(usage()));
    956       break;
    957 #endif
    958 #if FEATURE_TAR_STRIP_COMPONENTS
    959     // ?man -s:num: -strip-components num: strip num components
    960     case 's':
    961       if (strcmp(argv[0], "strip-components") == 0) {
    962         argv[0]                = "s";
    963         strip_components_count = estrtonum(EARGF(usage()), 0, INT_MAX);
    964         brk_                   = 1;
    965       } else if (strncmp(argv[0], "strip-components=", 17) == 0) {
    966         strip_components_count = estrtonum(argv[0] + 17, 0, INT_MAX);
    967         brk_                   = 1;
    968       } else {
    969         usage();
    970       }
    971       break;
    972 #endif
    973     // ?man --:num: specify - option
    974     case '-':
    975       if (strcmp(argv[0], "-no-same-owner") == 0) {
    976         no_same_owner = 1;
    977         brk_          = 1;
    978         break;
    979       }
    980 #if FEATURE_TAR_EXCLUDE
    981       if (strncmp(argv[0], "-exclude=", 9) == 0) {
    982         add_exclude(argv[0] + 9);
    983         brk_ = 1;
    984         break;
    985       } else if (strcmp(argv[0], "-exclude") == 0) {
    986         argv[0] = "-";
    987         add_exclude(EARGF(usage()));
    988         brk_ = 1;
    989         break;
    990       }
    991 #endif
    992 #if FEATURE_TAR_EXCLUDE_FROM
    993       if (strncmp(argv[0], "-exclude-from=", 14) == 0) {
    994         load_excludes_from_file(argv[0] + 14);
    995         brk_ = 1;
    996         break;
    997       } else if (strcmp(argv[0], "-exclude-from") == 0) {
    998         argv[0] = "-";
    999         load_excludes_from_file(EARGF(usage()));
   1000         brk_ = 1;
   1001         break;
   1002       }
   1003 #endif
   1004 #if FEATURE_TAR_TO_STDOUT
   1005       if (strcmp(argv[0], "-to-stdout") == 0) {
   1006         Oflag_stdout = 1;
   1007         brk_         = 1;
   1008         break;
   1009       }
   1010 #endif
   1011 #if FEATURE_TAR_KEEP_OLD
   1012       if (strcmp(argv[0], "-keep-old-files") == 0) {
   1013         kflag_keep = 1;
   1014         brk_       = 1;
   1015         break;
   1016       }
   1017 #endif
   1018 #if FEATURE_TAR_STRIP_COMPONENTS
   1019       if (strncmp(argv[0], "-strip-components=", 18) == 0) {
   1020         strip_components_count = estrtonum(argv[0] + 18, 0, INT_MAX);
   1021         brk_                   = 1;
   1022         break;
   1023       } else if (strcmp(argv[0], "-strip-components") == 0) {
   1024         argv[0]                = "-";
   1025         strip_components_count = estrtonum(EARGF(usage()), 0, INT_MAX);
   1026         brk_                   = 1;
   1027         break;
   1028       }
   1029 #endif
   1030 #if FEATURE_TAR_FILES_FROM
   1031       if (strncmp(argv[0], "-files-from=", 12) == 0) {
   1032         load_files_from_file(argv[0] + 12);
   1033         brk_ = 1;
   1034         break;
   1035       } else if (strcmp(argv[0], "-files-from") == 0) {
   1036         argv[0] = "-";
   1037         load_files_from_file(EARGF(usage()));
   1038         brk_ = 1;
   1039         break;
   1040       }
   1041 #endif
   1042       usage();
   1043       break;
   1044     default:
   1045       usage();
   1046   }
   1047   ARGEND
   1048 
   1049   switch (mode) {
   1050 #if FEATURE_TAR_CREATE
   1051     case 'c':
   1052       if (!argc && !files_from_cnt)
   1053         usage();
   1054       tarfd = 1;
   1055       if (file && *file != '-') {
   1056         tarfd = open(file, O_WRONLY | O_TRUNC | O_CREAT, 0644);
   1057         if (tarfd < 0)
   1058           eprintf("open %s:", file);
   1059         if (lstat(file, &st) < 0)
   1060           eprintf("lstat %s:", file);
   1061         tarinode = st.st_ino;
   1062         tardev   = st.st_dev;
   1063       }
   1064 
   1065       if (filtertool)
   1066         tarfd = comp(tarfd, filtertool, "-cf");
   1067 
   1068       if (chdir(dir) < 0)
   1069         eprintf("chdir %s:", dir);
   1070       for (; *argv; argc--, argv++)
   1071         recurse(AT_FDCWD, *argv, NULL, &r);
   1072 #if FEATURE_TAR_FILES_FROM
   1073       for (i = 0; i < files_from_cnt; i++)
   1074         recurse(AT_FDCWD, files_from[i], NULL, &r);
   1075 #endif
   1076       break;
   1077 #endif
   1078     case 't':
   1079     case 'x':
   1080       tarfd = 0;
   1081       if (file && *file != '-') {
   1082         tarfd = open(file, O_RDONLY);
   1083         if (tarfd < 0)
   1084           eprintf("open %s:", file);
   1085       }
   1086 
   1087       if (filtertool) {
   1088         fd    = tarfd;
   1089         tarfd = decomp(tarfd, filtertool, "-cdf");
   1090         close(fd);
   1091       }
   1092 
   1093       if (chdir(dir) < 0)
   1094         eprintf("chdir %s:", dir);
   1095       xt(argc, argv, mode);
   1096       break;
   1097     default:
   1098       usage();
   1099   }
   1100 
   1101 #if FEATURE_TAR_EXCLUDE
   1102   if (excludes) {
   1103     for (i = 0; i < excludes_cnt; i++)
   1104       free(excludes[i]);
   1105     free(excludes);
   1106   }
   1107 #endif
   1108 #if FEATURE_TAR_FILES_FROM
   1109   if (files_from) {
   1110     for (i = 0; i < files_from_cnt; i++)
   1111       free(files_from[i]);
   1112     free(files_from);
   1113   }
   1114 #endif
   1115   return recurse_status;
   1116 }