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