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