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