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