need longlink patch in checked out tree
[debian/tar] / src / create.c
1 /* Create a tar archive.
2
3    Copyright (C) 1985, 1992, 1993, 1994, 1996, 1997, 1999, 2000, 2001,
4    2003, 2004, 2005, 2006, 2007, 2009, 2010 Free Software Foundation, Inc.
5
6    Written by John Gilmore, on 1985-08-25.
7
8    This program is free software; you can redistribute it and/or modify it
9    under the terms of the GNU General Public License as published by the
10    Free Software Foundation; either version 3, or (at your option) any later
11    version.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
16    Public License for more details.
17
18    You should have received a copy of the GNU General Public License along
19    with this program; if not, write to the Free Software Foundation, Inc.,
20    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
21
22 #include <system.h>
23
24 #include <quotearg.h>
25
26 #include "common.h"
27 #include <hash.h>
28
29 extern int debian_longlink_hack;
30
31 /* Error number to use when an impostor is discovered.
32    Pretend the impostor isn't there.  */
33 enum { IMPOSTOR_ERRNO = ENOENT };
34
35 struct link
36   {
37     dev_t dev;
38     ino_t ino;
39     nlink_t nlink;
40     char name[1];
41   };
42
43 struct exclusion_tag
44 {
45   const char *name;
46   size_t length;
47   enum exclusion_tag_type type;
48   bool (*predicate) (int fd);
49   struct exclusion_tag *next;
50 };
51
52 static struct exclusion_tag *exclusion_tags;
53
54 void
55 add_exclusion_tag (const char *name, enum exclusion_tag_type type,
56                    bool (*predicate) (int fd))
57 {
58   struct exclusion_tag *tag = xmalloc (sizeof tag[0]);
59   tag->next = exclusion_tags;
60   tag->name = name;
61   tag->type = type;
62   tag->predicate = predicate;
63   tag->length = strlen (name);
64   exclusion_tags = tag;
65 }
66
67 void
68 exclusion_tag_warning (const char *dirname, const char *tagname,
69                        const char *message)
70 {
71   if (verbose_option)
72     WARNOPT (WARN_CACHEDIR,
73              (0, 0,
74               _("%s: contains a cache directory tag %s; %s"),
75               quotearg_colon (dirname),
76               quotearg_n (1, tagname),
77               message));
78 }
79
80 enum exclusion_tag_type
81 check_exclusion_tags (struct tar_stat_info const *st, char const **tag_file_name)
82 {
83   struct exclusion_tag *tag;
84
85   for (tag = exclusion_tags; tag; tag = tag->next)
86     {
87       int tagfd = subfile_open (st, tag->name, open_read_flags);
88       if (0 <= tagfd)
89         {
90           bool satisfied = !tag->predicate || tag->predicate (tagfd);
91           close (tagfd);
92           if (satisfied)
93             {
94               if (tag_file_name)
95                 *tag_file_name = tag->name;
96               return tag->type;
97             }
98         }
99     }
100
101   return exclusion_tag_none;
102 }
103
104 /* Exclusion predicate to test if the named file (usually "CACHEDIR.TAG")
105    contains a valid header, as described at:
106         http://www.brynosaurus.com/cachedir
107    Applications can write this file into directories they create
108    for use as caches containing purely regenerable, non-precious data,
109    allowing us to avoid archiving them if --exclude-caches is specified. */
110
111 #define CACHEDIR_SIGNATURE "Signature: 8a477f597d28d172789f06886806bc55"
112 #define CACHEDIR_SIGNATURE_SIZE (sizeof CACHEDIR_SIGNATURE - 1)
113
114 bool
115 cachedir_file_p (int fd)
116 {
117   char tagbuf[CACHEDIR_SIGNATURE_SIZE];
118
119   return
120     (read (fd, tagbuf, CACHEDIR_SIGNATURE_SIZE) == CACHEDIR_SIGNATURE_SIZE
121      && memcmp (tagbuf, CACHEDIR_SIGNATURE, CACHEDIR_SIGNATURE_SIZE) == 0);
122 }
123
124 \f
125 /* The maximum uintmax_t value that can be represented with DIGITS digits,
126    assuming that each digit is BITS_PER_DIGIT wide.  */
127 #define MAX_VAL_WITH_DIGITS(digits, bits_per_digit) \
128    ((digits) * (bits_per_digit) < sizeof (uintmax_t) * CHAR_BIT \
129     ? ((uintmax_t) 1 << ((digits) * (bits_per_digit))) - 1 \
130     : (uintmax_t) -1)
131
132 /* The maximum uintmax_t value that can be represented with octal
133    digits and a trailing NUL in BUFFER.  */
134 #define MAX_OCTAL_VAL(buffer) MAX_VAL_WITH_DIGITS (sizeof (buffer) - 1, LG_8)
135
136 /* Convert VALUE to an octal representation suitable for tar headers.
137    Output to buffer WHERE with size SIZE.
138    The result is undefined if SIZE is 0 or if VALUE is too large to fit.  */
139
140 static void
141 to_octal (uintmax_t value, char *where, size_t size)
142 {
143   uintmax_t v = value;
144   size_t i = size;
145
146   do
147     {
148       where[--i] = '0' + (v & ((1 << LG_8) - 1));
149       v >>= LG_8;
150     }
151   while (i);
152 }
153
154 /* Copy at most LEN bytes from the string SRC to DST.  Terminate with
155    NUL unless SRC is LEN or more bytes long.  */
156
157 static void
158 tar_copy_str (char *dst, const char *src, size_t len)
159 {
160   size_t i;
161   for (i = 0; i < len; i++)
162     if (! (dst[i] = src[i]))
163       break;
164 }
165
166 /* Same as tar_copy_str, but always terminate with NUL if using
167    is OLDGNU format */
168
169 static void
170 tar_name_copy_str (char *dst, const char *src, size_t len)
171 {
172   tar_copy_str (dst, src, len);
173   if (archive_format == OLDGNU_FORMAT)
174     dst[len-1] = 0;
175 }
176
177 /* Convert NEGATIVE VALUE to a base-256 representation suitable for
178    tar headers.  NEGATIVE is 1 if VALUE was negative before being cast
179    to uintmax_t, 0 otherwise.  Output to buffer WHERE with size SIZE.
180    The result is undefined if SIZE is 0 or if VALUE is too large to
181    fit.  */
182
183 static void
184 to_base256 (int negative, uintmax_t value, char *where, size_t size)
185 {
186   uintmax_t v = value;
187   uintmax_t propagated_sign_bits =
188     ((uintmax_t) - negative << (CHAR_BIT * sizeof v - LG_256));
189   size_t i = size;
190
191   do
192     {
193       where[--i] = v & ((1 << LG_256) - 1);
194       v = propagated_sign_bits | (v >> LG_256);
195     }
196   while (i);
197 }
198
199 #define GID_TO_CHARS(val, where) gid_to_chars (val, where, sizeof (where))
200 #define MAJOR_TO_CHARS(val, where) major_to_chars (val, where, sizeof (where))
201 #define MINOR_TO_CHARS(val, where) minor_to_chars (val, where, sizeof (where))
202 #define MODE_TO_CHARS(val, where) mode_to_chars (val, where, sizeof (where))
203 #define UID_TO_CHARS(val, where) uid_to_chars (val, where, sizeof (where))
204
205 #define UNAME_TO_CHARS(name,buf) string_to_chars (name, buf, sizeof(buf))
206 #define GNAME_TO_CHARS(name,buf) string_to_chars (name, buf, sizeof(buf))
207
208 static bool
209 to_chars (int negative, uintmax_t value, size_t valsize,
210           uintmax_t (*substitute) (int *),
211           char *where, size_t size, const char *type);
212
213 static bool
214 to_chars_subst (int negative, int gnu_format, uintmax_t value, size_t valsize,
215                 uintmax_t (*substitute) (int *),
216                 char *where, size_t size, const char *type)
217 {
218   uintmax_t maxval = (gnu_format
219                       ? MAX_VAL_WITH_DIGITS (size - 1, LG_256)
220                       : MAX_VAL_WITH_DIGITS (size - 1, LG_8));
221   char valbuf[UINTMAX_STRSIZE_BOUND + 1];
222   char maxbuf[UINTMAX_STRSIZE_BOUND];
223   char minbuf[UINTMAX_STRSIZE_BOUND + 1];
224   char const *minval_string;
225   char const *maxval_string = STRINGIFY_BIGINT (maxval, maxbuf);
226   char const *value_string;
227
228   if (gnu_format)
229     {
230       uintmax_t m = maxval + 1 ? maxval + 1 : maxval / 2 + 1;
231       char *p = STRINGIFY_BIGINT (m, minbuf + 1);
232       *--p = '-';
233       minval_string = p;
234     }
235   else
236     minval_string = "0";
237
238   if (negative)
239     {
240       char *p = STRINGIFY_BIGINT (- value, valbuf + 1);
241       *--p = '-';
242       value_string = p;
243     }
244   else
245     value_string = STRINGIFY_BIGINT (value, valbuf);
246
247   if (substitute)
248     {
249       int negsub;
250       uintmax_t sub = substitute (&negsub) & maxval;
251       /* NOTE: This is one of the few places where GNU_FORMAT differs from
252          OLDGNU_FORMAT.  The actual differences are:
253
254          1. In OLDGNU_FORMAT all strings in a tar header end in \0
255          2. Incremental archives use oldgnu_header.
256
257          Apart from this they are completely identical. */
258       uintmax_t s = (negsub &= archive_format == GNU_FORMAT) ? - sub : sub;
259       char subbuf[UINTMAX_STRSIZE_BOUND + 1];
260       char *sub_string = STRINGIFY_BIGINT (s, subbuf + 1);
261       if (negsub)
262         *--sub_string = '-';
263       WARN ((0, 0, _("value %s out of %s range %s..%s; substituting %s"),
264              value_string, type, minval_string, maxval_string,
265              sub_string));
266       return to_chars (negsub, s, valsize, 0, where, size, type);
267     }
268   else
269     ERROR ((0, 0, _("value %s out of %s range %s..%s"),
270             value_string, type, minval_string, maxval_string));
271   return false;
272 }
273
274 /* Convert NEGATIVE VALUE (which was originally of size VALSIZE) to
275    external form, using SUBSTITUTE (...) if VALUE won't fit.  Output
276    to buffer WHERE with size SIZE.  NEGATIVE is 1 iff VALUE was
277    negative before being cast to uintmax_t; its original bitpattern
278    can be deduced from VALSIZE, its original size before casting.
279    TYPE is the kind of value being output (useful for diagnostics).
280    Prefer the POSIX format of SIZE - 1 octal digits (with leading zero
281    digits), followed by '\0'.  If this won't work, and if GNU or
282    OLDGNU format is allowed, use '\200' followed by base-256, or (if
283    NEGATIVE is nonzero) '\377' followed by two's complement base-256.
284    If neither format works, use SUBSTITUTE (...)  instead.  Pass to
285    SUBSTITUTE the address of an 0-or-1 flag recording whether the
286    substitute value is negative.  */
287
288 static bool
289 to_chars (int negative, uintmax_t value, size_t valsize,
290           uintmax_t (*substitute) (int *),
291           char *where, size_t size, const char *type)
292 {
293   int gnu_format = (archive_format == GNU_FORMAT
294                     || archive_format == OLDGNU_FORMAT);
295
296   /* Generate the POSIX octal representation if the number fits.  */
297   if (! negative && value <= MAX_VAL_WITH_DIGITS (size - 1, LG_8))
298     {
299       where[size - 1] = '\0';
300       to_octal (value, where, size - 1);
301       return true;
302     }
303   else if (gnu_format)
304     {
305       /* Try to cope with the number by using traditional GNU format
306          methods */
307
308       /* Generate the base-256 representation if the number fits.  */
309       if (((negative ? -1 - value : value)
310            <= MAX_VAL_WITH_DIGITS (size - 1, LG_256)))
311         {
312           where[0] = negative ? -1 : 1 << (LG_256 - 1);
313           to_base256 (negative, value, where + 1, size - 1);
314           return true;
315         }
316
317       /* Otherwise, if the number is negative, and if it would not cause
318          ambiguity on this host by confusing positive with negative
319          values, then generate the POSIX octal representation of the value
320          modulo 2**(field bits).  The resulting tar file is
321          machine-dependent, since it depends on the host word size.  Yuck!
322          But this is the traditional behavior.  */
323       else if (negative && valsize * CHAR_BIT <= (size - 1) * LG_8)
324         {
325           static int warned_once;
326           if (! warned_once)
327             {
328               warned_once = 1;
329               WARN ((0, 0, _("Generating negative octal headers")));
330             }
331           where[size - 1] = '\0';
332           to_octal (value & MAX_VAL_WITH_DIGITS (valsize * CHAR_BIT, 1),
333                     where, size - 1);
334           return true;
335         }
336       /* Otherwise fall back to substitution, if possible: */
337     }
338   else
339     substitute = NULL; /* No substitution for formats, other than GNU */
340
341   return to_chars_subst (negative, gnu_format, value, valsize, substitute,
342                          where, size, type);
343 }
344
345 static uintmax_t
346 gid_substitute (int *negative)
347 {
348   gid_t r;
349 #ifdef GID_NOBODY
350   r = GID_NOBODY;
351 #else
352   static gid_t gid_nobody;
353   if (!gid_nobody && !gname_to_gid ("nobody", &gid_nobody))
354     gid_nobody = -2;
355   r = gid_nobody;
356 #endif
357   *negative = r < 0;
358   return r;
359 }
360
361 static bool
362 gid_to_chars (gid_t v, char *p, size_t s)
363 {
364   return to_chars (v < 0, (uintmax_t) v, sizeof v, gid_substitute, p, s, "gid_t");
365 }
366
367 static bool
368 major_to_chars (major_t v, char *p, size_t s)
369 {
370   return to_chars (v < 0, (uintmax_t) v, sizeof v, 0, p, s, "major_t");
371 }
372
373 static bool
374 minor_to_chars (minor_t v, char *p, size_t s)
375 {
376   return to_chars (v < 0, (uintmax_t) v, sizeof v, 0, p, s, "minor_t");
377 }
378
379 static bool
380 mode_to_chars (mode_t v, char *p, size_t s)
381 {
382   /* In the common case where the internal and external mode bits are the same,
383      and we are not using POSIX or GNU format,
384      propagate all unknown bits to the external mode.
385      This matches historical practice.
386      Otherwise, just copy the bits we know about.  */
387   int negative;
388   uintmax_t u;
389   if (S_ISUID == TSUID && S_ISGID == TSGID && S_ISVTX == TSVTX
390       && S_IRUSR == TUREAD && S_IWUSR == TUWRITE && S_IXUSR == TUEXEC
391       && S_IRGRP == TGREAD && S_IWGRP == TGWRITE && S_IXGRP == TGEXEC
392       && S_IROTH == TOREAD && S_IWOTH == TOWRITE && S_IXOTH == TOEXEC
393       && archive_format != POSIX_FORMAT
394       && archive_format != USTAR_FORMAT
395       && archive_format != GNU_FORMAT)
396     {
397       negative = v < 0;
398       u = v;
399     }
400   else
401     {
402       negative = 0;
403       u = ((v & S_ISUID ? TSUID : 0)
404            | (v & S_ISGID ? TSGID : 0)
405            | (v & S_ISVTX ? TSVTX : 0)
406            | (v & S_IRUSR ? TUREAD : 0)
407            | (v & S_IWUSR ? TUWRITE : 0)
408            | (v & S_IXUSR ? TUEXEC : 0)
409            | (v & S_IRGRP ? TGREAD : 0)
410            | (v & S_IWGRP ? TGWRITE : 0)
411            | (v & S_IXGRP ? TGEXEC : 0)
412            | (v & S_IROTH ? TOREAD : 0)
413            | (v & S_IWOTH ? TOWRITE : 0)
414            | (v & S_IXOTH ? TOEXEC : 0));
415     }
416   return to_chars (negative, u, sizeof v, 0, p, s, "mode_t");
417 }
418
419 bool
420 off_to_chars (off_t v, char *p, size_t s)
421 {
422   return to_chars (v < 0, (uintmax_t) v, sizeof v, 0, p, s, "off_t");
423 }
424
425 bool
426 time_to_chars (time_t v, char *p, size_t s)
427 {
428   return to_chars (v < 0, (uintmax_t) v, sizeof v, 0, p, s, "time_t");
429 }
430
431 static uintmax_t
432 uid_substitute (int *negative)
433 {
434   uid_t r;
435 #ifdef UID_NOBODY
436   r = UID_NOBODY;
437 #else
438   static uid_t uid_nobody;
439   if (!uid_nobody && !uname_to_uid ("nobody", &uid_nobody))
440     uid_nobody = -2;
441   r = uid_nobody;
442 #endif
443   *negative = r < 0;
444   return r;
445 }
446
447 static bool
448 uid_to_chars (uid_t v, char *p, size_t s)
449 {
450   return to_chars (v < 0, (uintmax_t) v, sizeof v, uid_substitute, p, s, "uid_t");
451 }
452
453 static bool
454 uintmax_to_chars (uintmax_t v, char *p, size_t s)
455 {
456   return to_chars (0, v, sizeof v, 0, p, s, "uintmax_t");
457 }
458
459 static void
460 string_to_chars (char const *str, char *p, size_t s)
461 {
462   tar_copy_str (p, str, s);
463   p[s - 1] = '\0';
464 }
465
466 \f
467 /* A directory is always considered dumpable.
468    Otherwise, only regular and contiguous files are considered dumpable.
469    Such a file is dumpable if it is sparse and both --sparse and --totals
470    are specified.
471    Otherwise, it is dumpable unless any of the following conditions occur:
472
473    a) it is empty *and* world-readable, or
474    b) current archive is /dev/null */
475
476 static bool
477 file_dumpable_p (struct stat const *st)
478 {
479   if (S_ISDIR (st->st_mode))
480     return true;
481   if (! (S_ISREG (st->st_mode) || S_ISCTG (st->st_mode)))
482     return false;
483   if (dev_null_output)
484     return totals_option && sparse_option && ST_IS_SPARSE (*st);
485   return ! (st->st_size == 0 && (st->st_mode & MODE_R) == MODE_R);
486 }
487
488 \f
489 /* Writing routines.  */
490
491 /* Write the EOT block(s).  Zero at least two blocks, through the end
492    of the record.  Old tar, as previous versions of GNU tar, writes
493    garbage after two zeroed blocks.  */
494 void
495 write_eot (void)
496 {
497   union block *pointer = find_next_block ();
498   memset (pointer->buffer, 0, BLOCKSIZE);
499   set_next_block_after (pointer);
500   pointer = find_next_block ();
501   memset (pointer->buffer, 0, available_space_after (pointer));
502   set_next_block_after (pointer);
503 }
504
505 /* Write a "private" header */
506 union block *
507 start_private_header (const char *name, size_t size, time_t t)
508 {
509   union block *header = find_next_block ();
510
511   memset (header->buffer, 0, sizeof (union block));
512
513   tar_name_copy_str (header->header.name, name, NAME_FIELD_SIZE);
514   OFF_TO_CHARS (size, header->header.size);
515
516   TIME_TO_CHARS (t, header->header.mtime);
517   MODE_TO_CHARS (S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH, header->header.mode);
518   UID_TO_CHARS (getuid (), header->header.uid);
519   GID_TO_CHARS (getgid (), header->header.gid);
520   MAJOR_TO_CHARS (0, header->header.devmajor);
521   MINOR_TO_CHARS (0, header->header.devminor);
522   strncpy (header->header.magic, TMAGIC, TMAGLEN);
523   strncpy (header->header.version, TVERSION, TVERSLEN);
524   return header;
525 }
526
527 /* Create a new header and store there at most NAME_FIELD_SIZE bytes of
528    the file name */
529
530 static union block *
531 write_short_name (struct tar_stat_info *st)
532 {
533   union block *header = find_next_block ();
534   memset (header->buffer, 0, sizeof (union block));
535   tar_name_copy_str (header->header.name, st->file_name, NAME_FIELD_SIZE);
536   return header;
537 }
538
539 #define FILL(field,byte) do {            \
540   memset(field, byte, sizeof(field)-1);  \
541   (field)[sizeof(field)-1] = 0;          \
542 } while (0)
543
544 /* Write a GNUTYPE_LONGLINK or GNUTYPE_LONGNAME block.  */
545 static void
546 write_gnu_long_link (struct tar_stat_info *st, const char *p, char type)
547 {
548   size_t size = strlen (p) + 1;
549   size_t bufsize;
550   union block *header;
551   char *tmpname;
552
553   header = start_private_header ("././@LongLink", size, time (NULL));
554   FILL (header->header.mtime, '0');
555   FILL (header->header.mode, '0');
556   FILL (header->header.uid, '0');
557   FILL (header->header.gid, '0');
558   FILL (header->header.devmajor, 0);
559   FILL (header->header.devminor, 0);
560   uid_to_uname (0, &tmpname);
561   UNAME_TO_CHARS (tmpname, header->header.uname);
562   free (tmpname);
563   gid_to_gname (0, &tmpname);
564   GNAME_TO_CHARS (tmpname, header->header.gname);
565   free (tmpname);
566
567   strcpy (header->buffer + offsetof (struct posix_header, magic),
568           OLDGNU_MAGIC);
569   header->header.typeflag = type;
570   finish_header (st, header, -1);
571
572   header = find_next_block ();
573
574   bufsize = available_space_after (header);
575
576   while (bufsize < size)
577     {
578       memcpy (header->buffer, p, bufsize);
579       p += bufsize;
580       size -= bufsize;
581       set_next_block_after (header + (bufsize - 1) / BLOCKSIZE);
582       header = find_next_block ();
583       bufsize = available_space_after (header);
584     }
585   memcpy (header->buffer, p, size);
586   memset (header->buffer + size, 0, bufsize - size);
587   set_next_block_after (header + (size - 1) / BLOCKSIZE);
588 }
589
590 static size_t
591 split_long_name (const char *name, size_t length)
592 {
593   size_t i;
594
595   if (length > PREFIX_FIELD_SIZE + 1)
596     length = PREFIX_FIELD_SIZE + 1;
597   else if (ISSLASH (name[length - 1]))
598     length--;
599   for (i = length - 1; i > 0; i--)
600     if (ISSLASH (name[i]))
601       break;
602   return i;
603 }
604
605 static union block *
606 write_ustar_long_name (const char *name)
607 {
608   size_t length = strlen (name);
609   size_t i, nlen;
610   union block *header;
611
612   if (length > PREFIX_FIELD_SIZE + NAME_FIELD_SIZE + 1)
613     {
614       ERROR ((0, 0, _("%s: file name is too long (max %d); not dumped"),
615               quotearg_colon (name),
616               PREFIX_FIELD_SIZE + NAME_FIELD_SIZE + 1));
617       return NULL;
618     }
619
620   i = split_long_name (name, length);
621   if (i == 0 || (nlen = length - i - 1) > NAME_FIELD_SIZE || nlen == 0)
622     {
623       ERROR ((0, 0,
624               _("%s: file name is too long (cannot be split); not dumped"),
625               quotearg_colon (name)));
626       return NULL;
627     }
628
629   header = find_next_block ();
630   memset (header->buffer, 0, sizeof (header->buffer));
631   memcpy (header->header.prefix, name, i);
632   memcpy (header->header.name, name + i + 1, length - i - 1);
633
634   return header;
635 }
636
637 /* Write a long link name, depending on the current archive format */
638 static void
639 write_long_link (struct tar_stat_info *st)
640 {
641   switch (archive_format)
642     {
643     case POSIX_FORMAT:
644       xheader_store ("linkpath", st, NULL);
645       break;
646
647     case V7_FORMAT:                     /* old V7 tar format */
648     case USTAR_FORMAT:
649     case STAR_FORMAT:
650       ERROR ((0, 0,
651               _("%s: link name is too long; not dumped"),
652               quotearg_colon (st->link_name)));
653       break;
654
655     case OLDGNU_FORMAT:
656     case GNU_FORMAT:
657       write_gnu_long_link (st, st->link_name, GNUTYPE_LONGLINK);
658       break;
659
660     default:
661       abort(); /*FIXME*/
662     }
663 }
664
665 static union block *
666 write_long_name (struct tar_stat_info *st)
667 {
668   switch (archive_format)
669     {
670     case POSIX_FORMAT:
671       xheader_store ("path", st, NULL);
672       break;
673
674     case V7_FORMAT:
675       if (strlen (st->file_name) > NAME_FIELD_SIZE-1)
676         {
677           ERROR ((0, 0, _("%s: file name is too long (max %d); not dumped"),
678                   quotearg_colon (st->file_name),
679                   NAME_FIELD_SIZE - 1));
680           return NULL;
681         }
682       break;
683
684     case USTAR_FORMAT:
685     case STAR_FORMAT:
686       return write_ustar_long_name (st->file_name);
687
688     case OLDGNU_FORMAT:
689     case GNU_FORMAT:
690       write_gnu_long_link (st, st->file_name, GNUTYPE_LONGNAME);
691       break;
692
693     default:
694       abort(); /*FIXME*/
695     }
696   return write_short_name (st);
697 }
698
699 union block *
700 write_extended (bool global, struct tar_stat_info *st, union block *old_header)
701 {
702   union block *header, hp;
703   char *p;
704   int type;
705   time_t t;
706
707   if (st->xhdr.buffer || st->xhdr.stk == NULL)
708     return old_header;
709
710   xheader_finish (&st->xhdr);
711   memcpy (hp.buffer, old_header, sizeof (hp));
712   if (global)
713     {
714       type = XGLTYPE;
715       p = xheader_ghdr_name ();
716       time (&t);
717     }
718   else
719     {
720       type = XHDTYPE;
721       p = xheader_xhdr_name (st);
722       t = st->stat.st_mtime;
723     }
724   xheader_write (type, p, t, &st->xhdr);
725   free (p);
726   header = find_next_block ();
727   memcpy (header, &hp.buffer, sizeof (hp.buffer));
728   return header;
729 }
730
731 static union block *
732 write_header_name (struct tar_stat_info *st)
733 {
734   if (archive_format == POSIX_FORMAT && !string_ascii_p (st->file_name))
735     {
736       xheader_store ("path", st, NULL);
737       return write_short_name (st);
738     }
739   else if (NAME_FIELD_SIZE - (archive_format == OLDGNU_FORMAT)
740            < strlen (st->file_name) + debian_longlink_hack)
741     return write_long_name (st);
742   else
743     return write_short_name (st);
744 }
745
746 \f
747 /* Header handling.  */
748
749 /* Make a header block for the file whose stat info is st,
750    and return its address.  */
751
752 union block *
753 start_header (struct tar_stat_info *st)
754 {
755   union block *header;
756
757   header = write_header_name (st);
758   if (!header)
759     return NULL;
760
761   /* Override some stat fields, if requested to do so.  */
762
763   if (owner_option != (uid_t) -1)
764     st->stat.st_uid = owner_option;
765   if (group_option != (gid_t) -1)
766     st->stat.st_gid = group_option;
767   if (mode_option)
768     st->stat.st_mode =
769       ((st->stat.st_mode & ~MODE_ALL)
770        | mode_adjust (st->stat.st_mode, S_ISDIR (st->stat.st_mode) != 0,
771                       initial_umask, mode_option, NULL));
772
773   /* Paul Eggert tried the trivial test ($WRITER cf a b; $READER tvf a)
774      for a few tars and came up with the following interoperability
775      matrix:
776
777               WRITER
778         1 2 3 4 5 6 7 8 9   READER
779         . . . . . . . . .   1 = SunOS 4.2 tar
780         # . . # # . . # #   2 = NEC SVR4.0.2 tar
781         . . . # # . . # .   3 = Solaris 2.1 tar
782         . . . . . . . . .   4 = GNU tar 1.11.1
783         . . . . . . . . .   5 = HP-UX 8.07 tar
784         . . . . . . . . .   6 = Ultrix 4.1
785         . . . . . . . . .   7 = AIX 3.2
786         . . . . . . . . .   8 = Hitachi HI-UX 1.03
787         . . . . . . . . .   9 = Omron UNIOS-B 4.3BSD 1.60Beta
788
789              . = works
790              # = ``impossible file type''
791
792      The following mask for old archive removes the `#'s in column 4
793      above, thus making GNU tar both a universal donor and a universal
794      acceptor for Paul's test.  */
795
796   if (archive_format == V7_FORMAT || archive_format == USTAR_FORMAT)
797     MODE_TO_CHARS (st->stat.st_mode & MODE_ALL, header->header.mode);
798   else
799     MODE_TO_CHARS (st->stat.st_mode, header->header.mode);
800
801   {
802     uid_t uid = st->stat.st_uid;
803     if (archive_format == POSIX_FORMAT
804         && MAX_OCTAL_VAL (header->header.uid) < uid)
805       {
806         xheader_store ("uid", st, NULL);
807         uid = 0;
808       }
809     if (!UID_TO_CHARS (uid, header->header.uid))
810       return NULL;
811   }
812
813   {
814     gid_t gid = st->stat.st_gid;
815     if (archive_format == POSIX_FORMAT
816         && MAX_OCTAL_VAL (header->header.gid) < gid)
817       {
818         xheader_store ("gid", st, NULL);
819         gid = 0;
820       }
821     if (!GID_TO_CHARS (gid, header->header.gid))
822       return NULL;
823   }
824
825   {
826     off_t size = st->stat.st_size;
827     if (archive_format == POSIX_FORMAT
828         && MAX_OCTAL_VAL (header->header.size) < size)
829       {
830         xheader_store ("size", st, NULL);
831         size = 0;
832       }
833     if (!OFF_TO_CHARS (size, header->header.size))
834       return NULL;
835   }
836
837   {
838     struct timespec mtime = set_mtime_option ? mtime_option : st->mtime;
839     if (archive_format == POSIX_FORMAT)
840       {
841         if (MAX_OCTAL_VAL (header->header.mtime) < mtime.tv_sec
842             || mtime.tv_nsec != 0)
843           xheader_store ("mtime", st, &mtime);
844         if (MAX_OCTAL_VAL (header->header.mtime) < mtime.tv_sec)
845           mtime.tv_sec = 0;
846       }
847     if (!TIME_TO_CHARS (mtime.tv_sec, header->header.mtime))
848       return NULL;
849   }
850
851   /* FIXME */
852   if (S_ISCHR (st->stat.st_mode)
853       || S_ISBLK (st->stat.st_mode))
854     {
855       major_t devmajor = major (st->stat.st_rdev);
856       minor_t devminor = minor (st->stat.st_rdev);
857
858       if (archive_format == POSIX_FORMAT
859           && MAX_OCTAL_VAL (header->header.devmajor) < devmajor)
860         {
861           xheader_store ("devmajor", st, NULL);
862           devmajor = 0;
863         }
864       if (!MAJOR_TO_CHARS (devmajor, header->header.devmajor))
865         return NULL;
866
867       if (archive_format == POSIX_FORMAT
868           && MAX_OCTAL_VAL (header->header.devminor) < devminor)
869         {
870           xheader_store ("devminor", st, NULL);
871           devminor = 0;
872         }
873       if (!MINOR_TO_CHARS (devminor, header->header.devminor))
874         return NULL;
875     }
876   else if (archive_format != GNU_FORMAT && archive_format != OLDGNU_FORMAT)
877     {
878       if (!(MAJOR_TO_CHARS (0, header->header.devmajor)
879             && MINOR_TO_CHARS (0, header->header.devminor)))
880         return NULL;
881     }
882
883   if (archive_format == POSIX_FORMAT)
884     {
885       xheader_store ("atime", st, NULL);
886       xheader_store ("ctime", st, NULL);
887     }
888   else if (incremental_option)
889     if (archive_format == OLDGNU_FORMAT || archive_format == GNU_FORMAT)
890       {
891         TIME_TO_CHARS (st->atime.tv_sec, header->oldgnu_header.atime);
892         TIME_TO_CHARS (st->ctime.tv_sec, header->oldgnu_header.ctime);
893       }
894
895   header->header.typeflag = archive_format == V7_FORMAT ? AREGTYPE : REGTYPE;
896
897   switch (archive_format)
898     {
899     case V7_FORMAT:
900       break;
901
902     case OLDGNU_FORMAT:
903     case GNU_FORMAT:   /*FIXME?*/
904       /* Overwrite header->header.magic and header.version in one blow.  */
905       strcpy (header->buffer + offsetof (struct posix_header, magic),
906               OLDGNU_MAGIC);
907       break;
908
909     case POSIX_FORMAT:
910     case USTAR_FORMAT:
911       strncpy (header->header.magic, TMAGIC, TMAGLEN);
912       strncpy (header->header.version, TVERSION, TVERSLEN);
913       break;
914
915     default:
916       abort ();
917     }
918
919   if (archive_format == V7_FORMAT || numeric_owner_option)
920     {
921       /* header->header.[ug]name are left as the empty string.  */
922     }
923   else
924     {
925       uid_to_uname (st->stat.st_uid, &st->uname);
926       gid_to_gname (st->stat.st_gid, &st->gname);
927
928       if (archive_format == POSIX_FORMAT
929           && (strlen (st->uname) > UNAME_FIELD_SIZE
930               || !string_ascii_p (st->uname)))
931         xheader_store ("uname", st, NULL);
932       UNAME_TO_CHARS (st->uname, header->header.uname);
933
934       if (archive_format == POSIX_FORMAT
935           && (strlen (st->gname) > GNAME_FIELD_SIZE
936               || !string_ascii_p (st->gname)))
937         xheader_store ("gname", st, NULL);
938       GNAME_TO_CHARS (st->gname, header->header.gname);
939     }
940
941   return header;
942 }
943
944 void
945 simple_finish_header (union block *header)
946 {
947   size_t i;
948   int sum;
949   char *p;
950
951   memcpy (header->header.chksum, CHKBLANKS, sizeof header->header.chksum);
952
953   sum = 0;
954   p = header->buffer;
955   for (i = sizeof *header; i-- != 0; )
956     /* We can't use unsigned char here because of old compilers, e.g. V7.  */
957     sum += 0xFF & *p++;
958
959   /* Fill in the checksum field.  It's formatted differently from the
960      other fields: it has [6] digits, a null, then a space -- rather than
961      digits, then a null.  We use to_chars.
962      The final space is already there, from
963      checksumming, and to_chars doesn't modify it.
964
965      This is a fast way to do:
966
967      sprintf(header->header.chksum, "%6o", sum);  */
968
969   uintmax_to_chars ((uintmax_t) sum, header->header.chksum, 7);
970
971   set_next_block_after (header);
972 }
973
974 /* Finish off a filled-in header block and write it out.  We also
975    print the file name and/or full info if verbose is on.  If BLOCK_ORDINAL
976    is not negative, is the block ordinal of the first record for this
977    file, which may be a preceding long name or long link record.  */
978 void
979 finish_header (struct tar_stat_info *st,
980                union block *header, off_t block_ordinal)
981 {
982   /* Note: It is important to do this before the call to write_extended(),
983      so that the actual ustar header is printed */
984   if (verbose_option
985       && header->header.typeflag != GNUTYPE_LONGLINK
986       && header->header.typeflag != GNUTYPE_LONGNAME
987       && header->header.typeflag != XHDTYPE
988       && header->header.typeflag != XGLTYPE)
989     {
990       /* FIXME: This global is used in print_header, sigh.  */
991       current_format = archive_format;
992       print_header (st, header, block_ordinal);
993     }
994
995   header = write_extended (false, st, header);
996   simple_finish_header (header);
997 }
998 \f
999
1000 void
1001 pad_archive (off_t size_left)
1002 {
1003   union block *blk;
1004   while (size_left > 0)
1005     {
1006       blk = find_next_block ();
1007       memset (blk->buffer, 0, BLOCKSIZE);
1008       set_next_block_after (blk);
1009       size_left -= BLOCKSIZE;
1010     }
1011 }
1012
1013 static enum dump_status
1014 dump_regular_file (int fd, struct tar_stat_info *st)
1015 {
1016   off_t size_left = st->stat.st_size;
1017   off_t block_ordinal;
1018   union block *blk;
1019
1020   block_ordinal = current_block_ordinal ();
1021   blk = start_header (st);
1022   if (!blk)
1023     return dump_status_fail;
1024
1025   /* Mark contiguous files, if we support them.  */
1026   if (archive_format != V7_FORMAT && S_ISCTG (st->stat.st_mode))
1027     blk->header.typeflag = CONTTYPE;
1028
1029   finish_header (st, blk, block_ordinal);
1030
1031   mv_begin_write (st->file_name, st->stat.st_size, st->stat.st_size);
1032   while (size_left > 0)
1033     {
1034       size_t bufsize, count;
1035
1036       blk = find_next_block ();
1037
1038       bufsize = available_space_after (blk);
1039
1040       if (size_left < bufsize)
1041         {
1042           /* Last read -- zero out area beyond.  */
1043           bufsize = size_left;
1044           count = bufsize % BLOCKSIZE;
1045           if (count)
1046             memset (blk->buffer + size_left, 0, BLOCKSIZE - count);
1047         }
1048
1049       count = (fd <= 0) ? bufsize : safe_read (fd, blk->buffer, bufsize);
1050       if (count == SAFE_READ_ERROR)
1051         {
1052           read_diag_details (st->orig_file_name,
1053                              st->stat.st_size - size_left, bufsize);
1054           pad_archive (size_left);
1055           return dump_status_short;
1056         }
1057       size_left -= count;
1058       set_next_block_after (blk + (bufsize - 1) / BLOCKSIZE);
1059
1060       if (count != bufsize)
1061         {
1062           char buf[UINTMAX_STRSIZE_BOUND];
1063           memset (blk->buffer + count, 0, bufsize - count);
1064           WARNOPT (WARN_FILE_SHRANK,
1065                    (0, 0,
1066                     ngettext ("%s: File shrank by %s byte; padding with zeros",
1067                               "%s: File shrank by %s bytes; padding with zeros",
1068                               size_left),
1069                     quotearg_colon (st->orig_file_name),
1070                     STRINGIFY_BIGINT (size_left, buf)));
1071           if (! ignore_failed_read_option)
1072             set_exit_status (TAREXIT_DIFFERS);
1073           pad_archive (size_left - (bufsize - count));
1074           return dump_status_short;
1075         }
1076     }
1077   return dump_status_ok;
1078 }
1079
1080 \f
1081 /* Copy info from the directory identified by ST into the archive.
1082    DIRECTORY contains the directory's entries.  */
1083
1084 static void
1085 dump_dir0 (struct tar_stat_info *st, char const *directory)
1086 {
1087   bool top_level = ! st->parent;
1088   const char *tag_file_name;
1089   union block *blk = NULL;
1090   off_t block_ordinal = current_block_ordinal ();
1091
1092   st->stat.st_size = 0; /* force 0 size on dir */
1093
1094   blk = start_header (st);
1095   if (!blk)
1096     return;
1097
1098   if (incremental_option && archive_format != POSIX_FORMAT)
1099     blk->header.typeflag = GNUTYPE_DUMPDIR;
1100   else /* if (standard_option) */
1101     blk->header.typeflag = DIRTYPE;
1102
1103   /* If we're gnudumping, we aren't done yet so don't close it.  */
1104
1105   if (!incremental_option)
1106     finish_header (st, blk, block_ordinal);
1107   else if (gnu_list_name->directory)
1108     {
1109       if (archive_format == POSIX_FORMAT)
1110         {
1111           xheader_store ("GNU.dumpdir", st,
1112                          safe_directory_contents (gnu_list_name->directory));
1113           finish_header (st, blk, block_ordinal);
1114         }
1115       else
1116         {
1117           off_t size_left;
1118           off_t totsize;
1119           size_t bufsize;
1120           ssize_t count;
1121           const char *buffer, *p_buffer;
1122
1123           block_ordinal = current_block_ordinal ();
1124           buffer = safe_directory_contents (gnu_list_name->directory);
1125           totsize = dumpdir_size (buffer);
1126           OFF_TO_CHARS (totsize, blk->header.size);
1127           finish_header (st, blk, block_ordinal);
1128           p_buffer = buffer;
1129           size_left = totsize;
1130
1131           mv_begin_write (st->file_name, totsize, totsize);
1132           while (size_left > 0)
1133             {
1134               blk = find_next_block ();
1135               bufsize = available_space_after (blk);
1136               if (size_left < bufsize)
1137                 {
1138                   bufsize = size_left;
1139                   count = bufsize % BLOCKSIZE;
1140                   if (count)
1141                     memset (blk->buffer + size_left, 0, BLOCKSIZE - count);
1142                 }
1143               memcpy (blk->buffer, p_buffer, bufsize);
1144               size_left -= bufsize;
1145               p_buffer += bufsize;
1146               set_next_block_after (blk + (bufsize - 1) / BLOCKSIZE);
1147             }
1148         }
1149       return;
1150     }
1151
1152   if (!recursion_option)
1153     return;
1154
1155   if (one_file_system_option
1156       && !top_level
1157       && st->parent->stat.st_dev != st->stat.st_dev)
1158     {
1159       if (verbose_option)
1160         WARNOPT (WARN_XDEV,
1161                  (0, 0,
1162                   _("%s: file is on a different filesystem; not dumped"),
1163                   quotearg_colon (st->orig_file_name)));
1164     }
1165   else
1166     {
1167       char *name_buf;
1168       size_t name_size;
1169
1170       switch (check_exclusion_tags (st, &tag_file_name))
1171         {
1172         case exclusion_tag_all:
1173           /* Handled in dump_file0 */
1174           break;
1175
1176         case exclusion_tag_none:
1177           {
1178             char const *entry;
1179             size_t entry_len;
1180             size_t name_len;
1181
1182             name_buf = xstrdup (st->orig_file_name);
1183             name_size = name_len = strlen (name_buf);
1184
1185             /* Now output all the files in the directory.  */
1186             for (entry = directory; (entry_len = strlen (entry)) != 0;
1187                  entry += entry_len + 1)
1188               {
1189                 if (name_size < name_len + entry_len)
1190                   {
1191                     name_size = name_len + entry_len;
1192                     name_buf = xrealloc (name_buf, name_size + 1);
1193                   }
1194                 strcpy (name_buf + name_len, entry);
1195                 if (!excluded_name (name_buf))
1196                   dump_file (st, entry, name_buf);
1197               }
1198
1199             free (name_buf);
1200           }
1201           break;
1202
1203         case exclusion_tag_contents:
1204           exclusion_tag_warning (st->orig_file_name, tag_file_name,
1205                                  _("contents not dumped"));
1206           name_size = strlen (st->orig_file_name) + strlen (tag_file_name) + 1;
1207           name_buf = xmalloc (name_size);
1208           strcpy (name_buf, st->orig_file_name);
1209           strcat (name_buf, tag_file_name);
1210           dump_file (st, tag_file_name, name_buf);
1211           free (name_buf);
1212           break;
1213
1214         case exclusion_tag_under:
1215           exclusion_tag_warning (st->orig_file_name, tag_file_name,
1216                                  _("contents not dumped"));
1217           break;
1218         }
1219     }
1220 }
1221
1222 /* Ensure exactly one trailing slash.  */
1223 static void
1224 ensure_slash (char **pstr)
1225 {
1226   size_t len = strlen (*pstr);
1227   while (len >= 1 && ISSLASH ((*pstr)[len - 1]))
1228     len--;
1229   if (!ISSLASH ((*pstr)[len]))
1230     *pstr = xrealloc (*pstr, len + 2);
1231   (*pstr)[len++] = '/';
1232   (*pstr)[len] = '\0';
1233 }
1234
1235 /* If we just ran out of file descriptors, release a file descriptor
1236    in the directory chain somewhere leading from DIR->parent->parent
1237    up through the root.  Return true if successful, false (preserving
1238    errno == EMFILE) otherwise.
1239
1240    Do not release DIR's file descriptor, or DIR's parent, as other
1241    code assumes that they work.  On some operating systems, another
1242    process can claim file descriptor resources as we release them, and
1243    some calls or their emulations require multiple file descriptors,
1244    so callers should not give up if a single release doesn't work.  */
1245
1246 static bool
1247 open_failure_recover (struct tar_stat_info const *dir)
1248 {
1249   if (errno == EMFILE && dir && dir->parent)
1250     {
1251       struct tar_stat_info *p;
1252       for (p = dir->parent->parent; p; p = p->parent)
1253         if (0 < p->fd && (! p->parent || p->parent->fd <= 0))
1254           {
1255             tar_stat_close (p);
1256             return true;
1257           }
1258       errno = EMFILE;
1259     }
1260
1261   return false;
1262 }
1263
1264 /* Return the directory entries of ST, in a dynamically allocated buffer,
1265    each entry followed by '\0' and the last followed by an extra '\0'.
1266    Return null on failure, setting errno.  */
1267 char *
1268 get_directory_entries (struct tar_stat_info *st)
1269 {
1270   while (! (st->dirstream = fdopendir (st->fd)))
1271     if (! open_failure_recover (st))
1272       return 0;
1273   return streamsavedir (st->dirstream);
1274 }
1275
1276 /* Dump the directory ST.  Return true if successful, false (emitting
1277    diagnostics) otherwise.  Get ST's entries, recurse through its
1278    subdirectories, and clean up file descriptors afterwards.  */
1279 static bool
1280 dump_dir (struct tar_stat_info *st)
1281 {
1282   char *directory = get_directory_entries (st);
1283   if (! directory)
1284     {
1285       savedir_diag (st->orig_file_name);
1286       return false;
1287     }
1288
1289   dump_dir0 (st, directory);
1290
1291   restore_parent_fd (st);
1292   free (directory);
1293   return true;
1294 }
1295
1296 \f
1297 /* Number of links a file can have without having to be entered into
1298    the link table.  Typically this is 1, but in trickier circumstances
1299    it is 0.  */
1300 static nlink_t trivial_link_count;
1301
1302 \f
1303 /* Main functions of this module.  */
1304
1305 void
1306 create_archive (void)
1307 {
1308   struct name const *p;
1309
1310   trivial_link_count = name_count <= 1 && ! dereference_option;
1311
1312   open_archive (ACCESS_WRITE);
1313   buffer_write_global_xheader ();
1314
1315   if (incremental_option)
1316     {
1317       size_t buffer_size = 1000;
1318       char *buffer = xmalloc (buffer_size);
1319       const char *q;
1320
1321       collect_and_sort_names ();
1322
1323       while ((p = name_from_list ()) != NULL)
1324         if (!excluded_name (p->name))
1325           dump_file (0, p->name, p->name);
1326
1327       blank_name_list ();
1328       while ((p = name_from_list ()) != NULL)
1329         if (!excluded_name (p->name))
1330           {
1331             struct tar_stat_info st;
1332             size_t plen = strlen (p->name);
1333             if (buffer_size <= plen)
1334               {
1335                 while ((buffer_size *= 2) <= plen)
1336                   continue;
1337                 buffer = xrealloc (buffer, buffer_size);
1338               }
1339             memcpy (buffer, p->name, plen);
1340             if (! ISSLASH (buffer[plen - 1]))
1341               buffer[plen++] = DIRECTORY_SEPARATOR;
1342             tar_stat_init (&st);
1343             q = directory_contents (gnu_list_name->directory);
1344             if (q)
1345               while (*q)
1346                 {
1347                   size_t qlen = strlen (q);
1348                   if (*q == 'Y')
1349                     {
1350                       if (! st.orig_file_name)
1351                         {
1352                           int fd = openat (chdir_fd, p->name,
1353                                            open_searchdir_flags);
1354                           if (fd < 0)
1355                             {
1356                               open_diag (p->name);
1357                               break;
1358                             }
1359                           st.fd = fd;
1360                           if (fstat (fd, &st.stat) != 0)
1361                             {
1362                               stat_diag (p->name);
1363                               break;
1364                             }
1365                           st.orig_file_name = xstrdup (p->name);
1366                         }
1367                       if (buffer_size < plen + qlen)
1368                         {
1369                           while ((buffer_size *=2 ) < plen + qlen)
1370                             continue;
1371                           buffer = xrealloc (buffer, buffer_size);
1372                         }
1373                       strcpy (buffer + plen, q + 1);
1374                       dump_file (&st, q + 1, buffer);
1375                     }
1376                   q += qlen + 1;
1377                 }
1378             tar_stat_destroy (&st);
1379           }
1380       free (buffer);
1381     }
1382   else
1383     {
1384       const char *name;
1385       while ((name = name_next (1)) != NULL)
1386         if (!excluded_name (name))
1387           dump_file (0, name, name);
1388     }
1389
1390   write_eot ();
1391   close_archive ();
1392   finish_deferred_unlinks ();
1393   if (listed_incremental_option)
1394     write_directory_file ();
1395 }
1396
1397
1398 /* Calculate the hash of a link.  */
1399 static size_t
1400 hash_link (void const *entry, size_t n_buckets)
1401 {
1402   struct link const *l = entry;
1403   uintmax_t num = l->dev ^ l->ino;
1404   return num % n_buckets;
1405 }
1406
1407 /* Compare two links for equality.  */
1408 static bool
1409 compare_links (void const *entry1, void const *entry2)
1410 {
1411   struct link const *link1 = entry1;
1412   struct link const *link2 = entry2;
1413   return ((link1->dev ^ link2->dev) | (link1->ino ^ link2->ino)) == 0;
1414 }
1415
1416 static void
1417 unknown_file_error (char const *p)
1418 {
1419   WARNOPT (WARN_FILE_IGNORED,
1420            (0, 0, _("%s: Unknown file type; file ignored"),
1421             quotearg_colon (p)));
1422   if (!ignore_failed_read_option)
1423     set_exit_status (TAREXIT_FAILURE);
1424 }
1425
1426 \f
1427 /* Handling of hard links */
1428
1429 /* Table of all non-directories that we've written so far.  Any time
1430    we see another, we check the table and avoid dumping the data
1431    again if we've done it once already.  */
1432 static Hash_table *link_table;
1433
1434 /* Try to dump stat as a hard link to another file in the archive.
1435    Return true if successful.  */
1436 static bool
1437 dump_hard_link (struct tar_stat_info *st)
1438 {
1439   if (link_table
1440       && (trivial_link_count < st->stat.st_nlink || remove_files_option))
1441     {
1442       struct link lp;
1443       struct link *duplicate;
1444       off_t block_ordinal;
1445       union block *blk;
1446
1447       lp.ino = st->stat.st_ino;
1448       lp.dev = st->stat.st_dev;
1449
1450       if ((duplicate = hash_lookup (link_table, &lp)))
1451         {
1452           /* We found a link.  */
1453           char const *link_name = safer_name_suffix (duplicate->name, true,
1454                                                      absolute_names_option);
1455
1456           duplicate->nlink--;
1457
1458           block_ordinal = current_block_ordinal ();
1459           assign_string (&st->link_name, link_name);
1460           if (NAME_FIELD_SIZE - (archive_format == OLDGNU_FORMAT)
1461               < strlen (link_name) + debian_longlink_hack)
1462             write_long_link (st);
1463
1464           st->stat.st_size = 0;
1465           blk = start_header (st);
1466           if (!blk)
1467             return false;
1468           tar_copy_str (blk->header.linkname, link_name, NAME_FIELD_SIZE);
1469
1470           blk->header.typeflag = LNKTYPE;
1471           finish_header (st, blk, block_ordinal);
1472
1473           if (remove_files_option)
1474             queue_deferred_unlink (st->orig_file_name, false);
1475
1476           return true;
1477         }
1478     }
1479   return false;
1480 }
1481
1482 static void
1483 file_count_links (struct tar_stat_info *st)
1484 {
1485   if (hard_dereference_option)
1486     return;
1487   if (trivial_link_count < st->stat.st_nlink)
1488     {
1489       struct link *duplicate;
1490       char *linkname = NULL;
1491       struct link *lp;
1492
1493       assign_string (&linkname, st->orig_file_name);
1494       transform_name (&linkname, XFORM_LINK);
1495
1496       lp = xmalloc (offsetof (struct link, name)
1497                                  + strlen (linkname) + 1);
1498       lp->ino = st->stat.st_ino;
1499       lp->dev = st->stat.st_dev;
1500       lp->nlink = st->stat.st_nlink;
1501       strcpy (lp->name, linkname);
1502       free (linkname);
1503
1504       if (! ((link_table
1505               || (link_table = hash_initialize (0, 0, hash_link,
1506                                                 compare_links, 0)))
1507              && (duplicate = hash_insert (link_table, lp))))
1508         xalloc_die ();
1509
1510       if (duplicate != lp)
1511         abort ();
1512       lp->nlink--;
1513     }
1514 }
1515
1516 /* For each dumped file, check if all its links were dumped. Emit
1517    warnings if it is not so. */
1518 void
1519 check_links (void)
1520 {
1521   struct link *lp;
1522
1523   if (!link_table)
1524     return;
1525
1526   for (lp = hash_get_first (link_table); lp;
1527        lp = hash_get_next (link_table, lp))
1528     {
1529       if (lp->nlink)
1530         {
1531           WARN ((0, 0, _("Missing links to %s."), quote (lp->name)));
1532         }
1533     }
1534 }
1535
1536 /* Assuming DIR is the working directory, open FILE, using FLAGS to
1537    control the open.  A null DIR means to use ".".  If we are low on
1538    file descriptors, try to release one or more from DIR's parents to
1539    reuse it.  */
1540 int
1541 subfile_open (struct tar_stat_info const *dir, char const *file, int flags)
1542 {
1543   int fd;
1544
1545   static bool initialized;
1546   if (! initialized)
1547     {
1548       /* Initialize any tables that might be needed when file
1549          descriptors are exhausted, and whose initialization might
1550          require a file descriptor.  This includes the system message
1551          catalog and tar's message catalog.  */
1552       initialized = true;
1553       strerror (ENOENT);
1554       gettext ("");
1555     }
1556
1557   while ((fd = openat (dir ? dir->fd : chdir_fd, file, flags)) < 0
1558          && open_failure_recover (dir))
1559     continue;
1560   return fd;
1561 }
1562
1563 /* Restore the file descriptor for ST->parent, if it was temporarily
1564    closed to conserve file descriptors.  On failure, set the file
1565    descriptor to the negative of the corresponding errno value.  Call
1566    this every time a subdirectory is ascended from.  */
1567 void
1568 restore_parent_fd (struct tar_stat_info const *st)
1569 {
1570   struct tar_stat_info *parent = st->parent;
1571   if (parent && ! parent->fd)
1572     {
1573       int parentfd = openat (st->fd, "..", open_searchdir_flags);
1574       struct stat parentstat;
1575
1576       if (parentfd < 0)
1577         parentfd = - errno;
1578       else if (! (fstat (parentfd, &parentstat) == 0
1579                   && parent->stat.st_ino == parentstat.st_ino
1580                   && parent->stat.st_dev == parentstat.st_dev))
1581         {
1582           close (parentfd);
1583           parentfd = IMPOSTOR_ERRNO;
1584         }
1585
1586       if (parentfd < 0)
1587         {
1588           int origfd = openat (chdir_fd, parent->orig_file_name,
1589                                open_searchdir_flags);
1590           if (0 <= origfd)
1591             {
1592               if (fstat (parentfd, &parentstat) == 0
1593                   && parent->stat.st_ino == parentstat.st_ino
1594                   && parent->stat.st_dev == parentstat.st_dev)
1595                 parentfd = origfd;
1596               else
1597                 close (origfd);
1598             }
1599         }
1600
1601       parent->fd = parentfd;
1602     }
1603 }
1604
1605 /* Dump a single file, recursing on directories.  ST is the file's
1606    status info, NAME its name relative to the parent directory, and P
1607    its full name (which may be relative to the working directory).  */
1608
1609 /* FIXME: One should make sure that for *every* path leading to setting
1610    exit_status to failure, a clear diagnostic has been issued.  */
1611
1612 static void
1613 dump_file0 (struct tar_stat_info *st, char const *name, char const *p)
1614 {
1615   union block *header;
1616   char type;
1617   off_t original_size;
1618   struct timespec original_ctime;
1619   off_t block_ordinal = -1;
1620   int fd = 0;
1621   bool is_dir;
1622   struct tar_stat_info const *parent = st->parent;
1623   bool top_level = ! parent;
1624   int parentfd = top_level ? chdir_fd : parent->fd;
1625   void (*diag) (char const *) = 0;
1626
1627   if (interactive_option && !confirm ("add", p))
1628     return;
1629
1630   assign_string (&st->orig_file_name, p);
1631   assign_string (&st->file_name,
1632                  safer_name_suffix (p, false, absolute_names_option));
1633
1634   transform_name (&st->file_name, XFORM_REGFILE);
1635
1636   if (parentfd < 0 && ! top_level)
1637     {
1638       errno = - parentfd;
1639       diag = open_diag;
1640     }
1641   else if (fstatat (parentfd, name, &st->stat, fstatat_flags) != 0)
1642     diag = stat_diag;
1643   else if (file_dumpable_p (&st->stat))
1644     {
1645       fd = subfile_open (parent, name, open_read_flags);
1646       if (fd < 0)
1647         diag = open_diag;
1648       else
1649         {
1650           st->fd = fd;
1651           if (fstat (fd, &st->stat) != 0)
1652             diag = stat_diag;
1653         }
1654     }
1655   if (diag)
1656     {
1657       file_removed_diag (p, top_level, diag);
1658       return;
1659     }
1660
1661   st->archive_file_size = original_size = st->stat.st_size;
1662   st->atime = get_stat_atime (&st->stat);
1663   st->mtime = get_stat_mtime (&st->stat);
1664   st->ctime = original_ctime = get_stat_ctime (&st->stat);
1665
1666 #ifdef S_ISHIDDEN
1667   if (S_ISHIDDEN (st->stat.st_mode))
1668     {
1669       char *new = (char *) alloca (strlen (p) + 2);
1670       if (new)
1671         {
1672           strcpy (new, p);
1673           strcat (new, "@");
1674           p = new;
1675         }
1676     }
1677 #endif
1678
1679   /* See if we want only new files, and check if this one is too old to
1680      put in the archive.
1681
1682      This check is omitted if incremental_option is set *and* the
1683      requested file is not explicitly listed in the command line.  */
1684
1685   if (! (incremental_option && ! top_level)
1686       && !S_ISDIR (st->stat.st_mode)
1687       && OLDER_TAR_STAT_TIME (*st, m)
1688       && (!after_date_option || OLDER_TAR_STAT_TIME (*st, c)))
1689     {
1690       if (!incremental_option && verbose_option)
1691         WARNOPT (WARN_FILE_UNCHANGED,
1692                  (0, 0, _("%s: file is unchanged; not dumped"),
1693                   quotearg_colon (p)));
1694       return;
1695     }
1696
1697   /* See if we are trying to dump the archive.  */
1698   if (sys_file_is_archive (st))
1699     {
1700       WARNOPT (WARN_IGNORE_ARCHIVE,
1701                (0, 0, _("%s: file is the archive; not dumped"),
1702                 quotearg_colon (p)));
1703       return;
1704     }
1705
1706   is_dir = S_ISDIR (st->stat.st_mode) != 0;
1707
1708   if (!is_dir && dump_hard_link (st))
1709     return;
1710
1711   if (is_dir || S_ISREG (st->stat.st_mode) || S_ISCTG (st->stat.st_mode))
1712     {
1713       bool ok;
1714       struct stat final_stat;
1715
1716       if (is_dir)
1717         {
1718           const char *tag_file_name;
1719           ensure_slash (&st->orig_file_name);
1720           ensure_slash (&st->file_name);
1721
1722           if (check_exclusion_tags (st, &tag_file_name) == exclusion_tag_all)
1723             {
1724               exclusion_tag_warning (st->orig_file_name, tag_file_name,
1725                                      _("directory not dumped"));
1726               return;
1727             }
1728
1729           ok = dump_dir (st);
1730
1731           fd = st->fd;
1732           parentfd = top_level ? chdir_fd : parent->fd;
1733         }
1734       else
1735         {
1736           enum dump_status status;
1737
1738           if (fd && sparse_option && ST_IS_SPARSE (st->stat))
1739             {
1740               status = sparse_dump_file (fd, st);
1741               if (status == dump_status_not_implemented)
1742                 status = dump_regular_file (fd, st);
1743             }
1744           else
1745             status = dump_regular_file (fd, st);
1746
1747           switch (status)
1748             {
1749             case dump_status_ok:
1750             case dump_status_short:
1751               file_count_links (st);
1752               break;
1753
1754             case dump_status_fail:
1755               break;
1756
1757             case dump_status_not_implemented:
1758               abort ();
1759             }
1760
1761           ok = status == dump_status_ok;
1762         }
1763
1764       if (ok)
1765         {
1766           if (fd < 0)
1767             {
1768               errno = - fd;
1769               ok = false;
1770             }
1771           else if (fd == 0)
1772             {
1773               if (parentfd < 0 && ! top_level)
1774                 {
1775                   errno = - parentfd;
1776                   ok = false;
1777                 }
1778               else
1779                 ok = fstatat (parentfd, name, &final_stat, fstatat_flags) == 0;
1780             }
1781           else
1782             ok = fstat (fd, &final_stat) == 0;
1783
1784           if (! ok)
1785             file_removed_diag (p, top_level, stat_diag);
1786         }
1787
1788       if (ok)
1789         {
1790           if ((timespec_cmp (get_stat_ctime (&final_stat), original_ctime) != 0
1791                /* Original ctime will change if the file is a directory and
1792                   --remove-files is given */
1793                && !(remove_files_option && is_dir))
1794               || original_size < final_stat.st_size)
1795             {
1796               WARNOPT (WARN_FILE_CHANGED,
1797                        (0, 0, _("%s: file changed as we read it"),
1798                         quotearg_colon (p)));
1799               set_exit_status (TAREXIT_DIFFERS);
1800             }
1801           else if (atime_preserve_option == replace_atime_preserve
1802                    && fd && (is_dir || original_size != 0)
1803                    && set_file_atime (fd, parentfd, name, st->atime) != 0)
1804             utime_error (p);
1805         }
1806
1807       ok &= tar_stat_close (st);
1808       if (ok && remove_files_option)
1809         queue_deferred_unlink (p, is_dir);
1810
1811       return;
1812     }
1813 #ifdef HAVE_READLINK
1814   else if (S_ISLNK (st->stat.st_mode))
1815     {
1816       char *buffer;
1817       int size;
1818       size_t linklen = st->stat.st_size;
1819       if (linklen != st->stat.st_size || linklen + 1 == 0)
1820         xalloc_die ();
1821       buffer = (char *) alloca (linklen + 1);
1822       size = readlinkat (parentfd, name, buffer, linklen + 1);
1823       if (size < 0)
1824         {
1825           file_removed_diag (p, top_level, readlink_diag);
1826           return;
1827         }
1828       buffer[size] = '\0';
1829       assign_string (&st->link_name, buffer);
1830       transform_name (&st->link_name, XFORM_SYMLINK);
1831       if (NAME_FIELD_SIZE - (archive_format == OLDGNU_FORMAT) < size)
1832         write_long_link (st);
1833
1834       block_ordinal = current_block_ordinal ();
1835       st->stat.st_size = 0;     /* force 0 size on symlink */
1836       header = start_header (st);
1837       if (!header)
1838         return;
1839       tar_copy_str (header->header.linkname, st->link_name, NAME_FIELD_SIZE);
1840       header->header.typeflag = SYMTYPE;
1841       finish_header (st, header, block_ordinal);
1842       /* nothing more to do to it */
1843
1844       if (remove_files_option)
1845         queue_deferred_unlink (p, false);
1846
1847       file_count_links (st);
1848       return;
1849     }
1850 #endif
1851   else if (S_ISCHR (st->stat.st_mode))
1852     type = CHRTYPE;
1853   else if (S_ISBLK (st->stat.st_mode))
1854     type = BLKTYPE;
1855   else if (S_ISFIFO (st->stat.st_mode))
1856     type = FIFOTYPE;
1857   else if (S_ISSOCK (st->stat.st_mode))
1858     {
1859       WARNOPT (WARN_FILE_IGNORED,
1860                (0, 0, _("%s: socket ignored"), quotearg_colon (p)));
1861       return;
1862     }
1863   else if (S_ISDOOR (st->stat.st_mode))
1864     {
1865       WARNOPT (WARN_FILE_IGNORED,
1866                (0, 0, _("%s: door ignored"), quotearg_colon (p)));
1867       return;
1868     }
1869   else
1870     {
1871       unknown_file_error (p);
1872       return;
1873     }
1874
1875   if (archive_format == V7_FORMAT)
1876     {
1877       unknown_file_error (p);
1878       return;
1879     }
1880
1881   block_ordinal = current_block_ordinal ();
1882   st->stat.st_size = 0; /* force 0 size */
1883   header = start_header (st);
1884   if (!header)
1885     return;
1886   header->header.typeflag = type;
1887
1888   if (type != FIFOTYPE)
1889     {
1890       MAJOR_TO_CHARS (major (st->stat.st_rdev),
1891                       header->header.devmajor);
1892       MINOR_TO_CHARS (minor (st->stat.st_rdev),
1893                       header->header.devminor);
1894     }
1895
1896   finish_header (st, header, block_ordinal);
1897   if (remove_files_option)
1898     queue_deferred_unlink (p, false);
1899 }
1900
1901 /* Dump a file, recursively.  PARENT describes the file's parent
1902    directory, NAME is the file's name relative to PARENT, and FULLNAME
1903    its full name, possibly relative to the working directory.  NAME
1904    may contain slashes at the top level of invocation.  */
1905
1906 void
1907 dump_file (struct tar_stat_info *parent, char const *name,
1908            char const *fullname)
1909 {
1910   struct tar_stat_info st;
1911   tar_stat_init (&st);
1912   st.parent = parent;
1913   dump_file0 (&st, name, fullname);
1914   if (parent && listed_incremental_option)
1915     update_parent_directory (parent);
1916   tar_stat_destroy (&st);
1917 }