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