1 /*-
2  * Copyright (c) 2003-2007 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 __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_tar.c 201161 2009-12-29 05:44:39Z kientzle $");
30 
31 #ifdef HAVE_ERRNO_H
32 #include <errno.h>
33 #endif
34 #include <stddef.h>
35 #ifdef HAVE_STDLIB_H
36 #include <stdlib.h>
37 #endif
38 #ifdef HAVE_STRING_H
39 #include <string.h>
40 #endif
41 
42 #include "archive.h"
43 #include "archive_acl_private.h" /* For ACL parsing routines. */
44 #include "archive_entry.h"
45 #include "archive_entry_locale.h"
46 #include "archive_private.h"
47 #include "archive_read_private.h"
48 
49 #define tar_min(a,b) ((a) < (b) ? (a) : (b))
50 
51 /*
52  * Layout of POSIX 'ustar' tar header.
53  */
54 struct archive_entry_header_ustar {
55 	char	name[100];
56 	char	mode[8];
57 	char	uid[8];
58 	char	gid[8];
59 	char	size[12];
60 	char	mtime[12];
61 	char	checksum[8];
62 	char	typeflag[1];
63 	char	linkname[100];	/* "old format" header ends here */
64 	char	magic[6];	/* For POSIX: "ustar\0" */
65 	char	version[2];	/* For POSIX: "00" */
66 	char	uname[32];
67 	char	gname[32];
68 	char	rdevmajor[8];
69 	char	rdevminor[8];
70 	char	prefix[155];
71 };
72 
73 /*
74  * Structure of GNU tar header
75  */
76 struct gnu_sparse {
77 	char	offset[12];
78 	char	numbytes[12];
79 };
80 
81 struct archive_entry_header_gnutar {
82 	char	name[100];
83 	char	mode[8];
84 	char	uid[8];
85 	char	gid[8];
86 	char	size[12];
87 	char	mtime[12];
88 	char	checksum[8];
89 	char	typeflag[1];
90 	char	linkname[100];
91 	char	magic[8];  /* "ustar  \0" (note blank/blank/null at end) */
92 	char	uname[32];
93 	char	gname[32];
94 	char	rdevmajor[8];
95 	char	rdevminor[8];
96 	char	atime[12];
97 	char	ctime[12];
98 	char	offset[12];
99 	char	longnames[4];
100 	char	unused[1];
101 	struct gnu_sparse sparse[4];
102 	char	isextended[1];
103 	char	realsize[12];
104 	/*
105 	 * Old GNU format doesn't use POSIX 'prefix' field; they use
106 	 * the 'L' (longname) entry instead.
107 	 */
108 };
109 
110 /*
111  * Data specific to this format.
112  */
113 struct sparse_block {
114 	struct sparse_block	*next;
115 	int64_t	offset;
116 	int64_t	remaining;
117 	int hole;
118 };
119 
120 struct tar {
121 	struct archive_string	 acl_text;
122 	struct archive_string	 entry_pathname;
123 	/* For "GNU.sparse.name" and other similar path extensions. */
124 	struct archive_string	 entry_pathname_override;
125 	struct archive_string	 entry_linkpath;
126 	struct archive_string	 entry_uname;
127 	struct archive_string	 entry_gname;
128 	struct archive_string	 longlink;
129 	struct archive_string	 longname;
130 	struct archive_string	 pax_header;
131 	struct archive_string	 pax_global;
132 	struct archive_string	 line;
133 	int			 pax_hdrcharset_binary;
134 	int			 header_recursion_depth;
135 	int64_t			 entry_bytes_remaining;
136 	int64_t			 entry_offset;
137 	int64_t			 entry_padding;
138 	int64_t 		 entry_bytes_unconsumed;
139 	int64_t			 realsize;
140 	int			 sparse_allowed;
141 	struct sparse_block	*sparse_list;
142 	struct sparse_block	*sparse_last;
143 	int64_t			 sparse_offset;
144 	int64_t			 sparse_numbytes;
145 	int			 sparse_gnu_major;
146 	int			 sparse_gnu_minor;
147 	char			 sparse_gnu_pending;
148 
149 	struct archive_string	 localname;
150 	struct archive_string_conv *opt_sconv;
151 	struct archive_string_conv *sconv;
152 	struct archive_string_conv *sconv_acl;
153 	struct archive_string_conv *sconv_default;
154 	int			 init_default_conversion;
155 	int			 compat_2x;
156 	int			 process_mac_extensions;
157 	int			 read_concatenated_archives;
158 	int			 realsize_override;
159 };
160 
161 static int	archive_block_is_null(const char *p);
162 static char	*base64_decode(const char *, size_t, size_t *);
163 static int	gnu_add_sparse_entry(struct archive_read *, struct tar *,
164 		    int64_t offset, int64_t remaining);
165 
166 static void	gnu_clear_sparse_list(struct tar *);
167 static int	gnu_sparse_old_read(struct archive_read *, struct tar *,
168 		    const struct archive_entry_header_gnutar *header, size_t *);
169 static int	gnu_sparse_old_parse(struct archive_read *, struct tar *,
170 		    const struct gnu_sparse *sparse, int length);
171 static int	gnu_sparse_01_parse(struct archive_read *, struct tar *,
172 		    const char *);
173 static ssize_t	gnu_sparse_10_read(struct archive_read *, struct tar *,
174 			size_t *);
175 static int	header_Solaris_ACL(struct archive_read *,  struct tar *,
176 		    struct archive_entry *, const void *, size_t *);
177 static int	header_common(struct archive_read *,  struct tar *,
178 		    struct archive_entry *, const void *);
179 static int	header_old_tar(struct archive_read *, struct tar *,
180 		    struct archive_entry *, const void *);
181 static int	header_pax_extensions(struct archive_read *, struct tar *,
182 		    struct archive_entry *, const void *, size_t *);
183 static int	header_pax_global(struct archive_read *, struct tar *,
184 		    struct archive_entry *, const void *h, size_t *);
185 static int	header_longlink(struct archive_read *, struct tar *,
186 		    struct archive_entry *, const void *h, size_t *);
187 static int	header_longname(struct archive_read *, struct tar *,
188 		    struct archive_entry *, const void *h, size_t *);
189 static int	read_mac_metadata_blob(struct archive_read *, struct tar *,
190 		    struct archive_entry *, const void *h, size_t *);
191 static int	header_volume(struct archive_read *, struct tar *,
192 		    struct archive_entry *, const void *h, size_t *);
193 static int	header_ustar(struct archive_read *, struct tar *,
194 		    struct archive_entry *, const void *h);
195 static int	header_gnutar(struct archive_read *, struct tar *,
196 		    struct archive_entry *, const void *h, size_t *);
197 static int	archive_read_format_tar_bid(struct archive_read *, int);
198 static int	archive_read_format_tar_options(struct archive_read *,
199 		    const char *, const char *);
200 static int	archive_read_format_tar_cleanup(struct archive_read *);
201 static int	archive_read_format_tar_read_data(struct archive_read *a,
202 		    const void **buff, size_t *size, int64_t *offset);
203 static int	archive_read_format_tar_skip(struct archive_read *a);
204 static int	archive_read_format_tar_read_header(struct archive_read *,
205 		    struct archive_entry *);
206 static int	checksum(struct archive_read *, const void *);
207 static int 	pax_attribute(struct archive_read *, struct tar *,
208 		    struct archive_entry *, const char *key, const char *value,
209 		    size_t value_length);
210 static int	pax_attribute_acl(struct archive_read *, struct tar *,
211 		    struct archive_entry *, const char *, int);
212 static int	pax_attribute_xattr(struct archive_entry *, const char *,
213 		    const char *);
214 static int 	pax_header(struct archive_read *, struct tar *,
215 		    struct archive_entry *, struct archive_string *);
216 static void	pax_time(const char *, int64_t *sec, long *nanos);
217 static ssize_t	readline(struct archive_read *, struct tar *, const char **,
218 		    ssize_t limit, size_t *);
219 static int	read_body_to_string(struct archive_read *, struct tar *,
220 		    struct archive_string *, const void *h, size_t *);
221 static int	solaris_sparse_parse(struct archive_read *, struct tar *,
222 		    struct archive_entry *, const char *);
223 static int64_t	tar_atol(const char *, size_t);
224 static int64_t	tar_atol10(const char *, size_t);
225 static int64_t	tar_atol256(const char *, size_t);
226 static int64_t	tar_atol8(const char *, size_t);
227 static int	tar_read_header(struct archive_read *, struct tar *,
228 		    struct archive_entry *, size_t *);
229 static int	tohex(int c);
230 static char	*url_decode(const char *);
231 static void	tar_flush_unconsumed(struct archive_read *, size_t *);
232 
233 
234 int
235 archive_read_support_format_gnutar(struct archive *a)
236 {
237 	archive_check_magic(a, ARCHIVE_READ_MAGIC,
238 	    ARCHIVE_STATE_NEW, "archive_read_support_format_gnutar");
239 	return (archive_read_support_format_tar(a));
240 }
241 
242 
243 int
244 archive_read_support_format_tar(struct archive *_a)
245 {
246 	struct archive_read *a = (struct archive_read *)_a;
247 	struct tar *tar;
248 	int r;
249 
250 	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
251 	    ARCHIVE_STATE_NEW, "archive_read_support_format_tar");
252 
253 	tar = (struct tar *)calloc(1, sizeof(*tar));
254 	if (tar == NULL) {
255 		archive_set_error(&a->archive, ENOMEM,
256 		    "Can't allocate tar data");
257 		return (ARCHIVE_FATAL);
258 	}
259 #ifdef HAVE_COPYFILE_H
260 	/* Set this by default on Mac OS. */
261 	tar->process_mac_extensions = 1;
262 #endif
263 
264 	r = __archive_read_register_format(a, tar, "tar",
265 	    archive_read_format_tar_bid,
266 	    archive_read_format_tar_options,
267 	    archive_read_format_tar_read_header,
268 	    archive_read_format_tar_read_data,
269 	    archive_read_format_tar_skip,
270 	    NULL,
271 	    archive_read_format_tar_cleanup,
272 	    NULL,
273 	    NULL);
274 
275 	if (r != ARCHIVE_OK)
276 		free(tar);
277 	return (ARCHIVE_OK);
278 }
279 
280 static int
281 archive_read_format_tar_cleanup(struct archive_read *a)
282 {
283 	struct tar *tar;
284 
285 	tar = (struct tar *)(a->format->data);
286 	gnu_clear_sparse_list(tar);
287 	archive_string_free(&tar->acl_text);
288 	archive_string_free(&tar->entry_pathname);
289 	archive_string_free(&tar->entry_pathname_override);
290 	archive_string_free(&tar->entry_linkpath);
291 	archive_string_free(&tar->entry_uname);
292 	archive_string_free(&tar->entry_gname);
293 	archive_string_free(&tar->line);
294 	archive_string_free(&tar->pax_global);
295 	archive_string_free(&tar->pax_header);
296 	archive_string_free(&tar->longname);
297 	archive_string_free(&tar->longlink);
298 	archive_string_free(&tar->localname);
299 	free(tar);
300 	(a->format->data) = NULL;
301 	return (ARCHIVE_OK);
302 }
303 
304 /*
305  * Validate number field
306  *
307  * This has to be pretty lenient in order to accommodate the enormous
308  * variety of tar writers in the world:
309  *  = POSIX (IEEE Std 1003.1-1988) ustar requires octal values with leading
310  *    zeros and allows fields to be terminated with space or null characters
311  *  = Many writers use different termination (in particular, libarchive
312  *    omits terminator bytes to squeeze one or two more digits)
313  *  = Many writers pad with space and omit leading zeros
314  *  = GNU tar and star write base-256 values if numbers are too
315  *    big to be represented in octal
316  *
317  *  Examples of specific tar headers that we should support:
318  *  = Perl Archive::Tar terminates uid, gid, devminor and devmajor with two
319  *    null bytes, pads size with spaces and other numeric fields with zeroes
320  *  = plexus-archiver prior to 2.6.3 (before switching to commons-compress)
321  *    may have uid and gid fields filled with spaces without any octal digits
322  *    at all and pads all numeric fields with spaces
323  *
324  * This should tolerate all variants in use.  It will reject a field
325  * where the writer just left garbage after a trailing NUL.
326  */
327 static int
328 validate_number_field(const char* p_field, size_t i_size)
329 {
330 	unsigned char marker = (unsigned char)p_field[0];
331 	if (marker == 128 || marker == 255 || marker == 0) {
332 		/* Base-256 marker, there's nothing we can check. */
333 		return 1;
334 	} else {
335 		/* Must be octal */
336 		size_t i = 0;
337 		/* Skip any leading spaces */
338 		while (i < i_size && p_field[i] == ' ') {
339 			++i;
340 		}
341 		/* Skip octal digits. */
342 		while (i < i_size && p_field[i] >= '0' && p_field[i] <= '7') {
343 			++i;
344 		}
345 		/* Any remaining characters must be space or NUL padding. */
346 		while (i < i_size) {
347 			if (p_field[i] != ' ' && p_field[i] != 0) {
348 				return 0;
349 			}
350 			++i;
351 		}
352 		return 1;
353 	}
354 }
355 
356 static int
357 archive_read_format_tar_bid(struct archive_read *a, int best_bid)
358 {
359 	int bid;
360 	const char *h;
361 	const struct archive_entry_header_ustar *header;
362 
363 	(void)best_bid; /* UNUSED */
364 
365 	bid = 0;
366 
367 	/* Now let's look at the actual header and see if it matches. */
368 	h = __archive_read_ahead(a, 512, NULL);
369 	if (h == NULL)
370 		return (-1);
371 
372 	/* If it's an end-of-archive mark, we can handle it. */
373 	if (h[0] == 0 && archive_block_is_null(h)) {
374 		/*
375 		 * Usually, I bid the number of bits verified, but
376 		 * in this case, 4096 seems excessive so I picked 10 as
377 		 * an arbitrary but reasonable-seeming value.
378 		 */
379 		return (10);
380 	}
381 
382 	/* If it's not an end-of-archive mark, it must have a valid checksum.*/
383 	if (!checksum(a, h))
384 		return (0);
385 	bid += 48;  /* Checksum is usually 6 octal digits. */
386 
387 	header = (const struct archive_entry_header_ustar *)h;
388 
389 	/* Recognize POSIX formats. */
390 	if ((memcmp(header->magic, "ustar\0", 6) == 0)
391 	    && (memcmp(header->version, "00", 2) == 0))
392 		bid += 56;
393 
394 	/* Recognize GNU tar format. */
395 	if ((memcmp(header->magic, "ustar ", 6) == 0)
396 	    && (memcmp(header->version, " \0", 2) == 0))
397 		bid += 56;
398 
399 	/* Type flag must be null, digit or A-Z, a-z. */
400 	if (header->typeflag[0] != 0 &&
401 	    !( header->typeflag[0] >= '0' && header->typeflag[0] <= '9') &&
402 	    !( header->typeflag[0] >= 'A' && header->typeflag[0] <= 'Z') &&
403 	    !( header->typeflag[0] >= 'a' && header->typeflag[0] <= 'z') )
404 		return (0);
405 	bid += 2;  /* 6 bits of variation in an 8-bit field leaves 2 bits. */
406 
407 	/*
408 	 * Check format of mode/uid/gid/mtime/size/rdevmajor/rdevminor fields.
409 	 */
410 	if (bid > 0 && (
411 	    validate_number_field(header->mode, sizeof(header->mode)) == 0
412 	    || validate_number_field(header->uid, sizeof(header->uid)) == 0
413 	    || validate_number_field(header->gid, sizeof(header->gid)) == 0
414 	    || validate_number_field(header->mtime, sizeof(header->mtime)) == 0
415 	    || validate_number_field(header->size, sizeof(header->size)) == 0
416 	    || validate_number_field(header->rdevmajor, sizeof(header->rdevmajor)) == 0
417 	    || validate_number_field(header->rdevminor, sizeof(header->rdevminor)) == 0)) {
418 		bid = 0;
419 	}
420 
421 	return (bid);
422 }
423 
424 static int
425 archive_read_format_tar_options(struct archive_read *a,
426     const char *key, const char *val)
427 {
428 	struct tar *tar;
429 	int ret = ARCHIVE_FAILED;
430 
431 	tar = (struct tar *)(a->format->data);
432 	if (strcmp(key, "compat-2x")  == 0) {
433 		/* Handle UTF-8 filenames as libarchive 2.x */
434 		tar->compat_2x = (val != NULL && val[0] != 0);
435 		tar->init_default_conversion = tar->compat_2x;
436 		return (ARCHIVE_OK);
437 	} else if (strcmp(key, "hdrcharset")  == 0) {
438 		if (val == NULL || val[0] == 0)
439 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
440 			    "tar: hdrcharset option needs a character-set name");
441 		else {
442 			tar->opt_sconv =
443 			    archive_string_conversion_from_charset(
444 				&a->archive, val, 0);
445 			if (tar->opt_sconv != NULL)
446 				ret = ARCHIVE_OK;
447 			else
448 				ret = ARCHIVE_FATAL;
449 		}
450 		return (ret);
451 	} else if (strcmp(key, "mac-ext") == 0) {
452 		tar->process_mac_extensions = (val != NULL && val[0] != 0);
453 		return (ARCHIVE_OK);
454 	} else if (strcmp(key, "read_concatenated_archives") == 0) {
455 		tar->read_concatenated_archives = (val != NULL && val[0] != 0);
456 		return (ARCHIVE_OK);
457 	}
458 
459 	/* Note: The "warn" return is just to inform the options
460 	 * supervisor that we didn't handle it.  It will generate
461 	 * a suitable error if no one used this option. */
462 	return (ARCHIVE_WARN);
463 }
464 
465 /* utility function- this exists to centralize the logic of tracking
466  * how much unconsumed data we have floating around, and to consume
467  * anything outstanding since we're going to do read_aheads
468  */
469 static void
470 tar_flush_unconsumed(struct archive_read *a, size_t *unconsumed)
471 {
472 	if (*unconsumed) {
473 /*
474 		void *data = (void *)__archive_read_ahead(a, *unconsumed, NULL);
475 		 * this block of code is to poison claimed unconsumed space, ensuring
476 		 * things break if it is in use still.
477 		 * currently it WILL break things, so enable it only for debugging this issue
478 		if (data) {
479 			memset(data, 0xff, *unconsumed);
480 		}
481 */
482 		__archive_read_consume(a, *unconsumed);
483 		*unconsumed = 0;
484 	}
485 }
486 
487 /*
488  * The function invoked by archive_read_next_header().  This
489  * just sets up a few things and then calls the internal
490  * tar_read_header() function below.
491  */
492 static int
493 archive_read_format_tar_read_header(struct archive_read *a,
494     struct archive_entry *entry)
495 {
496 	/*
497 	 * When converting tar archives to cpio archives, it is
498 	 * essential that each distinct file have a distinct inode
499 	 * number.  To simplify this, we keep a static count here to
500 	 * assign fake dev/inode numbers to each tar entry.  Note that
501 	 * pax format archives may overwrite this with something more
502 	 * useful.
503 	 *
504 	 * Ideally, we would track every file read from the archive so
505 	 * that we could assign the same dev/ino pair to hardlinks,
506 	 * but the memory required to store a complete lookup table is
507 	 * probably not worthwhile just to support the relatively
508 	 * obscure tar->cpio conversion case.
509 	 */
510 	static int default_inode;
511 	static int default_dev;
512 	struct tar *tar;
513 	const char *p;
514 	const wchar_t *wp;
515 	int r;
516 	size_t l, unconsumed = 0;
517 
518 	/* Assign default device/inode values. */
519 	archive_entry_set_dev(entry, 1 + default_dev); /* Don't use zero. */
520 	archive_entry_set_ino(entry, ++default_inode); /* Don't use zero. */
521 	/* Limit generated st_ino number to 16 bits. */
522 	if (default_inode >= 0xffff) {
523 		++default_dev;
524 		default_inode = 0;
525 	}
526 
527 	tar = (struct tar *)(a->format->data);
528 	tar->entry_offset = 0;
529 	gnu_clear_sparse_list(tar);
530 	tar->realsize = -1; /* Mark this as "unset" */
531 	tar->realsize_override = 0;
532 
533 	/* Setup default string conversion. */
534 	tar->sconv = tar->opt_sconv;
535 	if (tar->sconv == NULL) {
536 		if (!tar->init_default_conversion) {
537 			tar->sconv_default =
538 			    archive_string_default_conversion_for_read(&(a->archive));
539 			tar->init_default_conversion = 1;
540 		}
541 		tar->sconv = tar->sconv_default;
542 	}
543 
544 	r = tar_read_header(a, tar, entry, &unconsumed);
545 
546 	tar_flush_unconsumed(a, &unconsumed);
547 
548 	/*
549 	 * "non-sparse" files are really just sparse files with
550 	 * a single block.
551 	 */
552 	if (tar->sparse_list == NULL) {
553 		if (gnu_add_sparse_entry(a, tar, 0, tar->entry_bytes_remaining)
554 		    != ARCHIVE_OK)
555 			return (ARCHIVE_FATAL);
556 	} else {
557 		struct sparse_block *sb;
558 
559 		for (sb = tar->sparse_list; sb != NULL; sb = sb->next) {
560 			if (!sb->hole)
561 				archive_entry_sparse_add_entry(entry,
562 				    sb->offset, sb->remaining);
563 		}
564 	}
565 
566 	if (r == ARCHIVE_OK && archive_entry_filetype(entry) == AE_IFREG) {
567 		/*
568 		 * "Regular" entry with trailing '/' is really
569 		 * directory: This is needed for certain old tar
570 		 * variants and even for some broken newer ones.
571 		 */
572 		if ((wp = archive_entry_pathname_w(entry)) != NULL) {
573 			l = wcslen(wp);
574 			if (l > 0 && wp[l - 1] == L'/') {
575 				archive_entry_set_filetype(entry, AE_IFDIR);
576 			}
577 		} else if ((p = archive_entry_pathname(entry)) != NULL) {
578 			l = strlen(p);
579 			if (l > 0 && p[l - 1] == '/') {
580 				archive_entry_set_filetype(entry, AE_IFDIR);
581 			}
582 		}
583 	}
584 	return (r);
585 }
586 
587 static int
588 archive_read_format_tar_read_data(struct archive_read *a,
589     const void **buff, size_t *size, int64_t *offset)
590 {
591 	ssize_t bytes_read;
592 	struct tar *tar;
593 	struct sparse_block *p;
594 
595 	tar = (struct tar *)(a->format->data);
596 
597 	for (;;) {
598 		/* Remove exhausted entries from sparse list. */
599 		while (tar->sparse_list != NULL &&
600 		    tar->sparse_list->remaining == 0) {
601 			p = tar->sparse_list;
602 			tar->sparse_list = p->next;
603 			free(p);
604 		}
605 
606 		if (tar->entry_bytes_unconsumed) {
607 			__archive_read_consume(a, tar->entry_bytes_unconsumed);
608 			tar->entry_bytes_unconsumed = 0;
609 		}
610 
611 		/* If we're at end of file, return EOF. */
612 		if (tar->sparse_list == NULL ||
613 		    tar->entry_bytes_remaining == 0) {
614 			if (__archive_read_consume(a, tar->entry_padding) < 0)
615 				return (ARCHIVE_FATAL);
616 			tar->entry_padding = 0;
617 			*buff = NULL;
618 			*size = 0;
619 			*offset = tar->realsize;
620 			return (ARCHIVE_EOF);
621 		}
622 
623 		*buff = __archive_read_ahead(a, 1, &bytes_read);
624 		if (bytes_read < 0)
625 			return (ARCHIVE_FATAL);
626 		if (*buff == NULL) {
627 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
628 			    "Truncated tar archive");
629 			return (ARCHIVE_FATAL);
630 		}
631 		if (bytes_read > tar->entry_bytes_remaining)
632 			bytes_read = (ssize_t)tar->entry_bytes_remaining;
633 		/* Don't read more than is available in the
634 		 * current sparse block. */
635 		if (tar->sparse_list->remaining < bytes_read)
636 			bytes_read = (ssize_t)tar->sparse_list->remaining;
637 		*size = bytes_read;
638 		*offset = tar->sparse_list->offset;
639 		tar->sparse_list->remaining -= bytes_read;
640 		tar->sparse_list->offset += bytes_read;
641 		tar->entry_bytes_remaining -= bytes_read;
642 		tar->entry_bytes_unconsumed = bytes_read;
643 
644 		if (!tar->sparse_list->hole)
645 			return (ARCHIVE_OK);
646 		/* Current is hole data and skip this. */
647 	}
648 }
649 
650 static int
651 archive_read_format_tar_skip(struct archive_read *a)
652 {
653 	int64_t bytes_skipped;
654 	int64_t request;
655 	struct sparse_block *p;
656 	struct tar* tar;
657 
658 	tar = (struct tar *)(a->format->data);
659 
660 	/* Do not consume the hole of a sparse file. */
661 	request = 0;
662 	for (p = tar->sparse_list; p != NULL; p = p->next) {
663 		if (!p->hole) {
664 			if (p->remaining >= INT64_MAX - request) {
665 				return ARCHIVE_FATAL;
666 			}
667 			request += p->remaining;
668 		}
669 	}
670 	if (request > tar->entry_bytes_remaining)
671 		request = tar->entry_bytes_remaining;
672 	request += tar->entry_padding + tar->entry_bytes_unconsumed;
673 
674 	bytes_skipped = __archive_read_consume(a, request);
675 	if (bytes_skipped < 0)
676 		return (ARCHIVE_FATAL);
677 
678 	tar->entry_bytes_remaining = 0;
679 	tar->entry_bytes_unconsumed = 0;
680 	tar->entry_padding = 0;
681 
682 	/* Free the sparse list. */
683 	gnu_clear_sparse_list(tar);
684 
685 	return (ARCHIVE_OK);
686 }
687 
688 /*
689  * This function recursively interprets all of the headers associated
690  * with a single entry.
691  */
692 static int
693 tar_read_header(struct archive_read *a, struct tar *tar,
694     struct archive_entry *entry, size_t *unconsumed)
695 {
696 	ssize_t bytes;
697 	int err, eof_vol_header;
698 	const char *h;
699 	const struct archive_entry_header_ustar *header;
700 	const struct archive_entry_header_gnutar *gnuheader;
701 
702 	eof_vol_header = 0;
703 
704 	/* Loop until we find a workable header record. */
705 	for (;;) {
706 		tar_flush_unconsumed(a, unconsumed);
707 
708 		/* Read 512-byte header record */
709 		h = __archive_read_ahead(a, 512, &bytes);
710 		if (bytes < 0)
711 			return ((int)bytes);
712 		if (bytes == 0) { /* EOF at a block boundary. */
713 			/* Some writers do omit the block of nulls. <sigh> */
714 			return (ARCHIVE_EOF);
715 		}
716 		if (bytes < 512) {  /* Short block at EOF; this is bad. */
717 			archive_set_error(&a->archive,
718 			    ARCHIVE_ERRNO_FILE_FORMAT,
719 			    "Truncated tar archive");
720 			return (ARCHIVE_FATAL);
721 		}
722 		*unconsumed = 512;
723 
724 		/* Header is workable if it's not an end-of-archive mark. */
725 		if (h[0] != 0 || !archive_block_is_null(h))
726 			break;
727 
728 		/* Ensure format is set for archives with only null blocks. */
729 		if (a->archive.archive_format_name == NULL) {
730 			a->archive.archive_format = ARCHIVE_FORMAT_TAR;
731 			a->archive.archive_format_name = "tar";
732 		}
733 
734 		if (!tar->read_concatenated_archives) {
735 			/* Try to consume a second all-null record, as well. */
736 			tar_flush_unconsumed(a, unconsumed);
737 			h = __archive_read_ahead(a, 512, NULL);
738 			if (h != NULL && h[0] == 0 && archive_block_is_null(h))
739 				__archive_read_consume(a, 512);
740 			archive_clear_error(&a->archive);
741 			return (ARCHIVE_EOF);
742 		}
743 
744 		/*
745 		 * We're reading concatenated archives, ignore this block and
746 		 * loop to get the next.
747 		 */
748 	}
749 
750 	/*
751 	 * Note: If the checksum fails and we return ARCHIVE_RETRY,
752 	 * then the client is likely to just retry.  This is a very
753 	 * crude way to search for the next valid header!
754 	 *
755 	 * TODO: Improve this by implementing a real header scan.
756 	 */
757 	if (!checksum(a, h)) {
758 		tar_flush_unconsumed(a, unconsumed);
759 		archive_set_error(&a->archive, EINVAL, "Damaged tar archive");
760 		return (ARCHIVE_RETRY); /* Retryable: Invalid header */
761 	}
762 
763 	if (++tar->header_recursion_depth > 32) {
764 		tar_flush_unconsumed(a, unconsumed);
765 		archive_set_error(&a->archive, EINVAL, "Too many special headers");
766 		return (ARCHIVE_WARN);
767 	}
768 
769 	/* Determine the format variant. */
770 	header = (const struct archive_entry_header_ustar *)h;
771 
772 	switch(header->typeflag[0]) {
773 	case 'A': /* Solaris tar ACL */
774 		a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
775 		a->archive.archive_format_name = "Solaris tar";
776 		err = header_Solaris_ACL(a, tar, entry, h, unconsumed);
777 		break;
778 	case 'g': /* POSIX-standard 'g' header. */
779 		a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
780 		a->archive.archive_format_name = "POSIX pax interchange format";
781 		err = header_pax_global(a, tar, entry, h, unconsumed);
782 		if (err == ARCHIVE_EOF)
783 			return (err);
784 		break;
785 	case 'K': /* Long link name (GNU tar, others) */
786 		err = header_longlink(a, tar, entry, h, unconsumed);
787 		break;
788 	case 'L': /* Long filename (GNU tar, others) */
789 		err = header_longname(a, tar, entry, h, unconsumed);
790 		break;
791 	case 'V': /* GNU volume header */
792 		err = header_volume(a, tar, entry, h, unconsumed);
793 		if (err == ARCHIVE_EOF)
794 			eof_vol_header = 1;
795 		break;
796 	case 'X': /* Used by SUN tar; same as 'x'. */
797 		a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
798 		a->archive.archive_format_name =
799 		    "POSIX pax interchange format (Sun variant)";
800 		err = header_pax_extensions(a, tar, entry, h, unconsumed);
801 		break;
802 	case 'x': /* POSIX-standard 'x' header. */
803 		a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
804 		a->archive.archive_format_name = "POSIX pax interchange format";
805 		err = header_pax_extensions(a, tar, entry, h, unconsumed);
806 		break;
807 	default:
808 		gnuheader = (const struct archive_entry_header_gnutar *)h;
809 		if (memcmp(gnuheader->magic, "ustar  \0", 8) == 0) {
810 			a->archive.archive_format = ARCHIVE_FORMAT_TAR_GNUTAR;
811 			a->archive.archive_format_name = "GNU tar format";
812 			err = header_gnutar(a, tar, entry, h, unconsumed);
813 		} else if (memcmp(header->magic, "ustar", 5) == 0) {
814 			if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
815 				a->archive.archive_format = ARCHIVE_FORMAT_TAR_USTAR;
816 				a->archive.archive_format_name = "POSIX ustar format";
817 			}
818 			err = header_ustar(a, tar, entry, h);
819 		} else {
820 			a->archive.archive_format = ARCHIVE_FORMAT_TAR;
821 			a->archive.archive_format_name = "tar (non-POSIX)";
822 			err = header_old_tar(a, tar, entry, h);
823 		}
824 	}
825 	if (err == ARCHIVE_FATAL)
826 		return (err);
827 
828 	tar_flush_unconsumed(a, unconsumed);
829 
830 	h = NULL;
831 	header = NULL;
832 
833 	--tar->header_recursion_depth;
834 	/* Yuck.  Apple's design here ends up storing long pathname
835 	 * extensions for both the AppleDouble extension entry and the
836 	 * regular entry.
837 	 */
838 	if ((err == ARCHIVE_WARN || err == ARCHIVE_OK) &&
839 	    tar->header_recursion_depth == 0 &&
840 	    tar->process_mac_extensions) {
841 		int err2 = read_mac_metadata_blob(a, tar, entry, h, unconsumed);
842 		if (err2 < err)
843 			err = err2;
844 	}
845 
846 	/* We return warnings or success as-is.  Anything else is fatal. */
847 	if (err == ARCHIVE_WARN || err == ARCHIVE_OK) {
848 		if (tar->sparse_gnu_pending) {
849 			if (tar->sparse_gnu_major == 1 &&
850 			    tar->sparse_gnu_minor == 0) {
851 				ssize_t bytes_read;
852 
853 				tar->sparse_gnu_pending = 0;
854 				/* Read initial sparse map. */
855 				bytes_read = gnu_sparse_10_read(a, tar, unconsumed);
856 				if (bytes_read < 0)
857 					return ((int)bytes_read);
858 				tar->entry_bytes_remaining -= bytes_read;
859 			} else {
860 				archive_set_error(&a->archive,
861 				    ARCHIVE_ERRNO_MISC,
862 				    "Unrecognized GNU sparse file format");
863 				return (ARCHIVE_WARN);
864 			}
865 			tar->sparse_gnu_pending = 0;
866 		}
867 		return (err);
868 	}
869 	if (err == ARCHIVE_EOF) {
870 		if (!eof_vol_header) {
871 			/* EOF when recursively reading a header is bad. */
872 			archive_set_error(&a->archive, EINVAL,
873 			    "Damaged tar archive");
874 		} else {
875 			/* If we encounter just a GNU volume header treat
876 			 * this situation as an empty archive */
877 			return (ARCHIVE_EOF);
878 		}
879 	}
880 	return (ARCHIVE_FATAL);
881 }
882 
883 /*
884  * Return true if block checksum is correct.
885  */
886 static int
887 checksum(struct archive_read *a, const void *h)
888 {
889 	const unsigned char *bytes;
890 	const struct archive_entry_header_ustar	*header;
891 	int check, sum;
892 	size_t i;
893 
894 	(void)a; /* UNUSED */
895 	bytes = (const unsigned char *)h;
896 	header = (const struct archive_entry_header_ustar *)h;
897 
898 	/* Checksum field must hold an octal number */
899 	for (i = 0; i < sizeof(header->checksum); ++i) {
900 		char c = header->checksum[i];
901 		if (c != ' ' && c != '\0' && (c < '0' || c > '7'))
902 			return 0;
903 	}
904 
905 	/*
906 	 * Test the checksum.  Note that POSIX specifies _unsigned_
907 	 * bytes for this calculation.
908 	 */
909 	sum = (int)tar_atol(header->checksum, sizeof(header->checksum));
910 	check = 0;
911 	for (i = 0; i < 148; i++)
912 		check += (unsigned char)bytes[i];
913 	for (; i < 156; i++)
914 		check += 32;
915 	for (; i < 512; i++)
916 		check += (unsigned char)bytes[i];
917 	if (sum == check)
918 		return (1);
919 
920 	/*
921 	 * Repeat test with _signed_ bytes, just in case this archive
922 	 * was created by an old BSD, Solaris, or HP-UX tar with a
923 	 * broken checksum calculation.
924 	 */
925 	check = 0;
926 	for (i = 0; i < 148; i++)
927 		check += (signed char)bytes[i];
928 	for (; i < 156; i++)
929 		check += 32;
930 	for (; i < 512; i++)
931 		check += (signed char)bytes[i];
932 	if (sum == check)
933 		return (1);
934 
935 	return (0);
936 }
937 
938 /*
939  * Return true if this block contains only nulls.
940  */
941 static int
942 archive_block_is_null(const char *p)
943 {
944 	unsigned i;
945 
946 	for (i = 0; i < 512; i++)
947 		if (*p++)
948 			return (0);
949 	return (1);
950 }
951 
952 /*
953  * Interpret 'A' Solaris ACL header
954  */
955 static int
956 header_Solaris_ACL(struct archive_read *a, struct tar *tar,
957     struct archive_entry *entry, const void *h, size_t *unconsumed)
958 {
959 	const struct archive_entry_header_ustar *header;
960 	size_t size;
961 	int err, acl_type;
962 	int64_t type;
963 	char *acl, *p;
964 
965 	/*
966 	 * read_body_to_string adds a NUL terminator, but we need a little
967 	 * more to make sure that we don't overrun acl_text later.
968 	 */
969 	header = (const struct archive_entry_header_ustar *)h;
970 	size = (size_t)tar_atol(header->size, sizeof(header->size));
971 	err = read_body_to_string(a, tar, &(tar->acl_text), h, unconsumed);
972 	if (err != ARCHIVE_OK)
973 		return (err);
974 
975 	/* Recursively read next header */
976 	err = tar_read_header(a, tar, entry, unconsumed);
977 	if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
978 		return (err);
979 
980 	/* TODO: Examine the first characters to see if this
981 	 * is an AIX ACL descriptor.  We'll likely never support
982 	 * them, but it would be polite to recognize and warn when
983 	 * we do see them. */
984 
985 	/* Leading octal number indicates ACL type and number of entries. */
986 	p = acl = tar->acl_text.s;
987 	type = 0;
988 	while (*p != '\0' && p < acl + size) {
989 		if (*p < '0' || *p > '7') {
990 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
991 			    "Malformed Solaris ACL attribute (invalid digit)");
992 			return(ARCHIVE_WARN);
993 		}
994 		type <<= 3;
995 		type += *p - '0';
996 		if (type > 077777777) {
997 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
998 			    "Malformed Solaris ACL attribute (count too large)");
999 			return (ARCHIVE_WARN);
1000 		}
1001 		p++;
1002 	}
1003 	switch ((int)type & ~0777777) {
1004 	case 01000000:
1005 		/* POSIX.1e ACL */
1006 		acl_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS;
1007 		break;
1008 	case 03000000:
1009 		/* NFSv4 ACL */
1010 		acl_type = ARCHIVE_ENTRY_ACL_TYPE_NFS4;
1011 		break;
1012 	default:
1013 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1014 		    "Malformed Solaris ACL attribute (unsupported type %o)",
1015 		    (int)type);
1016 		return (ARCHIVE_WARN);
1017 	}
1018 	p++;
1019 
1020 	if (p >= acl + size) {
1021 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1022 		    "Malformed Solaris ACL attribute (body overflow)");
1023 		return(ARCHIVE_WARN);
1024 	}
1025 
1026 	/* ACL text is null-terminated; find the end. */
1027 	size -= (p - acl);
1028 	acl = p;
1029 
1030 	while (*p != '\0' && p < acl + size)
1031 		p++;
1032 
1033 	if (tar->sconv_acl == NULL) {
1034 		tar->sconv_acl = archive_string_conversion_from_charset(
1035 		    &(a->archive), "UTF-8", 1);
1036 		if (tar->sconv_acl == NULL)
1037 			return (ARCHIVE_FATAL);
1038 	}
1039 	archive_strncpy(&(tar->localname), acl, p - acl);
1040 	err = archive_acl_from_text_l(archive_entry_acl(entry),
1041 	    tar->localname.s, acl_type, tar->sconv_acl);
1042 	if (err != ARCHIVE_OK) {
1043 		if (errno == ENOMEM) {
1044 			archive_set_error(&a->archive, ENOMEM,
1045 			    "Can't allocate memory for ACL");
1046 		} else
1047 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1048 			    "Malformed Solaris ACL attribute (unparsable)");
1049 	}
1050 	return (err);
1051 }
1052 
1053 /*
1054  * Interpret 'K' long linkname header.
1055  */
1056 static int
1057 header_longlink(struct archive_read *a, struct tar *tar,
1058     struct archive_entry *entry, const void *h, size_t *unconsumed)
1059 {
1060 	int err;
1061 
1062 	err = read_body_to_string(a, tar, &(tar->longlink), h, unconsumed);
1063 	if (err != ARCHIVE_OK)
1064 		return (err);
1065 	err = tar_read_header(a, tar, entry, unconsumed);
1066 	if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
1067 		return (err);
1068 	/* Set symlink if symlink already set, else hardlink. */
1069 	archive_entry_copy_link(entry, tar->longlink.s);
1070 	return (ARCHIVE_OK);
1071 }
1072 
1073 static int
1074 set_conversion_failed_error(struct archive_read *a,
1075     struct archive_string_conv *sconv, const char *name)
1076 {
1077 	if (errno == ENOMEM) {
1078 		archive_set_error(&a->archive, ENOMEM,
1079 		    "Can't allocate memory for %s", name);
1080 		return (ARCHIVE_FATAL);
1081 	}
1082 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1083 	    "%s can't be converted from %s to current locale.",
1084 	    name, archive_string_conversion_charset_name(sconv));
1085 	return (ARCHIVE_WARN);
1086 }
1087 
1088 /*
1089  * Interpret 'L' long filename header.
1090  */
1091 static int
1092 header_longname(struct archive_read *a, struct tar *tar,
1093     struct archive_entry *entry, const void *h, size_t *unconsumed)
1094 {
1095 	int err;
1096 
1097 	err = read_body_to_string(a, tar, &(tar->longname), h, unconsumed);
1098 	if (err != ARCHIVE_OK)
1099 		return (err);
1100 	/* Read and parse "real" header, then override name. */
1101 	err = tar_read_header(a, tar, entry, unconsumed);
1102 	if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
1103 		return (err);
1104 	if (archive_entry_copy_pathname_l(entry, tar->longname.s,
1105 	    archive_strlen(&(tar->longname)), tar->sconv) != 0)
1106 		err = set_conversion_failed_error(a, tar->sconv, "Pathname");
1107 	return (err);
1108 }
1109 
1110 
1111 /*
1112  * Interpret 'V' GNU tar volume header.
1113  */
1114 static int
1115 header_volume(struct archive_read *a, struct tar *tar,
1116     struct archive_entry *entry, const void *h, size_t *unconsumed)
1117 {
1118 	(void)h;
1119 
1120 	/* Just skip this and read the next header. */
1121 	return (tar_read_header(a, tar, entry, unconsumed));
1122 }
1123 
1124 /*
1125  * Read body of an archive entry into an archive_string object.
1126  */
1127 static int
1128 read_body_to_string(struct archive_read *a, struct tar *tar,
1129     struct archive_string *as, const void *h, size_t *unconsumed)
1130 {
1131 	int64_t size;
1132 	const struct archive_entry_header_ustar *header;
1133 	const void *src;
1134 
1135 	(void)tar; /* UNUSED */
1136 	header = (const struct archive_entry_header_ustar *)h;
1137 	size  = tar_atol(header->size, sizeof(header->size));
1138 	if ((size > 1048576) || (size < 0)) {
1139 		archive_set_error(&a->archive, EINVAL,
1140 		    "Special header too large");
1141 		return (ARCHIVE_FATAL);
1142 	}
1143 
1144 	/* Fail if we can't make our buffer big enough. */
1145 	if (archive_string_ensure(as, (size_t)size+1) == NULL) {
1146 		archive_set_error(&a->archive, ENOMEM,
1147 		    "No memory");
1148 		return (ARCHIVE_FATAL);
1149 	}
1150 
1151 	tar_flush_unconsumed(a, unconsumed);
1152 
1153 	/* Read the body into the string. */
1154 	*unconsumed = (size_t)((size + 511) & ~ 511);
1155 	src = __archive_read_ahead(a, *unconsumed, NULL);
1156 	if (src == NULL) {
1157 		*unconsumed = 0;
1158 		return (ARCHIVE_FATAL);
1159 	}
1160 	memcpy(as->s, src, (size_t)size);
1161 	as->s[size] = '\0';
1162 	as->length = (size_t)size;
1163 	return (ARCHIVE_OK);
1164 }
1165 
1166 /*
1167  * Parse out common header elements.
1168  *
1169  * This would be the same as header_old_tar, except that the
1170  * filename is handled slightly differently for old and POSIX
1171  * entries  (POSIX entries support a 'prefix').  This factoring
1172  * allows header_old_tar and header_ustar
1173  * to handle filenames differently, while still putting most of the
1174  * common parsing into one place.
1175  */
1176 static int
1177 header_common(struct archive_read *a, struct tar *tar,
1178     struct archive_entry *entry, const void *h)
1179 {
1180 	const struct archive_entry_header_ustar	*header;
1181 	char	tartype;
1182 	int     err = ARCHIVE_OK;
1183 
1184 	header = (const struct archive_entry_header_ustar *)h;
1185 	if (header->linkname[0])
1186 		archive_strncpy(&(tar->entry_linkpath),
1187 		    header->linkname, sizeof(header->linkname));
1188 	else
1189 		archive_string_empty(&(tar->entry_linkpath));
1190 
1191 	/* Parse out the numeric fields (all are octal) */
1192 	archive_entry_set_mode(entry,
1193 		(mode_t)tar_atol(header->mode, sizeof(header->mode)));
1194 	archive_entry_set_uid(entry, tar_atol(header->uid, sizeof(header->uid)));
1195 	archive_entry_set_gid(entry, tar_atol(header->gid, sizeof(header->gid)));
1196 	tar->entry_bytes_remaining = tar_atol(header->size, sizeof(header->size));
1197 	if (tar->entry_bytes_remaining < 0) {
1198 		tar->entry_bytes_remaining = 0;
1199 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1200 		    "Tar entry has negative size");
1201 		return (ARCHIVE_FATAL);
1202 	}
1203 	if (tar->entry_bytes_remaining == INT64_MAX) {
1204 		/* Note: tar_atol returns INT64_MAX on overflow */
1205 		tar->entry_bytes_remaining = 0;
1206 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1207 		    "Tar entry size overflow");
1208 		return (ARCHIVE_FATAL);
1209 	}
1210 	tar->realsize = tar->entry_bytes_remaining;
1211 	archive_entry_set_size(entry, tar->entry_bytes_remaining);
1212 	archive_entry_set_mtime(entry, tar_atol(header->mtime, sizeof(header->mtime)), 0);
1213 
1214 	/* Handle the tar type flag appropriately. */
1215 	tartype = header->typeflag[0];
1216 
1217 	switch (tartype) {
1218 	case '1': /* Hard link */
1219 		if (archive_entry_copy_hardlink_l(entry, tar->entry_linkpath.s,
1220 		    archive_strlen(&(tar->entry_linkpath)), tar->sconv) != 0) {
1221 			err = set_conversion_failed_error(a, tar->sconv,
1222 			    "Linkname");
1223 			if (err == ARCHIVE_FATAL)
1224 				return (err);
1225 		}
1226 		/*
1227 		 * The following may seem odd, but: Technically, tar
1228 		 * does not store the file type for a "hard link"
1229 		 * entry, only the fact that it is a hard link.  So, I
1230 		 * leave the type zero normally.  But, pax interchange
1231 		 * format allows hard links to have data, which
1232 		 * implies that the underlying entry is a regular
1233 		 * file.
1234 		 */
1235 		if (archive_entry_size(entry) > 0)
1236 			archive_entry_set_filetype(entry, AE_IFREG);
1237 
1238 		/*
1239 		 * A tricky point: Traditionally, tar readers have
1240 		 * ignored the size field when reading hardlink
1241 		 * entries, and some writers put non-zero sizes even
1242 		 * though the body is empty.  POSIX blessed this
1243 		 * convention in the 1988 standard, but broke with
1244 		 * this tradition in 2001 by permitting hardlink
1245 		 * entries to store valid bodies in pax interchange
1246 		 * format, but not in ustar format.  Since there is no
1247 		 * hard and fast way to distinguish pax interchange
1248 		 * from earlier archives (the 'x' and 'g' entries are
1249 		 * optional, after all), we need a heuristic.
1250 		 */
1251 		if (archive_entry_size(entry) == 0) {
1252 			/* If the size is already zero, we're done. */
1253 		}  else if (a->archive.archive_format
1254 		    == ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE) {
1255 			/* Definitely pax extended; must obey hardlink size. */
1256 		} else if (a->archive.archive_format == ARCHIVE_FORMAT_TAR
1257 		    || a->archive.archive_format == ARCHIVE_FORMAT_TAR_GNUTAR)
1258 		{
1259 			/* Old-style or GNU tar: we must ignore the size. */
1260 			archive_entry_set_size(entry, 0);
1261 			tar->entry_bytes_remaining = 0;
1262 		} else if (archive_read_format_tar_bid(a, 50) > 50) {
1263 			/*
1264 			 * We don't know if it's pax: If the bid
1265 			 * function sees a valid ustar header
1266 			 * immediately following, then let's ignore
1267 			 * the hardlink size.
1268 			 */
1269 			archive_entry_set_size(entry, 0);
1270 			tar->entry_bytes_remaining = 0;
1271 		}
1272 		/*
1273 		 * TODO: There are still two cases I'd like to handle:
1274 		 *   = a ustar non-pax archive with a hardlink entry at
1275 		 *     end-of-archive.  (Look for block of nulls following?)
1276 		 *   = a pax archive that has not seen any pax headers
1277 		 *     and has an entry which is a hardlink entry storing
1278 		 *     a body containing an uncompressed tar archive.
1279 		 * The first is worth addressing; I don't see any reliable
1280 		 * way to deal with the second possibility.
1281 		 */
1282 		break;
1283 	case '2': /* Symlink */
1284 		archive_entry_set_filetype(entry, AE_IFLNK);
1285 		archive_entry_set_size(entry, 0);
1286 		tar->entry_bytes_remaining = 0;
1287 		if (archive_entry_copy_symlink_l(entry, tar->entry_linkpath.s,
1288 		    archive_strlen(&(tar->entry_linkpath)), tar->sconv) != 0) {
1289 			err = set_conversion_failed_error(a, tar->sconv,
1290 			    "Linkname");
1291 			if (err == ARCHIVE_FATAL)
1292 				return (err);
1293 		}
1294 		break;
1295 	case '3': /* Character device */
1296 		archive_entry_set_filetype(entry, AE_IFCHR);
1297 		archive_entry_set_size(entry, 0);
1298 		tar->entry_bytes_remaining = 0;
1299 		break;
1300 	case '4': /* Block device */
1301 		archive_entry_set_filetype(entry, AE_IFBLK);
1302 		archive_entry_set_size(entry, 0);
1303 		tar->entry_bytes_remaining = 0;
1304 		break;
1305 	case '5': /* Dir */
1306 		archive_entry_set_filetype(entry, AE_IFDIR);
1307 		archive_entry_set_size(entry, 0);
1308 		tar->entry_bytes_remaining = 0;
1309 		break;
1310 	case '6': /* FIFO device */
1311 		archive_entry_set_filetype(entry, AE_IFIFO);
1312 		archive_entry_set_size(entry, 0);
1313 		tar->entry_bytes_remaining = 0;
1314 		break;
1315 	case 'D': /* GNU incremental directory type */
1316 		/*
1317 		 * No special handling is actually required here.
1318 		 * It might be nice someday to preprocess the file list and
1319 		 * provide it to the client, though.
1320 		 */
1321 		archive_entry_set_filetype(entry, AE_IFDIR);
1322 		break;
1323 	case 'M': /* GNU "Multi-volume" (remainder of file from last archive)*/
1324 		/*
1325 		 * As far as I can tell, this is just like a regular file
1326 		 * entry, except that the contents should be _appended_ to
1327 		 * the indicated file at the indicated offset.  This may
1328 		 * require some API work to fully support.
1329 		 */
1330 		break;
1331 	case 'N': /* Old GNU "long filename" entry. */
1332 		/* The body of this entry is a script for renaming
1333 		 * previously-extracted entries.  Ugh.  It will never
1334 		 * be supported by libarchive. */
1335 		archive_entry_set_filetype(entry, AE_IFREG);
1336 		break;
1337 	case 'S': /* GNU sparse files */
1338 		/*
1339 		 * Sparse files are really just regular files with
1340 		 * sparse information in the extended area.
1341 		 */
1342 		/* FALLTHROUGH */
1343 	case '0':
1344 		/*
1345 		 * Enable sparse file "read" support only for regular
1346 		 * files and explicit GNU sparse files.  However, we
1347 		 * don't allow non-standard file types to be sparse.
1348 		 */
1349 		tar->sparse_allowed = 1;
1350 		/* FALLTHROUGH */
1351 	default: /* Regular file  and non-standard types */
1352 		/*
1353 		 * Per POSIX: non-recognized types should always be
1354 		 * treated as regular files.
1355 		 */
1356 		archive_entry_set_filetype(entry, AE_IFREG);
1357 		break;
1358 	}
1359 	return (err);
1360 }
1361 
1362 /*
1363  * Parse out header elements for "old-style" tar archives.
1364  */
1365 static int
1366 header_old_tar(struct archive_read *a, struct tar *tar,
1367     struct archive_entry *entry, const void *h)
1368 {
1369 	const struct archive_entry_header_ustar	*header;
1370 	int err = ARCHIVE_OK, err2;
1371 
1372 	/* Copy filename over (to ensure null termination). */
1373 	header = (const struct archive_entry_header_ustar *)h;
1374 	if (archive_entry_copy_pathname_l(entry,
1375 	    header->name, sizeof(header->name), tar->sconv) != 0) {
1376 		err = set_conversion_failed_error(a, tar->sconv, "Pathname");
1377 		if (err == ARCHIVE_FATAL)
1378 			return (err);
1379 	}
1380 
1381 	/* Grab rest of common fields */
1382 	err2 = header_common(a, tar, entry, h);
1383 	if (err > err2)
1384 		err = err2;
1385 
1386 	tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1387 	return (err);
1388 }
1389 
1390 /*
1391  * Read a Mac AppleDouble-encoded blob of file metadata,
1392  * if there is one.
1393  */
1394 static int
1395 read_mac_metadata_blob(struct archive_read *a, struct tar *tar,
1396     struct archive_entry *entry, const void *h, size_t *unconsumed)
1397 {
1398 	int64_t size;
1399 	const void *data;
1400 	const char *p, *name;
1401 	const wchar_t *wp, *wname;
1402 
1403 	(void)h; /* UNUSED */
1404 
1405 	wname = wp = archive_entry_pathname_w(entry);
1406 	if (wp != NULL) {
1407 		/* Find the last path element. */
1408 		for (; *wp != L'\0'; ++wp) {
1409 			if (wp[0] == '/' && wp[1] != L'\0')
1410 				wname = wp + 1;
1411 		}
1412 		/*
1413 		 * If last path element starts with "._", then
1414 		 * this is a Mac extension.
1415 		 */
1416 		if (wname[0] != L'.' || wname[1] != L'_' || wname[2] == L'\0')
1417 			return ARCHIVE_OK;
1418 	} else {
1419 		/* Find the last path element. */
1420 		name = p = archive_entry_pathname(entry);
1421 		if (p == NULL)
1422 			return (ARCHIVE_FAILED);
1423 		for (; *p != '\0'; ++p) {
1424 			if (p[0] == '/' && p[1] != '\0')
1425 				name = p + 1;
1426 		}
1427 		/*
1428 		 * If last path element starts with "._", then
1429 		 * this is a Mac extension.
1430 		 */
1431 		if (name[0] != '.' || name[1] != '_' || name[2] == '\0')
1432 			return ARCHIVE_OK;
1433 	}
1434 
1435  	/* Read the body as a Mac OS metadata blob. */
1436 	size = archive_entry_size(entry);
1437 
1438 	/*
1439 	 * TODO: Look beyond the body here to peek at the next header.
1440 	 * If it's a regular header (not an extension header)
1441 	 * that has the wrong name, just return the current
1442 	 * entry as-is, without consuming the body here.
1443 	 * That would reduce the risk of us mis-identifying
1444 	 * an ordinary file that just happened to have
1445 	 * a name starting with "._".
1446 	 *
1447 	 * Q: Is the above idea really possible?  Even
1448 	 * when there are GNU or pax extension entries?
1449 	 */
1450 	data = __archive_read_ahead(a, (size_t)size, NULL);
1451 	if (data == NULL) {
1452 		*unconsumed = 0;
1453 		return (ARCHIVE_FATAL);
1454 	}
1455 	archive_entry_copy_mac_metadata(entry, data, (size_t)size);
1456 	*unconsumed = (size_t)((size + 511) & ~ 511);
1457 	tar_flush_unconsumed(a, unconsumed);
1458 	return (tar_read_header(a, tar, entry, unconsumed));
1459 }
1460 
1461 /*
1462  * Parse a file header for a pax extended archive entry.
1463  */
1464 static int
1465 header_pax_global(struct archive_read *a, struct tar *tar,
1466     struct archive_entry *entry, const void *h, size_t *unconsumed)
1467 {
1468 	int err;
1469 
1470 	err = read_body_to_string(a, tar, &(tar->pax_global), h, unconsumed);
1471 	if (err != ARCHIVE_OK)
1472 		return (err);
1473 	err = tar_read_header(a, tar, entry, unconsumed);
1474 	return (err);
1475 }
1476 
1477 static int
1478 header_pax_extensions(struct archive_read *a, struct tar *tar,
1479     struct archive_entry *entry, const void *h, size_t *unconsumed)
1480 {
1481 	int err, err2;
1482 
1483 	err = read_body_to_string(a, tar, &(tar->pax_header), h, unconsumed);
1484 	if (err != ARCHIVE_OK)
1485 		return (err);
1486 
1487 	/* Parse the next header. */
1488 	err = tar_read_header(a, tar, entry, unconsumed);
1489 	if ((err != ARCHIVE_OK) && (err != ARCHIVE_WARN))
1490 		return (err);
1491 
1492 	/*
1493 	 * TODO: Parse global/default options into 'entry' struct here
1494 	 * before handling file-specific options.
1495 	 *
1496 	 * This design (parse standard header, then overwrite with pax
1497 	 * extended attribute data) usually works well, but isn't ideal;
1498 	 * it would be better to parse the pax extended attributes first
1499 	 * and then skip any fields in the standard header that were
1500 	 * defined in the pax header.
1501 	 */
1502 	err2 = pax_header(a, tar, entry, &tar->pax_header);
1503 	err =  err_combine(err, err2);
1504 	tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1505 	return (err);
1506 }
1507 
1508 
1509 /*
1510  * Parse a file header for a Posix "ustar" archive entry.  This also
1511  * handles "pax" or "extended ustar" entries.
1512  */
1513 static int
1514 header_ustar(struct archive_read *a, struct tar *tar,
1515     struct archive_entry *entry, const void *h)
1516 {
1517 	const struct archive_entry_header_ustar	*header;
1518 	struct archive_string *as;
1519 	int err = ARCHIVE_OK, r;
1520 
1521 	header = (const struct archive_entry_header_ustar *)h;
1522 
1523 	/* Copy name into an internal buffer to ensure null-termination. */
1524 	as = &(tar->entry_pathname);
1525 	if (header->prefix[0]) {
1526 		archive_strncpy(as, header->prefix, sizeof(header->prefix));
1527 		if (as->s[archive_strlen(as) - 1] != '/')
1528 			archive_strappend_char(as, '/');
1529 		archive_strncat(as, header->name, sizeof(header->name));
1530 	} else {
1531 		archive_strncpy(as, header->name, sizeof(header->name));
1532 	}
1533 	if (archive_entry_copy_pathname_l(entry, as->s, archive_strlen(as),
1534 	    tar->sconv) != 0) {
1535 		err = set_conversion_failed_error(a, tar->sconv, "Pathname");
1536 		if (err == ARCHIVE_FATAL)
1537 			return (err);
1538 	}
1539 
1540 	/* Handle rest of common fields. */
1541 	r = header_common(a, tar, entry, h);
1542 	if (r == ARCHIVE_FATAL)
1543 		return (r);
1544 	if (r < err)
1545 		err = r;
1546 
1547 	/* Handle POSIX ustar fields. */
1548 	if (archive_entry_copy_uname_l(entry,
1549 	    header->uname, sizeof(header->uname), tar->sconv) != 0) {
1550 		err = set_conversion_failed_error(a, tar->sconv, "Uname");
1551 		if (err == ARCHIVE_FATAL)
1552 			return (err);
1553 	}
1554 
1555 	if (archive_entry_copy_gname_l(entry,
1556 	    header->gname, sizeof(header->gname), tar->sconv) != 0) {
1557 		err = set_conversion_failed_error(a, tar->sconv, "Gname");
1558 		if (err == ARCHIVE_FATAL)
1559 			return (err);
1560 	}
1561 
1562 	/* Parse out device numbers only for char and block specials. */
1563 	if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
1564 		archive_entry_set_rdevmajor(entry, (dev_t)
1565 		    tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
1566 		archive_entry_set_rdevminor(entry, (dev_t)
1567 		    tar_atol(header->rdevminor, sizeof(header->rdevminor)));
1568 	}
1569 
1570 	tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
1571 
1572 	return (err);
1573 }
1574 
1575 
1576 /*
1577  * Parse the pax extended attributes record.
1578  *
1579  * Returns non-zero if there's an error in the data.
1580  */
1581 static int
1582 pax_header(struct archive_read *a, struct tar *tar,
1583     struct archive_entry *entry, struct archive_string *in_as)
1584 {
1585 	size_t attr_length, l, line_length, value_length;
1586 	char *p;
1587 	char *key, *value;
1588 	struct archive_string *as;
1589 	struct archive_string_conv *sconv;
1590 	int err, err2;
1591 	char *attr = in_as->s;
1592 
1593 	attr_length = in_as->length;
1594 	tar->pax_hdrcharset_binary = 0;
1595 	archive_string_empty(&(tar->entry_gname));
1596 	archive_string_empty(&(tar->entry_linkpath));
1597 	archive_string_empty(&(tar->entry_pathname));
1598 	archive_string_empty(&(tar->entry_pathname_override));
1599 	archive_string_empty(&(tar->entry_uname));
1600 	err = ARCHIVE_OK;
1601 	while (attr_length > 0) {
1602 		/* Parse decimal length field at start of line. */
1603 		line_length = 0;
1604 		l = attr_length;
1605 		p = attr; /* Record start of line. */
1606 		while (l>0) {
1607 			if (*p == ' ') {
1608 				p++;
1609 				l--;
1610 				break;
1611 			}
1612 			if (*p < '0' || *p > '9') {
1613 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1614 				    "Ignoring malformed pax extended attributes");
1615 				return (ARCHIVE_WARN);
1616 			}
1617 			line_length *= 10;
1618 			line_length += *p - '0';
1619 			if (line_length > 999999) {
1620 				archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1621 				    "Rejecting pax extended attribute > 1MB");
1622 				return (ARCHIVE_WARN);
1623 			}
1624 			p++;
1625 			l--;
1626 		}
1627 
1628 		/*
1629 		 * Parsed length must be no bigger than available data,
1630 		 * at least 1, and the last character of the line must
1631 		 * be '\n'.
1632 		 */
1633 		if (line_length > attr_length
1634 		    || line_length < 1
1635 		    || attr[line_length - 1] != '\n')
1636 		{
1637 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1638 			    "Ignoring malformed pax extended attribute");
1639 			return (ARCHIVE_WARN);
1640 		}
1641 
1642 		/* Null-terminate the line. */
1643 		attr[line_length - 1] = '\0';
1644 
1645 		/* Find end of key and null terminate it. */
1646 		key = p;
1647 		if (key[0] == '=')
1648 			return (-1);
1649 		while (*p && *p != '=')
1650 			++p;
1651 		if (*p == '\0') {
1652 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1653 			    "Invalid pax extended attributes");
1654 			return (ARCHIVE_WARN);
1655 		}
1656 		*p = '\0';
1657 
1658 		value = p + 1;
1659 
1660 		/* Some values may be binary data */
1661 		value_length = attr + line_length - 1 - value;
1662 
1663 		/* Identify this attribute and set it in the entry. */
1664 		err2 = pax_attribute(a, tar, entry, key, value, value_length);
1665 		if (err2 == ARCHIVE_FATAL)
1666 			return (err2);
1667 		err = err_combine(err, err2);
1668 
1669 		/* Skip to next line */
1670 		attr += line_length;
1671 		attr_length -= line_length;
1672 	}
1673 
1674 	/*
1675 	 * PAX format uses UTF-8 as default charset for its metadata
1676 	 * unless hdrcharset=BINARY is present in its header.
1677 	 * We apply the charset specified by the hdrcharset option only
1678 	 * when the hdrcharset attribute(in PAX header) is BINARY because
1679 	 * we respect the charset described in PAX header and BINARY also
1680 	 * means that metadata(filename,uname and gname) character-set
1681 	 * is unknown.
1682 	 */
1683 	if (tar->pax_hdrcharset_binary)
1684 		sconv = tar->opt_sconv;
1685 	else {
1686 		sconv = archive_string_conversion_from_charset(
1687 		    &(a->archive), "UTF-8", 1);
1688 		if (sconv == NULL)
1689 			return (ARCHIVE_FATAL);
1690 		if (tar->compat_2x)
1691 			archive_string_conversion_set_opt(sconv,
1692 			    SCONV_SET_OPT_UTF8_LIBARCHIVE2X);
1693 	}
1694 
1695 	if (archive_strlen(&(tar->entry_gname)) > 0) {
1696 		if (archive_entry_copy_gname_l(entry, tar->entry_gname.s,
1697 		    archive_strlen(&(tar->entry_gname)), sconv) != 0) {
1698 			err = set_conversion_failed_error(a, sconv, "Gname");
1699 			if (err == ARCHIVE_FATAL)
1700 				return (err);
1701 			/* Use a converted an original name. */
1702 			archive_entry_copy_gname(entry, tar->entry_gname.s);
1703 		}
1704 	}
1705 	if (archive_strlen(&(tar->entry_linkpath)) > 0) {
1706 		if (archive_entry_copy_link_l(entry, tar->entry_linkpath.s,
1707 		    archive_strlen(&(tar->entry_linkpath)), sconv) != 0) {
1708 			err = set_conversion_failed_error(a, sconv, "Linkname");
1709 			if (err == ARCHIVE_FATAL)
1710 				return (err);
1711 			/* Use a converted an original name. */
1712 			archive_entry_copy_link(entry, tar->entry_linkpath.s);
1713 		}
1714 	}
1715 	/*
1716 	 * Some extensions (such as the GNU sparse file extensions)
1717 	 * deliberately store a synthetic name under the regular 'path'
1718 	 * attribute and the real file name under a different attribute.
1719 	 * Since we're supposed to not care about the order, we
1720 	 * have no choice but to store all of the various filenames
1721 	 * we find and figure it all out afterwards.  This is the
1722 	 * figuring out part.
1723 	 */
1724 	as = NULL;
1725 	if (archive_strlen(&(tar->entry_pathname_override)) > 0)
1726 		as = &(tar->entry_pathname_override);
1727 	else if (archive_strlen(&(tar->entry_pathname)) > 0)
1728 		as = &(tar->entry_pathname);
1729 	if (as != NULL) {
1730 		if (archive_entry_copy_pathname_l(entry, as->s,
1731 		    archive_strlen(as), sconv) != 0) {
1732 			err = set_conversion_failed_error(a, sconv, "Pathname");
1733 			if (err == ARCHIVE_FATAL)
1734 				return (err);
1735 			/* Use a converted an original name. */
1736 			archive_entry_copy_pathname(entry, as->s);
1737 		}
1738 	}
1739 	if (archive_strlen(&(tar->entry_uname)) > 0) {
1740 		if (archive_entry_copy_uname_l(entry, tar->entry_uname.s,
1741 		    archive_strlen(&(tar->entry_uname)), sconv) != 0) {
1742 			err = set_conversion_failed_error(a, sconv, "Uname");
1743 			if (err == ARCHIVE_FATAL)
1744 				return (err);
1745 			/* Use a converted an original name. */
1746 			archive_entry_copy_uname(entry, tar->entry_uname.s);
1747 		}
1748 	}
1749 	return (err);
1750 }
1751 
1752 static int
1753 pax_attribute_xattr(struct archive_entry *entry,
1754 	const char *name, const char *value)
1755 {
1756 	char *name_decoded;
1757 	void *value_decoded;
1758 	size_t value_len;
1759 
1760 	if (strlen(name) < 18 || (memcmp(name, "LIBARCHIVE.xattr.", 17)) != 0)
1761 		return 3;
1762 
1763 	name += 17;
1764 
1765 	/* URL-decode name */
1766 	name_decoded = url_decode(name);
1767 	if (name_decoded == NULL)
1768 		return 2;
1769 
1770 	/* Base-64 decode value */
1771 	value_decoded = base64_decode(value, strlen(value), &value_len);
1772 	if (value_decoded == NULL) {
1773 		free(name_decoded);
1774 		return 1;
1775 	}
1776 
1777 	archive_entry_xattr_add_entry(entry, name_decoded,
1778 		value_decoded, value_len);
1779 
1780 	free(name_decoded);
1781 	free(value_decoded);
1782 	return 0;
1783 }
1784 
1785 static int
1786 pax_attribute_schily_xattr(struct archive_entry *entry,
1787 	const char *name, const char *value, size_t value_length)
1788 {
1789 	if (strlen(name) < 14 || (memcmp(name, "SCHILY.xattr.", 13)) != 0)
1790 		return 1;
1791 
1792 	name += 13;
1793 
1794 	archive_entry_xattr_add_entry(entry, name, value, value_length);
1795 
1796 	return 0;
1797 }
1798 
1799 static int
1800 pax_attribute_rht_security_selinux(struct archive_entry *entry,
1801 	const char *value, size_t value_length)
1802 {
1803 	archive_entry_xattr_add_entry(entry, "security.selinux",
1804             value, value_length);
1805 
1806 	return 0;
1807 }
1808 
1809 static int
1810 pax_attribute_acl(struct archive_read *a, struct tar *tar,
1811     struct archive_entry *entry, const char *value, int type)
1812 {
1813 	int r;
1814 	const char* errstr;
1815 
1816 	switch (type) {
1817 	case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
1818 		errstr = "SCHILY.acl.access";
1819 		break;
1820 	case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
1821 		errstr = "SCHILY.acl.default";
1822 		break;
1823 	case ARCHIVE_ENTRY_ACL_TYPE_NFS4:
1824 		errstr = "SCHILY.acl.ace";
1825 		break;
1826 	default:
1827 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1828 		    "Unknown ACL type: %d", type);
1829 		return(ARCHIVE_FATAL);
1830 	}
1831 
1832 	if (tar->sconv_acl == NULL) {
1833 		tar->sconv_acl =
1834 		    archive_string_conversion_from_charset(
1835 			&(a->archive), "UTF-8", 1);
1836 		if (tar->sconv_acl == NULL)
1837 			return (ARCHIVE_FATAL);
1838 	}
1839 
1840 	r = archive_acl_from_text_l(archive_entry_acl(entry), value, type,
1841 	    tar->sconv_acl);
1842 	if (r != ARCHIVE_OK) {
1843 		if (r == ARCHIVE_FATAL) {
1844 			archive_set_error(&a->archive, ENOMEM,
1845 			    "%s %s", "Can't allocate memory for ",
1846 			    errstr);
1847 			return (r);
1848 		}
1849 		archive_set_error(&a->archive,
1850 		    ARCHIVE_ERRNO_MISC, "%s %s", "Parse error: ", errstr);
1851 	}
1852 	return (r);
1853 }
1854 
1855 /*
1856  * Parse a single key=value attribute.  key/value pointers are
1857  * assumed to point into reasonably long-lived storage.
1858  *
1859  * Note that POSIX reserves all-lowercase keywords.  Vendor-specific
1860  * extensions should always have keywords of the form "VENDOR.attribute"
1861  * In particular, it's quite feasible to support many different
1862  * vendor extensions here.  I'm using "LIBARCHIVE" for extensions
1863  * unique to this library.
1864  *
1865  * Investigate other vendor-specific extensions and see if
1866  * any of them look useful.
1867  */
1868 static int
1869 pax_attribute(struct archive_read *a, struct tar *tar,
1870     struct archive_entry *entry, const char *key, const char *value, size_t value_length)
1871 {
1872 	int64_t s;
1873 	long n;
1874 	int err = ARCHIVE_OK, r;
1875 
1876 	if (value == NULL)
1877 		value = "";	/* Disable compiler warning; do not pass
1878 				 * NULL pointer to strlen().  */
1879 	switch (key[0]) {
1880 	case 'G':
1881 		/* Reject GNU.sparse.* headers on non-regular files. */
1882 		if (strncmp(key, "GNU.sparse", 10) == 0 &&
1883 		    !tar->sparse_allowed) {
1884 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1885 			    "Non-regular file cannot be sparse");
1886 			return (ARCHIVE_FATAL);
1887 		}
1888 
1889 		/* GNU "0.0" sparse pax format. */
1890 		if (strcmp(key, "GNU.sparse.numblocks") == 0) {
1891 			tar->sparse_offset = -1;
1892 			tar->sparse_numbytes = -1;
1893 			tar->sparse_gnu_major = 0;
1894 			tar->sparse_gnu_minor = 0;
1895 		}
1896 		if (strcmp(key, "GNU.sparse.offset") == 0) {
1897 			tar->sparse_offset = tar_atol10(value, strlen(value));
1898 			if (tar->sparse_numbytes != -1) {
1899 				if (gnu_add_sparse_entry(a, tar,
1900 				    tar->sparse_offset, tar->sparse_numbytes)
1901 				    != ARCHIVE_OK)
1902 					return (ARCHIVE_FATAL);
1903 				tar->sparse_offset = -1;
1904 				tar->sparse_numbytes = -1;
1905 			}
1906 		}
1907 		if (strcmp(key, "GNU.sparse.numbytes") == 0) {
1908 			tar->sparse_numbytes = tar_atol10(value, strlen(value));
1909 			if (tar->sparse_numbytes != -1) {
1910 				if (gnu_add_sparse_entry(a, tar,
1911 				    tar->sparse_offset, tar->sparse_numbytes)
1912 				    != ARCHIVE_OK)
1913 					return (ARCHIVE_FATAL);
1914 				tar->sparse_offset = -1;
1915 				tar->sparse_numbytes = -1;
1916 			}
1917 		}
1918 		if (strcmp(key, "GNU.sparse.size") == 0) {
1919 			tar->realsize = tar_atol10(value, strlen(value));
1920 			archive_entry_set_size(entry, tar->realsize);
1921 			tar->realsize_override = 1;
1922 		}
1923 
1924 		/* GNU "0.1" sparse pax format. */
1925 		if (strcmp(key, "GNU.sparse.map") == 0) {
1926 			tar->sparse_gnu_major = 0;
1927 			tar->sparse_gnu_minor = 1;
1928 			if (gnu_sparse_01_parse(a, tar, value) != ARCHIVE_OK)
1929 				return (ARCHIVE_WARN);
1930 		}
1931 
1932 		/* GNU "1.0" sparse pax format */
1933 		if (strcmp(key, "GNU.sparse.major") == 0) {
1934 			tar->sparse_gnu_major = (int)tar_atol10(value, strlen(value));
1935 			tar->sparse_gnu_pending = 1;
1936 		}
1937 		if (strcmp(key, "GNU.sparse.minor") == 0) {
1938 			tar->sparse_gnu_minor = (int)tar_atol10(value, strlen(value));
1939 			tar->sparse_gnu_pending = 1;
1940 		}
1941 		if (strcmp(key, "GNU.sparse.name") == 0) {
1942 			/*
1943 			 * The real filename; when storing sparse
1944 			 * files, GNU tar puts a synthesized name into
1945 			 * the regular 'path' attribute in an attempt
1946 			 * to limit confusion. ;-)
1947 			 */
1948 			archive_strcpy(&(tar->entry_pathname_override), value);
1949 		}
1950 		if (strcmp(key, "GNU.sparse.realsize") == 0) {
1951 			tar->realsize = tar_atol10(value, strlen(value));
1952 			archive_entry_set_size(entry, tar->realsize);
1953 			tar->realsize_override = 1;
1954 		}
1955 		break;
1956 	case 'L':
1957 		/* Our extensions */
1958 /* TODO: Handle arbitrary extended attributes... */
1959 /*
1960 		if (strcmp(key, "LIBARCHIVE.xxxxxxx") == 0)
1961 			archive_entry_set_xxxxxx(entry, value);
1962 */
1963 		if (strcmp(key, "LIBARCHIVE.creationtime") == 0) {
1964 			pax_time(value, &s, &n);
1965 			archive_entry_set_birthtime(entry, s, n);
1966 		}
1967 		if (strcmp(key, "LIBARCHIVE.symlinktype") == 0) {
1968 			if (strcmp(value, "file") == 0) {
1969 				archive_entry_set_symlink_type(entry,
1970 				    AE_SYMLINK_TYPE_FILE);
1971 			} else if (strcmp(value, "dir") == 0) {
1972 				archive_entry_set_symlink_type(entry,
1973 				    AE_SYMLINK_TYPE_DIRECTORY);
1974 			}
1975 		}
1976 		if (memcmp(key, "LIBARCHIVE.xattr.", 17) == 0)
1977 			pax_attribute_xattr(entry, key, value);
1978 		break;
1979 	case 'R':
1980 		/* GNU tar uses RHT.security header to store SELinux xattrs
1981 		 * SCHILY.xattr.security.selinux == RHT.security.selinux */
1982 		if (strcmp(key, "RHT.security.selinux") == 0) {
1983 			pax_attribute_rht_security_selinux(entry, value,
1984 			    value_length);
1985 			}
1986 		break;
1987 	case 'S':
1988 		/* We support some keys used by the "star" archiver */
1989 		if (strcmp(key, "SCHILY.acl.access") == 0) {
1990 			r = pax_attribute_acl(a, tar, entry, value,
1991 			    ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1992 			if (r == ARCHIVE_FATAL)
1993 				return (r);
1994 		} else if (strcmp(key, "SCHILY.acl.default") == 0) {
1995 			r = pax_attribute_acl(a, tar, entry, value,
1996 			    ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1997 			if (r == ARCHIVE_FATAL)
1998 				return (r);
1999 		} else if (strcmp(key, "SCHILY.acl.ace") == 0) {
2000 			r = pax_attribute_acl(a, tar, entry, value,
2001 			    ARCHIVE_ENTRY_ACL_TYPE_NFS4);
2002 			if (r == ARCHIVE_FATAL)
2003 				return (r);
2004 		} else if (strcmp(key, "SCHILY.devmajor") == 0) {
2005 			archive_entry_set_rdevmajor(entry,
2006 			    (dev_t)tar_atol10(value, strlen(value)));
2007 		} else if (strcmp(key, "SCHILY.devminor") == 0) {
2008 			archive_entry_set_rdevminor(entry,
2009 			    (dev_t)tar_atol10(value, strlen(value)));
2010 		} else if (strcmp(key, "SCHILY.fflags") == 0) {
2011 			archive_entry_copy_fflags_text(entry, value);
2012 		} else if (strcmp(key, "SCHILY.dev") == 0) {
2013 			archive_entry_set_dev(entry,
2014 			    (dev_t)tar_atol10(value, strlen(value)));
2015 		} else if (strcmp(key, "SCHILY.ino") == 0) {
2016 			archive_entry_set_ino(entry,
2017 			    tar_atol10(value, strlen(value)));
2018 		} else if (strcmp(key, "SCHILY.nlink") == 0) {
2019 			archive_entry_set_nlink(entry, (unsigned)
2020 			    tar_atol10(value, strlen(value)));
2021 		} else if (strcmp(key, "SCHILY.realsize") == 0) {
2022 			tar->realsize = tar_atol10(value, strlen(value));
2023 			tar->realsize_override = 1;
2024 			archive_entry_set_size(entry, tar->realsize);
2025 		} else if (strncmp(key, "SCHILY.xattr.", 13) == 0) {
2026 			pax_attribute_schily_xattr(entry, key, value,
2027 			    value_length);
2028 		} else if (strcmp(key, "SUN.holesdata") == 0) {
2029 			/* A Solaris extension for sparse. */
2030 			r = solaris_sparse_parse(a, tar, entry, value);
2031 			if (r < err) {
2032 				if (r == ARCHIVE_FATAL)
2033 					return (r);
2034 				err = r;
2035 				archive_set_error(&a->archive,
2036 				    ARCHIVE_ERRNO_MISC,
2037 				    "Parse error: SUN.holesdata");
2038 			}
2039 		}
2040 		break;
2041 	case 'a':
2042 		if (strcmp(key, "atime") == 0) {
2043 			pax_time(value, &s, &n);
2044 			archive_entry_set_atime(entry, s, n);
2045 		}
2046 		break;
2047 	case 'c':
2048 		if (strcmp(key, "ctime") == 0) {
2049 			pax_time(value, &s, &n);
2050 			archive_entry_set_ctime(entry, s, n);
2051 		} else if (strcmp(key, "charset") == 0) {
2052 			/* TODO: Publish charset information in entry. */
2053 		} else if (strcmp(key, "comment") == 0) {
2054 			/* TODO: Publish comment in entry. */
2055 		}
2056 		break;
2057 	case 'g':
2058 		if (strcmp(key, "gid") == 0) {
2059 			archive_entry_set_gid(entry,
2060 			    tar_atol10(value, strlen(value)));
2061 		} else if (strcmp(key, "gname") == 0) {
2062 			archive_strcpy(&(tar->entry_gname), value);
2063 		}
2064 		break;
2065 	case 'h':
2066 		if (strcmp(key, "hdrcharset") == 0) {
2067 			if (strcmp(value, "BINARY") == 0)
2068 				/* Binary  mode. */
2069 				tar->pax_hdrcharset_binary = 1;
2070 			else if (strcmp(value, "ISO-IR 10646 2000 UTF-8") == 0)
2071 				tar->pax_hdrcharset_binary = 0;
2072 		}
2073 		break;
2074 	case 'l':
2075 		/* pax interchange doesn't distinguish hardlink vs. symlink. */
2076 		if (strcmp(key, "linkpath") == 0) {
2077 			archive_strcpy(&(tar->entry_linkpath), value);
2078 		}
2079 		break;
2080 	case 'm':
2081 		if (strcmp(key, "mtime") == 0) {
2082 			pax_time(value, &s, &n);
2083 			archive_entry_set_mtime(entry, s, n);
2084 		}
2085 		break;
2086 	case 'p':
2087 		if (strcmp(key, "path") == 0) {
2088 			archive_strcpy(&(tar->entry_pathname), value);
2089 		}
2090 		break;
2091 	case 'r':
2092 		/* POSIX has reserved 'realtime.*' */
2093 		break;
2094 	case 's':
2095 		/* POSIX has reserved 'security.*' */
2096 		/* Someday: if (strcmp(key, "security.acl") == 0) { ... } */
2097 		if (strcmp(key, "size") == 0) {
2098 			/* "size" is the size of the data in the entry. */
2099 			tar->entry_bytes_remaining
2100 			    = tar_atol10(value, strlen(value));
2101 			/*
2102 			 * The "size" pax header keyword always overrides the
2103 			 * "size" field in the tar header.
2104 			 * GNU.sparse.realsize, GNU.sparse.size and
2105 			 * SCHILY.realsize override this value.
2106 			 */
2107 			if (!tar->realsize_override) {
2108 				archive_entry_set_size(entry,
2109 				    tar->entry_bytes_remaining);
2110 				tar->realsize
2111 				    = tar->entry_bytes_remaining;
2112 			}
2113 		}
2114 		break;
2115 	case 'u':
2116 		if (strcmp(key, "uid") == 0) {
2117 			archive_entry_set_uid(entry,
2118 			    tar_atol10(value, strlen(value)));
2119 		} else if (strcmp(key, "uname") == 0) {
2120 			archive_strcpy(&(tar->entry_uname), value);
2121 		}
2122 		break;
2123 	}
2124 	return (err);
2125 }
2126 
2127 
2128 
2129 /*
2130  * parse a decimal time value, which may include a fractional portion
2131  */
2132 static void
2133 pax_time(const char *p, int64_t *ps, long *pn)
2134 {
2135 	char digit;
2136 	int64_t	s;
2137 	unsigned long l;
2138 	int sign;
2139 	int64_t limit, last_digit_limit;
2140 
2141 	limit = INT64_MAX / 10;
2142 	last_digit_limit = INT64_MAX % 10;
2143 
2144 	s = 0;
2145 	sign = 1;
2146 	if (*p == '-') {
2147 		sign = -1;
2148 		p++;
2149 	}
2150 	while (*p >= '0' && *p <= '9') {
2151 		digit = *p - '0';
2152 		if (s > limit ||
2153 		    (s == limit && digit > last_digit_limit)) {
2154 			s = INT64_MAX;
2155 			break;
2156 		}
2157 		s = (s * 10) + digit;
2158 		++p;
2159 	}
2160 
2161 	*ps = s * sign;
2162 
2163 	/* Calculate nanoseconds. */
2164 	*pn = 0;
2165 
2166 	if (*p != '.')
2167 		return;
2168 
2169 	l = 100000000UL;
2170 	do {
2171 		++p;
2172 		if (*p >= '0' && *p <= '9')
2173 			*pn += (*p - '0') * l;
2174 		else
2175 			break;
2176 	} while (l /= 10);
2177 }
2178 
2179 /*
2180  * Parse GNU tar header
2181  */
2182 static int
2183 header_gnutar(struct archive_read *a, struct tar *tar,
2184     struct archive_entry *entry, const void *h, size_t *unconsumed)
2185 {
2186 	const struct archive_entry_header_gnutar *header;
2187 	int64_t t;
2188 	int err = ARCHIVE_OK;
2189 
2190 	/*
2191 	 * GNU header is like POSIX ustar, except 'prefix' is
2192 	 * replaced with some other fields. This also means the
2193 	 * filename is stored as in old-style archives.
2194 	 */
2195 
2196 	/* Grab fields common to all tar variants. */
2197 	err = header_common(a, tar, entry, h);
2198 	if (err == ARCHIVE_FATAL)
2199 		return (err);
2200 
2201 	/* Copy filename over (to ensure null termination). */
2202 	header = (const struct archive_entry_header_gnutar *)h;
2203 	if (archive_entry_copy_pathname_l(entry,
2204 	    header->name, sizeof(header->name), tar->sconv) != 0) {
2205 		err = set_conversion_failed_error(a, tar->sconv, "Pathname");
2206 		if (err == ARCHIVE_FATAL)
2207 			return (err);
2208 	}
2209 
2210 	/* Fields common to ustar and GNU */
2211 	/* XXX Can the following be factored out since it's common
2212 	 * to ustar and gnu tar?  Is it okay to move it down into
2213 	 * header_common, perhaps?  */
2214 	if (archive_entry_copy_uname_l(entry,
2215 	    header->uname, sizeof(header->uname), tar->sconv) != 0) {
2216 		err = set_conversion_failed_error(a, tar->sconv, "Uname");
2217 		if (err == ARCHIVE_FATAL)
2218 			return (err);
2219 	}
2220 
2221 	if (archive_entry_copy_gname_l(entry,
2222 	    header->gname, sizeof(header->gname), tar->sconv) != 0) {
2223 		err = set_conversion_failed_error(a, tar->sconv, "Gname");
2224 		if (err == ARCHIVE_FATAL)
2225 			return (err);
2226 	}
2227 
2228 	/* Parse out device numbers only for char and block specials */
2229 	if (header->typeflag[0] == '3' || header->typeflag[0] == '4') {
2230 		archive_entry_set_rdevmajor(entry, (dev_t)
2231 		    tar_atol(header->rdevmajor, sizeof(header->rdevmajor)));
2232 		archive_entry_set_rdevminor(entry, (dev_t)
2233 		    tar_atol(header->rdevminor, sizeof(header->rdevminor)));
2234 	} else
2235 		archive_entry_set_rdev(entry, 0);
2236 
2237 	tar->entry_padding = 0x1ff & (-tar->entry_bytes_remaining);
2238 
2239 	/* Grab GNU-specific fields. */
2240 	t = tar_atol(header->atime, sizeof(header->atime));
2241 	if (t > 0)
2242 		archive_entry_set_atime(entry, t, 0);
2243 	t = tar_atol(header->ctime, sizeof(header->ctime));
2244 	if (t > 0)
2245 		archive_entry_set_ctime(entry, t, 0);
2246 
2247 	if (header->realsize[0] != 0) {
2248 		tar->realsize
2249 		    = tar_atol(header->realsize, sizeof(header->realsize));
2250 		archive_entry_set_size(entry, tar->realsize);
2251 		tar->realsize_override = 1;
2252 	}
2253 
2254 	if (header->sparse[0].offset[0] != 0) {
2255 		if (gnu_sparse_old_read(a, tar, header, unconsumed)
2256 		    != ARCHIVE_OK)
2257 			return (ARCHIVE_FATAL);
2258 	} else {
2259 		if (header->isextended[0] != 0) {
2260 			/* XXX WTF? XXX */
2261 		}
2262 	}
2263 
2264 	return (err);
2265 }
2266 
2267 static int
2268 gnu_add_sparse_entry(struct archive_read *a, struct tar *tar,
2269     int64_t offset, int64_t remaining)
2270 {
2271 	struct sparse_block *p;
2272 
2273 	p = (struct sparse_block *)calloc(1, sizeof(*p));
2274 	if (p == NULL) {
2275 		archive_set_error(&a->archive, ENOMEM, "Out of memory");
2276 		return (ARCHIVE_FATAL);
2277 	}
2278 	if (tar->sparse_last != NULL)
2279 		tar->sparse_last->next = p;
2280 	else
2281 		tar->sparse_list = p;
2282 	tar->sparse_last = p;
2283 	if (remaining < 0 || offset < 0 || offset > INT64_MAX - remaining) {
2284 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Malformed sparse map data");
2285 		return (ARCHIVE_FATAL);
2286 	}
2287 	p->offset = offset;
2288 	p->remaining = remaining;
2289 	return (ARCHIVE_OK);
2290 }
2291 
2292 static void
2293 gnu_clear_sparse_list(struct tar *tar)
2294 {
2295 	struct sparse_block *p;
2296 
2297 	while (tar->sparse_list != NULL) {
2298 		p = tar->sparse_list;
2299 		tar->sparse_list = p->next;
2300 		free(p);
2301 	}
2302 	tar->sparse_last = NULL;
2303 }
2304 
2305 /*
2306  * GNU tar old-format sparse data.
2307  *
2308  * GNU old-format sparse data is stored in a fixed-field
2309  * format.  Offset/size values are 11-byte octal fields (same
2310  * format as 'size' field in ustart header).  These are
2311  * stored in the header, allocating subsequent header blocks
2312  * as needed.  Extending the header in this way is a pretty
2313  * severe POSIX violation; this design has earned GNU tar a
2314  * lot of criticism.
2315  */
2316 
2317 static int
2318 gnu_sparse_old_read(struct archive_read *a, struct tar *tar,
2319     const struct archive_entry_header_gnutar *header, size_t *unconsumed)
2320 {
2321 	ssize_t bytes_read;
2322 	const void *data;
2323 	struct extended {
2324 		struct gnu_sparse sparse[21];
2325 		char	isextended[1];
2326 		char	padding[7];
2327 	};
2328 	const struct extended *ext;
2329 
2330 	if (gnu_sparse_old_parse(a, tar, header->sparse, 4) != ARCHIVE_OK)
2331 		return (ARCHIVE_FATAL);
2332 	if (header->isextended[0] == 0)
2333 		return (ARCHIVE_OK);
2334 
2335 	do {
2336 		tar_flush_unconsumed(a, unconsumed);
2337 		data = __archive_read_ahead(a, 512, &bytes_read);
2338 		if (bytes_read < 0)
2339 			return (ARCHIVE_FATAL);
2340 		if (bytes_read < 512) {
2341 			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2342 			    "Truncated tar archive "
2343 			    "detected while reading sparse file data");
2344 			return (ARCHIVE_FATAL);
2345 		}
2346 		*unconsumed = 512;
2347 		ext = (const struct extended *)data;
2348 		if (gnu_sparse_old_parse(a, tar, ext->sparse, 21) != ARCHIVE_OK)
2349 			return (ARCHIVE_FATAL);
2350 	} while (ext->isextended[0] != 0);
2351 	if (tar->sparse_list != NULL)
2352 		tar->entry_offset = tar->sparse_list->offset;
2353 	return (ARCHIVE_OK);
2354 }
2355 
2356 static int
2357 gnu_sparse_old_parse(struct archive_read *a, struct tar *tar,
2358     const struct gnu_sparse *sparse, int length)
2359 {
2360 	while (length > 0 && sparse->offset[0] != 0) {
2361 		if (gnu_add_sparse_entry(a, tar,
2362 		    tar_atol(sparse->offset, sizeof(sparse->offset)),
2363 		    tar_atol(sparse->numbytes, sizeof(sparse->numbytes)))
2364 		    != ARCHIVE_OK)
2365 			return (ARCHIVE_FATAL);
2366 		sparse++;
2367 		length--;
2368 	}
2369 	return (ARCHIVE_OK);
2370 }
2371 
2372 /*
2373  * GNU tar sparse format 0.0
2374  *
2375  * Beginning with GNU tar 1.15, sparse files are stored using
2376  * information in the pax extended header.  The GNU tar maintainers
2377  * have gone through a number of variations in the process of working
2378  * out this scheme; fortunately, they're all numbered.
2379  *
2380  * Sparse format 0.0 uses attribute GNU.sparse.numblocks to store the
2381  * number of blocks, and GNU.sparse.offset/GNU.sparse.numbytes to
2382  * store offset/size for each block.  The repeated instances of these
2383  * latter fields violate the pax specification (which frowns on
2384  * duplicate keys), so this format was quickly replaced.
2385  */
2386 
2387 /*
2388  * GNU tar sparse format 0.1
2389  *
2390  * This version replaced the offset/numbytes attributes with
2391  * a single "map" attribute that stored a list of integers.  This
2392  * format had two problems: First, the "map" attribute could be very
2393  * long, which caused problems for some implementations.  More
2394  * importantly, the sparse data was lost when extracted by archivers
2395  * that didn't recognize this extension.
2396  */
2397 
2398 static int
2399 gnu_sparse_01_parse(struct archive_read *a, struct tar *tar, const char *p)
2400 {
2401 	const char *e;
2402 	int64_t offset = -1, size = -1;
2403 
2404 	for (;;) {
2405 		e = p;
2406 		while (*e != '\0' && *e != ',') {
2407 			if (*e < '0' || *e > '9')
2408 				return (ARCHIVE_WARN);
2409 			e++;
2410 		}
2411 		if (offset < 0) {
2412 			offset = tar_atol10(p, e - p);
2413 			if (offset < 0)
2414 				return (ARCHIVE_WARN);
2415 		} else {
2416 			size = tar_atol10(p, e - p);
2417 			if (size < 0)
2418 				return (ARCHIVE_WARN);
2419 			if (gnu_add_sparse_entry(a, tar, offset, size)
2420 			    != ARCHIVE_OK)
2421 				return (ARCHIVE_FATAL);
2422 			offset = -1;
2423 		}
2424 		if (*e == '\0')
2425 			return (ARCHIVE_OK);
2426 		p = e + 1;
2427 	}
2428 }
2429 
2430 /*
2431  * GNU tar sparse format 1.0
2432  *
2433  * The idea: The offset/size data is stored as a series of base-10
2434  * ASCII numbers prepended to the file data, so that dearchivers that
2435  * don't support this format will extract the block map along with the
2436  * data and a separate post-process can restore the sparseness.
2437  *
2438  * Unfortunately, GNU tar 1.16 had a bug that added unnecessary
2439  * padding to the body of the file when using this format.  GNU tar
2440  * 1.17 corrected this bug without bumping the version number, so
2441  * it's not possible to support both variants.  This code supports
2442  * the later variant at the expense of not supporting the former.
2443  *
2444  * This variant also replaced GNU.sparse.size with GNU.sparse.realsize
2445  * and introduced the GNU.sparse.major/GNU.sparse.minor attributes.
2446  */
2447 
2448 /*
2449  * Read the next line from the input, and parse it as a decimal
2450  * integer followed by '\n'.  Returns positive integer value or
2451  * negative on error.
2452  */
2453 static int64_t
2454 gnu_sparse_10_atol(struct archive_read *a, struct tar *tar,
2455     int64_t *remaining, size_t *unconsumed)
2456 {
2457 	int64_t l, limit, last_digit_limit;
2458 	const char *p;
2459 	ssize_t bytes_read;
2460 	int base, digit;
2461 
2462 	base = 10;
2463 	limit = INT64_MAX / base;
2464 	last_digit_limit = INT64_MAX % base;
2465 
2466 	/*
2467 	 * Skip any lines starting with '#'; GNU tar specs
2468 	 * don't require this, but they should.
2469 	 */
2470 	do {
2471 		bytes_read = readline(a, tar, &p,
2472 			(ssize_t)tar_min(*remaining, 100), unconsumed);
2473 		if (bytes_read <= 0)
2474 			return (ARCHIVE_FATAL);
2475 		*remaining -= bytes_read;
2476 	} while (p[0] == '#');
2477 
2478 	l = 0;
2479 	while (bytes_read > 0) {
2480 		if (*p == '\n')
2481 			return (l);
2482 		if (*p < '0' || *p >= '0' + base)
2483 			return (ARCHIVE_WARN);
2484 		digit = *p - '0';
2485 		if (l > limit || (l == limit && digit > last_digit_limit))
2486 			l = INT64_MAX; /* Truncate on overflow. */
2487 		else
2488 			l = (l * base) + digit;
2489 		p++;
2490 		bytes_read--;
2491 	}
2492 	/* TODO: Error message. */
2493 	return (ARCHIVE_WARN);
2494 }
2495 
2496 /*
2497  * Returns length (in bytes) of the sparse data description
2498  * that was read.
2499  */
2500 static ssize_t
2501 gnu_sparse_10_read(struct archive_read *a, struct tar *tar, size_t *unconsumed)
2502 {
2503 	ssize_t bytes_read;
2504 	int entries;
2505 	int64_t offset, size, to_skip, remaining;
2506 
2507 	/* Clear out the existing sparse list. */
2508 	gnu_clear_sparse_list(tar);
2509 
2510 	remaining = tar->entry_bytes_remaining;
2511 
2512 	/* Parse entries. */
2513 	entries = (int)gnu_sparse_10_atol(a, tar, &remaining, unconsumed);
2514 	if (entries < 0)
2515 		return (ARCHIVE_FATAL);
2516 	/* Parse the individual entries. */
2517 	while (entries-- > 0) {
2518 		/* Parse offset/size */
2519 		offset = gnu_sparse_10_atol(a, tar, &remaining, unconsumed);
2520 		if (offset < 0)
2521 			return (ARCHIVE_FATAL);
2522 		size = gnu_sparse_10_atol(a, tar, &remaining, unconsumed);
2523 		if (size < 0)
2524 			return (ARCHIVE_FATAL);
2525 		/* Add a new sparse entry. */
2526 		if (gnu_add_sparse_entry(a, tar, offset, size) != ARCHIVE_OK)
2527 			return (ARCHIVE_FATAL);
2528 	}
2529 	/* Skip rest of block... */
2530 	tar_flush_unconsumed(a, unconsumed);
2531 	bytes_read = (ssize_t)(tar->entry_bytes_remaining - remaining);
2532 	to_skip = 0x1ff & -bytes_read;
2533 	/* Fail if tar->entry_bytes_remaing would get negative */
2534 	if (to_skip > remaining)
2535 		return (ARCHIVE_FATAL);
2536 	if (to_skip != __archive_read_consume(a, to_skip))
2537 		return (ARCHIVE_FATAL);
2538 	return ((ssize_t)(bytes_read + to_skip));
2539 }
2540 
2541 /*
2542  * Solaris pax extension for a sparse file. This is recorded with the
2543  * data and hole pairs. The way recording sparse information by Solaris'
2544  * pax simply indicates where data and sparse are, so the stored contents
2545  * consist of both data and hole.
2546  */
2547 static int
2548 solaris_sparse_parse(struct archive_read *a, struct tar *tar,
2549     struct archive_entry *entry, const char *p)
2550 {
2551 	const char *e;
2552 	int64_t start, end;
2553 	int hole = 1;
2554 
2555 	(void)entry; /* UNUSED */
2556 
2557 	end = 0;
2558 	if (*p == ' ')
2559 		p++;
2560 	else
2561 		return (ARCHIVE_WARN);
2562 	for (;;) {
2563 		e = p;
2564 		while (*e != '\0' && *e != ' ') {
2565 			if (*e < '0' || *e > '9')
2566 				return (ARCHIVE_WARN);
2567 			e++;
2568 		}
2569 		start = end;
2570 		end = tar_atol10(p, e - p);
2571 		if (end < 0)
2572 			return (ARCHIVE_WARN);
2573 		if (start < end) {
2574 			if (gnu_add_sparse_entry(a, tar, start,
2575 			    end - start) != ARCHIVE_OK)
2576 				return (ARCHIVE_FATAL);
2577 			tar->sparse_last->hole = hole;
2578 		}
2579 		if (*e == '\0')
2580 			return (ARCHIVE_OK);
2581 		p = e + 1;
2582 		hole = hole == 0;
2583 	}
2584 }
2585 
2586 /*-
2587  * Convert text->integer.
2588  *
2589  * Traditional tar formats (including POSIX) specify base-8 for
2590  * all of the standard numeric fields.  This is a significant limitation
2591  * in practice:
2592  *   = file size is limited to 8GB
2593  *   = rdevmajor and rdevminor are limited to 21 bits
2594  *   = uid/gid are limited to 21 bits
2595  *
2596  * There are two workarounds for this:
2597  *   = pax extended headers, which use variable-length string fields
2598  *   = GNU tar and STAR both allow either base-8 or base-256 in
2599  *      most fields.  The high bit is set to indicate base-256.
2600  *
2601  * On read, this implementation supports both extensions.
2602  */
2603 static int64_t
2604 tar_atol(const char *p, size_t char_cnt)
2605 {
2606 	/*
2607 	 * Technically, GNU tar considers a field to be in base-256
2608 	 * only if the first byte is 0xff or 0x80.
2609 	 */
2610 	if (*p & 0x80)
2611 		return (tar_atol256(p, char_cnt));
2612 	return (tar_atol8(p, char_cnt));
2613 }
2614 
2615 /*
2616  * Note that this implementation does not (and should not!) obey
2617  * locale settings; you cannot simply substitute strtol here, since
2618  * it does obey locale.
2619  */
2620 static int64_t
2621 tar_atol_base_n(const char *p, size_t char_cnt, int base)
2622 {
2623 	int64_t	l, maxval, limit, last_digit_limit;
2624 	int digit, sign;
2625 
2626 	maxval = INT64_MAX;
2627 	limit = INT64_MAX / base;
2628 	last_digit_limit = INT64_MAX % base;
2629 
2630 	/* the pointer will not be dereferenced if char_cnt is zero
2631 	 * due to the way the && operator is evaluated.
2632 	 */
2633 	while (char_cnt != 0 && (*p == ' ' || *p == '\t')) {
2634 		p++;
2635 		char_cnt--;
2636 	}
2637 
2638 	sign = 1;
2639 	if (char_cnt != 0 && *p == '-') {
2640 		sign = -1;
2641 		p++;
2642 		char_cnt--;
2643 
2644 		maxval = INT64_MIN;
2645 		limit = -(INT64_MIN / base);
2646 		last_digit_limit = INT64_MIN % base;
2647 	}
2648 
2649 	l = 0;
2650 	if (char_cnt != 0) {
2651 		digit = *p - '0';
2652 		while (digit >= 0 && digit < base  && char_cnt != 0) {
2653 			if (l>limit || (l == limit && digit > last_digit_limit)) {
2654 				return maxval; /* Truncate on overflow. */
2655 			}
2656 			l = (l * base) + digit;
2657 			digit = *++p - '0';
2658 			char_cnt--;
2659 		}
2660 	}
2661 	return (sign < 0) ? -l : l;
2662 }
2663 
2664 static int64_t
2665 tar_atol8(const char *p, size_t char_cnt)
2666 {
2667 	return tar_atol_base_n(p, char_cnt, 8);
2668 }
2669 
2670 static int64_t
2671 tar_atol10(const char *p, size_t char_cnt)
2672 {
2673 	return tar_atol_base_n(p, char_cnt, 10);
2674 }
2675 
2676 /*
2677  * Parse a base-256 integer.  This is just a variable-length
2678  * twos-complement signed binary value in big-endian order, except
2679  * that the high-order bit is ignored.  The values here can be up to
2680  * 12 bytes, so we need to be careful about overflowing 64-bit
2681  * (8-byte) integers.
2682  *
2683  * This code unashamedly assumes that the local machine uses 8-bit
2684  * bytes and twos-complement arithmetic.
2685  */
2686 static int64_t
2687 tar_atol256(const char *_p, size_t char_cnt)
2688 {
2689 	uint64_t l;
2690 	const unsigned char *p = (const unsigned char *)_p;
2691 	unsigned char c, neg;
2692 
2693 	/* Extend 7-bit 2s-comp to 8-bit 2s-comp, decide sign. */
2694 	c = *p;
2695 	if (c & 0x40) {
2696 		neg = 0xff;
2697 		c |= 0x80;
2698 		l = ~ARCHIVE_LITERAL_ULL(0);
2699 	} else {
2700 		neg = 0;
2701 		c &= 0x7f;
2702 		l = 0;
2703 	}
2704 
2705 	/* If more than 8 bytes, check that we can ignore
2706 	 * high-order bits without overflow. */
2707 	while (char_cnt > sizeof(int64_t)) {
2708 		--char_cnt;
2709 		if (c != neg)
2710 			return neg ? INT64_MIN : INT64_MAX;
2711 		c = *++p;
2712 	}
2713 
2714 	/* c is first byte that fits; if sign mismatch, return overflow */
2715 	if ((c ^ neg) & 0x80) {
2716 		return neg ? INT64_MIN : INT64_MAX;
2717 	}
2718 
2719 	/* Accumulate remaining bytes. */
2720 	while (--char_cnt > 0) {
2721 		l = (l << 8) | c;
2722 		c = *++p;
2723 	}
2724 	l = (l << 8) | c;
2725 	/* Return signed twos-complement value. */
2726 	return (int64_t)(l);
2727 }
2728 
2729 /*
2730  * Returns length of line (including trailing newline)
2731  * or negative on error.  'start' argument is updated to
2732  * point to first character of line.  This avoids copying
2733  * when possible.
2734  */
2735 static ssize_t
2736 readline(struct archive_read *a, struct tar *tar, const char **start,
2737     ssize_t limit, size_t *unconsumed)
2738 {
2739 	ssize_t bytes_read;
2740 	ssize_t total_size = 0;
2741 	const void *t;
2742 	const char *s;
2743 	void *p;
2744 
2745 	tar_flush_unconsumed(a, unconsumed);
2746 
2747 	t = __archive_read_ahead(a, 1, &bytes_read);
2748 	if (bytes_read <= 0)
2749 		return (ARCHIVE_FATAL);
2750 	s = t;  /* Start of line? */
2751 	p = memchr(t, '\n', bytes_read);
2752 	/* If we found '\n' in the read buffer, return pointer to that. */
2753 	if (p != NULL) {
2754 		bytes_read = 1 + ((const char *)p) - s;
2755 		if (bytes_read > limit) {
2756 			archive_set_error(&a->archive,
2757 			    ARCHIVE_ERRNO_FILE_FORMAT,
2758 			    "Line too long");
2759 			return (ARCHIVE_FATAL);
2760 		}
2761 		*unconsumed = bytes_read;
2762 		*start = s;
2763 		return (bytes_read);
2764 	}
2765 	*unconsumed = bytes_read;
2766 	/* Otherwise, we need to accumulate in a line buffer. */
2767 	for (;;) {
2768 		if (total_size + bytes_read > limit) {
2769 			archive_set_error(&a->archive,
2770 			    ARCHIVE_ERRNO_FILE_FORMAT,
2771 			    "Line too long");
2772 			return (ARCHIVE_FATAL);
2773 		}
2774 		if (archive_string_ensure(&tar->line, total_size + bytes_read) == NULL) {
2775 			archive_set_error(&a->archive, ENOMEM,
2776 			    "Can't allocate working buffer");
2777 			return (ARCHIVE_FATAL);
2778 		}
2779 		memcpy(tar->line.s + total_size, t, bytes_read);
2780 		tar_flush_unconsumed(a, unconsumed);
2781 		total_size += bytes_read;
2782 		/* If we found '\n', clean up and return. */
2783 		if (p != NULL) {
2784 			*start = tar->line.s;
2785 			return (total_size);
2786 		}
2787 		/* Read some more. */
2788 		t = __archive_read_ahead(a, 1, &bytes_read);
2789 		if (bytes_read <= 0)
2790 			return (ARCHIVE_FATAL);
2791 		s = t;  /* Start of line? */
2792 		p = memchr(t, '\n', bytes_read);
2793 		/* If we found '\n', trim the read. */
2794 		if (p != NULL) {
2795 			bytes_read = 1 + ((const char *)p) - s;
2796 		}
2797 		*unconsumed = bytes_read;
2798 	}
2799 }
2800 
2801 /*
2802  * base64_decode - Base64 decode
2803  *
2804  * This accepts most variations of base-64 encoding, including:
2805  *    * with or without line breaks
2806  *    * with or without the final group padded with '=' or '_' characters
2807  * (The most economical Base-64 variant does not pad the last group and
2808  * omits line breaks; RFC1341 used for MIME requires both.)
2809  */
2810 static char *
2811 base64_decode(const char *s, size_t len, size_t *out_len)
2812 {
2813 	static const unsigned char digits[64] = {
2814 		'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
2815 		'O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b',
2816 		'c','d','e','f','g','h','i','j','k','l','m','n','o','p',
2817 		'q','r','s','t','u','v','w','x','y','z','0','1','2','3',
2818 		'4','5','6','7','8','9','+','/' };
2819 	static unsigned char decode_table[128];
2820 	char *out, *d;
2821 	const unsigned char *src = (const unsigned char *)s;
2822 
2823 	/* If the decode table is not yet initialized, prepare it. */
2824 	if (decode_table[digits[1]] != 1) {
2825 		unsigned i;
2826 		memset(decode_table, 0xff, sizeof(decode_table));
2827 		for (i = 0; i < sizeof(digits); i++)
2828 			decode_table[digits[i]] = i;
2829 	}
2830 
2831 	/* Allocate enough space to hold the entire output. */
2832 	/* Note that we may not use all of this... */
2833 	out = (char *)malloc(len - len / 4 + 1);
2834 	if (out == NULL) {
2835 		*out_len = 0;
2836 		return (NULL);
2837 	}
2838 	d = out;
2839 
2840 	while (len > 0) {
2841 		/* Collect the next group of (up to) four characters. */
2842 		int v = 0;
2843 		int group_size = 0;
2844 		while (group_size < 4 && len > 0) {
2845 			/* '=' or '_' padding indicates final group. */
2846 			if (*src == '=' || *src == '_') {
2847 				len = 0;
2848 				break;
2849 			}
2850 			/* Skip illegal characters (including line breaks) */
2851 			if (*src > 127 || *src < 32
2852 			    || decode_table[*src] == 0xff) {
2853 				len--;
2854 				src++;
2855 				continue;
2856 			}
2857 			v <<= 6;
2858 			v |= decode_table[*src++];
2859 			len --;
2860 			group_size++;
2861 		}
2862 		/* Align a short group properly. */
2863 		v <<= 6 * (4 - group_size);
2864 		/* Unpack the group we just collected. */
2865 		switch (group_size) {
2866 		case 4: d[2] = v & 0xff;
2867 			/* FALLTHROUGH */
2868 		case 3: d[1] = (v >> 8) & 0xff;
2869 			/* FALLTHROUGH */
2870 		case 2: d[0] = (v >> 16) & 0xff;
2871 			break;
2872 		case 1: /* this is invalid! */
2873 			break;
2874 		}
2875 		d += group_size * 3 / 4;
2876 	}
2877 
2878 	*out_len = d - out;
2879 	return (out);
2880 }
2881 
2882 static char *
2883 url_decode(const char *in)
2884 {
2885 	char *out, *d;
2886 	const char *s;
2887 
2888 	out = (char *)malloc(strlen(in) + 1);
2889 	if (out == NULL)
2890 		return (NULL);
2891 	for (s = in, d = out; *s != '\0'; ) {
2892 		if (s[0] == '%' && s[1] != '\0' && s[2] != '\0') {
2893 			/* Try to convert % escape */
2894 			int digit1 = tohex(s[1]);
2895 			int digit2 = tohex(s[2]);
2896 			if (digit1 >= 0 && digit2 >= 0) {
2897 				/* Looks good, consume three chars */
2898 				s += 3;
2899 				/* Convert output */
2900 				*d++ = ((digit1 << 4) | digit2);
2901 				continue;
2902 			}
2903 			/* Else fall through and treat '%' as normal char */
2904 		}
2905 		*d++ = *s++;
2906 	}
2907 	*d = '\0';
2908 	return (out);
2909 }
2910 
2911 static int
2912 tohex(int c)
2913 {
2914 	if (c >= '0' && c <= '9')
2915 		return (c - '0');
2916 	else if (c >= 'A' && c <= 'F')
2917 		return (c - 'A' + 10);
2918 	else if (c >= 'a' && c <= 'f')
2919 		return (c - 'a' + 10);
2920 	else
2921 		return (-1);
2922 }
2923