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