Home | History | Annotate | Download | only in posix
      1 /* cpio.c - a basic cpio
      2  *
      3  * Written 2013 AD by Isaac Dunham; this code is placed under the
      4  * same license as toybox or as CC0, at your option.
      5  *
      6  * Portions Copyright 2015 by Frontier Silicon Ltd.
      7  *
      8  * http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/cpio.html
      9  * and http://pubs.opengroup.org/onlinepubs/7908799/xcu/cpio.html
     10  *
     11  * Yes, that's SUSv2, the newer standards removed it around the time RPM
     12  * and initramfs started heavily using this archive format.
     13  *
     14  * Modern cpio expanded header to 110 bytes (first field 6 bytes, rest are 8).
     15  * In order: magic ino mode uid gid nlink mtime filesize devmajor devminor
     16  * rdevmajor rdevminor namesize check
     17  * This is the equiavlent of mode -H newc when using GNU CPIO.
     18 
     19 USE_CPIO(NEWTOY(cpio, "(no-preserve-owner)(trailer)mduH:p:|i|t|F:v(verbose)o|[!pio][!pot][!pF]", TOYFLAG_BIN))
     20 
     21 config CPIO
     22   bool "cpio"
     23   default y
     24   help
     25     usage: cpio -{o|t|i|p DEST} [-v] [--verbose] [-F FILE] [--no-preserve-owner]
     26            [ignored: -mdu -H newc]
     27 
     28     copy files into and out of a "newc" format cpio archive
     29 
     30     -F FILE	use archive FILE instead of stdin/stdout
     31     -p DEST	copy-pass mode, copy stdin file list to directory DEST
     32     -i	extract from archive into file system (stdin=archive)
     33     -o	create archive (stdin=list of files, stdout=archive)
     34     -t	test files (list only, stdin=archive, stdout=list of files)
     35     -v	verbose (list files during create/extract)
     36     --no-preserve-owner (don't set ownership during extract)
     37     --trailer Add legacy trailer (prevents concatenation).
     38 */
     39 
     40 #define FOR_cpio
     41 #include "toys.h"
     42 
     43 GLOBALS(
     44   char *archive;
     45   char *pass;
     46   char *fmt;
     47 )
     48 
     49 // Read strings, tail padded to 4 byte alignment. Argument "align" is amount
     50 // by which start of string isn't aligned (usually 0, but header is 110 bytes
     51 // which is 2 bytes off because the first field wasn't expanded from 6 to 8).
     52 static char *strpad(int fd, unsigned len, unsigned align)
     53 {
     54   char *str;
     55 
     56   align = (align + len) & 3;
     57   if (align) len += (4-align);
     58   xreadall(fd, str = xmalloc(len+1), len);
     59   str[len]=0; // redundant, in case archive is bad
     60 
     61   return str;
     62 }
     63 
     64 //convert hex to uint; mostly to allow using bits of non-terminated strings
     65 static unsigned x8u(char *hex)
     66 {
     67   unsigned val, inpos = 8, outpos;
     68   char pattern[6];
     69 
     70   while (*hex == '0') {
     71     hex++;
     72     if (!--inpos) return 0;
     73   }
     74   // Because scanf gratuitously treats %*X differently than printf does.
     75   sprintf(pattern, "%%%dX%%n", inpos);
     76   sscanf(hex, pattern, &val, &outpos);
     77   if (inpos != outpos) error_exit("bad header");
     78 
     79   return val;
     80 }
     81 
     82 void cpio_main(void)
     83 {
     84   // Subtle bit: FLAG_o is 1 so we can just use it to select stdin/stdout.
     85   int pipe, afd = toys.optflags & FLAG_o;
     86   pid_t pid = 0;
     87 
     88   // In passthrough mode, parent stays in original dir and generates archive
     89   // to pipe, child does chdir to new dir and reads archive from stdin (pipe).
     90   if (TT.pass) {
     91     if (toys.stacktop) {
     92       // xpopen() doesn't return from child due to vfork(), instead restarts
     93       // with !toys.stacktop
     94       pid = xpopen(0, &pipe, 0);
     95       afd = pipe;
     96     } else {
     97       // child
     98       toys.optflags |= FLAG_i;
     99       xchdir(TT.pass);
    100     }
    101   }
    102 
    103   if (TT.archive) {
    104     int perm = (toys.optflags & FLAG_o) ? O_CREAT|O_WRONLY|O_TRUNC : O_RDONLY;
    105 
    106     afd = xcreate(TT.archive, perm, 0644);
    107   }
    108 
    109   // read cpio archive
    110 
    111   if (toys.optflags & (FLAG_i|FLAG_t)) for (;;) {
    112     char *name, *tofree, *data;
    113     unsigned size, mode, uid, gid, timestamp;
    114     int test = toys.optflags & FLAG_t, err = 0;
    115 
    116     // Read header and name.
    117     if (!(size =readall(afd, toybuf, 110))) break;
    118     if (size != 110 || memcmp(toybuf, "070701", 6)) error_exit("bad header");
    119     tofree = name = strpad(afd, x8u(toybuf+94), 110);
    120     if (!strcmp("TRAILER!!!", name)) {
    121       if (CFG_TOYBOX_FREE) free(tofree);
    122       break;
    123     }
    124 
    125     // If you want to extract absolute paths, "cd /" and run cpio.
    126     while (*name == '/') name++;
    127     // TODO: remove .. entries
    128 
    129     size = x8u(toybuf+54);
    130     mode = x8u(toybuf+14);
    131     uid = x8u(toybuf+22);
    132     gid = x8u(toybuf+30);
    133     timestamp = x8u(toybuf+46); // unsigned 32 bit, so year 2100 problem
    134 
    135     if (toys.optflags & (FLAG_t|FLAG_v)) puts(name);
    136 
    137     if (!test && strrchr(name, '/') && mkpathat(AT_FDCWD, name, 0, 2)) {
    138       perror_msg("mkpath '%s'", name);
    139       test++;
    140     }
    141 
    142     // Consume entire record even if it couldn't create file, so we're
    143     // properly aligned with next file.
    144 
    145     if (S_ISDIR(mode)) {
    146       if (!test) err = mkdir(name, mode);
    147     } else if (S_ISLNK(mode)) {
    148       data = strpad(afd, size, 0);
    149       if (!test) err = symlink(data, name);
    150       free(data);
    151       // Can't get a filehandle to a symlink, so do special chown
    152       if (!err && !geteuid() && !(toys.optflags & FLAG_no_preserve_owner))
    153         err = lchown(name, uid, gid);
    154     } else if (S_ISREG(mode)) {
    155       int fd = test ? 0 : open(name, O_CREAT|O_WRONLY|O_TRUNC|O_NOFOLLOW, mode);
    156 
    157       // If write fails, we still need to read/discard data to continue with
    158       // archive. Since doing so overwrites errno, report error now
    159       if (fd < 0) {
    160         perror_msg("create %s", name);
    161         test++;
    162       }
    163 
    164       data = toybuf;
    165       while (size) {
    166         if (size < sizeof(toybuf)) data = strpad(afd, size, 0);
    167         else xreadall(afd, toybuf, sizeof(toybuf));
    168         if (!test) xwrite(fd, data, data == toybuf ? sizeof(toybuf) : size);
    169         if (data != toybuf) {
    170           free(data);
    171           break;
    172         }
    173         size -= sizeof(toybuf);
    174       }
    175 
    176       if (!test) {
    177         // set owner, restore dropped suid bit
    178         if (!geteuid() && !(toys.optflags & FLAG_no_preserve_owner)) {
    179           err = fchown(fd, uid, gid);
    180           if (!err) err = fchmod(fd, mode);
    181         }
    182         close(fd);
    183       }
    184     } else if (!test)
    185       err = mknod(name, mode, dev_makedev(x8u(toybuf+78), x8u(toybuf+86)));
    186 
    187     // Set ownership and timestamp.
    188     if (!test && !err) {
    189       // Creading dir/dev doesn't give us a filehandle, we have to refer to it
    190       // by name to chown/utime, but how do we know it's the same item?
    191       // Check that we at least have the right type of entity open, and do
    192       // NOT restore dropped suid bit in this case.
    193       if (!S_ISREG(mode) && !S_ISLNK(mode) && !geteuid()
    194           && !(toys.optflags & FLAG_no_preserve_owner))
    195       {
    196         int fd = open(name, O_RDONLY|O_NOFOLLOW);
    197         struct stat st;
    198 
    199         if (fd != -1 && !fstat(fd, &st) && (st.st_mode&S_IFMT) == (mode&S_IFMT))
    200           err = fchown(fd, uid, gid);
    201         else err = 1;
    202 
    203         close(fd);
    204       }
    205 
    206       // set timestamp
    207       if (!err) {
    208         struct timespec times[2];
    209 
    210         memset(times, 0, sizeof(struct timespec)*2);
    211         times[0].tv_sec = times[1].tv_sec = timestamp;
    212         err = utimensat(AT_FDCWD, name, times, AT_SYMLINK_NOFOLLOW);
    213       }
    214     }
    215 
    216     if (err) perror_msg_raw(name);
    217     free(tofree);
    218 
    219   // Output cpio archive
    220 
    221   } else {
    222     char *name = 0;
    223     size_t size = 0;
    224 
    225     for (;;) {
    226       struct stat st;
    227       unsigned nlen, error = 0, zero = 0;
    228       int len, fd = -1;
    229       ssize_t llen;
    230 
    231       len = getline(&name, &size, stdin);
    232       if (len<1) break;
    233       if (name[len-1] == '\n') name[--len] = 0;
    234       nlen = len+1;
    235       if (lstat(name, &st) || (S_ISREG(st.st_mode)
    236           && st.st_size && (fd = open(name, O_RDONLY))<0))
    237       {
    238         perror_msg_raw(name);
    239         continue;
    240       }
    241 
    242       if (!S_ISREG(st.st_mode) && !S_ISLNK(st.st_mode)) st.st_size = 0;
    243       if (st.st_size >> 32) perror_msg("skipping >2G file '%s'", name);
    244       else {
    245         llen = sprintf(toybuf,
    246           "070701%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X%08X",
    247           (int)st.st_ino, st.st_mode, st.st_uid, st.st_gid, (int)st.st_nlink,
    248           (int)st.st_mtime, (int)st.st_size, dev_major(st.st_dev),
    249           dev_minor(st.st_dev), dev_major(st.st_rdev), dev_minor(st.st_rdev),
    250           nlen, 0);
    251         xwrite(afd, toybuf, llen);
    252         xwrite(afd, name, nlen);
    253 
    254         // NUL Pad header up to 4 multiple bytes.
    255         llen = (llen + nlen) & 3;
    256         if (llen) xwrite(afd, &zero, 4-llen);
    257 
    258         // Write out body for symlink or regular file
    259         llen = st.st_size;
    260         if (S_ISLNK(st.st_mode)) {
    261           if (readlink(name, toybuf, sizeof(toybuf)-1) == llen)
    262             xwrite(afd, toybuf, llen);
    263           else perror_msg("readlink '%s'", name);
    264         } else while (llen) {
    265           nlen = llen > sizeof(toybuf) ? sizeof(toybuf) : llen;
    266           llen -= nlen;
    267           // If read fails, write anyway (already wrote size in header)
    268           if (nlen != readall(fd, toybuf, nlen))
    269             if (!error++) perror_msg("bad read from file '%s'", name);
    270           xwrite(afd, toybuf, nlen);
    271         }
    272         llen = st.st_size & 3;
    273         if (llen) xwrite(afd, &zero, 4-llen);
    274       }
    275       close(fd);
    276     }
    277     free(name);
    278 
    279     if (FLAG_trailer) {
    280       memset(toybuf, 0, sizeof(toybuf));
    281       xwrite(afd, toybuf,
    282         sprintf(toybuf, "070701%040X%056X%08XTRAILER!!!", 1, 0x0b, 0)+4);
    283     }
    284   }
    285   if (TT.archive) xclose(afd);
    286 
    287   if (TT.pass) toys.exitval |= xpclose(pid, pipe);
    288 }
    289