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