Merge from vendor branch LIBARCHIVE:
[dragonfly.git] / contrib / libarchive / archive_write_set_format_pax.c
1 /*-
2  * Copyright (c) 2003-2004 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer
10  *    in this position and unchanged.
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: src/lib/libarchive/archive_write_set_format_pax.c,v 1.19 2004/11/05 05:26:30 kientzle Exp $");
29
30 #include <sys/stat.h>
31 #include <errno.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <wchar.h>
36
37 #include "archive.h"
38 #include "archive_entry.h"
39 #include "archive_private.h"
40
41 struct pax {
42         uint64_t        entry_bytes_remaining;
43         uint64_t        entry_padding;
44         struct archive_string   pax_header;
45         char            written;
46 };
47
48 static void              add_pax_attr(struct archive_string *, const char *key,
49                              const char *value);
50 static void              add_pax_attr_int(struct archive_string *,
51                              const char *key, int64_t value);
52 static void              add_pax_attr_time(struct archive_string *,
53                              const char *key, int64_t sec,
54                              unsigned long nanos);
55 static void              add_pax_attr_w(struct archive_string *,
56                              const char *key, const wchar_t *wvalue);
57 static int               archive_write_pax_data(struct archive *,
58                              const void *, size_t);
59 static int               archive_write_pax_finish(struct archive *);
60 static int               archive_write_pax_finish_entry(struct archive *);
61 static int               archive_write_pax_header(struct archive *,
62                              struct archive_entry *);
63 static char             *build_pax_attribute_name(const char *abbreviated,
64                              struct archive_string *work);
65 static char             *build_ustar_entry_name(char *dest, const char *src);
66 static char             *format_int(char *dest, int64_t);
67 static int               write_nulls(struct archive *, size_t);
68
69 /*
70  * Set output format to 'restricted pax' format.
71  *
72  * This is the same as normal 'pax', but tries to suppress
73  * the pax header whenever possible.  This is the default for
74  * bsdtar, for instance.
75  */
76 int
77 archive_write_set_format_pax_restricted(struct archive *a)
78 {
79         int r;
80         r = archive_write_set_format_pax(a);
81         a->archive_format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
82         a->archive_format_name = "restricted POSIX pax interchange";
83         return (r);
84 }
85
86 /*
87  * Set output format to 'pax' format.
88  */
89 int
90 archive_write_set_format_pax(struct archive *a)
91 {
92         struct pax *pax;
93
94         if (a->format_finish != NULL)
95                 (a->format_finish)(a);
96
97         pax = malloc(sizeof(*pax));
98         if (pax == NULL) {
99                 archive_set_error(a, ENOMEM, "Can't allocate pax data");
100                 return (ARCHIVE_FATAL);
101         }
102         memset(pax, 0, sizeof(*pax));
103         a->format_data = pax;
104
105         a->pad_uncompressed = 1;
106         a->format_write_header = archive_write_pax_header;
107         a->format_write_data = archive_write_pax_data;
108         a->format_finish = archive_write_pax_finish;
109         a->format_finish_entry = archive_write_pax_finish_entry;
110         a->archive_format = ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE;
111         a->archive_format_name = "POSIX pax interchange";
112         return (ARCHIVE_OK);
113 }
114
115 /*
116  * Note: This code assumes that 'nanos' has the same sign as 'sec',
117  * which implies that sec=-1, nanos=200000000 represents -1.2 seconds
118  * and not -0.8 seconds.  This is a pretty pedantic point, as we're
119  * unlikely to encounter many real files created before Jan 1, 1970,
120  * much less ones with timestamps recorded to sub-second resolution.
121  */
122 static void
123 add_pax_attr_time(struct archive_string *as, const char *key,
124     int64_t sec, unsigned long nanos)
125 {
126         int digit, i;
127         char *t;
128         /*
129          * Note that each byte contributes fewer than 3 base-10
130          * digits, so this will always be big enough.
131          */
132         char tmp[1 + 3*sizeof(sec) + 1 + 3*sizeof(nanos)];
133
134         tmp[sizeof(tmp) - 1] = 0;
135         t = tmp + sizeof(tmp) - 1;
136
137         /* Skip trailing zeros in the fractional part. */
138         for(digit = 0, i = 10; i > 0 && digit == 0; i--) {
139                 digit = nanos % 10;
140                 nanos /= 10;
141         }
142
143         /* Only format the fraction if it's non-zero. */
144         if (i > 0) {
145                 while (i > 0) {
146                         *--t = "0123456789"[digit];
147                         digit = nanos % 10;
148                         nanos /= 10;
149                         i--;
150                 }
151                 *--t = '.';
152         }
153         t = format_int(t, sec);
154
155         add_pax_attr(as, key, t);
156 }
157
158 static char *
159 format_int(char *t, int64_t i)
160 {
161         int sign;
162
163         if (i < 0) {
164                 sign = -1;
165                 i = -i;
166         } else
167                 sign = 1;
168
169         do {
170                 *--t = "0123456789"[i % 10];
171         } while (i /= 10);
172         if (sign < 0)
173                 *--t = '-';
174         return (t);
175 }
176
177 static void
178 add_pax_attr_int(struct archive_string *as, const char *key, int64_t value)
179 {
180         char tmp[1 + 3 * sizeof(value)];
181
182         tmp[sizeof(tmp) - 1] = 0;
183         add_pax_attr(as, key, format_int(tmp + sizeof(tmp) - 1, value));
184 }
185
186 static void
187 add_pax_attr_w(struct archive_string *as, const char *key, const wchar_t *wval)
188 {
189         int     utf8len;
190         const wchar_t *wp;
191         unsigned long wc;
192         char *utf8_value, *p;
193
194         utf8len = 0;
195         for (wp = wval; *wp != L'\0'; ) {
196                 wc = *wp++;
197                 if (wc <= 0x7f)
198                         utf8len++;
199                 else if (wc <= 0x7ff)
200                         utf8len += 2;
201                 else if (wc <= 0xffff)
202                         utf8len += 3;
203                 else if (wc <= 0x1fffff)
204                         utf8len += 4;
205                 else if (wc <= 0x3ffffff)
206                         utf8len += 5;
207                 else if (wc <= 0x7fffffff)
208                         utf8len += 6;
209                 /* Ignore larger values; UTF-8 can't encode them. */
210         }
211
212         utf8_value = malloc(utf8len + 1);
213         for (wp = wval, p = utf8_value; *wp != L'\0'; ) {
214                 wc = *wp++;
215                 if (wc <= 0x7f) {
216                         *p++ = (char)wc;
217                 } else if (wc <= 0x7ff) {
218                         p[0] = 0xc0 | ((wc >> 6) & 0x1f);
219                         p[1] = 0x80 | (wc & 0x3f);
220                         p += 2;
221                 } else if (wc <= 0xffff) {
222                         p[0] = 0xe0 | ((wc >> 12) & 0x0f);
223                         p[1] = 0x80 | ((wc >> 6) & 0x3f);
224                         p[2] = 0x80 | (wc & 0x3f);
225                         p += 3;
226                 } else if (wc <= 0x1fffff) {
227                         p[0] = 0xf0 | ((wc >> 18) & 0x07);
228                         p[1] = 0x80 | ((wc >> 12) & 0x3f);
229                         p[2] = 0x80 | ((wc >> 6) & 0x3f);
230                         p[3] = 0x80 | (wc & 0x3f);
231                         p += 4;
232                 } else if (wc <= 0x3ffffff) {
233                         p[0] = 0xf8 | ((wc >> 24) & 0x03);
234                         p[1] = 0x80 | ((wc >> 18) & 0x3f);
235                         p[2] = 0x80 | ((wc >> 12) & 0x3f);
236                         p[3] = 0x80 | ((wc >> 6) & 0x3f);
237                         p[4] = 0x80 | (wc & 0x3f);
238                         p += 5;
239                 } else if (wc <= 0x7fffffff) {
240                         p[0] = 0xfc | ((wc >> 30) & 0x01);
241                         p[1] = 0x80 | ((wc >> 24) & 0x3f);
242                         p[1] = 0x80 | ((wc >> 18) & 0x3f);
243                         p[2] = 0x80 | ((wc >> 12) & 0x3f);
244                         p[3] = 0x80 | ((wc >> 6) & 0x3f);
245                         p[4] = 0x80 | (wc & 0x3f);
246                         p += 6;
247                 }
248                 /* Ignore larger values; UTF-8 can't encode them. */
249         }
250         *p = '\0';
251         add_pax_attr(as, key, utf8_value);
252         free(utf8_value);
253 }
254
255 /*
256  * Add a key/value attribute to the pax header.  This function handles
257  * the length field and various other syntactic requirements.
258  */
259 static void
260 add_pax_attr(struct archive_string *as, const char *key, const char *value)
261 {
262         int digits, i, len, next_ten;
263         char tmp[1 + 3 * sizeof(int)];  /* < 3 base-10 digits per byte */
264
265         /*-
266          * PAX attributes have the following layout:
267          *     <len> <space> <key> <=> <value> <nl>
268          */
269         len = 1 + strlen(key) + 1 + strlen(value) + 1;
270
271         /*
272          * The <len> field includes the length of the <len> field, so
273          * computing the correct length is tricky.  I start by
274          * counting the number of base-10 digits in 'len' and
275          * computing the next higher power of 10.
276          */
277         next_ten = 1;
278         digits = 0;
279         i = len;
280         while (i > 0) {
281                 i = i / 10;
282                 digits++;
283                 next_ten = next_ten * 10;
284         }
285         /*
286          * For example, if string without the length field is 99
287          * chars, then adding the 2 digit length "99" will force the
288          * total length past 100, requiring an extra digit.  The next
289          * statement adjusts for this effect.
290          */
291         if (len + digits >= next_ten)
292                 digits++;
293
294         /* Now, we have the right length so we can build the line. */
295         tmp[sizeof(tmp) - 1] = 0;       /* Null-terminate the work area. */
296         archive_strcat(as, format_int(tmp + sizeof(tmp) - 1, len + digits));
297         archive_strappend_char(as, ' ');
298         archive_strcat(as, key);
299         archive_strappend_char(as, '=');
300         archive_strcat(as, value);
301         archive_strappend_char(as, '\n');
302 }
303
304 /*
305  * TODO: Consider adding 'comment' and 'charset' fields to
306  * archive_entry so that clients can specify them.  Also, consider
307  * adding generic key/value tags so clients can add arbitrary
308  * key/value data.
309  */
310 static int
311 archive_write_pax_header(struct archive *a,
312     struct archive_entry *entry_original)
313 {
314         struct archive_entry *entry_main;
315         const char *linkname, *p;
316         const char *hardlink;
317         const wchar_t *wp, *wp2, *wname_start;
318         int need_extension, oldstate, r, ret;
319         struct pax *pax;
320         const struct stat *st_main, *st_original;
321
322         struct archive_string pax_entry_name;
323         char paxbuff[512];
324         char ustarbuff[512];
325         char ustar_entry_name[256];
326
327         archive_string_init(&pax_entry_name);
328         need_extension = 0;
329         pax = a->format_data;
330         pax->written = 1;
331
332         st_original = archive_entry_stat(entry_original);
333
334         hardlink = archive_entry_hardlink(entry_original);
335
336         /* Make sure this is a type of entry that we can handle here */
337         if (hardlink == NULL) {
338                 switch (st_original->st_mode & S_IFMT) {
339                 case S_IFREG:
340                 case S_IFLNK:
341                 case S_IFCHR:
342                 case S_IFBLK:
343                 case S_IFDIR:
344                 case S_IFIFO:
345                         break;
346                 case S_IFSOCK:
347                         archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
348                             "tar format cannot archive socket");
349                         return (ARCHIVE_WARN);
350                 default:
351                         archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
352                             "tar format cannot archive this (mode=0%lo)",
353                             (unsigned long)st_original->st_mode);
354                         return (ARCHIVE_WARN);
355                 }
356         }
357
358         /* Copy entry so we can modify it as needed. */
359         entry_main = archive_entry_clone(entry_original);
360         archive_string_empty(&(pax->pax_header)); /* Blank our work area. */
361         st_main = archive_entry_stat(entry_main);
362
363         /*
364          * Determining whether or not the name is too big is ugly
365          * because of the rules for dividing names between 'name' and
366          * 'prefix' fields.  Here, I pick out the longest possible
367          * suffix, then test whether the remaining prefix is too long.
368          */
369         wp = archive_entry_pathname_w(entry_main);
370         p = archive_entry_pathname(entry_main);
371         if (wcslen(wp) <= 100)  /* Short enough for just 'name' field */
372                 wname_start = wp;       /* Record a zero-length prefix */
373         else
374                 /* Find the largest suffix that fits in 'name' field. */
375                 wname_start = wcschr(wp + wcslen(wp) - 100 - 1, '/');
376
377         /* Find non-ASCII character, if any. */
378         wp2 = wp;
379         while (*wp2 != L'\0' && *wp2 < 128)
380                 wp2++;
381
382         /*
383          * If name is too long, or has non-ASCII characters, add
384          * 'path' to pax extended attrs.
385          */
386         if (wname_start == NULL || wname_start - wp > 155 ||
387             *wp2 != L'\0') {
388                 add_pax_attr_w(&(pax->pax_header), "path", wp);
389                 archive_entry_set_pathname(entry_main,
390                     build_ustar_entry_name(ustar_entry_name, p));
391                 need_extension = 1;
392         }
393
394         /* If link name is too long, add 'linkpath' to pax extended attrs. */
395         linkname = hardlink;
396         if (linkname == NULL)
397                 linkname = archive_entry_symlink(entry_main);
398
399         if (linkname != NULL && strlen(linkname) > 100) {
400                 add_pax_attr(&(pax->pax_header), "linkpath", linkname);
401                 if (hardlink != NULL)
402                         archive_entry_set_hardlink(entry_main,
403                             "././@LongHardLink");
404                 else
405                         archive_entry_set_symlink(entry_main,
406                             "././@LongSymLink");
407                 need_extension = 1;
408         }
409
410         /* If file size is too large, add 'size' to pax extended attrs. */
411         if (st_main->st_size >= (((int64_t)1) << 33)) {
412                 add_pax_attr_int(&(pax->pax_header), "size", st_main->st_size);
413                 need_extension = 1;
414         }
415
416         /* If numeric GID is too large, add 'gid' to pax extended attrs. */
417         if (st_main->st_gid >= (1 << 18)) {
418                 add_pax_attr_int(&(pax->pax_header), "gid", st_main->st_gid);
419                 need_extension = 1;
420         }
421
422         /* If group name is too large, add 'gname' to pax extended attrs. */
423         /* TODO: If gname has non-ASCII characters, use pax attribute. */
424         p = archive_entry_gname(entry_main);
425         if (p != NULL && strlen(p) > 31) {
426                 add_pax_attr(&(pax->pax_header), "gname", p);
427                 archive_entry_set_gname(entry_main, NULL);
428                 need_extension = 1;
429         }
430
431         /* If numeric UID is too large, add 'uid' to pax extended attrs. */
432         if (st_main->st_uid >= (1 << 18)) {
433                 add_pax_attr_int(&(pax->pax_header), "uid", st_main->st_uid);
434                 need_extension = 1;
435         }
436
437         /* If user name is too large, add 'uname' to pax extended attrs. */
438         /* TODO: If uname has non-ASCII characters, use pax attribute. */
439         p = archive_entry_uname(entry_main);
440         if (p != NULL && strlen(p) > 31) {
441                 add_pax_attr(&(pax->pax_header), "uname", p);
442                 archive_entry_set_uname(entry_main, NULL);
443                 need_extension = 1;
444         }
445
446         /*
447          * POSIX/SUSv3 doesn't provide a standard key for large device
448          * numbers.  I use the same keys here that Joerg Schilling
449          * used for 'star.'  (Which, somewhat confusingly, are called
450          * "devXXX" even though they code "rdev" values.)  No doubt,
451          * other implementations use other keys.  Note that there's no
452          * reason we can't write the same information into a number of
453          * different keys.
454          *
455          * Of course, this is only needed for block or char device entries.
456          */
457         if (S_ISBLK(st_main->st_mode) ||
458             S_ISCHR(st_main->st_mode)) {
459                 /*
460                  * If rdevmajor is too large, add 'SCHILY.devmajor' to
461                  * extended attributes.
462                  */
463                 dev_t rdevmajor, rdevminor;
464                 rdevmajor = major(st_main->st_rdev);
465                 rdevminor = minor(st_main->st_rdev);
466                 if (rdevmajor >= (1 << 18)) {
467                         add_pax_attr_int(&(pax->pax_header), "SCHILY.devmajor",
468                             rdevmajor);
469                         archive_entry_set_rdevmajor(entry_main, (1 << 18) - 1);
470                         need_extension = 1;
471                 }
472
473                 /*
474                  * If devminor is too large, add 'SCHILY.devminor' to
475                  * extended attributes.
476                  */
477                 if (rdevminor >= (1 << 18)) {
478                         add_pax_attr_int(&(pax->pax_header), "SCHILY.devminor",
479                             rdevminor);
480                         archive_entry_set_rdevminor(entry_main, (1 << 18) - 1);
481                         need_extension = 1;
482                 }
483         }
484
485         /*
486          * Technically, the mtime field in the ustar header can
487          * support 33 bits, but many platforms use signed 32-bit time
488          * values.  The cutoff of 0x7fffffff here is a compromise.
489          * Yes, this check is duplicated just below; this helps to
490          * avoid writing an mtime attribute just to handle a
491          * high-resolution timestamp in "restricted pax" mode.
492          */
493         if (!need_extension &&
494             ((st_main->st_mtime < 0) || (st_main->st_mtime >= 0x7fffffff)))
495                 need_extension = 1;
496
497         /* I use a star-compatible file flag attribute. */
498         p = archive_entry_fflags_text(entry_main);
499         if (!need_extension && p != NULL  &&  *p != '\0')
500                 need_extension = 1;
501
502         /* If there are non-trivial ACL entries, we need an extension. */
503         if (!need_extension && archive_entry_acl_count(entry_original,
504                 ARCHIVE_ENTRY_ACL_TYPE_ACCESS) > 0)
505                 need_extension = 1;
506
507         /* If there are non-trivial ACL entries, we need an extension. */
508         if (!need_extension && archive_entry_acl_count(entry_original,
509                 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) > 0)
510                 need_extension = 1;
511
512         /*
513          * The following items are handled differently in "pax
514          * restricted" format.  In particular, in "pax restricted"
515          * format they won't be added unless need_extension is
516          * already set (we're already generated an extended header, so
517          * may as well include these).
518          */
519         if (a->archive_format != ARCHIVE_FORMAT_TAR_PAX_RESTRICTED ||
520             need_extension) {
521
522                 if (st_main->st_mtime < 0  ||
523                     st_main->st_mtime >= 0x7fffffff  ||
524                     ARCHIVE_STAT_MTIME_NANOS(st_main) != 0)
525                         add_pax_attr_time(&(pax->pax_header), "mtime",
526                             st_main->st_mtime,
527                             ARCHIVE_STAT_MTIME_NANOS(st_main));
528
529                 if (st_main->st_ctime != 0  ||
530                     ARCHIVE_STAT_CTIME_NANOS(st_main) != 0)
531                         add_pax_attr_time(&(pax->pax_header), "ctime",
532                             st_main->st_ctime,
533                             ARCHIVE_STAT_CTIME_NANOS(st_main));
534
535                 if (st_main->st_atime != 0  ||
536                     ARCHIVE_STAT_ATIME_NANOS(st_main) != 0)
537                         add_pax_attr_time(&(pax->pax_header), "atime",
538                             st_main->st_atime,
539                             ARCHIVE_STAT_ATIME_NANOS(st_main));
540
541                 /* I use a star-compatible file flag attribute. */
542                 p = archive_entry_fflags_text(entry_main);
543                 if (p != NULL  &&  *p != '\0')
544                         add_pax_attr(&(pax->pax_header), "SCHILY.fflags", p);
545
546                 /* I use star-compatible ACL attributes. */
547                 wp = archive_entry_acl_text_w(entry_original,
548                     ARCHIVE_ENTRY_ACL_TYPE_ACCESS |
549                     ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID);
550                 if (wp != NULL && *wp != L'\0')
551                         add_pax_attr_w(&(pax->pax_header),
552                             "SCHILY.acl.access", wp);
553                 wp = archive_entry_acl_text_w(entry_original,
554                     ARCHIVE_ENTRY_ACL_TYPE_DEFAULT |
555                     ARCHIVE_ENTRY_ACL_STYLE_EXTRA_ID);
556                 if (wp != NULL && *wp != L'\0')
557                         add_pax_attr_w(&(pax->pax_header),
558                             "SCHILY.acl.default", wp);
559
560                 /* Include star-compatible metadata info. */
561                 /* Note: "SCHILY.dev{major,minor}" are NOT the
562                  * major/minor portions of "SCHILY.dev". */
563                 add_pax_attr_int(&(pax->pax_header), "SCHILY.dev",
564                     st_main->st_dev);
565                 add_pax_attr_int(&(pax->pax_header), "SCHILY.ino",
566                     st_main->st_ino);
567                 add_pax_attr_int(&(pax->pax_header), "SCHILY.nlink",
568                     st_main->st_nlink);
569         }
570
571         /* Only regular files have data. */
572         if (!S_ISREG(archive_entry_mode(entry_main)))
573                 archive_entry_set_size(entry_main, 0);
574
575         /*
576          * Pax-restricted does not store data for hardlinks, in order
577          * to improve compatibility with ustar.
578          */
579         if (a->archive_format != ARCHIVE_FORMAT_TAR_PAX_INTERCHANGE &&
580             hardlink != NULL)
581                 archive_entry_set_size(entry_main, 0);
582
583         /*
584          * XXX Full pax interchange format does permit a hardlink
585          * entry to have data associated with it.  I'm not supporting
586          * that here because the client expects me to tell them whether
587          * or not this format expects data for hardlinks.  If I
588          * don't check here, then every pax archive will end up with
589          * duplicated data for hardlinks.  Someday, there may be
590          * need to select this behavior, in which case the following
591          * will need to be revisited. XXX
592          */
593         if (hardlink != NULL)
594                 archive_entry_set_size(entry_main, 0);
595
596         /* Format 'ustar' header for main entry.
597          *
598          * The trouble with file size: If the reader can't understand
599          * the file size, they may not be able to locate the next
600          * entry and the rest of the archive is toast.  Pax-compliant
601          * readers are supposed to ignore the file size in the main
602          * header, so the question becomes how to maximize portability
603          * for readers that don't support pax attribute extensions.
604          * For maximum compatibility, I permit numeric extensions in
605          * the main header so that the file size stored will always be
606          * correct, even if it's in a format that only some
607          * implementations understand.  The technique used here is:
608          *
609          *  a) If possible, follow the standard exactly.  This handles
610          *  files up to 8 gigabytes minus 1.
611          *
612          *  b) If that fails, try octal but omit the field terminator.
613          *  That handles files up to 64 gigabytes minus 1.
614          *
615          *  c) Otherwise, use base-256 extensions.  That handles files
616          *  up to 2^63 in this implementation, with the potential to
617          *  go up to 2^94.  That should hold us for a while. ;-)
618          *
619          * The non-strict formatter uses similar logic for other
620          * numeric fields, though they're less critical.
621          */
622         __archive_write_format_header_ustar(a, ustarbuff, entry_main, -1, 0);
623
624         /* If we built any extended attributes, write that entry first. */
625         ret = ARCHIVE_OK;
626         if (archive_strlen(&(pax->pax_header)) > 0) {
627                 struct stat st;
628                 struct archive_entry *pax_attr_entry;
629                 const char *pax_attr_name;
630
631                 memset(&st, 0, sizeof(st));
632                 pax_attr_entry = archive_entry_new();
633                 p = archive_entry_pathname(entry_main);
634                 pax_attr_name = build_pax_attribute_name(p, &pax_entry_name);
635
636                 archive_entry_set_pathname(pax_attr_entry, pax_attr_name);
637                 st.st_size = archive_strlen(&(pax->pax_header));
638                 st.st_uid = st_main->st_uid;
639                 if (st.st_uid >= 1 << 18)
640                         st.st_uid = (1 << 18) - 1;
641                 st.st_gid = st_main->st_gid;
642                 if (st.st_gid >= 1 << 18)
643                         st.st_gid = (1 << 18) - 1;
644                 st.st_mode = st_main->st_mode;
645                 archive_entry_copy_stat(pax_attr_entry, &st);
646
647                 archive_entry_set_uname(pax_attr_entry,
648                     archive_entry_uname(entry_main));
649                 archive_entry_set_gname(pax_attr_entry,
650                     archive_entry_gname(entry_main));
651
652                 ret = __archive_write_format_header_ustar(a, paxbuff,
653                     pax_attr_entry, 'x', 1);
654
655                 archive_entry_free(pax_attr_entry);
656                 archive_string_free(&pax_entry_name);
657
658                 /* Note that the 'x' header shouldn't ever fail to format */
659                 if (ret != 0) {
660                         const char *msg = "archive_write_header_pax: "
661                             "'x' header failed?!  This can't happen.\n";
662                         write(2, msg, strlen(msg));
663                         exit(1);
664                 }
665                 r = (a->compression_write)(a, paxbuff, 512);
666                 if (r != ARCHIVE_OK) {
667                         pax->entry_bytes_remaining = 0;
668                         pax->entry_padding = 0;
669                         return (ARCHIVE_FATAL);
670                 }
671
672                 pax->entry_bytes_remaining = archive_strlen(&(pax->pax_header));
673                 pax->entry_padding = 0x1ff & (- pax->entry_bytes_remaining);
674
675                 oldstate = a->state;
676                 a->state = ARCHIVE_STATE_DATA;
677                 r = archive_write_data(a, pax->pax_header.s,
678                     archive_strlen(&(pax->pax_header)));
679                 a->state = oldstate;
680                 if (r != ARCHIVE_OK) {
681                         /* If a write fails, we're pretty much toast. */
682                         return (ARCHIVE_FATAL);
683                 }
684
685                 archive_write_pax_finish_entry(a);
686         }
687
688         /* Write the header for main entry. */
689         r = (a->compression_write)(a, ustarbuff, 512);
690         if (r != ARCHIVE_OK)
691                 return (r);
692
693         /*
694          * Inform the client of the on-disk size we're using, so
695          * they can avoid unnecessarily writing a body for something
696          * that we're just going to ignore.
697          */
698         archive_entry_set_size(entry_original, archive_entry_size(entry_main));
699         pax->entry_bytes_remaining = archive_entry_size(entry_main);
700         pax->entry_padding = 0x1ff & (- pax->entry_bytes_remaining);
701         archive_entry_free(entry_main);
702
703         return (ret);
704 }
705
706 /*
707  * We need a valid name for the regular 'ustar' entry.  This routine
708  * tries to hack something more-or-less reasonable.
709  */
710 static char *
711 build_ustar_entry_name(char *dest, const char *src)
712 {
713         const char *basename, *break_point, *prefix;
714         int basename_length, dirname_length, prefix_length;
715
716         prefix = src;
717         basename = strrchr(src, '/');
718         if (basename == NULL) {
719                 basename = src;
720                 prefix_length = 0;
721                 basename_length = strlen(basename);
722                 if (basename_length > 100)
723                         basename_length = 100;
724         } else {
725                 basename_length = strlen(basename);
726                 if (basename_length > 100)
727                         basename_length = 100;
728                 dirname_length = basename - src;
729
730                 break_point =
731                     strchr(src + dirname_length + basename_length - 101, '/');
732                 prefix_length = break_point - prefix - 1;
733                 while (prefix_length > 155) {
734                         prefix = strchr(prefix, '/') + 1; /* Drop 1st dir. */
735                         prefix_length = break_point - prefix - 1;
736                 }
737         }
738
739         /* The OpenBSD strlcpy function is safer, but less portable. */
740         /* Rather than maintain two versions, just use the strncpy version. */
741         strncpy(dest, prefix, basename - prefix + basename_length);
742         dest[basename - prefix + basename_length] = '\0';
743
744         return (dest);
745 }
746
747 /*
748  * The ustar header for the pax extended attributes must have a
749  * reasonable name:  SUSv3 suggests 'dirname'/PaxHeaders/'basename'
750  *
751  * Joerg Schiling has argued that this is unnecessary because, in practice,
752  * if the pax extended attributes get extracted as regular files, noone is
753  * going to bother reading those attributes to manually restore them.
754  * This is a tempting argument, but I'm not entirely convinced.
755  *
756  * Of course, adding "PaxHeaders/" might force the name to be too big.
757  * Here, I start from the (possibly already-trimmed) name used in the
758  * main ustar header and delete some additional early path elements to
759  * fit in the extra "PaxHeader/" part.
760  */
761 static char *
762 build_pax_attribute_name(const char *abbreviated, /* ustar-compat name */
763     struct archive_string *work)
764 {
765         const char *basename, *break_point, *prefix;
766         int prefix_length, suffix_length;
767
768         /*
769          * This is much simpler because I know that "abbreviated" is
770          * already small enough; I just need to determine if it needs
771          * any further trimming to fit the "PaxHeader/" portion.
772          */
773
774         /* Identify the final prefix and suffix portions. */
775         prefix = abbreviated;   /* First guess: prefix starts at beginning */
776         if (strlen(abbreviated) > 100) {
777                 break_point = strchr(prefix + strlen(prefix) - 101, '/');
778                 prefix_length = break_point - prefix - 1;
779                 suffix_length = strlen(break_point + 1);
780                 /*
781                  * The next loop keeps trimming until "/PaxHeader/" can
782                  * be added to either the prefix or the suffix.
783                  */
784                 while (prefix_length > 144 && suffix_length > 89) {
785                         prefix = strchr(prefix, '/') + 1; /* Drop 1st dir. */
786                         prefix_length = break_point - prefix - 1;
787                 }
788         }
789
790         archive_string_empty(work);
791         basename = strrchr(prefix, '/');
792         if (basename == NULL) {
793                 archive_strcpy(work, "PaxHeader/");
794                 archive_strcat(work, prefix);
795         } else {
796                 basename++;
797                 archive_strncpy(work, prefix, basename - prefix);
798                 archive_strcat(work, "PaxHeader/");
799                 archive_strcat(work, basename);
800         }
801
802         return (work->s);
803 }
804
805 /* Write two null blocks for the end of archive */
806 static int
807 archive_write_pax_finish(struct archive *a)
808 {
809         struct pax *pax;
810         int r;
811
812         r = ARCHIVE_OK;
813         pax = a->format_data;
814         if (pax->written && a->compression_write != NULL)
815                 r = write_nulls(a, 512 * 2);
816         archive_string_free(&pax->pax_header);
817         free(pax);
818         a->format_data = NULL;
819         return (r);
820 }
821
822 static int
823 archive_write_pax_finish_entry(struct archive *a)
824 {
825         struct pax *pax;
826         int ret;
827
828         pax = a->format_data;
829         ret = write_nulls(a, pax->entry_bytes_remaining + pax->entry_padding);
830         pax->entry_bytes_remaining = pax->entry_padding = 0;
831         return (ret);
832 }
833
834 static int
835 write_nulls(struct archive *a, size_t padding)
836 {
837         int ret, to_write;
838
839         while (padding > 0) {
840                 to_write = padding < a->null_length ? padding : a->null_length;
841                 ret = (a->compression_write)(a, a->nulls, to_write);
842                 if (ret != ARCHIVE_OK)
843                         return (ret);
844                 padding -= to_write;
845         }
846         return (ARCHIVE_OK);
847 }
848
849 static int
850 archive_write_pax_data(struct archive *a, const void *buff, size_t s)
851 {
852         struct pax *pax;
853         int ret;
854
855         pax = a->format_data;
856         pax->written = 1;
857         if (s > pax->entry_bytes_remaining)
858                 s = pax->entry_bytes_remaining;
859
860         ret = (a->compression_write)(a, buff, s);
861         pax->entry_bytes_remaining -= s;
862         return (ret);
863 }