Import libarchive-3.0.4.
[dragonfly.git] / contrib / libarchive / libarchive / archive_write_set_format_ustar.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * Copyright (c) 2011-2012 Michihiro NAKAJIMA
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "archive_platform.h"
28 __FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_ustar.c 191579 2009-04-27 18:35:03Z kientzle $");
29
30
31 #ifdef HAVE_ERRNO_H
32 #include <errno.h>
33 #endif
34 #include <stdio.h>
35 #ifdef HAVE_STDLIB_H
36 #include <stdlib.h>
37 #endif
38 #ifdef HAVE_STRING_H
39 #include <string.h>
40 #endif
41
42 #include "archive.h"
43 #include "archive_entry.h"
44 #include "archive_entry_locale.h"
45 #include "archive_private.h"
46 #include "archive_write_private.h"
47
48 struct ustar {
49         uint64_t        entry_bytes_remaining;
50         uint64_t        entry_padding;
51
52         struct archive_string_conv *opt_sconv;
53         struct archive_string_conv *sconv_default;
54         int     init_default_conversion;
55 };
56
57 /*
58  * Define structure of POSIX 'ustar' tar header.
59  */
60 #define USTAR_name_offset 0
61 #define USTAR_name_size 100
62 #define USTAR_mode_offset 100
63 #define USTAR_mode_size 6
64 #define USTAR_mode_max_size 8
65 #define USTAR_uid_offset 108
66 #define USTAR_uid_size 6
67 #define USTAR_uid_max_size 8
68 #define USTAR_gid_offset 116
69 #define USTAR_gid_size 6
70 #define USTAR_gid_max_size 8
71 #define USTAR_size_offset 124
72 #define USTAR_size_size 11
73 #define USTAR_size_max_size 12
74 #define USTAR_mtime_offset 136
75 #define USTAR_mtime_size 11
76 #define USTAR_mtime_max_size 11
77 #define USTAR_checksum_offset 148
78 #define USTAR_checksum_size 8
79 #define USTAR_typeflag_offset 156
80 #define USTAR_typeflag_size 1
81 #define USTAR_linkname_offset 157
82 #define USTAR_linkname_size 100
83 #define USTAR_magic_offset 257
84 #define USTAR_magic_size 6
85 #define USTAR_version_offset 263
86 #define USTAR_version_size 2
87 #define USTAR_uname_offset 265
88 #define USTAR_uname_size 32
89 #define USTAR_gname_offset 297
90 #define USTAR_gname_size 32
91 #define USTAR_rdevmajor_offset 329
92 #define USTAR_rdevmajor_size 6
93 #define USTAR_rdevmajor_max_size 8
94 #define USTAR_rdevminor_offset 337
95 #define USTAR_rdevminor_size 6
96 #define USTAR_rdevminor_max_size 8
97 #define USTAR_prefix_offset 345
98 #define USTAR_prefix_size 155
99 #define USTAR_padding_offset 500
100 #define USTAR_padding_size 12
101
102 /*
103  * A filled-in copy of the header for initialization.
104  */
105 static const char template_header[] = {
106         /* name: 100 bytes */
107         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
108         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
109         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
110         0,0,0,0,
111         /* Mode, space-null termination: 8 bytes */
112         '0','0','0','0','0','0', ' ','\0',
113         /* uid, space-null termination: 8 bytes */
114         '0','0','0','0','0','0', ' ','\0',
115         /* gid, space-null termination: 8 bytes */
116         '0','0','0','0','0','0', ' ','\0',
117         /* size, space termation: 12 bytes */
118         '0','0','0','0','0','0','0','0','0','0','0', ' ',
119         /* mtime, space termation: 12 bytes */
120         '0','0','0','0','0','0','0','0','0','0','0', ' ',
121         /* Initial checksum value: 8 spaces */
122         ' ',' ',' ',' ',' ',' ',' ',' ',
123         /* Typeflag: 1 byte */
124         '0',                    /* '0' = regular file */
125         /* Linkname: 100 bytes */
126         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
127         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
128         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
129         0,0,0,0,
130         /* Magic: 6 bytes, Version: 2 bytes */
131         'u','s','t','a','r','\0', '0','0',
132         /* Uname: 32 bytes */
133         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
134         /* Gname: 32 bytes */
135         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
136         /* rdevmajor + space/null padding: 8 bytes */
137         '0','0','0','0','0','0', ' ','\0',
138         /* rdevminor + space/null padding: 8 bytes */
139         '0','0','0','0','0','0', ' ','\0',
140         /* Prefix: 155 bytes */
141         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
142         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
143         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
144         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,
145         0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,
146         /* Padding: 12 bytes */
147         0,0,0,0,0,0,0,0, 0,0,0,0
148 };
149
150 static ssize_t  archive_write_ustar_data(struct archive_write *a, const void *buff,
151                     size_t s);
152 static int      archive_write_ustar_free(struct archive_write *);
153 static int      archive_write_ustar_close(struct archive_write *);
154 static int      archive_write_ustar_finish_entry(struct archive_write *);
155 static int      archive_write_ustar_header(struct archive_write *,
156                     struct archive_entry *entry);
157 static int      archive_write_ustar_options(struct archive_write *,
158                     const char *, const char *);
159 static int      format_256(int64_t, char *, int);
160 static int      format_number(int64_t, char *, int size, int max, int strict);
161 static int      format_octal(int64_t, char *, int);
162
163 /*
164  * Set output format to 'ustar' format.
165  */
166 int
167 archive_write_set_format_ustar(struct archive *_a)
168 {
169         struct archive_write *a = (struct archive_write *)_a;
170         struct ustar *ustar;
171
172         archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
173             ARCHIVE_STATE_NEW, "archive_write_set_format_ustar");
174
175         /* If someone else was already registered, unregister them. */
176         if (a->format_free != NULL)
177                 (a->format_free)(a);
178
179         /* Basic internal sanity test. */
180         if (sizeof(template_header) != 512) {
181                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
182                     "Internal: template_header wrong size: %zu should be 512",
183                     sizeof(template_header));
184                 return (ARCHIVE_FATAL);
185         }
186
187         ustar = (struct ustar *)malloc(sizeof(*ustar));
188         if (ustar == NULL) {
189                 archive_set_error(&a->archive, ENOMEM,
190                     "Can't allocate ustar data");
191                 return (ARCHIVE_FATAL);
192         }
193         memset(ustar, 0, sizeof(*ustar));
194         a->format_data = ustar;
195         a->format_name = "ustar";
196         a->format_options = archive_write_ustar_options;
197         a->format_write_header = archive_write_ustar_header;
198         a->format_write_data = archive_write_ustar_data;
199         a->format_close = archive_write_ustar_close;
200         a->format_free = archive_write_ustar_free;
201         a->format_finish_entry = archive_write_ustar_finish_entry;
202         a->archive.archive_format = ARCHIVE_FORMAT_TAR_USTAR;
203         a->archive.archive_format_name = "POSIX ustar";
204         return (ARCHIVE_OK);
205 }
206
207 static int
208 archive_write_ustar_options(struct archive_write *a, const char *key,
209     const char *val)
210 {
211         struct ustar *ustar = (struct ustar *)a->format_data;
212         int ret = ARCHIVE_FAILED;
213
214         if (strcmp(key, "hdrcharset")  == 0) {
215                 if (val == NULL || val[0] == 0)
216                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
217                             "%s: hdrcharset option needs a character-set name",
218                             a->format_name);
219                 else {
220                         ustar->opt_sconv = archive_string_conversion_to_charset(
221                             &a->archive, val, 0);
222                         if (ustar->opt_sconv != NULL)
223                                 ret = ARCHIVE_OK;
224                         else
225                                 ret = ARCHIVE_FATAL;
226                 }
227                 return (ret);
228         }
229
230         /* Note: The "warn" return is just to inform the options
231          * supervisor that we didn't handle it.  It will generate
232          * a suitable error if no one used this option. */
233         return (ARCHIVE_WARN);
234 }
235
236 static int
237 archive_write_ustar_header(struct archive_write *a, struct archive_entry *entry)
238 {
239         char buff[512];
240         int ret, ret2;
241         struct ustar *ustar;
242         struct archive_entry *entry_main;
243         struct archive_string_conv *sconv;
244
245         ustar = (struct ustar *)a->format_data;
246
247         /* Setup default string conversion. */
248         if (ustar->opt_sconv == NULL) {
249                 if (!ustar->init_default_conversion) {
250                         ustar->sconv_default =
251                             archive_string_default_conversion_for_write(&(a->archive));
252                         ustar->init_default_conversion = 1;
253                 }
254                 sconv = ustar->sconv_default;
255         } else
256                 sconv = ustar->opt_sconv;
257
258         /* Sanity check. */
259         if (archive_entry_pathname(entry) == NULL) {
260                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
261                     "Can't record entry in tar file without pathname");
262                 return (ARCHIVE_FAILED);
263         }
264
265         /* Only regular files (not hardlinks) have data. */
266         if (archive_entry_hardlink(entry) != NULL ||
267             archive_entry_symlink(entry) != NULL ||
268             !(archive_entry_filetype(entry) == AE_IFREG))
269                 archive_entry_set_size(entry, 0);
270
271         if (AE_IFDIR == archive_entry_filetype(entry)) {
272                 const char *p;
273                 size_t path_length;
274                 /*
275                  * Ensure a trailing '/'.  Modify the entry so
276                  * the client sees the change.
277                  */
278 #if defined(_WIN32) && !defined(__CYGWIN__)
279                 const wchar_t *wp;
280
281                 wp = archive_entry_pathname_w(entry);
282                 if (wp != NULL && wp[wcslen(wp) -1] != L'/') {
283                         struct archive_wstring ws;
284
285                         archive_string_init(&ws);
286                         path_length = wcslen(wp);
287                         if (archive_wstring_ensure(&ws,
288                             path_length + 2) == NULL) {
289                                 archive_set_error(&a->archive, ENOMEM,
290                                     "Can't allocate ustar data");
291                                 archive_wstring_free(&ws);
292                                 return(ARCHIVE_FATAL);
293                         }
294                         /* Should we keep '\' ? */
295                         if (wp[path_length -1] == L'\\')
296                                 path_length--;
297                         archive_wstrncpy(&ws, wp, path_length);
298                         archive_wstrappend_wchar(&ws, L'/');
299                         archive_entry_copy_pathname_w(entry, ws.s);
300                         archive_wstring_free(&ws);
301                         p = NULL;
302                 } else
303 #endif
304                         p = archive_entry_pathname(entry);
305                 /*
306                  * On Windows, this is a backup operation just in
307                  * case getting WCS failed. On POSIX, this is a
308                  * normal operation.
309                  */
310                 if (p != NULL && p[strlen(p) - 1] != '/') {
311                         struct archive_string as;
312
313                         archive_string_init(&as);
314                         path_length = strlen(p);
315                         if (archive_string_ensure(&as,
316                             path_length + 2) == NULL) {
317                                 archive_set_error(&a->archive, ENOMEM,
318                                     "Can't allocate ustar data");
319                                 archive_string_free(&as);
320                                 return(ARCHIVE_FATAL);
321                         }
322 #if defined(_WIN32) && !defined(__CYGWIN__)
323                         /* NOTE: This might break the pathname
324                          * if the current code page is CP932 and
325                          * the pathname includes a character '\'
326                          * as a part of its multibyte pathname. */
327                         if (p[strlen(p) -1] == '\\')
328                                 path_length--;
329                         else
330 #endif
331                         archive_strncpy(&as, p, path_length);
332                         archive_strappend_char(&as, '/');
333                         archive_entry_copy_pathname(entry, as.s);
334                         archive_string_free(&as);
335                 }
336         }
337
338 #if defined(_WIN32) && !defined(__CYGWIN__)
339         /* Make sure the path separators in pahtname, hardlink and symlink
340          * are all slash '/', not the Windows path separator '\'. */
341         entry_main = __la_win_entry_in_posix_pathseparator(entry);
342         if (entry_main == NULL) {
343                 archive_set_error(&a->archive, ENOMEM,
344                     "Can't allocate ustar data");
345                 return(ARCHIVE_FATAL);
346         }
347         if (entry != entry_main)
348                 entry = entry_main;
349         else
350                 entry_main = NULL;
351 #else
352         entry_main = NULL;
353 #endif
354         ret = __archive_write_format_header_ustar(a, buff, entry, -1, 1, sconv);
355         if (ret < ARCHIVE_WARN) {
356                 if (entry_main)
357                         archive_entry_free(entry_main);
358                 return (ret);
359         }
360         ret2 = __archive_write_output(a, buff, 512);
361         if (ret2 < ARCHIVE_WARN) {
362                 if (entry_main)
363                         archive_entry_free(entry_main);
364                 return (ret2);
365         }
366         if (ret2 < ret)
367                 ret = ret2;
368
369         ustar->entry_bytes_remaining = archive_entry_size(entry);
370         ustar->entry_padding = 0x1ff & (-(int64_t)ustar->entry_bytes_remaining);
371         if (entry_main)
372                 archive_entry_free(entry_main);
373         return (ret);
374 }
375
376 /*
377  * Format a basic 512-byte "ustar" header.
378  *
379  * Returns -1 if format failed (due to field overflow).
380  * Note that this always formats as much of the header as possible.
381  * If "strict" is set to zero, it will extend numeric fields as
382  * necessary (overwriting terminators or using base-256 extensions).
383  *
384  * This is exported so that other 'tar' formats can use it.
385  */
386 int
387 __archive_write_format_header_ustar(struct archive_write *a, char h[512],
388     struct archive_entry *entry, int tartype, int strict,
389     struct archive_string_conv *sconv)
390 {
391         unsigned int checksum;
392         int i, r, ret;
393         size_t copy_length;
394         const char *p, *pp;
395         int mytartype;
396
397         ret = 0;
398         mytartype = -1;
399         /*
400          * The "template header" already includes the "ustar"
401          * signature, various end-of-field markers and other required
402          * elements.
403          */
404         memcpy(h, &template_header, 512);
405
406         /*
407          * Because the block is already null-filled, and strings
408          * are allowed to exactly fill their destination (without null),
409          * I use memcpy(dest, src, strlen()) here a lot to copy strings.
410          */
411         r = archive_entry_pathname_l(entry, &pp, &copy_length, sconv);
412         if (r != 0) {
413                 if (errno == ENOMEM) {
414                         archive_set_error(&a->archive, ENOMEM,
415                             "Can't allocate memory for Pathname");
416                         return (ARCHIVE_FATAL);
417                 }
418                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
419                     "Can't translate pathname '%s' to %s",
420                     pp, archive_string_conversion_charset_name(sconv));
421                 ret = ARCHIVE_WARN;
422         }
423         if (copy_length <= USTAR_name_size)
424                 memcpy(h + USTAR_name_offset, pp, copy_length);
425         else {
426                 /* Store in two pieces, splitting at a '/'. */
427                 p = strchr(pp + copy_length - USTAR_name_size - 1, '/');
428                 /*
429                  * Look for the next '/' if we chose the first character
430                  * as the separator.  (ustar format doesn't permit
431                  * an empty prefix.)
432                  */
433                 if (p == pp)
434                         p = strchr(p + 1, '/');
435                 /* Fail if the name won't fit. */
436                 if (!p) {
437                         /* No separator. */
438                         archive_set_error(&a->archive, ENAMETOOLONG,
439                             "Pathname too long");
440                         ret = ARCHIVE_FAILED;
441                 } else if (p[1] == '\0') {
442                         /*
443                          * The only feasible separator is a final '/';
444                          * this would result in a non-empty prefix and
445                          * an empty name, which POSIX doesn't
446                          * explicitly forbid, but it just feels wrong.
447                          */
448                         archive_set_error(&a->archive, ENAMETOOLONG,
449                             "Pathname too long");
450                         ret = ARCHIVE_FAILED;
451                 } else if (p  > pp + USTAR_prefix_size) {
452                         /* Prefix is too long. */
453                         archive_set_error(&a->archive, ENAMETOOLONG,
454                             "Pathname too long");
455                         ret = ARCHIVE_FAILED;
456                 } else {
457                         /* Copy prefix and remainder to appropriate places */
458                         memcpy(h + USTAR_prefix_offset, pp, p - pp);
459                         memcpy(h + USTAR_name_offset, p + 1,
460                             pp + copy_length - p - 1);
461                 }
462         }
463
464         r = archive_entry_hardlink_l(entry, &p, &copy_length, sconv);
465         if (r != 0) {
466                 if (errno == ENOMEM) {
467                         archive_set_error(&a->archive, ENOMEM,
468                             "Can't allocate memory for Linkname");
469                         return (ARCHIVE_FATAL);
470                 }
471                 archive_set_error(&a->archive,
472                     ARCHIVE_ERRNO_FILE_FORMAT,
473                     "Can't translate linkname '%s' to %s",
474                     p, archive_string_conversion_charset_name(sconv));
475                 ret = ARCHIVE_WARN;
476         }
477         if (copy_length > 0)
478                 mytartype = '1';
479         else {
480                 r = archive_entry_symlink_l(entry, &p, &copy_length, sconv);
481                 if (r != 0) {
482                         if (errno == ENOMEM) {
483                                 archive_set_error(&a->archive, ENOMEM,
484                                     "Can't allocate memory for Linkname");
485                                 return (ARCHIVE_FATAL);
486                         }
487                         archive_set_error(&a->archive,
488                             ARCHIVE_ERRNO_FILE_FORMAT,
489                             "Can't translate linkname '%s' to %s",
490                             p, archive_string_conversion_charset_name(sconv));
491                         ret = ARCHIVE_WARN;
492                 }
493         }
494         if (copy_length > 0) {
495                 if (copy_length > USTAR_linkname_size) {
496                         archive_set_error(&a->archive, ENAMETOOLONG,
497                             "Link contents too long");
498                         ret = ARCHIVE_FAILED;
499                         copy_length = USTAR_linkname_size;
500                 }
501                 memcpy(h + USTAR_linkname_offset, p, copy_length);
502         }
503
504         r = archive_entry_uname_l(entry, &p, &copy_length, sconv);
505         if (r != 0) {
506                 if (errno == ENOMEM) {
507                         archive_set_error(&a->archive, ENOMEM,
508                             "Can't allocate memory for Uname");
509                         return (ARCHIVE_FATAL);
510                 }
511                 archive_set_error(&a->archive,
512                     ARCHIVE_ERRNO_FILE_FORMAT,
513                     "Can't translate uname '%s' to %s",
514                     p, archive_string_conversion_charset_name(sconv));
515                 ret = ARCHIVE_WARN;
516         }
517         if (copy_length > 0) {
518                 if (copy_length > USTAR_uname_size) {
519                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
520                             "Username too long");
521                         ret = ARCHIVE_FAILED;
522                         copy_length = USTAR_uname_size;
523                 }
524                 memcpy(h + USTAR_uname_offset, p, copy_length);
525         }
526
527         r = archive_entry_gname_l(entry, &p, &copy_length, sconv);
528         if (r != 0) {
529                 if (errno == ENOMEM) {
530                         archive_set_error(&a->archive, ENOMEM,
531                             "Can't allocate memory for Gname");
532                         return (ARCHIVE_FATAL);
533                 }
534                 archive_set_error(&a->archive,
535                     ARCHIVE_ERRNO_FILE_FORMAT,
536                     "Can't translate gname '%s' to %s",
537                     p, archive_string_conversion_charset_name(sconv));
538                 ret = ARCHIVE_WARN;
539         }
540         if (copy_length > 0) {
541                 if (strlen(p) > USTAR_gname_size) {
542                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
543                             "Group name too long");
544                         ret = ARCHIVE_FAILED;
545                         copy_length = USTAR_gname_size;
546                 }
547                 memcpy(h + USTAR_gname_offset, p, copy_length);
548         }
549
550         if (format_number(archive_entry_mode(entry) & 07777,
551             h + USTAR_mode_offset, USTAR_mode_size, USTAR_mode_max_size, strict)) {
552                 archive_set_error(&a->archive, ERANGE,
553                     "Numeric mode too large");
554                 ret = ARCHIVE_FAILED;
555         }
556
557         if (format_number(archive_entry_uid(entry),
558             h + USTAR_uid_offset, USTAR_uid_size, USTAR_uid_max_size, strict)) {
559                 archive_set_error(&a->archive, ERANGE,
560                     "Numeric user ID too large");
561                 ret = ARCHIVE_FAILED;
562         }
563
564         if (format_number(archive_entry_gid(entry),
565             h + USTAR_gid_offset, USTAR_gid_size, USTAR_gid_max_size, strict)) {
566                 archive_set_error(&a->archive, ERANGE,
567                     "Numeric group ID too large");
568                 ret = ARCHIVE_FAILED;
569         }
570
571         if (format_number(archive_entry_size(entry),
572             h + USTAR_size_offset, USTAR_size_size, USTAR_size_max_size, strict)) {
573                 archive_set_error(&a->archive, ERANGE,
574                     "File size out of range");
575                 ret = ARCHIVE_FAILED;
576         }
577
578         if (format_number(archive_entry_mtime(entry),
579             h + USTAR_mtime_offset, USTAR_mtime_size, USTAR_mtime_max_size, strict)) {
580                 archive_set_error(&a->archive, ERANGE,
581                     "File modification time too large");
582                 ret = ARCHIVE_FAILED;
583         }
584
585         if (archive_entry_filetype(entry) == AE_IFBLK
586             || archive_entry_filetype(entry) == AE_IFCHR) {
587                 if (format_number(archive_entry_rdevmajor(entry),
588                     h + USTAR_rdevmajor_offset, USTAR_rdevmajor_size,
589                     USTAR_rdevmajor_max_size, strict)) {
590                         archive_set_error(&a->archive, ERANGE,
591                             "Major device number too large");
592                         ret = ARCHIVE_FAILED;
593                 }
594
595                 if (format_number(archive_entry_rdevminor(entry),
596                     h + USTAR_rdevminor_offset, USTAR_rdevminor_size,
597                     USTAR_rdevminor_max_size, strict)) {
598                         archive_set_error(&a->archive, ERANGE,
599                             "Minor device number too large");
600                         ret = ARCHIVE_FAILED;
601                 }
602         }
603
604         if (tartype >= 0) {
605                 h[USTAR_typeflag_offset] = tartype;
606         } else if (mytartype >= 0) {
607                 h[USTAR_typeflag_offset] = mytartype;
608         } else {
609                 switch (archive_entry_filetype(entry)) {
610                 case AE_IFREG: h[USTAR_typeflag_offset] = '0' ; break;
611                 case AE_IFLNK: h[USTAR_typeflag_offset] = '2' ; break;
612                 case AE_IFCHR: h[USTAR_typeflag_offset] = '3' ; break;
613                 case AE_IFBLK: h[USTAR_typeflag_offset] = '4' ; break;
614                 case AE_IFDIR: h[USTAR_typeflag_offset] = '5' ; break;
615                 case AE_IFIFO: h[USTAR_typeflag_offset] = '6' ; break;
616                 case AE_IFSOCK:
617                         archive_set_error(&a->archive,
618                             ARCHIVE_ERRNO_FILE_FORMAT,
619                             "tar format cannot archive socket");
620                         return (ARCHIVE_FAILED);
621                 default:
622                         archive_set_error(&a->archive,
623                             ARCHIVE_ERRNO_FILE_FORMAT,
624                             "tar format cannot archive this (mode=0%lo)",
625                             (unsigned long)archive_entry_mode(entry));
626                         ret = ARCHIVE_FAILED;
627                 }
628         }
629
630         checksum = 0;
631         for (i = 0; i < 512; i++)
632                 checksum += 255 & (unsigned int)h[i];
633         h[USTAR_checksum_offset + 6] = '\0'; /* Can't be pre-set in the template. */
634         /* h[USTAR_checksum_offset + 7] = ' '; */ /* This is pre-set in the template. */
635         format_octal(checksum, h + USTAR_checksum_offset, 6);
636         return (ret);
637 }
638
639 /*
640  * Format a number into a field, with some intelligence.
641  */
642 static int
643 format_number(int64_t v, char *p, int s, int maxsize, int strict)
644 {
645         int64_t limit;
646
647         limit = ((int64_t)1 << (s*3));
648
649         /* "Strict" only permits octal values with proper termination. */
650         if (strict)
651                 return (format_octal(v, p, s));
652
653         /*
654          * In non-strict mode, we allow the number to overwrite one or
655          * more bytes of the field termination.  Even old tar
656          * implementations should be able to handle this with no
657          * problem.
658          */
659         if (v >= 0) {
660                 while (s <= maxsize) {
661                         if (v < limit)
662                                 return (format_octal(v, p, s));
663                         s++;
664                         limit <<= 3;
665                 }
666         }
667
668         /* Base-256 can handle any number, positive or negative. */
669         return (format_256(v, p, maxsize));
670 }
671
672 /*
673  * Format a number into the specified field using base-256.
674  */
675 static int
676 format_256(int64_t v, char *p, int s)
677 {
678         p += s;
679         while (s-- > 0) {
680                 *--p = (char)(v & 0xff);
681                 v >>= 8;
682         }
683         *p |= 0x80; /* Set the base-256 marker bit. */
684         return (0);
685 }
686
687 /*
688  * Format a number into the specified field.
689  */
690 static int
691 format_octal(int64_t v, char *p, int s)
692 {
693         int len;
694
695         len = s;
696
697         /* Octal values can't be negative, so use 0. */
698         if (v < 0) {
699                 while (len-- > 0)
700                         *p++ = '0';
701                 return (-1);
702         }
703
704         p += s;         /* Start at the end and work backwards. */
705         while (s-- > 0) {
706                 *--p = (char)('0' + (v & 7));
707                 v >>= 3;
708         }
709
710         if (v == 0)
711                 return (0);
712
713         /* If it overflowed, fill field with max value. */
714         while (len-- > 0)
715                 *p++ = '7';
716
717         return (-1);
718 }
719
720 static int
721 archive_write_ustar_close(struct archive_write *a)
722 {
723         return (__archive_write_nulls(a, 512*2));
724 }
725
726 static int
727 archive_write_ustar_free(struct archive_write *a)
728 {
729         struct ustar *ustar;
730
731         ustar = (struct ustar *)a->format_data;
732         free(ustar);
733         a->format_data = NULL;
734         return (ARCHIVE_OK);
735 }
736
737 static int
738 archive_write_ustar_finish_entry(struct archive_write *a)
739 {
740         struct ustar *ustar;
741         int ret;
742
743         ustar = (struct ustar *)a->format_data;
744         ret = __archive_write_nulls(a,
745             (size_t)(ustar->entry_bytes_remaining + ustar->entry_padding));
746         ustar->entry_bytes_remaining = ustar->entry_padding = 0;
747         return (ret);
748 }
749
750 static ssize_t
751 archive_write_ustar_data(struct archive_write *a, const void *buff, size_t s)
752 {
753         struct ustar *ustar;
754         int ret;
755
756         ustar = (struct ustar *)a->format_data;
757         if (s > ustar->entry_bytes_remaining)
758                 s = (size_t)ustar->entry_bytes_remaining;
759         ret = __archive_write_output(a, buff, s);
760         ustar->entry_bytes_remaining -= s;
761         if (ret != ARCHIVE_OK)
762                 return (ret);
763         return (s);
764 }