1228753Smm/*-
2228753Smm * Copyright (c) 2003-2007 Tim Kientzle
3232153Smm * Copyright (c) 2010-2012 Michihiro NAKAJIMA
4313571Smm * Copyright (c) 2016 Martin Matuska
5228753Smm * All rights reserved.
6228753Smm *
7228753Smm * Redistribution and use in source and binary forms, with or without
8228753Smm * modification, are permitted provided that the following conditions
9228753Smm * are met:
10228753Smm * 1. Redistributions of source code must retain the above copyright
11228753Smm *    notice, this list of conditions and the following disclaimer.
12228753Smm * 2. Redistributions in binary form must reproduce the above copyright
13228753Smm *    notice, this list of conditions and the following disclaimer in the
14228753Smm *    documentation and/or other materials provided with the distribution.
15228753Smm *
16228753Smm * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17228753Smm * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18228753Smm * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19228753Smm * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20228753Smm * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21228753Smm * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22228753Smm * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23228753Smm * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24228753Smm * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25228753Smm * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26228753Smm */
27228753Smm
28228753Smm#include "archive_platform.h"
29228763Smm__FBSDID("$FreeBSD: stable/10/contrib/libarchive/libarchive/archive_write_set_format_pax.c 358090 2020-02-19 01:51:44Z mm $");
30228753Smm
31228753Smm#ifdef HAVE_ERRNO_H
32228753Smm#include <errno.h>
33228753Smm#endif
34228753Smm#ifdef HAVE_STDLIB_H
35228753Smm#include <stdlib.h>
36228753Smm#endif
37228753Smm#ifdef HAVE_STRING_H
38228753Smm#include <string.h>
39228753Smm#endif
40228753Smm
41228753Smm#include "archive.h"
42228753Smm#include "archive_entry.h"
43232153Smm#include "archive_entry_locale.h"
44228753Smm#include "archive_private.h"
45228753Smm#include "archive_write_private.h"
46358090Smm#include "archive_write_set_format_private.h"
47228753Smm
48232153Smmstruct sparse_block {
49232153Smm	struct sparse_block	*next;
50232153Smm	int		is_hole;
51232153Smm	uint64_t	offset;
52232153Smm	uint64_t	remaining;
53232153Smm};
54232153Smm
55228753Smmstruct pax {
56228753Smm	uint64_t	entry_bytes_remaining;
57228753Smm	uint64_t	entry_padding;
58232153Smm	struct archive_string	l_url_encoded_name;
59228753Smm	struct archive_string	pax_header;
60232153Smm	struct archive_string	sparse_map;
61232153Smm	size_t			sparse_map_padding;
62232153Smm	struct sparse_block	*sparse_list;
63232153Smm	struct sparse_block	*sparse_tail;
64232153Smm	struct archive_string_conv *sconv_utf8;
65232153Smm	int			 opt_binary;
66313571Smm
67313571Smm	unsigned flags;
68313571Smm#define WRITE_SCHILY_XATTR       (1 << 0)
69313571Smm#define WRITE_LIBARCHIVE_XATTR   (1 << 1)
70228753Smm};
71228753Smm
72228753Smmstatic void		 add_pax_attr(struct archive_string *, const char *key,
73228753Smm			     const char *value);
74313571Smmstatic void		 add_pax_attr_binary(struct archive_string *,
75313571Smm			     const char *key,
76313571Smm			     const char *value, size_t value_len);
77228753Smmstatic void		 add_pax_attr_int(struct archive_string *,
78228753Smm			     const char *key, int64_t value);
79228753Smmstatic void		 add_pax_attr_time(struct archive_string *,
80228753Smm			     const char *key, int64_t sec,
81228753Smm			     unsigned long nanos);
82313571Smmstatic int		 add_pax_acl(struct archive_write *,
83313571Smm			    struct archive_entry *, struct pax *, int);
84228753Smmstatic ssize_t		 archive_write_pax_data(struct archive_write *,
85228753Smm			     const void *, size_t);
86232153Smmstatic int		 archive_write_pax_close(struct archive_write *);
87232153Smmstatic int		 archive_write_pax_free(struct archive_write *);
88228753Smmstatic int		 archive_write_pax_finish_entry(struct archive_write *);
89228753Smmstatic int		 archive_write_pax_header(struct archive_write *,
90228753Smm			     struct archive_entry *);
91232153Smmstatic int		 archive_write_pax_options(struct archive_write *,
92232153Smm			     const char *, const char *);
93228753Smmstatic char		*base64_encode(const char *src, size_t len);
94232153Smmstatic char		*build_gnu_sparse_name(char *dest, const char *src);
95228753Smmstatic char		*build_pax_attribute_name(char *dest, const char *src);
96228753Smmstatic char		*build_ustar_entry_name(char *dest, const char *src,
97228753Smm			     size_t src_length, const char *insert);
98228753Smmstatic char		*format_int(char *dest, int64_t);
99232153Smmstatic int		 has_non_ASCII(const char *);
100232153Smmstatic void		 sparse_list_clear(struct pax *);
101232153Smmstatic int		 sparse_list_add(struct pax *, int64_t, int64_t);
102228753Smmstatic char		*url_encode(const char *in);
103228753Smm
104228753Smm/*
105228753Smm * Set output format to 'restricted pax' format.
106228753Smm *
107228753Smm * This is the same as normal 'pax', but tries to suppress
108228753Smm * the pax header whenever possible.  This is the default for
109228753Smm * bsdtar, for instance.
110228753Smm */
111228753Smmint
112228753Smmarchive_write_set_format_pax_restricted(struct archive *_a)
113228753Smm{
114228753Smm	struct archive_write *a = (struct archive_write *)_a;
115228753Smm	int r;
116232153Smm
117232153Smm	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
118232153Smm	    ARCHIVE_STATE_NEW, "archive_write_set_format_pax_restricted");
119232153Smm
120228753Smm	r = archive_write_set_format_pax(&a->archive);
121228753Smm	a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
122228753Smm	a->archive.archive_format_name = "restricted POSIX pax interchange";
123228753Smm	return (r);
124228753Smm}
125228753Smm
126228753Smm/*
127228753Smm * Set output format to 'pax' format.
128228753Smm */
129228753Smmint
130228753Smmarchive_write_set_format_pax(struct archive *_a)
131228753Smm{
132228753Smm	struct archive_write *a = (struct archive_write *)_a;
133228753Smm	struct pax *pax;
134228753Smm
135232153Smm	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
136232153Smm	    ARCHIVE_STATE_NEW, "archive_write_set_format_pax");
137228753Smm
138232153Smm	if (a->format_free != NULL)
139232153Smm		(a->format_free)(a);
140232153Smm
141311042Smm	pax = (struct pax *)calloc(1, sizeof(*pax));
142228753Smm	if (pax == NULL) {
143232153Smm		archive_set_error(&a->archive, ENOMEM,
144232153Smm		    "Can't allocate pax data");
145228753Smm		return (ARCHIVE_FATAL);
146228753Smm	}
147313571Smm	pax->flags = WRITE_LIBARCHIVE_XATTR | WRITE_SCHILY_XATTR;
148313571Smm
149228753Smm	a->format_data = pax;
150228753Smm	a->format_name = "pax";
151232153Smm	a->format_options = archive_write_pax_options;
152228753Smm	a->format_write_header = archive_write_pax_header;
153228753Smm	a->format_write_data = archive_write_pax_data;
154232153Smm	a->format_close = archive_write_pax_close;
155232153Smm	a->format_free = archive_write_pax_free;
156228753Smm	a->format_finish_entry = archive_write_pax_finish_entry;
157228753Smm	a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
158228753Smm	a->archive.archive_format_name = "POSIX pax interchange";
159228753Smm	return (ARCHIVE_OK);
160228753Smm}
161228753Smm
162232153Smmstatic int
163232153Smmarchive_write_pax_options(struct archive_write *a, const char *key,
164232153Smm    const char *val)
165232153Smm{
166232153Smm	struct pax *pax = (struct pax *)a->format_data;
167232153Smm	int ret = ARCHIVE_FAILED;
168232153Smm
169232153Smm	if (strcmp(key, "hdrcharset")  == 0) {
170232153Smm		/*
171232153Smm		 * The character-set we can use are defined in
172232153Smm		 * IEEE Std 1003.1-2001
173232153Smm		 */
174232153Smm		if (val == NULL || val[0] == 0)
175232153Smm			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
176232153Smm			    "pax: hdrcharset option needs a character-set name");
177232153Smm		else if (strcmp(val, "BINARY") == 0 ||
178232153Smm		    strcmp(val, "binary") == 0) {
179232153Smm			/*
180232153Smm			 * Specify binary mode. We will not convert
181232153Smm			 * filenames, uname and gname to any charsets.
182232153Smm			 */
183232153Smm			pax->opt_binary = 1;
184232153Smm			ret = ARCHIVE_OK;
185232153Smm		} else if (strcmp(val, "UTF-8") == 0) {
186232153Smm			/*
187232153Smm			 * Specify UTF-8 character-set to be used for
188232153Smm			 * filenames. This is almost the test that
189232153Smm			 * running platform supports the string conversion.
190232153Smm			 * Especially libarchive_test needs this trick for
191232153Smm			 * its test.
192232153Smm			 */
193232153Smm			pax->sconv_utf8 = archive_string_conversion_to_charset(
194232153Smm			    &(a->archive), "UTF-8", 0);
195232153Smm			if (pax->sconv_utf8 == NULL)
196232153Smm				ret = ARCHIVE_FATAL;
197232153Smm			else
198232153Smm				ret = ARCHIVE_OK;
199232153Smm		} else
200232153Smm			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
201232153Smm			    "pax: invalid charset name");
202232153Smm		return (ret);
203358090Smm	} else if (strcmp(key, "xattrheader") == 0) {
204358090Smm		if (val == NULL || val[0] == 0) {
205358090Smm			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
206358090Smm			    "pax: xattrheader requires a value");
207358090Smm		} else if (strcmp(val, "ALL") == 0 ||
208358090Smm		    strcmp(val, "all") == 0) {
209358090Smm			pax->flags |= WRITE_LIBARCHIVE_XATTR | WRITE_SCHILY_XATTR;
210358090Smm			ret = ARCHIVE_OK;
211358090Smm		} else if (strcmp(val, "SCHILY") == 0 ||
212358090Smm		    strcmp(val, "schily") == 0) {
213358090Smm			pax->flags |= WRITE_SCHILY_XATTR;
214358090Smm			pax->flags &= ~WRITE_LIBARCHIVE_XATTR;
215358090Smm			ret = ARCHIVE_OK;
216358090Smm		} else if (strcmp(val, "LIBARCHIVE") == 0 ||
217358090Smm		    strcmp(val, "libarchive") == 0) {
218358090Smm			pax->flags |= WRITE_LIBARCHIVE_XATTR;
219358090Smm			pax->flags &= ~WRITE_SCHILY_XATTR;
220358090Smm			ret = ARCHIVE_OK;
221358090Smm		} else
222358090Smm			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
223358090Smm			    "pax: invalid xattr header name");
224358090Smm		return (ret);
225232153Smm	}
226232153Smm
227232153Smm	/* Note: The "warn" return is just to inform the options
228232153Smm	 * supervisor that we didn't handle it.  It will generate
229232153Smm	 * a suitable error if no one used this option. */
230232153Smm	return (ARCHIVE_WARN);
231232153Smm}
232232153Smm
233228753Smm/*
234228753Smm * Note: This code assumes that 'nanos' has the same sign as 'sec',
235228753Smm * which implies that sec=-1, nanos=200000000 represents -1.2 seconds
236228753Smm * and not -0.8 seconds.  This is a pretty pedantic point, as we're
237228753Smm * unlikely to encounter many real files created before Jan 1, 1970,
238228753Smm * much less ones with timestamps recorded to sub-second resolution.
239228753Smm */
240228753Smmstatic void
241228753Smmadd_pax_attr_time(struct archive_string *as, const char *key,
242228753Smm    int64_t sec, unsigned long nanos)
243228753Smm{
244228753Smm	int digit, i;
245228753Smm	char *t;
246228753Smm	/*
247228753Smm	 * Note that each byte contributes fewer than 3 base-10
248228753Smm	 * digits, so this will always be big enough.
249228753Smm	 */
250228753Smm	char tmp[1 + 3*sizeof(sec) + 1 + 3*sizeof(nanos)];
251228753Smm
252228753Smm	tmp[sizeof(tmp) - 1] = 0;
253228753Smm	t = tmp + sizeof(tmp) - 1;
254228753Smm
255228753Smm	/* Skip trailing zeros in the fractional part. */
256228753Smm	for (digit = 0, i = 10; i > 0 && digit == 0; i--) {
257228753Smm		digit = nanos % 10;
258228753Smm		nanos /= 10;
259228753Smm	}
260228753Smm
261228753Smm	/* Only format the fraction if it's non-zero. */
262228753Smm	if (i > 0) {
263228753Smm		while (i > 0) {
264228753Smm			*--t = "0123456789"[digit];
265228753Smm			digit = nanos % 10;
266228753Smm			nanos /= 10;
267228753Smm			i--;
268228753Smm		}
269228753Smm		*--t = '.';
270228753Smm	}
271228753Smm	t = format_int(t, sec);
272228753Smm
273228753Smm	add_pax_attr(as, key, t);
274228753Smm}
275228753Smm
276228753Smmstatic char *
277228753Smmformat_int(char *t, int64_t i)
278228753Smm{
279232153Smm	uint64_t ui;
280228753Smm
281232153Smm	if (i < 0)
282232153Smm		ui = (i == INT64_MIN) ? (uint64_t)(INT64_MAX) + 1 : (uint64_t)(-i);
283232153Smm	else
284232153Smm		ui = i;
285228753Smm
286228753Smm	do {
287232153Smm		*--t = "0123456789"[ui % 10];
288232153Smm	} while (ui /= 10);
289232153Smm	if (i < 0)
290228753Smm		*--t = '-';
291228753Smm	return (t);
292228753Smm}
293228753Smm
294228753Smmstatic void
295228753Smmadd_pax_attr_int(struct archive_string *as, const char *key, int64_t value)
296228753Smm{
297228753Smm	char tmp[1 + 3 * sizeof(value)];
298228753Smm
299228753Smm	tmp[sizeof(tmp) - 1] = 0;
300228753Smm	add_pax_attr(as, key, format_int(tmp + sizeof(tmp) - 1, value));
301228753Smm}
302228753Smm
303228753Smm/*
304228753Smm * Add a key/value attribute to the pax header.  This function handles
305228753Smm * the length field and various other syntactic requirements.
306228753Smm */
307228753Smmstatic void
308228753Smmadd_pax_attr(struct archive_string *as, const char *key, const char *value)
309228753Smm{
310313571Smm	add_pax_attr_binary(as, key, value, strlen(value));
311313571Smm}
312313571Smm
313313571Smm/*
314313571Smm * Add a key/value attribute to the pax header.  This function handles
315313571Smm * binary values.
316313571Smm */
317313571Smmstatic void
318313571Smmadd_pax_attr_binary(struct archive_string *as, const char *key,
319313571Smm		    const char *value, size_t value_len)
320313571Smm{
321228753Smm	int digits, i, len, next_ten;
322228753Smm	char tmp[1 + 3 * sizeof(int)];	/* < 3 base-10 digits per byte */
323228753Smm
324228753Smm	/*-
325228753Smm	 * PAX attributes have the following layout:
326228753Smm	 *     <len> <space> <key> <=> <value> <nl>
327228753Smm	 */
328313571Smm	len = 1 + (int)strlen(key) + 1 + (int)value_len + 1;
329228753Smm
330228753Smm	/*
331228753Smm	 * The <len> field includes the length of the <len> field, so
332228753Smm	 * computing the correct length is tricky.  I start by
333228753Smm	 * counting the number of base-10 digits in 'len' and
334228753Smm	 * computing the next higher power of 10.
335228753Smm	 */
336228753Smm	next_ten = 1;
337228753Smm	digits = 0;
338228753Smm	i = len;
339228753Smm	while (i > 0) {
340228753Smm		i = i / 10;
341228753Smm		digits++;
342228753Smm		next_ten = next_ten * 10;
343228753Smm	}
344228753Smm	/*
345228753Smm	 * For example, if string without the length field is 99
346228753Smm	 * chars, then adding the 2 digit length "99" will force the
347228753Smm	 * total length past 100, requiring an extra digit.  The next
348228753Smm	 * statement adjusts for this effect.
349228753Smm	 */
350228753Smm	if (len + digits >= next_ten)
351228753Smm		digits++;
352228753Smm
353228753Smm	/* Now, we have the right length so we can build the line. */
354228753Smm	tmp[sizeof(tmp) - 1] = 0;	/* Null-terminate the work area. */
355228753Smm	archive_strcat(as, format_int(tmp + sizeof(tmp) - 1, len + digits));
356228753Smm	archive_strappend_char(as, ' ');
357228753Smm	archive_strcat(as, key);
358228753Smm	archive_strappend_char(as, '=');
359313571Smm	archive_array_append(as, value, value_len);
360228753Smm	archive_strappend_char(as, '\n');
361228753Smm}
362228753Smm
363313571Smmstatic void
364313571Smmarchive_write_pax_header_xattr(struct pax *pax, const char *encoded_name,
365313571Smm    const void *value, size_t value_len)
366313571Smm{
367313571Smm	struct archive_string s;
368313571Smm	char *encoded_value;
369313571Smm
370313571Smm	if (pax->flags & WRITE_LIBARCHIVE_XATTR) {
371313571Smm		encoded_value = base64_encode((const char *)value, value_len);
372313571Smm
373313571Smm		if (encoded_name != NULL && encoded_value != NULL) {
374313571Smm			archive_string_init(&s);
375313571Smm			archive_strcpy(&s, "LIBARCHIVE.xattr.");
376313571Smm			archive_strcat(&s, encoded_name);
377313571Smm			add_pax_attr(&(pax->pax_header), s.s, encoded_value);
378313571Smm			archive_string_free(&s);
379313571Smm		}
380313571Smm		free(encoded_value);
381313571Smm	}
382313571Smm	if (pax->flags & WRITE_SCHILY_XATTR) {
383313571Smm		archive_string_init(&s);
384313571Smm		archive_strcpy(&s, "SCHILY.xattr.");
385313571Smm		archive_strcat(&s, encoded_name);
386313571Smm		add_pax_attr_binary(&(pax->pax_header), s.s, value, value_len);
387313571Smm		archive_string_free(&s);
388313571Smm	}
389313571Smm}
390313571Smm
391232153Smmstatic int
392232153Smmarchive_write_pax_header_xattrs(struct archive_write *a,
393232153Smm    struct pax *pax, struct archive_entry *entry)
394228753Smm{
395228753Smm	int i = archive_entry_xattr_reset(entry);
396228753Smm
397228753Smm	while (i--) {
398228753Smm		const char *name;
399228753Smm		const void *value;
400228753Smm		char *url_encoded_name = NULL, *encoded_name = NULL;
401228753Smm		size_t size;
402232153Smm		int r;
403228753Smm
404228753Smm		archive_entry_xattr_next(entry, &name, &value, &size);
405228753Smm		url_encoded_name = url_encode(name);
406228753Smm		if (url_encoded_name != NULL) {
407232153Smm			/* Convert narrow-character to UTF-8. */
408238856Smm			r = archive_strcpy_l(&(pax->l_url_encoded_name),
409232153Smm			    url_encoded_name, pax->sconv_utf8);
410228753Smm			free(url_encoded_name); /* Done with this. */
411232153Smm			if (r == 0)
412232153Smm				encoded_name = pax->l_url_encoded_name.s;
413232153Smm			else if (errno == ENOMEM) {
414232153Smm				archive_set_error(&a->archive, ENOMEM,
415232153Smm				    "Can't allocate memory for Linkname");
416232153Smm				return (ARCHIVE_FATAL);
417232153Smm			}
418228753Smm		}
419228753Smm
420313571Smm		archive_write_pax_header_xattr(pax, encoded_name,
421313571Smm		    value, size);
422228753Smm
423228753Smm	}
424232153Smm	return (ARCHIVE_OK);
425228753Smm}
426228753Smm
427232153Smmstatic int
428232153Smmget_entry_hardlink(struct archive_write *a, struct archive_entry *entry,
429232153Smm    const char **name, size_t *length, struct archive_string_conv *sc)
430232153Smm{
431232153Smm	int r;
432232153Smm
433232153Smm	r = archive_entry_hardlink_l(entry, name, length, sc);
434232153Smm	if (r != 0) {
435232153Smm		if (errno == ENOMEM) {
436232153Smm			archive_set_error(&a->archive, ENOMEM,
437232153Smm			    "Can't allocate memory for Linkname");
438232153Smm			return (ARCHIVE_FATAL);
439232153Smm		}
440232153Smm		return (ARCHIVE_WARN);
441232153Smm	}
442232153Smm	return (ARCHIVE_OK);
443232153Smm}
444232153Smm
445232153Smmstatic int
446232153Smmget_entry_pathname(struct archive_write *a, struct archive_entry *entry,
447232153Smm    const char **name, size_t *length, struct archive_string_conv *sc)
448232153Smm{
449232153Smm	int r;
450232153Smm
451232153Smm	r = archive_entry_pathname_l(entry, name, length, sc);
452232153Smm	if (r != 0) {
453232153Smm		if (errno == ENOMEM) {
454232153Smm			archive_set_error(&a->archive, ENOMEM,
455232153Smm			    "Can't allocate memory for Pathname");
456232153Smm			return (ARCHIVE_FATAL);
457232153Smm		}
458232153Smm		return (ARCHIVE_WARN);
459232153Smm	}
460232153Smm	return (ARCHIVE_OK);
461232153Smm}
462232153Smm
463232153Smmstatic int
464232153Smmget_entry_uname(struct archive_write *a, struct archive_entry *entry,
465232153Smm    const char **name, size_t *length, struct archive_string_conv *sc)
466232153Smm{
467232153Smm	int r;
468232153Smm
469232153Smm	r = archive_entry_uname_l(entry, name, length, sc);
470232153Smm	if (r != 0) {
471232153Smm		if (errno == ENOMEM) {
472232153Smm			archive_set_error(&a->archive, ENOMEM,
473232153Smm			    "Can't allocate memory for Uname");
474232153Smm			return (ARCHIVE_FATAL);
475232153Smm		}
476232153Smm		return (ARCHIVE_WARN);
477232153Smm	}
478232153Smm	return (ARCHIVE_OK);
479232153Smm}
480232153Smm
481232153Smmstatic int
482232153Smmget_entry_gname(struct archive_write *a, struct archive_entry *entry,
483232153Smm    const char **name, size_t *length, struct archive_string_conv *sc)
484232153Smm{
485232153Smm	int r;
486232153Smm
487232153Smm	r = archive_entry_gname_l(entry, name, length, sc);
488232153Smm	if (r != 0) {
489232153Smm		if (errno == ENOMEM) {
490232153Smm			archive_set_error(&a->archive, ENOMEM,
491232153Smm			    "Can't allocate memory for Gname");
492232153Smm			return (ARCHIVE_FATAL);
493232153Smm		}
494232153Smm		return (ARCHIVE_WARN);
495232153Smm	}
496232153Smm	return (ARCHIVE_OK);
497232153Smm}
498232153Smm
499232153Smmstatic int
500232153Smmget_entry_symlink(struct archive_write *a, struct archive_entry *entry,
501232153Smm    const char **name, size_t *length, struct archive_string_conv *sc)
502232153Smm{
503232153Smm	int r;
504232153Smm
505232153Smm	r = archive_entry_symlink_l(entry, name, length, sc);
506232153Smm	if (r != 0) {
507232153Smm		if (errno == ENOMEM) {
508232153Smm			archive_set_error(&a->archive, ENOMEM,
509232153Smm			    "Can't allocate memory for Linkname");
510232153Smm			return (ARCHIVE_FATAL);
511232153Smm		}
512232153Smm		return (ARCHIVE_WARN);
513232153Smm	}
514232153Smm	return (ARCHIVE_OK);
515232153Smm}
516232153Smm
517313571Smm/* Add ACL to pax header */
518313571Smmstatic int
519313571Smmadd_pax_acl(struct archive_write *a,
520313571Smm    struct archive_entry *entry, struct pax *pax, int flags)
521313571Smm{
522313571Smm	char *p;
523313571Smm	const char *attr;
524313571Smm	int acl_types;
525313571Smm
526313571Smm	acl_types = archive_entry_acl_types(entry);
527313571Smm
528313571Smm	if ((acl_types & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0)
529313571Smm		attr = "SCHILY.acl.ace";
530313571Smm	else if ((flags & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0)
531313571Smm		attr = "SCHILY.acl.access";
532313571Smm	else if ((flags & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0)
533313571Smm		attr = "SCHILY.acl.default";
534313571Smm	else
535313571Smm		return (ARCHIVE_FATAL);
536313571Smm
537313571Smm	p = archive_entry_acl_to_text_l(entry, NULL, flags, pax->sconv_utf8);
538313571Smm	if (p == NULL) {
539313571Smm		if (errno == ENOMEM) {
540313571Smm			archive_set_error(&a->archive, ENOMEM, "%s %s",
541313571Smm			    "Can't allocate memory for ", attr);
542313571Smm			return (ARCHIVE_FATAL);
543313571Smm		}
544313571Smm		archive_set_error(&a->archive,
545313571Smm		    ARCHIVE_ERRNO_FILE_FORMAT, "%s %s %s",
546313571Smm		    "Can't translate ", attr, " to UTF-8");
547313571Smm		return(ARCHIVE_WARN);
548313571Smm	} else if (*p != '\0') {
549313571Smm		add_pax_attr(&(pax->pax_header),
550313571Smm		    attr, p);
551313571Smm		free(p);
552313571Smm	}
553313571Smm	return(ARCHIVE_OK);
554313571Smm}
555313571Smm
556228753Smm/*
557228753Smm * TODO: Consider adding 'comment' and 'charset' fields to
558228753Smm * archive_entry so that clients can specify them.  Also, consider
559228753Smm * adding generic key/value tags so clients can add arbitrary
560228753Smm * key/value data.
561232153Smm *
562232153Smm * TODO: Break up this 700-line function!!!!  Yowza!
563228753Smm */
564228753Smmstatic int
565228753Smmarchive_write_pax_header(struct archive_write *a,
566228753Smm    struct archive_entry *entry_original)
567228753Smm{
568228753Smm	struct archive_entry *entry_main;
569228753Smm	const char *p;
570228753Smm	const char *suffix;
571228753Smm	int need_extension, r, ret;
572313571Smm	int acl_types;
573232153Smm	int sparse_count;
574232153Smm	uint64_t sparse_total, real_size;
575228753Smm	struct pax *pax;
576228753Smm	const char *hardlink;
577228753Smm	const char *path = NULL, *linkpath = NULL;
578228753Smm	const char *uname = NULL, *gname = NULL;
579232153Smm	const void *mac_metadata;
580232153Smm	size_t mac_metadata_size;
581232153Smm	struct archive_string_conv *sconv;
582232153Smm	size_t hardlink_length, path_length, linkpath_length;
583232153Smm	size_t uname_length, gname_length;
584228753Smm
585228753Smm	char paxbuff[512];
586228753Smm	char ustarbuff[512];
587228753Smm	char ustar_entry_name[256];
588228753Smm	char pax_entry_name[256];
589232153Smm	char gnu_sparse_name[256];
590232153Smm	struct archive_string entry_name;
591228753Smm
592228753Smm	ret = ARCHIVE_OK;
593228753Smm	need_extension = 0;
594228753Smm	pax = (struct pax *)a->format_data;
595228753Smm
596232153Smm	/* Sanity check. */
597232153Smm	if (archive_entry_pathname(entry_original) == NULL) {
598232153Smm		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
599232153Smm			  "Can't record entry in tar file without pathname");
600232153Smm		return (ARCHIVE_FAILED);
601232153Smm	}
602228753Smm
603232153Smm	/*
604232153Smm	 * Choose a header encoding.
605232153Smm	 */
606232153Smm	if (pax->opt_binary)
607232153Smm		sconv = NULL;/* Binary mode. */
608232153Smm	else {
609232153Smm		/* Header encoding is UTF-8. */
610232153Smm		if (pax->sconv_utf8 == NULL) {
611232153Smm			/* Initialize the string conversion object
612232153Smm			 * we must need */
613232153Smm			pax->sconv_utf8 = archive_string_conversion_to_charset(
614232153Smm			    &(a->archive), "UTF-8", 1);
615232153Smm			if (pax->sconv_utf8 == NULL)
616232153Smm				/* Couldn't allocate memory */
617232153Smm				return (ARCHIVE_FAILED);
618232153Smm		}
619232153Smm		sconv = pax->sconv_utf8;
620232153Smm	}
621232153Smm
622232153Smm	r = get_entry_hardlink(a, entry_original, &hardlink,
623232153Smm	    &hardlink_length, sconv);
624232153Smm	if (r == ARCHIVE_FATAL)
625232153Smm		return (r);
626232153Smm	else if (r != ARCHIVE_OK) {
627232153Smm		r = get_entry_hardlink(a, entry_original, &hardlink,
628232153Smm		    &hardlink_length, NULL);
629232153Smm		if (r == ARCHIVE_FATAL)
630232153Smm			return (r);
631232153Smm		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
632232153Smm		    "Can't translate linkname '%s' to %s", hardlink,
633232153Smm		    archive_string_conversion_charset_name(sconv));
634232153Smm		ret = ARCHIVE_WARN;
635232153Smm		sconv = NULL;/* The header charset switches to binary mode. */
636232153Smm	}
637232153Smm
638228753Smm	/* Make sure this is a type of entry that we can handle here */
639228753Smm	if (hardlink == NULL) {
640228753Smm		switch (archive_entry_filetype(entry_original)) {
641228753Smm		case AE_IFBLK:
642228753Smm		case AE_IFCHR:
643228753Smm		case AE_IFIFO:
644228753Smm		case AE_IFLNK:
645228753Smm		case AE_IFREG:
646228753Smm			break;
647228753Smm		case AE_IFDIR:
648232153Smm		{
649228753Smm			/*
650228753Smm			 * Ensure a trailing '/'.  Modify the original
651228753Smm			 * entry so the client sees the change.
652228753Smm			 */
653232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
654232153Smm			const wchar_t *wp;
655232153Smm
656232153Smm			wp = archive_entry_pathname_w(entry_original);
657232153Smm			if (wp != NULL && wp[wcslen(wp) -1] != L'/') {
658232153Smm				struct archive_wstring ws;
659232153Smm
660232153Smm				archive_string_init(&ws);
661232153Smm				path_length = wcslen(wp);
662232153Smm				if (archive_wstring_ensure(&ws,
663232153Smm				    path_length + 2) == NULL) {
664228753Smm					archive_set_error(&a->archive, ENOMEM,
665232153Smm					    "Can't allocate pax data");
666232153Smm					archive_wstring_free(&ws);
667228753Smm					return(ARCHIVE_FATAL);
668228753Smm				}
669232153Smm				/* Should we keep '\' ? */
670232153Smm				if (wp[path_length -1] == L'\\')
671232153Smm					path_length--;
672232153Smm				archive_wstrncpy(&ws, wp, path_length);
673232153Smm				archive_wstrappend_wchar(&ws, L'/');
674232153Smm				archive_entry_copy_pathname_w(
675232153Smm				    entry_original, ws.s);
676232153Smm				archive_wstring_free(&ws);
677232153Smm				p = NULL;
678232153Smm			} else
679232153Smm#endif
680232153Smm				p = archive_entry_pathname(entry_original);
681232153Smm			/*
682232153Smm			 * On Windows, this is a backup operation just in
683232153Smm			 * case getting WCS failed. On POSIX, this is a
684232153Smm			 * normal operation.
685232153Smm			 */
686342361Smm			if (p != NULL && p[0] != '\0' && p[strlen(p) - 1] != '/') {
687232153Smm				struct archive_string as;
688232153Smm
689232153Smm				archive_string_init(&as);
690232153Smm				path_length = strlen(p);
691232153Smm				if (archive_string_ensure(&as,
692232153Smm				    path_length + 2) == NULL) {
693232153Smm					archive_set_error(&a->archive, ENOMEM,
694232153Smm					    "Can't allocate pax data");
695232153Smm					archive_string_free(&as);
696232153Smm					return(ARCHIVE_FATAL);
697232153Smm				}
698232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
699232153Smm				/* NOTE: This might break the pathname
700232153Smm				 * if the current code page is CP932 and
701232153Smm				 * the pathname includes a character '\'
702232153Smm				 * as a part of its multibyte pathname. */
703232153Smm				if (p[strlen(p) -1] == '\\')
704232153Smm					path_length--;
705232153Smm				else
706232153Smm#endif
707232153Smm				archive_strncpy(&as, p, path_length);
708232153Smm				archive_strappend_char(&as, '/');
709232153Smm				archive_entry_copy_pathname(
710232153Smm				    entry_original, as.s);
711232153Smm				archive_string_free(&as);
712228753Smm			}
713228753Smm			break;
714232153Smm		}
715358090Smm		default: /* AE_IFSOCK and unknown */
716358090Smm			__archive_write_entry_filetype_unsupported(
717358090Smm			    &a->archive, entry_original, "pax");
718232153Smm			return (ARCHIVE_FAILED);
719228753Smm		}
720228753Smm	}
721228753Smm
722232153Smm	/*
723232153Smm	 * If Mac OS metadata blob is here, recurse to write that
724232153Smm	 * as a separate entry.  This is really a pretty poor design:
725232153Smm	 * In particular, it doubles the overhead for long filenames.
726232153Smm	 * TODO: Help Apple folks design something better and figure
727232153Smm	 * out how to transition from this legacy format.
728232153Smm	 *
729232153Smm	 * Note that this code is present on every platform; clients
730232153Smm	 * on non-Mac are unlikely to ever provide this data, but
731232153Smm	 * applications that copy entries from one archive to another
732232153Smm	 * should not lose data just because the local filesystem
733232153Smm	 * can't store it.
734232153Smm	 */
735232153Smm	mac_metadata =
736232153Smm	    archive_entry_mac_metadata(entry_original, &mac_metadata_size);
737232153Smm	if (mac_metadata != NULL) {
738232153Smm		const char *oname;
739232153Smm		char *name, *bname;
740232153Smm		size_t name_length;
741232153Smm		struct archive_entry *extra = archive_entry_new2(&a->archive);
742232153Smm
743232153Smm		oname = archive_entry_pathname(entry_original);
744232153Smm		name_length = strlen(oname);
745232153Smm		name = malloc(name_length + 3);
746248616Smm		if (name == NULL || extra == NULL) {
747232153Smm			/* XXX error message */
748248616Smm			archive_entry_free(extra);
749248616Smm			free(name);
750232153Smm			return (ARCHIVE_FAILED);
751232153Smm		}
752232153Smm		strcpy(name, oname);
753232153Smm		/* Find last '/'; strip trailing '/' characters */
754232153Smm		bname = strrchr(name, '/');
755232153Smm		while (bname != NULL && bname[1] == '\0') {
756232153Smm			*bname = '\0';
757232153Smm			bname = strrchr(name, '/');
758232153Smm		}
759232153Smm		if (bname == NULL) {
760232153Smm			memmove(name + 2, name, name_length + 1);
761232153Smm			memmove(name, "._", 2);
762232153Smm		} else {
763232153Smm			bname += 1;
764232153Smm			memmove(bname + 2, bname, strlen(bname) + 1);
765232153Smm			memmove(bname, "._", 2);
766232153Smm		}
767232153Smm		archive_entry_copy_pathname(extra, name);
768232153Smm		free(name);
769232153Smm
770232153Smm		archive_entry_set_size(extra, mac_metadata_size);
771232153Smm		archive_entry_set_filetype(extra, AE_IFREG);
772232153Smm		archive_entry_set_perm(extra,
773232153Smm		    archive_entry_perm(entry_original));
774232153Smm		archive_entry_set_mtime(extra,
775232153Smm		    archive_entry_mtime(entry_original),
776232153Smm		    archive_entry_mtime_nsec(entry_original));
777232153Smm		archive_entry_set_gid(extra,
778232153Smm		    archive_entry_gid(entry_original));
779232153Smm		archive_entry_set_gname(extra,
780232153Smm		    archive_entry_gname(entry_original));
781232153Smm		archive_entry_set_uid(extra,
782232153Smm		    archive_entry_uid(entry_original));
783232153Smm		archive_entry_set_uname(extra,
784232153Smm		    archive_entry_uname(entry_original));
785232153Smm
786232153Smm		/* Recurse to write the special copyfile entry. */
787232153Smm		r = archive_write_pax_header(a, extra);
788248616Smm		archive_entry_free(extra);
789232153Smm		if (r < ARCHIVE_WARN)
790232153Smm			return (r);
791232153Smm		if (r < ret)
792232153Smm			ret = r;
793248616Smm		r = (int)archive_write_pax_data(a, mac_metadata,
794248616Smm		    mac_metadata_size);
795232153Smm		if (r < ARCHIVE_WARN)
796232153Smm			return (r);
797232153Smm		if (r < ret)
798232153Smm			ret = r;
799232153Smm		r = archive_write_pax_finish_entry(a);
800232153Smm		if (r < ARCHIVE_WARN)
801232153Smm			return (r);
802232153Smm		if (r < ret)
803232153Smm			ret = r;
804232153Smm	}
805232153Smm
806228753Smm	/* Copy entry so we can modify it as needed. */
807232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
808311042Smm	/* Make sure the path separators in pathname, hardlink and symlink
809232153Smm	 * are all slash '/', not the Windows path separator '\'. */
810232153Smm	entry_main = __la_win_entry_in_posix_pathseparator(entry_original);
811232153Smm	if (entry_main == entry_original)
812232153Smm		entry_main = archive_entry_clone(entry_original);
813232153Smm#else
814228753Smm	entry_main = archive_entry_clone(entry_original);
815232153Smm#endif
816232153Smm	if (entry_main == NULL) {
817232153Smm		archive_set_error(&a->archive, ENOMEM,
818232153Smm		    "Can't allocate pax data");
819232153Smm		return(ARCHIVE_FATAL);
820232153Smm	}
821228753Smm	archive_string_empty(&(pax->pax_header)); /* Blank our work area. */
822232153Smm	archive_string_empty(&(pax->sparse_map));
823232153Smm	sparse_total = 0;
824232153Smm	sparse_list_clear(pax);
825228753Smm
826232153Smm	if (hardlink == NULL &&
827232153Smm	    archive_entry_filetype(entry_main) == AE_IFREG)
828232153Smm		sparse_count = archive_entry_sparse_reset(entry_main);
829232153Smm	else
830232153Smm		sparse_count = 0;
831232153Smm	if (sparse_count) {
832232153Smm		int64_t offset, length, last_offset = 0;
833232153Smm		/* Get the last entry of sparse block. */
834232153Smm		while (archive_entry_sparse_next(
835232153Smm		    entry_main, &offset, &length) == ARCHIVE_OK)
836232153Smm			last_offset = offset + length;
837232153Smm
838232153Smm		/* If the last sparse block does not reach the end of file,
839232153Smm		 * We have to add a empty sparse block as the last entry to
840232153Smm		 * manage storing file data. */
841232153Smm		if (last_offset < archive_entry_size(entry_main))
842232153Smm			archive_entry_sparse_add_entry(entry_main,
843232153Smm			    archive_entry_size(entry_main), 0);
844232153Smm		sparse_count = archive_entry_sparse_reset(entry_main);
845232153Smm	}
846232153Smm
847228753Smm	/*
848228753Smm	 * First, check the name fields and see if any of them
849228753Smm	 * require binary coding.  If any of them does, then all of
850228753Smm	 * them do.
851228753Smm	 */
852232153Smm	r = get_entry_pathname(a, entry_main, &path, &path_length, sconv);
853358090Smm	if (r == ARCHIVE_FATAL) {
854358090Smm		archive_entry_free(entry_main);
855232153Smm		return (r);
856358090Smm	} else if (r != ARCHIVE_OK) {
857232153Smm		r = get_entry_pathname(a, entry_main, &path,
858232153Smm		    &path_length, NULL);
859358090Smm		if (r == ARCHIVE_FATAL) {
860358090Smm			archive_entry_free(entry_main);
861232153Smm			return (r);
862358090Smm		}
863228753Smm		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
864232153Smm		    "Can't translate pathname '%s' to %s", path,
865232153Smm		    archive_string_conversion_charset_name(sconv));
866228753Smm		ret = ARCHIVE_WARN;
867232153Smm		sconv = NULL;/* The header charset switches to binary mode. */
868228753Smm	}
869232153Smm	r = get_entry_uname(a, entry_main, &uname, &uname_length, sconv);
870358090Smm	if (r == ARCHIVE_FATAL) {
871358090Smm		archive_entry_free(entry_main);
872232153Smm		return (r);
873358090Smm	} else if (r != ARCHIVE_OK) {
874232153Smm		r = get_entry_uname(a, entry_main, &uname, &uname_length, NULL);
875358090Smm		if (r == ARCHIVE_FATAL) {
876358090Smm			archive_entry_free(entry_main);
877232153Smm			return (r);
878358090Smm		}
879228753Smm		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
880232153Smm		    "Can't translate uname '%s' to %s", uname,
881232153Smm		    archive_string_conversion_charset_name(sconv));
882228753Smm		ret = ARCHIVE_WARN;
883232153Smm		sconv = NULL;/* The header charset switches to binary mode. */
884228753Smm	}
885232153Smm	r = get_entry_gname(a, entry_main, &gname, &gname_length, sconv);
886358090Smm	if (r == ARCHIVE_FATAL) {
887358090Smm		archive_entry_free(entry_main);
888232153Smm		return (r);
889358090Smm	} else if (r != ARCHIVE_OK) {
890232153Smm		r = get_entry_gname(a, entry_main, &gname, &gname_length, NULL);
891358090Smm		if (r == ARCHIVE_FATAL) {
892358090Smm			archive_entry_free(entry_main);
893232153Smm			return (r);
894358090Smm		}
895228753Smm		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
896232153Smm		    "Can't translate gname '%s' to %s", gname,
897232153Smm		    archive_string_conversion_charset_name(sconv));
898228753Smm		ret = ARCHIVE_WARN;
899232153Smm		sconv = NULL;/* The header charset switches to binary mode. */
900228753Smm	}
901228753Smm	linkpath = hardlink;
902232153Smm	linkpath_length = hardlink_length;
903232153Smm	if (linkpath == NULL) {
904232153Smm		r = get_entry_symlink(a, entry_main, &linkpath,
905232153Smm		    &linkpath_length, sconv);
906358090Smm		if (r == ARCHIVE_FATAL) {
907358090Smm			archive_entry_free(entry_main);
908232153Smm			return (r);
909358090Smm		} else if (r != ARCHIVE_OK) {
910232153Smm			r = get_entry_symlink(a, entry_main, &linkpath,
911232153Smm			    &linkpath_length, NULL);
912358090Smm			if (r == ARCHIVE_FATAL) {
913358090Smm				archive_entry_free(entry_main);
914232153Smm				return (r);
915358090Smm			}
916232153Smm			archive_set_error(&a->archive,
917232153Smm			    ARCHIVE_ERRNO_FILE_FORMAT,
918232153Smm			    "Can't translate linkname '%s' to %s", linkpath,
919232153Smm			    archive_string_conversion_charset_name(sconv));
920232153Smm			ret = ARCHIVE_WARN;
921232153Smm			sconv = NULL;
922232153Smm		}
923228753Smm	}
924232153Smm
925232153Smm	/* If any string conversions failed, get all attributes
926232153Smm	 * in binary-mode. */
927232153Smm	if (sconv == NULL && !pax->opt_binary) {
928232153Smm		if (hardlink != NULL) {
929232153Smm			r = get_entry_hardlink(a, entry_main, &hardlink,
930232153Smm			    &hardlink_length, NULL);
931358090Smm			if (r == ARCHIVE_FATAL) {
932358090Smm				archive_entry_free(entry_main);
933232153Smm				return (r);
934358090Smm			}
935232153Smm			linkpath = hardlink;
936232153Smm			linkpath_length = hardlink_length;
937232153Smm		}
938232153Smm		r = get_entry_pathname(a, entry_main, &path,
939232153Smm		    &path_length, NULL);
940358090Smm		if (r == ARCHIVE_FATAL) {
941358090Smm			archive_entry_free(entry_main);
942232153Smm			return (r);
943358090Smm		}
944232153Smm		r = get_entry_uname(a, entry_main, &uname, &uname_length, NULL);
945358090Smm		if (r == ARCHIVE_FATAL) {
946358090Smm			archive_entry_free(entry_main);
947232153Smm			return (r);
948358090Smm		}
949232153Smm		r = get_entry_gname(a, entry_main, &gname, &gname_length, NULL);
950358090Smm		if (r == ARCHIVE_FATAL) {
951358090Smm			archive_entry_free(entry_main);
952232153Smm			return (r);
953358090Smm		}
954228753Smm	}
955228753Smm
956228753Smm	/* Store the header encoding first, to be nice to readers. */
957232153Smm	if (sconv == NULL)
958232153Smm		add_pax_attr(&(pax->pax_header), "hdrcharset", "BINARY");
959228753Smm
960228753Smm
961228753Smm	/*
962228753Smm	 * If name is too long, or has non-ASCII characters, add
963228753Smm	 * 'path' to pax extended attrs.  (Note that an unconvertible
964228753Smm	 * name must have non-ASCII characters.)
965228753Smm	 */
966232153Smm	if (has_non_ASCII(path)) {
967228753Smm		/* We have non-ASCII characters. */
968232153Smm		add_pax_attr(&(pax->pax_header), "path", path);
969228753Smm		archive_entry_set_pathname(entry_main,
970228753Smm		    build_ustar_entry_name(ustar_entry_name,
971232153Smm			path, path_length, NULL));
972228753Smm		need_extension = 1;
973228753Smm	} else {
974228753Smm		/* We have an all-ASCII path; we'd like to just store
975228753Smm		 * it in the ustar header if it will fit.  Yes, this
976228753Smm		 * duplicates some of the logic in
977232153Smm		 * archive_write_set_format_ustar.c
978228753Smm		 */
979232153Smm		if (path_length <= 100) {
980228753Smm			/* Fits in the old 100-char tar name field. */
981228753Smm		} else {
982228753Smm			/* Find largest suffix that will fit. */
983228753Smm			/* Note: strlen() > 100, so strlen() - 100 - 1 >= 0 */
984232153Smm			suffix = strchr(path + path_length - 100 - 1, '/');
985228753Smm			/* Don't attempt an empty prefix. */
986228753Smm			if (suffix == path)
987228753Smm				suffix = strchr(suffix + 1, '/');
988228753Smm			/* We can put it in the ustar header if it's
989228753Smm			 * all ASCII and it's either <= 100 characters
990228753Smm			 * or can be split at a '/' into a prefix <=
991228753Smm			 * 155 chars and a suffix <= 100 chars.  (Note
992228753Smm			 * the strchr() above will return NULL exactly
993228753Smm			 * when the path can't be split.)
994228753Smm			 */
995228753Smm			if (suffix == NULL       /* Suffix > 100 chars. */
996228753Smm			    || suffix[1] == '\0'    /* empty suffix */
997228753Smm			    || suffix - path > 155)  /* Prefix > 155 chars */
998228753Smm			{
999232153Smm				add_pax_attr(&(pax->pax_header), "path", path);
1000228753Smm				archive_entry_set_pathname(entry_main,
1001228753Smm				    build_ustar_entry_name(ustar_entry_name,
1002232153Smm					path, path_length, NULL));
1003228753Smm				need_extension = 1;
1004228753Smm			}
1005228753Smm		}
1006228753Smm	}
1007228753Smm
1008228753Smm	if (linkpath != NULL) {
1009228753Smm		/* If link name is too long or has non-ASCII characters, add
1010228753Smm		 * 'linkpath' to pax extended attrs. */
1011232153Smm		if (linkpath_length > 100 || has_non_ASCII(linkpath)) {
1012232153Smm			add_pax_attr(&(pax->pax_header), "linkpath", linkpath);
1013232153Smm			if (linkpath_length > 100) {
1014228753Smm				if (hardlink != NULL)
1015228753Smm					archive_entry_set_hardlink(entry_main,
1016228753Smm					    "././@LongHardLink");
1017228753Smm				else
1018228753Smm					archive_entry_set_symlink(entry_main,
1019228753Smm					    "././@LongSymLink");
1020228753Smm			}
1021228753Smm			need_extension = 1;
1022228753Smm		}
1023228753Smm	}
1024232153Smm	/* Save a pathname since it will be renamed if `entry_main` has
1025232153Smm	 * sparse blocks. */
1026232153Smm	archive_string_init(&entry_name);
1027232153Smm	archive_strcpy(&entry_name, archive_entry_pathname(entry_main));
1028228753Smm
1029228753Smm	/* If file size is too large, add 'size' to pax extended attrs. */
1030228753Smm	if (archive_entry_size(entry_main) >= (((int64_t)1) << 33)) {
1031228753Smm		add_pax_attr_int(&(pax->pax_header), "size",
1032228753Smm		    archive_entry_size(entry_main));
1033228753Smm		need_extension = 1;
1034228753Smm	}
1035228753Smm
1036228753Smm	/* If numeric GID is too large, add 'gid' to pax extended attrs. */
1037228753Smm	if ((unsigned int)archive_entry_gid(entry_main) >= (1 << 18)) {
1038228753Smm		add_pax_attr_int(&(pax->pax_header), "gid",
1039228753Smm		    archive_entry_gid(entry_main));
1040228753Smm		need_extension = 1;
1041228753Smm	}
1042228753Smm
1043228753Smm	/* If group name is too large or has non-ASCII characters, add
1044228753Smm	 * 'gname' to pax extended attrs. */
1045228753Smm	if (gname != NULL) {
1046232153Smm		if (gname_length > 31 || has_non_ASCII(gname)) {
1047232153Smm			add_pax_attr(&(pax->pax_header), "gname", gname);
1048228753Smm			need_extension = 1;
1049228753Smm		}
1050228753Smm	}
1051228753Smm
1052228753Smm	/* If numeric UID is too large, add 'uid' to pax extended attrs. */
1053228753Smm	if ((unsigned int)archive_entry_uid(entry_main) >= (1 << 18)) {
1054228753Smm		add_pax_attr_int(&(pax->pax_header), "uid",
1055228753Smm		    archive_entry_uid(entry_main));
1056228753Smm		need_extension = 1;
1057228753Smm	}
1058228753Smm
1059228753Smm	/* Add 'uname' to pax extended attrs if necessary. */
1060228753Smm	if (uname != NULL) {
1061232153Smm		if (uname_length > 31 || has_non_ASCII(uname)) {
1062232153Smm			add_pax_attr(&(pax->pax_header), "uname", uname);
1063228753Smm			need_extension = 1;
1064228753Smm		}
1065228753Smm	}
1066228753Smm
1067228753Smm	/*
1068228753Smm	 * POSIX/SUSv3 doesn't provide a standard key for large device
1069228753Smm	 * numbers.  I use the same keys here that Joerg Schilling
1070228753Smm	 * used for 'star.'  (Which, somewhat confusingly, are called
1071228753Smm	 * "devXXX" even though they code "rdev" values.)  No doubt,
1072228753Smm	 * other implementations use other keys.  Note that there's no
1073228753Smm	 * reason we can't write the same information into a number of
1074228753Smm	 * different keys.
1075228753Smm	 *
1076228753Smm	 * Of course, this is only needed for block or char device entries.
1077228753Smm	 */
1078228753Smm	if (archive_entry_filetype(entry_main) == AE_IFBLK
1079228753Smm	    || archive_entry_filetype(entry_main) == AE_IFCHR) {
1080228753Smm		/*
1081228753Smm		 * If rdevmajor is too large, add 'SCHILY.devmajor' to
1082228753Smm		 * extended attributes.
1083228753Smm		 */
1084232153Smm		int rdevmajor, rdevminor;
1085228753Smm		rdevmajor = archive_entry_rdevmajor(entry_main);
1086228753Smm		rdevminor = archive_entry_rdevminor(entry_main);
1087228753Smm		if (rdevmajor >= (1 << 18)) {
1088228753Smm			add_pax_attr_int(&(pax->pax_header), "SCHILY.devmajor",
1089228753Smm			    rdevmajor);
1090228753Smm			/*
1091228753Smm			 * Non-strict formatting below means we don't
1092228753Smm			 * have to truncate here.  Not truncating improves
1093228753Smm			 * the chance that some more modern tar archivers
1094228753Smm			 * (such as GNU tar 1.13) can restore the full
1095228753Smm			 * value even if they don't understand the pax
1096228753Smm			 * extended attributes.  See my rant below about
1097228753Smm			 * file size fields for additional details.
1098228753Smm			 */
1099228753Smm			/* archive_entry_set_rdevmajor(entry_main,
1100228753Smm			   rdevmajor & ((1 << 18) - 1)); */
1101228753Smm			need_extension = 1;
1102228753Smm		}
1103228753Smm
1104228753Smm		/*
1105228753Smm		 * If devminor is too large, add 'SCHILY.devminor' to
1106228753Smm		 * extended attributes.
1107228753Smm		 */
1108228753Smm		if (rdevminor >= (1 << 18)) {
1109228753Smm			add_pax_attr_int(&(pax->pax_header), "SCHILY.devminor",
1110228753Smm			    rdevminor);
1111228753Smm			/* Truncation is not necessary here, either. */
1112228753Smm			/* archive_entry_set_rdevminor(entry_main,
1113228753Smm			   rdevminor & ((1 << 18) - 1)); */
1114228753Smm			need_extension = 1;
1115228753Smm		}
1116228753Smm	}
1117228753Smm
1118228753Smm	/*
1119228753Smm	 * Technically, the mtime field in the ustar header can
1120228753Smm	 * support 33 bits, but many platforms use signed 32-bit time
1121228753Smm	 * values.  The cutoff of 0x7fffffff here is a compromise.
1122228753Smm	 * Yes, this check is duplicated just below; this helps to
1123228753Smm	 * avoid writing an mtime attribute just to handle a
1124228753Smm	 * high-resolution timestamp in "restricted pax" mode.
1125228753Smm	 */
1126228753Smm	if (!need_extension &&
1127228753Smm	    ((archive_entry_mtime(entry_main) < 0)
1128228753Smm		|| (archive_entry_mtime(entry_main) >= 0x7fffffff)))
1129228753Smm		need_extension = 1;
1130228753Smm
1131228753Smm	/* I use a star-compatible file flag attribute. */
1132228753Smm	p = archive_entry_fflags_text(entry_main);
1133228753Smm	if (!need_extension && p != NULL  &&  *p != '\0')
1134228753Smm		need_extension = 1;
1135228753Smm
1136228753Smm	/* If there are extended attributes, we need an extension */
1137228753Smm	if (!need_extension && archive_entry_xattr_count(entry_original) > 0)
1138228753Smm		need_extension = 1;
1139228753Smm
1140232153Smm	/* If there are sparse info, we need an extension */
1141232153Smm	if (!need_extension && sparse_count > 0)
1142232153Smm		need_extension = 1;
1143232153Smm
1144313571Smm	acl_types = archive_entry_acl_types(entry_original);
1145313571Smm
1146313571Smm	/* If there are any ACL entries, we need an extension */
1147313571Smm	if (!need_extension && acl_types != 0)
1148313571Smm		need_extension = 1;
1149313571Smm
1150348608Smm	/* If the symlink type is defined, we need an extension */
1151348608Smm	if (!need_extension && archive_entry_symlink_type(entry_main) > 0)
1152348608Smm		need_extension = 1;
1153348608Smm
1154228753Smm	/*
1155302001Smm	 * Libarchive used to include these in extended headers for
1156302001Smm	 * restricted pax format, but that confused people who
1157302001Smm	 * expected ustar-like time semantics.  So now we only include
1158302001Smm	 * them in full pax format.
1159228753Smm	 */
1160302001Smm	if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED) {
1161228753Smm		if (archive_entry_ctime(entry_main) != 0  ||
1162228753Smm		    archive_entry_ctime_nsec(entry_main) != 0)
1163228753Smm			add_pax_attr_time(&(pax->pax_header), "ctime",
1164228753Smm			    archive_entry_ctime(entry_main),
1165228753Smm			    archive_entry_ctime_nsec(entry_main));
1166228753Smm
1167228753Smm		if (archive_entry_atime(entry_main) != 0 ||
1168228753Smm		    archive_entry_atime_nsec(entry_main) != 0)
1169228753Smm			add_pax_attr_time(&(pax->pax_header), "atime",
1170228753Smm			    archive_entry_atime(entry_main),
1171228753Smm			    archive_entry_atime_nsec(entry_main));
1172228753Smm
1173228753Smm		/* Store birth/creationtime only if it's earlier than mtime */
1174228753Smm		if (archive_entry_birthtime_is_set(entry_main) &&
1175228753Smm		    archive_entry_birthtime(entry_main)
1176228753Smm		    < archive_entry_mtime(entry_main))
1177228753Smm			add_pax_attr_time(&(pax->pax_header),
1178228753Smm			    "LIBARCHIVE.creationtime",
1179228753Smm			    archive_entry_birthtime(entry_main),
1180228753Smm			    archive_entry_birthtime_nsec(entry_main));
1181302001Smm	}
1182228753Smm
1183302001Smm	/*
1184302001Smm	 * The following items are handled differently in "pax
1185302001Smm	 * restricted" format.  In particular, in "pax restricted"
1186302001Smm	 * format they won't be added unless need_extension is
1187302001Smm	 * already set (we're already generating an extended header, so
1188302001Smm	 * may as well include these).
1189302001Smm	 */
1190302001Smm	if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED ||
1191302001Smm	    need_extension) {
1192302001Smm		if (archive_entry_mtime(entry_main) < 0  ||
1193302001Smm		    archive_entry_mtime(entry_main) >= 0x7fffffff  ||
1194302001Smm		    archive_entry_mtime_nsec(entry_main) != 0)
1195302001Smm			add_pax_attr_time(&(pax->pax_header), "mtime",
1196302001Smm			    archive_entry_mtime(entry_main),
1197302001Smm			    archive_entry_mtime_nsec(entry_main));
1198302001Smm
1199228753Smm		/* I use a star-compatible file flag attribute. */
1200228753Smm		p = archive_entry_fflags_text(entry_main);
1201228753Smm		if (p != NULL  &&  *p != '\0')
1202228753Smm			add_pax_attr(&(pax->pax_header), "SCHILY.fflags", p);
1203228753Smm
1204228753Smm		/* I use star-compatible ACL attributes. */
1205313571Smm		if ((acl_types & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) {
1206313571Smm			ret = add_pax_acl(a, entry_original, pax,
1207313571Smm			    ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID |
1208313927Smm			    ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA |
1209313927Smm			    ARCHIVE_ENTRY_ACL_STYLE_COMPACT);
1210358090Smm			if (ret == ARCHIVE_FATAL) {
1211358090Smm				archive_entry_free(entry_main);
1212358090Smm				archive_string_free(&entry_name);
1213232153Smm				return (ARCHIVE_FATAL);
1214358090Smm			}
1215232153Smm		}
1216313571Smm		if (acl_types & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) {
1217313571Smm			ret = add_pax_acl(a, entry_original, pax,
1218313571Smm			    ARCHIVE_ENTRY_ACL_TYPE_ACCESS |
1219313571Smm			    ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID |
1220313571Smm			    ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA);
1221358090Smm			if (ret == ARCHIVE_FATAL) {
1222358090Smm				archive_entry_free(entry_main);
1223358090Smm				archive_string_free(&entry_name);
1224232153Smm				return (ARCHIVE_FATAL);
1225358090Smm			}
1226232153Smm		}
1227313571Smm		if (acl_types & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) {
1228313571Smm			ret = add_pax_acl(a, entry_original, pax,
1229313571Smm			    ARCHIVE_ENTRY_ACL_TYPE_DEFAULT |
1230313571Smm			    ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID |
1231313571Smm			    ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA);
1232358090Smm			if (ret == ARCHIVE_FATAL) {
1233358090Smm				archive_entry_free(entry_main);
1234358090Smm				archive_string_free(&entry_name);
1235313571Smm				return (ARCHIVE_FATAL);
1236358090Smm			}
1237313571Smm		}
1238228753Smm
1239232153Smm		/* We use GNU-tar-compatible sparse attributes. */
1240232153Smm		if (sparse_count > 0) {
1241232153Smm			int64_t soffset, slength;
1242228753Smm
1243232153Smm			add_pax_attr_int(&(pax->pax_header),
1244232153Smm			    "GNU.sparse.major", 1);
1245232153Smm			add_pax_attr_int(&(pax->pax_header),
1246232153Smm			    "GNU.sparse.minor", 0);
1247318483Smm			/*
1248318483Smm			 * Make sure to store the original path, since
1249318483Smm			 * truncation to ustar limit happened already.
1250318483Smm			 */
1251232153Smm			add_pax_attr(&(pax->pax_header),
1252318483Smm			    "GNU.sparse.name", path);
1253232153Smm			add_pax_attr_int(&(pax->pax_header),
1254232153Smm			    "GNU.sparse.realsize",
1255232153Smm			    archive_entry_size(entry_main));
1256232153Smm
1257232153Smm			/* Rename the file name which will be used for
1258232153Smm			 * ustar header to a special name, which GNU
1259232153Smm			 * PAX Format 1.0 requires */
1260232153Smm			archive_entry_set_pathname(entry_main,
1261232153Smm			    build_gnu_sparse_name(gnu_sparse_name,
1262232153Smm			        entry_name.s));
1263232153Smm
1264232153Smm			/*
1265232153Smm			 * - Make a sparse map, which will precede a file data.
1266232153Smm			 * - Get the total size of available data of sparse.
1267232153Smm			 */
1268232153Smm			archive_string_sprintf(&(pax->sparse_map), "%d\n",
1269232153Smm			    sparse_count);
1270232153Smm			while (archive_entry_sparse_next(entry_main,
1271232153Smm			    &soffset, &slength) == ARCHIVE_OK) {
1272232153Smm				archive_string_sprintf(&(pax->sparse_map),
1273232153Smm				    "%jd\n%jd\n",
1274232153Smm				    (intmax_t)soffset,
1275232153Smm				    (intmax_t)slength);
1276232153Smm				sparse_total += slength;
1277232153Smm				if (sparse_list_add(pax, soffset, slength)
1278232153Smm				    != ARCHIVE_OK) {
1279232153Smm					archive_set_error(&a->archive,
1280232153Smm					    ENOMEM,
1281232153Smm					    "Can't allocate memory");
1282232153Smm					archive_entry_free(entry_main);
1283232153Smm					archive_string_free(&entry_name);
1284232153Smm					return (ARCHIVE_FATAL);
1285232153Smm				}
1286232153Smm			}
1287232153Smm		}
1288232153Smm
1289228753Smm		/* Store extended attributes */
1290232153Smm		if (archive_write_pax_header_xattrs(a, pax, entry_original)
1291232153Smm		    == ARCHIVE_FATAL) {
1292232153Smm			archive_entry_free(entry_main);
1293232153Smm			archive_string_free(&entry_name);
1294232153Smm			return (ARCHIVE_FATAL);
1295232153Smm		}
1296348608Smm
1297348608Smm		/* Store extended symlink information */
1298348608Smm		if (archive_entry_symlink_type(entry_main) ==
1299348608Smm		    AE_SYMLINK_TYPE_FILE) {
1300348608Smm			add_pax_attr(&(pax->pax_header),
1301348608Smm			    "LIBARCHIVE.symlinktype", "file");
1302348608Smm		} else if (archive_entry_symlink_type(entry_main) ==
1303348608Smm		    AE_SYMLINK_TYPE_DIRECTORY) {
1304348608Smm			add_pax_attr(&(pax->pax_header),
1305348608Smm			    "LIBARCHIVE.symlinktype", "dir");
1306348608Smm		}
1307228753Smm	}
1308228753Smm
1309228753Smm	/* Only regular files have data. */
1310228753Smm	if (archive_entry_filetype(entry_main) != AE_IFREG)
1311228753Smm		archive_entry_set_size(entry_main, 0);
1312228753Smm
1313228753Smm	/*
1314228753Smm	 * Pax-restricted does not store data for hardlinks, in order
1315228753Smm	 * to improve compatibility with ustar.
1316228753Smm	 */
1317228753Smm	if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
1318228753Smm	    hardlink != NULL)
1319228753Smm		archive_entry_set_size(entry_main, 0);
1320228753Smm
1321228753Smm	/*
1322228753Smm	 * XXX Full pax interchange format does permit a hardlink
1323228753Smm	 * entry to have data associated with it.  I'm not supporting
1324228753Smm	 * that here because the client expects me to tell them whether
1325228753Smm	 * or not this format expects data for hardlinks.  If I
1326228753Smm	 * don't check here, then every pax archive will end up with
1327228753Smm	 * duplicated data for hardlinks.  Someday, there may be
1328228753Smm	 * need to select this behavior, in which case the following
1329228753Smm	 * will need to be revisited. XXX
1330228753Smm	 */
1331228753Smm	if (hardlink != NULL)
1332228753Smm		archive_entry_set_size(entry_main, 0);
1333228753Smm
1334232153Smm	/* Save a real file size. */
1335232153Smm	real_size = archive_entry_size(entry_main);
1336232153Smm	/*
1337232153Smm	 * Overwrite a file size by the total size of sparse blocks and
1338232153Smm	 * the size of sparse map info. That file size is the length of
1339232153Smm	 * the data, which we will exactly store into an archive file.
1340232153Smm	 */
1341232153Smm	if (archive_strlen(&(pax->sparse_map))) {
1342232153Smm		size_t mapsize = archive_strlen(&(pax->sparse_map));
1343232153Smm		pax->sparse_map_padding = 0x1ff & (-(ssize_t)mapsize);
1344232153Smm		archive_entry_set_size(entry_main,
1345232153Smm		    mapsize + pax->sparse_map_padding + sparse_total);
1346232153Smm	}
1347232153Smm
1348228753Smm	/* Format 'ustar' header for main entry.
1349228753Smm	 *
1350228753Smm	 * The trouble with file size: If the reader can't understand
1351228753Smm	 * the file size, they may not be able to locate the next
1352228753Smm	 * entry and the rest of the archive is toast.  Pax-compliant
1353228753Smm	 * readers are supposed to ignore the file size in the main
1354228753Smm	 * header, so the question becomes how to maximize portability
1355228753Smm	 * for readers that don't support pax attribute extensions.
1356228753Smm	 * For maximum compatibility, I permit numeric extensions in
1357228753Smm	 * the main header so that the file size stored will always be
1358228753Smm	 * correct, even if it's in a format that only some
1359228753Smm	 * implementations understand.  The technique used here is:
1360228753Smm	 *
1361228753Smm	 *  a) If possible, follow the standard exactly.  This handles
1362228753Smm	 *  files up to 8 gigabytes minus 1.
1363228753Smm	 *
1364228753Smm	 *  b) If that fails, try octal but omit the field terminator.
1365228753Smm	 *  That handles files up to 64 gigabytes minus 1.
1366228753Smm	 *
1367228753Smm	 *  c) Otherwise, use base-256 extensions.  That handles files
1368228753Smm	 *  up to 2^63 in this implementation, with the potential to
1369228753Smm	 *  go up to 2^94.  That should hold us for a while. ;-)
1370228753Smm	 *
1371228753Smm	 * The non-strict formatter uses similar logic for other
1372228753Smm	 * numeric fields, though they're less critical.
1373228753Smm	 */
1374232153Smm	if (__archive_write_format_header_ustar(a, ustarbuff, entry_main, -1, 0,
1375358090Smm	    NULL) == ARCHIVE_FATAL) {
1376358090Smm		archive_entry_free(entry_main);
1377358090Smm		archive_string_free(&entry_name);
1378232153Smm		return (ARCHIVE_FATAL);
1379358090Smm	}
1380228753Smm
1381228753Smm	/* If we built any extended attributes, write that entry first. */
1382228753Smm	if (archive_strlen(&(pax->pax_header)) > 0) {
1383228753Smm		struct archive_entry *pax_attr_entry;
1384228753Smm		time_t s;
1385232153Smm		int64_t uid, gid;
1386232153Smm		int mode;
1387228753Smm
1388232153Smm		pax_attr_entry = archive_entry_new2(&a->archive);
1389232153Smm		p = entry_name.s;
1390228753Smm		archive_entry_set_pathname(pax_attr_entry,
1391228753Smm		    build_pax_attribute_name(pax_entry_name, p));
1392228753Smm		archive_entry_set_size(pax_attr_entry,
1393228753Smm		    archive_strlen(&(pax->pax_header)));
1394228753Smm		/* Copy uid/gid (but clip to ustar limits). */
1395228753Smm		uid = archive_entry_uid(entry_main);
1396232153Smm		if (uid >= 1 << 18)
1397232153Smm			uid = (1 << 18) - 1;
1398228753Smm		archive_entry_set_uid(pax_attr_entry, uid);
1399228753Smm		gid = archive_entry_gid(entry_main);
1400232153Smm		if (gid >= 1 << 18)
1401232153Smm			gid = (1 << 18) - 1;
1402228753Smm		archive_entry_set_gid(pax_attr_entry, gid);
1403228753Smm		/* Copy mode over (but not setuid/setgid bits) */
1404228753Smm		mode = archive_entry_mode(entry_main);
1405228753Smm#ifdef S_ISUID
1406228753Smm		mode &= ~S_ISUID;
1407228753Smm#endif
1408228753Smm#ifdef S_ISGID
1409228753Smm		mode &= ~S_ISGID;
1410228753Smm#endif
1411228753Smm#ifdef S_ISVTX
1412228753Smm		mode &= ~S_ISVTX;
1413228753Smm#endif
1414228753Smm		archive_entry_set_mode(pax_attr_entry, mode);
1415228753Smm
1416228753Smm		/* Copy uname/gname. */
1417228753Smm		archive_entry_set_uname(pax_attr_entry,
1418228753Smm		    archive_entry_uname(entry_main));
1419228753Smm		archive_entry_set_gname(pax_attr_entry,
1420228753Smm		    archive_entry_gname(entry_main));
1421228753Smm
1422228753Smm		/* Copy mtime, but clip to ustar limits. */
1423228753Smm		s = archive_entry_mtime(entry_main);
1424228753Smm		if (s < 0) { s = 0; }
1425228753Smm		if (s >= 0x7fffffff) { s = 0x7fffffff; }
1426228753Smm		archive_entry_set_mtime(pax_attr_entry, s, 0);
1427228753Smm
1428228753Smm		/* Standard ustar doesn't support atime. */
1429228753Smm		archive_entry_set_atime(pax_attr_entry, 0, 0);
1430228753Smm
1431228753Smm		/* Standard ustar doesn't support ctime. */
1432228753Smm		archive_entry_set_ctime(pax_attr_entry, 0, 0);
1433228753Smm
1434228753Smm		r = __archive_write_format_header_ustar(a, paxbuff,
1435232153Smm		    pax_attr_entry, 'x', 1, NULL);
1436228753Smm
1437228753Smm		archive_entry_free(pax_attr_entry);
1438228753Smm
1439228753Smm		/* Note that the 'x' header shouldn't ever fail to format */
1440232153Smm		if (r < ARCHIVE_WARN) {
1441232153Smm			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1442232153Smm			    "archive_write_pax_header: "
1443232153Smm			    "'x' header failed?!  This can't happen.\n");
1444358090Smm			archive_entry_free(entry_main);
1445358090Smm			archive_string_free(&entry_name);
1446232153Smm			return (ARCHIVE_FATAL);
1447232153Smm		} else if (r < ret)
1448232153Smm			ret = r;
1449232153Smm		r = __archive_write_output(a, paxbuff, 512);
1450228753Smm		if (r != ARCHIVE_OK) {
1451232153Smm			sparse_list_clear(pax);
1452228753Smm			pax->entry_bytes_remaining = 0;
1453228753Smm			pax->entry_padding = 0;
1454358090Smm			archive_entry_free(entry_main);
1455358090Smm			archive_string_free(&entry_name);
1456228753Smm			return (ARCHIVE_FATAL);
1457228753Smm		}
1458228753Smm
1459228753Smm		pax->entry_bytes_remaining = archive_strlen(&(pax->pax_header));
1460232153Smm		pax->entry_padding =
1461232153Smm		    0x1ff & (-(int64_t)pax->entry_bytes_remaining);
1462228753Smm
1463232153Smm		r = __archive_write_output(a, pax->pax_header.s,
1464228753Smm		    archive_strlen(&(pax->pax_header)));
1465228753Smm		if (r != ARCHIVE_OK) {
1466228753Smm			/* If a write fails, we're pretty much toast. */
1467358090Smm			archive_entry_free(entry_main);
1468358090Smm			archive_string_free(&entry_name);
1469228753Smm			return (ARCHIVE_FATAL);
1470228753Smm		}
1471228753Smm		/* Pad out the end of the entry. */
1472238856Smm		r = __archive_write_nulls(a, (size_t)pax->entry_padding);
1473228753Smm		if (r != ARCHIVE_OK) {
1474228753Smm			/* If a write fails, we're pretty much toast. */
1475358090Smm			archive_entry_free(entry_main);
1476358090Smm			archive_string_free(&entry_name);
1477228753Smm			return (ARCHIVE_FATAL);
1478228753Smm		}
1479228753Smm		pax->entry_bytes_remaining = pax->entry_padding = 0;
1480228753Smm	}
1481228753Smm
1482228753Smm	/* Write the header for main entry. */
1483232153Smm	r = __archive_write_output(a, ustarbuff, 512);
1484358090Smm	if (r != ARCHIVE_OK) {
1485358090Smm		archive_entry_free(entry_main);
1486358090Smm		archive_string_free(&entry_name);
1487228753Smm		return (r);
1488358090Smm	}
1489228753Smm
1490228753Smm	/*
1491228753Smm	 * Inform the client of the on-disk size we're using, so
1492228753Smm	 * they can avoid unnecessarily writing a body for something
1493228753Smm	 * that we're just going to ignore.
1494228753Smm	 */
1495232153Smm	archive_entry_set_size(entry_original, real_size);
1496232153Smm	if (pax->sparse_list == NULL && real_size > 0) {
1497232153Smm		/* This is not a sparse file but we handle its data as
1498232153Smm		 * a sparse block. */
1499232153Smm		sparse_list_add(pax, 0, real_size);
1500232153Smm		sparse_total = real_size;
1501232153Smm	}
1502232153Smm	pax->entry_padding = 0x1ff & (-(int64_t)sparse_total);
1503228753Smm	archive_entry_free(entry_main);
1504232153Smm	archive_string_free(&entry_name);
1505228753Smm
1506228753Smm	return (ret);
1507228753Smm}
1508228753Smm
1509228753Smm/*
1510228753Smm * We need a valid name for the regular 'ustar' entry.  This routine
1511228753Smm * tries to hack something more-or-less reasonable.
1512228753Smm *
1513228753Smm * The approach here tries to preserve leading dir names.  We do so by
1514228753Smm * working with four sections:
1515228753Smm *   1) "prefix" directory names,
1516228753Smm *   2) "suffix" directory names,
1517228753Smm *   3) inserted dir name (optional),
1518228753Smm *   4) filename.
1519228753Smm *
1520228753Smm * These sections must satisfy the following requirements:
1521228753Smm *   * Parts 1 & 2 together form an initial portion of the dir name.
1522228753Smm *   * Part 3 is specified by the caller.  (It should not contain a leading
1523228753Smm *     or trailing '/'.)
1524228753Smm *   * Part 4 forms an initial portion of the base filename.
1525228753Smm *   * The filename must be <= 99 chars to fit the ustar 'name' field.
1526228753Smm *   * Parts 2, 3, 4 together must be <= 99 chars to fit the ustar 'name' fld.
1527228753Smm *   * Part 1 must be <= 155 chars to fit the ustar 'prefix' field.
1528228753Smm *   * If the original name ends in a '/', the new name must also end in a '/'
1529228753Smm *   * Trailing '/.' sequences may be stripped.
1530228753Smm *
1531228753Smm * Note: Recall that the ustar format does not store the '/' separating
1532228753Smm * parts 1 & 2, but does store the '/' separating parts 2 & 3.
1533228753Smm */
1534228753Smmstatic char *
1535228753Smmbuild_ustar_entry_name(char *dest, const char *src, size_t src_length,
1536228753Smm    const char *insert)
1537228753Smm{
1538228753Smm	const char *prefix, *prefix_end;
1539228753Smm	const char *suffix, *suffix_end;
1540228753Smm	const char *filename, *filename_end;
1541228753Smm	char *p;
1542228753Smm	int need_slash = 0; /* Was there a trailing slash? */
1543228753Smm	size_t suffix_length = 99;
1544228753Smm	size_t insert_length;
1545228753Smm
1546228753Smm	/* Length of additional dir element to be added. */
1547228753Smm	if (insert == NULL)
1548228753Smm		insert_length = 0;
1549228753Smm	else
1550228753Smm		/* +2 here allows for '/' before and after the insert. */
1551228753Smm		insert_length = strlen(insert) + 2;
1552228753Smm
1553228753Smm	/* Step 0: Quick bailout in a common case. */
1554228753Smm	if (src_length < 100 && insert == NULL) {
1555228753Smm		strncpy(dest, src, src_length);
1556228753Smm		dest[src_length] = '\0';
1557228753Smm		return (dest);
1558228753Smm	}
1559228753Smm
1560228753Smm	/* Step 1: Locate filename and enforce the length restriction. */
1561228753Smm	filename_end = src + src_length;
1562228753Smm	/* Remove trailing '/' chars and '/.' pairs. */
1563228753Smm	for (;;) {
1564228753Smm		if (filename_end > src && filename_end[-1] == '/') {
1565228753Smm			filename_end --;
1566228753Smm			need_slash = 1; /* Remember to restore trailing '/'. */
1567228753Smm			continue;
1568228753Smm		}
1569228753Smm		if (filename_end > src + 1 && filename_end[-1] == '.'
1570228753Smm		    && filename_end[-2] == '/') {
1571228753Smm			filename_end -= 2;
1572228753Smm			need_slash = 1; /* "foo/." will become "foo/" */
1573228753Smm			continue;
1574228753Smm		}
1575228753Smm		break;
1576228753Smm	}
1577228753Smm	if (need_slash)
1578228753Smm		suffix_length--;
1579228753Smm	/* Find start of filename. */
1580228753Smm	filename = filename_end - 1;
1581228753Smm	while ((filename > src) && (*filename != '/'))
1582228753Smm		filename --;
1583228753Smm	if ((*filename == '/') && (filename < filename_end - 1))
1584228753Smm		filename ++;
1585228753Smm	/* Adjust filename_end so that filename + insert fits in 99 chars. */
1586228753Smm	suffix_length -= insert_length;
1587228753Smm	if (filename_end > filename + suffix_length)
1588228753Smm		filename_end = filename + suffix_length;
1589228753Smm	/* Calculate max size for "suffix" section (#3 above). */
1590228753Smm	suffix_length -= filename_end - filename;
1591228753Smm
1592228753Smm	/* Step 2: Locate the "prefix" section of the dirname, including
1593228753Smm	 * trailing '/'. */
1594228753Smm	prefix = src;
1595228753Smm	prefix_end = prefix + 155;
1596228753Smm	if (prefix_end > filename)
1597228753Smm		prefix_end = filename;
1598228753Smm	while (prefix_end > prefix && *prefix_end != '/')
1599228753Smm		prefix_end--;
1600228753Smm	if ((prefix_end < filename) && (*prefix_end == '/'))
1601228753Smm		prefix_end++;
1602228753Smm
1603228753Smm	/* Step 3: Locate the "suffix" section of the dirname,
1604228753Smm	 * including trailing '/'. */
1605228753Smm	suffix = prefix_end;
1606228753Smm	suffix_end = suffix + suffix_length; /* Enforce limit. */
1607228753Smm	if (suffix_end > filename)
1608228753Smm		suffix_end = filename;
1609228753Smm	if (suffix_end < suffix)
1610228753Smm		suffix_end = suffix;
1611228753Smm	while (suffix_end > suffix && *suffix_end != '/')
1612228753Smm		suffix_end--;
1613228753Smm	if ((suffix_end < filename) && (*suffix_end == '/'))
1614228753Smm		suffix_end++;
1615228753Smm
1616228753Smm	/* Step 4: Build the new name. */
1617228753Smm	/* The OpenBSD strlcpy function is safer, but less portable. */
1618228753Smm	/* Rather than maintain two versions, just use the strncpy version. */
1619228753Smm	p = dest;
1620228753Smm	if (prefix_end > prefix) {
1621228753Smm		strncpy(p, prefix, prefix_end - prefix);
1622228753Smm		p += prefix_end - prefix;
1623228753Smm	}
1624228753Smm	if (suffix_end > suffix) {
1625228753Smm		strncpy(p, suffix, suffix_end - suffix);
1626228753Smm		p += suffix_end - suffix;
1627228753Smm	}
1628228753Smm	if (insert != NULL) {
1629228753Smm		/* Note: assume insert does not have leading or trailing '/' */
1630228753Smm		strcpy(p, insert);
1631228753Smm		p += strlen(insert);
1632228753Smm		*p++ = '/';
1633228753Smm	}
1634228753Smm	strncpy(p, filename, filename_end - filename);
1635228753Smm	p += filename_end - filename;
1636228753Smm	if (need_slash)
1637228753Smm		*p++ = '/';
1638228753Smm	*p = '\0';
1639228753Smm
1640228753Smm	return (dest);
1641228753Smm}
1642228753Smm
1643228753Smm/*
1644228753Smm * The ustar header for the pax extended attributes must have a
1645228753Smm * reasonable name:  SUSv3 requires 'dirname'/PaxHeader.'pid'/'filename'
1646228753Smm * where 'pid' is the PID of the archiving process.  Unfortunately,
1647228753Smm * that makes testing a pain since the output varies for each run,
1648228753Smm * so I'm sticking with the simpler 'dirname'/PaxHeader/'filename'
1649228753Smm * for now.  (Someday, I'll make this settable.  Then I can use the
1650228753Smm * SUS recommendation as default and test harnesses can override it
1651228753Smm * to get predictable results.)
1652228753Smm *
1653228753Smm * Joerg Schilling has argued that this is unnecessary because, in
1654228753Smm * practice, if the pax extended attributes get extracted as regular
1655232153Smm * files, no one is going to bother reading those attributes to
1656228753Smm * manually restore them.  Based on this, 'star' uses
1657228753Smm * /tmp/PaxHeader/'basename' as the ustar header name.  This is a
1658228753Smm * tempting argument, in part because it's simpler than the SUSv3
1659228753Smm * recommendation, but I'm not entirely convinced.  I'm also
1660228753Smm * uncomfortable with the fact that "/tmp" is a Unix-ism.
1661228753Smm *
1662228753Smm * The following routine leverages build_ustar_entry_name() above and
1663228753Smm * so is simpler than you might think.  It just needs to provide the
1664228753Smm * additional path element and handle a few pathological cases).
1665228753Smm */
1666228753Smmstatic char *
1667228753Smmbuild_pax_attribute_name(char *dest, const char *src)
1668228753Smm{
1669228753Smm	char buff[64];
1670228753Smm	const char *p;
1671228753Smm
1672228753Smm	/* Handle the null filename case. */
1673228753Smm	if (src == NULL || *src == '\0') {
1674228753Smm		strcpy(dest, "PaxHeader/blank");
1675228753Smm		return (dest);
1676228753Smm	}
1677228753Smm
1678228753Smm	/* Prune final '/' and other unwanted final elements. */
1679228753Smm	p = src + strlen(src);
1680228753Smm	for (;;) {
1681228753Smm		/* Ends in "/", remove the '/' */
1682228753Smm		if (p > src && p[-1] == '/') {
1683228753Smm			--p;
1684228753Smm			continue;
1685228753Smm		}
1686228753Smm		/* Ends in "/.", remove the '.' */
1687228753Smm		if (p > src + 1 && p[-1] == '.'
1688228753Smm		    && p[-2] == '/') {
1689228753Smm			--p;
1690228753Smm			continue;
1691228753Smm		}
1692228753Smm		break;
1693228753Smm	}
1694228753Smm
1695228753Smm	/* Pathological case: After above, there was nothing left.
1696228753Smm	 * This includes "/." "/./." "/.//./." etc. */
1697228753Smm	if (p == src) {
1698228753Smm		strcpy(dest, "/PaxHeader/rootdir");
1699228753Smm		return (dest);
1700228753Smm	}
1701228753Smm
1702228753Smm	/* Convert unadorned "." into a suitable filename. */
1703228753Smm	if (*src == '.' && p == src + 1) {
1704228753Smm		strcpy(dest, "PaxHeader/currentdir");
1705228753Smm		return (dest);
1706228753Smm	}
1707228753Smm
1708228753Smm	/*
1709228753Smm	 * TODO: Push this string into the 'pax' structure to avoid
1710228753Smm	 * recomputing it every time.  That will also open the door
1711228753Smm	 * to having clients override it.
1712228753Smm	 */
1713228753Smm#if HAVE_GETPID && 0  /* Disable this for now; see above comment. */
1714228753Smm	sprintf(buff, "PaxHeader.%d", getpid());
1715228753Smm#else
1716228753Smm	/* If the platform can't fetch the pid, don't include it. */
1717228753Smm	strcpy(buff, "PaxHeader");
1718228753Smm#endif
1719232153Smm	/* General case: build a ustar-compatible name adding
1720232153Smm	 * "/PaxHeader/". */
1721228753Smm	build_ustar_entry_name(dest, src, p - src, buff);
1722228753Smm
1723228753Smm	return (dest);
1724228753Smm}
1725228753Smm
1726232153Smm/*
1727232153Smm * GNU PAX Format 1.0 requires the special name, which pattern is:
1728232153Smm * <dir>/GNUSparseFile.<pid>/<original file name>
1729232153Smm *
1730324418Smm * Since reproducible archives are more important, use 0 as pid.
1731318483Smm *
1732232153Smm * This function is used for only Sparse file, a file type of which
1733232153Smm * is regular file.
1734232153Smm */
1735232153Smmstatic char *
1736232153Smmbuild_gnu_sparse_name(char *dest, const char *src)
1737228753Smm{
1738232153Smm	const char *p;
1739228753Smm
1740232153Smm	/* Handle the null filename case. */
1741232153Smm	if (src == NULL || *src == '\0') {
1742232153Smm		strcpy(dest, "GNUSparseFile/blank");
1743232153Smm		return (dest);
1744232153Smm	}
1745228753Smm
1746232153Smm	/* Prune final '/' and other unwanted final elements. */
1747232153Smm	p = src + strlen(src);
1748232153Smm	for (;;) {
1749232153Smm		/* Ends in "/", remove the '/' */
1750232153Smm		if (p > src && p[-1] == '/') {
1751232153Smm			--p;
1752232153Smm			continue;
1753232153Smm		}
1754232153Smm		/* Ends in "/.", remove the '.' */
1755232153Smm		if (p > src + 1 && p[-1] == '.'
1756232153Smm		    && p[-2] == '/') {
1757232153Smm			--p;
1758232153Smm			continue;
1759232153Smm		}
1760232153Smm		break;
1761232153Smm	}
1762232153Smm
1763232153Smm	/* General case: build a ustar-compatible name adding
1764232153Smm	 * "/GNUSparseFile/". */
1765318483Smm	build_ustar_entry_name(dest, src, p - src, "GNUSparseFile.0");
1766232153Smm
1767232153Smm	return (dest);
1768228753Smm}
1769228753Smm
1770232153Smm/* Write two null blocks for the end of archive */
1771228753Smmstatic int
1772232153Smmarchive_write_pax_close(struct archive_write *a)
1773228753Smm{
1774232153Smm	return (__archive_write_nulls(a, 512 * 2));
1775232153Smm}
1776232153Smm
1777232153Smmstatic int
1778232153Smmarchive_write_pax_free(struct archive_write *a)
1779232153Smm{
1780228753Smm	struct pax *pax;
1781228753Smm
1782228753Smm	pax = (struct pax *)a->format_data;
1783228753Smm	if (pax == NULL)
1784228753Smm		return (ARCHIVE_OK);
1785228753Smm
1786228753Smm	archive_string_free(&pax->pax_header);
1787232153Smm	archive_string_free(&pax->sparse_map);
1788232153Smm	archive_string_free(&pax->l_url_encoded_name);
1789232153Smm	sparse_list_clear(pax);
1790228753Smm	free(pax);
1791228753Smm	a->format_data = NULL;
1792228753Smm	return (ARCHIVE_OK);
1793228753Smm}
1794228753Smm
1795228753Smmstatic int
1796228753Smmarchive_write_pax_finish_entry(struct archive_write *a)
1797228753Smm{
1798228753Smm	struct pax *pax;
1799232153Smm	uint64_t remaining;
1800228753Smm	int ret;
1801228753Smm
1802228753Smm	pax = (struct pax *)a->format_data;
1803232153Smm	remaining = pax->entry_bytes_remaining;
1804232153Smm	if (remaining == 0) {
1805232153Smm		while (pax->sparse_list) {
1806232153Smm			struct sparse_block *sb;
1807232153Smm			if (!pax->sparse_list->is_hole)
1808232153Smm				remaining += pax->sparse_list->remaining;
1809232153Smm			sb = pax->sparse_list->next;
1810232153Smm			free(pax->sparse_list);
1811232153Smm			pax->sparse_list = sb;
1812232153Smm		}
1813232153Smm	}
1814238856Smm	ret = __archive_write_nulls(a, (size_t)(remaining + pax->entry_padding));
1815228753Smm	pax->entry_bytes_remaining = pax->entry_padding = 0;
1816228753Smm	return (ret);
1817228753Smm}
1818228753Smm
1819232153Smmstatic ssize_t
1820232153Smmarchive_write_pax_data(struct archive_write *a, const void *buff, size_t s)
1821228753Smm{
1822232153Smm	struct pax *pax;
1823232153Smm	size_t ws;
1824232153Smm	size_t total;
1825228753Smm	int ret;
1826228753Smm
1827232153Smm	pax = (struct pax *)a->format_data;
1828232153Smm
1829232153Smm	/*
1830232153Smm	 * According to GNU PAX format 1.0, write a sparse map
1831232153Smm	 * before the body.
1832232153Smm	 */
1833232153Smm	if (archive_strlen(&(pax->sparse_map))) {
1834232153Smm		ret = __archive_write_output(a, pax->sparse_map.s,
1835232153Smm		    archive_strlen(&(pax->sparse_map)));
1836228753Smm		if (ret != ARCHIVE_OK)
1837228753Smm			return (ret);
1838232153Smm		ret = __archive_write_nulls(a, pax->sparse_map_padding);
1839232153Smm		if (ret != ARCHIVE_OK)
1840232153Smm			return (ret);
1841232153Smm		archive_string_empty(&(pax->sparse_map));
1842228753Smm	}
1843228753Smm
1844232153Smm	total = 0;
1845232153Smm	while (total < s) {
1846232153Smm		const unsigned char *p;
1847228753Smm
1848232153Smm		while (pax->sparse_list != NULL &&
1849232153Smm		    pax->sparse_list->remaining == 0) {
1850232153Smm			struct sparse_block *sb = pax->sparse_list->next;
1851232153Smm			free(pax->sparse_list);
1852232153Smm			pax->sparse_list = sb;
1853232153Smm		}
1854228753Smm
1855232153Smm		if (pax->sparse_list == NULL)
1856232153Smm			return (total);
1857232153Smm
1858232153Smm		p = ((const unsigned char *)buff) + total;
1859232153Smm		ws = s - total;
1860232153Smm		if (ws > pax->sparse_list->remaining)
1861238856Smm			ws = (size_t)pax->sparse_list->remaining;
1862232153Smm
1863232153Smm		if (pax->sparse_list->is_hole) {
1864232153Smm			/* Current block is hole thus we do not write
1865232153Smm			 * the body. */
1866232153Smm			pax->sparse_list->remaining -= ws;
1867232153Smm			total += ws;
1868232153Smm			continue;
1869232153Smm		}
1870232153Smm
1871232153Smm		ret = __archive_write_output(a, p, ws);
1872232153Smm		pax->sparse_list->remaining -= ws;
1873232153Smm		total += ws;
1874232153Smm		if (ret != ARCHIVE_OK)
1875232153Smm			return (ret);
1876232153Smm	}
1877232153Smm	return (total);
1878228753Smm}
1879228753Smm
1880228753Smmstatic int
1881232153Smmhas_non_ASCII(const char *_p)
1882228753Smm{
1883232153Smm	const unsigned char *p = (const unsigned char *)_p;
1884232153Smm
1885232153Smm	if (p == NULL)
1886228753Smm		return (1);
1887232153Smm	while (*p != '\0' && *p < 128)
1888232153Smm		p++;
1889232153Smm	return (*p != '\0');
1890228753Smm}
1891228753Smm
1892228753Smm/*
1893228753Smm * Used by extended attribute support; encodes the name
1894228753Smm * so that there will be no '=' characters in the result.
1895228753Smm */
1896228753Smmstatic char *
1897228753Smmurl_encode(const char *in)
1898228753Smm{
1899228753Smm	const char *s;
1900228753Smm	char *d;
1901228753Smm	int out_len = 0;
1902228753Smm	char *out;
1903228753Smm
1904228753Smm	for (s = in; *s != '\0'; s++) {
1905228753Smm		if (*s < 33 || *s > 126 || *s == '%' || *s == '=')
1906228753Smm			out_len += 3;
1907228753Smm		else
1908228753Smm			out_len++;
1909228753Smm	}
1910228753Smm
1911228753Smm	out = (char *)malloc(out_len + 1);
1912228753Smm	if (out == NULL)
1913228753Smm		return (NULL);
1914228753Smm
1915228753Smm	for (s = in, d = out; *s != '\0'; s++) {
1916228753Smm		/* encode any non-printable ASCII character or '%' or '=' */
1917228753Smm		if (*s < 33 || *s > 126 || *s == '%' || *s == '=') {
1918228753Smm			/* URL encoding is '%' followed by two hex digits */
1919228753Smm			*d++ = '%';
1920228753Smm			*d++ = "0123456789ABCDEF"[0x0f & (*s >> 4)];
1921228753Smm			*d++ = "0123456789ABCDEF"[0x0f & *s];
1922228753Smm		} else {
1923228753Smm			*d++ = *s;
1924228753Smm		}
1925228753Smm	}
1926228753Smm	*d = '\0';
1927228753Smm	return (out);
1928228753Smm}
1929228753Smm
1930228753Smm/*
1931228753Smm * Encode a sequence of bytes into a C string using base-64 encoding.
1932228753Smm *
1933228753Smm * Returns a null-terminated C string allocated with malloc(); caller
1934228753Smm * is responsible for freeing the result.
1935228753Smm */
1936228753Smmstatic char *
1937228753Smmbase64_encode(const char *s, size_t len)
1938228753Smm{
1939228753Smm	static const char digits[64] =
1940228753Smm	    { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
1941228753Smm	      'P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d',
1942228753Smm	      'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s',
1943228753Smm	      't','u','v','w','x','y','z','0','1','2','3','4','5','6','7',
1944228753Smm	      '8','9','+','/' };
1945228753Smm	int v;
1946228753Smm	char *d, *out;
1947228753Smm
1948228753Smm	/* 3 bytes becomes 4 chars, but round up and allow for trailing NUL */
1949228753Smm	out = (char *)malloc((len * 4 + 2) / 3 + 1);
1950228753Smm	if (out == NULL)
1951228753Smm		return (NULL);
1952228753Smm	d = out;
1953228753Smm
1954228753Smm	/* Convert each group of 3 bytes into 4 characters. */
1955228753Smm	while (len >= 3) {
1956228753Smm		v = (((int)s[0] << 16) & 0xff0000)
1957228753Smm		    | (((int)s[1] << 8) & 0xff00)
1958228753Smm		    | (((int)s[2]) & 0x00ff);
1959228753Smm		s += 3;
1960228753Smm		len -= 3;
1961228753Smm		*d++ = digits[(v >> 18) & 0x3f];
1962228753Smm		*d++ = digits[(v >> 12) & 0x3f];
1963228753Smm		*d++ = digits[(v >> 6) & 0x3f];
1964228753Smm		*d++ = digits[(v) & 0x3f];
1965228753Smm	}
1966228753Smm	/* Handle final group of 1 byte (2 chars) or 2 bytes (3 chars). */
1967228753Smm	switch (len) {
1968228753Smm	case 0: break;
1969228753Smm	case 1:
1970228753Smm		v = (((int)s[0] << 16) & 0xff0000);
1971228753Smm		*d++ = digits[(v >> 18) & 0x3f];
1972228753Smm		*d++ = digits[(v >> 12) & 0x3f];
1973228753Smm		break;
1974228753Smm	case 2:
1975228753Smm		v = (((int)s[0] << 16) & 0xff0000)
1976228753Smm		    | (((int)s[1] << 8) & 0xff00);
1977228753Smm		*d++ = digits[(v >> 18) & 0x3f];
1978228753Smm		*d++ = digits[(v >> 12) & 0x3f];
1979228753Smm		*d++ = digits[(v >> 6) & 0x3f];
1980228753Smm		break;
1981228753Smm	}
1982228753Smm	/* Add trailing NUL character so output is a valid C string. */
1983228753Smm	*d = '\0';
1984228753Smm	return (out);
1985228753Smm}
1986232153Smm
1987232153Smmstatic void
1988232153Smmsparse_list_clear(struct pax *pax)
1989232153Smm{
1990232153Smm	while (pax->sparse_list != NULL) {
1991232153Smm		struct sparse_block *sb = pax->sparse_list;
1992232153Smm		pax->sparse_list = sb->next;
1993232153Smm		free(sb);
1994232153Smm	}
1995232153Smm	pax->sparse_tail = NULL;
1996232153Smm}
1997232153Smm
1998232153Smmstatic int
1999232153Smm_sparse_list_add_block(struct pax *pax, int64_t offset, int64_t length,
2000232153Smm    int is_hole)
2001232153Smm{
2002232153Smm	struct sparse_block *sb;
2003232153Smm
2004232153Smm	sb = (struct sparse_block *)malloc(sizeof(*sb));
2005232153Smm	if (sb == NULL)
2006232153Smm		return (ARCHIVE_FATAL);
2007232153Smm	sb->next = NULL;
2008232153Smm	sb->is_hole = is_hole;
2009232153Smm	sb->offset = offset;
2010232153Smm	sb->remaining = length;
2011248616Smm	if (pax->sparse_list == NULL || pax->sparse_tail == NULL)
2012232153Smm		pax->sparse_list = pax->sparse_tail = sb;
2013232153Smm	else {
2014232153Smm		pax->sparse_tail->next = sb;
2015232153Smm		pax->sparse_tail = sb;
2016232153Smm	}
2017232153Smm	return (ARCHIVE_OK);
2018232153Smm}
2019232153Smm
2020232153Smmstatic int
2021232153Smmsparse_list_add(struct pax *pax, int64_t offset, int64_t length)
2022232153Smm{
2023232153Smm	int64_t last_offset;
2024232153Smm	int r;
2025232153Smm
2026232153Smm	if (pax->sparse_tail == NULL)
2027232153Smm		last_offset = 0;
2028232153Smm	else {
2029232153Smm		last_offset = pax->sparse_tail->offset +
2030232153Smm		    pax->sparse_tail->remaining;
2031232153Smm	}
2032232153Smm	if (last_offset < offset) {
2033232153Smm		/* Add a hole block. */
2034232153Smm		r = _sparse_list_add_block(pax, last_offset,
2035232153Smm		    offset - last_offset, 1);
2036232153Smm		if (r != ARCHIVE_OK)
2037232153Smm			return (r);
2038232153Smm	}
2039232153Smm	/* Add data block. */
2040232153Smm	return (_sparse_list_add_block(pax, offset, length, 0));
2041232153Smm}
2042232153Smm
2043