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