xref: /freebsd/contrib/libarchive/libarchive/archive_read_support_format_tar.c (revision 401026e4825a05abba6f945cf1b74b3328876fa2)
1 /*-
2  * Copyright (c) 2003-2023 Tim Kientzle
3  * Copyright (c) 2011-2012 Michihiro NAKAJIMA
4  * Copyright (c) 2016 Martin Matuska
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include "archive_platform.h"
29 
30 #ifdef HAVE_ERRNO_H
31 #include <errno.h>
32 #endif
33 #include <stddef.h>
34 #ifdef HAVE_STDLIB_H
35 #include <stdlib.h>
36 #endif
37 #ifdef HAVE_STRING_H
38 #include <string.h>
39 #endif
40 
41 #include "archive.h"
42 #include "archive_acl_private.h" /* For ACL parsing routines. */
43 #include "archive_entry.h"
44 #include "archive_entry_locale.h"
45 #include "archive_private.h"
46 #include "archive_read_private.h"
47 
48 #define tar_min(a,b) ((a) < (b) ? (a) : (b))
49 
50 /*
51  * Layout of POSIX 'ustar' tar header.
52  */
53 struct archive_entry_header_ustar {
54 	char	name[100];
55 	char	mode[8];
56 	char	uid[8];
57 	char	gid[8];
58 	char	size[12];
59 	char	mtime[12];
60 	char	checksum[8];
61 	char	typeflag[1];
62 	char	linkname[100];	/* "old format" header ends here */
63 	char	magic[6];	/* For POSIX: "ustar\0" */
64 	char	version[2];	/* For POSIX: "00" */
65 	char	uname[32];
66 	char	gname[32];
67 	char	rdevmajor[8];
68 	char	rdevminor[8];
69 	char	prefix[155];
70 };
71 
72 /*
73  * Structure of GNU tar header
74  */
75 struct gnu_sparse {
76 	char	offset[12];
77 	char	numbytes[12];
78 };
79 
80 struct archive_entry_header_gnutar {
81 	char	name[100];
82 	char	mode[8];
83 	char	uid[8];
84 	char	gid[8];
85 	char	size[12];
86 	char	mtime[12];
87 	char	checksum[8];
88 	char	typeflag[1];
89 	char	linkname[100];
90 	char	magic[8];  /* "ustar  \0" (note blank/blank/null at end) */
91 	char	uname[32];
92 	char	gname[32];
93 	char	rdevmajor[8];
94 	char	rdevminor[8];
95 	char	atime[12];
96 	char	ctime[12];
97 	char	offset[12];
98 	char	longnames[4];
99 	char	unused[1];
100 	struct gnu_sparse sparse[4];
101 	char	isextended[1];
102 	char	realsize[12];
103 	/*
104 	 * Old GNU format doesn't use POSIX 'prefix' field; they use
105 	 * the 'L' (longname) entry instead.
106 	 */
107 };
108 
109 /*
110  * Data specific to this format.
111  */
112 struct sparse_block {
113 	struct sparse_block	*next;
114 	int64_t	offset;
115 	int64_t	remaining;
116 	int hole;
117 };
118 
119 struct tar {
120 	struct archive_string	 entry_pathname;
121 	/* For "GNU.sparse.name" and other similar path extensions. */
122 	struct archive_string	 entry_pathname_override;
123 	struct archive_string	 entry_uname;
124 	struct archive_string	 entry_gname;
125 	struct archive_string	 entry_linkpath;
126 	struct archive_string	 line;
127 	int			 pax_hdrcharset_utf8;
128 	int64_t			 entry_bytes_remaining;
129 	int64_t			 entry_offset;
130 	int64_t			 entry_padding;
131 	int64_t 		 entry_bytes_unconsumed;
132 	int64_t			 disk_size;
133 	int64_t			 GNU_sparse_realsize;
134 	int64_t			 GNU_sparse_size;
135 	int64_t			 SCHILY_sparse_realsize;
136 	int64_t			 pax_size;
137 	struct sparse_block	*sparse_list;
138 	struct sparse_block	*sparse_last;
139 	int64_t			 sparse_offset;
140 	int64_t			 sparse_numbytes;
141 	int			 sparse_gnu_major;
142 	int			 sparse_gnu_minor;
143 	char			 sparse_gnu_attributes_seen;
144 	char			 filetype;
145 	char			 size_fields; /* Bits defined below */
146 
147 	struct archive_string	 localname;
148 	struct archive_string_conv *opt_sconv;
149 	struct archive_string_conv *sconv;
150 	struct archive_string_conv *sconv_acl;
151 	struct archive_string_conv *sconv_default;
152 	int			 init_default_conversion;
153 	int			 compat_2x;
154 	int			 process_mac_extensions;
155 	int			 read_concatenated_archives;
156 };
157 
158 /* Track which size fields were present in the headers */
159 #define TAR_SIZE_PAX_SIZE 1
160 #define TAR_SIZE_GNU_SPARSE_REALSIZE 2
161 #define TAR_SIZE_GNU_SPARSE_SIZE 4
162 #define TAR_SIZE_SCHILY_SPARSE_REALSIZE 8
163 
164 
165 static int	archive_block_is_null(const char *p);
166 static char	*base64_decode(const char *, size_t, size_t *);
167 static int	gnu_add_sparse_entry(struct archive_read *, struct tar *,
168 		    int64_t offset, int64_t remaining);
169 
170 static void	gnu_clear_sparse_list(struct tar *);
171 static int	gnu_sparse_old_read(struct archive_read *, struct tar *,
172 		    const struct archive_entry_header_gnutar *header, int64_t *);
173 static int	gnu_sparse_old_parse(struct archive_read *, struct tar *,
174 		    const struct gnu_sparse *sparse, int length);
175 static int	gnu_sparse_01_parse(struct archive_read *, struct tar *,
176 		    const char *, size_t);
177 static int64_t	gnu_sparse_10_read(struct archive_read *, struct tar *,
178 		    int64_t *);
179 static int	header_Solaris_ACL(struct archive_read *,  struct tar *,
180 		    struct archive_entry *, const void *, int64_t *);
181 static int	header_common(struct archive_read *,  struct tar *,
182 		    struct archive_entry *, const void *);
183 static int	header_old_tar(struct archive_read *, struct tar *,
184 		    struct archive_entry *, const void *);
185 static int	header_pax_extension(struct archive_read *, struct tar *,
186 		    struct archive_entry *, const void *, int64_t *);
187 static int	header_pax_global(struct archive_read *, struct tar *,
188 		    struct archive_entry *, const void *h, int64_t *);
189 static int	header_gnu_longlink(struct archive_read *, struct tar *,
190 		    struct archive_entry *, const void *h, int64_t *);
191 static int	header_gnu_longname(struct archive_read *, struct tar *,
192 		    struct archive_entry *, const void *h, int64_t *);
193 static int	is_mac_metadata_entry(struct archive_entry *entry);
194 static int	read_mac_metadata_blob(struct archive_read *,
195 		    struct archive_entry *, int64_t *);
196 static int	header_volume(struct archive_read *, struct tar *,
197 		    struct archive_entry *, const void *h, int64_t *);
198 static int	header_ustar(struct archive_read *, struct tar *,
199 		    struct archive_entry *, const void *h);
200 static int	header_gnutar(struct archive_read *, struct tar *,
201 		    struct archive_entry *, const void *h, int64_t *);
202 static int	archive_read_format_tar_bid(struct archive_read *, int);
203 static int	archive_read_format_tar_options(struct archive_read *,
204 		    const char *, const char *);
205 static int	archive_read_format_tar_cleanup(struct archive_read *);
206 static int	archive_read_format_tar_read_data(struct archive_read *a,
207 		    const void **buff, size_t *size, int64_t *offset);
208 static int	archive_read_format_tar_skip(struct archive_read *a);
209 static int	archive_read_format_tar_read_header(struct archive_read *,
210 		    struct archive_entry *);
211 static int	checksum(struct archive_read *, const void *);
212 static int 	pax_attribute(struct archive_read *, struct tar *,
213 		    struct archive_entry *, const char *key, size_t key_length,
214 		    size_t value_length, int64_t *unconsumed);
215 static int	pax_attribute_LIBARCHIVE_xattr(struct archive_entry *,
216 		    const char *, size_t, const char *, size_t);
217 static int	pax_attribute_SCHILY_acl(struct archive_read *, struct tar *,
218 		    struct archive_entry *, size_t, int);
219 static int	pax_attribute_SUN_holesdata(struct archive_read *, struct tar *,
220 		    struct archive_entry *, const char *, size_t);
221 static void	pax_time(const char *, size_t, int64_t *sec, long *nanos);
222 static ssize_t	readline(struct archive_read *, struct tar *, const char **,
223 		    ssize_t limit, int64_t *);
224 static int	read_body_to_string(struct archive_read *, struct tar *,
225 		    struct archive_string *, const void *h, int64_t *);
226 static int	read_bytes_to_string(struct archive_read *,
227 		    struct archive_string *, size_t, int64_t *);
228 static int64_t	tar_atol(const char *, size_t);
229 static int64_t	tar_atol10(const char *, size_t);
230 static int64_t	tar_atol256(const char *, size_t);
231 static int64_t	tar_atol8(const char *, size_t);
232 static int	tar_read_header(struct archive_read *, struct tar *,
233 		    struct archive_entry *, int64_t *);
234 static int	tohex(int c);
235 static char	*url_decode(const char *, size_t);
236 static int	tar_flush_unconsumed(struct archive_read *, int64_t *);
237 
238 /* Sanity limits:  These numbers should be low enough to
239  * prevent a maliciously-crafted archive from forcing us to
240  * allocate extreme amounts of memory.  But of course, they
241  * need to be high enough for any correct value.  These
242  * will likely need some adjustment as we get more experience. */
243 static const size_t guname_limit = 65536; /* Longest uname or gname: 64kiB */
244 static const size_t pathname_limit = 1048576; /* Longest path name: 1MiB */
245 static const size_t sparse_map_limit = 8 * 1048576; /* Longest sparse map: 8MiB */
246 static const size_t xattr_limit = 16 * 1048576; /* Longest xattr: 16MiB */
247 static const size_t fflags_limit = 512; /* Longest fflags */
248 static const size_t acl_limit = 131072; /* Longest textual ACL: 128kiB */
249 static const int64_t entry_limit = 0xfffffffffffffffLL; /* 2^60 bytes = 1 ExbiByte */
250 
251 int
archive_read_support_format_gnutar(struct archive * a)252 archive_read_support_format_gnutar(struct archive *a)
253 {
254 	archive_check_magic(a, ARCHIVE_READ_MAGIC,
255 	    ARCHIVE_STATE_NEW, "archive_read_support_format_gnutar");
256 	return (archive_read_support_format_tar(a));
257 }
258 
259 
260 int
archive_read_support_format_tar(struct archive * _a)261 archive_read_support_format_tar(struct archive *_a)
262 {
263 	struct archive_read *a = (struct archive_read *)_a;
264 	struct tar *tar;
265 	int r;
266 
267 	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
268 	    ARCHIVE_STATE_NEW, "archive_read_support_format_tar");
269 
270 	tar = calloc(1, sizeof(*tar));
271 	if (tar == NULL) {
272 		archive_set_error(&a->archive, ENOMEM,
273 		    "Can't allocate tar data");
274 		return (ARCHIVE_FATAL);
275 	}
276 #ifdef HAVE_COPYFILE_H
277 	/* Set this by default on Mac OS. */
278 	tar->process_mac_extensions = 1;
279 #endif
280 
281 	r = __archive_read_register_format(a, tar, "tar",
282 	    archive_read_format_tar_bid,
283 	    archive_read_format_tar_options,
284 	    archive_read_format_tar_read_header,
285 	    archive_read_format_tar_read_data,
286 	    archive_read_format_tar_skip,
287 	    NULL,
288 	    archive_read_format_tar_cleanup,
289 	    NULL,
290 	    NULL);
291 
292 	if (r != ARCHIVE_OK)
293 		free(tar);
294 	return (ARCHIVE_OK);
295 }
296 
297 static int
archive_read_format_tar_cleanup(struct archive_read * a)298 archive_read_format_tar_cleanup(struct archive_read *a)
299 {
300 	struct tar *tar;
301 
302 	tar = (struct tar *)(a->format->data);
303 	gnu_clear_sparse_list(tar);
304 	archive_string_free(&tar->entry_pathname);
305 	archive_string_free(&tar->entry_pathname_override);
306 	archive_string_free(&tar->entry_uname);
307 	archive_string_free(&tar->entry_gname);
308 	archive_string_free(&tar->entry_linkpath);
309 	archive_string_free(&tar->line);
310 	archive_string_free(&tar->localname);
311 	free(tar);
312 	(a->format->data) = NULL;
313 	return (ARCHIVE_OK);
314 }
315 
316 /*
317  * Validate number field
318  *
319  * This has to be pretty lenient in order to accommodate the enormous
320  * variety of tar writers in the world:
321  *  = POSIX (IEEE Std 1003.1-1988) ustar requires octal values with leading
322  *    zeros and allows fields to be terminated with space or null characters
323  *  = Many writers use different termination (in particular, libarchive
324  *    omits terminator bytes to squeeze one or two more digits)
325  *  = Many writers pad with space and omit leading zeros
326  *  = GNU tar and star write base-256 values if numbers are too
327  *    big to be represented in octal
328  *
329  *  Examples of specific tar headers that we should support:
330  *  = Perl Archive::Tar terminates uid, gid, devminor and devmajor with two
331  *    null bytes, pads size with spaces and other numeric fields with zeroes
332  *  = plexus-archiver prior to 2.6.3 (before switching to commons-compress)
333  *    may have uid and gid fields filled with spaces without any octal digits
334  *    at all and pads all numeric fields with spaces
335  *
336  * This should tolerate all variants in use.  It will reject a field
337  * where the writer just left garbage after a trailing NUL.
338  */
339 static int
validate_number_field(const char * p_field,size_t i_size)340 validate_number_field(const char* p_field, size_t i_size)
341 {
342 	unsigned char marker = (unsigned char)p_field[0];
343 	if (marker == 128 || marker == 255 || marker == 0) {
344 		/* Base-256 marker, there's nothing we can check. */
345 		return 1;
346 	} else {
347 		/* Must be octal */
348 		size_t i = 0;
349 		/* Skip any leading spaces */
350 		while (i < i_size && p_field[i] == ' ') {
351 			++i;
352 		}
353 		/* Skip octal digits. */
354 		while (i < i_size && p_field[i] >= '0' && p_field[i] <= '7') {
355 			++i;
356 		}
357 		/* Any remaining characters must be space or NUL padding. */
358 		while (i < i_size) {
359 			if (p_field[i] != ' ' && p_field[i] != 0) {
360 				return 0;
361 			}
362 			++i;
363 		}
364 		return 1;
365 	}
366 }
367 
368 static int
archive_read_format_tar_bid(struct archive_read * a,int best_bid)369 archive_read_format_tar_bid(struct archive_read *a, int best_bid)
370 {
371 	int bid;
372 	const char *h;
373 	const struct archive_entry_header_ustar *header;
374 
375 	(void)best_bid; /* UNUSED */
376 
377 	bid = 0;
378 
379 	/* Now let's look at the actual header and see if it matches. */
380 	h = __archive_read_ahead(a, 512, NULL);
381 	if (h == NULL)
382 		return (-1);
383 
384 	/* If it's an end-of-archive mark, we can handle it. */
385 	if (h[0] == 0 && archive_block_is_null(h)) {
386 		/*
387 		 * Usually, I bid the number of bits verified, but
388 		 * in this case, 4096 seems excessive so I picked 10 as
389 		 * an arbitrary but reasonable-seeming value.
390 		 */
391 		return (10);
392 	}
393 
394 	/* If it's not an end-of-archive mark, it must have a valid checksum.*/
395 	if (!checksum(a, h))
396 		return (0);
397 	bid += 48;  /* Checksum is usually 6 octal digits. */
398 
399 	header = (const struct archive_entry_header_ustar *)h;
400 
401 	/* Recognize POSIX formats. */
402 	if ((memcmp(header->magic, "ustar\0", 6) == 0)
403 	    && (memcmp(header->version, "00", 2) == 0))
404 		bid += 56;
405 
406 	/* Recognize GNU tar format. */
407 	if ((memcmp(header->magic, "ustar ", 6) == 0)
408 	    && (memcmp(header->version, " \0", 2) == 0))
409 		bid += 56;
410 
411 	/* Type flag must be null, digit or A-Z, a-z. */
412 	if (header->typeflag[0] != 0 &&
413 	    !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
414 	    !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
415 	    !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
416 		return (0);
417 	bid += 2;  /* 6 bits of variation in an 8-bit field leaves 2 bits. */
418 
419 	/*
420 	 * Check format of mode/uid/gid/mtime/size/rdevmajor/rdevminor fields.
421 	 */
422 	if (validate_number_field(header->mode, sizeof(header->mode)) == 0
423 	    || validate_number_field(header->uid, sizeof(header->uid)) == 0
424 	    || validate_number_field(header->gid, sizeof(header->gid)) == 0
425 	    || validate_number_field(header->mtime, sizeof(header->mtime)) == 0
426 	    || validate_number_field(header->size, sizeof(header->size)) == 0
427 	    || validate_number_field(header->rdevmajor, sizeof(header->rdevmajor)) == 0
428 	    || validate_number_field(header->rdevminor, sizeof(header->rdevminor)) == 0) {
429 		bid = 0;
430 	}
431 
432 	return (bid);
433 }
434 
435 static int
archive_read_format_tar_options(struct archive_read * a,const char * key,const char * val)436 archive_read_format_tar_options(struct archive_read *a,
437     const char *key, const char *val)
438 {
439 	struct tar *tar;
440 	int ret = ARCHIVE_FAILED;
441 
442 	tar = (struct tar *)(a->format->data);
443 	if (strcmp(key, "compat-2x")  == 0) {
444 		/* Handle UTF-8 filenames as libarchive 2.x */
445 		tar->compat_2x = (val != NULL && val[0] != 0);
446 		tar->init_default_conversion = tar->compat_2x;
447 		return (ARCHIVE_OK);
448 	} else if (strcmp(key, "hdrcharset")  == 0) {
449 		if (val == NULL || val[0] == 0)
450 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
451 			    "tar: hdrcharset option needs a character-set name");
452 		else {
453 			tar->opt_sconv =
454 			    archive_string_conversion_from_charset(
455 				&a->archive, val, 0);
456 			if (tar->opt_sconv != NULL)
457 				ret = ARCHIVE_OK;
458 			else
459 				ret = ARCHIVE_FATAL;
460 		}
461 		return (ret);
462 	} else if (strcmp(key, "mac-ext") == 0) {
463 		tar->process_mac_extensions = (val != NULL && val[0] != 0);
464 		return (ARCHIVE_OK);
465 	} else if (strcmp(key, "read_concatenated_archives") == 0) {
466 		tar->read_concatenated_archives = (val != NULL && val[0] != 0);
467 		return (ARCHIVE_OK);
468 	}
469 
470 	/* Note: The "warn" return is just to inform the options
471 	 * supervisor that we didn't handle it.  It will generate
472 	 * a suitable error if no one used this option. */
473 	return (ARCHIVE_WARN);
474 }
475 
476 /* utility function- this exists to centralize the logic of tracking
477  * how much unconsumed data we have floating around, and to consume
478  * anything outstanding since we're going to do read_aheads
479  */
480 static int
tar_flush_unconsumed(struct archive_read * a,int64_t * unconsumed)481 tar_flush_unconsumed(struct archive_read *a, int64_t *unconsumed)
482 {
483 	if (*unconsumed) {
484 /*
485 		void *data = (void *)__archive_read_ahead(a, *unconsumed, NULL);
486 		 * this block of code is to poison claimed unconsumed space, ensuring
487 		 * things break if it is in use still.
488 		 * currently it WILL break things, so enable it only for debugging this issue
489 		if (data) {
490 			memset(data, 0xff, *unconsumed);
491 		}
492 */
493 		int64_t consumed = __archive_read_consume(a, *unconsumed);
494 		if (consumed != *unconsumed) {
495 			return (ARCHIVE_FATAL);
496 		}
497 		*unconsumed = 0;
498 	}
499 	return (ARCHIVE_OK);
500 }
501 
502 /*
503  * The function invoked by archive_read_next_header().  This
504  * just sets up a few things and then calls the internal
505  * tar_read_header() function below.
506  */
507 static int
archive_read_format_tar_read_header(struct archive_read * a,struct archive_entry * entry)508 archive_read_format_tar_read_header(struct archive_read *a,
509     struct archive_entry *entry)
510 {
511 	/*
512 	 * When converting tar archives to cpio archives, it is
513 	 * essential that each distinct file have a distinct inode
514 	 * number.  To simplify this, we keep a static count here to
515 	 * assign fake dev/inode numbers to each tar entry.  Note that
516 	 * pax format archives may overwrite this with something more
517 	 * useful.
518 	 *
519 	 * Ideally, we would track every file read from the archive so
520 	 * that we could assign the same dev/ino pair to hardlinks,
521 	 * but the memory required to store a complete lookup table is
522 	 * probably not worthwhile just to support the relatively
523 	 * obscure tar->cpio conversion case.
524 	 */
525 	/* TODO: Move this into `struct tar` to avoid conflicts
526 	 * when reading multiple archives */
527 	static int default_inode;
528 	static int default_dev;
529 	struct tar *tar;
530 	const char *p;
531 	const wchar_t *wp;
532 	int r;
533 	size_t l;
534 	int64_t unconsumed = 0;
535 
536 	/* Assign default device/inode values. */
537 	archive_entry_set_dev(entry, 1 + default_dev); /* Don't use zero. */
538 	archive_entry_set_ino(entry, ++default_inode); /* Don't use zero. */
539 	/* Limit generated st_ino number to 16 bits. */
540 	if (default_inode >= 0xffff) {
541 		++default_dev;
542 		default_inode = 0;
543 	}
544 
545 	tar = (struct tar *)(a->format->data);
546 	tar->entry_offset = 0;
547 	gnu_clear_sparse_list(tar);
548 	tar->size_fields = 0; /* We don't have any size info yet */
549 
550 	/* Setup default string conversion. */
551 	tar->sconv = tar->opt_sconv;
552 	if (tar->sconv == NULL) {
553 		if (!tar->init_default_conversion) {
554 			tar->sconv_default =
555 			    archive_string_default_conversion_for_read(&(a->archive));
556 			tar->init_default_conversion = 1;
557 		}
558 		tar->sconv = tar->sconv_default;
559 	}
560 
561 	r = tar_read_header(a, tar, entry, &unconsumed);
562 
563 	tar_flush_unconsumed(a, &unconsumed);
564 
565 	/*
566 	 * "non-sparse" files are really just sparse files with
567 	 * a single block.
568 	 */
569 	if (tar->sparse_list == NULL) {
570 		if (gnu_add_sparse_entry(a, tar, 0, tar->entry_bytes_remaining)
571 		    != ARCHIVE_OK)
572 			return (ARCHIVE_FATAL);
573 	} else {
574 		struct sparse_block *sb;
575 
576 		for (sb = tar->sparse_list; sb != NULL; sb = sb->next) {
577 			if (!sb->hole)
578 				archive_entry_sparse_add_entry(entry,
579 				    sb->offset, sb->remaining);
580 		}
581 	}
582 
583 	if (r == ARCHIVE_OK && archive_entry_filetype(entry) == AE_IFREG) {
584 		/*
585 		 * "Regular" entry with trailing '/' is really
586 		 * directory: This is needed for certain old tar
587 		 * variants and even for some broken newer ones.
588 		 */
589 		if ((wp = archive_entry_pathname_w(entry)) != NULL) {
590 			l = wcslen(wp);
591 			if (l > 0 && wp[l - 1] == L'/') {
592 				archive_entry_set_filetype(entry, AE_IFDIR);
593 				tar->entry_bytes_remaining = 0;
594 				tar->entry_padding = 0;
595 			}
596 		} else if ((p = archive_entry_pathname(entry)) != NULL) {
597 			l = strlen(p);
598 			if (l > 0 && p[l - 1] == '/') {
599 				archive_entry_set_filetype(entry, AE_IFDIR);
600 				tar->entry_bytes_remaining = 0;
601 				tar->entry_padding = 0;
602 			}
603 		}
604 	}
605 	return (r);
606 }
607 
608 static int
archive_read_format_tar_read_data(struct archive_read * a,const void ** buff,size_t * size,int64_t * offset)609 archive_read_format_tar_read_data(struct archive_read *a,
610     const void **buff, size_t *size, int64_t *offset)
611 {
612 	ssize_t bytes_read;
613 	struct tar *tar;
614 	struct sparse_block *p;
615 
616 	tar = (struct tar *)(a->format->data);
617 
618 	for (;;) {
619 		/* Remove exhausted entries from sparse list. */
620 		while (tar->sparse_list != NULL &&
621 		    tar->sparse_list->remaining == 0) {
622 			p = tar->sparse_list;
623 			tar->sparse_list = p->next;
624 			free(p);
625 		}
626 
627 		if (tar->entry_bytes_unconsumed) {
628 			__archive_read_consume(a, tar->entry_bytes_unconsumed);
629 			tar->entry_bytes_unconsumed = 0;
630 		}
631 
632 		/* If we're at end of file, return EOF. */
633 		if (tar->sparse_list == NULL ||
634 		    tar->entry_bytes_remaining == 0) {
635 			int64_t request = tar->entry_bytes_remaining +
636 			    tar->entry_padding;
637 
638 			if (__archive_read_consume(a, request) != request)
639 				return (ARCHIVE_FATAL);
640 			tar->entry_padding = 0;
641 			*buff = NULL;
642 			*size = 0;
643 			*offset = tar->disk_size;
644 			return (ARCHIVE_EOF);
645 		}
646 
647 		*buff = __archive_read_ahead(a, 1, &bytes_read);
648 		if (*buff == NULL) {
649 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
650 			    "Truncated tar archive"
651 			    " detected while reading data");
652 			return (ARCHIVE_FATAL);
653 		}
654 		if (bytes_read > tar->entry_bytes_remaining)
655 			bytes_read = (ssize_t)tar->entry_bytes_remaining;
656 		/* Don't read more than is available in the
657 		 * current sparse block. */
658 		if (tar->sparse_list->remaining < bytes_read)
659 			bytes_read = (ssize_t)tar->sparse_list->remaining;
660 		*size = bytes_read;
661 		*offset = tar->sparse_list->offset;
662 		tar->sparse_list->remaining -= bytes_read;
663 		tar->sparse_list->offset += bytes_read;
664 		tar->entry_bytes_remaining -= bytes_read;
665 		tar->entry_bytes_unconsumed = bytes_read;
666 
667 		if (!tar->sparse_list->hole)
668 			return (ARCHIVE_OK);
669 		/* Current is hole data and skip this. */
670 	}
671 }
672 
673 static int
archive_read_format_tar_skip(struct archive_read * a)674 archive_read_format_tar_skip(struct archive_read *a)
675 {
676 	int64_t request;
677 	struct tar* tar;
678 
679 	tar = (struct tar *)(a->format->data);
680 
681 	request = tar->entry_bytes_remaining + tar->entry_padding +
682 	    tar->entry_bytes_unconsumed;
683 
684 	if (__archive_read_consume(a, request) != request)
685 		return (ARCHIVE_FATAL);
686 
687 	tar->entry_bytes_remaining = 0;
688 	tar->entry_bytes_unconsumed = 0;
689 	tar->entry_padding = 0;
690 
691 	/* Free the sparse list. */
692 	gnu_clear_sparse_list(tar);
693 
694 	return (ARCHIVE_OK);
695 }
696 
697 /*
698  * This function resets the accumulated state while reading
699  * a header.
700  */
701 static void
tar_reset_header_state(struct tar * tar)702 tar_reset_header_state(struct tar *tar)
703 {
704 	tar->pax_hdrcharset_utf8 = 1;
705 	tar->sparse_gnu_attributes_seen = 0;
706 	archive_string_empty(&(tar->entry_gname));
707 	archive_string_empty(&(tar->entry_pathname));
708 	archive_string_empty(&(tar->entry_pathname_override));
709 	archive_string_empty(&(tar->entry_uname));
710 	archive_string_empty(&tar->entry_linkpath);
711 }
712 
713 /*
714  * This function reads and interprets all of the headers associated
715  * with a single entry.
716  */
717 static int
tar_read_header(struct archive_read * a,struct tar * tar,struct archive_entry * entry,int64_t * unconsumed)718 tar_read_header(struct archive_read *a, struct tar *tar,
719     struct archive_entry *entry, int64_t *unconsumed)
720 {
721 	ssize_t bytes;
722 	int err = ARCHIVE_OK, err2;
723 	int eof_fatal = 0; /* EOF is okay at some points... */
724 	const char *h;
725 	const struct archive_entry_header_ustar *header;
726 	const struct archive_entry_header_gnutar *gnuheader;
727 
728 	/* Bitmask of what header types we've seen. */
729 	int32_t seen_headers = 0;
730 	static const int32_t seen_A_header = 1;
731 	static const int32_t seen_g_header = 2;
732 	static const int32_t seen_K_header = 4;
733 	static const int32_t seen_L_header = 8;
734 	static const int32_t seen_V_header = 16;
735 	static const int32_t seen_x_header = 32; /* Also X */
736 	static const int32_t seen_mac_metadata = 512;
737 
738 	tar_reset_header_state(tar);
739 
740 	/* Ensure format is set. */
741 	if (a->archive.archive_format_name == NULL) {
742 		a->archive.archive_format = ARCHIVE_FORMAT_TAR;
743 		a->archive.archive_format_name = "tar";
744 	}
745 
746 	/*
747 	 * TODO: Write global/default pax options into
748 	 * 'entry' struct here before overwriting with
749 	 * file-specific options.
750 	 */
751 
752 	/* Loop over all the headers needed for the next entry */
753 	for (;;) {
754 
755 		/* Find the next valid header record. */
756 		while (1) {
757 			if (tar_flush_unconsumed(a, unconsumed) != ARCHIVE_OK) {
758 				return (ARCHIVE_FATAL);
759 			}
760 
761 			/* Read 512-byte header record */
762 			h = __archive_read_ahead(a, 512, &bytes);
763 			if (bytes == 0) { /* EOF at a block boundary. */
764 				if (eof_fatal) {
765 					/* We've read a special header already;
766 					 * if there's no regular header, then this is
767 					 * a premature EOF. */
768 					archive_set_error(&a->archive, EINVAL,
769 							  "Damaged tar archive (end-of-archive within a sequence of headers)");
770 					return (ARCHIVE_FATAL);
771 				} else {
772 					return (ARCHIVE_EOF);
773 				}
774 			}
775 			if (h == NULL) {  /* Short block at EOF; this is bad. */
776 				archive_set_error(&a->archive,
777 				    ARCHIVE_ERRNO_FILE_FORMAT,
778 				    "Truncated tar archive"
779 				    " detected while reading next header");
780 				return (ARCHIVE_FATAL);
781 			}
782 			*unconsumed += 512;
783 
784 			if (h[0] == 0 && archive_block_is_null(h)) {
785 				/* We found a NULL block which indicates end-of-archive */
786 
787 				if (tar->read_concatenated_archives) {
788 					/* We're ignoring NULL blocks, so keep going. */
789 					continue;
790 				}
791 
792 				/* Try to consume a second all-null record, as well. */
793 				/* If we can't, that's okay. */
794 				tar_flush_unconsumed(a, unconsumed);
795 				h = __archive_read_ahead(a, 512, NULL);
796 				if (h != NULL && h[0] == 0 && archive_block_is_null(h))
797 						__archive_read_consume(a, 512);
798 
799 				archive_clear_error(&a->archive);
800 				return (ARCHIVE_EOF);
801 			}
802 
803 			/* This is NOT a null block, so it must be a valid header. */
804 			if (!checksum(a, h)) {
805 				if (tar_flush_unconsumed(a, unconsumed) != ARCHIVE_OK) {
806 					return (ARCHIVE_FATAL);
807 				}
808 				archive_set_error(&a->archive, EINVAL,
809 						  "Damaged tar archive (bad header checksum)");
810 				/* If we've read some critical information (pax headers, etc)
811 				 * and _then_ see a bad header, we can't really recover. */
812 				if (eof_fatal) {
813 					return (ARCHIVE_FATAL);
814 				} else {
815 					return (ARCHIVE_RETRY);
816 				}
817 			}
818 			break;
819 		}
820 
821 		/* Determine the format variant. */
822 		header = (const struct archive_entry_header_ustar *)h;
823 		switch(header->typeflag[0]) {
824 		case 'A': /* Solaris tar ACL */
825 			if (seen_headers & seen_A_header) {
826 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
827 						  "Redundant 'A' header");
828 				return (ARCHIVE_FATAL);
829 			}
830 			seen_headers |= seen_A_header;
831 			a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
832 			a->archive.archive_format_name = "Solaris tar";
833 			err2 = header_Solaris_ACL(a, tar, entry, h, unconsumed);
834 			break;
835 		case 'g': /* POSIX-standard 'g' header. */
836 			if (seen_headers & seen_g_header) {
837 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
838 						  "Redundant 'g' header");
839 				return (ARCHIVE_FATAL);
840 			}
841 			seen_headers |= seen_g_header;
842 			a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
843 			a->archive.archive_format_name = "POSIX pax interchange format";
844 			err2 = header_pax_global(a, tar, entry, h, unconsumed);
845 			break;
846 		case 'K': /* Long link name (GNU tar, others) */
847 			if (seen_headers & seen_K_header) {
848 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
849 						  "Damaged archive: Redundant 'K' headers may cause linknames to be incorrect");
850 				err = err_combine(err, ARCHIVE_WARN);
851 			}
852 			seen_headers |= seen_K_header;
853 			a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
854 			a->archive.archive_format_name = "GNU tar format";
855 			err2 = header_gnu_longlink(a, tar, entry, h, unconsumed);
856 			break;
857 		case 'L': /* Long filename (GNU tar, others) */
858 			if (seen_headers & seen_L_header) {
859 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
860 						  "Damaged archive: Redundant 'L' headers may cause filenames to be incorrect");
861 				err = err_combine(err, ARCHIVE_WARN);
862 			}
863 			seen_headers |= seen_L_header;
864 			a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
865 			a->archive.archive_format_name = "GNU tar format";
866 			err2 = header_gnu_longname(a, tar, entry, h, unconsumed);
867 			break;
868 		case 'V': /* GNU volume header */
869 			if (seen_headers & seen_V_header) {
870 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
871 						  "Redundant 'V' header");
872 				err = err_combine(err, ARCHIVE_WARN);
873 			}
874 			seen_headers |= seen_V_header;
875 			a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
876 			a->archive.archive_format_name = "GNU tar format";
877 			err2 = header_volume(a, tar, entry, h, unconsumed);
878 			break;
879 		case 'X': /* Used by SUN tar; same as 'x'. */
880 			if (seen_headers & seen_x_header) {
881 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
882 						  "Redundant 'X'/'x' header");
883 				return (ARCHIVE_FATAL);
884 			}
885 			seen_headers |= seen_x_header;
886 			a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
887 			a->archive.archive_format_name =
888 				"POSIX pax interchange format (Sun variant)";
889 			err2 = header_pax_extension(a, tar, entry, h, unconsumed);
890 			break;
891 		case 'x': /* POSIX-standard 'x' header. */
892 			if (seen_headers & seen_x_header) {
893 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
894 						  "Redundant 'x' header");
895 				return (ARCHIVE_FATAL);
896 			}
897 			seen_headers |= seen_x_header;
898 			a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
899 			a->archive.archive_format_name = "POSIX pax interchange format";
900 			err2 = header_pax_extension(a, tar, entry, h, unconsumed);
901 			break;
902 		default: /* Regular header: Legacy tar, GNU tar, or ustar */
903 			gnuheader = (const struct archive_entry_header_gnutar *)h;
904 			if (memcmp(gnuheader->magic, "ustar  \0", 8) == 0) {
905 				a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
906 				a->archive.archive_format_name = "GNU tar format";
907 				err2 = header_gnutar(a, tar, entry, h, unconsumed);
908 			} else if (memcmp(header->magic, "ustar", 5) == 0) {
909 				if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
910 					a->archive.archive_format = ARCHIVE_FORMAT_TAR_USTAR;
911 					a->archive.archive_format_name = "POSIX ustar format";
912 				}
913 				err2 = header_ustar(a, tar, entry, h);
914 			} else {
915 				a->archive.archive_format = ARCHIVE_FORMAT_TAR;
916 				a->archive.archive_format_name = "tar (non-POSIX)";
917 				err2 = header_old_tar(a, tar, entry, h);
918 			}
919 			err = err_combine(err, err2);
920 			/* We return warnings or success as-is.  Anything else is fatal. */
921 			if (err < ARCHIVE_WARN) {
922 				return (ARCHIVE_FATAL);
923 			}
924 			/* Filename of the form `._filename` is an AppleDouble
925 			 * extension entry.  The body is the macOS metadata blob;
926 			 * this is followed by another entry with the actual
927 			 * regular file data.
928 			 * This design has two drawbacks:
929 			 * = it's brittle; you might just have a file with such a name
930 			 * = it duplicates any long pathname extensions
931 			 *
932 			 * TODO: This probably shouldn't be here at all.  Consider
933 			 * just returning the contents as a regular entry here and
934 			 * then dealing with it when we write data to disk.
935 			 */
936 			if (tar->process_mac_extensions
937 			    && ((seen_headers & seen_mac_metadata) == 0)
938 			    && is_mac_metadata_entry(entry)) {
939 				err2 = read_mac_metadata_blob(a, entry, unconsumed);
940 				if (err2 < ARCHIVE_WARN) {
941 					return (ARCHIVE_FATAL);
942 				}
943 				err = err_combine(err, err2);
944 				/* Note: Other headers can appear again. */
945 				seen_headers = seen_mac_metadata;
946 				tar_reset_header_state(tar);
947 				break;
948 			}
949 
950 			/* Reconcile GNU sparse attributes */
951 			if (tar->sparse_gnu_attributes_seen) {
952 				/* Only 'S' (GNU sparse) and ustar '0' regular files can be sparse */
953 				if (tar->filetype != 'S' && tar->filetype != '0') {
954 					archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
955 							  "Non-regular file cannot be sparse");
956 					return (ARCHIVE_WARN);
957 				} else if (tar->sparse_gnu_major == 0 &&
958 				    tar->sparse_gnu_minor == 0) {
959 					/* Sparse map already parsed from 'x' header */
960 				} else if (tar->sparse_gnu_major == 0 &&
961 				    tar->sparse_gnu_minor == 1) {
962 					/* Sparse map already parsed from 'x' header */
963 				} else if (tar->sparse_gnu_major == 1 &&
964 				    tar->sparse_gnu_minor == 0) {
965 					/* Sparse map is prepended to file contents */
966 					ssize_t bytes_read;
967 					bytes_read = gnu_sparse_10_read(a, tar, unconsumed);
968 					if (bytes_read < 0)
969 						return ((int)bytes_read);
970 					tar->entry_bytes_remaining -= bytes_read;
971 				} else {
972 					archive_set_error(&a->archive,
973 							  ARCHIVE_ERRNO_MISC,
974 							  "Unrecognized GNU sparse file format");
975 					return (ARCHIVE_WARN);
976 				}
977 			}
978 			return (err);
979 		}
980 
981 		/* We're between headers ... */
982 		err = err_combine(err, err2);
983 		if (err == ARCHIVE_FATAL)
984 			return (err);
985 
986 		/* The GNU volume header and the pax `g` global header
987 		 * are both allowed to be the only header in an
988 		 * archive.  If we've seen any other header, a
989 		 * following EOF is fatal. */
990 		if ((seen_headers & ~seen_V_header & ~seen_g_header) != 0) {
991 			eof_fatal = 1;
992 		}
993 	}
994 }
995 
996 /*
997  * Return true if block checksum is correct.
998  */
999 static int
checksum(struct archive_read * a,const void * h)1000 checksum(struct archive_read *a, const void *h)
1001 {
1002 	const unsigned char *bytes;
1003 	const struct archive_entry_header_ustar	*header;
1004 	int check, sum;
1005 	size_t i;
1006 
1007 	(void)a; /* UNUSED */
1008 	bytes = (const unsigned char *)h;
1009 	header = (const struct archive_entry_header_ustar *)h;
1010 
1011 	/* Checksum field must hold an octal number */
1012 	for (i = 0; i < sizeof(header->checksum); ++i) {
1013 		char c = header->checksum[i];
1014 		if (c != ' ' && c != '\0' && (c < '0' || c > '7'))
1015 			return 0;
1016 	}
1017 
1018 	/*
1019 	 * Test the checksum.  Note that POSIX specifies _unsigned_
1020 	 * bytes for this calculation.
1021 	 */
1022 	sum = (int)tar_atol(header->checksum, sizeof(header->checksum));
1023 	check = 0;
1024 	for (i = 0; i < 148; i++)
1025 		check += (unsigned char)bytes[i];
1026 	for (; i < 156; i++)
1027 		check += 32;
1028 	for (; i < 512; i++)
1029 		check += (unsigned char)bytes[i];
1030 	if (sum == check)
1031 		return (1);
1032 
1033 	/*
1034 	 * Repeat test with _signed_ bytes, just in case this archive
1035 	 * was created by an old BSD, Solaris, or HP-UX tar with a
1036 	 * broken checksum calculation.
1037 	 */
1038 	check = 0;
1039 	for (i = 0; i < 148; i++)
1040 		check += (signed char)bytes[i];
1041 	for (; i < 156; i++)
1042 		check += 32;
1043 	for (; i < 512; i++)
1044 		check += (signed char)bytes[i];
1045 	if (sum == check)
1046 		return (1);
1047 
1048 #if DONT_FAIL_ON_CRC_ERROR
1049 	/* Speed up fuzzing by pretending the checksum is always right. */
1050 	return (1);
1051 #else
1052 	return (0);
1053 #endif
1054 }
1055 
1056 /*
1057  * Return true if this block contains only nulls.
1058  */
1059 static int
archive_block_is_null(const char * p)1060 archive_block_is_null(const char *p)
1061 {
1062 	unsigned i;
1063 
1064 	for (i = 0; i < 512; i++)
1065 		if (*p++)
1066 			return (0);
1067 	return (1);
1068 }
1069 
1070 /*
1071  * Interpret 'A' Solaris ACL header
1072  */
1073 static int
header_Solaris_ACL(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const void * h,int64_t * unconsumed)1074 header_Solaris_ACL(struct archive_read *a, struct tar *tar,
1075     struct archive_entry *entry, const void *h, int64_t *unconsumed)
1076 {
1077 	const struct archive_entry_header_ustar *header;
1078 	struct archive_string	 acl_text;
1079 	size_t size;
1080 	int err, acl_type;
1081 	uint64_t type;
1082 	char *acl, *p;
1083 
1084 	header = (const struct archive_entry_header_ustar *)h;
1085 	size = (size_t)tar_atol(header->size, sizeof(header->size));
1086 	archive_string_init(&acl_text);
1087 	err = read_body_to_string(a, tar, &acl_text, h, unconsumed);
1088 	if (err != ARCHIVE_OK) {
1089 		archive_string_free(&acl_text);
1090 		return (err);
1091 	}
1092 
1093 	/* TODO: Examine the first characters to see if this
1094 	 * is an AIX ACL descriptor.  We'll likely never support
1095 	 * them, but it would be polite to recognize and warn when
1096 	 * we do see them. */
1097 
1098 	/* Leading octal number indicates ACL type and number of entries. */
1099 	p = acl = acl_text.s;
1100 	type = 0;
1101 	while (*p != '\0' && p < acl + size) {
1102 		if (*p < '0' || *p > '7') {
1103 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1104 			    "Malformed Solaris ACL attribute (invalid digit)");
1105 			archive_string_free(&acl_text);
1106 			return(ARCHIVE_WARN);
1107 		}
1108 		type <<= 3;
1109 		type += *p - '0';
1110 		if (type > 077777777) {
1111 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1112 			    "Malformed Solaris ACL attribute (count too large)");
1113 			archive_string_free(&acl_text);
1114 			return (ARCHIVE_WARN);
1115 		}
1116 		p++;
1117 	}
1118 	switch (type & ~0777777) {
1119 	case 01000000:
1120 		/* POSIX.1e ACL */
1121 		acl_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS;
1122 		break;
1123 	case 03000000:
1124 		/* NFSv4 ACL */
1125 		acl_type = ARCHIVE_ENTRY_ACL_TYPE_NFS4;
1126 		break;
1127 	default:
1128 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1129 		    "Malformed Solaris ACL attribute (unsupported type %llu)",
1130 		    (unsigned long long)type);
1131 		archive_string_free(&acl_text);
1132 		return (ARCHIVE_WARN);
1133 	}
1134 	p++;
1135 
1136 	if (p >= acl + size) {
1137 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1138 		    "Malformed Solaris ACL attribute (body overflow)");
1139 		archive_string_free(&acl_text);
1140 		return(ARCHIVE_WARN);
1141 	}
1142 
1143 	/* ACL text is null-terminated; find the end. */
1144 	size -= (p - acl);
1145 	acl = p;
1146 
1147 	while (*p != '\0' && p < acl + size)
1148 		p++;
1149 
1150 	if (tar->sconv_acl == NULL) {
1151 		tar->sconv_acl = archive_string_conversion_from_charset(
1152 		    &(a->archive), "UTF-8", 1);
1153 		if (tar->sconv_acl == NULL) {
1154 			archive_string_free(&acl_text);
1155 			return (ARCHIVE_FATAL);
1156 		}
1157 	}
1158 	archive_strncpy(&(tar->localname), acl, p - acl);
1159 	err = archive_acl_from_text_l(archive_entry_acl(entry),
1160 	    tar->localname.s, acl_type, tar->sconv_acl);
1161 	/* Workaround: Force perm_is_set() to be correct */
1162 	/* If this bit were stored in the ACL, this wouldn't be needed */
1163 	archive_entry_set_perm(entry, archive_entry_perm(entry));
1164 	if (err != ARCHIVE_OK) {
1165 		if (errno == ENOMEM) {
1166 			archive_set_error(&a->archive, ENOMEM,
1167 			    "Can't allocate memory for ACL");
1168 		} else
1169 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1170 			    "Malformed Solaris ACL attribute (unparsable)");
1171 	}
1172 	archive_string_free(&acl_text);
1173 	return (err);
1174 }
1175 
1176 /*
1177  * Interpret 'K' long linkname header.
1178  */
1179 static int
header_gnu_longlink(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const void * h,int64_t * unconsumed)1180 header_gnu_longlink(struct archive_read *a, struct tar *tar,
1181     struct archive_entry *entry, const void *h, int64_t *unconsumed)
1182 {
1183 	int err;
1184 
1185 	struct archive_string linkpath;
1186 	archive_string_init(&linkpath);
1187 	err = read_body_to_string(a, tar, &linkpath, h, unconsumed);
1188 	if (err == ARCHIVE_OK) {
1189 		archive_entry_set_link(entry, linkpath.s);
1190 	}
1191 	archive_string_free(&linkpath);
1192 	return (err);
1193 }
1194 
1195 static int
set_conversion_failed_error(struct archive_read * a,struct archive_string_conv * sconv,const char * name)1196 set_conversion_failed_error(struct archive_read *a,
1197     struct archive_string_conv *sconv, const char *name)
1198 {
1199 	if (errno == ENOMEM) {
1200 		archive_set_error(&a->archive, ENOMEM,
1201 		    "Can't allocate memory for %s", name);
1202 		return (ARCHIVE_FATAL);
1203 	}
1204 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1205 	    "%s can't be converted from %s to current locale.",
1206 	    name, archive_string_conversion_charset_name(sconv));
1207 	return (ARCHIVE_WARN);
1208 }
1209 
1210 /*
1211  * Interpret 'L' long filename header.
1212  */
1213 static int
header_gnu_longname(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const void * h,int64_t * unconsumed)1214 header_gnu_longname(struct archive_read *a, struct tar *tar,
1215     struct archive_entry *entry, const void *h, int64_t *unconsumed)
1216 {
1217 	int err;
1218 	struct archive_string longname;
1219 
1220 	archive_string_init(&longname);
1221 	err = read_body_to_string(a, tar, &longname, h, unconsumed);
1222 	if (err == ARCHIVE_OK) {
1223 		if (archive_entry_copy_pathname_l(entry, longname.s,
1224 		    archive_strlen(&longname), tar->sconv) != 0)
1225 			err = set_conversion_failed_error(a, tar->sconv, "Pathname");
1226 	}
1227 	archive_string_free(&longname);
1228 	return (err);
1229 }
1230 
1231 /*
1232  * Interpret 'V' GNU tar volume header.
1233  */
1234 static int
header_volume(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const void * h,int64_t * unconsumed)1235 header_volume(struct archive_read *a, struct tar *tar,
1236     struct archive_entry *entry, const void *h, int64_t *unconsumed)
1237 {
1238 	const struct archive_entry_header_ustar *header;
1239 	int64_t size, to_consume;
1240 
1241 	(void)a; /* UNUSED */
1242 	(void)tar; /* UNUSED */
1243 	(void)entry; /* UNUSED */
1244 
1245 	header = (const struct archive_entry_header_ustar *)h;
1246 	size = tar_atol(header->size, sizeof(header->size));
1247 	if (size < 0 || size > (int64_t)pathname_limit) {
1248 		return (ARCHIVE_FATAL);
1249 	}
1250 	to_consume = ((size + 511) & ~511);
1251 	*unconsumed += to_consume;
1252 	return (ARCHIVE_OK);
1253 }
1254 
1255 /*
1256  * Read the next `size` bytes into the provided string.
1257  * Null-terminate the string.
1258  */
1259 static int
read_bytes_to_string(struct archive_read * a,struct archive_string * as,size_t size,int64_t * unconsumed)1260 read_bytes_to_string(struct archive_read *a,
1261 		     struct archive_string *as, size_t size,
1262 		     int64_t *unconsumed) {
1263 	const void *src;
1264 
1265 	/* Fail if we can't make our buffer big enough. */
1266 	if (archive_string_ensure(as, size + 1) == NULL) {
1267 		archive_set_error(&a->archive, ENOMEM,
1268 		    "No memory");
1269 		return (ARCHIVE_FATAL);
1270 	}
1271 
1272 	if (tar_flush_unconsumed(a, unconsumed) != ARCHIVE_OK) {
1273 		return (ARCHIVE_FATAL);
1274 	}
1275 
1276 	/* Read the body into the string. */
1277 	src = __archive_read_ahead(a, size, NULL);
1278 	if (src == NULL) {
1279 		archive_set_error(&a->archive, EINVAL,
1280 		    "Truncated archive"
1281 		    " detected while reading metadata");
1282 		*unconsumed = 0;
1283 		return (ARCHIVE_FATAL);
1284 	}
1285 	memcpy(as->s, src, size);
1286 	as->s[size] = '\0';
1287 	as->length = size;
1288 	*unconsumed += size;
1289 	return (ARCHIVE_OK);
1290 }
1291 
1292 /*
1293  * Read body of an archive entry into an archive_string object.
1294  */
1295 static int
read_body_to_string(struct archive_read * a,struct tar * tar,struct archive_string * as,const void * h,int64_t * unconsumed)1296 read_body_to_string(struct archive_read *a, struct tar *tar,
1297     struct archive_string *as, const void *h, int64_t *unconsumed)
1298 {
1299 	int64_t size;
1300 	const struct archive_entry_header_ustar *header;
1301 	int r;
1302 
1303 	(void)tar; /* UNUSED */
1304 	header = (const struct archive_entry_header_ustar *)h;
1305 	size  = tar_atol(header->size, sizeof(header->size));
1306 	if (size < 0 || size > entry_limit) {
1307 		archive_set_error(&a->archive, EINVAL,
1308 		    "Special header has invalid size: %lld",
1309 		    (long long)size);
1310 		return (ARCHIVE_FATAL);
1311 	}
1312 	if (size > (int64_t)pathname_limit) {
1313 		archive_string_empty(as);
1314 		int64_t to_consume = ((size + 511) & ~511);
1315 		if (to_consume != __archive_read_consume(a, to_consume)) {
1316 			return (ARCHIVE_FATAL);
1317 		}
1318 		archive_set_error(&a->archive, EINVAL,
1319 		    "Special header too large: %lld > 1MiB",
1320 		    (long long)size);
1321 		return (ARCHIVE_WARN);
1322 	}
1323 	r = read_bytes_to_string(a, as, size, unconsumed);
1324 	*unconsumed += 0x1ff & (-size);
1325 	return(r);
1326 }
1327 
1328 /*
1329  * Parse out common header elements.
1330  *
1331  * This would be the same as header_old_tar, except that the
1332  * filename is handled slightly differently for old and POSIX
1333  * entries  (POSIX entries support a 'prefix').  This factoring
1334  * allows header_old_tar and header_ustar
1335  * to handle filenames differently, while still putting most of the
1336  * common parsing into one place.
1337  *
1338  * This is called _after_ ustar, GNU tar, Schily, etc, special
1339  * fields have already been parsed into the `tar` structure.
1340  * So we can make final decisions here about how to reconcile
1341  * size, mode, etc, information.
1342  */
1343 static int
header_common(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const void * h)1344 header_common(struct archive_read *a, struct tar *tar,
1345     struct archive_entry *entry, const void *h)
1346 {
1347 	const struct archive_entry_header_ustar	*header;
1348 	const char *existing_linkpath;
1349 	const wchar_t *existing_wcs_linkpath;
1350 	int     err = ARCHIVE_OK;
1351 
1352 	header = (const struct archive_entry_header_ustar *)h;
1353 
1354 	/* Parse out the numeric fields (all are octal) */
1355 
1356 	/* Split mode handling: Set filetype always, perm only if not already set */
1357 	archive_entry_set_filetype(entry,
1358 	    (mode_t)tar_atol(header->mode, sizeof(header->mode)));
1359 	if (!archive_entry_perm_is_set(entry)) {
1360 		archive_entry_set_perm(entry,
1361 			(mode_t)tar_atol(header->mode, sizeof(header->mode)));
1362 	}
1363 
1364 	/* Set uid, gid, mtime if not already set */
1365 	if (!archive_entry_uid_is_set(entry)) {
1366 		archive_entry_set_uid(entry, tar_atol(header->uid, sizeof(header->uid)));
1367 	}
1368 	if (!archive_entry_gid_is_set(entry)) {
1369 		archive_entry_set_gid(entry, tar_atol(header->gid, sizeof(header->gid)));
1370 	}
1371 	if (!archive_entry_mtime_is_set(entry)) {
1372 		archive_entry_set_mtime(entry, tar_atol(header->mtime, sizeof(header->mtime)), 0);
1373 	}
1374 
1375 	/* Reconcile the size info. */
1376 	/* First, how big is the file on disk? */
1377 	if ((tar->size_fields & TAR_SIZE_GNU_SPARSE_REALSIZE) != 0) {
1378 		/* GNU sparse format 1.0 uses `GNU.sparse.realsize`
1379 		 * to hold the size of the file on disk. */
1380 		tar->disk_size = tar->GNU_sparse_realsize;
1381 	} else if ((tar->size_fields & TAR_SIZE_GNU_SPARSE_SIZE) != 0
1382 		   && (tar->sparse_gnu_major == 0)) {
1383 		/* GNU sparse format 0.0 and 0.1 use `GNU.sparse.size`
1384 		 * to hold the size of the file on disk. */
1385 		tar->disk_size = tar->GNU_sparse_size;
1386 	} else if ((tar->size_fields & TAR_SIZE_SCHILY_SPARSE_REALSIZE) != 0) {
1387 		tar->disk_size = tar->SCHILY_sparse_realsize;
1388 	} else if ((tar->size_fields & TAR_SIZE_PAX_SIZE) != 0) {
1389 		tar->disk_size = tar->pax_size;
1390 	} else {
1391 		/* There wasn't a suitable pax header, so use the ustar info */
1392 		tar->disk_size = tar_atol(header->size, sizeof(header->size));
1393 	}
1394 
1395 	if (tar->disk_size < 0) {
1396 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1397 				  "Tar entry has negative file size");
1398 		return (ARCHIVE_FATAL);
1399 	} else if (tar->disk_size > entry_limit) {
1400 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1401 				  "Tar entry size overflow");
1402 		return (ARCHIVE_FATAL);
1403 	} else {
1404 		archive_entry_set_size(entry, tar->disk_size);
1405 	}
1406 
1407 	/* Second, how big is the data in the archive? */
1408 	if ((tar->size_fields & TAR_SIZE_GNU_SPARSE_SIZE) != 0
1409 	    && (tar->sparse_gnu_major == 1)) {
1410 		/* GNU sparse format 1.0 uses `GNU.sparse.size`
1411 		 * to hold the size of the data in the archive. */
1412 		tar->entry_bytes_remaining = tar->GNU_sparse_size;
1413 	} else if ((tar->size_fields & TAR_SIZE_PAX_SIZE) != 0) {
1414 		tar->entry_bytes_remaining = tar->pax_size;
1415 	} else {
1416 		tar->entry_bytes_remaining
1417 			= tar_atol(header->size, sizeof(header->size));
1418 	}
1419 	if (tar->entry_bytes_remaining < 0) {
1420 		tar->entry_bytes_remaining = 0;
1421 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1422 				  "Tar entry has negative size");
1423 		return (ARCHIVE_FATAL);
1424 	} else if (tar->entry_bytes_remaining > entry_limit) {
1425 		tar->entry_bytes_remaining = 0;
1426 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1427 				  "Tar entry size overflow");
1428 		return (ARCHIVE_FATAL);
1429 	}
1430 
1431 	/* Handle the tar type flag appropriately. */
1432 	tar->filetype = header->typeflag[0];
1433 
1434 	/*
1435 	 * TODO: If the linkpath came from Pax extension header, then
1436 	 * we should obey the hdrcharset_utf8 flag when converting these.
1437 	 */
1438 	switch (tar->filetype) {
1439 	case '1': /* Hard link */
1440 		archive_entry_set_link_to_hardlink(entry);
1441 		existing_wcs_linkpath = archive_entry_hardlink_w(entry);
1442 		existing_linkpath = archive_entry_hardlink(entry);
1443 		if ((existing_linkpath == NULL || existing_linkpath[0] == '\0')
1444 		    && (existing_wcs_linkpath == NULL || existing_wcs_linkpath[0] == '\0')) {
1445 			struct archive_string linkpath;
1446 			archive_string_init(&linkpath);
1447 			archive_strncpy(&linkpath,
1448 					header->linkname, sizeof(header->linkname));
1449 			if (archive_entry_copy_hardlink_l(entry, linkpath.s,
1450 							  archive_strlen(&linkpath), tar->sconv) != 0) {
1451 				err = set_conversion_failed_error(a, tar->sconv,
1452 								  "Linkname");
1453 				if (err == ARCHIVE_FATAL) {
1454 					archive_string_free(&linkpath);
1455 					return (err);
1456 				}
1457 			}
1458 			archive_string_free(&linkpath);
1459 		}
1460 		/*
1461 		 * The following may seem odd, but: Technically, tar
1462 		 * does not store the file type for a "hard link"
1463 		 * entry, only the fact that it is a hard link.  So, I
1464 		 * leave the type zero normally.  But, pax interchange
1465 		 * format allows hard links to have data, which
1466 		 * implies that the underlying entry is a regular
1467 		 * file.
1468 		 */
1469 		if (archive_entry_size(entry) > 0)
1470 			archive_entry_set_filetype(entry, AE_IFREG);
1471 
1472 		/*
1473 		 * A tricky point: Traditionally, tar readers have
1474 		 * ignored the size field when reading hardlink
1475 		 * entries, and some writers put non-zero sizes even
1476 		 * though the body is empty.  POSIX blessed this
1477 		 * convention in the 1988 standard, but broke with
1478 		 * this tradition in 2001 by permitting hardlink
1479 		 * entries to store valid bodies in pax interchange
1480 		 * format, but not in ustar format.  Since there is no
1481 		 * hard and fast way to distinguish pax interchange
1482 		 * from earlier archives (the 'x' and 'g' entries are
1483 		 * optional, after all), we need a heuristic.
1484 		 */
1485 		if (archive_entry_size(entry) == 0) {
1486 			/* If the size is already zero, we're done. */
1487 		}  else if (a->archive.archive_format
1488 		    == ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
1489 			/* Definitely pax extended; must obey hardlink size. */
1490 		} else if (a->archive.archive_format == ARCHIVE_FORMAT_TAR
1491 		    || a->archive.archive_format == ARCHIVE_FORMAT_TAR_GNUTAR)
1492 		{
1493 			/* Old-style or GNU tar: we must ignore the size. */
1494 			archive_entry_set_size(entry, 0);
1495 			tar->entry_bytes_remaining = 0;
1496 		} else if (archive_read_format_tar_bid(a, 50) > 50) {
1497 			/*
1498 			 * We don't know if it's pax: If the bid
1499 			 * function sees a valid ustar header
1500 			 * immediately following, then let's ignore
1501 			 * the hardlink size.
1502 			 */
1503 			archive_entry_set_size(entry, 0);
1504 			tar->entry_bytes_remaining = 0;
1505 		}
1506 		/*
1507 		 * TODO: There are still two cases I'd like to handle:
1508 		 *   = a ustar non-pax archive with a hardlink entry at
1509 		 *     end-of-archive.  (Look for block of nulls following?)
1510 		 *   = a pax archive that has not seen any pax headers
1511 		 *     and has an entry which is a hardlink entry storing
1512 		 *     a body containing an uncompressed tar archive.
1513 		 * The first is worth addressing; I don't see any reliable
1514 		 * way to deal with the second possibility.
1515 		 */
1516 		break;
1517 	case '2': /* Symlink */
1518 		archive_entry_set_link_to_symlink(entry);
1519 		existing_wcs_linkpath = archive_entry_symlink_w(entry);
1520 		existing_linkpath = archive_entry_symlink(entry);
1521 		if ((existing_linkpath == NULL || existing_linkpath[0] == '\0')
1522 		    && (existing_wcs_linkpath == NULL || existing_wcs_linkpath[0] == '\0')) {
1523 			struct archive_string linkpath;
1524 			archive_string_init(&linkpath);
1525 			archive_strncpy(&linkpath,
1526 					header->linkname, sizeof(header->linkname));
1527 			if (archive_entry_copy_symlink_l(entry, linkpath.s,
1528 			    archive_strlen(&linkpath), tar->sconv) != 0) {
1529 				err = set_conversion_failed_error(a, tar->sconv,
1530 				    "Linkname");
1531 				if (err == ARCHIVE_FATAL) {
1532 					archive_string_free(&linkpath);
1533 					return (err);
1534 				}
1535 			}
1536 			archive_string_free(&linkpath);
1537 		}
1538 		archive_entry_set_filetype(entry, AE_IFLNK);
1539 		archive_entry_set_size(entry, 0);
1540 		tar->entry_bytes_remaining = 0;
1541 		break;
1542 	case '3': /* Character device */
1543 		archive_entry_set_filetype(entry, AE_IFCHR);
1544 		archive_entry_set_size(entry, 0);
1545 		tar->entry_bytes_remaining = 0;
1546 		break;
1547 	case '4': /* Block device */
1548 		archive_entry_set_filetype(entry, AE_IFBLK);
1549 		archive_entry_set_size(entry, 0);
1550 		tar->entry_bytes_remaining = 0;
1551 		break;
1552 	case '5': /* Dir */
1553 		archive_entry_set_filetype(entry, AE_IFDIR);
1554 		archive_entry_set_size(entry, 0);
1555 		tar->entry_bytes_remaining = 0;
1556 		break;
1557 	case '6': /* FIFO device */
1558 		archive_entry_set_filetype(entry, AE_IFIFO);
1559 		archive_entry_set_size(entry, 0);
1560 		tar->entry_bytes_remaining = 0;
1561 		break;
1562 	case 'D': /* GNU incremental directory type */
1563 		/*
1564 		 * No special handling is actually required here.
1565 		 * It might be nice someday to preprocess the file list and
1566 		 * provide it to the client, though.
1567 		 */
1568 		archive_entry_set_filetype(entry, AE_IFDIR);
1569 		break;
1570 	case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
1571 		/*
1572 		 * As far as I can tell, this is just like a regular file
1573 		 * entry, except that the contents should be _appended_ to
1574 		 * the indicated file at the indicated offset.  This may
1575 		 * require some API work to fully support.
1576 		 */
1577 		break;
1578 	case 'N': /* Old GNU "long filename" entry. */
1579 		/* The body of this entry is a script for renaming
1580 		 * previously-extracted entries.  Ugh.  It will never
1581 		 * be supported by libarchive. */
1582 		archive_entry_set_filetype(entry, AE_IFREG);
1583 		break;
1584 	case 'S': /* GNU sparse files */
1585 		/*
1586 		 * Sparse files are really just regular files with
1587 		 * sparse information in the extended area.
1588 		 */
1589 		/* FALLTHROUGH */
1590 	case '0': /* ustar "regular" file */
1591 		/* FALLTHROUGH */
1592 	default: /* Non-standard file types */
1593 		/*
1594 		 * Per POSIX: non-recognized types should always be
1595 		 * treated as regular files.
1596 		 */
1597 		archive_entry_set_filetype(entry, AE_IFREG);
1598 		break;
1599 	}
1600 	return (err);
1601 }
1602 
1603 /*
1604  * Parse out header elements for "old-style" tar archives.
1605  */
1606 static int
header_old_tar(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const void * h)1607 header_old_tar(struct archive_read *a, struct tar *tar,
1608     struct archive_entry *entry, const void *h)
1609 {
1610 	const struct archive_entry_header_ustar	*header;
1611 	int err = ARCHIVE_OK, err2;
1612 
1613 	/*
1614 	 * Copy filename over (to ensure null termination).
1615 	 * Skip if pathname was already set e.g. by header_gnu_longname()
1616 	 */
1617 	header = (const struct archive_entry_header_ustar *)h;
1618 
1619 	const char *existing_pathname = archive_entry_pathname(entry);
1620 	const wchar_t *existing_wcs_pathname = archive_entry_pathname_w(entry);
1621 	if ((existing_pathname == NULL || existing_pathname[0] == '\0')
1622 	    && (existing_wcs_pathname == NULL || existing_wcs_pathname[0] == '\0') &&
1623 	    archive_entry_copy_pathname_l(entry,
1624 	    header->name, sizeof(header->name), tar->sconv) != 0) {
1625 		err = set_conversion_failed_error(a, tar->sconv, "Pathname");
1626 		if (err == ARCHIVE_FATAL)
1627 			return (err);
1628 	}
1629 
1630 	/* Grab rest of common fields */
1631 	err2 = header_common(a, tar, entry, h);
1632 	if (err > err2)
1633 		err = err2;
1634 
1635 	tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1636 	return (err);
1637 }
1638 
1639 /*
1640  * Is this likely an AppleDouble extension?
1641  */
1642 static int
is_mac_metadata_entry(struct archive_entry * entry)1643 is_mac_metadata_entry(struct archive_entry *entry) {
1644 	const char *p, *name;
1645 	const wchar_t *wp, *wname;
1646 
1647 	wname = wp = archive_entry_pathname_w(entry);
1648 	if (wp != NULL) {
1649 		/* Find the last path element. */
1650 		for (; *wp != L'\0'; ++wp) {
1651 			if (wp[0] == '/' && wp[1] != L'\0')
1652 				wname = wp + 1;
1653 		}
1654 		/*
1655 		 * If last path element starts with "._", then
1656 		 * this is a Mac extension.
1657 		 */
1658 		if (wname[0] == L'.' && wname[1] == L'_' && wname[2] != L'\0')
1659 			return 1;
1660 	} else {
1661 		/* Find the last path element. */
1662 		name = p = archive_entry_pathname(entry);
1663 		if (p == NULL)
1664 			return (ARCHIVE_FAILED);
1665 		for (; *p != '\0'; ++p) {
1666 			if (p[0] == '/' && p[1] != '\0')
1667 				name = p + 1;
1668 		}
1669 		/*
1670 		 * If last path element starts with "._", then
1671 		 * this is a Mac extension.
1672 		 */
1673 		if (name[0] == '.' && name[1] == '_' && name[2] != '\0')
1674 			return 1;
1675 	}
1676 	/* Not a mac extension */
1677 	return 0;
1678 }
1679 
1680 /*
1681  * Read a Mac AppleDouble-encoded blob of file metadata,
1682  * if there is one.
1683  *
1684  * TODO: In Libarchive 4, we should consider ripping this
1685  * out -- instead, return a file starting with `._` as
1686  * a regular file and let the client (or archive_write logic)
1687  * handle it.
1688  */
1689 static int
read_mac_metadata_blob(struct archive_read * a,struct archive_entry * entry,int64_t * unconsumed)1690 read_mac_metadata_blob(struct archive_read *a,
1691     struct archive_entry *entry, int64_t *unconsumed)
1692 {
1693 	int64_t size;
1694 	size_t msize;
1695 	const void *data;
1696 
1697  	/* Read the body as a Mac OS metadata blob. */
1698 	size = archive_entry_size(entry);
1699 	msize = (size_t)size;
1700 	if (size < 0 || (uintmax_t)msize != (uintmax_t)size) {
1701 		*unconsumed = 0;
1702 		return (ARCHIVE_FATAL);
1703 	}
1704 
1705 	/* TODO: Should this merely skip the overlarge entry and
1706 	 * WARN?  Or is xattr_limit sufficiently large that we can
1707 	 * safely assume anything larger is malicious? */
1708 	if (size > (int64_t)xattr_limit) {
1709 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1710 		    "Oversized AppleDouble extension has size %llu > %llu",
1711 		    (unsigned long long)size,
1712 		    (unsigned long long)xattr_limit);
1713 		return (ARCHIVE_FATAL);
1714 	}
1715 
1716 	/*
1717 	 * TODO: Look beyond the body here to peek at the next header.
1718 	 * If it's a regular header (not an extension header)
1719 	 * that has the wrong name, just return the current
1720 	 * entry as-is, without consuming the body here.
1721 	 * That would reduce the risk of us mis-identifying
1722 	 * an ordinary file that just happened to have
1723 	 * a name starting with "._".
1724 	 *
1725 	 * Q: Is the above idea really possible?  Even
1726 	 * when there are GNU or pax extension entries?
1727 	 */
1728 	if (tar_flush_unconsumed(a, unconsumed) != ARCHIVE_OK) {
1729 		return (ARCHIVE_FATAL);
1730 	}
1731 	data = __archive_read_ahead(a, msize, NULL);
1732 	if (data == NULL) {
1733 		archive_set_error(&a->archive, EINVAL,
1734 		    "Truncated archive"
1735 		    " detected while reading macOS metadata");
1736 		*unconsumed = 0;
1737 		return (ARCHIVE_FATAL);
1738 	}
1739 	archive_entry_clear(entry);
1740 	archive_entry_copy_mac_metadata(entry, data, msize);
1741 	*unconsumed = (msize + 511) & ~ 511;
1742 	return (ARCHIVE_OK);
1743 }
1744 
1745 /*
1746  * Parse a file header for a pax extended archive entry.
1747  */
1748 static int
header_pax_global(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const void * h,int64_t * unconsumed)1749 header_pax_global(struct archive_read *a, struct tar *tar,
1750     struct archive_entry *entry, const void *h, int64_t *unconsumed)
1751 {
1752 	const struct archive_entry_header_ustar *header;
1753 	int64_t size, to_consume;
1754 
1755 	(void)a; /* UNUSED */
1756 	(void)tar; /* UNUSED */
1757 	(void)entry; /* UNUSED */
1758 
1759 	header = (const struct archive_entry_header_ustar *)h;
1760 	size = tar_atol(header->size, sizeof(header->size));
1761 	if (size < 0 || size > entry_limit) {
1762 		archive_set_error(&a->archive, EINVAL,
1763 		    "Special header has invalid size: %lld",
1764 		    (long long)size);
1765 		return (ARCHIVE_FATAL);
1766 	}
1767 	to_consume = ((size + 511) & ~511);
1768 	*unconsumed += to_consume;
1769 	return (ARCHIVE_OK);
1770 }
1771 
1772 /*
1773  * Parse a file header for a Posix "ustar" archive entry.  This also
1774  * handles "pax" or "extended ustar" entries.
1775  *
1776  * In order to correctly handle pax attributes (which precede this),
1777  * we have to skip parsing any field for which the entry already has
1778  * contents.
1779  */
1780 static int
header_ustar(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const void * h)1781 header_ustar(struct archive_read *a, struct tar *tar,
1782     struct archive_entry *entry, const void *h)
1783 {
1784 	const struct archive_entry_header_ustar	*header;
1785 	struct archive_string as;
1786 	int err = ARCHIVE_OK, r;
1787 
1788 	header = (const struct archive_entry_header_ustar *)h;
1789 
1790 	/* Copy name into an internal buffer to ensure null-termination. */
1791 	const char *existing_pathname = archive_entry_pathname(entry);
1792 	const wchar_t *existing_wcs_pathname = archive_entry_pathname_w(entry);
1793 	if ((existing_pathname == NULL || existing_pathname[0] == '\0')
1794 	    && (existing_wcs_pathname == NULL || existing_wcs_pathname[0] == '\0')) {
1795 		archive_string_init(&as);
1796 		if (header->prefix[0]) {
1797 			archive_strncpy(&as, header->prefix, sizeof(header->prefix));
1798 			if (as.s[archive_strlen(&as) - 1] != '/')
1799 				archive_strappend_char(&as, '/');
1800 			archive_strncat(&as, header->name, sizeof(header->name));
1801 		} else {
1802 			archive_strncpy(&as, header->name, sizeof(header->name));
1803 		}
1804 		if (archive_entry_copy_pathname_l(entry, as.s, archive_strlen(&as),
1805 		    tar->sconv) != 0) {
1806 			err = set_conversion_failed_error(a, tar->sconv, "Pathname");
1807 			if (err == ARCHIVE_FATAL)
1808 				return (err);
1809 		}
1810 		archive_string_free(&as);
1811 	}
1812 
1813 	/* Handle rest of common fields. */
1814 	r = header_common(a, tar, entry, h);
1815 	if (r == ARCHIVE_FATAL)
1816 		return (r);
1817 	if (r < err)
1818 		err = r;
1819 
1820 	/* Handle POSIX ustar fields. */
1821 	const char *existing_uname = archive_entry_uname(entry);
1822 	if (existing_uname == NULL || existing_uname[0] == '\0') {
1823 		if (archive_entry_copy_uname_l(entry,
1824 		    header->uname, sizeof(header->uname), tar->sconv) != 0) {
1825 			err = set_conversion_failed_error(a, tar->sconv, "Uname");
1826 			if (err == ARCHIVE_FATAL)
1827 				return (err);
1828 		}
1829 	}
1830 
1831 	const char *existing_gname = archive_entry_gname(entry);
1832 	if (existing_gname == NULL || existing_gname[0] == '\0') {
1833 		if (archive_entry_copy_gname_l(entry,
1834 		    header->gname, sizeof(header->gname), tar->sconv) != 0) {
1835 			err = set_conversion_failed_error(a, tar->sconv, "Gname");
1836 			if (err == ARCHIVE_FATAL)
1837 				return (err);
1838 		}
1839 	}
1840 
1841 	/* Parse out device numbers only for char and block specials. */
1842 	if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1843 		if (!archive_entry_rdev_is_set(entry)) {
1844 			archive_entry_set_rdevmajor(entry, (dev_t)
1845 			    tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
1846 			archive_entry_set_rdevminor(entry, (dev_t)
1847 			    tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1848 		}
1849 	} else {
1850 		archive_entry_set_rdev(entry, 0);
1851 	}
1852 
1853 	tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1854 
1855 	return (err);
1856 }
1857 
1858 static int
header_pax_extension(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const void * h,int64_t * unconsumed)1859 header_pax_extension(struct archive_read *a, struct tar *tar,
1860     struct archive_entry *entry, const void *h, int64_t *unconsumed)
1861 {
1862 	/* Sanity checks: The largest `x` body I've ever heard of was
1863 	 * a little over 4MB.  So I doubt there has ever been a
1864 	 * well-formed archive with an `x` body over 1GiB.  Similarly,
1865 	 * it seems plausible that no single attribute has ever been
1866 	 * larger than 100MB.  So if we see a larger value here, it's
1867 	 * almost certainly a sign of a corrupted/malicious archive. */
1868 
1869 	/* Maximum sane size for extension body: 1 GiB */
1870 	/* This cannot be raised to larger than 8GiB without
1871 	 * exceeding the maximum size for a standard ustar
1872 	 * entry. */
1873 	const int64_t ext_size_limit = 1024 * 1024 * (int64_t)1024;
1874 	/* Maximum size for a single line/attr: 100 million characters */
1875 	/* This cannot be raised to more than 2GiB without exceeding
1876 	 * a `size_t` on 32-bit platforms. */
1877 	const size_t max_parsed_line_length = 99999999ULL;
1878 	/* Largest attribute prolog:  size + name. */
1879 	const size_t max_size_name = 512;
1880 
1881 	/* Size and padding of the full extension body */
1882 	int64_t ext_size, ext_padding;
1883 	size_t line_length, value_length, name_length;
1884 	ssize_t to_read, did_read;
1885 	const struct archive_entry_header_ustar *header;
1886 	const char *p, *attr_start, *name_start;
1887 	struct archive_string_conv *sconv;
1888 	struct archive_string *pas = NULL;
1889 	struct archive_string attr_name;
1890 	int err = ARCHIVE_OK, r;
1891 
1892 	header = (const struct archive_entry_header_ustar *)h;
1893 	ext_size  = tar_atol(header->size, sizeof(header->size));
1894 	if (ext_size > entry_limit) {
1895 		return (ARCHIVE_FATAL);
1896 	}
1897 	if (ext_size < 0) {
1898 	  archive_set_error(&a->archive, EINVAL,
1899 			    "pax extension header has invalid size: %lld",
1900 			    (long long)ext_size);
1901 	  return (ARCHIVE_FATAL);
1902 	}
1903 
1904 	ext_padding = 0x1ff & (-ext_size);
1905 	if (ext_size > ext_size_limit) {
1906 		/* Consume the pax extension body and return an error */
1907 		if (ext_size + ext_padding != __archive_read_consume(a, ext_size + ext_padding)) {
1908 			return (ARCHIVE_FATAL);
1909 		}
1910 		archive_set_error(&a->archive, EINVAL,
1911 		    "Ignoring oversized pax extensions: %lld > %lld",
1912 		    (long long)ext_size, (long long)ext_size_limit);
1913 		return (ARCHIVE_WARN);
1914 	}
1915 	if (tar_flush_unconsumed(a, unconsumed) != ARCHIVE_OK) {
1916 		return (ARCHIVE_FATAL);
1917 	}
1918 
1919 	/* Parse the size/name of each pax attribute in the body */
1920 	archive_string_init(&attr_name);
1921 	while (ext_size > 0) {
1922 		/* Read enough bytes to parse the size/name of the next attribute */
1923 		to_read = max_size_name;
1924 		if (to_read > ext_size) {
1925 			to_read = ext_size;
1926 		}
1927 		p = __archive_read_ahead(a, to_read, &did_read);
1928 		if (p == NULL) { /* EOF */
1929 			archive_set_error(&a->archive, EINVAL,
1930 					  "Truncated tar archive"
1931 					  " detected while reading pax attribute name");
1932 			return (ARCHIVE_FATAL);
1933 		}
1934 		if (did_read > ext_size) {
1935 			did_read = ext_size;
1936 		}
1937 
1938 		/* Parse size of attribute */
1939 		line_length = 0;
1940 		attr_start = p;
1941 		while (1) {
1942 			if (p >= attr_start + did_read) {
1943 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1944 						  "Ignoring malformed pax attributes: overlarge attribute size field");
1945 				*unconsumed += ext_size + ext_padding;
1946 				return (ARCHIVE_WARN);
1947 			}
1948 			if (*p == ' ') {
1949 				p++;
1950 				break;
1951 			}
1952 			if (*p < '0' || *p > '9') {
1953 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1954 						  "Ignoring malformed pax attributes: malformed attribute size field");
1955 				*unconsumed += ext_size + ext_padding;
1956 				return (ARCHIVE_WARN);
1957 			}
1958 			line_length *= 10;
1959 			line_length += *p - '0';
1960 			if (line_length > max_parsed_line_length) {
1961 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1962 						  "Ignoring malformed pax attribute: size > %lld",
1963 						  (long long)max_parsed_line_length);
1964 				*unconsumed += ext_size + ext_padding;
1965 				return (ARCHIVE_WARN);
1966 			}
1967 			p++;
1968 		}
1969 
1970 		if ((int64_t)line_length > ext_size) {
1971 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1972 						  "Ignoring malformed pax attribute:  %lld > %lld",
1973 						  (long long)line_length, (long long)ext_size);
1974 				*unconsumed += ext_size + ext_padding;
1975 				return (ARCHIVE_WARN);
1976 		}
1977 
1978 		/* Parse name of attribute */
1979 		if (p >= attr_start + did_read
1980 		    || p >= attr_start + line_length
1981 		    || *p == '=') {
1982 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1983 					  "Ignoring malformed pax attributes: empty name found");
1984 			*unconsumed += ext_size + ext_padding;
1985 			return (ARCHIVE_WARN);
1986 		}
1987 		name_start = p;
1988 		while (1) {
1989 			if (p >= attr_start + did_read || p >= attr_start + line_length) {
1990 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1991 						  "Ignoring malformed pax attributes: overlarge attribute name");
1992 				*unconsumed += ext_size + ext_padding;
1993 				return (ARCHIVE_WARN);
1994 			}
1995 			if (*p == '=') {
1996 				break;
1997 			}
1998 			p++;
1999 		}
2000 		name_length = p - name_start;
2001 		p++; // Skip '='
2002 
2003 		// Save the name before we consume it
2004 		archive_strncpy(&attr_name, name_start, name_length);
2005 
2006 		ext_size -= p - attr_start;
2007 		value_length = line_length - (p - attr_start);
2008 
2009 		/* Consume size, name, and `=` */
2010 		*unconsumed += p - attr_start;
2011 		if (tar_flush_unconsumed(a, unconsumed) != ARCHIVE_OK) {
2012 			return (ARCHIVE_FATAL);
2013 		}
2014 
2015 		if (value_length == 0) {
2016 			archive_set_error(&a->archive, EINVAL,
2017 					  "Malformed pax attributes");
2018 			*unconsumed += ext_size + ext_padding;
2019 			return (ARCHIVE_WARN);
2020 		}
2021 
2022 		/* pax_attribute will consume value_length - 1 */
2023 		r = pax_attribute(a, tar, entry, attr_name.s, archive_strlen(&attr_name), value_length - 1, unconsumed);
2024 		ext_size -= value_length - 1;
2025 
2026 		// Release the allocated attr_name (either here or before every return in this function)
2027 		archive_string_free(&attr_name);
2028 
2029 		if (r < ARCHIVE_WARN) {
2030 			*unconsumed += ext_size + ext_padding;
2031 			return (r);
2032 		}
2033 		err = err_combine(err, r);
2034 
2035 		/* Consume the `\n` that follows the pax attribute value. */
2036 		if (tar_flush_unconsumed(a, unconsumed) != ARCHIVE_OK) {
2037 			return (ARCHIVE_FATAL);
2038 		}
2039 		p = __archive_read_ahead(a, 1, &did_read);
2040 		if (p == NULL) {
2041 			archive_set_error(&a->archive, EINVAL,
2042 					  "Truncated tar archive"
2043 					  " detected while completing pax attribute");
2044 			return (ARCHIVE_FATAL);
2045 		}
2046 		if (p[0] != '\n') {
2047 			archive_set_error(&a->archive, EINVAL,
2048 					  "Malformed pax attributes");
2049 			*unconsumed += ext_size + ext_padding;
2050 			return (ARCHIVE_WARN);
2051 		}
2052 		ext_size -= 1;
2053 		*unconsumed += 1;
2054 		if (tar_flush_unconsumed(a, unconsumed) != ARCHIVE_OK) {
2055 			return (ARCHIVE_FATAL);
2056 		}
2057 	}
2058 	*unconsumed += ext_size + ext_padding;
2059 
2060 	/*
2061 	 * Some PAX values -- pathname, linkpath, uname, gname --
2062 	 * can't be copied into the entry until we know the character
2063 	 * set to use:
2064 	 */
2065 	if (!tar->pax_hdrcharset_utf8)
2066 		/* PAX specified "BINARY", so use the default charset */
2067 		sconv = tar->opt_sconv;
2068 	else {
2069 		/* PAX default UTF-8 */
2070 		sconv = archive_string_conversion_from_charset(
2071 		    &(a->archive), "UTF-8", 1);
2072 		if (sconv == NULL)
2073 			return (ARCHIVE_FATAL);
2074 		if (tar->compat_2x)
2075 			archive_string_conversion_set_opt(sconv,
2076 			    SCONV_SET_OPT_UTF8_LIBARCHIVE2X);
2077 	}
2078 
2079 	/* Pathname */
2080 	pas = NULL;
2081 	if (archive_strlen(&(tar->entry_pathname_override)) > 0) {
2082 		/* Prefer GNU.sparse.name attribute if present */
2083 		/* GNU sparse files store a fake name under the standard
2084 		 * "pathname" key. */
2085 		pas = &(tar->entry_pathname_override);
2086 	} else if (archive_strlen(&(tar->entry_pathname)) > 0) {
2087 		/* Use standard "pathname" PAX extension */
2088 		pas = &(tar->entry_pathname);
2089 	}
2090 	if (pas != NULL) {
2091 		if (archive_entry_copy_pathname_l(entry, pas->s,
2092 		    archive_strlen(pas), sconv) != 0) {
2093 			err = set_conversion_failed_error(a, sconv, "Pathname");
2094 			if (err == ARCHIVE_FATAL)
2095 				return (err);
2096 			/* Use raw name without conversion */
2097 			archive_entry_copy_pathname(entry, pas->s);
2098 		}
2099 	}
2100 	/* Uname */
2101 	if (archive_strlen(&(tar->entry_uname)) > 0) {
2102 		if (archive_entry_copy_uname_l(entry, tar->entry_uname.s,
2103 		    archive_strlen(&(tar->entry_uname)), sconv) != 0) {
2104 			err = set_conversion_failed_error(a, sconv, "Uname");
2105 			if (err == ARCHIVE_FATAL)
2106 				return (err);
2107 			/* Use raw name without conversion */
2108 			archive_entry_copy_uname(entry, tar->entry_uname.s);
2109 		}
2110 	}
2111 	/* Gname */
2112 	if (archive_strlen(&(tar->entry_gname)) > 0) {
2113 		if (archive_entry_copy_gname_l(entry, tar->entry_gname.s,
2114 		    archive_strlen(&(tar->entry_gname)), sconv) != 0) {
2115 			err = set_conversion_failed_error(a, sconv, "Gname");
2116 			if (err == ARCHIVE_FATAL)
2117 				return (err);
2118 			/* Use raw name without conversion */
2119 			archive_entry_copy_gname(entry, tar->entry_gname.s);
2120 		}
2121 	}
2122 	/* Linkpath */
2123 	if (archive_strlen(&(tar->entry_linkpath)) > 0) {
2124 		if (archive_entry_copy_link_l(entry, tar->entry_linkpath.s,
2125 		    archive_strlen(&(tar->entry_linkpath)), sconv) != 0) {
2126 			err = set_conversion_failed_error(a, sconv, "Linkpath");
2127 			if (err == ARCHIVE_FATAL)
2128 				return (err);
2129 			/* Use raw name without conversion */
2130 			archive_entry_copy_link(entry, tar->entry_linkpath.s);
2131 		}
2132 	}
2133 
2134 	/* Extension may have given us a corrected `entry_bytes_remaining` for
2135 	 * the main entry; update the padding appropriately. */
2136 	tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
2137 	return (err);
2138 }
2139 
2140 static int
pax_attribute_LIBARCHIVE_xattr(struct archive_entry * entry,const char * name,size_t name_length,const char * value,size_t value_length)2141 pax_attribute_LIBARCHIVE_xattr(struct archive_entry *entry,
2142 	const char *name, size_t name_length, const char *value, size_t value_length)
2143 {
2144 	char *name_decoded;
2145 	void *value_decoded;
2146 	size_t value_len;
2147 
2148 	if (name_length < 1)
2149 		return 3;
2150 
2151 	/* URL-decode name */
2152 	name_decoded = url_decode(name, name_length);
2153 	if (name_decoded == NULL)
2154 		return 2;
2155 
2156 	/* Base-64 decode value */
2157 	value_decoded = base64_decode(value, value_length, &value_len);
2158 	if (value_decoded == NULL) {
2159 		free(name_decoded);
2160 		return 1;
2161 	}
2162 
2163 	archive_entry_xattr_add_entry(entry, name_decoded,
2164 		value_decoded, value_len);
2165 
2166 	free(name_decoded);
2167 	free(value_decoded);
2168 	return 0;
2169 }
2170 
2171 static int
pax_attribute_SCHILY_xattr(struct archive_entry * entry,const char * name,size_t name_length,const char * value,size_t value_length)2172 pax_attribute_SCHILY_xattr(struct archive_entry *entry,
2173 	const char *name, size_t name_length, const char *value, size_t value_length)
2174 {
2175 	if (name_length < 1 || name_length > 128) {
2176 		return 1;
2177 	}
2178 
2179 	char * null_terminated_name = malloc(name_length + 1);
2180 	if (null_terminated_name != NULL) {
2181 		memcpy(null_terminated_name, name, name_length);
2182 		null_terminated_name[name_length] = '\0';
2183 		archive_entry_xattr_add_entry(entry, null_terminated_name, value, value_length);
2184 		free(null_terminated_name);
2185 	}
2186 
2187 	return 0;
2188 }
2189 
2190 static int
pax_attribute_RHT_security_selinux(struct archive_entry * entry,const char * value,size_t value_length)2191 pax_attribute_RHT_security_selinux(struct archive_entry *entry,
2192 	const char *value, size_t value_length)
2193 {
2194 	archive_entry_xattr_add_entry(entry, "security.selinux",
2195             value, value_length);
2196 
2197 	return 0;
2198 }
2199 
2200 static int
pax_attribute_SCHILY_acl(struct archive_read * a,struct tar * tar,struct archive_entry * entry,size_t value_length,int type)2201 pax_attribute_SCHILY_acl(struct archive_read *a, struct tar *tar,
2202 	struct archive_entry *entry, size_t value_length, int type)
2203 {
2204 	int r;
2205 	const char *p;
2206 	const char* errstr;
2207 
2208 	switch (type) {
2209 	case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
2210 		errstr = "SCHILY.acl.access";
2211 		break;
2212 	case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
2213 		errstr = "SCHILY.acl.default";
2214 		break;
2215 	case ARCHIVE_ENTRY_ACL_TYPE_NFS4:
2216 		errstr = "SCHILY.acl.ace";
2217 		break;
2218 	default:
2219 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2220 		    "Unknown ACL type: %d", type);
2221 		return(ARCHIVE_FATAL);
2222 	}
2223 
2224 	if (tar->sconv_acl == NULL) {
2225 		tar->sconv_acl =
2226 		    archive_string_conversion_from_charset(
2227 			&(a->archive), "UTF-8", 1);
2228 		if (tar->sconv_acl == NULL)
2229 			return (ARCHIVE_FATAL);
2230 	}
2231 
2232 	if (value_length > acl_limit) {
2233 		__archive_read_consume(a, value_length);
2234 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2235 				  "Unreasonably large ACL: %llu > %llu",
2236 				  (unsigned long long)value_length,
2237 				  (unsigned long long)acl_limit);
2238 		return (ARCHIVE_WARN);
2239 	}
2240 
2241 	p = __archive_read_ahead(a, value_length, NULL);
2242 	if (p == NULL) {
2243 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2244 				  "Truncated tar archive "
2245 				  "detected while reading ACL data");
2246 		return (ARCHIVE_FATAL);
2247 	}
2248 
2249 	r = archive_acl_from_text_nl(archive_entry_acl(entry), p, value_length,
2250 	    type, tar->sconv_acl);
2251 	__archive_read_consume(a, value_length);
2252 	/* Workaround: Force perm_is_set() to be correct */
2253 	/* If this bit were stored in the ACL, this wouldn't be needed */
2254 	archive_entry_set_perm(entry, archive_entry_perm(entry));
2255 	if (r != ARCHIVE_OK) {
2256 		if (r == ARCHIVE_FATAL) {
2257 			archive_set_error(&a->archive, ENOMEM,
2258 			    "%s %s", "Can't allocate memory for ",
2259 			    errstr);
2260 			return (r);
2261 		}
2262 		archive_set_error(&a->archive,
2263 		    ARCHIVE_ERRNO_MISC, "%s %s", "Parse error: ", errstr);
2264 	}
2265 	return (r);
2266 }
2267 
2268 static int
pax_attribute_read_time(struct archive_read * a,size_t value_length,int64_t * ps,long * pn,int64_t * unconsumed)2269 pax_attribute_read_time(struct archive_read *a, size_t value_length, int64_t *ps, long *pn, int64_t *unconsumed) {
2270 	struct archive_string as;
2271 	int r;
2272 
2273 	if (value_length > 128) {
2274 		__archive_read_consume(a, value_length);
2275 		*ps = 0;
2276 		*pn = 0;
2277 		return (ARCHIVE_FATAL);
2278 	}
2279 
2280 	archive_string_init(&as);
2281 	r = read_bytes_to_string(a, &as, value_length, unconsumed);
2282 	if (r < ARCHIVE_OK) {
2283 		archive_string_free(&as);
2284 		*ps = 0;
2285 		*pn = 0;
2286 		return (r);
2287 	}
2288 
2289 	pax_time(as.s, archive_strlen(&as), ps, pn);
2290 	archive_string_free(&as);
2291 	if (*ps == INT64_MIN) {
2292 		*ps = 0;
2293 		*pn = 0;
2294 		return (ARCHIVE_WARN);
2295 	}
2296 	return (ARCHIVE_OK);
2297 }
2298 
2299 static int
pax_attribute_read_number(struct archive_read * a,size_t value_length,int64_t * result)2300 pax_attribute_read_number(struct archive_read *a, size_t value_length, int64_t *result) {
2301 	struct archive_string as;
2302 	int64_t unconsumed = 0;
2303 	int r;
2304 
2305 	if (value_length > 64) {
2306 		__archive_read_consume(a, value_length);
2307 		*result = 0;
2308 		return (ARCHIVE_FATAL);
2309 	}
2310 
2311 	archive_string_init(&as);
2312 	r = read_bytes_to_string(a, &as, value_length, &unconsumed);
2313 	if (tar_flush_unconsumed(a, &unconsumed) != ARCHIVE_OK) {
2314 		return (ARCHIVE_FATAL);
2315 	}
2316 	if (r < ARCHIVE_OK) {
2317 		archive_string_free(&as);
2318 		*result = 0;
2319 		return (r);
2320 	}
2321 
2322 	*result = tar_atol10(as.s, archive_strlen(&as));
2323 	archive_string_free(&as);
2324 	if (*result < 0 || *result == INT64_MAX) {
2325 		*result = INT64_MAX;
2326 		return (ARCHIVE_WARN);
2327 	}
2328 	return (ARCHIVE_OK);
2329 }
2330 
2331 /*
2332  * Parse a single key=value attribute.
2333  *
2334  * POSIX reserves all-lowercase keywords.  Vendor-specific extensions
2335  * should always have keywords of the form "VENDOR.attribute" In
2336  * particular, it's quite feasible to support many different vendor
2337  * extensions here.  I'm using "LIBARCHIVE" for extensions unique to
2338  * this library.
2339  *
2340  * TODO: Investigate other vendor-specific extensions and see if
2341  * any of them look useful.
2342  */
2343 static int
pax_attribute(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const char * key,size_t key_length,size_t value_length,int64_t * unconsumed)2344 pax_attribute(struct archive_read *a, struct tar *tar, struct archive_entry *entry,
2345 	      const char *key, size_t key_length, size_t value_length, int64_t *unconsumed)
2346 {
2347 	int64_t t;
2348 	long n;
2349 	const char *p;
2350 	ssize_t bytes_read;
2351 	int err = ARCHIVE_OK;
2352 
2353 	switch (key[0]) {
2354 	case 'G':
2355 		/* GNU.* extensions */
2356 		if (key_length > 4 && memcmp(key, "GNU.", 4) == 0) {
2357 			key += 4;
2358 			key_length -= 4;
2359 
2360 			/* GNU.sparse marks the existence of GNU sparse information */
2361 			if (key_length == 6 && memcmp(key, "sparse", 6) == 0) {
2362 				tar->sparse_gnu_attributes_seen = 1;
2363 			}
2364 
2365 			/* GNU.sparse.* extensions */
2366 			else if (key_length > 7 && memcmp(key, "sparse.", 7) == 0) {
2367 				tar->sparse_gnu_attributes_seen = 1;
2368 				key += 7;
2369 				key_length -= 7;
2370 
2371 				/* GNU "0.0" sparse pax format. */
2372 				if (key_length == 9 && memcmp(key, "numblocks", 9) == 0) {
2373 					/* GNU.sparse.numblocks */
2374 					tar->sparse_offset = -1;
2375 					tar->sparse_numbytes = -1;
2376 					tar->sparse_gnu_major = 0;
2377 					tar->sparse_gnu_minor = 0;
2378 				}
2379 				else if (key_length == 6 && memcmp(key, "offset", 6) == 0) {
2380 					/* GNU.sparse.offset */
2381 					if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2382 						tar->sparse_offset = t;
2383 						if (tar->sparse_numbytes != -1) {
2384 							if (gnu_add_sparse_entry(a, tar,
2385 									 tar->sparse_offset, tar->sparse_numbytes)
2386 							    != ARCHIVE_OK)
2387 								return (ARCHIVE_FATAL);
2388 							tar->sparse_offset = -1;
2389 							tar->sparse_numbytes = -1;
2390 						}
2391 					}
2392 					return (err);
2393 				}
2394 				else if (key_length == 8 && memcmp(key, "numbytes", 8) == 0) {
2395 					/* GNU.sparse.numbytes */
2396 					if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2397 						tar->sparse_numbytes = t;
2398 						if (tar->sparse_offset != -1) {
2399 							if (gnu_add_sparse_entry(a, tar,
2400 									 tar->sparse_offset, tar->sparse_numbytes)
2401 							    != ARCHIVE_OK)
2402 								return (ARCHIVE_FATAL);
2403 							tar->sparse_offset = -1;
2404 							tar->sparse_numbytes = -1;
2405 						}
2406 					}
2407 					return (err);
2408 				}
2409 				else if (key_length == 4 && memcmp(key, "size", 4) == 0) {
2410 					/* GNU.sparse.size */
2411 					/* This is either the size of stored entry OR the size of data on disk,
2412 					 * depending on which GNU sparse format version is in use.
2413 					 * Since pax attributes can be in any order, we may not actually
2414 					 * know at this point how to interpret this. */
2415 					if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2416 						tar->GNU_sparse_size = t;
2417 						tar->size_fields |= TAR_SIZE_GNU_SPARSE_SIZE;
2418 					}
2419 					return (err);
2420 				}
2421 
2422 				/* GNU "0.1" sparse pax format. */
2423 				else if (key_length == 3 && memcmp(key, "map", 3) == 0) {
2424 					/* GNU.sparse.map */
2425 					tar->sparse_gnu_major = 0;
2426 					tar->sparse_gnu_minor = 1;
2427 					if (value_length > sparse_map_limit) {
2428 						archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2429 								  "Unreasonably large sparse map: %llu > %llu",
2430 								  (unsigned long long)value_length,
2431 								  (unsigned long long)sparse_map_limit);
2432 						err = ARCHIVE_FAILED;
2433 					} else {
2434 						p = __archive_read_ahead(a, value_length, &bytes_read);
2435 						if (p == NULL) {
2436 							archive_set_error(&a->archive, EINVAL,
2437 									  "Truncated archive"
2438 									  " detected while reading GNU sparse data");
2439 							return (ARCHIVE_FATAL);
2440 						}
2441 						if (gnu_sparse_01_parse(a, tar, p, value_length) != ARCHIVE_OK) {
2442 							err = ARCHIVE_WARN;
2443 						}
2444 					}
2445 					__archive_read_consume(a, value_length);
2446 					return (err);
2447 				}
2448 
2449 				/* GNU "1.0" sparse pax format */
2450 				else if (key_length == 5 && memcmp(key, "major", 5) == 0) {
2451 					/* GNU.sparse.major */
2452 					if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK
2453 					    && t >= 0
2454 					    && t <= 10) {
2455 						tar->sparse_gnu_major = (int)t;
2456 					}
2457 					return (err);
2458 				}
2459 				else if (key_length == 5 && memcmp(key, "minor", 5) == 0) {
2460 					/* GNU.sparse.minor */
2461 					if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK
2462 					    && t >= 0
2463 					    && t <= 10) {
2464 						tar->sparse_gnu_minor = (int)t;
2465 					}
2466 					return (err);
2467 				}
2468 				else if (key_length == 4 && memcmp(key, "name", 4) == 0) {
2469 					/* GNU.sparse.name */
2470 					/*
2471 					 * The real filename; when storing sparse
2472 					 * files, GNU tar puts a synthesized name into
2473 					 * the regular 'path' attribute in an attempt
2474 					 * to limit confusion. ;-)
2475 					 */
2476 					if (value_length > pathname_limit) {
2477 						*unconsumed += value_length;
2478 						err = ARCHIVE_WARN;
2479 					} else {
2480 						err = read_bytes_to_string(a, &(tar->entry_pathname_override),
2481 									   value_length, unconsumed);
2482 					}
2483 					return (err);
2484 				}
2485 				else if (key_length == 8 && memcmp(key, "realsize", 8) == 0) {
2486 					/* GNU.sparse.realsize = size of file on disk */
2487 					if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2488 						tar->GNU_sparse_realsize = t;
2489 						tar->size_fields |= TAR_SIZE_GNU_SPARSE_REALSIZE;
2490 					}
2491 					return (err);
2492 				}
2493 			}
2494 		}
2495 		break;
2496 	case 'L':
2497 		/* LIBARCHIVE extensions */
2498 		if (key_length > 11 && memcmp(key, "LIBARCHIVE.", 11) == 0) {
2499 			key_length -= 11;
2500 			key += 11;
2501 
2502 			/* TODO: Handle arbitrary extended attributes... */
2503 			/*
2504 			  if (strcmp(key, "LIBARCHIVE.xxxxxxx") == 0)
2505 				  archive_entry_set_xxxxxx(entry, value);
2506 			*/
2507 			if (key_length == 12 && memcmp(key, "creationtime", 12) == 0) {
2508 				/* LIBARCHIVE.creationtime */
2509 				if ((err = pax_attribute_read_time(a, value_length, &t, &n, unconsumed)) == ARCHIVE_OK) {
2510 					archive_entry_set_birthtime(entry, t, n);
2511 				}
2512 				return (err);
2513 			}
2514 			else if (key_length == 11 && memcmp(key, "symlinktype", 11) == 0) {
2515 				/* LIBARCHIVE.symlinktype */
2516 				if (value_length < 16) {
2517 					p = __archive_read_ahead(a, value_length, &bytes_read);
2518 					if (p == NULL) {
2519 						archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2520 								  "Truncated tar archive "
2521 								  "detected while reading `symlinktype` attribute");
2522 						return (ARCHIVE_FATAL);
2523 					}
2524 					if (value_length == 4 && memcmp(p, "file", 4) == 0) {
2525 						archive_entry_set_symlink_type(entry,
2526 									       AE_SYMLINK_TYPE_FILE);
2527 					} else if (value_length == 3 && memcmp(p, "dir", 3) == 0) {
2528 							archive_entry_set_symlink_type(entry,
2529 										       AE_SYMLINK_TYPE_DIRECTORY);
2530 					} else {
2531 						archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2532 								  "Unrecognized symlink type");
2533 						err = ARCHIVE_WARN;
2534 					}
2535 				} else {
2536 					archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2537 							  "symlink type is very long"
2538 							  "(longest recognized value is 4 bytes, this is %llu)",
2539 							  (unsigned long long)value_length);
2540 					err = ARCHIVE_WARN;
2541 				}
2542 				__archive_read_consume(a, value_length);
2543 				return (err);
2544 			}
2545 			else if (key_length > 6 && memcmp(key, "xattr.", 6) == 0) {
2546 				key_length -= 6;
2547 				key += 6;
2548 				if (value_length > xattr_limit) {
2549 					err = ARCHIVE_WARN;
2550 				} else {
2551 					p = __archive_read_ahead(a, value_length, &bytes_read);
2552 					if (p == NULL) {
2553 						archive_set_error(&a->archive, EINVAL,
2554 								  "Truncated archive"
2555 								  " detected while reading xattr information");
2556 						return (ARCHIVE_FATAL);
2557 					}
2558 					if (pax_attribute_LIBARCHIVE_xattr(entry, key, key_length, p, value_length)) {
2559 						/* TODO: Unable to parse xattr */
2560 						err = ARCHIVE_WARN;
2561 					}
2562 				}
2563 				__archive_read_consume(a, value_length);
2564 				return (err);
2565 			}
2566 		}
2567 		break;
2568 	case 'R':
2569 		/* GNU tar uses RHT.security header to store SELinux xattrs
2570 		 * SCHILY.xattr.security.selinux == RHT.security.selinux */
2571 		if (key_length == 20 && memcmp(key, "RHT.security.selinux", 20) == 0) {
2572 			if (value_length > xattr_limit) {
2573 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2574 						  "Ignoring unreasonably large security.selinux attribute:"
2575 						  " %llu > %llu",
2576 						  (unsigned long long)value_length,
2577 						  (unsigned long long)xattr_limit);
2578 				/* TODO: Should this be FAILED instead? */
2579 				err = ARCHIVE_WARN;
2580 			} else {
2581 				p = __archive_read_ahead(a, value_length, &bytes_read);
2582 				if (p == NULL) {
2583 					archive_set_error(&a->archive, EINVAL,
2584 							  "Truncated archive"
2585 							  " detected while reading selinux data");
2586 					return (ARCHIVE_FATAL);
2587 				}
2588 				if (pax_attribute_RHT_security_selinux(entry, p, value_length)) {
2589 					/* TODO: Unable to parse xattr */
2590 					err = ARCHIVE_WARN;
2591 				}
2592 			}
2593 			__archive_read_consume(a, value_length);
2594 			return (err);
2595 		}
2596 		break;
2597 	case 'S':
2598 		/* SCHILY.* extensions used by "star" archiver */
2599 		if (key_length > 7 && memcmp(key, "SCHILY.", 7) == 0) {
2600 			key_length -= 7;
2601 			key += 7;
2602 
2603 			if (key_length == 10 && memcmp(key, "acl.access", 10) == 0) {
2604 				err = pax_attribute_SCHILY_acl(a, tar, entry, value_length,
2605 						      ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
2606 				// TODO: Mark mode as set
2607 				return (err);
2608 			}
2609 			else if (key_length == 11 && memcmp(key, "acl.default", 11) == 0) {
2610 				err = pax_attribute_SCHILY_acl(a, tar, entry, value_length,
2611 						      ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
2612 				return (err);
2613 			}
2614 			else if (key_length == 7 && memcmp(key, "acl.ace", 7) == 0) {
2615 				err = pax_attribute_SCHILY_acl(a, tar, entry, value_length,
2616 						      ARCHIVE_ENTRY_ACL_TYPE_NFS4);
2617 				// TODO: Mark mode as set
2618 				return (err);
2619 			}
2620 			else if (key_length == 8 && memcmp(key, "devmajor", 8) == 0) {
2621 				if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2622 					archive_entry_set_rdevmajor(entry, (dev_t)t);
2623 				}
2624 				return (err);
2625 			}
2626 			else if (key_length == 8 && memcmp(key, "devminor", 8) == 0) {
2627 				if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2628 					archive_entry_set_rdevminor(entry, (dev_t)t);
2629 				}
2630 				return (err);
2631 			}
2632 			else if (key_length == 6 && memcmp(key, "fflags", 6) == 0) {
2633 				if (value_length < fflags_limit) {
2634 					p = __archive_read_ahead(a, value_length, &bytes_read);
2635 					if (p == NULL) {
2636 						/* Truncated archive */
2637 						archive_set_error(&a->archive, EINVAL,
2638 								  "Truncated archive"
2639 								  " detected while reading SCHILY.fflags");
2640 						return (ARCHIVE_FATAL);
2641 					}
2642 					archive_entry_copy_fflags_text_len(entry, p, value_length);
2643 					err = ARCHIVE_OK;
2644 				} else {
2645 					/* Overlong fflags field */
2646 					err = ARCHIVE_WARN;
2647 				}
2648 				__archive_read_consume(a, value_length);
2649 				return (err);
2650 			}
2651 			else if (key_length == 3 && memcmp(key, "dev", 3) == 0) {
2652 				if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2653 					archive_entry_set_dev(entry, (dev_t)t);
2654 				}
2655 				return (err);
2656 			}
2657 			else if (key_length == 3 && memcmp(key, "ino", 3) == 0) {
2658 				if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2659 					archive_entry_set_ino(entry, t);
2660 				}
2661 				return (err);
2662 			}
2663 			else if (key_length == 5 && memcmp(key, "nlink", 5) == 0) {
2664 				if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2665 					archive_entry_set_nlink(entry, (unsigned int)t);
2666 				}
2667 				return (err);
2668 			}
2669 			else if (key_length == 8 && memcmp(key, "realsize", 8) == 0) {
2670 				if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2671 					tar->SCHILY_sparse_realsize = t;
2672 					tar->size_fields |= TAR_SIZE_SCHILY_SPARSE_REALSIZE;
2673 				}
2674 				return (err);
2675 			}
2676 			/* TODO: Is there a SCHILY.sparse.size similar to GNU.sparse.size ? */
2677 			else if (key_length > 6 && memcmp(key, "xattr.", 6) == 0) {
2678 				key_length -= 6;
2679 				key += 6;
2680 				if (value_length < xattr_limit) {
2681 					p = __archive_read_ahead(a, value_length, &bytes_read);
2682 					if (p == NULL) {
2683 						archive_set_error(&a->archive, EINVAL,
2684 								  "Truncated archive"
2685 								  " detected while reading SCHILY.xattr");
2686 						return (ARCHIVE_FATAL);
2687 					}
2688 					if (pax_attribute_SCHILY_xattr(entry, key, key_length, p, value_length)) {
2689 						/* TODO: Unable to parse xattr */
2690 						err = ARCHIVE_WARN;
2691 					}
2692 				} else {
2693 					archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2694 							  "Unreasonably large xattr: %llu > %llu",
2695 							  (unsigned long long)value_length,
2696 							  (unsigned long long)xattr_limit);
2697 					err = ARCHIVE_WARN;
2698 				}
2699 				__archive_read_consume(a, value_length);
2700 				return (err);
2701 			}
2702 		}
2703 		/* SUN.* extensions from Solaris tar */
2704 		if (key_length > 4 && memcmp(key, "SUN.", 4) == 0) {
2705 			key_length -= 4;
2706 			key += 4;
2707 
2708 			if (key_length == 9 && memcmp(key, "holesdata", 9) == 0) {
2709 				/* SUN.holesdata */
2710 				if (value_length < sparse_map_limit) {
2711 					p = __archive_read_ahead(a, value_length, &bytes_read);
2712 					if (p == NULL) {
2713 						archive_set_error(&a->archive, EINVAL,
2714 								  "Truncated archive"
2715 								  " detected while reading SUN.holesdata");
2716 						return (ARCHIVE_FATAL);
2717 					}
2718 					err = pax_attribute_SUN_holesdata(a, tar, entry, p, value_length);
2719 					if (err < ARCHIVE_OK) {
2720 						archive_set_error(&a->archive,
2721 								  ARCHIVE_ERRNO_MISC,
2722 								  "Parse error: SUN.holesdata");
2723 					}
2724 				} else {
2725 					archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2726 							  "Unreasonably large sparse map: %llu > %llu",
2727 							  (unsigned long long)value_length,
2728 							  (unsigned long long)sparse_map_limit);
2729 					err = ARCHIVE_FAILED;
2730 				}
2731 				__archive_read_consume(a, value_length);
2732 				return (err);
2733 			}
2734 		}
2735 		break;
2736 	case 'a':
2737 		if (key_length == 5 && memcmp(key, "atime", 5) == 0) {
2738 			if ((err = pax_attribute_read_time(a, value_length, &t, &n, unconsumed)) == ARCHIVE_OK) {
2739 				archive_entry_set_atime(entry, t, n);
2740 			}
2741 			return (err);
2742 		}
2743 		break;
2744 	case 'c':
2745 		if (key_length == 5 && memcmp(key, "ctime", 5) == 0) {
2746 			if ((err = pax_attribute_read_time(a, value_length, &t, &n, unconsumed)) == ARCHIVE_OK) {
2747 				archive_entry_set_ctime(entry, t, n);
2748 			}
2749 			return (err);
2750 		} else if (key_length == 7 && memcmp(key, "charset", 7) == 0) {
2751 			/* TODO: Publish charset information in entry. */
2752 		} else if (key_length == 7 && memcmp(key, "comment", 7) == 0) {
2753 			/* TODO: Publish comment in entry. */
2754 		}
2755 		break;
2756 	case 'g':
2757 		if (key_length == 3 && memcmp(key, "gid", 3) == 0) {
2758 			if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2759 				archive_entry_set_gid(entry, t);
2760 			}
2761 			return (err);
2762 		} else if (key_length == 5 && memcmp(key, "gname", 5) == 0) {
2763 			if (value_length > guname_limit) {
2764 				*unconsumed += value_length;
2765 				err = ARCHIVE_WARN;
2766 			} else {
2767 				err = read_bytes_to_string(a, &(tar->entry_gname), value_length, unconsumed);
2768 			}
2769 			return (err);
2770 		}
2771 		break;
2772 	case 'h':
2773 		if (key_length == 10 && memcmp(key, "hdrcharset", 10) == 0) {
2774 			if (value_length < 64) {
2775 				p = __archive_read_ahead(a, value_length, &bytes_read);
2776 				if (p == NULL) {
2777 					archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2778 							  "Truncated tar archive "
2779 							  "detected while reading hdrcharset attribute");
2780 					return (ARCHIVE_FATAL);
2781 				}
2782 				if (value_length == 6
2783 				    && memcmp(p, "BINARY", 6) == 0) {
2784 					/* Binary  mode. */
2785 					tar->pax_hdrcharset_utf8 = 0;
2786 					err = ARCHIVE_OK;
2787 				} else if (value_length == 23
2788 					   && memcmp(p, "ISO-IR 10646 2000 UTF-8", 23) == 0) {
2789 					tar->pax_hdrcharset_utf8 = 1;
2790 					err = ARCHIVE_OK;
2791 				} else {
2792 					/* TODO: Unrecognized character set */
2793 					err  = ARCHIVE_WARN;
2794 				}
2795 			} else {
2796 				archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2797 						  "hdrcharset attribute is unreasonably large (%llu bytes)",
2798 						  (unsigned long long)value_length);
2799 				err = ARCHIVE_WARN;
2800 			}
2801 			__archive_read_consume(a, value_length);
2802 			return (err);
2803 		}
2804 		break;
2805 	case 'l':
2806 		/* pax interchange doesn't distinguish hardlink vs. symlink. */
2807 		if (key_length == 8 && memcmp(key, "linkpath", 8) == 0) {
2808 			if (value_length > pathname_limit) {
2809 				*unconsumed += value_length;
2810 				err = ARCHIVE_WARN;
2811 			} else {
2812 				err = read_bytes_to_string(a, &tar->entry_linkpath, value_length, unconsumed);
2813 			}
2814 			return (err);
2815 		}
2816 		break;
2817 	case 'm':
2818 		if (key_length == 5 && memcmp(key, "mtime", 5) == 0) {
2819 			if ((err = pax_attribute_read_time(a, value_length, &t, &n, unconsumed)) == ARCHIVE_OK) {
2820 				archive_entry_set_mtime(entry, t, n);
2821 			}
2822 			return (err);
2823 		}
2824 		break;
2825 	case 'p':
2826 		if (key_length == 4 && memcmp(key, "path", 4) == 0) {
2827 			if (value_length > pathname_limit) {
2828 				*unconsumed += value_length;
2829 				err = ARCHIVE_WARN;
2830 			} else {
2831 				err = read_bytes_to_string(a, &(tar->entry_pathname), value_length, unconsumed);
2832 			}
2833 			return (err);
2834 		}
2835 		break;
2836 	case 'r':
2837 		/* POSIX has reserved 'realtime.*' */
2838 		break;
2839 	case 's':
2840 		/* POSIX has reserved 'security.*' */
2841 		/* Someday: if (strcmp(key, "security.acl") == 0) { ... } */
2842 		if (key_length == 4 && memcmp(key, "size", 4) == 0) {
2843 			/* "size" is the size of the data in the entry. */
2844 			if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2845 				tar->pax_size = t;
2846 				tar->size_fields |= TAR_SIZE_PAX_SIZE;
2847 			}
2848 			else if (t == INT64_MAX) {
2849 				/* Note: pax_attr_read_number returns INT64_MAX on overflow or < 0 */
2850 				tar->entry_bytes_remaining = 0;
2851 				archive_set_error(&a->archive,
2852 				    ARCHIVE_ERRNO_MISC,
2853 				    "Tar size attribute overflow");
2854 				return (ARCHIVE_FATAL);
2855 			}
2856 			return (err);
2857 		}
2858 		break;
2859 	case 'u':
2860 		if (key_length == 3 && memcmp(key, "uid", 3) == 0) {
2861 			if ((err = pax_attribute_read_number(a, value_length, &t)) == ARCHIVE_OK) {
2862 				archive_entry_set_uid(entry, t);
2863 			}
2864 			return (err);
2865 		} else if (key_length == 5 && memcmp(key, "uname", 5) == 0) {
2866 			if (value_length > guname_limit) {
2867 				*unconsumed += value_length;
2868 				err = ARCHIVE_WARN;
2869 			} else {
2870 				err = read_bytes_to_string(a, &(tar->entry_uname), value_length, unconsumed);
2871 			}
2872 			return (err);
2873 		}
2874 		break;
2875 	}
2876 
2877 	/* Unrecognized key, just skip the entire value. */
2878 	__archive_read_consume(a, value_length);
2879 	return (err);
2880 }
2881 
2882 
2883 
2884 /*
2885  * Parse a decimal time value, which may include a fractional portion
2886  *
2887  * Sets ps to INT64_MIN on error.
2888  */
2889 static void
pax_time(const char * p,size_t length,int64_t * ps,long * pn)2890 pax_time(const char *p, size_t length, int64_t *ps, long *pn)
2891 {
2892 	char digit;
2893 	int64_t	s;
2894 	unsigned long l;
2895 	int sign;
2896 	int64_t limit, last_digit_limit;
2897 
2898 	limit = INT64_MAX / 10;
2899 	last_digit_limit = INT64_MAX % 10;
2900 
2901 	if (length <= 0) {
2902 		*ps = 0;
2903 		*pn = 0;
2904 		return;
2905 	}
2906 	s = 0;
2907 	sign = 1;
2908 	if (*p == '-') {
2909 		sign = -1;
2910 		p++;
2911 		length--;
2912 	}
2913 	while (length > 0 && *p >= '0' && *p <= '9') {
2914 		digit = *p - '0';
2915 		if (s > limit ||
2916 		    (s == limit && digit > last_digit_limit)) {
2917 			*ps = INT64_MIN;
2918 			*pn = 0;
2919 			return;
2920 		}
2921 		s = (s * 10) + digit;
2922 		++p;
2923 		--length;
2924 	}
2925 
2926 	*ps = s * sign;
2927 
2928 	/* Calculate nanoseconds. */
2929 	*pn = 0;
2930 
2931 	if (length <= 0 || *p != '.')
2932 		return;
2933 
2934 	l = 100000000UL;
2935 	do {
2936 		++p;
2937 		--length;
2938 		if (length > 0 && *p >= '0' && *p <= '9')
2939 			*pn += (*p - '0') * l;
2940 		else
2941 			break;
2942 	} while (l /= 10);
2943 }
2944 
2945 /*
2946  * Parse GNU tar header
2947  */
2948 static int
header_gnutar(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const void * h,int64_t * unconsumed)2949 header_gnutar(struct archive_read *a, struct tar *tar,
2950     struct archive_entry *entry, const void *h, int64_t *unconsumed)
2951 {
2952 	const struct archive_entry_header_gnutar *header;
2953 	int64_t t;
2954 	int err = ARCHIVE_OK;
2955 
2956 	/*
2957 	 * GNU header is like POSIX ustar, except 'prefix' is
2958 	 * replaced with some other fields. This also means the
2959 	 * filename is stored as in old-style archives.
2960 	 */
2961 
2962 	/* Copy filename over (to ensure null termination). */
2963 	header = (const struct archive_entry_header_gnutar *)h;
2964 	const char *existing_pathname = archive_entry_pathname(entry);
2965 	const wchar_t *existing_wcs_pathname = archive_entry_pathname_w(entry);
2966 	if ((existing_pathname == NULL || existing_pathname[0] == '\0')
2967 	    && (existing_wcs_pathname == NULL || existing_wcs_pathname[0] == L'\0')) {
2968 		if (archive_entry_copy_pathname_l(entry,
2969 		    header->name, sizeof(header->name), tar->sconv) != 0) {
2970 			err = set_conversion_failed_error(a, tar->sconv, "Pathname");
2971 			if (err == ARCHIVE_FATAL)
2972 				return (err);
2973 		}
2974 	}
2975 
2976 	/* Fields common to ustar and GNU */
2977 	/* XXX Can the following be factored out since it's common
2978 	 * to ustar and gnu tar?  Is it okay to move it down into
2979 	 * header_common, perhaps?  */
2980 	const char *existing_uname = archive_entry_uname(entry);
2981 	if (existing_uname == NULL || existing_uname[0] == '\0') {
2982 		if (archive_entry_copy_uname_l(entry,
2983 		    header->uname, sizeof(header->uname), tar->sconv) != 0) {
2984 			err = set_conversion_failed_error(a, tar->sconv, "Uname");
2985 			if (err == ARCHIVE_FATAL)
2986 				return (err);
2987 		}
2988 	}
2989 
2990 	const char *existing_gname = archive_entry_gname(entry);
2991 	if (existing_gname == NULL || existing_gname[0] == '\0') {
2992 		if (archive_entry_copy_gname_l(entry,
2993 		    header->gname, sizeof(header->gname), tar->sconv) != 0) {
2994 			err = set_conversion_failed_error(a, tar->sconv, "Gname");
2995 			if (err == ARCHIVE_FATAL)
2996 				return (err);
2997 		}
2998 	}
2999 
3000 	/* Parse out device numbers only for char and block specials */
3001 	if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
3002 		if (!archive_entry_rdev_is_set(entry)) {
3003 			archive_entry_set_rdevmajor(entry, (dev_t)
3004 			    tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
3005 			archive_entry_set_rdevminor(entry, (dev_t)
3006 			    tar_atol(header->rdevminor, sizeof(header->rdevminor)));
3007 		}
3008 	} else {
3009 		archive_entry_set_rdev(entry, 0);
3010 	}
3011 
3012 	/* Grab GNU-specific fields. */
3013 	if (!archive_entry_atime_is_set(entry)) {
3014 		t = tar_atol(header->atime, sizeof(header->atime));
3015 		if (t > 0)
3016 			archive_entry_set_atime(entry, t, 0);
3017 	}
3018 	if (!archive_entry_ctime_is_set(entry)) {
3019 		t = tar_atol(header->ctime, sizeof(header->ctime));
3020 		if (t > 0)
3021 			archive_entry_set_ctime(entry, t, 0);
3022 	}
3023 
3024 	if (header->realsize[0] != 0) {
3025 		/* Treat as a synonym for the pax GNU.sparse.realsize attr */
3026 		tar->GNU_sparse_realsize
3027 		    = tar_atol(header->realsize, sizeof(header->realsize));
3028 		tar->size_fields |= TAR_SIZE_GNU_SPARSE_REALSIZE;
3029 	}
3030 
3031 	if (header->sparse[0].offset[0] != 0) {
3032 		if (gnu_sparse_old_read(a, tar, header, unconsumed)
3033 		    != ARCHIVE_OK)
3034 			return (ARCHIVE_FATAL);
3035 	} else {
3036 		if (header->isextended[0] != 0) {
3037 			/* XXX WTF? XXX */
3038 		}
3039 	}
3040 
3041 	/* Grab fields common to all tar variants. */
3042 	err = header_common(a, tar, entry, h);
3043 	if (err == ARCHIVE_FATAL)
3044 		return (err);
3045 
3046 	tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
3047 
3048 	return (err);
3049 }
3050 
3051 static int
gnu_add_sparse_entry(struct archive_read * a,struct tar * tar,int64_t offset,int64_t remaining)3052 gnu_add_sparse_entry(struct archive_read *a, struct tar *tar,
3053     int64_t offset, int64_t remaining)
3054 {
3055 	struct sparse_block *p;
3056 
3057 	p = calloc(1, sizeof(*p));
3058 	if (p == NULL) {
3059 		archive_set_error(&a->archive, ENOMEM, "Out of memory");
3060 		return (ARCHIVE_FATAL);
3061 	}
3062 	if (tar->sparse_last != NULL)
3063 		tar->sparse_last->next = p;
3064 	else
3065 		tar->sparse_list = p;
3066 	tar->sparse_last = p;
3067 	if (remaining < 0 || offset < 0 || offset > INT64_MAX - remaining) {
3068 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Malformed sparse map data");
3069 		return (ARCHIVE_FATAL);
3070 	}
3071 	p->offset = offset;
3072 	p->remaining = remaining;
3073 	return (ARCHIVE_OK);
3074 }
3075 
3076 static void
gnu_clear_sparse_list(struct tar * tar)3077 gnu_clear_sparse_list(struct tar *tar)
3078 {
3079 	struct sparse_block *p;
3080 
3081 	while (tar->sparse_list != NULL) {
3082 		p = tar->sparse_list;
3083 		tar->sparse_list = p->next;
3084 		free(p);
3085 	}
3086 	tar->sparse_last = NULL;
3087 }
3088 
3089 /*
3090  * GNU tar old-format sparse data.
3091  *
3092  * GNU old-format sparse data is stored in a fixed-field
3093  * format.  Offset/size values are 11-byte octal fields (same
3094  * format as 'size' field in ustart header).  These are
3095  * stored in the header, allocating subsequent header blocks
3096  * as needed.  Extending the header in this way is a pretty
3097  * severe POSIX violation; this design has earned GNU tar a
3098  * lot of criticism.
3099  */
3100 
3101 static int
gnu_sparse_old_read(struct archive_read * a,struct tar * tar,const struct archive_entry_header_gnutar * header,int64_t * unconsumed)3102 gnu_sparse_old_read(struct archive_read *a, struct tar *tar,
3103     const struct archive_entry_header_gnutar *header, int64_t *unconsumed)
3104 {
3105 	ssize_t bytes_read;
3106 	const void *data;
3107 	struct extended {
3108 		struct gnu_sparse sparse[21];
3109 		char	isextended[1];
3110 		char	padding[7];
3111 	};
3112 	const struct extended *ext;
3113 
3114 	if (gnu_sparse_old_parse(a, tar, header->sparse, 4) != ARCHIVE_OK)
3115 		return (ARCHIVE_FATAL);
3116 	if (header->isextended[0] == 0)
3117 		return (ARCHIVE_OK);
3118 
3119 	do {
3120 		if (tar_flush_unconsumed(a, unconsumed) != ARCHIVE_OK) {
3121 			return (ARCHIVE_FATAL);
3122 		}
3123 		data = __archive_read_ahead(a, 512, &bytes_read);
3124 		if (data == NULL) {
3125 			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3126 			    "Truncated tar archive "
3127 			    "detected while reading sparse file data");
3128 			return (ARCHIVE_FATAL);
3129 		}
3130 		*unconsumed = 512;
3131 		ext = (const struct extended *)data;
3132 		if (gnu_sparse_old_parse(a, tar, ext->sparse, 21) != ARCHIVE_OK)
3133 			return (ARCHIVE_FATAL);
3134 	} while (ext->isextended[0] != 0);
3135 	if (tar->sparse_list != NULL)
3136 		tar->entry_offset = tar->sparse_list->offset;
3137 	return (ARCHIVE_OK);
3138 }
3139 
3140 static int
gnu_sparse_old_parse(struct archive_read * a,struct tar * tar,const struct gnu_sparse * sparse,int length)3141 gnu_sparse_old_parse(struct archive_read *a, struct tar *tar,
3142     const struct gnu_sparse *sparse, int length)
3143 {
3144 	while (length > 0 && sparse->offset[0] != 0) {
3145 		if (gnu_add_sparse_entry(a, tar,
3146 		    tar_atol(sparse->offset, sizeof(sparse->offset)),
3147 		    tar_atol(sparse->numbytes, sizeof(sparse->numbytes)))
3148 		    != ARCHIVE_OK)
3149 			return (ARCHIVE_FATAL);
3150 		sparse++;
3151 		length--;
3152 	}
3153 	return (ARCHIVE_OK);
3154 }
3155 
3156 /*
3157  * GNU tar sparse format 0.0
3158  *
3159  * Beginning with GNU tar 1.15, sparse files are stored using
3160  * information in the pax extended header.  The GNU tar maintainers
3161  * have gone through a number of variations in the process of working
3162  * out this scheme; fortunately, they're all numbered.
3163  *
3164  * Sparse format 0.0 uses attribute GNU.sparse.numblocks to store the
3165  * number of blocks, and GNU.sparse.offset/GNU.sparse.numbytes to
3166  * store offset/size for each block.  The repeated instances of these
3167  * latter fields violate the pax specification (which frowns on
3168  * duplicate keys), so this format was quickly replaced.
3169  */
3170 
3171 /*
3172  * GNU tar sparse format 0.1
3173  *
3174  * This version replaced the offset/numbytes attributes with
3175  * a single "map" attribute that stored a list of integers.  This
3176  * format had two problems: First, the "map" attribute could be very
3177  * long, which caused problems for some implementations.  More
3178  * importantly, the sparse data was lost when extracted by archivers
3179  * that didn't recognize this extension.
3180  */
3181 static int
gnu_sparse_01_parse(struct archive_read * a,struct tar * tar,const char * p,size_t length)3182 gnu_sparse_01_parse(struct archive_read *a, struct tar *tar, const char *p, size_t length)
3183 {
3184 	const char *e;
3185 	int64_t offset = -1, size = -1;
3186 
3187 	for (;;) {
3188 		e = p;
3189 		while (length > 0 && *e != ',') {
3190 			if (*e < '0' || *e > '9')
3191 				return (ARCHIVE_WARN);
3192 			e++;
3193 			length--;
3194 		}
3195 		if (offset < 0) {
3196 			offset = tar_atol10(p, e - p);
3197 			if (offset < 0)
3198 				return (ARCHIVE_WARN);
3199 		} else {
3200 			size = tar_atol10(p, e - p);
3201 			if (size < 0)
3202 				return (ARCHIVE_WARN);
3203 			if (gnu_add_sparse_entry(a, tar, offset, size)
3204 			    != ARCHIVE_OK)
3205 				return (ARCHIVE_FATAL);
3206 			offset = -1;
3207 		}
3208 		if (length == 0)
3209 			return (ARCHIVE_OK);
3210 		p = e + 1;
3211 		length--;
3212 	}
3213 }
3214 
3215 /*
3216  * GNU tar sparse format 1.0
3217  *
3218  * The idea: The offset/size data is stored as a series of base-10
3219  * ASCII numbers prepended to the file data, so that dearchivers that
3220  * don't support this format will extract the block map along with the
3221  * data and a separate post-process can restore the sparseness.
3222  *
3223  * Unfortunately, GNU tar 1.16 had a bug that added unnecessary
3224  * padding to the body of the file when using this format.  GNU tar
3225  * 1.17 corrected this bug without bumping the version number, so
3226  * it's not possible to support both variants.  This code supports
3227  * the later variant at the expense of not supporting the former.
3228  *
3229  * This variant also introduced the GNU.sparse.major/GNU.sparse.minor attributes.
3230  */
3231 
3232 /*
3233  * Read the next line from the input, and parse it as a decimal
3234  * integer followed by '\n'.  Returns positive integer value or
3235  * negative on error.
3236  */
3237 static int64_t
gnu_sparse_10_atol(struct archive_read * a,struct tar * tar,int64_t * remaining,int64_t * unconsumed)3238 gnu_sparse_10_atol(struct archive_read *a, struct tar *tar,
3239     int64_t *remaining, int64_t *unconsumed)
3240 {
3241 	int64_t l, limit, last_digit_limit;
3242 	const char *p;
3243 	ssize_t bytes_read;
3244 	int base, digit;
3245 
3246 	base = 10;
3247 	limit = INT64_MAX / base;
3248 	last_digit_limit = INT64_MAX % base;
3249 
3250 	/*
3251 	 * Skip any lines starting with '#'; GNU tar specs
3252 	 * don't require this, but they should.
3253 	 */
3254 	do {
3255 		bytes_read = readline(a, tar, &p,
3256 			(ssize_t)tar_min(*remaining, 100), unconsumed);
3257 		if (bytes_read <= 0)
3258 			return (ARCHIVE_FATAL);
3259 		*remaining -= bytes_read;
3260 	} while (p[0] == '#');
3261 
3262 	l = 0;
3263 	while (bytes_read > 0) {
3264 		if (*p == '\n')
3265 			return (l);
3266 		if (*p < '0' || *p >= '0' + base)
3267 			return (ARCHIVE_WARN);
3268 		digit = *p - '0';
3269 		if (l > limit || (l == limit && digit > last_digit_limit))
3270 			l = INT64_MAX; /* Truncate on overflow. */
3271 		else
3272 			l = (l * base) + digit;
3273 		p++;
3274 		bytes_read--;
3275 	}
3276 	/* TODO: Error message. */
3277 	return (ARCHIVE_WARN);
3278 }
3279 
3280 /*
3281  * Returns length (in bytes) of the sparse data description
3282  * that was read.
3283  */
3284 static int64_t
gnu_sparse_10_read(struct archive_read * a,struct tar * tar,int64_t * unconsumed)3285 gnu_sparse_10_read(struct archive_read *a, struct tar *tar, int64_t *unconsumed)
3286 {
3287 	int64_t bytes_read, entries, offset, size, to_skip, remaining;
3288 
3289 	/* Clear out the existing sparse list. */
3290 	gnu_clear_sparse_list(tar);
3291 
3292 	remaining = tar->entry_bytes_remaining;
3293 
3294 	/* Parse entries. */
3295 	entries = gnu_sparse_10_atol(a, tar, &remaining, unconsumed);
3296 	if (entries < 0)
3297 		return (ARCHIVE_FATAL);
3298 	/* Parse the individual entries. */
3299 	while (entries-- > 0) {
3300 		/* Parse offset/size */
3301 		offset = gnu_sparse_10_atol(a, tar, &remaining, unconsumed);
3302 		if (offset < 0)
3303 			return (ARCHIVE_FATAL);
3304 		size = gnu_sparse_10_atol(a, tar, &remaining, unconsumed);
3305 		if (size < 0)
3306 			return (ARCHIVE_FATAL);
3307 		/* Add a new sparse entry. */
3308 		if (gnu_add_sparse_entry(a, tar, offset, size) != ARCHIVE_OK)
3309 			return (ARCHIVE_FATAL);
3310 	}
3311 	/* Skip rest of block... */
3312 	if (tar_flush_unconsumed(a, unconsumed) != ARCHIVE_OK) {
3313 		return (ARCHIVE_FATAL);
3314 	}
3315 	bytes_read = tar->entry_bytes_remaining - remaining;
3316 	to_skip = 0x1ff & -bytes_read;
3317 	/* Fail if tar->entry_bytes_remaing would get negative */
3318 	if (to_skip > remaining)
3319 		return (ARCHIVE_FATAL);
3320 	if (to_skip != __archive_read_consume(a, to_skip))
3321 		return (ARCHIVE_FATAL);
3322 	return (bytes_read + to_skip);
3323 }
3324 
3325 /*
3326  * Solaris pax extension for a sparse file. This is recorded with the
3327  * data and hole pairs. The way recording sparse information by Solaris'
3328  * pax simply indicates where data and sparse are, so the stored contents
3329  * consist of both data and hole.
3330  */
3331 static int
pax_attribute_SUN_holesdata(struct archive_read * a,struct tar * tar,struct archive_entry * entry,const char * p,size_t length)3332 pax_attribute_SUN_holesdata(struct archive_read *a, struct tar *tar,
3333 	struct archive_entry *entry, const char *p, size_t length)
3334 {
3335 	const char *e;
3336 	int64_t start, end;
3337 	int hole = 1;
3338 
3339 	(void)entry; /* UNUSED */
3340 
3341 	end = 0;
3342 	if (length <= 0)
3343 		return (ARCHIVE_WARN);
3344 	if (*p == ' ') {
3345 		p++;
3346 		length--;
3347 	} else {
3348 		return (ARCHIVE_WARN);
3349 	}
3350 	for (;;) {
3351 		e = p;
3352 		while (length > 0 && *e != ' ') {
3353 			if (*e < '0' || *e > '9')
3354 				return (ARCHIVE_WARN);
3355 			e++;
3356 			length--;
3357 		}
3358 		start = end;
3359 		end = tar_atol10(p, e - p);
3360 		if (end < 0)
3361 			return (ARCHIVE_WARN);
3362 		if (start < end) {
3363 			if (gnu_add_sparse_entry(a, tar, start,
3364 			    end - start) != ARCHIVE_OK)
3365 				return (ARCHIVE_FATAL);
3366 			tar->sparse_last->hole = hole;
3367 		}
3368 		if (length == 0 || *e == '\n') {
3369 			if (length == 0 && *e == '\n') {
3370 				return (ARCHIVE_OK);
3371 			} else {
3372 				return (ARCHIVE_WARN);
3373 			}
3374 		}
3375 		p = e + 1;
3376 		length--;
3377 		hole = hole == 0;
3378 	}
3379 }
3380 
3381 /*-
3382  * Convert text->integer.
3383  *
3384  * Traditional tar formats (including POSIX) specify base-8 for
3385  * all of the standard numeric fields.  This is a significant limitation
3386  * in practice:
3387  *   = file size is limited to 8GB
3388  *   = rdevmajor and rdevminor are limited to 21 bits
3389  *   = uid/gid are limited to 21 bits
3390  *
3391  * There are two workarounds for this:
3392  *   = pax extended headers, which use variable-length string fields
3393  *   = GNU tar and STAR both allow either base-8 or base-256 in
3394  *      most fields.  The high bit is set to indicate base-256.
3395  *
3396  * On read, this implementation supports both extensions.
3397  */
3398 static int64_t
tar_atol(const char * p,size_t char_cnt)3399 tar_atol(const char *p, size_t char_cnt)
3400 {
3401 	/*
3402 	 * Technically, GNU tar considers a field to be in base-256
3403 	 * only if the first byte is 0xff or 0x80.
3404 	 */
3405 	if (*p & 0x80)
3406 		return (tar_atol256(p, char_cnt));
3407 	return (tar_atol8(p, char_cnt));
3408 }
3409 
3410 /*
3411  * Note that this implementation does not (and should not!) obey
3412  * locale settings; you cannot simply substitute strtol here, since
3413  * it does obey locale.
3414  */
3415 static int64_t
tar_atol_base_n(const char * p,size_t char_cnt,int base)3416 tar_atol_base_n(const char *p, size_t char_cnt, int base)
3417 {
3418 	int64_t	l, maxval, limit, last_digit_limit;
3419 	int digit, sign;
3420 
3421 	maxval = INT64_MAX;
3422 	limit = INT64_MAX / base;
3423 	last_digit_limit = INT64_MAX % base;
3424 
3425 	/* the pointer will not be dereferenced if char_cnt is zero
3426 	 * due to the way the && operator is evaluated.
3427 	 */
3428 	while (char_cnt != 0 && (*p == ' ' || *p == '\t')) {
3429 		p++;
3430 		char_cnt--;
3431 	}
3432 
3433 	sign = 1;
3434 	if (char_cnt != 0 && *p == '-') {
3435 		sign = -1;
3436 		p++;
3437 		char_cnt--;
3438 
3439 		maxval = INT64_MIN;
3440 		limit = -(INT64_MIN / base);
3441 		last_digit_limit = -(INT64_MIN % base);
3442 	}
3443 
3444 	l = 0;
3445 	if (char_cnt != 0) {
3446 		digit = *p - '0';
3447 		while (digit >= 0 && digit < base  && char_cnt != 0) {
3448 			if (l>limit || (l == limit && digit >= last_digit_limit)) {
3449 				return maxval; /* Truncate on overflow. */
3450 			}
3451 			l = (l * base) + digit;
3452 			digit = *++p - '0';
3453 			char_cnt--;
3454 		}
3455 	}
3456 	return (sign < 0) ? -l : l;
3457 }
3458 
3459 static int64_t
tar_atol8(const char * p,size_t char_cnt)3460 tar_atol8(const char *p, size_t char_cnt)
3461 {
3462 	return tar_atol_base_n(p, char_cnt, 8);
3463 }
3464 
3465 static int64_t
tar_atol10(const char * p,size_t char_cnt)3466 tar_atol10(const char *p, size_t char_cnt)
3467 {
3468 	return tar_atol_base_n(p, char_cnt, 10);
3469 }
3470 
3471 /*
3472  * Parse a base-256 integer.  This is just a variable-length
3473  * twos-complement signed binary value in big-endian order, except
3474  * that the high-order bit is ignored.  The values here can be up to
3475  * 12 bytes, so we need to be careful about overflowing 64-bit
3476  * (8-byte) integers.
3477  *
3478  * This code unashamedly assumes that the local machine uses 8-bit
3479  * bytes and twos-complement arithmetic.
3480  */
3481 static int64_t
tar_atol256(const char * _p,size_t char_cnt)3482 tar_atol256(const char *_p, size_t char_cnt)
3483 {
3484 	uint64_t l;
3485 	const unsigned char *p = (const unsigned char *)_p;
3486 	unsigned char c, neg;
3487 
3488 	/* Extend 7-bit 2s-comp to 8-bit 2s-comp, decide sign. */
3489 	c = *p;
3490 	if (c & 0x40) {
3491 		neg = 0xff;
3492 		c |= 0x80;
3493 		l = ~ARCHIVE_LITERAL_ULL(0);
3494 	} else {
3495 		neg = 0;
3496 		c &= 0x7f;
3497 		l = 0;
3498 	}
3499 
3500 	/* If more than 8 bytes, check that we can ignore
3501 	 * high-order bits without overflow. */
3502 	while (char_cnt > sizeof(int64_t)) {
3503 		--char_cnt;
3504 		if (c != neg)
3505 			return neg ? INT64_MIN : INT64_MAX;
3506 		c = *++p;
3507 	}
3508 
3509 	/* c is first byte that fits; if sign mismatch, return overflow */
3510 	if ((c ^ neg) & 0x80) {
3511 		return neg ? INT64_MIN : INT64_MAX;
3512 	}
3513 
3514 	/* Accumulate remaining bytes. */
3515 	while (--char_cnt > 0) {
3516 		l = (l << 8) | c;
3517 		c = *++p;
3518 	}
3519 	l = (l << 8) | c;
3520 	/* Return signed twos-complement value. */
3521 	return (int64_t)(l);
3522 }
3523 
3524 /*
3525  * Returns length of line (including trailing newline)
3526  * or negative on error.  'start' argument is updated to
3527  * point to first character of line.  This avoids copying
3528  * when possible.
3529  */
3530 static ssize_t
readline(struct archive_read * a,struct tar * tar,const char ** start,ssize_t limit,int64_t * unconsumed)3531 readline(struct archive_read *a, struct tar *tar, const char **start,
3532     ssize_t limit, int64_t *unconsumed)
3533 {
3534 	ssize_t bytes_read;
3535 	ssize_t total_size = 0;
3536 	const void *t;
3537 	const char *s;
3538 	void *p;
3539 
3540 	if (tar_flush_unconsumed(a, unconsumed) != ARCHIVE_OK) {
3541 		return (ARCHIVE_FATAL);
3542 	}
3543 
3544 	t = __archive_read_ahead(a, 1, &bytes_read);
3545 	if (bytes_read <= 0 || t == NULL)
3546 		return (ARCHIVE_FATAL);
3547 	s = t;  /* Start of line? */
3548 	p = memchr(t, '\n', bytes_read);
3549 	/* If we found '\n' in the read buffer, return pointer to that. */
3550 	if (p != NULL) {
3551 		bytes_read = 1 + ((const char *)p) - s;
3552 		if (bytes_read > limit) {
3553 			archive_set_error(&a->archive,
3554 			    ARCHIVE_ERRNO_FILE_FORMAT,
3555 			    "Line too long");
3556 			return (ARCHIVE_FATAL);
3557 		}
3558 		*unconsumed = bytes_read;
3559 		*start = s;
3560 		return (bytes_read);
3561 	}
3562 	*unconsumed = bytes_read;
3563 	/* Otherwise, we need to accumulate in a line buffer. */
3564 	for (;;) {
3565 		if (total_size + bytes_read > limit) {
3566 			archive_set_error(&a->archive,
3567 			    ARCHIVE_ERRNO_FILE_FORMAT,
3568 			    "Line too long");
3569 			return (ARCHIVE_FATAL);
3570 		}
3571 		if (archive_string_ensure(&tar->line, total_size + bytes_read) == NULL) {
3572 			archive_set_error(&a->archive, ENOMEM,
3573 			    "Can't allocate working buffer");
3574 			return (ARCHIVE_FATAL);
3575 		}
3576 		memcpy(tar->line.s + total_size, t, bytes_read);
3577 		tar_flush_unconsumed(a, unconsumed);
3578 		total_size += bytes_read;
3579 		/* If we found '\n', clean up and return. */
3580 		if (p != NULL) {
3581 			*start = tar->line.s;
3582 			return (total_size);
3583 		}
3584 		/* Read some more. */
3585 		t = __archive_read_ahead(a, 1, &bytes_read);
3586 		if (bytes_read <= 0 || t == NULL)
3587 			return (ARCHIVE_FATAL);
3588 		s = t;  /* Start of line? */
3589 		p = memchr(t, '\n', bytes_read);
3590 		/* If we found '\n', trim the read. */
3591 		if (p != NULL) {
3592 			bytes_read = 1 + ((const char *)p) - s;
3593 		}
3594 		*unconsumed = bytes_read;
3595 	}
3596 }
3597 
3598 /*
3599  * base64_decode - Base64 decode
3600  *
3601  * This accepts most variations of base-64 encoding, including:
3602  *    * with or without line breaks
3603  *    * with or without the final group padded with '=' or '_' characters
3604  * (The most economical Base-64 variant does not pad the last group and
3605  * omits line breaks; RFC1341 used for MIME requires both.)
3606  */
3607 static char *
base64_decode(const char * s,size_t len,size_t * out_len)3608 base64_decode(const char *s, size_t len, size_t *out_len)
3609 {
3610 	static const unsigned char digits[64] = {
3611 		'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
3612 		'O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b',
3613 		'c','d','e','f','g','h','i','j','k','l','m','n','o','p',
3614 		'q','r','s','t','u','v','w','x','y','z','0','1','2','3',
3615 		'4','5','6','7','8','9','+','/' };
3616 	static unsigned char decode_table[128];
3617 	char *out, *d;
3618 	const unsigned char *src = (const unsigned char *)s;
3619 
3620 	/* If the decode table is not yet initialized, prepare it. */
3621 	if (decode_table[digits[1]] != 1) {
3622 		unsigned i;
3623 		memset(decode_table, 0xff, sizeof(decode_table));
3624 		for (i = 0; i < sizeof(digits); i++)
3625 			decode_table[digits[i]] = i;
3626 	}
3627 
3628 	/* Allocate enough space to hold the entire output. */
3629 	/* Note that we may not use all of this... */
3630 	out = malloc(len - len / 4 + 1);
3631 	if (out == NULL) {
3632 		*out_len = 0;
3633 		return (NULL);
3634 	}
3635 	d = out;
3636 
3637 	while (len > 0) {
3638 		/* Collect the next group of (up to) four characters. */
3639 		int v = 0;
3640 		int group_size = 0;
3641 		while (group_size < 4 && len > 0) {
3642 			/* '=' or '_' padding indicates final group. */
3643 			if (*src == '=' || *src == '_') {
3644 				len = 0;
3645 				break;
3646 			}
3647 			/* Skip illegal characters (including line breaks) */
3648 			if (*src > 127 || *src < 32
3649 			    || decode_table[*src] == 0xff) {
3650 				len--;
3651 				src++;
3652 				continue;
3653 			}
3654 			v <<= 6;
3655 			v |= decode_table[*src++];
3656 			len --;
3657 			group_size++;
3658 		}
3659 		/* Align a short group properly. */
3660 		v <<= 6 * (4 - group_size);
3661 		/* Unpack the group we just collected. */
3662 		switch (group_size) {
3663 		case 4: d[2] = v & 0xff;
3664 			/* FALLTHROUGH */
3665 		case 3: d[1] = (v >> 8) & 0xff;
3666 			/* FALLTHROUGH */
3667 		case 2: d[0] = (v >> 16) & 0xff;
3668 			break;
3669 		case 1: /* this is invalid! */
3670 			break;
3671 		}
3672 		d += group_size * 3 / 4;
3673 	}
3674 
3675 	*out_len = d - out;
3676 	return (out);
3677 }
3678 
3679 static char *
url_decode(const char * in,size_t length)3680 url_decode(const char *in, size_t length)
3681 {
3682 	char *out, *d;
3683 	const char *s;
3684 
3685 	out = malloc(length + 1);
3686 	if (out == NULL)
3687 		return (NULL);
3688 	for (s = in, d = out; length > 0 && *s != '\0'; ) {
3689 		if (s[0] == '%' && length > 2) {
3690 			/* Try to convert % escape */
3691 			int digit1 = tohex(s[1]);
3692 			int digit2 = tohex(s[2]);
3693 			if (digit1 >= 0 && digit2 >= 0) {
3694 				/* Looks good, consume three chars */
3695 				s += 3;
3696 				length -= 3;
3697 				/* Convert output */
3698 				*d++ = ((digit1 << 4) | digit2);
3699 				continue;
3700 			}
3701 			/* Else fall through and treat '%' as normal char */
3702 		}
3703 		*d++ = *s++;
3704 		--length;
3705 	}
3706 	*d = '\0';
3707 	return (out);
3708 }
3709 
3710 static int
tohex(int c)3711 tohex(int c)
3712 {
3713 	if (c >= '0' && c <= '9')
3714 		return (c - '0');
3715 	else if (c >= 'A' && c <= 'F')
3716 		return (c - 'A' + 10);
3717 	else if (c >= 'a' && c <= 'f')
3718 		return (c - 'a' + 10);
3719 	else
3720 		return (-1);
3721 }
3722