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