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