]> git.cworth.org Git - tar/blob - src/list.c
Don't close file stream before EOF, closes #525818
[tar] / src / list.c
1 /* List a tar archive, with support routines for reading a tar archive.
2
3    Copyright (C) 1988, 1992, 1993, 1994, 1996, 1997, 1998, 1999, 2000,
4    2001, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5
6    Written by John Gilmore, on 1985-08-26.
7
8    This program is free software; you can redistribute it and/or modify it
9    under the terms of the GNU General Public License as published by the
10    Free Software Foundation; either version 3, or (at your option) any later
11    version.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
16    Public License for more details.
17
18    You should have received a copy of the GNU General Public License along
19    with this program; if not, write to the Free Software Foundation, Inc.,
20    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
21
22 #include <system.h>
23 #include <inttostr.h>
24 #include <quotearg.h>
25
26 #include "common.h"
27
28 #define max(a, b) ((a) < (b) ? (b) : (a))
29
30 union block *current_header;    /* points to current archive header */
31 enum archive_format current_format; /* recognized format */
32 union block *recent_long_name;  /* recent long name header and contents */
33 union block *recent_long_link;  /* likewise, for long link */
34 size_t recent_long_name_blocks; /* number of blocks in recent_long_name */
35 size_t recent_long_link_blocks; /* likewise, for long link */
36
37 static uintmax_t from_header (const char *, size_t, const char *,
38                               uintmax_t, uintmax_t, bool, bool);
39
40 /* Base 64 digits; see Internet RFC 2045 Table 1.  */
41 static char const base_64_digits[64] =
42 {
43   'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
44   'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
45   'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
46   'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
47   '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
48 };
49
50 /* Table of base-64 digit values indexed by unsigned chars.
51    The value is 64 for unsigned chars that are not base-64 digits.  */
52 static char base64_map[UCHAR_MAX + 1];
53
54 static void
55 base64_init (void)
56 {
57   int i;
58   memset (base64_map, 64, sizeof base64_map);
59   for (i = 0; i < 64; i++)
60     base64_map[(int) base_64_digits[i]] = i;
61 }
62
63 /* Main loop for reading an archive.  */
64 void
65 read_and (void (*do_something) (void))
66 {
67   enum read_header status = HEADER_STILL_UNREAD;
68   enum read_header prev_status;
69   struct timespec mtime;
70
71   base64_init ();
72   name_gather ();
73
74   open_archive (ACCESS_READ);
75   do
76     {
77       prev_status = status;
78       tar_stat_destroy (&current_stat_info);
79
80       status = read_header (false);
81       switch (status)
82         {
83         case HEADER_STILL_UNREAD:
84         case HEADER_SUCCESS_EXTENDED:
85           abort ();
86
87         case HEADER_SUCCESS:
88
89           /* Valid header.  We should decode next field (mode) first.
90              Ensure incoming names are null terminated.  */
91
92           if (! name_match (current_stat_info.file_name)
93               || (NEWER_OPTION_INITIALIZED (newer_mtime_option)
94                   /* FIXME: We get mtime now, and again later; this causes
95                      duplicate diagnostics if header.mtime is bogus.  */
96                   && ((mtime.tv_sec
97                        = TIME_FROM_HEADER (current_header->header.mtime)),
98                       /* FIXME: Grab fractional time stamps from
99                          extended header.  */
100                       mtime.tv_nsec = 0,
101                       current_stat_info.mtime = mtime,
102                       OLDER_TAR_STAT_TIME (current_stat_info, m)))
103               || excluded_name (current_stat_info.file_name))
104             {
105               switch (current_header->header.typeflag)
106                 {
107                 case GNUTYPE_VOLHDR:
108                 case GNUTYPE_MULTIVOL:
109                   break;
110
111                 case DIRTYPE:
112                   if (show_omitted_dirs_option)
113                     WARN ((0, 0, _("%s: Omitting"),
114                            quotearg_colon (current_stat_info.file_name)));
115                   /* Fall through.  */
116                 default:
117                   decode_header (current_header,
118                                  &current_stat_info, &current_format, 0);
119                   skip_member ();
120                   continue;
121                 }
122             }
123
124           (*do_something) ();
125           continue;
126
127         case HEADER_ZERO_BLOCK:
128           if (block_number_option)
129             {
130               char buf[UINTMAX_STRSIZE_BOUND];
131               fprintf (stdlis, _("block %s: ** Block of NULs **\n"),
132                        STRINGIFY_BIGINT (current_block_ordinal (), buf));
133             }
134
135           set_next_block_after (current_header);
136
137           if (!ignore_zeros_option)
138             {
139               char buf[UINTMAX_STRSIZE_BOUND];
140
141               status = read_header (false);
142               if (status == HEADER_ZERO_BLOCK)
143                 break;
144               /* 
145                * According to POSIX tar specs, this is wrong, but on the web
146                * there are some tar specs that can trigger this, and some tar
147                * implementations create tars according to that spec.  For now,
148                * let's not be pedantic about issuing the warning.
149                */
150 #if 0          
151               WARN ((0, 0, _("A lone zero block at %s"),
152                      STRINGIFY_BIGINT (current_block_ordinal (), buf)));
153 #endif
154               break;
155             }
156           status = prev_status;
157           continue;
158
159         case HEADER_END_OF_FILE:
160           if (block_number_option)
161             {
162               char buf[UINTMAX_STRSIZE_BOUND];
163               fprintf (stdlis, _("block %s: ** End of File **\n"),
164                        STRINGIFY_BIGINT (current_block_ordinal (), buf));
165             }
166           break;
167
168         case HEADER_FAILURE:
169           /* If the previous header was good, tell them that we are
170              skipping bad ones.  */
171           set_next_block_after (current_header);
172           switch (prev_status)
173             {
174             case HEADER_STILL_UNREAD:
175               ERROR ((0, 0, _("This does not look like a tar archive")));
176               /* Fall through.  */
177
178             case HEADER_ZERO_BLOCK:
179             case HEADER_SUCCESS:
180               if (block_number_option)
181                 {
182                   char buf[UINTMAX_STRSIZE_BOUND];
183                   off_t block_ordinal = current_block_ordinal ();
184                   block_ordinal -= recent_long_name_blocks;
185                   block_ordinal -= recent_long_link_blocks;
186                   fprintf (stdlis, _("block %s: "),
187                            STRINGIFY_BIGINT (block_ordinal, buf));
188                 }
189               ERROR ((0, 0, _("Skipping to next header")));
190               break;
191
192             case HEADER_END_OF_FILE:
193             case HEADER_FAILURE:
194               /* We are in the middle of a cascade of errors.  */
195               break;
196
197             case HEADER_SUCCESS_EXTENDED:
198               abort ();
199             }
200           continue;
201         }
202       break;
203     }
204   while (!all_names_found (&current_stat_info));
205
206   close_archive ();
207   names_notfound ();            /* print names not found */
208 }
209
210 /* Print a header block, based on tar options.  */
211 void
212 list_archive (void)
213 {
214   off_t block_ordinal = current_block_ordinal ();
215   /* Print the header block.  */
216
217   decode_header (current_header, &current_stat_info, &current_format, 0);
218   if (verbose_option)
219     print_header (&current_stat_info, block_ordinal);
220
221   if (incremental_option)
222     {
223       if (verbose_option > 2)
224         {
225           if (is_dumpdir (&current_stat_info))
226             list_dumpdir (current_stat_info.dumpdir,
227                           dumpdir_size (current_stat_info.dumpdir));
228         }
229     }
230
231   skip_member ();
232 }
233
234 /* Check header checksum */
235 /* The standard BSD tar sources create the checksum by adding up the
236    bytes in the header as type char.  I think the type char was unsigned
237    on the PDP-11, but it's signed on the Next and Sun.  It looks like the
238    sources to BSD tar were never changed to compute the checksum
239    correctly, so both the Sun and Next add the bytes of the header as
240    signed chars.  This doesn't cause a problem until you get a file with
241    a name containing characters with the high bit set.  So tar_checksum
242    computes two checksums -- signed and unsigned.  */
243
244 enum read_header
245 tar_checksum (union block *header, bool silent)
246 {
247   size_t i;
248   int unsigned_sum = 0;         /* the POSIX one :-) */
249   int signed_sum = 0;           /* the Sun one :-( */
250   int recorded_sum;
251   uintmax_t parsed_sum;
252   char *p;
253
254   p = header->buffer;
255   for (i = sizeof *header; i-- != 0;)
256     {
257       unsigned_sum += (unsigned char) *p;
258       signed_sum += (signed char) (*p++);
259     }
260
261   if (unsigned_sum == 0)
262     return HEADER_ZERO_BLOCK;
263
264   /* Adjust checksum to count the "chksum" field as blanks.  */
265
266   for (i = sizeof header->header.chksum; i-- != 0;)
267     {
268       unsigned_sum -= (unsigned char) header->header.chksum[i];
269       signed_sum -= (signed char) (header->header.chksum[i]);
270     }
271   unsigned_sum += ' ' * sizeof header->header.chksum;
272   signed_sum += ' ' * sizeof header->header.chksum;
273
274   parsed_sum = from_header (header->header.chksum,
275                             sizeof header->header.chksum, 0,
276                             (uintmax_t) 0,
277                             (uintmax_t) TYPE_MAXIMUM (int), true, silent);
278   if (parsed_sum == (uintmax_t) -1)
279     return HEADER_FAILURE;
280
281   recorded_sum = parsed_sum;
282
283   if (unsigned_sum != recorded_sum && signed_sum != recorded_sum)
284     return HEADER_FAILURE;
285
286   return HEADER_SUCCESS;
287 }
288
289 /* Read a block that's supposed to be a header block.  Return its
290    address in "current_header", and if it is good, the file's size
291    and names (file name, link name) in *info.
292
293    Return 1 for success, 0 if the checksum is bad, EOF on eof, 2 for a
294    block full of zeros (EOF marker).
295
296    If RAW_EXTENDED_HEADERS is nonzero, do not automagically fold the
297    GNU long name and link headers into later headers.
298
299    You must always set_next_block_after(current_header) to skip past
300    the header which this routine reads.  */
301
302 enum read_header
303 read_header_primitive (bool raw_extended_headers, struct tar_stat_info *info)
304 {
305   union block *header;
306   union block *header_copy;
307   char *bp;
308   union block *data_block;
309   size_t size, written;
310   union block *next_long_name = 0;
311   union block *next_long_link = 0;
312   size_t next_long_name_blocks = 0;
313   size_t next_long_link_blocks = 0;
314
315   while (1)
316     {
317       enum read_header status;
318
319       header = find_next_block ();
320       current_header = header;
321       if (!header)
322         return HEADER_END_OF_FILE;
323
324       if ((status = tar_checksum (header, false)) != HEADER_SUCCESS)
325         return status;
326
327       /* Good block.  Decode file size and return.  */
328
329       if (header->header.typeflag == LNKTYPE)
330         info->stat.st_size = 0; /* links 0 size on tape */
331       else
332         info->stat.st_size = OFF_FROM_HEADER (header->header.size);
333
334       if (header->header.typeflag == GNUTYPE_LONGNAME
335           || header->header.typeflag == GNUTYPE_LONGLINK
336           || header->header.typeflag == XHDTYPE
337           || header->header.typeflag == XGLTYPE
338           || header->header.typeflag == SOLARIS_XHDTYPE)
339         {
340           if (raw_extended_headers)
341             return HEADER_SUCCESS_EXTENDED;
342           else if (header->header.typeflag == GNUTYPE_LONGNAME
343                    || header->header.typeflag == GNUTYPE_LONGLINK)
344             {
345               size_t name_size = info->stat.st_size;
346               size_t n = name_size % BLOCKSIZE;
347               size = name_size + BLOCKSIZE;
348               if (n)
349                 size += BLOCKSIZE - n;
350
351               if (name_size != info->stat.st_size || size < name_size)
352                 xalloc_die ();
353
354               header_copy = xmalloc (size + 1);
355
356               if (header->header.typeflag == GNUTYPE_LONGNAME)
357                 {
358                   if (next_long_name)
359                     free (next_long_name);
360                   next_long_name = header_copy;
361                   next_long_name_blocks = size / BLOCKSIZE;
362                 }
363               else
364                 {
365                   if (next_long_link)
366                     free (next_long_link);
367                   next_long_link = header_copy;
368                   next_long_link_blocks = size / BLOCKSIZE;
369                 }
370
371               set_next_block_after (header);
372               *header_copy = *header;
373               bp = header_copy->buffer + BLOCKSIZE;
374
375               for (size -= BLOCKSIZE; size > 0; size -= written)
376                 {
377                   data_block = find_next_block ();
378                   if (! data_block)
379                     {
380                       ERROR ((0, 0, _("Unexpected EOF in archive")));
381                       break;
382                     }
383                   written = available_space_after (data_block);
384                   if (written > size)
385                     written = size;
386
387                   memcpy (bp, data_block->buffer, written);
388                   bp += written;
389                   set_next_block_after ((union block *)
390                                         (data_block->buffer + written - 1));
391                 }
392
393               *bp = '\0';
394             }
395           else if (header->header.typeflag == XHDTYPE
396                    || header->header.typeflag == SOLARIS_XHDTYPE)
397             xheader_read (&info->xhdr, header,
398                           OFF_FROM_HEADER (header->header.size));
399           else if (header->header.typeflag == XGLTYPE)
400             {
401               struct xheader xhdr;
402               memset (&xhdr, 0, sizeof xhdr);
403               xheader_read (&xhdr, header,
404                             OFF_FROM_HEADER (header->header.size));
405               xheader_decode_global (&xhdr);
406               xheader_destroy (&xhdr);
407             }
408
409           /* Loop!  */
410
411         }
412       else
413         {
414           char const *name;
415           struct posix_header const *h = &current_header->header;
416           char namebuf[sizeof h->prefix + 1 + NAME_FIELD_SIZE + 1];
417
418           if (recent_long_name)
419             free (recent_long_name);
420
421           if (next_long_name)
422             {
423               name = next_long_name->buffer + BLOCKSIZE;
424               recent_long_name = next_long_name;
425               recent_long_name_blocks = next_long_name_blocks;
426             }
427           else
428             {
429               /* Accept file names as specified by POSIX.1-1996
430                  section 10.1.1.  */
431               char *np = namebuf;
432
433               if (h->prefix[0] && strcmp (h->magic, TMAGIC) == 0)
434                 {
435                   memcpy (np, h->prefix, sizeof h->prefix);
436                   np[sizeof h->prefix] = '\0';
437                   np += strlen (np);
438                   *np++ = '/';
439                 }
440               memcpy (np, h->name, sizeof h->name);
441               np[sizeof h->name] = '\0';
442               name = namebuf;
443               recent_long_name = 0;
444               recent_long_name_blocks = 0;
445             }
446           assign_string (&info->orig_file_name, name);
447           assign_string (&info->file_name, name);
448           info->had_trailing_slash = strip_trailing_slashes (info->file_name);
449
450           if (recent_long_link)
451             free (recent_long_link);
452
453           if (next_long_link)
454             {
455               name = next_long_link->buffer + BLOCKSIZE;
456               recent_long_link = next_long_link;
457               recent_long_link_blocks = next_long_link_blocks;
458             }
459           else
460             {
461               memcpy (namebuf, h->linkname, sizeof h->linkname);
462               namebuf[sizeof h->linkname] = '\0';
463               name = namebuf;
464               recent_long_link = 0;
465               recent_long_link_blocks = 0;
466             }
467           assign_string (&info->link_name, name);
468
469           return HEADER_SUCCESS;
470         }
471     }
472 }
473
474 enum read_header
475 read_header (bool raw_extended_headers)
476 {
477   return read_header_primitive (raw_extended_headers, &current_stat_info);
478 }
479
480 static char *
481 decode_xform (char *file_name, void *data)
482 {
483   int type = *(int*)data;
484
485   switch (type)
486     {
487     case XFORM_SYMLINK:
488       /* FIXME: It is not quite clear how and to which extent are the symbolic
489          links subject to filename transformation.  In the absence of another
490          solution, symbolic links are exempt from component stripping and
491          name suffix normalization, but subject to filename transformation
492          proper. */ 
493       return file_name;
494       
495     case XFORM_LINK:
496       file_name = safer_name_suffix (file_name, true, absolute_names_option);
497       break;
498       
499     case XFORM_REGFILE:
500       file_name = safer_name_suffix (file_name, false, absolute_names_option);
501       break;
502     }
503   
504   if (strip_name_components)
505     {
506       size_t prefix_len = stripped_prefix_len (file_name,
507                                                strip_name_components);
508       if (prefix_len == (size_t) -1)
509         prefix_len = strlen (file_name);
510       file_name += prefix_len;
511     }
512   return file_name;
513 }
514
515 bool
516 transform_member_name (char **pinput, int type)
517 {
518   return transform_name_fp (pinput, type, decode_xform, &type);
519 }
520
521 #define ISOCTAL(c) ((c)>='0'&&(c)<='7')
522
523 /* Decode things from a file HEADER block into STAT_INFO, also setting
524    *FORMAT_POINTER depending on the header block format.  If
525    DO_USER_GROUP, decode the user/group information (this is useful
526    for extraction, but waste time when merely listing).
527
528    read_header() has already decoded the checksum and length, so we don't.
529
530    This routine should *not* be called twice for the same block, since
531    the two calls might use different DO_USER_GROUP values and thus
532    might end up with different uid/gid for the two calls.  If anybody
533    wants the uid/gid they should decode it first, and other callers
534    should decode it without uid/gid before calling a routine,
535    e.g. print_header, that assumes decoded data.  */
536 void
537 decode_header (union block *header, struct tar_stat_info *stat_info,
538                enum archive_format *format_pointer, int do_user_group)
539 {
540   enum archive_format format;
541
542   if (strcmp (header->header.magic, TMAGIC) == 0)
543     {
544       if (header->star_header.prefix[130] == 0
545           && ISOCTAL (header->star_header.atime[0])
546           && header->star_header.atime[11] == ' '
547           && ISOCTAL (header->star_header.ctime[0])
548           && header->star_header.ctime[11] == ' ')
549         format = STAR_FORMAT;
550       else if (stat_info->xhdr.size)
551         format = POSIX_FORMAT;
552       else
553         format = USTAR_FORMAT;
554     }
555   else if (strcmp (header->header.magic, OLDGNU_MAGIC) == 0)
556     format = OLDGNU_FORMAT;
557   else
558     format = V7_FORMAT;
559   *format_pointer = format;
560
561   stat_info->stat.st_mode = MODE_FROM_HEADER (header->header.mode);
562   stat_info->mtime.tv_sec = TIME_FROM_HEADER (header->header.mtime);
563   stat_info->mtime.tv_nsec = 0;
564   assign_string (&stat_info->uname,
565                  header->header.uname[0] ? header->header.uname : NULL);
566   assign_string (&stat_info->gname,
567                  header->header.gname[0] ? header->header.gname : NULL);
568
569   if (format == OLDGNU_FORMAT && incremental_option)
570     {
571       stat_info->atime.tv_sec = TIME_FROM_HEADER (header->oldgnu_header.atime);
572       stat_info->ctime.tv_sec = TIME_FROM_HEADER (header->oldgnu_header.ctime);
573       stat_info->atime.tv_nsec = stat_info->ctime.tv_nsec = 0;
574     }
575   else if (format == STAR_FORMAT)
576     {
577       stat_info->atime.tv_sec = TIME_FROM_HEADER (header->star_header.atime);
578       stat_info->ctime.tv_sec = TIME_FROM_HEADER (header->star_header.ctime);
579       stat_info->atime.tv_nsec = stat_info->ctime.tv_nsec = 0;
580     }
581   else
582     stat_info->atime = stat_info->ctime = start_time;
583
584   if (format == V7_FORMAT)
585     {
586       stat_info->stat.st_uid = UID_FROM_HEADER (header->header.uid);
587       stat_info->stat.st_gid = GID_FROM_HEADER (header->header.gid);
588       stat_info->stat.st_rdev = 0;
589     }
590   else
591     {
592       if (do_user_group)
593         {
594           /* FIXME: Decide if this should somewhat depend on -p.  */
595
596           if (numeric_owner_option
597               || !*header->header.uname
598               || !uname_to_uid (header->header.uname, &stat_info->stat.st_uid))
599             stat_info->stat.st_uid = UID_FROM_HEADER (header->header.uid);
600
601           if (numeric_owner_option
602               || !*header->header.gname
603               || !gname_to_gid (header->header.gname, &stat_info->stat.st_gid))
604             stat_info->stat.st_gid = GID_FROM_HEADER (header->header.gid);
605         }
606
607       switch (header->header.typeflag)
608         {
609         case BLKTYPE:
610         case CHRTYPE:
611           stat_info->stat.st_rdev =
612             makedev (MAJOR_FROM_HEADER (header->header.devmajor),
613                      MINOR_FROM_HEADER (header->header.devminor));
614           break;
615
616         default:
617           stat_info->stat.st_rdev = 0;
618         }
619     }
620
621   stat_info->archive_file_size = stat_info->stat.st_size;
622   xheader_decode (stat_info);
623
624   if (sparse_member_p (stat_info))
625     {
626       sparse_fixup_header (stat_info);
627       stat_info->is_sparse = true;
628     }
629   else
630     {
631       stat_info->is_sparse = false;
632       if (((current_format == GNU_FORMAT
633             || current_format == OLDGNU_FORMAT)
634            && current_header->header.typeflag == GNUTYPE_DUMPDIR)
635           || stat_info->dumpdir)
636         stat_info->is_dumpdir = true;
637     }
638
639   transform_member_name (&stat_info->file_name, XFORM_REGFILE);
640   switch (header->header.typeflag)
641     {
642     case SYMTYPE:
643       transform_member_name (&stat_info->link_name, XFORM_SYMLINK);
644       break;
645       
646     case LNKTYPE:
647       transform_member_name (&stat_info->link_name, XFORM_LINK);
648     }
649 }
650
651 /* Convert buffer at WHERE0 of size DIGS from external format to
652    uintmax_t.  DIGS must be positive.  If TYPE is nonnull, the data
653    are of type TYPE.  The buffer must represent a value in the range
654    -MINUS_MINVAL through MAXVAL.  If OCTAL_ONLY, allow only octal
655    numbers instead of the other GNU extensions.  Return -1 on error,
656    diagnosing the error if TYPE is nonnull and if !SILENT.  */
657 static uintmax_t
658 from_header (char const *where0, size_t digs, char const *type,
659              uintmax_t minus_minval, uintmax_t maxval,
660              bool octal_only, bool silent)
661 {
662   uintmax_t value;
663   char const *where = where0;
664   char const *lim = where + digs;
665   int negative = 0;
666
667   /* Accommodate buggy tar of unknown vintage, which outputs leading
668      NUL if the previous field overflows.  */
669   where += !*where;
670
671   /* Accommodate older tars, which output leading spaces.  */
672   for (;;)
673     {
674       if (where == lim)
675         {
676           if (type && !silent)
677             ERROR ((0, 0,
678                     /* TRANSLATORS: %s is type of the value (gid_t, uid_t, etc.) */
679                     _("Blanks in header where numeric %s value expected"),
680                     type));
681           return -1;
682         }
683       if (!ISSPACE ((unsigned char) *where))
684         break;
685       where++;
686     }
687
688   value = 0;
689   if (ISODIGIT (*where))
690     {
691       char const *where1 = where;
692       uintmax_t overflow = 0;
693
694       for (;;)
695         {
696           value += *where++ - '0';
697           if (where == lim || ! ISODIGIT (*where))
698             break;
699           overflow |= value ^ (value << LG_8 >> LG_8);
700           value <<= LG_8;
701         }
702
703       /* Parse the output of older, unportable tars, which generate
704          negative values in two's complement octal.  If the leading
705          nonzero digit is 1, we can't recover the original value
706          reliably; so do this only if the digit is 2 or more.  This
707          catches the common case of 32-bit negative time stamps.  */
708       if ((overflow || maxval < value) && '2' <= *where1 && type)
709         {
710           /* Compute the negative of the input value, assuming two's
711              complement.  */
712           int digit = (*where1 - '0') | 4;
713           overflow = 0;
714           value = 0;
715           where = where1;
716           for (;;)
717             {
718               value += 7 - digit;
719               where++;
720               if (where == lim || ! ISODIGIT (*where))
721                 break;
722               digit = *where - '0';
723               overflow |= value ^ (value << LG_8 >> LG_8);
724               value <<= LG_8;
725             }
726           value++;
727           overflow |= !value;
728
729           if (!overflow && value <= minus_minval)
730             {
731               if (!silent)
732                 WARN ((0, 0,
733                        /* TRANSLATORS: Second %s is a type name (gid_t,uid_t,etc.) */
734                        _("Archive octal value %.*s is out of %s range; assuming two's complement"),
735                        (int) (where - where1), where1, type));
736               negative = 1;
737             }
738         }
739
740       if (overflow)
741         {
742           if (type && !silent)
743             ERROR ((0, 0,
744                     /* TRANSLATORS: Second %s is a type name (gid_t,uid_t,etc.) */
745                     _("Archive octal value %.*s is out of %s range"),
746                     (int) (where - where1), where1, type));
747           return -1;
748         }
749     }
750   else if (octal_only)
751     {
752       /* Suppress the following extensions.  */
753     }
754   else if (*where == '-' || *where == '+')
755     {
756       /* Parse base-64 output produced only by tar test versions
757          1.13.6 (1999-08-11) through 1.13.11 (1999-08-23).
758          Support for this will be withdrawn in future releases.  */
759       int dig;
760       if (!silent)
761         {
762           static bool warned_once;
763           if (! warned_once)
764             {
765               warned_once = true;
766               WARN ((0, 0, _("Archive contains obsolescent base-64 headers")));
767             }
768         }
769       negative = *where++ == '-';
770       while (where != lim
771              && (dig = base64_map[(unsigned char) *where]) < 64)
772         {
773           if (value << LG_64 >> LG_64 != value)
774             {
775               char *string = alloca (digs + 1);
776               memcpy (string, where0, digs);
777               string[digs] = '\0';
778               if (type && !silent)
779                 ERROR ((0, 0,
780                         _("Archive signed base-64 string %s is out of %s range"),
781                         quote (string), type));
782               return -1;
783             }
784           value = (value << LG_64) | dig;
785           where++;
786         }
787     }
788   else if (*where == '\200' /* positive base-256 */
789            || *where == '\377' /* negative base-256 */)
790     {
791       /* Parse base-256 output.  A nonnegative number N is
792          represented as (256**DIGS)/2 + N; a negative number -N is
793          represented as (256**DIGS) - N, i.e. as two's complement.
794          The representation guarantees that the leading bit is
795          always on, so that we don't confuse this format with the
796          others (assuming ASCII bytes of 8 bits or more).  */
797       int signbit = *where & (1 << (LG_256 - 2));
798       uintmax_t topbits = (((uintmax_t) - signbit)
799                            << (CHAR_BIT * sizeof (uintmax_t)
800                                - LG_256 - (LG_256 - 2)));
801       value = (*where++ & ((1 << (LG_256 - 2)) - 1)) - signbit;
802       for (;;)
803         {
804           value = (value << LG_256) + (unsigned char) *where++;
805           if (where == lim)
806             break;
807           if (((value << LG_256 >> LG_256) | topbits) != value)
808             {
809               if (type && !silent)
810                 ERROR ((0, 0,
811                         _("Archive base-256 value is out of %s range"),
812                         type));
813               return -1;
814             }
815         }
816       negative = signbit;
817       if (negative)
818         value = -value;
819     }
820
821   if (where != lim && *where && !ISSPACE ((unsigned char) *where))
822     {
823       if (type)
824         {
825           char buf[1000]; /* Big enough to represent any header.  */
826           static struct quoting_options *o;
827
828           if (!o)
829             {
830               o = clone_quoting_options (0);
831               set_quoting_style (o, locale_quoting_style);
832             }
833
834           while (where0 != lim && ! lim[-1])
835             lim--;
836           quotearg_buffer (buf, sizeof buf, where0, lim - where, o);
837           if (!silent)
838             ERROR ((0, 0,
839                     /* TRANSLATORS: Second %s is a type name (gid_t,uid_t,etc.) */
840                     _("Archive contains %.*s where numeric %s value expected"),
841                     (int) sizeof buf, buf, type));
842         }
843
844       return -1;
845     }
846
847   if (value <= (negative ? minus_minval : maxval))
848     return negative ? -value : value;
849
850   if (type && !silent)
851     {
852       char minval_buf[UINTMAX_STRSIZE_BOUND + 1];
853       char maxval_buf[UINTMAX_STRSIZE_BOUND];
854       char value_buf[UINTMAX_STRSIZE_BOUND + 1];
855       char *minval_string = STRINGIFY_BIGINT (minus_minval, minval_buf + 1);
856       char *value_string = STRINGIFY_BIGINT (value, value_buf + 1);
857       if (negative)
858         *--value_string = '-';
859       if (minus_minval)
860         *--minval_string = '-';
861       /* TRANSLATORS: Second %s is type name (gid_t,uid_t,etc.) */
862       ERROR ((0, 0, _("Archive value %s is out of %s range %s..%s"),
863               value_string, type,
864               minval_string, STRINGIFY_BIGINT (maxval, maxval_buf)));
865     }
866
867   return -1;
868 }
869
870 gid_t
871 gid_from_header (const char *p, size_t s)
872 {
873   return from_header (p, s, "gid_t",
874                       - (uintmax_t) TYPE_MINIMUM (gid_t),
875                       (uintmax_t) TYPE_MAXIMUM (gid_t),
876                       false, false);
877 }
878
879 major_t
880 major_from_header (const char *p, size_t s)
881 {
882   return from_header (p, s, "major_t",
883                       - (uintmax_t) TYPE_MINIMUM (major_t),
884                       (uintmax_t) TYPE_MAXIMUM (major_t), false, false);
885 }
886
887 minor_t
888 minor_from_header (const char *p, size_t s)
889 {
890   return from_header (p, s, "minor_t",
891                       - (uintmax_t) TYPE_MINIMUM (minor_t),
892                       (uintmax_t) TYPE_MAXIMUM (minor_t), false, false);
893 }
894
895 mode_t
896 mode_from_header (const char *p, size_t s)
897 {
898   /* Do not complain about unrecognized mode bits.  */
899   unsigned u = from_header (p, s, "mode_t",
900                             - (uintmax_t) TYPE_MINIMUM (mode_t),
901                             TYPE_MAXIMUM (uintmax_t), false, false);
902   return ((u & TSUID ? S_ISUID : 0)
903           | (u & TSGID ? S_ISGID : 0)
904           | (u & TSVTX ? S_ISVTX : 0)
905           | (u & TUREAD ? S_IRUSR : 0)
906           | (u & TUWRITE ? S_IWUSR : 0)
907           | (u & TUEXEC ? S_IXUSR : 0)
908           | (u & TGREAD ? S_IRGRP : 0)
909           | (u & TGWRITE ? S_IWGRP : 0)
910           | (u & TGEXEC ? S_IXGRP : 0)
911           | (u & TOREAD ? S_IROTH : 0)
912           | (u & TOWRITE ? S_IWOTH : 0)
913           | (u & TOEXEC ? S_IXOTH : 0));
914 }
915
916 off_t
917 off_from_header (const char *p, size_t s)
918 {
919   /* Negative offsets are not allowed in tar files, so invoke
920      from_header with minimum value 0, not TYPE_MINIMUM (off_t).  */
921   return from_header (p, s, "off_t", (uintmax_t) 0,
922                       (uintmax_t) TYPE_MAXIMUM (off_t), false, false);
923 }
924
925 size_t
926 size_from_header (const char *p, size_t s)
927 {
928   return from_header (p, s, "size_t", (uintmax_t) 0,
929                       (uintmax_t) TYPE_MAXIMUM (size_t), false, false);
930 }
931
932 time_t
933 time_from_header (const char *p, size_t s)
934 {
935   return from_header (p, s, "time_t",
936                       - (uintmax_t) TYPE_MINIMUM (time_t),
937                       (uintmax_t) TYPE_MAXIMUM (time_t), false, false);
938 }
939
940 uid_t
941 uid_from_header (const char *p, size_t s)
942 {
943   return from_header (p, s, "uid_t",
944                       - (uintmax_t) TYPE_MINIMUM (uid_t),
945                       (uintmax_t) TYPE_MAXIMUM (uid_t), false, false);
946 }
947
948 uintmax_t
949 uintmax_from_header (const char *p, size_t s)
950 {
951   return from_header (p, s, "uintmax_t", (uintmax_t) 0,
952                       TYPE_MAXIMUM (uintmax_t), false, false);
953 }
954
955
956 /* Return a printable representation of T.  The result points to
957    static storage that can be reused in the next call to this
958    function, to ctime, or to asctime.  If FULL_TIME, then output the
959    time stamp to its full resolution; otherwise, just output it to
960    1-minute resolution.  */
961 char const *
962 tartime (struct timespec t, bool full_time)
963 {
964   enum { fraclen = sizeof ".FFFFFFFFF" - 1 };
965   static char buffer[max (UINTMAX_STRSIZE_BOUND + 1,
966                           INT_STRLEN_BOUND (int) + 16)
967                      + fraclen];
968   struct tm *tm;
969   time_t s = t.tv_sec;
970   int ns = t.tv_nsec;
971   bool negative = s < 0;
972   char *p;
973
974   if (negative && ns != 0)
975     {
976       s++;
977       ns = 1000000000 - ns;
978     }
979
980   tm = utc_option ? gmtime (&s) : localtime (&s);
981   if (tm)
982     {
983       if (full_time)
984         {
985           sprintf (buffer, "%04ld-%02d-%02d %02d:%02d:%02d",
986                    tm->tm_year + 1900L, tm->tm_mon + 1, tm->tm_mday,
987                    tm->tm_hour, tm->tm_min, tm->tm_sec);
988           code_ns_fraction (ns, buffer + strlen (buffer));
989         }
990       else
991         sprintf (buffer, "%04ld-%02d-%02d %02d:%02d",
992                  tm->tm_year + 1900L, tm->tm_mon + 1, tm->tm_mday,
993                  tm->tm_hour, tm->tm_min);
994       return buffer;
995     }
996
997   /* The time stamp cannot be broken down, most likely because it
998      is out of range.  Convert it as an integer,
999      right-adjusted in a field with the same width as the usual
1000      4-year ISO time format.  */
1001   p = umaxtostr (negative ? - (uintmax_t) s : s,
1002                  buffer + sizeof buffer - UINTMAX_STRSIZE_BOUND - fraclen);
1003   if (negative)
1004     *--p = '-';
1005   while ((buffer + sizeof buffer - sizeof "YYYY-MM-DD HH:MM"
1006           + (full_time ? sizeof ":SS.FFFFFFFFF" - 1 : 0))
1007          < p)
1008     *--p = ' ';
1009   if (full_time)
1010     code_ns_fraction (ns, buffer + sizeof buffer - 1 - fraclen);
1011   return p;
1012 }
1013
1014 /* Actually print it.
1015
1016    Plain and fancy file header block logging.  Non-verbose just prints
1017    the name, e.g. for "tar t" or "tar x".  This should just contain
1018    file names, so it can be fed back into tar with xargs or the "-T"
1019    option.  The verbose option can give a bunch of info, one line per
1020    file.  I doubt anybody tries to parse its format, or if they do,
1021    they shouldn't.  Unix tar is pretty random here anyway.  */
1022
1023
1024 /* FIXME: Note that print_header uses the globals HEAD, HSTAT, and
1025    HEAD_STANDARD, which must be set up in advance.  Not very clean..  */
1026
1027 /* Width of "user/group size", with initial value chosen
1028    heuristically.  This grows as needed, though this may cause some
1029    stairstepping in the output.  Make it too small and the output will
1030    almost always look ragged.  Make it too large and the output will
1031    be spaced out too far.  */
1032 static int ugswidth = 19;
1033
1034 /* Width of printed time stamps.  It grows if longer time stamps are
1035    found (typically, those with nanosecond resolution).  Like
1036    USGWIDTH, some stairstepping may occur.  */
1037 static int datewidth = sizeof "YYYY-MM-DD HH:MM" - 1;
1038
1039 void
1040 print_header (struct tar_stat_info *st, off_t block_ordinal)
1041 {
1042   char modes[11];
1043   char const *time_stamp;
1044   int time_stamp_len;
1045   char *temp_name;
1046
1047   /* These hold formatted ints.  */
1048   char uform[UINTMAX_STRSIZE_BOUND], gform[UINTMAX_STRSIZE_BOUND];
1049   char *user, *group;
1050   char size[2 * UINTMAX_STRSIZE_BOUND];
1051                                 /* holds formatted size or major,minor */
1052   char uintbuf[UINTMAX_STRSIZE_BOUND];
1053   int pad;
1054   int sizelen;
1055
1056   if (test_label_option && current_header->header.typeflag != GNUTYPE_VOLHDR)
1057     return;
1058
1059   if (show_transformed_names_option)
1060     temp_name = st->file_name ? st->file_name : st->orig_file_name;
1061   else
1062     temp_name = st->orig_file_name ? st->orig_file_name : st->file_name;
1063
1064   if (block_number_option)
1065     {
1066       char buf[UINTMAX_STRSIZE_BOUND];
1067       if (block_ordinal < 0)
1068         block_ordinal = current_block_ordinal ();
1069       block_ordinal -= recent_long_name_blocks;
1070       block_ordinal -= recent_long_link_blocks;
1071       fprintf (stdlis, _("block %s: "),
1072                STRINGIFY_BIGINT (block_ordinal, buf));
1073     }
1074
1075   if (verbose_option <= 1)
1076     {
1077       /* Just the fax, mam.  */
1078       fprintf (stdlis, "%s\n", quotearg (temp_name));
1079     }
1080   else
1081     {
1082       /* File type and modes.  */
1083
1084       modes[0] = '?';
1085       switch (current_header->header.typeflag)
1086         {
1087         case GNUTYPE_VOLHDR:
1088           modes[0] = 'V';
1089           break;
1090
1091         case GNUTYPE_MULTIVOL:
1092           modes[0] = 'M';
1093           break;
1094
1095         case GNUTYPE_LONGNAME:
1096         case GNUTYPE_LONGLINK:
1097           modes[0] = 'L';
1098           ERROR ((0, 0, _("Unexpected long name header")));
1099           break;
1100
1101         case GNUTYPE_SPARSE:
1102         case REGTYPE:
1103         case AREGTYPE:
1104           modes[0] = '-';
1105           if (temp_name[strlen (temp_name) - 1] == '/')
1106             modes[0] = 'd';
1107           break;
1108         case LNKTYPE:
1109           modes[0] = 'h';
1110           break;
1111         case GNUTYPE_DUMPDIR:
1112           modes[0] = 'd';
1113           break;
1114         case DIRTYPE:
1115           modes[0] = 'd';
1116           break;
1117         case SYMTYPE:
1118           modes[0] = 'l';
1119           break;
1120         case BLKTYPE:
1121           modes[0] = 'b';
1122           break;
1123         case CHRTYPE:
1124           modes[0] = 'c';
1125           break;
1126         case FIFOTYPE:
1127           modes[0] = 'p';
1128           break;
1129         case CONTTYPE:
1130           modes[0] = 'C';
1131           break;
1132         }
1133
1134       pax_decode_mode (st->stat.st_mode, modes + 1);
1135
1136       /* Time stamp.  */
1137
1138       time_stamp = tartime (st->mtime, false);
1139       time_stamp_len = strlen (time_stamp);
1140       if (datewidth < time_stamp_len)
1141         datewidth = time_stamp_len;
1142
1143       /* User and group names.  */
1144
1145       if (st->uname
1146           && st->uname[0]
1147           && current_format != V7_FORMAT
1148           && !numeric_owner_option)
1149         user = st->uname;
1150       else
1151         {
1152           /* Try parsing it as an unsigned integer first, and as a
1153              uid_t if that fails.  This method can list positive user
1154              ids that are too large to fit in a uid_t.  */
1155           uintmax_t u = from_header (current_header->header.uid,
1156                                      sizeof current_header->header.uid, 0,
1157                                      (uintmax_t) 0,
1158                                      (uintmax_t) TYPE_MAXIMUM (uintmax_t),
1159                                      false, false);
1160           if (u != -1)
1161             user = STRINGIFY_BIGINT (u, uform);
1162           else
1163             {
1164               sprintf (uform, "%ld",
1165                        (long) UID_FROM_HEADER (current_header->header.uid));
1166               user = uform;
1167             }
1168         }
1169
1170       if (st->gname
1171           && st->gname[0]
1172           && current_format != V7_FORMAT
1173           && !numeric_owner_option)
1174         group = st->gname;
1175       else
1176         {
1177           /* Try parsing it as an unsigned integer first, and as a
1178              gid_t if that fails.  This method can list positive group
1179              ids that are too large to fit in a gid_t.  */
1180           uintmax_t g = from_header (current_header->header.gid,
1181                                      sizeof current_header->header.gid, 0,
1182                                      (uintmax_t) 0,
1183                                      (uintmax_t) TYPE_MAXIMUM (uintmax_t),
1184                                      false, false);
1185           if (g != -1)
1186             group = STRINGIFY_BIGINT (g, gform);
1187           else
1188             {
1189               sprintf (gform, "%ld",
1190                        (long) GID_FROM_HEADER (current_header->header.gid));
1191               group = gform;
1192             }
1193         }
1194
1195       /* Format the file size or major/minor device numbers.  */
1196
1197       switch (current_header->header.typeflag)
1198         {
1199         case CHRTYPE:
1200         case BLKTYPE:
1201           strcpy (size,
1202                   STRINGIFY_BIGINT (major (st->stat.st_rdev), uintbuf));
1203           strcat (size, ",");
1204           strcat (size,
1205                   STRINGIFY_BIGINT (minor (st->stat.st_rdev), uintbuf));
1206           break;
1207
1208         default:
1209           /* st->stat.st_size keeps stored file size */
1210           strcpy (size, STRINGIFY_BIGINT (st->stat.st_size, uintbuf));
1211           break;
1212         }
1213
1214       /* Figure out padding and print the whole line.  */
1215
1216       sizelen = strlen (size);
1217       pad = strlen (user) + 1 + strlen (group) + 1 + sizelen;
1218       if (pad > ugswidth)
1219         ugswidth = pad;
1220
1221       fprintf (stdlis, "%s %s/%s %*s %-*s",
1222                modes, user, group, ugswidth - pad + sizelen, size,
1223                datewidth, time_stamp);
1224
1225       fprintf (stdlis, " %s", quotearg (temp_name));
1226
1227       switch (current_header->header.typeflag)
1228         {
1229         case SYMTYPE:
1230           fprintf (stdlis, " -> %s\n", quotearg (st->link_name));
1231           break;
1232
1233         case LNKTYPE:
1234           fprintf (stdlis, _(" link to %s\n"), quotearg (st->link_name));
1235           break;
1236
1237         default:
1238           {
1239             char type_string[2];
1240             type_string[0] = current_header->header.typeflag;
1241             type_string[1] = '\0';
1242             fprintf (stdlis, _(" unknown file type %s\n"),
1243                      quote (type_string));
1244           }
1245           break;
1246
1247         case AREGTYPE:
1248         case REGTYPE:
1249         case GNUTYPE_SPARSE:
1250         case CHRTYPE:
1251         case BLKTYPE:
1252         case DIRTYPE:
1253         case FIFOTYPE:
1254         case CONTTYPE:
1255         case GNUTYPE_DUMPDIR:
1256           putc ('\n', stdlis);
1257           break;
1258
1259         case GNUTYPE_LONGLINK:
1260           fprintf (stdlis, _("--Long Link--\n"));
1261           break;
1262
1263         case GNUTYPE_LONGNAME:
1264           fprintf (stdlis, _("--Long Name--\n"));
1265           break;
1266
1267         case GNUTYPE_VOLHDR:
1268           fprintf (stdlis, _("--Volume Header--\n"));
1269           break;
1270
1271         case GNUTYPE_MULTIVOL:
1272           strcpy (size,
1273                   STRINGIFY_BIGINT
1274                   (UINTMAX_FROM_HEADER (current_header->oldgnu_header.offset),
1275                    uintbuf));
1276           fprintf (stdlis, _("--Continued at byte %s--\n"), size);
1277           break;
1278         }
1279     }
1280   fflush (stdlis);
1281 }
1282
1283 /* Print a similar line when we make a directory automatically.  */
1284 void
1285 print_for_mkdir (char *dirname, int length, mode_t mode)
1286 {
1287   char modes[11];
1288
1289   if (verbose_option > 1)
1290     {
1291       /* File type and modes.  */
1292
1293       modes[0] = 'd';
1294       pax_decode_mode (mode, modes + 1);
1295
1296       if (block_number_option)
1297         {
1298           char buf[UINTMAX_STRSIZE_BOUND];
1299           fprintf (stdlis, _("block %s: "),
1300                    STRINGIFY_BIGINT (current_block_ordinal (), buf));
1301         }
1302
1303       fprintf (stdlis, "%s %*s %.*s\n", modes, ugswidth + 1 + datewidth,
1304                _("Creating directory:"), length, quotearg (dirname));
1305     }
1306 }
1307
1308 /* Skip over SIZE bytes of data in blocks in the archive.  */
1309 void
1310 skip_file (off_t size)
1311 {
1312   union block *x;
1313
1314   /* FIXME: Make sure mv_begin is always called before it */
1315
1316   if (seekable_archive)
1317     {
1318       off_t nblk = seek_archive (size);
1319       if (nblk >= 0)
1320         size -= nblk * BLOCKSIZE;
1321       else
1322         seekable_archive = false;
1323     }
1324
1325   mv_size_left (size);
1326
1327   while (size > 0)
1328     {
1329       x = find_next_block ();
1330       if (! x)
1331         FATAL_ERROR ((0, 0, _("Unexpected EOF in archive")));
1332
1333       set_next_block_after (x);
1334       size -= BLOCKSIZE;
1335       mv_size_left (size);
1336     }
1337 }
1338
1339 /* Skip the current member in the archive.
1340    NOTE: Current header must be decoded before calling this function. */
1341 void
1342 skip_member (void)
1343 {
1344   if (!current_stat_info.skipped)
1345     {
1346       char save_typeflag = current_header->header.typeflag;
1347       set_next_block_after (current_header);
1348
1349       mv_begin (&current_stat_info);
1350
1351       if (current_stat_info.is_sparse)
1352         sparse_skip_file (&current_stat_info);
1353       else if (save_typeflag != DIRTYPE)
1354         skip_file (current_stat_info.stat.st_size);
1355
1356       mv_end ();
1357     }
1358 }