tar: add support for PAX-encoded path=LONGFILENAME
[oweals/busybox.git] / archival / libarchive / get_header_tar.c
1 /* vi: set sw=4 ts=4: */
2 /* Licensed under GPLv2 or later, see file LICENSE in this source tree.
3  *
4  * FIXME:
5  *    In privileged mode if uname and gname map to a uid and gid then use the
6  *    mapped value instead of the uid/gid values in tar header
7  *
8  * References:
9  *    GNU tar and star man pages,
10  *    Opengroup's ustar interchange format,
11  *    http://www.opengroup.org/onlinepubs/007904975/utilities/pax.html
12  */
13
14 #include "libbb.h"
15 #include "bb_archive.h"
16
17 typedef uint32_t aliased_uint32_t FIX_ALIASING;
18 typedef off_t    aliased_off_t    FIX_ALIASING;
19
20
21 const char* FAST_FUNC strip_unsafe_prefix(const char *str)
22 {
23         const char *cp = str;
24         while (1) {
25                 char *cp2;
26                 if (*cp == '/') {
27                         cp++;
28                         continue;
29                 }
30                 if (strncmp(cp, "/../"+1, 3) == 0) {
31                         cp += 3;
32                         continue;
33                 }
34                 cp2 = strstr(cp, "/../");
35                 if (!cp2)
36                         break;
37                 cp = cp2 + 4;
38         }
39         if (cp != str) {
40                 static smallint warned = 0;
41                 if (!warned) {
42                         warned = 1;
43                         bb_error_msg("removing leading '%.*s' from member names",
44                                 (int)(cp - str), str);
45                 }
46         }
47         return cp;
48 }
49
50 /* NB: _DESTROYS_ str[len] character! */
51 static unsigned long long getOctal(char *str, int len)
52 {
53         unsigned long long v;
54         char *end;
55         /* NB: leading spaces are allowed. Using strtoull to handle that.
56          * The downside is that we accept e.g. "-123" too :(
57          */
58         str[len] = '\0';
59         v = strtoull(str, &end, 8);
60         /* std: "Each numeric field is terminated by one or more
61          * <space> or NUL characters". We must support ' '! */
62         if (*end != '\0' && *end != ' ') {
63                 int8_t first = str[0];
64                 if (!(first & 0x80))
65                         bb_error_msg_and_die("corrupted octal value in tar header");
66                 /*
67                  * GNU tar uses "base-256 encoding" for very large numbers.
68                  * Encoding is binary, with highest bit always set as a marker
69                  * and sign in next-highest bit:
70                  * 80 00 .. 00 - zero
71                  * bf ff .. ff - largest positive number
72                  * ff ff .. ff - minus 1
73                  * c0 00 .. 00 - smallest negative number
74                  *
75                  * Example of tar file with 8914993153 (0x213600001) byte file.
76                  * Field starts at offset 7c:
77                  * 00070  30 30 30 00 30 30 30 30  30 30 30 00 80 00 00 00  |000.0000000.....|
78                  * 00080  00 00 00 02 13 60 00 01  31 31 31 32 30 33 33 36  |.....`..11120336|
79                  *
80                  * NB: tarballs with NEGATIVE unix times encoded that way were seen!
81                  */
82                 /* Sign-extend 7bit 'first' to 64bit 'v' (that is, using 6th bit as sign): */
83                 first <<= 1;
84                 first >>= 1; /* now 7th bit = 6th bit */
85                 v = first;   /* sign-extend 8 bits to 64 */
86                 while (--len != 0)
87                         v = (v << 8) + (unsigned char) *str++;
88         }
89         return v;
90 }
91 #define GET_OCTAL(a) getOctal((a), sizeof(a))
92
93 /* "global" is 0 or 1 */
94 static void process_pax_hdr(archive_handle_t *archive_handle, unsigned sz, int global)
95 {
96         char *buf, *p;
97         unsigned blk_sz;
98
99         blk_sz = (sz + 511) & (~511);
100         p = buf = xmalloc(blk_sz + 1);
101         xread(archive_handle->src_fd, buf, blk_sz);
102         archive_handle->offset += blk_sz;
103
104         /* prevent bb_strtou from running off the buffer */
105         buf[sz] = '\0';
106
107         while (sz != 0) {
108                 char *end, *value;
109                 unsigned len;
110
111                 /* Every record has this format: "LEN NAME=VALUE\n" */
112                 len = bb_strtou(p, &end, 10);
113                 /* expect errno to be EINVAL, because the character
114                  * following the digits should be a space
115                  */
116                 p += len;
117                 sz -= len;
118                 if ((int)sz < 0
119                  || len == 0
120                  || errno != EINVAL
121                  || *end != ' '
122                 ) {
123                         bb_error_msg("malformed extended header, skipped");
124                         // More verbose version:
125                         //bb_error_msg("malformed extended header at %"OFF_FMT"d, skipped",
126                         //              archive_handle->offset - (sz + len));
127                         break;
128                 }
129                 /* overwrite the terminating newline with NUL
130                  * (we do not bother to check that it *was* a newline)
131                  */
132                 p[-1] = '\0';
133                 value = end + 1;
134
135 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
136                 if (!global && strncmp(value, "path=", sizeof("path=") - 1) == 0) {
137                         value += sizeof("path=") - 1;
138                         free(archive_handle->tar__longname);
139                         archive_handle->tar__longname = xstrdup(value);
140                         continue;
141                 }
142 #endif
143
144 #if ENABLE_FEATURE_TAR_SELINUX
145                 /* Scan for SELinux contexts, via "RHT.security.selinux" keyword.
146                  * This is what Red Hat's patched version of tar uses.
147                  */
148 # define SELINUX_CONTEXT_KEYWORD "RHT.security.selinux"
149                 if (strncmp(value, SELINUX_CONTEXT_KEYWORD"=", sizeof(SELINUX_CONTEXT_KEYWORD"=") - 1) == 0) {
150                         value += sizeof(SELINUX_CONTEXT_KEYWORD"=") - 1;
151                         free(archive_handle->tar__sctx[global]);
152                         archive_handle->tar__sctx[global] = xstrdup(value);
153                         continue;
154                 }
155 #endif
156         }
157
158         free(buf);
159 }
160
161 char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
162 {
163         file_header_t *file_header = archive_handle->file_header;
164         struct tar_header_t tar;
165         char *cp;
166         int i, sum_u, sum;
167 #if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
168         int sum_s;
169 #endif
170         int parse_names;
171
172         /* Our "private data" */
173 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
174 # define p_longname (archive_handle->tar__longname)
175 # define p_linkname (archive_handle->tar__linkname)
176 #else
177 # define p_longname 0
178 # define p_linkname 0
179 #endif
180
181 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS || ENABLE_FEATURE_TAR_SELINUX
182  again:
183 #endif
184         /* Align header */
185         data_align(archive_handle, 512);
186
187  again_after_align:
188
189 #if ENABLE_DESKTOP || ENABLE_FEATURE_TAR_AUTODETECT
190         /* to prevent misdetection of bz2 sig */
191         *(aliased_uint32_t*)&tar = 0;
192         i = full_read(archive_handle->src_fd, &tar, 512);
193         /* If GNU tar sees EOF in above read, it says:
194          * "tar: A lone zero block at N", where N = kilobyte
195          * where EOF was met (not EOF block, actual EOF!),
196          * and exits with EXIT_SUCCESS.
197          * We will mimic exit(EXIT_SUCCESS), although we will not mimic
198          * the message and we don't check whether we indeed
199          * saw zero block directly before this. */
200         if (i == 0) {
201                 xfunc_error_retval = 0;
202  short_read:
203                 bb_error_msg_and_die("short read");
204         }
205         if (i != 512) {
206                 IF_FEATURE_TAR_AUTODETECT(goto autodetect;)
207                 goto short_read;
208         }
209
210 #else
211         i = 512;
212         xread(archive_handle->src_fd, &tar, i);
213 #endif
214         archive_handle->offset += i;
215
216         /* If there is no filename its an empty header */
217         if (tar.name[0] == 0 && tar.prefix[0] == 0) {
218                 if (archive_handle->tar__end) {
219                         /* Second consecutive empty header - end of archive.
220                          * Read until the end to empty the pipe from gz or bz2
221                          */
222                         while (full_read(archive_handle->src_fd, &tar, 512) == 512)
223                                 continue;
224                         return EXIT_FAILURE;
225                 }
226                 archive_handle->tar__end = 1;
227                 return EXIT_SUCCESS;
228         }
229         archive_handle->tar__end = 0;
230
231         /* Check header has valid magic, "ustar" is for the proper tar,
232          * five NULs are for the old tar format  */
233         if (strncmp(tar.magic, "ustar", 5) != 0
234          && (!ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
235              || memcmp(tar.magic, "\0\0\0\0", 5) != 0)
236         ) {
237 #if ENABLE_FEATURE_TAR_AUTODETECT
238                 char FAST_FUNC (*get_header_ptr)(archive_handle_t *);
239                 uint16_t magic2;
240
241  autodetect:
242                 magic2 = *(bb__aliased_uint16_t*)tar.name;
243                 /* tar gz/bz autodetect: check for gz/bz2 magic.
244                  * If we see the magic, and it is the very first block,
245                  * we can switch to get_header_tar_gz/bz2/lzma().
246                  * Needs seekable fd. I wish recv(MSG_PEEK) works
247                  * on any fd... */
248 # if ENABLE_FEATURE_SEAMLESS_GZ
249                 if (magic2 == GZIP_MAGIC) {
250                         get_header_ptr = get_header_tar_gz;
251                 } else
252 # endif
253 # if ENABLE_FEATURE_SEAMLESS_BZ2
254                 if (magic2 == BZIP2_MAGIC
255                  && tar.name[2] == 'h' && isdigit(tar.name[3])
256                 ) { /* bzip2 */
257                         get_header_ptr = get_header_tar_bz2;
258                 } else
259 # endif
260 # if ENABLE_FEATURE_SEAMLESS_XZ
261                 //TODO: if (magic2 == XZ_MAGIC1)...
262                 //else
263 # endif
264                         goto err;
265                 /* Two different causes for lseek() != 0:
266                  * unseekable fd (would like to support that too, but...),
267                  * or not first block (false positive, it's not .gz/.bz2!) */
268                 if (lseek(archive_handle->src_fd, -i, SEEK_CUR) != 0)
269                         goto err;
270                 while (get_header_ptr(archive_handle) == EXIT_SUCCESS)
271                         continue;
272                 return EXIT_FAILURE;
273  err:
274 #endif /* FEATURE_TAR_AUTODETECT */
275                 bb_error_msg_and_die("invalid tar magic");
276         }
277
278         /* Do checksum on headers.
279          * POSIX says that checksum is done on unsigned bytes, but
280          * Sun and HP-UX gets it wrong... more details in
281          * GNU tar source. */
282 #if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
283         sum_s = ' ' * sizeof(tar.chksum);
284 #endif
285         sum_u = ' ' * sizeof(tar.chksum);
286         for (i = 0; i < 148; i++) {
287                 sum_u += ((unsigned char*)&tar)[i];
288 #if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
289                 sum_s += ((signed char*)&tar)[i];
290 #endif
291         }
292         for (i = 156; i < 512; i++) {
293                 sum_u += ((unsigned char*)&tar)[i];
294 #if ENABLE_FEATURE_TAR_OLDSUN_COMPATIBILITY
295                 sum_s += ((signed char*)&tar)[i];
296 #endif
297         }
298         /* This field does not need special treatment (getOctal) */
299         {
300                 char *endp; /* gcc likes temp var for &endp */
301                 sum = strtoul(tar.chksum, &endp, 8);
302                 if ((*endp != '\0' && *endp != ' ')
303                  || (sum_u != sum IF_FEATURE_TAR_OLDSUN_COMPATIBILITY(&& sum_s != sum))
304                 ) {
305                         bb_error_msg_and_die("invalid tar header checksum");
306                 }
307         }
308         /* don't use xstrtoul, tar.chksum may have leading spaces */
309         sum = strtoul(tar.chksum, NULL, 8);
310         if (sum_u != sum IF_FEATURE_TAR_OLDSUN_COMPATIBILITY(&& sum_s != sum)) {
311                 bb_error_msg_and_die("invalid tar header checksum");
312         }
313
314         /* 0 is reserved for high perf file, treat as normal file */
315         if (!tar.typeflag) tar.typeflag = '0';
316         parse_names = (tar.typeflag >= '0' && tar.typeflag <= '7');
317
318         /* getOctal trashes subsequent field, therefore we call it
319          * on fields in reverse order */
320         if (tar.devmajor[0]) {
321                 char t = tar.prefix[0];
322                 /* we trash prefix[0] here, but we DO need it later! */
323                 unsigned minor = GET_OCTAL(tar.devminor);
324                 unsigned major = GET_OCTAL(tar.devmajor);
325                 file_header->device = makedev(major, minor);
326                 tar.prefix[0] = t;
327         }
328         file_header->link_target = NULL;
329         if (!p_linkname && parse_names && tar.linkname[0]) {
330                 file_header->link_target = xstrndup(tar.linkname, sizeof(tar.linkname));
331                 /* FIXME: what if we have non-link object with link_target? */
332                 /* Will link_target be free()ed? */
333         }
334 #if ENABLE_FEATURE_TAR_UNAME_GNAME
335         file_header->tar__uname = tar.uname[0] ? xstrndup(tar.uname, sizeof(tar.uname)) : NULL;
336         file_header->tar__gname = tar.gname[0] ? xstrndup(tar.gname, sizeof(tar.gname)) : NULL;
337 #endif
338         file_header->mtime = GET_OCTAL(tar.mtime);
339         file_header->size = GET_OCTAL(tar.size);
340         file_header->gid = GET_OCTAL(tar.gid);
341         file_header->uid = GET_OCTAL(tar.uid);
342         /* Set bits 0-11 of the files mode */
343         file_header->mode = 07777 & GET_OCTAL(tar.mode);
344
345         file_header->name = NULL;
346         if (!p_longname && parse_names) {
347                 /* we trash mode[0] here, it's ok */
348                 //tar.name[sizeof(tar.name)] = '\0'; - gcc 4.3.0 would complain
349                 tar.mode[0] = '\0';
350                 if (tar.prefix[0]) {
351                         /* and padding[0] */
352                         //tar.prefix[sizeof(tar.prefix)] = '\0'; - gcc 4.3.0 would complain
353                         tar.padding[0] = '\0';
354                         file_header->name = concat_path_file(tar.prefix, tar.name);
355                 } else
356                         file_header->name = xstrdup(tar.name);
357         }
358
359         /* Set bits 12-15 of the files mode */
360         /* (typeflag was not trashed because chksum does not use getOctal) */
361         switch (tar.typeflag) {
362         case '1': /* hardlink */
363                 /* we mark hardlinks as regular files with zero size and a link name */
364                 file_header->mode |= S_IFREG;
365                 /* on size of link fields from star(4)
366                  * ... For tar archives written by pre POSIX.1-1988
367                  * implementations, the size field usually contains the size of
368                  * the file and needs to be ignored as no data may follow this
369                  * header type.  For POSIX.1- 1988 compliant archives, the size
370                  * field needs to be 0.  For POSIX.1-2001 compliant archives,
371                  * the size field may be non zero, indicating that file data is
372                  * included in the archive.
373                  * i.e; always assume this is zero for safety.
374                  */
375                 goto size0;
376         case '7':
377         /* case 0: */
378         case '0':
379 #if ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
380                 if (last_char_is(file_header->name, '/')) {
381                         goto set_dir;
382                 }
383 #endif
384                 file_header->mode |= S_IFREG;
385                 break;
386         case '2':
387                 file_header->mode |= S_IFLNK;
388                 /* have seen tarballs with size field containing
389                  * the size of the link target's name */
390  size0:
391                 file_header->size = 0;
392                 break;
393         case '3':
394                 file_header->mode |= S_IFCHR;
395                 goto size0; /* paranoia */
396         case '4':
397                 file_header->mode |= S_IFBLK;
398                 goto size0;
399         case '5':
400  IF_FEATURE_TAR_OLDGNU_COMPATIBILITY(set_dir:)
401                 file_header->mode |= S_IFDIR;
402                 goto size0;
403         case '6':
404                 file_header->mode |= S_IFIFO;
405                 goto size0;
406 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
407         case 'L':
408                 /* free: paranoia: tar with several consecutive longnames */
409                 free(p_longname);
410                 /* For paranoia reasons we allocate extra NUL char */
411                 p_longname = xzalloc(file_header->size + 1);
412                 /* We read ASCIZ string, including NUL */
413                 xread(archive_handle->src_fd, p_longname, file_header->size);
414                 archive_handle->offset += file_header->size;
415                 /* return get_header_tar(archive_handle); */
416                 /* gcc 4.1.1 didn't optimize it into jump */
417                 /* so we will do it ourself, this also saves stack */
418                 goto again;
419         case 'K':
420                 free(p_linkname);
421                 p_linkname = xzalloc(file_header->size + 1);
422                 xread(archive_handle->src_fd, p_linkname, file_header->size);
423                 archive_handle->offset += file_header->size;
424                 /* return get_header_tar(archive_handle); */
425                 goto again;
426         case 'D':       /* GNU dump dir */
427         case 'M':       /* Continuation of multi volume archive */
428         case 'N':       /* Old GNU for names > 100 characters */
429         case 'S':       /* Sparse file */
430         case 'V':       /* Volume header */
431 #endif
432         case 'g':       /* pax global header */
433         case 'x': {     /* pax extended header */
434                 if ((uoff_t)file_header->size > 0xfffff) /* paranoia */
435                         goto skip_ext_hdr;
436                 process_pax_hdr(archive_handle, file_header->size, (tar.typeflag == 'g'));
437                 goto again_after_align;
438         }
439  skip_ext_hdr:
440         {
441                 off_t sz;
442                 bb_error_msg("warning: skipping header '%c'", tar.typeflag);
443                 sz = (file_header->size + 511) & ~(off_t)511;
444                 archive_handle->offset += sz;
445                 sz >>= 9; /* sz /= 512 but w/o contortions for signed div */
446                 while (sz--)
447                         xread(archive_handle->src_fd, &tar, 512);
448                 /* return get_header_tar(archive_handle); */
449                 goto again_after_align;
450         }
451         default:
452                 bb_error_msg_and_die("unknown typeflag: 0x%x", tar.typeflag);
453         }
454
455 #if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
456         if (p_longname) {
457                 file_header->name = p_longname;
458                 p_longname = NULL;
459         }
460         if (p_linkname) {
461                 file_header->link_target = p_linkname;
462                 p_linkname = NULL;
463         }
464 #endif
465
466         /* Everything up to and including last ".." component is stripped */
467         overlapping_strcpy(file_header->name, strip_unsafe_prefix(file_header->name));
468
469         /* Strip trailing '/' in directories */
470         /* Must be done after mode is set as '/' is used to check if it's a directory */
471         cp = last_char_is(file_header->name, '/');
472
473         if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
474                 archive_handle->action_header(/*archive_handle->*/ file_header);
475                 /* Note that we kill the '/' only after action_header() */
476                 /* (like GNU tar 1.15.1: verbose mode outputs "dir/dir/") */
477                 if (cp)
478                         *cp = '\0';
479                 archive_handle->action_data(archive_handle);
480                 if (archive_handle->accept || archive_handle->reject)
481                         llist_add_to(&archive_handle->passed, file_header->name);
482                 else /* Caller isn't interested in list of unpacked files */
483                         free(file_header->name);
484         } else {
485                 data_skip(archive_handle);
486                 free(file_header->name);
487         }
488         archive_handle->offset += file_header->size;
489
490         free(file_header->link_target);
491         /* Do not free(file_header->name)!
492          * It might be inserted in archive_handle->passed - see above */
493 #if ENABLE_FEATURE_TAR_UNAME_GNAME
494         free(file_header->tar__uname);
495         free(file_header->tar__gname);
496 #endif
497         return EXIT_SUCCESS;
498 }