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