2 * Copyright (c) 2003-2007 Tim Kientzle
3 * Copyright (c) 2010-2012 Michihiro NAKAJIMA
4 * Copyright (c) 2016 Martin Matuska
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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.
28 #include "archive_platform.h"
29 __FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_pax.c 201162 2009-12-29 05:47:46Z kientzle $");
42 #include "archive_entry.h"
43 #include "archive_entry_locale.h"
44 #include "archive_private.h"
45 #include "archive_write_private.h"
46 #include "archive_write_set_format_private.h"
49 struct sparse_block *next;
56 uint64_t entry_bytes_remaining;
57 uint64_t entry_padding;
58 struct archive_string l_url_encoded_name;
59 struct archive_string pax_header;
60 struct archive_string sparse_map;
61 size_t sparse_map_padding;
62 struct sparse_block *sparse_list;
63 struct sparse_block *sparse_tail;
64 struct archive_string_conv *sconv_utf8;
68 #define WRITE_SCHILY_XATTR (1 << 0)
69 #define WRITE_LIBARCHIVE_XATTR (1 << 1)
72 static void add_pax_attr(struct archive_string *, const char *key,
74 static void add_pax_attr_binary(struct archive_string *,
76 const char *value, size_t value_len);
77 static void add_pax_attr_int(struct archive_string *,
78 const char *key, int64_t value);
79 static void add_pax_attr_time(struct archive_string *,
80 const char *key, int64_t sec,
82 static int add_pax_acl(struct archive_write *,
83 struct archive_entry *, struct pax *, int);
84 static ssize_t archive_write_pax_data(struct archive_write *,
85 const void *, size_t);
86 static int archive_write_pax_close(struct archive_write *);
87 static int archive_write_pax_free(struct archive_write *);
88 static int archive_write_pax_finish_entry(struct archive_write *);
89 static int archive_write_pax_header(struct archive_write *,
90 struct archive_entry *);
91 static int archive_write_pax_options(struct archive_write *,
92 const char *, const char *);
93 static char *base64_encode(const char *src, size_t len);
94 static char *build_gnu_sparse_name(char *dest, const char *src);
95 static char *build_pax_attribute_name(char *dest, const char *src);
96 static char *build_ustar_entry_name(char *dest, const char *src,
97 size_t src_length, const char *insert);
98 static char *format_int(char *dest, int64_t);
99 static int has_non_ASCII(const char *);
100 static void sparse_list_clear(struct pax *);
101 static int sparse_list_add(struct pax *, int64_t, int64_t);
102 static char *url_encode(const char *in);
105 * Set output format to 'restricted pax' format.
107 * This is the same as normal 'pax', but tries to suppress
108 * the pax header whenever possible. This is the default for
109 * bsdtar, for instance.
112 archive_write_set_format_pax_restricted(struct archive *_a)
114 struct archive_write *a = (struct archive_write *)_a;
117 archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
118 ARCHIVE_STATE_NEW, "archive_write_set_format_pax_restricted");
120 r = archive_write_set_format_pax(&a->archive);
121 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
122 a->archive.archive_format_name = "restricted POSIX pax interchange";
127 * Set output format to 'pax' format.
130 archive_write_set_format_pax(struct archive *_a)
132 struct archive_write *a = (struct archive_write *)_a;
135 archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
136 ARCHIVE_STATE_NEW, "archive_write_set_format_pax");
138 if (a->format_free != NULL)
141 pax = (struct pax *)calloc(1, sizeof(*pax));
143 archive_set_error(&a->archive, ENOMEM,
144 "Can't allocate pax data");
145 return (ARCHIVE_FATAL);
147 pax->flags = WRITE_LIBARCHIVE_XATTR | WRITE_SCHILY_XATTR;
149 a->format_data = pax;
150 a->format_name = "pax";
151 a->format_options = archive_write_pax_options;
152 a->format_write_header = archive_write_pax_header;
153 a->format_write_data = archive_write_pax_data;
154 a->format_close = archive_write_pax_close;
155 a->format_free = archive_write_pax_free;
156 a->format_finish_entry = archive_write_pax_finish_entry;
157 a->archive.archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
158 a->archive.archive_format_name = "POSIX pax interchange";
163 archive_write_pax_options(struct archive_write *a, const char *key,
166 struct pax *pax = (struct pax *)a->format_data;
167 int ret = ARCHIVE_FAILED;
169 if (strcmp(key, "hdrcharset") == 0) {
171 * The character-set we can use are defined in
172 * IEEE Std 1003.1-2001
174 if (val == NULL || val[0] == 0)
175 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
176 "pax: hdrcharset option needs a character-set name");
177 else if (strcmp(val, "BINARY") == 0 ||
178 strcmp(val, "binary") == 0) {
180 * Specify binary mode. We will not convert
181 * filenames, uname and gname to any charsets.
185 } else if (strcmp(val, "UTF-8") == 0) {
187 * Specify UTF-8 character-set to be used for
188 * filenames. This is almost the test that
189 * running platform supports the string conversion.
190 * Especially libarchive_test needs this trick for
193 pax->sconv_utf8 = archive_string_conversion_to_charset(
194 &(a->archive), "UTF-8", 0);
195 if (pax->sconv_utf8 == NULL)
200 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
201 "pax: invalid charset name");
203 } else if (strcmp(key, "xattrheader") == 0) {
204 if (val == NULL || val[0] == 0) {
205 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
206 "pax: xattrheader requires a value");
207 } else if (strcmp(val, "ALL") == 0 ||
208 strcmp(val, "all") == 0) {
209 pax->flags |= WRITE_LIBARCHIVE_XATTR | WRITE_SCHILY_XATTR;
211 } else if (strcmp(val, "SCHILY") == 0 ||
212 strcmp(val, "schily") == 0) {
213 pax->flags |= WRITE_SCHILY_XATTR;
214 pax->flags &= ~WRITE_LIBARCHIVE_XATTR;
216 } else if (strcmp(val, "LIBARCHIVE") == 0 ||
217 strcmp(val, "libarchive") == 0) {
218 pax->flags |= WRITE_LIBARCHIVE_XATTR;
219 pax->flags &= ~WRITE_SCHILY_XATTR;
222 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
223 "pax: invalid xattr header name");
227 /* Note: The "warn" return is just to inform the options
228 * supervisor that we didn't handle it. It will generate
229 * a suitable error if no one used this option. */
230 return (ARCHIVE_WARN);
234 * Note: This code assumes that 'nanos' has the same sign as 'sec',
235 * which implies that sec=-1, nanos=200000000 represents -1.2 seconds
236 * and not -0.8 seconds. This is a pretty pedantic point, as we're
237 * unlikely to encounter many real files created before Jan 1, 1970,
238 * much less ones with timestamps recorded to sub-second resolution.
241 add_pax_attr_time(struct archive_string *as, const char *key,
242 int64_t sec, unsigned long nanos)
247 * Note that each byte contributes fewer than 3 base-10
248 * digits, so this will always be big enough.
250 char tmp[1 + 3*sizeof(sec) + 1 + 3*sizeof(nanos)];
252 tmp[sizeof(tmp) - 1] = 0;
253 t = tmp + sizeof(tmp) - 1;
255 /* Skip trailing zeros in the fractional part. */
256 for (digit = 0, i = 10; i > 0 && digit == 0; i--) {
261 /* Only format the fraction if it's non-zero. */
264 *--t = "0123456789"[digit];
271 t = format_int(t, sec);
273 add_pax_attr(as, key, t);
277 format_int(char *t, int64_t i)
282 ui = (i == INT64_MIN) ? (uint64_t)(INT64_MAX) + 1 : (uint64_t)(-i);
287 *--t = "0123456789"[ui % 10];
295 add_pax_attr_int(struct archive_string *as, const char *key, int64_t value)
297 char tmp[1 + 3 * sizeof(value)];
299 tmp[sizeof(tmp) - 1] = 0;
300 add_pax_attr(as, key, format_int(tmp + sizeof(tmp) - 1, value));
304 * Add a key/value attribute to the pax header. This function handles
305 * the length field and various other syntactic requirements.
308 add_pax_attr(struct archive_string *as, const char *key, const char *value)
310 add_pax_attr_binary(as, key, value, strlen(value));
314 * Add a key/value attribute to the pax header. This function handles
318 add_pax_attr_binary(struct archive_string *as, const char *key,
319 const char *value, size_t value_len)
321 int digits, i, len, next_ten;
322 char tmp[1 + 3 * sizeof(int)]; /* < 3 base-10 digits per byte */
325 * PAX attributes have the following layout:
326 * <len> <space> <key> <=> <value> <nl>
328 len = 1 + (int)strlen(key) + 1 + (int)value_len + 1;
331 * The <len> field includes the length of the <len> field, so
332 * computing the correct length is tricky. I start by
333 * counting the number of base-10 digits in 'len' and
334 * computing the next higher power of 10.
342 next_ten = next_ten * 10;
345 * For example, if string without the length field is 99
346 * chars, then adding the 2 digit length "99" will force the
347 * total length past 100, requiring an extra digit. The next
348 * statement adjusts for this effect.
350 if (len + digits >= next_ten)
353 /* Now, we have the right length so we can build the line. */
354 tmp[sizeof(tmp) - 1] = 0; /* Null-terminate the work area. */
355 archive_strcat(as, format_int(tmp + sizeof(tmp) - 1, len + digits));
356 archive_strappend_char(as, ' ');
357 archive_strcat(as, key);
358 archive_strappend_char(as, '=');
359 archive_array_append(as, value, value_len);
360 archive_strappend_char(as, '\n');
364 archive_write_pax_header_xattr(struct pax *pax, const char *encoded_name,
365 const void *value, size_t value_len)
367 struct archive_string s;
370 if (pax->flags & WRITE_LIBARCHIVE_XATTR) {
371 encoded_value = base64_encode((const char *)value, value_len);
373 if (encoded_name != NULL && encoded_value != NULL) {
374 archive_string_init(&s);
375 archive_strcpy(&s, "LIBARCHIVE.xattr.");
376 archive_strcat(&s, encoded_name);
377 add_pax_attr(&(pax->pax_header), s.s, encoded_value);
378 archive_string_free(&s);
382 if (pax->flags & WRITE_SCHILY_XATTR) {
383 archive_string_init(&s);
384 archive_strcpy(&s, "SCHILY.xattr.");
385 archive_strcat(&s, encoded_name);
386 add_pax_attr_binary(&(pax->pax_header), s.s, value, value_len);
387 archive_string_free(&s);
392 archive_write_pax_header_xattrs(struct archive_write *a,
393 struct pax *pax, struct archive_entry *entry)
395 int i = archive_entry_xattr_reset(entry);
400 char *url_encoded_name = NULL, *encoded_name = NULL;
404 archive_entry_xattr_next(entry, &name, &value, &size);
405 url_encoded_name = url_encode(name);
406 if (url_encoded_name != NULL) {
407 /* Convert narrow-character to UTF-8. */
408 r = archive_strcpy_l(&(pax->l_url_encoded_name),
409 url_encoded_name, pax->sconv_utf8);
410 free(url_encoded_name); /* Done with this. */
412 encoded_name = pax->l_url_encoded_name.s;
413 else if (errno == ENOMEM) {
414 archive_set_error(&a->archive, ENOMEM,
415 "Can't allocate memory for Linkname");
416 return (ARCHIVE_FATAL);
420 archive_write_pax_header_xattr(pax, encoded_name,
428 get_entry_hardlink(struct archive_write *a, struct archive_entry *entry,
429 const char **name, size_t *length, struct archive_string_conv *sc)
433 r = archive_entry_hardlink_l(entry, name, length, sc);
435 if (errno == ENOMEM) {
436 archive_set_error(&a->archive, ENOMEM,
437 "Can't allocate memory for Linkname");
438 return (ARCHIVE_FATAL);
440 return (ARCHIVE_WARN);
446 get_entry_pathname(struct archive_write *a, struct archive_entry *entry,
447 const char **name, size_t *length, struct archive_string_conv *sc)
451 r = archive_entry_pathname_l(entry, name, length, sc);
453 if (errno == ENOMEM) {
454 archive_set_error(&a->archive, ENOMEM,
455 "Can't allocate memory for Pathname");
456 return (ARCHIVE_FATAL);
458 return (ARCHIVE_WARN);
464 get_entry_uname(struct archive_write *a, struct archive_entry *entry,
465 const char **name, size_t *length, struct archive_string_conv *sc)
469 r = archive_entry_uname_l(entry, name, length, sc);
471 if (errno == ENOMEM) {
472 archive_set_error(&a->archive, ENOMEM,
473 "Can't allocate memory for Uname");
474 return (ARCHIVE_FATAL);
476 return (ARCHIVE_WARN);
482 get_entry_gname(struct archive_write *a, struct archive_entry *entry,
483 const char **name, size_t *length, struct archive_string_conv *sc)
487 r = archive_entry_gname_l(entry, name, length, sc);
489 if (errno == ENOMEM) {
490 archive_set_error(&a->archive, ENOMEM,
491 "Can't allocate memory for Gname");
492 return (ARCHIVE_FATAL);
494 return (ARCHIVE_WARN);
500 get_entry_symlink(struct archive_write *a, struct archive_entry *entry,
501 const char **name, size_t *length, struct archive_string_conv *sc)
505 r = archive_entry_symlink_l(entry, name, length, sc);
507 if (errno == ENOMEM) {
508 archive_set_error(&a->archive, ENOMEM,
509 "Can't allocate memory for Linkname");
510 return (ARCHIVE_FATAL);
512 return (ARCHIVE_WARN);
517 /* Add ACL to pax header */
519 add_pax_acl(struct archive_write *a,
520 struct archive_entry *entry, struct pax *pax, int flags)
526 acl_types = archive_entry_acl_types(entry);
528 if ((acl_types & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0)
529 attr = "SCHILY.acl.ace";
530 else if ((flags & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0)
531 attr = "SCHILY.acl.access";
532 else if ((flags & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0)
533 attr = "SCHILY.acl.default";
535 return (ARCHIVE_FATAL);
537 p = archive_entry_acl_to_text_l(entry, NULL, flags, pax->sconv_utf8);
539 if (errno == ENOMEM) {
540 archive_set_error(&a->archive, ENOMEM, "%s %s",
541 "Can't allocate memory for ", attr);
542 return (ARCHIVE_FATAL);
544 archive_set_error(&a->archive,
545 ARCHIVE_ERRNO_FILE_FORMAT, "%s %s %s",
546 "Can't translate ", attr, " to UTF-8");
547 return(ARCHIVE_WARN);
551 add_pax_attr(&(pax->pax_header),
559 * TODO: Consider adding 'comment' and 'charset' fields to
560 * archive_entry so that clients can specify them. Also, consider
561 * adding generic key/value tags so clients can add arbitrary
564 * TODO: Break up this 700-line function!!!! Yowza!
567 archive_write_pax_header(struct archive_write *a,
568 struct archive_entry *entry_original)
570 struct archive_entry *entry_main;
573 int need_extension, r, ret;
576 uint64_t sparse_total, real_size;
578 const char *hardlink;
579 const char *path = NULL, *linkpath = NULL;
580 const char *uname = NULL, *gname = NULL;
581 const void *mac_metadata;
582 size_t mac_metadata_size;
583 struct archive_string_conv *sconv;
584 size_t hardlink_length, path_length, linkpath_length;
585 size_t uname_length, gname_length;
589 char ustar_entry_name[256];
590 char pax_entry_name[256];
591 char gnu_sparse_name[256];
592 struct archive_string entry_name;
596 pax = (struct pax *)a->format_data;
599 if (archive_entry_pathname(entry_original) == NULL) {
600 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
601 "Can't record entry in tar file without pathname");
602 return (ARCHIVE_FAILED);
606 * Choose a header encoding.
609 sconv = NULL;/* Binary mode. */
611 /* Header encoding is UTF-8. */
612 if (pax->sconv_utf8 == NULL) {
613 /* Initialize the string conversion object
615 pax->sconv_utf8 = archive_string_conversion_to_charset(
616 &(a->archive), "UTF-8", 1);
617 if (pax->sconv_utf8 == NULL)
618 /* Couldn't allocate memory */
619 return (ARCHIVE_FAILED);
621 sconv = pax->sconv_utf8;
624 r = get_entry_hardlink(a, entry_original, &hardlink,
625 &hardlink_length, sconv);
626 if (r == ARCHIVE_FATAL)
628 else if (r != ARCHIVE_OK) {
629 r = get_entry_hardlink(a, entry_original, &hardlink,
630 &hardlink_length, NULL);
631 if (r == ARCHIVE_FATAL)
633 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
634 "Can't translate linkname '%s' to %s", hardlink,
635 archive_string_conversion_charset_name(sconv));
637 sconv = NULL;/* The header charset switches to binary mode. */
640 /* Make sure this is a type of entry that we can handle here */
641 if (hardlink == NULL) {
642 switch (archive_entry_filetype(entry_original)) {
652 * Ensure a trailing '/'. Modify the original
653 * entry so the client sees the change.
655 #if defined(_WIN32) && !defined(__CYGWIN__)
658 wp = archive_entry_pathname_w(entry_original);
659 if (wp != NULL && wp[wcslen(wp) -1] != L'/') {
660 struct archive_wstring ws;
662 archive_string_init(&ws);
663 path_length = wcslen(wp);
664 if (archive_wstring_ensure(&ws,
665 path_length + 2) == NULL) {
666 archive_set_error(&a->archive, ENOMEM,
667 "Can't allocate pax data");
668 archive_wstring_free(&ws);
669 return(ARCHIVE_FATAL);
671 /* Should we keep '\' ? */
672 if (wp[path_length -1] == L'\\')
674 archive_wstrncpy(&ws, wp, path_length);
675 archive_wstrappend_wchar(&ws, L'/');
676 archive_entry_copy_pathname_w(
677 entry_original, ws.s);
678 archive_wstring_free(&ws);
682 p = archive_entry_pathname(entry_original);
684 * On Windows, this is a backup operation just in
685 * case getting WCS failed. On POSIX, this is a
688 if (p != NULL && p[0] != '\0' && p[strlen(p) - 1] != '/') {
689 struct archive_string as;
691 archive_string_init(&as);
692 path_length = strlen(p);
693 if (archive_string_ensure(&as,
694 path_length + 2) == NULL) {
695 archive_set_error(&a->archive, ENOMEM,
696 "Can't allocate pax data");
697 archive_string_free(&as);
698 return(ARCHIVE_FATAL);
700 #if defined(_WIN32) && !defined(__CYGWIN__)
701 /* NOTE: This might break the pathname
702 * if the current code page is CP932 and
703 * the pathname includes a character '\'
704 * as a part of its multibyte pathname. */
705 if (p[strlen(p) -1] == '\\')
709 archive_strncpy(&as, p, path_length);
710 archive_strappend_char(&as, '/');
711 archive_entry_copy_pathname(
712 entry_original, as.s);
713 archive_string_free(&as);
717 default: /* AE_IFSOCK and unknown */
718 __archive_write_entry_filetype_unsupported(
719 &a->archive, entry_original, "pax");
720 return (ARCHIVE_FAILED);
725 * If Mac OS metadata blob is here, recurse to write that
726 * as a separate entry. This is really a pretty poor design:
727 * In particular, it doubles the overhead for long filenames.
728 * TODO: Help Apple folks design something better and figure
729 * out how to transition from this legacy format.
731 * Note that this code is present on every platform; clients
732 * on non-Mac are unlikely to ever provide this data, but
733 * applications that copy entries from one archive to another
734 * should not lose data just because the local filesystem
738 archive_entry_mac_metadata(entry_original, &mac_metadata_size);
739 if (mac_metadata != NULL) {
743 struct archive_entry *extra = archive_entry_new2(&a->archive);
745 oname = archive_entry_pathname(entry_original);
746 name_length = strlen(oname);
747 name = malloc(name_length + 3);
748 if (name == NULL || extra == NULL) {
749 /* XXX error message */
750 archive_entry_free(extra);
752 return (ARCHIVE_FAILED);
755 /* Find last '/'; strip trailing '/' characters */
756 bname = strrchr(name, '/');
757 while (bname != NULL && bname[1] == '\0') {
759 bname = strrchr(name, '/');
762 memmove(name + 2, name, name_length + 1);
763 memmove(name, "._", 2);
766 memmove(bname + 2, bname, strlen(bname) + 1);
767 memmove(bname, "._", 2);
769 archive_entry_copy_pathname(extra, name);
772 archive_entry_set_size(extra, mac_metadata_size);
773 archive_entry_set_filetype(extra, AE_IFREG);
774 archive_entry_set_perm(extra,
775 archive_entry_perm(entry_original));
776 archive_entry_set_mtime(extra,
777 archive_entry_mtime(entry_original),
778 archive_entry_mtime_nsec(entry_original));
779 archive_entry_set_gid(extra,
780 archive_entry_gid(entry_original));
781 archive_entry_set_gname(extra,
782 archive_entry_gname(entry_original));
783 archive_entry_set_uid(extra,
784 archive_entry_uid(entry_original));
785 archive_entry_set_uname(extra,
786 archive_entry_uname(entry_original));
788 /* Recurse to write the special copyfile entry. */
789 r = archive_write_pax_header(a, extra);
790 archive_entry_free(extra);
791 if (r < ARCHIVE_WARN)
795 r = (int)archive_write_pax_data(a, mac_metadata,
797 if (r < ARCHIVE_WARN)
801 r = archive_write_pax_finish_entry(a);
802 if (r < ARCHIVE_WARN)
808 /* Copy entry so we can modify it as needed. */
809 #if defined(_WIN32) && !defined(__CYGWIN__)
810 /* Make sure the path separators in pathname, hardlink and symlink
811 * are all slash '/', not the Windows path separator '\'. */
812 entry_main = __la_win_entry_in_posix_pathseparator(entry_original);
813 if (entry_main == entry_original)
814 entry_main = archive_entry_clone(entry_original);
816 entry_main = archive_entry_clone(entry_original);
818 if (entry_main == NULL) {
819 archive_set_error(&a->archive, ENOMEM,
820 "Can't allocate pax data");
821 return(ARCHIVE_FATAL);
823 archive_string_empty(&(pax->pax_header)); /* Blank our work area. */
824 archive_string_empty(&(pax->sparse_map));
826 sparse_list_clear(pax);
828 if (hardlink == NULL &&
829 archive_entry_filetype(entry_main) == AE_IFREG)
830 sparse_count = archive_entry_sparse_reset(entry_main);
834 int64_t offset, length, last_offset = 0;
835 /* Get the last entry of sparse block. */
836 while (archive_entry_sparse_next(
837 entry_main, &offset, &length) == ARCHIVE_OK)
838 last_offset = offset + length;
840 /* If the last sparse block does not reach the end of file,
841 * We have to add a empty sparse block as the last entry to
842 * manage storing file data. */
843 if (last_offset < archive_entry_size(entry_main))
844 archive_entry_sparse_add_entry(entry_main,
845 archive_entry_size(entry_main), 0);
846 sparse_count = archive_entry_sparse_reset(entry_main);
850 * First, check the name fields and see if any of them
851 * require binary coding. If any of them does, then all of
854 r = get_entry_pathname(a, entry_main, &path, &path_length, sconv);
855 if (r == ARCHIVE_FATAL) {
856 archive_entry_free(entry_main);
858 } else if (r != ARCHIVE_OK) {
859 r = get_entry_pathname(a, entry_main, &path,
861 if (r == ARCHIVE_FATAL) {
862 archive_entry_free(entry_main);
865 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
866 "Can't translate pathname '%s' to %s", path,
867 archive_string_conversion_charset_name(sconv));
869 sconv = NULL;/* The header charset switches to binary mode. */
871 r = get_entry_uname(a, entry_main, &uname, &uname_length, sconv);
872 if (r == ARCHIVE_FATAL) {
873 archive_entry_free(entry_main);
875 } else if (r != ARCHIVE_OK) {
876 r = get_entry_uname(a, entry_main, &uname, &uname_length, NULL);
877 if (r == ARCHIVE_FATAL) {
878 archive_entry_free(entry_main);
881 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
882 "Can't translate uname '%s' to %s", uname,
883 archive_string_conversion_charset_name(sconv));
885 sconv = NULL;/* The header charset switches to binary mode. */
887 r = get_entry_gname(a, entry_main, &gname, &gname_length, sconv);
888 if (r == ARCHIVE_FATAL) {
889 archive_entry_free(entry_main);
891 } else if (r != ARCHIVE_OK) {
892 r = get_entry_gname(a, entry_main, &gname, &gname_length, NULL);
893 if (r == ARCHIVE_FATAL) {
894 archive_entry_free(entry_main);
897 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
898 "Can't translate gname '%s' to %s", gname,
899 archive_string_conversion_charset_name(sconv));
901 sconv = NULL;/* The header charset switches to binary mode. */
904 linkpath_length = hardlink_length;
905 if (linkpath == NULL) {
906 r = get_entry_symlink(a, entry_main, &linkpath,
907 &linkpath_length, sconv);
908 if (r == ARCHIVE_FATAL) {
909 archive_entry_free(entry_main);
911 } else if (r != ARCHIVE_OK) {
912 r = get_entry_symlink(a, entry_main, &linkpath,
913 &linkpath_length, NULL);
914 if (r == ARCHIVE_FATAL) {
915 archive_entry_free(entry_main);
918 archive_set_error(&a->archive,
919 ARCHIVE_ERRNO_FILE_FORMAT,
920 "Can't translate linkname '%s' to %s", linkpath,
921 archive_string_conversion_charset_name(sconv));
927 /* If any string conversions failed, get all attributes
929 if (sconv == NULL && !pax->opt_binary) {
930 if (hardlink != NULL) {
931 r = get_entry_hardlink(a, entry_main, &hardlink,
932 &hardlink_length, NULL);
933 if (r == ARCHIVE_FATAL) {
934 archive_entry_free(entry_main);
938 linkpath_length = hardlink_length;
940 r = get_entry_pathname(a, entry_main, &path,
942 if (r == ARCHIVE_FATAL) {
943 archive_entry_free(entry_main);
946 r = get_entry_uname(a, entry_main, &uname, &uname_length, NULL);
947 if (r == ARCHIVE_FATAL) {
948 archive_entry_free(entry_main);
951 r = get_entry_gname(a, entry_main, &gname, &gname_length, NULL);
952 if (r == ARCHIVE_FATAL) {
953 archive_entry_free(entry_main);
958 /* Store the header encoding first, to be nice to readers. */
960 add_pax_attr(&(pax->pax_header), "hdrcharset", "BINARY");
964 * If name is too long, or has non-ASCII characters, add
965 * 'path' to pax extended attrs. (Note that an unconvertible
966 * name must have non-ASCII characters.)
968 if (has_non_ASCII(path)) {
969 /* We have non-ASCII characters. */
970 add_pax_attr(&(pax->pax_header), "path", path);
971 archive_entry_set_pathname(entry_main,
972 build_ustar_entry_name(ustar_entry_name,
973 path, path_length, NULL));
976 /* We have an all-ASCII path; we'd like to just store
977 * it in the ustar header if it will fit. Yes, this
978 * duplicates some of the logic in
979 * archive_write_set_format_ustar.c
981 if (path_length <= 100) {
982 /* Fits in the old 100-char tar name field. */
984 /* Find largest suffix that will fit. */
985 /* Note: strlen() > 100, so strlen() - 100 - 1 >= 0 */
986 suffix = strchr(path + path_length - 100 - 1, '/');
987 /* Don't attempt an empty prefix. */
989 suffix = strchr(suffix + 1, '/');
990 /* We can put it in the ustar header if it's
991 * all ASCII and it's either <= 100 characters
992 * or can be split at a '/' into a prefix <=
993 * 155 chars and a suffix <= 100 chars. (Note
994 * the strchr() above will return NULL exactly
995 * when the path can't be split.)
997 if (suffix == NULL /* Suffix > 100 chars. */
998 || suffix[1] == '\0' /* empty suffix */
999 || suffix - path > 155) /* Prefix > 155 chars */
1001 add_pax_attr(&(pax->pax_header), "path", path);
1002 archive_entry_set_pathname(entry_main,
1003 build_ustar_entry_name(ustar_entry_name,
1004 path, path_length, NULL));
1010 if (linkpath != NULL) {
1011 /* If link name is too long or has non-ASCII characters, add
1012 * 'linkpath' to pax extended attrs. */
1013 if (linkpath_length > 100 || has_non_ASCII(linkpath)) {
1014 add_pax_attr(&(pax->pax_header), "linkpath", linkpath);
1015 if (linkpath_length > 100) {
1016 if (hardlink != NULL)
1017 archive_entry_set_hardlink(entry_main,
1018 "././@LongHardLink");
1020 archive_entry_set_symlink(entry_main,
1021 "././@LongSymLink");
1026 /* Save a pathname since it will be renamed if `entry_main` has
1028 archive_string_init(&entry_name);
1029 archive_strcpy(&entry_name, archive_entry_pathname(entry_main));
1031 /* If file size is too large, add 'size' to pax extended attrs. */
1032 if (archive_entry_size(entry_main) >= (((int64_t)1) << 33)) {
1033 add_pax_attr_int(&(pax->pax_header), "size",
1034 archive_entry_size(entry_main));
1038 /* If numeric GID is too large, add 'gid' to pax extended attrs. */
1039 if ((unsigned int)archive_entry_gid(entry_main) >= (1 << 18)) {
1040 add_pax_attr_int(&(pax->pax_header), "gid",
1041 archive_entry_gid(entry_main));
1045 /* If group name is too large or has non-ASCII characters, add
1046 * 'gname' to pax extended attrs. */
1047 if (gname != NULL) {
1048 if (gname_length > 31 || has_non_ASCII(gname)) {
1049 add_pax_attr(&(pax->pax_header), "gname", gname);
1054 /* If numeric UID is too large, add 'uid' to pax extended attrs. */
1055 if ((unsigned int)archive_entry_uid(entry_main) >= (1 << 18)) {
1056 add_pax_attr_int(&(pax->pax_header), "uid",
1057 archive_entry_uid(entry_main));
1061 /* Add 'uname' to pax extended attrs if necessary. */
1062 if (uname != NULL) {
1063 if (uname_length > 31 || has_non_ASCII(uname)) {
1064 add_pax_attr(&(pax->pax_header), "uname", uname);
1070 * POSIX/SUSv3 doesn't provide a standard key for large device
1071 * numbers. I use the same keys here that Joerg Schilling
1072 * used for 'star.' (Which, somewhat confusingly, are called
1073 * "devXXX" even though they code "rdev" values.) No doubt,
1074 * other implementations use other keys. Note that there's no
1075 * reason we can't write the same information into a number of
1078 * Of course, this is only needed for block or char device entries.
1080 if (archive_entry_filetype(entry_main) == AE_IFBLK
1081 || archive_entry_filetype(entry_main) == AE_IFCHR) {
1083 * If rdevmajor is too large, add 'SCHILY.devmajor' to
1084 * extended attributes.
1086 int rdevmajor, rdevminor;
1087 rdevmajor = archive_entry_rdevmajor(entry_main);
1088 rdevminor = archive_entry_rdevminor(entry_main);
1089 if (rdevmajor >= (1 << 18)) {
1090 add_pax_attr_int(&(pax->pax_header), "SCHILY.devmajor",
1093 * Non-strict formatting below means we don't
1094 * have to truncate here. Not truncating improves
1095 * the chance that some more modern tar archivers
1096 * (such as GNU tar 1.13) can restore the full
1097 * value even if they don't understand the pax
1098 * extended attributes. See my rant below about
1099 * file size fields for additional details.
1101 /* archive_entry_set_rdevmajor(entry_main,
1102 rdevmajor & ((1 << 18) - 1)); */
1107 * If devminor is too large, add 'SCHILY.devminor' to
1108 * extended attributes.
1110 if (rdevminor >= (1 << 18)) {
1111 add_pax_attr_int(&(pax->pax_header), "SCHILY.devminor",
1113 /* Truncation is not necessary here, either. */
1114 /* archive_entry_set_rdevminor(entry_main,
1115 rdevminor & ((1 << 18) - 1)); */
1121 * Technically, the mtime field in the ustar header can
1122 * support 33 bits, but many platforms use signed 32-bit time
1123 * values. The cutoff of 0x7fffffff here is a compromise.
1124 * Yes, this check is duplicated just below; this helps to
1125 * avoid writing an mtime attribute just to handle a
1126 * high-resolution timestamp in "restricted pax" mode.
1128 if (!need_extension &&
1129 ((archive_entry_mtime(entry_main) < 0)
1130 || (archive_entry_mtime(entry_main) >= 0x7fffffff)))
1133 /* I use a star-compatible file flag attribute. */
1134 p = archive_entry_fflags_text(entry_main);
1135 if (!need_extension && p != NULL && *p != '\0')
1138 /* If there are extended attributes, we need an extension */
1139 if (!need_extension && archive_entry_xattr_count(entry_original) > 0)
1142 /* If there are sparse info, we need an extension */
1143 if (!need_extension && sparse_count > 0)
1146 acl_types = archive_entry_acl_types(entry_original);
1148 /* If there are any ACL entries, we need an extension */
1149 if (!need_extension && acl_types != 0)
1152 /* If the symlink type is defined, we need an extension */
1153 if (!need_extension && archive_entry_symlink_type(entry_main) > 0)
1157 * Libarchive used to include these in extended headers for
1158 * restricted pax format, but that confused people who
1159 * expected ustar-like time semantics. So now we only include
1160 * them in full pax format.
1162 if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED) {
1163 if (archive_entry_ctime(entry_main) != 0 ||
1164 archive_entry_ctime_nsec(entry_main) != 0)
1165 add_pax_attr_time(&(pax->pax_header), "ctime",
1166 archive_entry_ctime(entry_main),
1167 archive_entry_ctime_nsec(entry_main));
1169 if (archive_entry_atime(entry_main) != 0 ||
1170 archive_entry_atime_nsec(entry_main) != 0)
1171 add_pax_attr_time(&(pax->pax_header), "atime",
1172 archive_entry_atime(entry_main),
1173 archive_entry_atime_nsec(entry_main));
1175 /* Store birth/creationtime only if it's earlier than mtime */
1176 if (archive_entry_birthtime_is_set(entry_main) &&
1177 archive_entry_birthtime(entry_main)
1178 < archive_entry_mtime(entry_main))
1179 add_pax_attr_time(&(pax->pax_header),
1180 "LIBARCHIVE.creationtime",
1181 archive_entry_birthtime(entry_main),
1182 archive_entry_birthtime_nsec(entry_main));
1186 * The following items are handled differently in "pax
1187 * restricted" format. In particular, in "pax restricted"
1188 * format they won't be added unless need_extension is
1189 * already set (we're already generating an extended header, so
1190 * may as well include these).
1192 if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED ||
1194 if (archive_entry_mtime(entry_main) < 0 ||
1195 archive_entry_mtime(entry_main) >= 0x7fffffff ||
1196 archive_entry_mtime_nsec(entry_main) != 0)
1197 add_pax_attr_time(&(pax->pax_header), "mtime",
1198 archive_entry_mtime(entry_main),
1199 archive_entry_mtime_nsec(entry_main));
1201 /* I use a star-compatible file flag attribute. */
1202 p = archive_entry_fflags_text(entry_main);
1203 if (p != NULL && *p != '\0')
1204 add_pax_attr(&(pax->pax_header), "SCHILY.fflags", p);
1206 /* I use star-compatible ACL attributes. */
1207 if ((acl_types & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) {
1208 ret = add_pax_acl(a, entry_original, pax,
1209 ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID |
1210 ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA |
1211 ARCHIVE_ENTRY_ACL_STYLE_COMPACT);
1212 if (ret == ARCHIVE_FATAL) {
1213 archive_entry_free(entry_main);
1214 archive_string_free(&entry_name);
1215 return (ARCHIVE_FATAL);
1218 if (acl_types & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) {
1219 ret = add_pax_acl(a, entry_original, pax,
1220 ARCHIVE_ENTRY_ACL_TYPE_ACCESS |
1221 ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID |
1222 ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA);
1223 if (ret == ARCHIVE_FATAL) {
1224 archive_entry_free(entry_main);
1225 archive_string_free(&entry_name);
1226 return (ARCHIVE_FATAL);
1229 if (acl_types & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) {
1230 ret = add_pax_acl(a, entry_original, pax,
1231 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT |
1232 ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID |
1233 ARCHIVE_ENTRY_ACL_STYLE_SEPARATOR_COMMA);
1234 if (ret == ARCHIVE_FATAL) {
1235 archive_entry_free(entry_main);
1236 archive_string_free(&entry_name);
1237 return (ARCHIVE_FATAL);
1241 /* We use GNU-tar-compatible sparse attributes. */
1242 if (sparse_count > 0) {
1243 int64_t soffset, slength;
1245 add_pax_attr_int(&(pax->pax_header),
1246 "GNU.sparse.major", 1);
1247 add_pax_attr_int(&(pax->pax_header),
1248 "GNU.sparse.minor", 0);
1250 * Make sure to store the original path, since
1251 * truncation to ustar limit happened already.
1253 add_pax_attr(&(pax->pax_header),
1254 "GNU.sparse.name", path);
1255 add_pax_attr_int(&(pax->pax_header),
1256 "GNU.sparse.realsize",
1257 archive_entry_size(entry_main));
1259 /* Rename the file name which will be used for
1260 * ustar header to a special name, which GNU
1261 * PAX Format 1.0 requires */
1262 archive_entry_set_pathname(entry_main,
1263 build_gnu_sparse_name(gnu_sparse_name,
1267 * - Make a sparse map, which will precede a file data.
1268 * - Get the total size of available data of sparse.
1270 archive_string_sprintf(&(pax->sparse_map), "%d\n",
1272 while (archive_entry_sparse_next(entry_main,
1273 &soffset, &slength) == ARCHIVE_OK) {
1274 archive_string_sprintf(&(pax->sparse_map),
1278 sparse_total += slength;
1279 if (sparse_list_add(pax, soffset, slength)
1281 archive_set_error(&a->archive,
1283 "Can't allocate memory");
1284 archive_entry_free(entry_main);
1285 archive_string_free(&entry_name);
1286 return (ARCHIVE_FATAL);
1291 /* Store extended attributes */
1292 if (archive_write_pax_header_xattrs(a, pax, entry_original)
1294 archive_entry_free(entry_main);
1295 archive_string_free(&entry_name);
1296 return (ARCHIVE_FATAL);
1299 /* Store extended symlink information */
1300 if (archive_entry_symlink_type(entry_main) ==
1301 AE_SYMLINK_TYPE_FILE) {
1302 add_pax_attr(&(pax->pax_header),
1303 "LIBARCHIVE.symlinktype", "file");
1304 } else if (archive_entry_symlink_type(entry_main) ==
1305 AE_SYMLINK_TYPE_DIRECTORY) {
1306 add_pax_attr(&(pax->pax_header),
1307 "LIBARCHIVE.symlinktype", "dir");
1311 /* Only regular files have data. */
1312 if (archive_entry_filetype(entry_main) != AE_IFREG)
1313 archive_entry_set_size(entry_main, 0);
1316 * Pax-restricted does not store data for hardlinks, in order
1317 * to improve compatibility with ustar.
1319 if (a->archive.archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
1321 archive_entry_set_size(entry_main, 0);
1324 * XXX Full pax interchange format does permit a hardlink
1325 * entry to have data associated with it. I'm not supporting
1326 * that here because the client expects me to tell them whether
1327 * or not this format expects data for hardlinks. If I
1328 * don't check here, then every pax archive will end up with
1329 * duplicated data for hardlinks. Someday, there may be
1330 * need to select this behavior, in which case the following
1331 * will need to be revisited. XXX
1333 if (hardlink != NULL)
1334 archive_entry_set_size(entry_main, 0);
1336 /* Save a real file size. */
1337 real_size = archive_entry_size(entry_main);
1339 * Overwrite a file size by the total size of sparse blocks and
1340 * the size of sparse map info. That file size is the length of
1341 * the data, which we will exactly store into an archive file.
1343 if (archive_strlen(&(pax->sparse_map))) {
1344 size_t mapsize = archive_strlen(&(pax->sparse_map));
1345 pax->sparse_map_padding = 0x1ff & (-(ssize_t)mapsize);
1346 archive_entry_set_size(entry_main,
1347 mapsize + pax->sparse_map_padding + sparse_total);
1350 /* Format 'ustar' header for main entry.
1352 * The trouble with file size: If the reader can't understand
1353 * the file size, they may not be able to locate the next
1354 * entry and the rest of the archive is toast. Pax-compliant
1355 * readers are supposed to ignore the file size in the main
1356 * header, so the question becomes how to maximize portability
1357 * for readers that don't support pax attribute extensions.
1358 * For maximum compatibility, I permit numeric extensions in
1359 * the main header so that the file size stored will always be
1360 * correct, even if it's in a format that only some
1361 * implementations understand. The technique used here is:
1363 * a) If possible, follow the standard exactly. This handles
1364 * files up to 8 gigabytes minus 1.
1366 * b) If that fails, try octal but omit the field terminator.
1367 * That handles files up to 64 gigabytes minus 1.
1369 * c) Otherwise, use base-256 extensions. That handles files
1370 * up to 2^63 in this implementation, with the potential to
1371 * go up to 2^94. That should hold us for a while. ;-)
1373 * The non-strict formatter uses similar logic for other
1374 * numeric fields, though they're less critical.
1376 if (__archive_write_format_header_ustar(a, ustarbuff, entry_main, -1, 0,
1377 NULL) == ARCHIVE_FATAL) {
1378 archive_entry_free(entry_main);
1379 archive_string_free(&entry_name);
1380 return (ARCHIVE_FATAL);
1383 /* If we built any extended attributes, write that entry first. */
1384 if (archive_strlen(&(pax->pax_header)) > 0) {
1385 struct archive_entry *pax_attr_entry;
1390 pax_attr_entry = archive_entry_new2(&a->archive);
1392 archive_entry_set_pathname(pax_attr_entry,
1393 build_pax_attribute_name(pax_entry_name, p));
1394 archive_entry_set_size(pax_attr_entry,
1395 archive_strlen(&(pax->pax_header)));
1396 /* Copy uid/gid (but clip to ustar limits). */
1397 uid = archive_entry_uid(entry_main);
1399 uid = (1 << 18) - 1;
1400 archive_entry_set_uid(pax_attr_entry, uid);
1401 gid = archive_entry_gid(entry_main);
1403 gid = (1 << 18) - 1;
1404 archive_entry_set_gid(pax_attr_entry, gid);
1405 /* Copy mode over (but not setuid/setgid bits) */
1406 mode = archive_entry_mode(entry_main);
1416 archive_entry_set_mode(pax_attr_entry, mode);
1418 /* Copy uname/gname. */
1419 archive_entry_set_uname(pax_attr_entry,
1420 archive_entry_uname(entry_main));
1421 archive_entry_set_gname(pax_attr_entry,
1422 archive_entry_gname(entry_main));
1424 /* Copy mtime, but clip to ustar limits. */
1425 s = archive_entry_mtime(entry_main);
1426 if (s < 0) { s = 0; }
1427 if (s >= 0x7fffffff) { s = 0x7fffffff; }
1428 archive_entry_set_mtime(pax_attr_entry, s, 0);
1430 /* Standard ustar doesn't support atime. */
1431 archive_entry_set_atime(pax_attr_entry, 0, 0);
1433 /* Standard ustar doesn't support ctime. */
1434 archive_entry_set_ctime(pax_attr_entry, 0, 0);
1436 r = __archive_write_format_header_ustar(a, paxbuff,
1437 pax_attr_entry, 'x', 1, NULL);
1439 archive_entry_free(pax_attr_entry);
1441 /* Note that the 'x' header shouldn't ever fail to format */
1442 if (r < ARCHIVE_WARN) {
1443 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1444 "archive_write_pax_header: "
1445 "'x' header failed?! This can't happen.\n");
1446 archive_entry_free(entry_main);
1447 archive_string_free(&entry_name);
1448 return (ARCHIVE_FATAL);
1451 r = __archive_write_output(a, paxbuff, 512);
1452 if (r != ARCHIVE_OK) {
1453 sparse_list_clear(pax);
1454 pax->entry_bytes_remaining = 0;
1455 pax->entry_padding = 0;
1456 archive_entry_free(entry_main);
1457 archive_string_free(&entry_name);
1458 return (ARCHIVE_FATAL);
1461 pax->entry_bytes_remaining = archive_strlen(&(pax->pax_header));
1462 pax->entry_padding =
1463 0x1ff & (-(int64_t)pax->entry_bytes_remaining);
1465 r = __archive_write_output(a, pax->pax_header.s,
1466 archive_strlen(&(pax->pax_header)));
1467 if (r != ARCHIVE_OK) {
1468 /* If a write fails, we're pretty much toast. */
1469 archive_entry_free(entry_main);
1470 archive_string_free(&entry_name);
1471 return (ARCHIVE_FATAL);
1473 /* Pad out the end of the entry. */
1474 r = __archive_write_nulls(a, (size_t)pax->entry_padding);
1475 if (r != ARCHIVE_OK) {
1476 /* If a write fails, we're pretty much toast. */
1477 archive_entry_free(entry_main);
1478 archive_string_free(&entry_name);
1479 return (ARCHIVE_FATAL);
1481 pax->entry_bytes_remaining = pax->entry_padding = 0;
1484 /* Write the header for main entry. */
1485 r = __archive_write_output(a, ustarbuff, 512);
1486 if (r != ARCHIVE_OK) {
1487 archive_entry_free(entry_main);
1488 archive_string_free(&entry_name);
1493 * Inform the client of the on-disk size we're using, so
1494 * they can avoid unnecessarily writing a body for something
1495 * that we're just going to ignore.
1497 archive_entry_set_size(entry_original, real_size);
1498 if (pax->sparse_list == NULL && real_size > 0) {
1499 /* This is not a sparse file but we handle its data as
1500 * a sparse block. */
1501 sparse_list_add(pax, 0, real_size);
1502 sparse_total = real_size;
1504 pax->entry_padding = 0x1ff & (-(int64_t)sparse_total);
1505 archive_entry_free(entry_main);
1506 archive_string_free(&entry_name);
1512 * We need a valid name for the regular 'ustar' entry. This routine
1513 * tries to hack something more-or-less reasonable.
1515 * The approach here tries to preserve leading dir names. We do so by
1516 * working with four sections:
1517 * 1) "prefix" directory names,
1518 * 2) "suffix" directory names,
1519 * 3) inserted dir name (optional),
1522 * These sections must satisfy the following requirements:
1523 * * Parts 1 & 2 together form an initial portion of the dir name.
1524 * * Part 3 is specified by the caller. (It should not contain a leading
1526 * * Part 4 forms an initial portion of the base filename.
1527 * * The filename must be <= 99 chars to fit the ustar 'name' field.
1528 * * Parts 2, 3, 4 together must be <= 99 chars to fit the ustar 'name' fld.
1529 * * Part 1 must be <= 155 chars to fit the ustar 'prefix' field.
1530 * * If the original name ends in a '/', the new name must also end in a '/'
1531 * * Trailing '/.' sequences may be stripped.
1533 * Note: Recall that the ustar format does not store the '/' separating
1534 * parts 1 & 2, but does store the '/' separating parts 2 & 3.
1537 build_ustar_entry_name(char *dest, const char *src, size_t src_length,
1540 const char *prefix, *prefix_end;
1541 const char *suffix, *suffix_end;
1542 const char *filename, *filename_end;
1544 int need_slash = 0; /* Was there a trailing slash? */
1545 size_t suffix_length = 99;
1546 size_t insert_length;
1548 /* Length of additional dir element to be added. */
1552 /* +2 here allows for '/' before and after the insert. */
1553 insert_length = strlen(insert) + 2;
1555 /* Step 0: Quick bailout in a common case. */
1556 if (src_length < 100 && insert == NULL) {
1557 strncpy(dest, src, src_length);
1558 dest[src_length] = '\0';
1562 /* Step 1: Locate filename and enforce the length restriction. */
1563 filename_end = src + src_length;
1564 /* Remove trailing '/' chars and '/.' pairs. */
1566 if (filename_end > src && filename_end[-1] == '/') {
1568 need_slash = 1; /* Remember to restore trailing '/'. */
1571 if (filename_end > src + 1 && filename_end[-1] == '.'
1572 && filename_end[-2] == '/') {
1574 need_slash = 1; /* "foo/." will become "foo/" */
1581 /* Find start of filename. */
1582 filename = filename_end - 1;
1583 while ((filename > src) && (*filename != '/'))
1585 if ((*filename == '/') && (filename < filename_end - 1))
1587 /* Adjust filename_end so that filename + insert fits in 99 chars. */
1588 suffix_length -= insert_length;
1589 if (filename_end > filename + suffix_length)
1590 filename_end = filename + suffix_length;
1591 /* Calculate max size for "suffix" section (#3 above). */
1592 suffix_length -= filename_end - filename;
1594 /* Step 2: Locate the "prefix" section of the dirname, including
1597 prefix_end = prefix + 155;
1598 if (prefix_end > filename)
1599 prefix_end = filename;
1600 while (prefix_end > prefix && *prefix_end != '/')
1602 if ((prefix_end < filename) && (*prefix_end == '/'))
1605 /* Step 3: Locate the "suffix" section of the dirname,
1606 * including trailing '/'. */
1607 suffix = prefix_end;
1608 suffix_end = suffix + suffix_length; /* Enforce limit. */
1609 if (suffix_end > filename)
1610 suffix_end = filename;
1611 if (suffix_end < suffix)
1612 suffix_end = suffix;
1613 while (suffix_end > suffix && *suffix_end != '/')
1615 if ((suffix_end < filename) && (*suffix_end == '/'))
1618 /* Step 4: Build the new name. */
1619 /* The OpenBSD strlcpy function is safer, but less portable. */
1620 /* Rather than maintain two versions, just use the strncpy version. */
1622 if (prefix_end > prefix) {
1623 strncpy(p, prefix, prefix_end - prefix);
1624 p += prefix_end - prefix;
1626 if (suffix_end > suffix) {
1627 strncpy(p, suffix, suffix_end - suffix);
1628 p += suffix_end - suffix;
1630 if (insert != NULL) {
1631 /* Note: assume insert does not have leading or trailing '/' */
1633 p += strlen(insert);
1636 strncpy(p, filename, filename_end - filename);
1637 p += filename_end - filename;
1646 * The ustar header for the pax extended attributes must have a
1647 * reasonable name: SUSv3 requires 'dirname'/PaxHeader.'pid'/'filename'
1648 * where 'pid' is the PID of the archiving process. Unfortunately,
1649 * that makes testing a pain since the output varies for each run,
1650 * so I'm sticking with the simpler 'dirname'/PaxHeader/'filename'
1651 * for now. (Someday, I'll make this settable. Then I can use the
1652 * SUS recommendation as default and test harnesses can override it
1653 * to get predictable results.)
1655 * Joerg Schilling has argued that this is unnecessary because, in
1656 * practice, if the pax extended attributes get extracted as regular
1657 * files, no one is going to bother reading those attributes to
1658 * manually restore them. Based on this, 'star' uses
1659 * /tmp/PaxHeader/'basename' as the ustar header name. This is a
1660 * tempting argument, in part because it's simpler than the SUSv3
1661 * recommendation, but I'm not entirely convinced. I'm also
1662 * uncomfortable with the fact that "/tmp" is a Unix-ism.
1664 * The following routine leverages build_ustar_entry_name() above and
1665 * so is simpler than you might think. It just needs to provide the
1666 * additional path element and handle a few pathological cases).
1669 build_pax_attribute_name(char *dest, const char *src)
1674 /* Handle the null filename case. */
1675 if (src == NULL || *src == '\0') {
1676 strcpy(dest, "PaxHeader/blank");
1680 /* Prune final '/' and other unwanted final elements. */
1681 p = src + strlen(src);
1683 /* Ends in "/", remove the '/' */
1684 if (p > src && p[-1] == '/') {
1688 /* Ends in "/.", remove the '.' */
1689 if (p > src + 1 && p[-1] == '.'
1697 /* Pathological case: After above, there was nothing left.
1698 * This includes "/." "/./." "/.//./." etc. */
1700 strcpy(dest, "/PaxHeader/rootdir");
1704 /* Convert unadorned "." into a suitable filename. */
1705 if (*src == '.' && p == src + 1) {
1706 strcpy(dest, "PaxHeader/currentdir");
1711 * TODO: Push this string into the 'pax' structure to avoid
1712 * recomputing it every time. That will also open the door
1713 * to having clients override it.
1715 #if HAVE_GETPID && 0 /* Disable this for now; see above comment. */
1716 sprintf(buff, "PaxHeader.%d", getpid());
1718 /* If the platform can't fetch the pid, don't include it. */
1719 strcpy(buff, "PaxHeader");
1721 /* General case: build a ustar-compatible name adding
1723 build_ustar_entry_name(dest, src, p - src, buff);
1729 * GNU PAX Format 1.0 requires the special name, which pattern is:
1730 * <dir>/GNUSparseFile.<pid>/<original file name>
1732 * Since reproducible archives are more important, use 0 as pid.
1734 * This function is used for only Sparse file, a file type of which
1738 build_gnu_sparse_name(char *dest, const char *src)
1742 /* Handle the null filename case. */
1743 if (src == NULL || *src == '\0') {
1744 strcpy(dest, "GNUSparseFile/blank");
1748 /* Prune final '/' and other unwanted final elements. */
1749 p = src + strlen(src);
1751 /* Ends in "/", remove the '/' */
1752 if (p > src && p[-1] == '/') {
1756 /* Ends in "/.", remove the '.' */
1757 if (p > src + 1 && p[-1] == '.'
1765 /* General case: build a ustar-compatible name adding
1766 * "/GNUSparseFile/". */
1767 build_ustar_entry_name(dest, src, p - src, "GNUSparseFile.0");
1772 /* Write two null blocks for the end of archive */
1774 archive_write_pax_close(struct archive_write *a)
1776 return (__archive_write_nulls(a, 512 * 2));
1780 archive_write_pax_free(struct archive_write *a)
1784 pax = (struct pax *)a->format_data;
1786 return (ARCHIVE_OK);
1788 archive_string_free(&pax->pax_header);
1789 archive_string_free(&pax->sparse_map);
1790 archive_string_free(&pax->l_url_encoded_name);
1791 sparse_list_clear(pax);
1793 a->format_data = NULL;
1794 return (ARCHIVE_OK);
1798 archive_write_pax_finish_entry(struct archive_write *a)
1804 pax = (struct pax *)a->format_data;
1805 remaining = pax->entry_bytes_remaining;
1806 if (remaining == 0) {
1807 while (pax->sparse_list) {
1808 struct sparse_block *sb;
1809 if (!pax->sparse_list->is_hole)
1810 remaining += pax->sparse_list->remaining;
1811 sb = pax->sparse_list->next;
1812 free(pax->sparse_list);
1813 pax->sparse_list = sb;
1816 ret = __archive_write_nulls(a, (size_t)(remaining + pax->entry_padding));
1817 pax->entry_bytes_remaining = pax->entry_padding = 0;
1822 archive_write_pax_data(struct archive_write *a, const void *buff, size_t s)
1829 pax = (struct pax *)a->format_data;
1832 * According to GNU PAX format 1.0, write a sparse map
1835 if (archive_strlen(&(pax->sparse_map))) {
1836 ret = __archive_write_output(a, pax->sparse_map.s,
1837 archive_strlen(&(pax->sparse_map)));
1838 if (ret != ARCHIVE_OK)
1840 ret = __archive_write_nulls(a, pax->sparse_map_padding);
1841 if (ret != ARCHIVE_OK)
1843 archive_string_empty(&(pax->sparse_map));
1848 const unsigned char *p;
1850 while (pax->sparse_list != NULL &&
1851 pax->sparse_list->remaining == 0) {
1852 struct sparse_block *sb = pax->sparse_list->next;
1853 free(pax->sparse_list);
1854 pax->sparse_list = sb;
1857 if (pax->sparse_list == NULL)
1860 p = ((const unsigned char *)buff) + total;
1862 if (ws > pax->sparse_list->remaining)
1863 ws = (size_t)pax->sparse_list->remaining;
1865 if (pax->sparse_list->is_hole) {
1866 /* Current block is hole thus we do not write
1868 pax->sparse_list->remaining -= ws;
1873 ret = __archive_write_output(a, p, ws);
1874 pax->sparse_list->remaining -= ws;
1876 if (ret != ARCHIVE_OK)
1883 has_non_ASCII(const char *_p)
1885 const unsigned char *p = (const unsigned char *)_p;
1889 while (*p != '\0' && *p < 128)
1891 return (*p != '\0');
1895 * Used by extended attribute support; encodes the name
1896 * so that there will be no '=' characters in the result.
1899 url_encode(const char *in)
1906 for (s = in; *s != '\0'; s++) {
1907 if (*s < 33 || *s > 126 || *s == '%' || *s == '=')
1913 out = (char *)malloc(out_len + 1);
1917 for (s = in, d = out; *s != '\0'; s++) {
1918 /* encode any non-printable ASCII character or '%' or '=' */
1919 if (*s < 33 || *s > 126 || *s == '%' || *s == '=') {
1920 /* URL encoding is '%' followed by two hex digits */
1922 *d++ = "0123456789ABCDEF"[0x0f & (*s >> 4)];
1923 *d++ = "0123456789ABCDEF"[0x0f & *s];
1933 * Encode a sequence of bytes into a C string using base-64 encoding.
1935 * Returns a null-terminated C string allocated with malloc(); caller
1936 * is responsible for freeing the result.
1939 base64_encode(const char *s, size_t len)
1941 static const char digits[64] =
1942 { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
1943 'P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d',
1944 'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s',
1945 't','u','v','w','x','y','z','0','1','2','3','4','5','6','7',
1950 /* 3 bytes becomes 4 chars, but round up and allow for trailing NUL */
1951 out = (char *)malloc((len * 4 + 2) / 3 + 1);
1956 /* Convert each group of 3 bytes into 4 characters. */
1958 v = (((int)s[0] << 16) & 0xff0000)
1959 | (((int)s[1] << 8) & 0xff00)
1960 | (((int)s[2]) & 0x00ff);
1963 *d++ = digits[(v >> 18) & 0x3f];
1964 *d++ = digits[(v >> 12) & 0x3f];
1965 *d++ = digits[(v >> 6) & 0x3f];
1966 *d++ = digits[(v) & 0x3f];
1968 /* Handle final group of 1 byte (2 chars) or 2 bytes (3 chars). */
1972 v = (((int)s[0] << 16) & 0xff0000);
1973 *d++ = digits[(v >> 18) & 0x3f];
1974 *d++ = digits[(v >> 12) & 0x3f];
1977 v = (((int)s[0] << 16) & 0xff0000)
1978 | (((int)s[1] << 8) & 0xff00);
1979 *d++ = digits[(v >> 18) & 0x3f];
1980 *d++ = digits[(v >> 12) & 0x3f];
1981 *d++ = digits[(v >> 6) & 0x3f];
1984 /* Add trailing NUL character so output is a valid C string. */
1990 sparse_list_clear(struct pax *pax)
1992 while (pax->sparse_list != NULL) {
1993 struct sparse_block *sb = pax->sparse_list;
1994 pax->sparse_list = sb->next;
1997 pax->sparse_tail = NULL;
2001 _sparse_list_add_block(struct pax *pax, int64_t offset, int64_t length,
2004 struct sparse_block *sb;
2006 sb = (struct sparse_block *)malloc(sizeof(*sb));
2008 return (ARCHIVE_FATAL);
2010 sb->is_hole = is_hole;
2011 sb->offset = offset;
2012 sb->remaining = length;
2013 if (pax->sparse_list == NULL || pax->sparse_tail == NULL)
2014 pax->sparse_list = pax->sparse_tail = sb;
2016 pax->sparse_tail->next = sb;
2017 pax->sparse_tail = sb;
2019 return (ARCHIVE_OK);
2023 sparse_list_add(struct pax *pax, int64_t offset, int64_t length)
2025 int64_t last_offset;
2028 if (pax->sparse_tail == NULL)
2031 last_offset = pax->sparse_tail->offset +
2032 pax->sparse_tail->remaining;
2034 if (last_offset < offset) {
2035 /* Add a hole block. */
2036 r = _sparse_list_add_block(pax, last_offset,
2037 offset - last_offset, 1);
2038 if (r != ARCHIVE_OK)
2041 /* Add data block. */
2042 return (_sparse_list_add_block(pax, offset, length, 0));