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