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