Home | History | Annotate | Line # | Download | only in libarchive
      1 /*-
      2  * Copyright (c) 2003-2007 Tim Kientzle
      3  * Copyright (c) 2010-2012 Michihiro NAKAJIMA
      4  * Copyright (c) 2016 Martin Matuska
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
     17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     19  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 #include "archive_platform.h"
     29 
     30 #ifdef HAVE_ERRNO_H
     31 #include <errno.h>
     32 #endif
     33 #ifdef HAVE_STDLIB_H
     34 #include <stdlib.h>
     35 #endif
     36 #ifdef HAVE_STRING_H
     37 #include <string.h>
     38 #endif
     39 
     40 #include "archive.h"
     41 #include "archive_entry.h"
     42 #include "archive_entry_locale.h"
     43 #include "archive_private.h"
     44 #include "archive_write_private.h"
     45 #include "archive_write_set_format_private.h"
     46 
     47 struct sparse_block {
     48 	struct sparse_block	*next;
     49 	int		is_hole;
     50 	uint64_t	offset;
     51 	uint64_t	remaining;
     52 };
     53 
     54 struct pax {
     55 	uint64_t	entry_bytes_remaining;
     56 	uint64_t	entry_padding;
     57 	struct archive_string	l_url_encoded_name;
     58 	struct archive_string	pax_header;
     59 	struct archive_string	sparse_map;
     60 	size_t			sparse_map_padding;
     61 	struct sparse_block	*sparse_list;
     62 	struct sparse_block	*sparse_tail;
     63 	struct archive_string_conv *sconv_utf8;
     64 	int			 opt_binary;
     65 
     66 	unsigned flags;
     67 #define WRITE_SCHILY_XATTR       (1 << 0)
     68 #define WRITE_LIBARCHIVE_XATTR   (1 << 1)
     69 };
     70 
     71 static void		 add_pax_attr(struct archive_string *, const char *key,
     72 			     const char *value);
     73 static void		 add_pax_attr_binary(struct archive_string *,
     74 			     const char *key,
     75 			     const char *value, size_t value_len);
     76 static void		 add_pax_attr_int(struct archive_string *,
     77 			     const char *key, int64_t value);
     78 static void		 add_pax_attr_time(struct archive_string *,
     79 			     const char *key, int64_t sec,
     80 			     unsigned long nanos);
     81 static int		 add_pax_acl(struct archive_write *,
     82 			    struct archive_entry *, struct pax *, int);
     83 static ssize_t		 archive_write_pax_data(struct archive_write *,
     84 			     const void *, size_t);
     85 static int		 archive_write_pax_close(struct archive_write *);
     86 static int		 archive_write_pax_free(struct archive_write *);
     87 static int		 archive_write_pax_finish_entry(struct archive_write *);
     88 static int		 archive_write_pax_header(struct archive_write *,
     89 			     struct archive_entry *);
     90 static int		 archive_write_pax_options(struct archive_write *,
     91 			     const char *, const char *);
     92 static char		*base64_encode(const char *src, size_t len);
     93 static char		*build_gnu_sparse_name(char *dest, const char *src);
     94 static char		*build_pax_attribute_name(char *dest, const char *src);
     95 static char		*build_ustar_entry_name(char *dest, const char *src,
     96 			     size_t src_length, const char *insert);
     97 static char		*format_int(char *dest, int64_t);
     98 static int		 has_non_ASCII(const char *);
     99 static void		 sparse_list_clear(struct pax *);
    100 static int		 sparse_list_add(struct pax *, int64_t, int64_t);
    101 static char		*url_encode(const char *in);
    102 static time_t		 get_ustar_max_mtime(void);
    103 
    104 /*
    105  * Set output format to 'restricted pax' format.
    106  *
    107  * This is the same as normal 'pax', but tries to suppress
    108  * the pax header whenever possible.  This is the default for
    109  * bsdtar, for instance.
    110  */
    111 int
    112 archive_write_set_format_pax_restricted(struct archive *_a)
    113 {
    114 	struct archive_write *a = (struct archive_write *)_a;
    115 	int r;
    116 
    117 	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
    118 	    ARCHIVE_STATE_NEW, "archive_write_set_format_pax_restricted");
    119 
    120 	r = archive_write_set_format_pax(&a->archive);
    121 	a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
    122 	a->archive.archive_format_name = "restricted POSIX pax interchange";
    123 	return (r);
    124 }
    125 
    126 /*
    127  * Set output format to 'pax' format.
    128  */
    129 int
    130 archive_write_set_format_pax(struct archive *_a)
    131 {
    132 	struct archive_write *a = (struct archive_write *)_a;
    133 	struct pax *pax;
    134 
    135 	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
    136 	    ARCHIVE_STATE_NEW, "archive_write_set_format_pax");
    137 
    138 	if (a->format_free != NULL)
    139 		(a->format_free)(a);
    140 
    141 	pax = calloc(1, sizeof(*pax));
    142 	if (pax == NULL) {
    143 		archive_set_error(&a->archive, ENOMEM,
    144 		    "Can't allocate pax data");
    145 		return (ARCHIVE_FATAL);
    146 	}
    147 	pax->flags = WRITE_LIBARCHIVE_XATTR | WRITE_SCHILY_XATTR;
    148 
    149 	a->format_data = pax;
    150 	a->format_name = "pax";
    151 	a->format_options = archive_write_pax_options;
    152 	a->format_write_header = archive_write_pax_header;
    153 	a->format_write_data = archive_write_pax_data;
    154 	a->format_close = archive_write_pax_close;
    155 	a->format_free = archive_write_pax_free;
    156 	a->format_finish_entry = archive_write_pax_finish_entry;
    157 	a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
    158 	a->archive.archive_format_name = "POSIX pax interchange";
    159 	return (ARCHIVE_OK);
    160 }
    161 
    162 static int
    163 archive_write_pax_options(struct archive_write *a, const char *key,
    164     const char *val)
    165 {
    166 	struct pax *pax = (struct pax *)a->format_data;
    167 	int ret = ARCHIVE_FAILED;
    168 
    169 	if (strcmp(key, "hdrcharset")  == 0) {
    170 		/*
    171 		 * The character-set we can use are defined in
    172 		 * IEEE Std 1003.1-2001
    173 		 */
    174 		if (val == NULL || val[0] == 0)
    175 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
    176 			    "pax: hdrcharset option needs a character-set name");
    177 		else if (strcmp(val, "BINARY") == 0 ||
    178 		    strcmp(val, "binary") == 0) {
    179 			/*
    180 			 * Specify binary mode. We will not convert
    181 			 * filenames, uname and gname to any charsets.
    182 			 */
    183 			pax->opt_binary = 1;
    184 			ret = ARCHIVE_OK;
    185 		} else if (strcmp(val, "UTF-8") == 0) {
    186 			/*
    187 			 * Specify UTF-8 character-set to be used for
    188 			 * filenames. This is almost the test that
    189 			 * running platform supports the string conversion.
    190 			 * Especially libarchive_test needs this trick for
    191 			 * its test.
    192 			 */
    193 			pax->sconv_utf8 = archive_string_conversion_to_charset(
    194 			    &(a->archive), "UTF-8", 0);
    195 			if (pax->sconv_utf8 == NULL)
    196 				ret = ARCHIVE_FATAL;
    197 			else
    198 				ret = ARCHIVE_OK;
    199 		} else
    200 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
    201 			    "pax: invalid charset name");
    202 		return (ret);
    203 	} else if (strcmp(key, "xattrheader") == 0) {
    204 		if (val == NULL || val[0] == 0) {
    205 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
    206 			    "pax: xattrheader requires a value");
    207 		} else if (strcmp(val, "ALL") == 0 ||
    208 		    strcmp(val, "all") == 0) {
    209 			pax->flags |= WRITE_LIBARCHIVE_XATTR | WRITE_SCHILY_XATTR;
    210 			ret = ARCHIVE_OK;
    211 		} else if (strcmp(val, "SCHILY") == 0 ||
    212 		    strcmp(val, "schily") == 0) {
    213 			pax->flags |= WRITE_SCHILY_XATTR;
    214 			pax->flags &= ~WRITE_LIBARCHIVE_XATTR;
    215 			ret = ARCHIVE_OK;
    216 		} else if (strcmp(val, "LIBARCHIVE") == 0 ||
    217 		    strcmp(val, "libarchive") == 0) {
    218 			pax->flags |= WRITE_LIBARCHIVE_XATTR;
    219 			pax->flags &= ~WRITE_SCHILY_XATTR;
    220 			ret = ARCHIVE_OK;
    221 		} else
    222 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
    223 			    "pax: invalid xattr header name");
    224 		return (ret);
    225 	}
    226 
    227 	/* Note: The "warn" return is just to inform the options
    228 	 * supervisor that we didn't handle it.  It will generate
    229 	 * a suitable error if no one used this option. */
    230 	return (ARCHIVE_WARN);
    231 }
    232 
    233 /*
    234  * Note: This code assumes that 'nanos' has the same sign as 'sec',
    235  * which implies that sec=-1, nanos=200000000 represents -1.2 seconds
    236  * and not -0.8 seconds.  This is a pretty pedantic point, as we're
    237  * unlikely to encounter many real files created before Jan 1, 1970,
    238  * much less ones with timestamps recorded to sub-second resolution.
    239  */
    240 static void
    241 add_pax_attr_time(struct archive_string *as, const char *key,
    242     int64_t sec, unsigned long nanos)
    243 {
    244 	int digit, i;
    245 	char *t;
    246 	/*
    247 	 * Note that each byte contributes fewer than 3 base-10
    248 	 * digits, so this will always be big enough.
    249 	 */
    250 	char tmp[1 + 3*sizeof(sec) + 1 + 3*sizeof(nanos)];
    251 
    252 	tmp[sizeof(tmp) - 1] = 0;
    253 	t = tmp + sizeof(tmp) - 1;
    254 
    255 	/* Skip trailing zeros in the fractional part. */
    256 	for (digit = 0, i = 10; i > 0 && digit == 0; i--) {
    257 		digit = nanos % 10;
    258 		nanos /= 10;
    259 	}
    260 
    261 	/* Only format the fraction if it's non-zero. */
    262 	if (i > 0) {
    263 		while (i > 0) {
    264 			*--t = "0123456789"[digit];
    265 			digit = nanos % 10;
    266 			nanos /= 10;
    267 			i--;
    268 		}
    269 		*--t = '.';
    270 	}
    271 	t = format_int(t, sec);
    272 
    273 	add_pax_attr(as, key, t);
    274 }
    275 
    276 static char *
    277 format_int(char *t, int64_t i)
    278 {
    279 	uint64_t ui;
    280 
    281 	if (i < 0)
    282 		ui = (i == INT64_MIN) ? (uint64_t)(INT64_MAX) + 1 : (uint64_t)(-i);
    283 	else
    284 		ui = i;
    285 
    286 	do {
    287 		*--t = "0123456789"[ui % 10];
    288 	} while (ui /= 10);
    289 	if (i < 0)
    290 		*--t = '-';
    291 	return (t);
    292 }
    293 
    294 static void
    295 add_pax_attr_int(struct archive_string *as, const char *key, int64_t value)
    296 {
    297 	char tmp[1 + 3 * sizeof(value)];
    298 
    299 	tmp[sizeof(tmp) - 1] = 0;
    300 	add_pax_attr(as, key, format_int(tmp + sizeof(tmp) - 1, value));
    301 }
    302 
    303 /*
    304  * Add a key/value attribute to the pax header.  This function handles
    305  * the length field and various other syntactic requirements.
    306  */
    307 static void
    308 add_pax_attr(struct archive_string *as, const char *key, const char *value)
    309 {
    310 	add_pax_attr_binary(as, key, value, strlen(value));
    311 }
    312 
    313 /*
    314  * Add a key/value attribute to the pax header.  This function handles
    315  * binary values.
    316  */
    317 static void
    318 add_pax_attr_binary(struct archive_string *as, const char *key,
    319 		    const char *value, size_t value_len)
    320 {
    321 	int digits, i, len, next_ten;
    322 	char tmp[1 + 3 * sizeof(int)];	/* < 3 base-10 digits per byte */
    323 
    324 	/*-
    325 	 * PAX attributes have the following layout:
    326 	 *     <len> <space> <key> <=> <value> <nl>
    327 	 */
    328 	len = 1 + (int)strlen(key) + 1 + (int)value_len + 1;
    329 
    330 	/*
    331 	 * The <len> field includes the length of the <len> field, so
    332 	 * computing the correct length is tricky.  I start by
    333 	 * counting the number of base-10 digits in 'len' and
    334 	 * computing the next higher power of 10.
    335 	 */
    336 	next_ten = 1;
    337 	digits = 0;
    338 	i = len;
    339 	while (i > 0) {
    340 		i = i / 10;
    341 		digits++;
    342 		next_ten = next_ten * 10;
    343 	}
    344 	/*
    345 	 * For example, if string without the length field is 99
    346 	 * chars, then adding the 2 digit length "99" will force the
    347 	 * total length past 100, requiring an extra digit.  The next
    348 	 * statement adjusts for this effect.
    349 	 */
    350 	if (len + digits >= next_ten)
    351 		digits++;
    352 
    353 	/* Now, we have the right length so we can build the line. */
    354 	tmp[sizeof(tmp) - 1] = 0;	/* Null-terminate the work area. */
    355 	archive_strcat(as, format_int(tmp + sizeof(tmp) - 1, len + digits));
    356 	archive_strappend_char(as, ' ');
    357 	archive_strcat(as, key);
    358 	archive_strappend_char(as, '=');
    359 	archive_array_append(as, value, value_len);
    360 	archive_strappend_char(as, '\n');
    361 }
    362 
    363 static void
    364 archive_write_pax_header_xattr(struct pax *pax, const char *encoded_name,
    365     const void *value, size_t value_len)
    366 {
    367 	struct archive_string s;
    368 	char *encoded_value;
    369 
    370 	if (encoded_name == NULL)
    371 		return;
    372 
    373 	if (pax->flags & WRITE_LIBARCHIVE_XATTR) {
    374 		encoded_value = base64_encode((const char *)value, value_len);
    375 		if (encoded_value != NULL) {
    376 			archive_string_init(&s);
    377 			archive_strcpy(&s, "LIBARCHIVE.xattr.");
    378 			archive_strcat(&s, encoded_name);
    379 			add_pax_attr(&(pax->pax_header), s.s, encoded_value);
    380 			archive_string_free(&s);
    381 		}
    382 		free(encoded_value);
    383 	}
    384 	if (pax->flags & WRITE_SCHILY_XATTR) {
    385 		archive_string_init(&s);
    386 		archive_strcpy(&s, "SCHILY.xattr.");
    387 		archive_strcat(&s, encoded_name);
    388 		add_pax_attr_binary(&(pax->pax_header), s.s, value, value_len);
    389 		archive_string_free(&s);
    390 	}
    391 }
    392 
    393 static int
    394 archive_write_pax_header_xattrs(struct archive_write *a,
    395     struct pax *pax, struct archive_entry *entry)
    396 {
    397 	int i = archive_entry_xattr_reset(entry);
    398 
    399 	while (i--) {
    400 		const char *name;
    401 		const void *value;
    402 		char *url_encoded_name = NULL, *encoded_name = NULL;
    403 		size_t size;
    404 		int r;
    405 
    406 		archive_entry_xattr_next(entry, &name, &value, &size);
    407 		url_encoded_name = url_encode(name);
    408 		if (url_encoded_name == NULL)
    409 			goto malloc_error;
    410 		else {
    411 			/* Convert narrow-character to UTF-8. */
    412 			r = archive_strcpy_l(&(pax->l_url_encoded_name),
    413 			    url_encoded_name, pax->sconv_utf8);
    414 			free(url_encoded_name); /* Done with this. */
    415 			if (r == 0)
    416 				encoded_name = pax->l_url_encoded_name.s;
    417 			else if (r == -1)
    418 				goto malloc_error;
    419 			else {
    420 				archive_set_error(&a->archive,
    421 				    ARCHIVE_ERRNO_MISC,
    422 				    "Error encoding pax extended attribute");
    423 				return (ARCHIVE_FAILED);
    424 			}
    425 		}
    426 
    427 		archive_write_pax_header_xattr(pax, encoded_name,
    428 		    value, size);
    429 
    430 	}
    431 	return (ARCHIVE_OK);
    432 malloc_error:
    433 	archive_set_error(&a->archive, ENOMEM, "Can't allocate memory");
    434 	return (ARCHIVE_FATAL);
    435 }
    436 
    437 static int
    438 get_entry_hardlink(struct archive_write *a, struct archive_entry *entry,
    439     const char **name, size_t *length, struct archive_string_conv *sc)
    440 {
    441 	int r;
    442 
    443 	r = archive_entry_hardlink_l(entry, name, length, sc);
    444 	if (r != 0) {
    445 		if (errno == ENOMEM) {
    446 			archive_set_error(&a->archive, ENOMEM,
    447 			    "Can't allocate memory for Linkname");
    448 			return (ARCHIVE_FATAL);
    449 		}
    450 		return (ARCHIVE_WARN);
    451 	}
    452 	return (ARCHIVE_OK);
    453 }
    454 
    455 static int
    456 get_entry_pathname(struct archive_write *a, struct archive_entry *entry,
    457     const char **name, size_t *length, struct archive_string_conv *sc)
    458 {
    459 	int r;
    460 
    461 	r = archive_entry_pathname_l(entry, name, length, sc);
    462 	if (r != 0) {
    463 		if (errno == ENOMEM) {
    464 			archive_set_error(&a->archive, ENOMEM,
    465 			    "Can't allocate memory for Pathname");
    466 			return (ARCHIVE_FATAL);
    467 		}
    468 		return (ARCHIVE_WARN);
    469 	}
    470 	return (ARCHIVE_OK);
    471 }
    472 
    473 static int
    474 get_entry_uname(struct archive_write *a, struct archive_entry *entry,
    475     const char **name, size_t *length, struct archive_string_conv *sc)
    476 {
    477 	int r;
    478 
    479 	r = archive_entry_uname_l(entry, name, length, sc);
    480 	if (r != 0) {
    481 		if (errno == ENOMEM) {
    482 			archive_set_error(&a->archive, ENOMEM,
    483 			    "Can't allocate memory for Uname");
    484 			return (ARCHIVE_FATAL);
    485 		}
    486 		return (ARCHIVE_WARN);
    487 	}
    488 	return (ARCHIVE_OK);
    489 }
    490 
    491 static int
    492 get_entry_gname(struct archive_write *a, struct archive_entry *entry,
    493     const char **name, size_t *length, struct archive_string_conv *sc)
    494 {
    495 	int r;
    496 
    497 	r = archive_entry_gname_l(entry, name, length, sc);
    498 	if (r != 0) {
    499 		if (errno == ENOMEM) {
    500 			archive_set_error(&a->archive, ENOMEM,
    501 			    "Can't allocate memory for Gname");
    502 			return (ARCHIVE_FATAL);
    503 		}
    504 		return (ARCHIVE_WARN);
    505 	}
    506 	return (ARCHIVE_OK);
    507 }
    508 
    509 static int
    510 get_entry_symlink(struct archive_write *a, struct archive_entry *entry,
    511     const char **name, size_t *length, struct archive_string_conv *sc)
    512 {
    513 	int r;
    514 
    515 	r = archive_entry_symlink_l(entry, name, length, sc);
    516 	if (r != 0) {
    517 		if (errno == ENOMEM) {
    518 			archive_set_error(&a->archive, ENOMEM,
    519 			    "Can't allocate memory for Linkname");
    520 			return (ARCHIVE_FATAL);
    521 		}
    522 		return (ARCHIVE_WARN);
    523 	}
    524 	return (ARCHIVE_OK);
    525 }
    526 
    527 /* Add ACL to pax header */
    528 static int
    529 add_pax_acl(struct archive_write *a,
    530     struct archive_entry *entry, struct pax *pax, int flags)
    531 {
    532 	char *p;
    533 	const char *attr;
    534 	int acl_types;
    535 
    536 	acl_types = archive_entry_acl_types(entry);
    537 
    538 	if ((acl_types & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0)
    539 		attr = "SCHILY.acl.ace";
    540 	else if ((flags & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0)
    541 		attr = "SCHILY.acl.access";
    542 	else if ((flags & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0)
    543 		attr = "SCHILY.acl.default";
    544 	else
    545 		return (ARCHIVE_FATAL);
    546 
    547 	p = archive_entry_acl_to_text_l(entry, NULL, flags, pax->sconv_utf8);
    548 	if (p == NULL) {
    549 		if (errno == ENOMEM) {
    550 			archive_set_error(&a->archive, ENOMEM, "%s %s",
    551 			    "Can't allocate memory for ", attr);
    552 			return (ARCHIVE_FATAL);
    553 		}
    554 		archive_set_error(&a->archive,
    555 		    ARCHIVE_ERRNO_FILE_FORMAT, "%s %s %s",
    556 		    "Can't translate ", attr, " to UTF-8");
    557 		return(ARCHIVE_WARN);
    558 	}
    559 
    560 	if (*p != '\0') {
    561 		add_pax_attr(&(pax->pax_header),
    562 		    attr, p);
    563 	}
    564 	free(p);
    565 	return(ARCHIVE_OK);
    566 }
    567 
    568 /*
    569  * TODO: Consider adding 'comment' and 'charset' fields to
    570  * archive_entry so that clients can specify them.  Also, consider
    571  * adding generic key/value tags so clients can add arbitrary
    572  * key/value data.
    573  *
    574  * TODO: Break up this 700-line function!!!!  Yowza!
    575  */
    576 static int
    577 archive_write_pax_header(struct archive_write *a,
    578     struct archive_entry *entry_original)
    579 {
    580 	struct archive_entry *entry_main;
    581 	const char *p;
    582 	const char *suffix;
    583 	int need_extension, r, ret;
    584 	int acl_types;
    585 	int sparse_count;
    586 	uint64_t sparse_total, real_size;
    587 	struct pax *pax;
    588 	const char *hardlink;
    589 	const char *path = NULL, *linkpath = NULL;
    590 	const char *uname = NULL, *gname = NULL;
    591 	const void *mac_metadata;
    592 	size_t mac_metadata_size;
    593 	struct archive_string_conv *sconv;
    594 	size_t hardlink_length, path_length, linkpath_length;
    595 	size_t uname_length, gname_length;
    596 
    597 	char paxbuff[512];
    598 	char ustarbuff[512];
    599 	char ustar_entry_name[256];
    600 	char pax_entry_name[256];
    601 	char gnu_sparse_name[256];
    602 	struct archive_string entry_name;
    603 
    604 	ret = ARCHIVE_OK;
    605 	need_extension = 0;
    606 	pax = (struct pax *)a->format_data;
    607 
    608 	const time_t ustar_max_mtime = get_ustar_max_mtime();
    609 
    610 	/* Sanity check. */
    611 #if defined(_WIN32) && !defined(__CYGWIN__)
    612 	/* NOTE: If the caller supplied a pathname that fails WCS conversion (e.g.
    613 	 * if it is invalid UTF-8), we are expected to return ARCHIVE_WARN later on
    614 	 * in execution, hence the check for both pointers */
    615 	if ((archive_entry_pathname_w(entry_original) == NULL) &&
    616 	    (archive_entry_pathname(entry_original) == NULL)) {
    617 #else
    618 	if (archive_entry_pathname(entry_original) == NULL) {
    619 #endif
    620 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
    621 			  "Can't record entry in tar file without pathname");
    622 		return (ARCHIVE_FAILED);
    623 	}
    624 
    625 	/*
    626 	 * Choose a header encoding.
    627 	 */
    628 	if (pax->opt_binary)
    629 		sconv = NULL;/* Binary mode. */
    630 	else {
    631 		/* Header encoding is UTF-8. */
    632 		if (pax->sconv_utf8 == NULL) {
    633 			/* Initialize the string conversion object
    634 			 * we must need */
    635 			pax->sconv_utf8 = archive_string_conversion_to_charset(
    636 			    &(a->archive), "UTF-8", 1);
    637 			if (pax->sconv_utf8 == NULL)
    638 				/* Couldn't allocate memory */
    639 				return (ARCHIVE_FAILED);
    640 		}
    641 		sconv = pax->sconv_utf8;
    642 	}
    643 
    644 	r = get_entry_hardlink(a, entry_original, &hardlink,
    645 	    &hardlink_length, sconv);
    646 	if (r == ARCHIVE_FATAL)
    647 		return (r);
    648 	else if (r != ARCHIVE_OK) {
    649 		r = get_entry_hardlink(a, entry_original, &hardlink,
    650 		    &hardlink_length, NULL);
    651 		if (r == ARCHIVE_FATAL)
    652 			return (r);
    653 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
    654 		    "Can't translate linkname '%s' to %s", hardlink,
    655 		    archive_string_conversion_charset_name(sconv));
    656 		ret = ARCHIVE_WARN;
    657 		sconv = NULL;/* The header charset switches to binary mode. */
    658 	}
    659 
    660 	/* Make sure this is a type of entry that we can handle here */
    661 	if (hardlink == NULL) {
    662 		switch (archive_entry_filetype(entry_original)) {
    663 		case AE_IFBLK:
    664 		case AE_IFCHR:
    665 		case AE_IFIFO:
    666 		case AE_IFLNK:
    667 		case AE_IFREG:
    668 			break;
    669 		case AE_IFDIR:
    670 		{
    671 			/*
    672 			 * Ensure a trailing '/'.  Modify the original
    673 			 * entry so the client sees the change.
    674 			 */
    675 #if defined(_WIN32) && !defined(__CYGWIN__)
    676 			const wchar_t *wp;
    677 
    678 			wp = archive_entry_pathname_w(entry_original);
    679 			if (wp != NULL && wp[wcslen(wp) -1] != L'/') {
    680 				struct archive_wstring ws;
    681 
    682 				archive_string_init(&ws);
    683 				path_length = wcslen(wp);
    684 				if (archive_wstring_ensure(&ws,
    685 				    path_length + 2) == NULL) {
    686 					archive_set_error(&a->archive, ENOMEM,
    687 					    "Can't allocate pax data");
    688 					archive_wstring_free(&ws);
    689 					return(ARCHIVE_FATAL);
    690 				}
    691 				/* Should we keep '\' ? */
    692 				if (wp[path_length -1] == L'\\')
    693 					path_length--;
    694 				archive_wstrncpy(&ws, wp, path_length);
    695 				archive_wstrappend_wchar(&ws, L'/');
    696 				archive_entry_copy_pathname_w(
    697 				    entry_original, ws.s);
    698 				archive_wstring_free(&ws);
    699 				p = NULL;
    700 			} else
    701 #endif
    702 				p = archive_entry_pathname(entry_original);
    703 			/*
    704 			 * On Windows, this is a backup operation just in
    705 			 * case getting WCS failed. On POSIX, this is a
    706 			 * normal operation.
    707 			 */
    708 			if (p != NULL && p[0] != '\0' && p[strlen(p) - 1] != '/') {
    709 				struct archive_string as;
    710 
    711 				archive_string_init(&as);
    712 				path_length = strlen(p);
    713 				if (archive_string_ensure(&as,
    714 				    path_length + 2) == NULL) {
    715 					archive_set_error(&a->archive, ENOMEM,
    716 					    "Can't allocate pax data");
    717 					archive_string_free(&as);
    718 					return(ARCHIVE_FATAL);
    719 				}
    720 #if defined(_WIN32) && !defined(__CYGWIN__)
    721 				/* NOTE: This might break the pathname
    722 				 * if the current code page is CP932 and
    723 				 * the pathname includes a character '\'
    724 				 * as a part of its multibyte pathname. */
    725 				if (p[strlen(p) -1] == '\\')
    726 					path_length--;
    727 				else
    728 #endif
    729 				archive_strncpy(&as, p, path_length);
    730 				archive_strappend_char(&as, '/');
    731 				archive_entry_copy_pathname(
    732 				    entry_original, as.s);
    733 				archive_string_free(&as);
    734 			}
    735 			break;
    736 		}
    737 		default: /* AE_IFSOCK and unknown */
    738 			__archive_write_entry_filetype_unsupported(
    739 			    &a->archive, entry_original, "pax");
    740 			return (ARCHIVE_FAILED);
    741 		}
    742 	}
    743 
    744 	/*
    745 	 * If Mac OS metadata blob is here, recurse to write that
    746 	 * as a separate entry.  This is really a pretty poor design:
    747 	 * In particular, it doubles the overhead for long filenames.
    748 	 * TODO: Help Apple folks design something better and figure
    749 	 * out how to transition from this legacy format.
    750 	 *
    751 	 * Note that this code is present on every platform; clients
    752 	 * on non-Mac are unlikely to ever provide this data, but
    753 	 * applications that copy entries from one archive to another
    754 	 * should not lose data just because the local filesystem
    755 	 * can't store it.
    756 	 */
    757 	mac_metadata =
    758 	    archive_entry_mac_metadata(entry_original, &mac_metadata_size);
    759 	if (mac_metadata != NULL) {
    760 		const char *oname;
    761 		char *name, *bname;
    762 		size_t name_length;
    763 		struct archive_entry *extra = archive_entry_new2(&a->archive);
    764 
    765 		oname = archive_entry_pathname(entry_original);
    766 		name_length = strlen(oname);
    767 		name = malloc(name_length + 3);
    768 		if (name == NULL || extra == NULL) {
    769 			/* XXX error message */
    770 			archive_entry_free(extra);
    771 			free(name);
    772 			return (ARCHIVE_FAILED);
    773 		}
    774 		strcpy(name, oname);
    775 		/* Find last '/'; strip trailing '/' characters */
    776 		bname = strrchr(name, '/');
    777 		while (bname != NULL && bname[1] == '\0') {
    778 			*bname = '\0';
    779 			bname = strrchr(name, '/');
    780 		}
    781 		if (bname == NULL) {
    782 			memmove(name + 2, name, name_length + 1);
    783 			memmove(name, "._", 2);
    784 		} else {
    785 			bname += 1;
    786 			memmove(bname + 2, bname, strlen(bname) + 1);
    787 			memmove(bname, "._", 2);
    788 		}
    789 		archive_entry_copy_pathname(extra, name);
    790 		free(name);
    791 
    792 		archive_entry_set_size(extra, mac_metadata_size);
    793 		archive_entry_set_filetype(extra, AE_IFREG);
    794 		archive_entry_set_perm(extra,
    795 		    archive_entry_perm(entry_original));
    796 		archive_entry_set_mtime(extra,
    797 		    archive_entry_mtime(entry_original),
    798 		    archive_entry_mtime_nsec(entry_original));
    799 		archive_entry_set_gid(extra,
    800 		    archive_entry_gid(entry_original));
    801 		archive_entry_set_gname(extra,
    802 		    archive_entry_gname(entry_original));
    803 		archive_entry_set_uid(extra,
    804 		    archive_entry_uid(entry_original));
    805 		archive_entry_set_uname(extra,
    806 		    archive_entry_uname(entry_original));
    807 
    808 		/* Recurse to write the special copyfile entry. */
    809 		r = archive_write_pax_header(a, extra);
    810 		archive_entry_free(extra);
    811 		if (r < ARCHIVE_WARN)
    812 			return (r);
    813 		if (r < ret)
    814 			ret = r;
    815 		r = (int)archive_write_pax_data(a, mac_metadata,
    816 		    mac_metadata_size);
    817 		if (r < ARCHIVE_WARN)
    818 			return (r);
    819 		if (r < ret)
    820 			ret = r;
    821 		r = archive_write_pax_finish_entry(a);
    822 		if (r < ARCHIVE_WARN)
    823 			return (r);
    824 		if (r < ret)
    825 			ret = r;
    826 	}
    827 
    828 	/* Copy entry so we can modify it as needed. */
    829 #if defined(_WIN32) && !defined(__CYGWIN__)
    830 	/* Make sure the path separators in pathname, hardlink and symlink
    831 	 * are all slash '/', not the Windows path separator '\'. */
    832 	entry_main = __la_win_entry_in_posix_pathseparator(entry_original);
    833 	if (entry_main == entry_original)
    834 		entry_main = archive_entry_clone(entry_original);
    835 #else
    836 	entry_main = archive_entry_clone(entry_original);
    837 #endif
    838 	if (entry_main == NULL) {
    839 		archive_set_error(&a->archive, ENOMEM,
    840 		    "Can't allocate pax data");
    841 		return(ARCHIVE_FATAL);
    842 	}
    843 	archive_string_empty(&(pax->pax_header)); /* Blank our work area. */
    844 	archive_string_empty(&(pax->sparse_map));
    845 	sparse_total = 0;
    846 	sparse_list_clear(pax);
    847 
    848 	if (hardlink == NULL &&
    849 	    archive_entry_filetype(entry_main) == AE_IFREG)
    850 		sparse_count = archive_entry_sparse_reset(entry_main);
    851 	else
    852 		sparse_count = 0;
    853 	if (sparse_count) {
    854 		int64_t offset, length, last_offset = 0;
    855 		/* Get the last entry of sparse block. */
    856 		while (archive_entry_sparse_next(
    857 		    entry_main, &offset, &length) == ARCHIVE_OK)
    858 			last_offset = offset + length;
    859 
    860 		/* If the last sparse block does not reach the end of file,
    861 		 * We have to add a empty sparse block as the last entry to
    862 		 * manage storing file data. */
    863 		if (last_offset < archive_entry_size(entry_main))
    864 			archive_entry_sparse_add_entry(entry_main,
    865 			    archive_entry_size(entry_main), 0);
    866 		sparse_count = archive_entry_sparse_reset(entry_main);
    867 	}
    868 
    869 	/*
    870 	 * First, check the name fields and see if any of them
    871 	 * require binary coding.  If any of them does, then all of
    872 	 * them do.
    873 	 */
    874 	r = get_entry_pathname(a, entry_main, &path, &path_length, sconv);
    875 	if (r == ARCHIVE_FATAL) {
    876 		archive_entry_free(entry_main);
    877 		return (r);
    878 	} else if (r != ARCHIVE_OK) {
    879 		r = get_entry_pathname(a, entry_main, &path,
    880 		    &path_length, NULL);
    881 		if (r == ARCHIVE_FATAL) {
    882 			archive_entry_free(entry_main);
    883 			return (r);
    884 		}
    885 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
    886 		    "Can't translate pathname '%s' to %s", path,
    887 		    archive_string_conversion_charset_name(sconv));
    888 		ret = ARCHIVE_WARN;
    889 		sconv = NULL;/* The header charset switches to binary mode. */
    890 	}
    891 	r = get_entry_uname(a, entry_main, &uname, &uname_length, sconv);
    892 	if (r == ARCHIVE_FATAL) {
    893 		archive_entry_free(entry_main);
    894 		return (r);
    895 	} else if (r != ARCHIVE_OK) {
    896 		r = get_entry_uname(a, entry_main, &uname, &uname_length, NULL);
    897 		if (r == ARCHIVE_FATAL) {
    898 			archive_entry_free(entry_main);
    899 			return (r);
    900 		}
    901 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
    902 		    "Can't translate uname '%s' to %s", uname,
    903 		    archive_string_conversion_charset_name(sconv));
    904 		ret = ARCHIVE_WARN;
    905 		sconv = NULL;/* The header charset switches to binary mode. */
    906 	}
    907 	r = get_entry_gname(a, entry_main, &gname, &gname_length, sconv);
    908 	if (r == ARCHIVE_FATAL) {
    909 		archive_entry_free(entry_main);
    910 		return (r);
    911 	} else if (r != ARCHIVE_OK) {
    912 		r = get_entry_gname(a, entry_main, &gname, &gname_length, NULL);
    913 		if (r == ARCHIVE_FATAL) {
    914 			archive_entry_free(entry_main);
    915 			return (r);
    916 		}
    917 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
    918 		    "Can't translate gname '%s' to %s", gname,
    919 		    archive_string_conversion_charset_name(sconv));
    920 		ret = ARCHIVE_WARN;
    921 		sconv = NULL;/* The header charset switches to binary mode. */
    922 	}
    923 	linkpath = hardlink;
    924 	linkpath_length = hardlink_length;
    925 	if (linkpath == NULL) {
    926 		r = get_entry_symlink(a, entry_main, &linkpath,
    927 		    &linkpath_length, sconv);
    928 		if (r == ARCHIVE_FATAL) {
    929 			archive_entry_free(entry_main);
    930 			return (r);
    931 		} else if (r != ARCHIVE_OK) {
    932 			r = get_entry_symlink(a, entry_main, &linkpath,
    933 			    &linkpath_length, NULL);
    934 			if (r == ARCHIVE_FATAL) {
    935 				archive_entry_free(entry_main);
    936 				return (r);
    937 			}
    938 			archive_set_error(&a->archive,
    939 			    ARCHIVE_ERRNO_FILE_FORMAT,
    940 			    "Can't translate linkname '%s' to %s", linkpath,
    941 			    archive_string_conversion_charset_name(sconv));
    942 			ret = ARCHIVE_WARN;
    943 			sconv = NULL;
    944 		}
    945 	}
    946 
    947 	/* If any string conversions failed, get all attributes
    948 	 * in binary-mode. */
    949 	if (sconv == NULL && !pax->opt_binary) {
    950 		if (hardlink != NULL) {
    951 			r = get_entry_hardlink(a, entry_main, &hardlink,
    952 			    &hardlink_length, NULL);
    953 			if (r == ARCHIVE_FATAL) {
    954 				archive_entry_free(entry_main);
    955 				return (r);
    956 			}
    957 			linkpath = hardlink;
    958 			linkpath_length = hardlink_length;
    959 		}
    960 		r = get_entry_pathname(a, entry_main, &path,
    961 		    &path_length, NULL);
    962 		if (r == ARCHIVE_FATAL) {
    963 			archive_entry_free(entry_main);
    964 			return (r);
    965 		}
    966 		r = get_entry_uname(a, entry_main, &uname, &uname_length, NULL);
    967 		if (r == ARCHIVE_FATAL) {
    968 			archive_entry_free(entry_main);
    969 			return (r);
    970 		}
    971 		r = get_entry_gname(a, entry_main, &gname, &gname_length, NULL);
    972 		if (r == ARCHIVE_FATAL) {
    973 			archive_entry_free(entry_main);
    974 			return (r);
    975 		}
    976 	}
    977 
    978 	/* Store the header encoding first, to be nice to readers. */
    979 	if (sconv == NULL)
    980 		add_pax_attr(&(pax->pax_header), "hdrcharset", "BINARY");
    981 
    982 
    983 	/*
    984 	 * If name is too long, or has non-ASCII characters, add
    985 	 * 'path' to pax extended attrs.  (Note that an unconvertible
    986 	 * name must have non-ASCII characters.)
    987 	 */
    988 	if (has_non_ASCII(path)) {
    989 		/* We have non-ASCII characters. */
    990 		add_pax_attr(&(pax->pax_header), "path", path);
    991 		archive_entry_set_pathname(entry_main,
    992 		    build_ustar_entry_name(ustar_entry_name,
    993 			path, path_length, NULL));
    994 		need_extension = 1;
    995 	} else {
    996 		/* We have an all-ASCII path; we'd like to just store
    997 		 * it in the ustar header if it will fit.  Yes, this
    998 		 * duplicates some of the logic in
    999 		 * archive_write_set_format_ustar.c
   1000 		 */
   1001 		if (path_length <= 100) {
   1002 			/* Fits in the old 100-char tar name field. */
   1003 		} else {
   1004 			/* Find largest suffix that will fit. */
   1005 			/* Note: strlen() > 100, so strlen() - 100 - 1 >= 0 */
   1006 			suffix = strchr(path + path_length - 100 - 1, '/');
   1007 			/* Don't attempt an empty prefix. */
   1008 			if (suffix == path)
   1009 				suffix = strchr(suffix + 1, '/');
   1010 			/* We can put it in the ustar header if it's
   1011 			 * all ASCII and it's either <= 100 characters
   1012 			 * or can be split at a '/' into a prefix <=
   1013 			 * 155 chars and a suffix <= 100 chars.  (Note
   1014 			 * the strchr() above will return NULL exactly
   1015 			 * when the path can't be split.)
   1016 			 */
   1017 			if (suffix == NULL       /* Suffix > 100 chars. */
   1018 			    || suffix[1] == '\0'    /* empty suffix */
   1019 			    || suffix - path > 155)  /* Prefix > 155 chars */
   1020 			{
   1021 				add_pax_attr(&(pax->pax_header), "path", path);
   1022 				archive_entry_set_pathname(entry_main,
   1023 				    build_ustar_entry_name(ustar_entry_name,
   1024 					path, path_length, NULL));
   1025 				need_extension = 1;
   1026 			}
   1027 		}
   1028 	}
   1029 
   1030 	if (linkpath != NULL) {
   1031 		/* If link name is too long or has non-ASCII characters, add
   1032 		 * 'linkpath' to pax extended attrs. */
   1033 		if (linkpath_length > 100 || has_non_ASCII(linkpath)) {
   1034 			add_pax_attr(&(pax->pax_header), "linkpath", linkpath);
   1035 			if (linkpath_length > 100) {
   1036 				if (hardlink != NULL)
   1037 					archive_entry_set_hardlink(entry_main,
   1038 					    "././@LongHardLink");
   1039 				else
   1040 					archive_entry_set_symlink(entry_main,
   1041 					    "././@LongSymLink");
   1042 			}
   1043 			else {
   1044 				/* Otherwise, has non-ASCII characters; update the paths to
   1045 				 * however they got decoded above */
   1046 				if (hardlink != NULL)
   1047 					archive_entry_set_hardlink(entry_main, linkpath);
   1048 				else
   1049 					archive_entry_set_symlink(entry_main, linkpath);
   1050 			}
   1051 			need_extension = 1;
   1052 		}
   1053 	}
   1054 	/* Save a pathname since it will be renamed if `entry_main` has
   1055 	 * sparse blocks. */
   1056 	archive_string_init(&entry_name);
   1057 	archive_strcpy(&entry_name, archive_entry_pathname(entry_main));
   1058 
   1059 	/* If file size is too large, we need pax extended attrs. */
   1060 	if (archive_entry_size(entry_main) >= (((int64_t)1) << 33)) {
   1061 		need_extension = 1;
   1062 	}
   1063 
   1064 	/* If numeric GID is too large, add 'gid' to pax extended attrs. */
   1065 	if (archive_entry_gid(entry_main) >= (1 << 18)) {
   1066 		add_pax_attr_int(&(pax->pax_header), "gid",
   1067 		    archive_entry_gid(entry_main));
   1068 		need_extension = 1;
   1069 	}
   1070 
   1071 	/* If group name is too large or has non-ASCII characters, add
   1072 	 * 'gname' to pax extended attrs. */
   1073 	if (gname != NULL) {
   1074 		if (gname_length > 31 || has_non_ASCII(gname)) {
   1075 			add_pax_attr(&(pax->pax_header), "gname", gname);
   1076 			need_extension = 1;
   1077 		}
   1078 	}
   1079 
   1080 	/* If numeric UID is too large, add 'uid' to pax extended attrs. */
   1081 	if (archive_entry_uid(entry_main) >= (1 << 18)) {
   1082 		add_pax_attr_int(&(pax->pax_header), "uid",
   1083 		    archive_entry_uid(entry_main));
   1084 		need_extension = 1;
   1085 	}
   1086 
   1087 	/* Add 'uname' to pax extended attrs if necessary. */
   1088 	if (uname != NULL) {
   1089 		if (uname_length > 31 || has_non_ASCII(uname)) {
   1090 			add_pax_attr(&(pax->pax_header), "uname", uname);
   1091 			need_extension = 1;
   1092 		}
   1093 	}
   1094 
   1095 	/*
   1096 	 * POSIX/SUSv3 doesn't provide a standard key for large device
   1097 	 * numbers.  I use the same keys here that Joerg Schilling
   1098 	 * used for 'star.'  (Which, somewhat confusingly, are called
   1099 	 * "devXXX" even though they code "rdev" values.)  No doubt,
   1100 	 * other implementations use other keys.  Note that there's no
   1101 	 * reason we can't write the same information into a number of
   1102 	 * different keys.
   1103 	 *
   1104 	 * Of course, this is only needed for block or char device entries.
   1105 	 */
   1106 	if (archive_entry_filetype(entry_main) == AE_IFBLK
   1107 	    || archive_entry_filetype(entry_main) == AE_IFCHR) {
   1108 		/*
   1109 		 * If rdevmajor is too large, add 'SCHILY.devmajor' to
   1110 		 * extended attributes.
   1111 		 */
   1112 		int rdevmajor, rdevminor;
   1113 		rdevmajor = archive_entry_rdevmajor(entry_main);
   1114 		rdevminor = archive_entry_rdevminor(entry_main);
   1115 		if (rdevmajor >= (1 << 18)) {
   1116 			add_pax_attr_int(&(pax->pax_header), "SCHILY.devmajor",
   1117 			    rdevmajor);
   1118 			/*
   1119 			 * Non-strict formatting below means we don't
   1120 			 * have to truncate here.  Not truncating improves
   1121 			 * the chance that some more modern tar archivers
   1122 			 * (such as GNU tar 1.13) can restore the full
   1123 			 * value even if they don't understand the pax
   1124 			 * extended attributes.  See my rant below about
   1125 			 * file size fields for additional details.
   1126 			 */
   1127 			/* archive_entry_set_rdevmajor(entry_main,
   1128 			   rdevmajor & ((1 << 18) - 1)); */
   1129 			need_extension = 1;
   1130 		}
   1131 
   1132 		/*
   1133 		 * If devminor is too large, add 'SCHILY.devminor' to
   1134 		 * extended attributes.
   1135 		 */
   1136 		if (rdevminor >= (1 << 18)) {
   1137 			add_pax_attr_int(&(pax->pax_header), "SCHILY.devminor",
   1138 			    rdevminor);
   1139 			/* Truncation is not necessary here, either. */
   1140 			/* archive_entry_set_rdevminor(entry_main,
   1141 			   rdevminor & ((1 << 18) - 1)); */
   1142 			need_extension = 1;
   1143 		}
   1144 	}
   1145 
   1146 	/*
   1147 	 * Yes, this check is duplicated just below; this helps to
   1148 	 * avoid writing an mtime attribute just to handle a
   1149 	 * high-resolution timestamp in "restricted pax" mode.
   1150 	 */
   1151 	if (!need_extension &&
   1152 	    ((archive_entry_mtime(entry_main) < 0)
   1153 		|| (archive_entry_mtime(entry_main) >= ustar_max_mtime)))
   1154 		need_extension = 1;
   1155 
   1156 	/* I use a star-compatible file flag attribute. */
   1157 	p = archive_entry_fflags_text(entry_main);
   1158 	if (!need_extension && p != NULL  &&  *p != '\0')
   1159 		need_extension = 1;
   1160 
   1161 	/* If there are extended attributes, we need an extension */
   1162 	if (!need_extension && archive_entry_xattr_count(entry_original) > 0)
   1163 		need_extension = 1;
   1164 
   1165 	/* If there are sparse info, we need an extension */
   1166 	if (!need_extension && sparse_count > 0)
   1167 		need_extension = 1;
   1168 
   1169 	acl_types = archive_entry_acl_types(entry_original);
   1170 
   1171 	/* If there are any ACL entries, we need an extension */
   1172 	if (!need_extension && acl_types != 0)
   1173 		need_extension = 1;
   1174 
   1175 	/* If the symlink type is defined, we need an extension */
   1176 	if (!need_extension && archive_entry_symlink_type(entry_main) > 0)
   1177 		need_extension = 1;
   1178 
   1179 	/*
   1180 	 * Libarchive used to include these in extended headers for
   1181 	 * restricted pax format, but that confused people who
   1182 	 * expected ustar-like time semantics.  So now we only include
   1183 	 * them in full pax format.
   1184 	 */
   1185 	if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED) {
   1186 		if (archive_entry_ctime(entry_main) != 0  ||
   1187 		    archive_entry_ctime_nsec(entry_main) != 0)
   1188 			add_pax_attr_time(&(pax->pax_header), "ctime",
   1189 			    archive_entry_ctime(entry_main),
   1190 			    archive_entry_ctime_nsec(entry_main));
   1191 
   1192 		if (archive_entry_atime(entry_main) != 0 ||
   1193 		    archive_entry_atime_nsec(entry_main) != 0)
   1194 			add_pax_attr_time(&(pax->pax_header), "atime",
   1195 			    archive_entry_atime(entry_main),
   1196 			    archive_entry_atime_nsec(entry_main));
   1197 
   1198 		/* Store birth/creationtime only if it's earlier than mtime */
   1199 		if (archive_entry_birthtime_is_set(entry_main) &&
   1200 		    archive_entry_birthtime(entry_main)
   1201 		    < archive_entry_mtime(entry_main))
   1202 			add_pax_attr_time(&(pax->pax_header),
   1203 			    "LIBARCHIVE.creationtime",
   1204 			    archive_entry_birthtime(entry_main),
   1205 			    archive_entry_birthtime_nsec(entry_main));
   1206 	}
   1207 
   1208 	/*
   1209 	 * The following items are handled differently in "pax
   1210 	 * restricted" format.  In particular, in "pax restricted"
   1211 	 * format they won't be added unless need_extension is
   1212 	 * already set (we're already generating an extended header, so
   1213 	 * may as well include these).
   1214 	 */
   1215 	if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED ||
   1216 	    need_extension) {
   1217 		if (archive_entry_mtime(entry_main) < 0  ||
   1218 		    archive_entry_mtime(entry_main) >= ustar_max_mtime  ||
   1219 		    archive_entry_mtime_nsec(entry_main) != 0)
   1220 			add_pax_attr_time(&(pax->pax_header), "mtime",
   1221 			    archive_entry_mtime(entry_main),
   1222 			    archive_entry_mtime_nsec(entry_main));
   1223 
   1224 		/* I use a star-compatible file flag attribute. */
   1225 		p = archive_entry_fflags_text(entry_main);
   1226 		if (p != NULL  &&  *p != '\0')
   1227 			add_pax_attr(&(pax->pax_header), "SCHILY.fflags", p);
   1228 
   1229 		/* I use star-compatible ACL attributes. */
   1230 		if ((acl_types & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) {
   1231 			ret = add_pax_acl(a, entry_original, pax,
   1232 			    ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID |
   1233 			    ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA |
   1234 			    ARCHIVE_ENTRY_ACL_STYLE_COMPACT);
   1235 			if (ret == ARCHIVE_FATAL) {
   1236 				archive_entry_free(entry_main);
   1237 				archive_string_free(&entry_name);
   1238 				return (ARCHIVE_FATAL);
   1239 			}
   1240 		}
   1241 		if (acl_types & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) {
   1242 			ret = add_pax_acl(a, entry_original, pax,
   1243 			    ARCHIVE_ENTRY_ACL_TYPE_ACCESS |
   1244 			    ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID |
   1245 			    ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA);
   1246 			if (ret == ARCHIVE_FATAL) {
   1247 				archive_entry_free(entry_main);
   1248 				archive_string_free(&entry_name);
   1249 				return (ARCHIVE_FATAL);
   1250 			}
   1251 		}
   1252 		if (acl_types & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) {
   1253 			ret = add_pax_acl(a, entry_original, pax,
   1254 			    ARCHIVE_ENTRY_ACL_TYPE_DEFAULT |
   1255 			    ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID |
   1256 			    ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA);
   1257 			if (ret == ARCHIVE_FATAL) {
   1258 				archive_entry_free(entry_main);
   1259 				archive_string_free(&entry_name);
   1260 				return (ARCHIVE_FATAL);
   1261 			}
   1262 		}
   1263 
   1264 		/* We use GNU-tar-compatible sparse attributes. */
   1265 		if (sparse_count > 0) {
   1266 			int64_t soffset, slength;
   1267 
   1268 			add_pax_attr_int(&(pax->pax_header),
   1269 			    "GNU.sparse.major", 1);
   1270 			add_pax_attr_int(&(pax->pax_header),
   1271 			    "GNU.sparse.minor", 0);
   1272 			/*
   1273 			 * Make sure to store the original path, since
   1274 			 * truncation to ustar limit happened already.
   1275 			 */
   1276 			add_pax_attr(&(pax->pax_header),
   1277 			    "GNU.sparse.name", path);
   1278 			add_pax_attr_int(&(pax->pax_header),
   1279 			    "GNU.sparse.realsize",
   1280 			    archive_entry_size(entry_main));
   1281 
   1282 			/* Rename the file name which will be used for
   1283 			 * ustar header to a special name, which GNU
   1284 			 * PAX Format 1.0 requires */
   1285 			archive_entry_set_pathname(entry_main,
   1286 			    build_gnu_sparse_name(gnu_sparse_name,
   1287 			        entry_name.s));
   1288 
   1289 			/*
   1290 			 * - Make a sparse map, which will precede a file data.
   1291 			 * - Get the total size of available data of sparse.
   1292 			 */
   1293 			archive_string_sprintf(&(pax->sparse_map), "%d\n",
   1294 			    sparse_count);
   1295 			while (archive_entry_sparse_next(entry_main,
   1296 			    &soffset, &slength) == ARCHIVE_OK) {
   1297 				archive_string_sprintf(&(pax->sparse_map),
   1298 				    "%jd\n%jd\n",
   1299 				    (intmax_t)soffset,
   1300 				    (intmax_t)slength);
   1301 				sparse_total += slength;
   1302 				if (sparse_list_add(pax, soffset, slength)
   1303 				    != ARCHIVE_OK) {
   1304 					archive_set_error(&a->archive,
   1305 					    ENOMEM,
   1306 					    "Can't allocate memory");
   1307 					archive_entry_free(entry_main);
   1308 					archive_string_free(&entry_name);
   1309 					return (ARCHIVE_FATAL);
   1310 				}
   1311 			}
   1312 		}
   1313 
   1314 		/* Store extended attributes */
   1315 		if (archive_write_pax_header_xattrs(a, pax, entry_original)
   1316 		    == ARCHIVE_FATAL) {
   1317 			archive_entry_free(entry_main);
   1318 			archive_string_free(&entry_name);
   1319 			return (ARCHIVE_FATAL);
   1320 		}
   1321 
   1322 		/* Store extended symlink information */
   1323 		if (archive_entry_symlink_type(entry_main) ==
   1324 		    AE_SYMLINK_TYPE_FILE) {
   1325 			add_pax_attr(&(pax->pax_header),
   1326 			    "LIBARCHIVE.symlinktype", "file");
   1327 		} else if (archive_entry_symlink_type(entry_main) ==
   1328 		    AE_SYMLINK_TYPE_DIRECTORY) {
   1329 			add_pax_attr(&(pax->pax_header),
   1330 			    "LIBARCHIVE.symlinktype", "dir");
   1331 		}
   1332 	}
   1333 
   1334 	/* Only regular files have data. */
   1335 	if (archive_entry_filetype(entry_main) != AE_IFREG)
   1336 		archive_entry_set_size(entry_main, 0);
   1337 
   1338 	/*
   1339 	 * Pax-restricted does not store data for hardlinks, in order
   1340 	 * to improve compatibility with ustar.
   1341 	 */
   1342 	if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
   1343 	    hardlink != NULL)
   1344 		archive_entry_set_size(entry_main, 0);
   1345 
   1346 	/*
   1347 	 * XXX Full pax interchange format does permit a hardlink
   1348 	 * entry to have data associated with it.  I'm not supporting
   1349 	 * that here because the client expects me to tell them whether
   1350 	 * or not this format expects data for hardlinks.  If I
   1351 	 * don't check here, then every pax archive will end up with
   1352 	 * duplicated data for hardlinks.  Someday, there may be
   1353 	 * need to select this behavior, in which case the following
   1354 	 * will need to be revisited. XXX
   1355 	 */
   1356 	if (hardlink != NULL)
   1357 		archive_entry_set_size(entry_main, 0);
   1358 
   1359 	/* Save a real file size. */
   1360 	real_size = archive_entry_size(entry_main);
   1361 	/*
   1362 	 * Overwrite a file size by the total size of sparse blocks and
   1363 	 * the size of sparse map info. That file size is the length of
   1364 	 * the data, which we will exactly store into an archive file.
   1365 	 */
   1366 	if (archive_strlen(&(pax->sparse_map))) {
   1367 		size_t mapsize = archive_strlen(&(pax->sparse_map));
   1368 		pax->sparse_map_padding = 0x1ff & (-(ssize_t)mapsize);
   1369 		archive_entry_set_size(entry_main,
   1370 		    mapsize + pax->sparse_map_padding + sparse_total);
   1371 	}
   1372 
   1373 	/* If file size is too large, add 'size' to pax extended attrs. */
   1374 	if (archive_entry_size(entry_main) >= (((int64_t)1) << 33)) {
   1375 		add_pax_attr_int(&(pax->pax_header), "size",
   1376 		    archive_entry_size(entry_main));
   1377 	}
   1378 
   1379 	/* Format 'ustar' header for main entry.
   1380 	 *
   1381 	 * The trouble with file size: If the reader can't understand
   1382 	 * the file size, they may not be able to locate the next
   1383 	 * entry and the rest of the archive is toast.  Pax-compliant
   1384 	 * readers are supposed to ignore the file size in the main
   1385 	 * header, so the question becomes how to maximize portability
   1386 	 * for readers that don't support pax attribute extensions.
   1387 	 * For maximum compatibility, I permit numeric extensions in
   1388 	 * the main header so that the file size stored will always be
   1389 	 * correct, even if it's in a format that only some
   1390 	 * implementations understand.  The technique used here is:
   1391 	 *
   1392 	 *  a) If possible, follow the standard exactly.  This handles
   1393 	 *  files up to 8 gigabytes minus 1.
   1394 	 *
   1395 	 *  b) If that fails, try octal but omit the field terminator.
   1396 	 *  That handles files up to 64 gigabytes minus 1.
   1397 	 *
   1398 	 *  c) Otherwise, use base-256 extensions.  That handles files
   1399 	 *  up to 2^63 in this implementation, with the potential to
   1400 	 *  go up to 2^94.  That should hold us for a while. ;-)
   1401 	 *
   1402 	 * The non-strict formatter uses similar logic for other
   1403 	 * numeric fields, though they're less critical.
   1404 	 */
   1405 	if (__archive_write_format_header_ustar(a, ustarbuff, entry_main, -1, 0,
   1406 	    NULL) == ARCHIVE_FATAL) {
   1407 		archive_entry_free(entry_main);
   1408 		archive_string_free(&entry_name);
   1409 		return (ARCHIVE_FATAL);
   1410 	}
   1411 
   1412 	/* If we built any extended attributes, write that entry first. */
   1413 	if (archive_strlen(&(pax->pax_header)) > 0) {
   1414 		struct archive_entry *pax_attr_entry;
   1415 		time_t s;
   1416 		int64_t uid, gid;
   1417 		__LA_MODE_T mode;
   1418 
   1419 		pax_attr_entry = archive_entry_new2(&a->archive);
   1420 		p = entry_name.s;
   1421 		archive_entry_set_pathname(pax_attr_entry,
   1422 		    build_pax_attribute_name(pax_entry_name, p));
   1423 		archive_entry_set_size(pax_attr_entry,
   1424 		    archive_strlen(&(pax->pax_header)));
   1425 		/* Copy uid/gid (but clip to ustar limits). */
   1426 		uid = archive_entry_uid(entry_main);
   1427 		if (uid >= 1 << 18)
   1428 			uid = (1 << 18) - 1;
   1429 		archive_entry_set_uid(pax_attr_entry, uid);
   1430 		gid = archive_entry_gid(entry_main);
   1431 		if (gid >= 1 << 18)
   1432 			gid = (1 << 18) - 1;
   1433 		archive_entry_set_gid(pax_attr_entry, gid);
   1434 		/* Copy mode over (but not setuid/setgid bits) */
   1435 		mode = archive_entry_mode(entry_main);
   1436 #ifdef S_ISUID
   1437 		mode &= ~S_ISUID;
   1438 #endif
   1439 #ifdef S_ISGID
   1440 		mode &= ~S_ISGID;
   1441 #endif
   1442 #ifdef S_ISVTX
   1443 		mode &= ~S_ISVTX;
   1444 #endif
   1445 		archive_entry_set_mode(pax_attr_entry, mode);
   1446 
   1447 		/* Copy uname/gname. */
   1448 		archive_entry_set_uname(pax_attr_entry,
   1449 		    archive_entry_uname(entry_main));
   1450 		archive_entry_set_gname(pax_attr_entry,
   1451 		    archive_entry_gname(entry_main));
   1452 
   1453 		/* Copy mtime, but clip to ustar limits. */
   1454 		s = archive_entry_mtime(entry_main);
   1455 		if (s < 0) { s = 0; }
   1456 		if (s > ustar_max_mtime) { s = ustar_max_mtime; }
   1457 		archive_entry_set_mtime(pax_attr_entry, s, 0);
   1458 
   1459 		/* Standard ustar doesn't support atime. */
   1460 		archive_entry_set_atime(pax_attr_entry, 0, 0);
   1461 
   1462 		/* Standard ustar doesn't support ctime. */
   1463 		archive_entry_set_ctime(pax_attr_entry, 0, 0);
   1464 
   1465 		r = __archive_write_format_header_ustar(a, paxbuff,
   1466 		    pax_attr_entry, 'x', 1, NULL);
   1467 
   1468 		archive_entry_free(pax_attr_entry);
   1469 
   1470 		/* Note that the 'x' header shouldn't ever fail to format */
   1471 		if (r < ARCHIVE_WARN) {
   1472 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
   1473 			    "archive_write_pax_header: "
   1474 			    "'x' header failed?!  This can't happen");
   1475 			archive_entry_free(entry_main);
   1476 			archive_string_free(&entry_name);
   1477 			return (ARCHIVE_FATAL);
   1478 		} else if (r < ret)
   1479 			ret = r;
   1480 		r = __archive_write_output(a, paxbuff, 512);
   1481 		if (r != ARCHIVE_OK) {
   1482 			sparse_list_clear(pax);
   1483 			pax->entry_bytes_remaining = 0;
   1484 			pax->entry_padding = 0;
   1485 			archive_entry_free(entry_main);
   1486 			archive_string_free(&entry_name);
   1487 			return (ARCHIVE_FATAL);
   1488 		}
   1489 
   1490 		pax->entry_bytes_remaining = archive_strlen(&(pax->pax_header));
   1491 		pax->entry_padding =
   1492 		    0x1ff & (-(int64_t)pax->entry_bytes_remaining);
   1493 
   1494 		r = __archive_write_output(a, pax->pax_header.s,
   1495 		    archive_strlen(&(pax->pax_header)));
   1496 		if (r != ARCHIVE_OK) {
   1497 			/* If a write fails, we're pretty much toast. */
   1498 			archive_entry_free(entry_main);
   1499 			archive_string_free(&entry_name);
   1500 			return (ARCHIVE_FATAL);
   1501 		}
   1502 		/* Pad out the end of the entry. */
   1503 		r = __archive_write_nulls(a, (size_t)pax->entry_padding);
   1504 		if (r != ARCHIVE_OK) {
   1505 			/* If a write fails, we're pretty much toast. */
   1506 			archive_entry_free(entry_main);
   1507 			archive_string_free(&entry_name);
   1508 			return (ARCHIVE_FATAL);
   1509 		}
   1510 		pax->entry_bytes_remaining = pax->entry_padding = 0;
   1511 	}
   1512 
   1513 	/* Write the header for main entry. */
   1514 	r = __archive_write_output(a, ustarbuff, 512);
   1515 	if (r != ARCHIVE_OK) {
   1516 		archive_entry_free(entry_main);
   1517 		archive_string_free(&entry_name);
   1518 		return (r);
   1519 	}
   1520 
   1521 	/*
   1522 	 * Inform the client of the on-disk size we're using, so
   1523 	 * they can avoid unnecessarily writing a body for something
   1524 	 * that we're just going to ignore.
   1525 	 */
   1526 	archive_entry_set_size(entry_original, real_size);
   1527 	if (pax->sparse_list == NULL && real_size > 0) {
   1528 		/* This is not a sparse file but we handle its data as
   1529 		 * a sparse block. */
   1530 		sparse_list_add(pax, 0, real_size);
   1531 		sparse_total = real_size;
   1532 	}
   1533 	pax->entry_padding = 0x1ff & (-(int64_t)sparse_total);
   1534 	archive_entry_free(entry_main);
   1535 	archive_string_free(&entry_name);
   1536 
   1537 	return (ret);
   1538 }
   1539 
   1540 /*
   1541  * We need a valid name for the regular 'ustar' entry.  This routine
   1542  * tries to hack something more-or-less reasonable.
   1543  *
   1544  * The approach here tries to preserve leading dir names.  We do so by
   1545  * working with four sections:
   1546  *   1) "prefix" directory names,
   1547  *   2) "suffix" directory names,
   1548  *   3) inserted dir name (optional),
   1549  *   4) filename.
   1550  *
   1551  * These sections must satisfy the following requirements:
   1552  *   * Parts 1 & 2 together form an initial portion of the dir name.
   1553  *   * Part 3 is specified by the caller.  (It should not contain a leading
   1554  *     or trailing '/'.)
   1555  *   * Part 4 forms an initial portion of the base filename.
   1556  *   * The filename must be <= 99 chars to fit the ustar 'name' field.
   1557  *   * Parts 2, 3, 4 together must be <= 99 chars to fit the ustar 'name' fld.
   1558  *   * Part 1 must be <= 155 chars to fit the ustar 'prefix' field.
   1559  *   * If the original name ends in a '/', the new name must also end in a '/'
   1560  *   * Trailing '/.' sequences may be stripped.
   1561  *
   1562  * Note: Recall that the ustar format does not store the '/' separating
   1563  * parts 1 & 2, but does store the '/' separating parts 2 & 3.
   1564  */
   1565 static char *
   1566 build_ustar_entry_name(char *dest, const char *src, size_t src_length,
   1567     const char *insert)
   1568 {
   1569 	const char *prefix, *prefix_end;
   1570 	const char *suffix, *suffix_end;
   1571 	const char *filename, *filename_end;
   1572 	char *p;
   1573 	int need_slash = 0; /* Was there a trailing slash? */
   1574 	size_t suffix_length = 98; /* 99 - 1 for trailing slash */
   1575 	size_t insert_length;
   1576 
   1577 	/* Length of additional dir element to be added. */
   1578 	if (insert == NULL)
   1579 		insert_length = 0;
   1580 	else
   1581 		/* +2 here allows for '/' before and after the insert. */
   1582 		insert_length = strlen(insert) + 2;
   1583 
   1584 	/* Step 0: Quick bailout in a common case. */
   1585 	if (src_length < 100 && insert == NULL) {
   1586 		strncpy(dest, src, src_length);
   1587 		dest[src_length] = '\0';
   1588 		return (dest);
   1589 	}
   1590 
   1591 	/* Step 1: Locate filename and enforce the length restriction. */
   1592 	filename_end = src + src_length;
   1593 	/* Remove trailing '/' chars and '/.' pairs. */
   1594 	for (;;) {
   1595 		if (filename_end > src && filename_end[-1] == '/') {
   1596 			filename_end --;
   1597 			need_slash = 1; /* Remember to restore trailing '/'. */
   1598 			continue;
   1599 		}
   1600 		if (filename_end > src + 1 && filename_end[-1] == '.'
   1601 		    && filename_end[-2] == '/') {
   1602 			filename_end -= 2;
   1603 			need_slash = 1; /* "foo/." will become "foo/" */
   1604 			continue;
   1605 		}
   1606 		break;
   1607 	}
   1608 	if (need_slash)
   1609 		suffix_length--;
   1610 	/* Find start of filename. */
   1611 	filename = filename_end - 1;
   1612 	while ((filename > src) && (*filename != '/'))
   1613 		filename --;
   1614 	if ((*filename == '/') && (filename < filename_end - 1))
   1615 		filename ++;
   1616 	/* Adjust filename_end so that filename + insert fits in 99 chars. */
   1617 	suffix_length -= insert_length;
   1618 	if (filename_end > filename + suffix_length)
   1619 		filename_end = filename + suffix_length;
   1620 	/* Calculate max size for "suffix" section (#3 above). */
   1621 	suffix_length -= filename_end - filename;
   1622 
   1623 	/* Step 2: Locate the "prefix" section of the dirname, including
   1624 	 * trailing '/'. */
   1625 	prefix = src;
   1626 	prefix_end = prefix + 154 /* 155 - 1 for trailing / */;
   1627 	if (prefix_end > filename)
   1628 		prefix_end = filename;
   1629 	while (prefix_end > prefix && *prefix_end != '/')
   1630 		prefix_end--;
   1631 	if ((prefix_end < filename) && (*prefix_end == '/'))
   1632 		prefix_end++;
   1633 
   1634 	/* Step 3: Locate the "suffix" section of the dirname,
   1635 	 * including trailing '/'. */
   1636 	suffix = prefix_end;
   1637 	suffix_end = suffix + suffix_length; /* Enforce limit. */
   1638 	if (suffix_end > filename)
   1639 		suffix_end = filename;
   1640 	if (suffix_end < suffix)
   1641 		suffix_end = suffix;
   1642 	while (suffix_end > suffix && *suffix_end != '/')
   1643 		suffix_end--;
   1644 	if ((suffix_end < filename) && (*suffix_end == '/'))
   1645 		suffix_end++;
   1646 
   1647 	/* Step 4: Build the new name. */
   1648 	/* The OpenBSD strlcpy function is safer, but less portable. */
   1649 	/* Rather than maintain two versions, just use the strncpy version. */
   1650 	p = dest;
   1651 	if (prefix_end > prefix) {
   1652 		strncpy(p, prefix, prefix_end - prefix);
   1653 		p += prefix_end - prefix;
   1654 	}
   1655 	if (suffix_end > suffix) {
   1656 		strncpy(p, suffix, suffix_end - suffix);
   1657 		p += suffix_end - suffix;
   1658 	}
   1659 	if (insert != NULL) {
   1660 		/* Note: assume insert does not have leading or trailing '/' */
   1661 		strcpy(p, insert);
   1662 		p += strlen(insert);
   1663 		*p++ = '/';
   1664 	}
   1665 	strncpy(p, filename, filename_end - filename);
   1666 	p += filename_end - filename;
   1667 	if (need_slash)
   1668 		*p++ = '/';
   1669 	*p = '\0';
   1670 
   1671 	return (dest);
   1672 }
   1673 
   1674 /*
   1675  * The ustar header for the pax extended attributes must have a
   1676  * reasonable name:  SUSv3 requires 'dirname'/PaxHeader.'pid'/'filename'
   1677  * where 'pid' is the PID of the archiving process.  Unfortunately,
   1678  * that makes testing a pain since the output varies for each run,
   1679  * so I'm sticking with the simpler 'dirname'/PaxHeader/'filename'
   1680  * for now.  (Someday, I'll make this settable.  Then I can use the
   1681  * SUS recommendation as default and test harnesses can override it
   1682  * to get predictable results.)
   1683  *
   1684  * Joerg Schilling has argued that this is unnecessary because, in
   1685  * practice, if the pax extended attributes get extracted as regular
   1686  * files, no one is going to bother reading those attributes to
   1687  * manually restore them.  Based on this, 'star' uses
   1688  * /tmp/PaxHeader/'basename' as the ustar header name.  This is a
   1689  * tempting argument, in part because it's simpler than the SUSv3
   1690  * recommendation, but I'm not entirely convinced.  I'm also
   1691  * uncomfortable with the fact that "/tmp" is a Unix-ism.
   1692  *
   1693  * The following routine leverages build_ustar_entry_name() above and
   1694  * so is simpler than you might think.  It just needs to provide the
   1695  * additional path element and handle a few pathological cases).
   1696  */
   1697 static char *
   1698 build_pax_attribute_name(char *dest, const char *src)
   1699 {
   1700 	char buff[64];
   1701 	const char *p;
   1702 
   1703 	/* Handle the null filename case. */
   1704 	if (src == NULL || *src == '\0') {
   1705 		strcpy(dest, "PaxHeader/blank");
   1706 		return (dest);
   1707 	}
   1708 
   1709 	/* Prune final '/' and other unwanted final elements. */
   1710 	p = src + strlen(src);
   1711 	for (;;) {
   1712 		/* Ends in "/", remove the '/' */
   1713 		if (p > src && p[-1] == '/') {
   1714 			--p;
   1715 			continue;
   1716 		}
   1717 		/* Ends in "/.", remove the '.' */
   1718 		if (p > src + 1 && p[-1] == '.'
   1719 		    && p[-2] == '/') {
   1720 			--p;
   1721 			continue;
   1722 		}
   1723 		break;
   1724 	}
   1725 
   1726 	/* Pathological case: After above, there was nothing left.
   1727 	 * This includes "/." "/./." "/.//./." etc. */
   1728 	if (p == src) {
   1729 		strcpy(dest, "/PaxHeader/rootdir");
   1730 		return (dest);
   1731 	}
   1732 
   1733 	/* Convert unadorned "." into a suitable filename. */
   1734 	if (*src == '.' && p == src + 1) {
   1735 		strcpy(dest, "PaxHeader/currentdir");
   1736 		return (dest);
   1737 	}
   1738 
   1739 	/*
   1740 	 * TODO: Push this string into the 'pax' structure to avoid
   1741 	 * recomputing it every time.  That will also open the door
   1742 	 * to having clients override it.
   1743 	 */
   1744 #if HAVE_GETPID && 0  /* Disable this for now; see above comment. */
   1745 	snprintf(buff, sizeof(buff), "PaxHeader.%d", getpid());
   1746 #else
   1747 	/* If the platform can't fetch the pid, don't include it. */
   1748 	strcpy(buff, "PaxHeader");
   1749 #endif
   1750 	/* General case: build a ustar-compatible name adding
   1751 	 * "/PaxHeader/". */
   1752 	build_ustar_entry_name(dest, src, p - src, buff);
   1753 
   1754 	return (dest);
   1755 }
   1756 
   1757 /*
   1758  * GNU PAX Format 1.0 requires the special name, which pattern is:
   1759  * <dir>/GNUSparseFile.<pid>/<original file name>
   1760  *
   1761  * Since reproducible archives are more important, use 0 as pid.
   1762  *
   1763  * This function is used for only Sparse file, a file type of which
   1764  * is regular file.
   1765  */
   1766 static char *
   1767 build_gnu_sparse_name(char *dest, const char *src)
   1768 {
   1769 	const char *p;
   1770 
   1771 	/* Handle the null filename case. */
   1772 	if (src == NULL || *src == '\0') {
   1773 		strcpy(dest, "GNUSparseFile/blank");
   1774 		return (dest);
   1775 	}
   1776 
   1777 	/* Prune final '/' and other unwanted final elements. */
   1778 	p = src + strlen(src);
   1779 	for (;;) {
   1780 		/* Ends in "/", remove the '/' */
   1781 		if (p > src && p[-1] == '/') {
   1782 			--p;
   1783 			continue;
   1784 		}
   1785 		/* Ends in "/.", remove the '.' */
   1786 		if (p > src + 1 && p[-1] == '.'
   1787 		    && p[-2] == '/') {
   1788 			--p;
   1789 			continue;
   1790 		}
   1791 		break;
   1792 	}
   1793 
   1794 	/* General case: build a ustar-compatible name adding
   1795 	 * "/GNUSparseFile/". */
   1796 	build_ustar_entry_name(dest, src, p - src, "GNUSparseFile.0");
   1797 
   1798 	return (dest);
   1799 }
   1800 
   1801 /* Write two null blocks for the end of archive */
   1802 static int
   1803 archive_write_pax_close(struct archive_write *a)
   1804 {
   1805 	return (__archive_write_nulls(a, 512 * 2));
   1806 }
   1807 
   1808 static int
   1809 archive_write_pax_free(struct archive_write *a)
   1810 {
   1811 	struct pax *pax;
   1812 
   1813 	pax = (struct pax *)a->format_data;
   1814 	if (pax == NULL)
   1815 		return (ARCHIVE_OK);
   1816 
   1817 	archive_string_free(&pax->pax_header);
   1818 	archive_string_free(&pax->sparse_map);
   1819 	archive_string_free(&pax->l_url_encoded_name);
   1820 	sparse_list_clear(pax);
   1821 	free(pax);
   1822 	a->format_data = NULL;
   1823 	return (ARCHIVE_OK);
   1824 }
   1825 
   1826 static int
   1827 archive_write_pax_finish_entry(struct archive_write *a)
   1828 {
   1829 	struct pax *pax;
   1830 	uint64_t remaining;
   1831 	int ret;
   1832 
   1833 	pax = (struct pax *)a->format_data;
   1834 	remaining = pax->entry_bytes_remaining;
   1835 	if (remaining == 0) {
   1836 		while (pax->sparse_list) {
   1837 			struct sparse_block *sb;
   1838 			if (!pax->sparse_list->is_hole)
   1839 				remaining += pax->sparse_list->remaining;
   1840 			sb = pax->sparse_list->next;
   1841 			free(pax->sparse_list);
   1842 			pax->sparse_list = sb;
   1843 		}
   1844 	}
   1845 	ret = __archive_write_nulls(a, (size_t)(remaining + pax->entry_padding));
   1846 	pax->entry_bytes_remaining = pax->entry_padding = 0;
   1847 	return (ret);
   1848 }
   1849 
   1850 static ssize_t
   1851 archive_write_pax_data(struct archive_write *a, const void *buff, size_t s)
   1852 {
   1853 	struct pax *pax;
   1854 	size_t ws;
   1855 	size_t total;
   1856 	int ret;
   1857 
   1858 	pax = (struct pax *)a->format_data;
   1859 
   1860 	/*
   1861 	 * According to GNU PAX format 1.0, write a sparse map
   1862 	 * before the body.
   1863 	 */
   1864 	if (archive_strlen(&(pax->sparse_map))) {
   1865 		ret = __archive_write_output(a, pax->sparse_map.s,
   1866 		    archive_strlen(&(pax->sparse_map)));
   1867 		if (ret != ARCHIVE_OK)
   1868 			return (ret);
   1869 		ret = __archive_write_nulls(a, pax->sparse_map_padding);
   1870 		if (ret != ARCHIVE_OK)
   1871 			return (ret);
   1872 		archive_string_empty(&(pax->sparse_map));
   1873 	}
   1874 
   1875 	total = 0;
   1876 	while (total < s) {
   1877 		const unsigned char *p;
   1878 
   1879 		while (pax->sparse_list != NULL &&
   1880 		    pax->sparse_list->remaining == 0) {
   1881 			struct sparse_block *sb = pax->sparse_list->next;
   1882 			free(pax->sparse_list);
   1883 			pax->sparse_list = sb;
   1884 		}
   1885 
   1886 		if (pax->sparse_list == NULL)
   1887 			return (total);
   1888 
   1889 		p = ((const unsigned char *)buff) + total;
   1890 		ws = s - total;
   1891 		if (ws > pax->sparse_list->remaining)
   1892 			ws = (size_t)pax->sparse_list->remaining;
   1893 
   1894 		if (pax->sparse_list->is_hole) {
   1895 			/* Current block is hole thus we do not write
   1896 			 * the body. */
   1897 			pax->sparse_list->remaining -= ws;
   1898 			total += ws;
   1899 			continue;
   1900 		}
   1901 
   1902 		ret = __archive_write_output(a, p, ws);
   1903 		pax->sparse_list->remaining -= ws;
   1904 		total += ws;
   1905 		if (ret != ARCHIVE_OK)
   1906 			return (ret);
   1907 	}
   1908 	return (total);
   1909 }
   1910 
   1911 static int
   1912 has_non_ASCII(const char *_p)
   1913 {
   1914 	const unsigned char *p = (const unsigned char *)_p;
   1915 
   1916 	if (p == NULL)
   1917 		return (1);
   1918 	while (*p != '\0' && *p < 128)
   1919 		p++;
   1920 	return (*p != '\0');
   1921 }
   1922 
   1923 /*
   1924  * Used by extended attribute support; encodes the name
   1925  * so that there will be no '=' characters in the result.
   1926  */
   1927 static char *
   1928 url_encode(const char *in)
   1929 {
   1930 	const char *s;
   1931 	char *d;
   1932 	size_t out_len = 0;
   1933 	char *out;
   1934 
   1935 	for (s = in; *s != '\0'; s++) {
   1936 		if (*s < 33 || *s > 126 || *s == '%' || *s == '=') {
   1937 			if (SIZE_MAX - out_len < 4)
   1938 				return (NULL);
   1939 			out_len += 3;
   1940 		} else {
   1941 			if (SIZE_MAX - out_len < 2)
   1942 				return (NULL);
   1943 			out_len++;
   1944 		}
   1945 	}
   1946 
   1947 	out = malloc(out_len + 1);
   1948 	if (out == NULL)
   1949 		return (NULL);
   1950 
   1951 	for (s = in, d = out; *s != '\0'; s++) {
   1952 		/* encode any non-printable ASCII character or '%' or '=' */
   1953 		if (*s < 33 || *s > 126 || *s == '%' || *s == '=') {
   1954 			/* URL encoding is '%' followed by two hex digits */
   1955 			*d++ = '%';
   1956 			*d++ = "0123456789ABCDEF"[0x0f & (*s >> 4)];
   1957 			*d++ = "0123456789ABCDEF"[0x0f & *s];
   1958 		} else {
   1959 			*d++ = *s;
   1960 		}
   1961 	}
   1962 	*d = '\0';
   1963 	return (out);
   1964 }
   1965 
   1966 /*
   1967  * Encode a sequence of bytes into a C string using base-64 encoding.
   1968  *
   1969  * Returns a null-terminated C string allocated with malloc(); caller
   1970  * is responsible for freeing the result.
   1971  */
   1972 static char *
   1973 base64_encode(const char *s, size_t len)
   1974 {
   1975 	static const char digits[64] =
   1976 	    { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
   1977 	      'P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d',
   1978 	      'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s',
   1979 	      't','u','v','w','x','y','z','0','1','2','3','4','5','6','7',
   1980 	      '8','9','+','/' };
   1981 	int v;
   1982 	char *d, *out;
   1983 
   1984 	/* 3 bytes becomes 4 chars, but round up and allow for trailing NUL */
   1985 	out = malloc((len * 4 + 2) / 3 + 1);
   1986 	if (out == NULL)
   1987 		return (NULL);
   1988 	d = out;
   1989 
   1990 	/* Convert each group of 3 bytes into 4 characters. */
   1991 	while (len >= 3) {
   1992 		v = (((int)s[0] << 16) & 0xff0000)
   1993 		    | (((int)s[1] << 8) & 0xff00)
   1994 		    | (((int)s[2]) & 0x00ff);
   1995 		s += 3;
   1996 		len -= 3;
   1997 		*d++ = digits[(v >> 18) & 0x3f];
   1998 		*d++ = digits[(v >> 12) & 0x3f];
   1999 		*d++ = digits[(v >> 6) & 0x3f];
   2000 		*d++ = digits[(v) & 0x3f];
   2001 	}
   2002 	/* Handle final group of 1 byte (2 chars) or 2 bytes (3 chars). */
   2003 	switch (len) {
   2004 	case 0: break;
   2005 	case 1:
   2006 		v = (((int)s[0] << 16) & 0xff0000);
   2007 		*d++ = digits[(v >> 18) & 0x3f];
   2008 		*d++ = digits[(v >> 12) & 0x3f];
   2009 		break;
   2010 	case 2:
   2011 		v = (((int)s[0] << 16) & 0xff0000)
   2012 		    | (((int)s[1] << 8) & 0xff00);
   2013 		*d++ = digits[(v >> 18) & 0x3f];
   2014 		*d++ = digits[(v >> 12) & 0x3f];
   2015 		*d++ = digits[(v >> 6) & 0x3f];
   2016 		break;
   2017 	}
   2018 	/* Add trailing NUL character so output is a valid C string. */
   2019 	*d = '\0';
   2020 	return (out);
   2021 }
   2022 
   2023 static void
   2024 sparse_list_clear(struct pax *pax)
   2025 {
   2026 	while (pax->sparse_list != NULL) {
   2027 		struct sparse_block *sb = pax->sparse_list;
   2028 		pax->sparse_list = sb->next;
   2029 		free(sb);
   2030 	}
   2031 	pax->sparse_tail = NULL;
   2032 }
   2033 
   2034 static int
   2035 _sparse_list_add_block(struct pax *pax, int64_t offset, int64_t length,
   2036     int is_hole)
   2037 {
   2038 	struct sparse_block *sb;
   2039 
   2040 	sb = malloc(sizeof(*sb));
   2041 	if (sb == NULL)
   2042 		return (ARCHIVE_FATAL);
   2043 	sb->next = NULL;
   2044 	sb->is_hole = is_hole;
   2045 	sb->offset = offset;
   2046 	sb->remaining = length;
   2047 	if (pax->sparse_list == NULL || pax->sparse_tail == NULL)
   2048 		pax->sparse_list = pax->sparse_tail = sb;
   2049 	else {
   2050 		pax->sparse_tail->next = sb;
   2051 		pax->sparse_tail = sb;
   2052 	}
   2053 	return (ARCHIVE_OK);
   2054 }
   2055 
   2056 static int
   2057 sparse_list_add(struct pax *pax, int64_t offset, int64_t length)
   2058 {
   2059 	int64_t last_offset;
   2060 	int r;
   2061 
   2062 	if (pax->sparse_tail == NULL)
   2063 		last_offset = 0;
   2064 	else {
   2065 		last_offset = pax->sparse_tail->offset +
   2066 		    pax->sparse_tail->remaining;
   2067 	}
   2068 	if (last_offset < offset) {
   2069 		/* Add a hole block. */
   2070 		r = _sparse_list_add_block(pax, last_offset,
   2071 		    offset - last_offset, 1);
   2072 		if (r != ARCHIVE_OK)
   2073 			return (r);
   2074 	}
   2075 	/* Add data block. */
   2076 	return (_sparse_list_add_block(pax, offset, length, 0));
   2077 }
   2078 
   2079 static time_t
   2080 get_ustar_max_mtime(void)
   2081 {
   2082 	/*
   2083 	 * Technically, the mtime field in the ustar header can
   2084 	 * support 33 bits. We are using all of them to keep
   2085 	 * tar/test/test_option_C_mtree.c simple and passing after 2038.
   2086 	 * For platforms that use signed 32-bit time values we
   2087 	 * use the 32-bit maximum.
   2088 	 */
   2089 	if (sizeof(time_t) > sizeof(int32_t))
   2090 		return (time_t)0x1ffffffff;
   2091 	else
   2092 		return (time_t)0x7fffffff;
   2093 }
   2094