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