3a0f2dce9267bfd7b25999a5e6539a5b3b989d17
[debian/tar] / src / create.c
1 /* Create a tar archive.
2
3    Copyright 1985, 1992-1994, 1996-1997, 1999-2001, 2003-2007,
4    2009-2010, 2012-2014, 2016 Free Software Foundation, Inc.
5
6    This file is part of GNU tar.
7
8    GNU tar is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    GNU tar is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21    Written by John Gilmore, on 1985-08-25.  */
22
23 #include <system.h>
24
25 #include <areadlink.h>
26 #include <quotearg.h>
27
28 #include "common.h"
29 #include <hash.h>
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 < 0 ? 0 : min (t, MAX_OCTAL_VAL (header->header.mtime)),
517                  header->header.mtime);
518   MODE_TO_CHARS (S_IFREG|S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH, header->header.mode);
519   UID_TO_CHARS (0, header->header.uid);
520   GID_TO_CHARS (0, header->header.gid);
521   strncpy (header->header.magic, TMAGIC, TMAGLEN);
522   strncpy (header->header.version, TVERSION, TVERSLEN);
523   return header;
524 }
525
526 /* Create a new header and store there at most NAME_FIELD_SIZE bytes of
527    the file name */
528
529 static union block *
530 write_short_name (struct tar_stat_info *st)
531 {
532   union block *header = find_next_block ();
533   memset (header->buffer, 0, sizeof (union block));
534   tar_name_copy_str (header->header.name, st->file_name, NAME_FIELD_SIZE);
535   return header;
536 }
537
538 /* Write a GNUTYPE_LONGLINK or GNUTYPE_LONGNAME block.  */
539 static void
540 write_gnu_long_link (struct tar_stat_info *st, const char *p, char type)
541 {
542   size_t size = strlen (p) + 1;
543   size_t bufsize;
544   union block *header;
545   char *tmpname;
546
547   header = start_private_header ("././@LongLink", size, 0);
548   uid_to_uname (0, &tmpname);
549   UNAME_TO_CHARS (tmpname, header->header.uname);
550   free (tmpname);
551   gid_to_gname (0, &tmpname);
552   GNAME_TO_CHARS (tmpname, header->header.gname);
553   free (tmpname);
554
555   strcpy (header->buffer + offsetof (struct posix_header, magic),
556           OLDGNU_MAGIC);
557   header->header.typeflag = type;
558   finish_header (st, header, -1);
559
560   header = find_next_block ();
561
562   bufsize = available_space_after (header);
563
564   while (bufsize < size)
565     {
566       memcpy (header->buffer, p, bufsize);
567       p += bufsize;
568       size -= bufsize;
569       set_next_block_after (header + (bufsize - 1) / BLOCKSIZE);
570       header = find_next_block ();
571       bufsize = available_space_after (header);
572     }
573   memcpy (header->buffer, p, size);
574   memset (header->buffer + size, 0, bufsize - size);
575   set_next_block_after (header + (size - 1) / BLOCKSIZE);
576 }
577
578 static size_t
579 split_long_name (const char *name, size_t length)
580 {
581   size_t i;
582
583   if (length > PREFIX_FIELD_SIZE + 1)
584     length = PREFIX_FIELD_SIZE + 1;
585   else if (ISSLASH (name[length - 1]))
586     length--;
587   for (i = length - 1; i > 0; i--)
588     if (ISSLASH (name[i]))
589       break;
590   return i;
591 }
592
593 static union block *
594 write_ustar_long_name (const char *name)
595 {
596   size_t length = strlen (name);
597   size_t i, nlen;
598   union block *header;
599
600   if (length > PREFIX_FIELD_SIZE + NAME_FIELD_SIZE + 1)
601     {
602       ERROR ((0, 0, _("%s: file name is too long (max %d); not dumped"),
603               quotearg_colon (name),
604               PREFIX_FIELD_SIZE + NAME_FIELD_SIZE + 1));
605       return NULL;
606     }
607
608   i = split_long_name (name, length);
609   if (i == 0 || (nlen = length - i - 1) > NAME_FIELD_SIZE || nlen == 0)
610     {
611       ERROR ((0, 0,
612               _("%s: file name is too long (cannot be split); not dumped"),
613               quotearg_colon (name)));
614       return NULL;
615     }
616
617   header = find_next_block ();
618   memset (header->buffer, 0, sizeof (header->buffer));
619   memcpy (header->header.prefix, name, i);
620   memcpy (header->header.name, name + i + 1, length - i - 1);
621
622   return header;
623 }
624
625 /* Write a long link name, depending on the current archive format */
626 static void
627 write_long_link (struct tar_stat_info *st)
628 {
629   switch (archive_format)
630     {
631     case POSIX_FORMAT:
632       xheader_store ("linkpath", st, NULL);
633       break;
634
635     case V7_FORMAT:                     /* old V7 tar format */
636     case USTAR_FORMAT:
637     case STAR_FORMAT:
638       ERROR ((0, 0,
639               _("%s: link name is too long; not dumped"),
640               quotearg_colon (st->link_name)));
641       break;
642
643     case OLDGNU_FORMAT:
644     case GNU_FORMAT:
645       write_gnu_long_link (st, st->link_name, GNUTYPE_LONGLINK);
646       break;
647
648     default:
649       abort(); /*FIXME*/
650     }
651 }
652
653 static union block *
654 write_long_name (struct tar_stat_info *st)
655 {
656   switch (archive_format)
657     {
658     case POSIX_FORMAT:
659       xheader_store ("path", st, NULL);
660       break;
661
662     case V7_FORMAT:
663       if (strlen (st->file_name) > NAME_FIELD_SIZE-1)
664         {
665           ERROR ((0, 0, _("%s: file name is too long (max %d); not dumped"),
666                   quotearg_colon (st->file_name),
667                   NAME_FIELD_SIZE - 1));
668           return NULL;
669         }
670       break;
671
672     case USTAR_FORMAT:
673     case STAR_FORMAT:
674       return write_ustar_long_name (st->file_name);
675
676     case OLDGNU_FORMAT:
677     case GNU_FORMAT:
678       write_gnu_long_link (st, st->file_name, GNUTYPE_LONGNAME);
679       break;
680
681     default:
682       abort(); /*FIXME*/
683     }
684   return write_short_name (st);
685 }
686
687 union block *
688 write_extended (bool global, struct tar_stat_info *st, union block *old_header)
689 {
690   union block *header, hp;
691   char *p;
692   int type;
693   time_t t;
694
695   if (st->xhdr.buffer || st->xhdr.stk == NULL)
696     return old_header;
697
698   xheader_finish (&st->xhdr);
699   memcpy (hp.buffer, old_header, sizeof (hp));
700   if (global)
701     {
702       type = XGLTYPE;
703       p = xheader_ghdr_name ();
704       t = start_time.tv_sec;
705     }
706   else
707     {
708       type = XHDTYPE;
709       p = xheader_xhdr_name (st);
710       t = set_mtime_option ? mtime_option.tv_sec : st->stat.st_mtime;
711     }
712   xheader_write (type, p, t, &st->xhdr);
713   free (p);
714   header = find_next_block ();
715   memcpy (header, &hp.buffer, sizeof (hp.buffer));
716   return header;
717 }
718
719 static union block *
720 write_header_name (struct tar_stat_info *st)
721 {
722   if (archive_format == POSIX_FORMAT && !string_ascii_p (st->file_name))
723     {
724       xheader_store ("path", st, NULL);
725       return write_short_name (st);
726     }
727   else if (NAME_FIELD_SIZE - (archive_format == OLDGNU_FORMAT)
728            < strlen (st->file_name))
729     return write_long_name (st);
730   else
731     return write_short_name (st);
732 }
733
734 \f
735 /* Header handling.  */
736
737 /* Make a header block for the file whose stat info is st,
738    and return its address.  */
739
740 union block *
741 start_header (struct tar_stat_info *st)
742 {
743   union block *header;
744   char const *uname = NULL;
745   char const *gname = NULL;
746   
747   header = write_header_name (st);
748   if (!header)
749     return NULL;
750
751   /* Override some stat fields, if requested to do so.  */
752   owner_map_translate (st->stat.st_uid, &st->stat.st_uid, &uname);
753   group_map_translate (st->stat.st_gid, &st->stat.st_gid, &gname);
754
755   if (mode_option)
756     st->stat.st_mode =
757       ((st->stat.st_mode & ~MODE_ALL)
758        | mode_adjust (st->stat.st_mode, S_ISDIR (st->stat.st_mode) != 0,
759                       initial_umask, mode_option, NULL));
760
761   /* Paul Eggert tried the trivial test ($WRITER cf a b; $READER tvf a)
762      for a few tars and came up with the following interoperability
763      matrix:
764
765               WRITER
766         1 2 3 4 5 6 7 8 9   READER
767         . . . . . . . . .   1 = SunOS 4.2 tar
768         # . . # # . . # #   2 = NEC SVR4.0.2 tar
769         . . . # # . . # .   3 = Solaris 2.1 tar
770         . . . . . . . . .   4 = GNU tar 1.11.1
771         . . . . . . . . .   5 = HP-UX 8.07 tar
772         . . . . . . . . .   6 = Ultrix 4.1
773         . . . . . . . . .   7 = AIX 3.2
774         . . . . . . . . .   8 = Hitachi HI-UX 1.03
775         . . . . . . . . .   9 = Omron UNIOS-B 4.3BSD 1.60Beta
776
777              . = works
778              # = "impossible file type"
779
780      The following mask for old archive removes the '#'s in column 4
781      above, thus making GNU tar both a universal donor and a universal
782      acceptor for Paul's test.  */
783
784   if (archive_format == V7_FORMAT || archive_format == USTAR_FORMAT)
785     MODE_TO_CHARS (st->stat.st_mode & MODE_ALL, header->header.mode);
786   else
787     MODE_TO_CHARS (st->stat.st_mode, header->header.mode);
788
789   {
790     uid_t uid = st->stat.st_uid;
791     if (archive_format == POSIX_FORMAT
792         && MAX_OCTAL_VAL (header->header.uid) < uid)
793       {
794         xheader_store ("uid", st, NULL);
795         uid = 0;
796       }
797     if (!UID_TO_CHARS (uid, header->header.uid))
798       return NULL;
799   }
800
801   {
802     gid_t gid = st->stat.st_gid;
803     if (archive_format == POSIX_FORMAT
804         && MAX_OCTAL_VAL (header->header.gid) < gid)
805       {
806         xheader_store ("gid", st, NULL);
807         gid = 0;
808       }
809     if (!GID_TO_CHARS (gid, header->header.gid))
810       return NULL;
811   }
812
813   {
814     off_t size = st->stat.st_size;
815     if (archive_format == POSIX_FORMAT
816         && MAX_OCTAL_VAL (header->header.size) < size)
817       {
818         xheader_store ("size", st, NULL);
819         size = 0;
820       }
821     if (!OFF_TO_CHARS (size, header->header.size))
822       return NULL;
823   }
824
825   {
826     struct timespec mtime;
827
828     switch (set_mtime_option)
829       {
830       case USE_FILE_MTIME:
831         mtime = st->mtime;
832         break;
833           
834       case FORCE_MTIME:
835         mtime = mtime_option;
836         break;
837           
838       case CLAMP_MTIME:
839         mtime = timespec_cmp (st->mtime, mtime_option) > 0
840                    ? mtime_option : st->mtime;
841         break;
842       }
843
844     if (archive_format == POSIX_FORMAT)
845       {
846         if (MAX_OCTAL_VAL (header->header.mtime) < mtime.tv_sec
847             || mtime.tv_nsec != 0)
848           xheader_store ("mtime", st, &mtime);
849         if (MAX_OCTAL_VAL (header->header.mtime) < mtime.tv_sec)
850           mtime.tv_sec = 0;
851       }
852     if (!TIME_TO_CHARS (mtime.tv_sec, header->header.mtime))
853       return NULL;
854   }
855
856   /* FIXME */
857   if (S_ISCHR (st->stat.st_mode)
858       || S_ISBLK (st->stat.st_mode))
859     {
860       major_t devmajor = major (st->stat.st_rdev);
861       minor_t devminor = minor (st->stat.st_rdev);
862
863       if (archive_format == POSIX_FORMAT
864           && MAX_OCTAL_VAL (header->header.devmajor) < devmajor)
865         {
866           xheader_store ("devmajor", st, NULL);
867           devmajor = 0;
868         }
869       if (!MAJOR_TO_CHARS (devmajor, header->header.devmajor))
870         return NULL;
871
872       if (archive_format == POSIX_FORMAT
873           && MAX_OCTAL_VAL (header->header.devminor) < devminor)
874         {
875           xheader_store ("devminor", st, NULL);
876           devminor = 0;
877         }
878       if (!MINOR_TO_CHARS (devminor, header->header.devminor))
879         return NULL;
880     }
881   else if (archive_format != GNU_FORMAT && archive_format != OLDGNU_FORMAT)
882     {
883       if (!(MAJOR_TO_CHARS (0, header->header.devmajor)
884             && MINOR_TO_CHARS (0, header->header.devminor)))
885         return NULL;
886     }
887
888   if (archive_format == POSIX_FORMAT)
889     {
890       xheader_store ("atime", st, NULL);
891       xheader_store ("ctime", st, NULL);
892     }
893   else if (incremental_option)
894     if (archive_format == OLDGNU_FORMAT || archive_format == GNU_FORMAT)
895       {
896         TIME_TO_CHARS (st->atime.tv_sec, header->oldgnu_header.atime);
897         TIME_TO_CHARS (st->ctime.tv_sec, header->oldgnu_header.ctime);
898       }
899
900   header->header.typeflag = archive_format == V7_FORMAT ? AREGTYPE : REGTYPE;
901
902   switch (archive_format)
903     {
904     case V7_FORMAT:
905       break;
906
907     case OLDGNU_FORMAT:
908     case GNU_FORMAT:   /*FIXME?*/
909       /* Overwrite header->header.magic and header.version in one blow.  */
910       strcpy (header->buffer + offsetof (struct posix_header, magic),
911               OLDGNU_MAGIC);
912       break;
913
914     case POSIX_FORMAT:
915     case USTAR_FORMAT:
916       strncpy (header->header.magic, TMAGIC, TMAGLEN);
917       strncpy (header->header.version, TVERSION, TVERSLEN);
918       break;
919
920     default:
921       abort ();
922     }
923
924   if (archive_format == V7_FORMAT || numeric_owner_option)
925     {
926       /* header->header.[ug]name are left as the empty string.  */
927     }
928   else
929     {
930       if (uname)
931         st->uname = xstrdup (uname);
932       else
933         uid_to_uname (st->stat.st_uid, &st->uname);
934
935       if (gname)
936         st->gname = xstrdup (gname);
937       else
938         gid_to_gname (st->stat.st_gid, &st->gname);
939
940       if (archive_format == POSIX_FORMAT
941           && (strlen (st->uname) > UNAME_FIELD_SIZE
942               || !string_ascii_p (st->uname)))
943         xheader_store ("uname", st, NULL);
944       UNAME_TO_CHARS (st->uname, header->header.uname);
945
946       if (archive_format == POSIX_FORMAT
947           && (strlen (st->gname) > GNAME_FIELD_SIZE
948               || !string_ascii_p (st->gname)))
949         xheader_store ("gname", st, NULL);
950       GNAME_TO_CHARS (st->gname, header->header.gname);
951     }
952
953   if (archive_format == POSIX_FORMAT)
954     {
955       if (acls_option > 0)
956         {
957           if (st->acls_a_ptr)
958             xheader_store ("SCHILY.acl.access", st, NULL);
959           if (st->acls_d_ptr)
960             xheader_store ("SCHILY.acl.default", st, NULL);
961         }
962       if ((selinux_context_option > 0) && st->cntx_name)
963         xheader_store ("RHT.security.selinux", st, NULL);
964       if (xattrs_option > 0)
965         {
966           size_t scan_xattr = 0;
967           struct xattr_array *xattr_map = st->xattr_map;
968
969           while (scan_xattr < st->xattr_map_size)
970             {
971               xheader_store (xattr_map[scan_xattr].xkey, st, &scan_xattr);
972               ++scan_xattr;
973             }
974         }
975     }
976
977   return header;
978 }
979
980 void
981 simple_finish_header (union block *header)
982 {
983   size_t i;
984   int sum;
985   char *p;
986
987   memcpy (header->header.chksum, CHKBLANKS, sizeof header->header.chksum);
988
989   sum = 0;
990   p = header->buffer;
991   for (i = sizeof *header; i-- != 0; )
992     /* We can't use unsigned char here because of old compilers, e.g. V7.  */
993     sum += 0xFF & *p++;
994
995   /* Fill in the checksum field.  It's formatted differently from the
996      other fields: it has [6] digits, a null, then a space -- rather than
997      digits, then a null.  We use to_chars.
998      The final space is already there, from
999      checksumming, and to_chars doesn't modify it.
1000
1001      This is a fast way to do:
1002
1003      sprintf(header->header.chksum, "%6o", sum);  */
1004
1005   uintmax_to_chars ((uintmax_t) sum, header->header.chksum, 7);
1006
1007   set_next_block_after (header);
1008 }
1009
1010 /* Finish off a filled-in header block and write it out.  We also
1011    print the file name and/or full info if verbose is on.  If BLOCK_ORDINAL
1012    is not negative, is the block ordinal of the first record for this
1013    file, which may be a preceding long name or long link record.  */
1014 void
1015 finish_header (struct tar_stat_info *st,
1016                union block *header, off_t block_ordinal)
1017 {
1018   /* Note: It is important to do this before the call to write_extended(),
1019      so that the actual ustar header is printed */
1020   if (verbose_option
1021       && header->header.typeflag != GNUTYPE_LONGLINK
1022       && header->header.typeflag != GNUTYPE_LONGNAME
1023       && header->header.typeflag != XHDTYPE
1024       && header->header.typeflag != XGLTYPE)
1025     {
1026       /* FIXME: This global is used in print_header, sigh.  */
1027       current_format = archive_format;
1028       print_header (st, header, block_ordinal);
1029     }
1030
1031   header = write_extended (false, st, header);
1032   simple_finish_header (header);
1033 }
1034 \f
1035
1036 void
1037 pad_archive (off_t size_left)
1038 {
1039   union block *blk;
1040   while (size_left > 0)
1041     {
1042       blk = find_next_block ();
1043       memset (blk->buffer, 0, BLOCKSIZE);
1044       set_next_block_after (blk);
1045       size_left -= BLOCKSIZE;
1046     }
1047 }
1048
1049 static enum dump_status
1050 dump_regular_file (int fd, struct tar_stat_info *st)
1051 {
1052   off_t size_left = st->stat.st_size;
1053   off_t block_ordinal;
1054   union block *blk;
1055
1056   block_ordinal = current_block_ordinal ();
1057   blk = start_header (st);
1058   if (!blk)
1059     return dump_status_fail;
1060
1061   /* Mark contiguous files, if we support them.  */
1062   if (archive_format != V7_FORMAT && S_ISCTG (st->stat.st_mode))
1063     blk->header.typeflag = CONTTYPE;
1064
1065   finish_header (st, blk, block_ordinal);
1066
1067   mv_begin_write (st->file_name, st->stat.st_size, st->stat.st_size);
1068   while (size_left > 0)
1069     {
1070       size_t bufsize, count;
1071
1072       blk = find_next_block ();
1073
1074       bufsize = available_space_after (blk);
1075
1076       if (size_left < bufsize)
1077         {
1078           /* Last read -- zero out area beyond.  */
1079           bufsize = size_left;
1080           count = bufsize % BLOCKSIZE;
1081           if (count)
1082             memset (blk->buffer + size_left, 0, BLOCKSIZE - count);
1083         }
1084
1085       count = (fd <= 0) ? bufsize : blocking_read (fd, blk->buffer, bufsize);
1086       if (count == SAFE_READ_ERROR)
1087         {
1088           read_diag_details (st->orig_file_name,
1089                              st->stat.st_size - size_left, bufsize);
1090           pad_archive (size_left);
1091           return dump_status_short;
1092         }
1093       size_left -= count;
1094       set_next_block_after (blk + (bufsize - 1) / BLOCKSIZE);
1095
1096       if (count != bufsize)
1097         {
1098           char buf[UINTMAX_STRSIZE_BOUND];
1099           memset (blk->buffer + count, 0, bufsize - count);
1100           WARNOPT (WARN_FILE_SHRANK,
1101                    (0, 0,
1102                     ngettext ("%s: File shrank by %s byte; padding with zeros",
1103                               "%s: File shrank by %s bytes; padding with zeros",
1104                               size_left),
1105                     quotearg_colon (st->orig_file_name),
1106                     STRINGIFY_BIGINT (size_left, buf)));
1107           if (! ignore_failed_read_option)
1108             set_exit_status (TAREXIT_DIFFERS);
1109           pad_archive (size_left - (bufsize - count));
1110           return dump_status_short;
1111         }
1112     }
1113   return dump_status_ok;
1114 }
1115
1116 \f
1117 /* Copy info from the directory identified by ST into the archive.
1118    DIRECTORY contains the directory's entries.  */
1119
1120 static void
1121 dump_dir0 (struct tar_stat_info *st, char const *directory)
1122 {
1123   bool top_level = ! st->parent;
1124   const char *tag_file_name;
1125   union block *blk = NULL;
1126   off_t block_ordinal = current_block_ordinal ();
1127
1128   st->stat.st_size = 0; /* force 0 size on dir */
1129
1130   blk = start_header (st);
1131   if (!blk)
1132     return;
1133
1134   info_attach_exclist (st);
1135
1136   if (incremental_option && archive_format != POSIX_FORMAT)
1137     blk->header.typeflag = GNUTYPE_DUMPDIR;
1138   else /* if (standard_option) */
1139     blk->header.typeflag = DIRTYPE;
1140
1141   /* If we're gnudumping, we aren't done yet so don't close it.  */
1142
1143   if (!incremental_option)
1144     finish_header (st, blk, block_ordinal);
1145   else if (gnu_list_name->directory)
1146     {
1147       if (archive_format == POSIX_FORMAT)
1148         {
1149           xheader_store ("GNU.dumpdir", st,
1150                          safe_directory_contents (gnu_list_name->directory));
1151           finish_header (st, blk, block_ordinal);
1152         }
1153       else
1154         {
1155           off_t size_left;
1156           off_t totsize;
1157           size_t bufsize;
1158           ssize_t count;
1159           const char *buffer, *p_buffer;
1160
1161           block_ordinal = current_block_ordinal ();
1162           buffer = safe_directory_contents (gnu_list_name->directory);
1163           totsize = dumpdir_size (buffer);
1164           OFF_TO_CHARS (totsize, blk->header.size);
1165           finish_header (st, blk, block_ordinal);
1166           p_buffer = buffer;
1167           size_left = totsize;
1168
1169           mv_begin_write (st->file_name, totsize, totsize);
1170           while (size_left > 0)
1171             {
1172               blk = find_next_block ();
1173               bufsize = available_space_after (blk);
1174               if (size_left < bufsize)
1175                 {
1176                   bufsize = size_left;
1177                   count = bufsize % BLOCKSIZE;
1178                   if (count)
1179                     memset (blk->buffer + size_left, 0, BLOCKSIZE - count);
1180                 }
1181               memcpy (blk->buffer, p_buffer, bufsize);
1182               size_left -= bufsize;
1183               p_buffer += bufsize;
1184               set_next_block_after (blk + (bufsize - 1) / BLOCKSIZE);
1185             }
1186         }
1187       return;
1188     }
1189
1190   if (!recursion_option)
1191     return;
1192
1193   if (one_file_system_option
1194       && !top_level
1195       && st->parent->stat.st_dev != st->stat.st_dev)
1196     {
1197       if (verbose_option)
1198         WARNOPT (WARN_XDEV,
1199                  (0, 0,
1200                   _("%s: file is on a different filesystem; not dumped"),
1201                   quotearg_colon (st->orig_file_name)));
1202     }
1203   else
1204     {
1205       char *name_buf;
1206       size_t name_size;
1207
1208       switch (check_exclusion_tags (st, &tag_file_name))
1209         {
1210         case exclusion_tag_all:
1211           /* Handled in dump_file0 */
1212           break;
1213
1214         case exclusion_tag_none:
1215           {
1216             char const *entry;
1217             size_t entry_len;
1218             size_t name_len;
1219
1220             name_buf = xstrdup (st->orig_file_name);
1221             name_size = name_len = strlen (name_buf);
1222
1223             /* Now output all the files in the directory.  */
1224             for (entry = directory; (entry_len = strlen (entry)) != 0;
1225                  entry += entry_len + 1)
1226               {
1227                 if (name_size < name_len + entry_len)
1228                   {
1229                     name_size = name_len + entry_len;
1230                     name_buf = xrealloc (name_buf, name_size + 1);
1231                   }
1232                 strcpy (name_buf + name_len, entry);
1233                 if (!excluded_name (name_buf, st))
1234                   dump_file (st, entry, name_buf);
1235               }
1236
1237             free (name_buf);
1238           }
1239           break;
1240
1241         case exclusion_tag_contents:
1242           exclusion_tag_warning (st->orig_file_name, tag_file_name,
1243                                  _("contents not dumped"));
1244           name_size = strlen (st->orig_file_name) + strlen (tag_file_name) + 1;
1245           name_buf = xmalloc (name_size);
1246           strcpy (name_buf, st->orig_file_name);
1247           strcat (name_buf, tag_file_name);
1248           dump_file (st, tag_file_name, name_buf);
1249           free (name_buf);
1250           break;
1251
1252         case exclusion_tag_under:
1253           exclusion_tag_warning (st->orig_file_name, tag_file_name,
1254                                  _("contents not dumped"));
1255           break;
1256         }
1257     }
1258 }
1259
1260 /* Ensure exactly one trailing slash.  */
1261 static void
1262 ensure_slash (char **pstr)
1263 {
1264   size_t len = strlen (*pstr);
1265   while (len >= 1 && ISSLASH ((*pstr)[len - 1]))
1266     len--;
1267   if (!ISSLASH ((*pstr)[len]))
1268     *pstr = xrealloc (*pstr, len + 2);
1269   (*pstr)[len++] = '/';
1270   (*pstr)[len] = '\0';
1271 }
1272
1273 /* If we just ran out of file descriptors, release a file descriptor
1274    in the directory chain somewhere leading from DIR->parent->parent
1275    up through the root.  Return true if successful, false (preserving
1276    errno == EMFILE) otherwise.
1277
1278    Do not release DIR's file descriptor, or DIR's parent, as other
1279    code assumes that they work.  On some operating systems, another
1280    process can claim file descriptor resources as we release them, and
1281    some calls or their emulations require multiple file descriptors,
1282    so callers should not give up if a single release doesn't work.  */
1283
1284 static bool
1285 open_failure_recover (struct tar_stat_info const *dir)
1286 {
1287   if (errno == EMFILE && dir && dir->parent)
1288     {
1289       struct tar_stat_info *p;
1290       for (p = dir->parent->parent; p; p = p->parent)
1291         if (0 < p->fd && (! p->parent || p->parent->fd <= 0))
1292           {
1293             tar_stat_close (p);
1294             return true;
1295           }
1296       errno = EMFILE;
1297     }
1298
1299   return false;
1300 }
1301
1302 /* Return the directory entries of ST, in a dynamically allocated buffer,
1303    each entry followed by '\0' and the last followed by an extra '\0'.
1304    Return null on failure, setting errno.  */
1305 char *
1306 get_directory_entries (struct tar_stat_info *st)
1307 {
1308   while (! (st->dirstream = fdopendir (st->fd)))
1309     if (! open_failure_recover (st))
1310       return 0;
1311   return streamsavedir (st->dirstream, savedir_sort_order);
1312 }
1313
1314 /* Dump the directory ST.  Return true if successful, false (emitting
1315    diagnostics) otherwise.  Get ST's entries, recurse through its
1316    subdirectories, and clean up file descriptors afterwards.  */
1317 static bool
1318 dump_dir (struct tar_stat_info *st)
1319 {
1320   char *directory = get_directory_entries (st);
1321   if (! directory)
1322     {
1323       savedir_diag (st->orig_file_name);
1324       return false;
1325     }
1326
1327   dump_dir0 (st, directory);
1328
1329   restore_parent_fd (st);
1330   free (directory);
1331   return true;
1332 }
1333
1334 \f
1335 /* Number of links a file can have without having to be entered into
1336    the link table.  Typically this is 1, but in trickier circumstances
1337    it is 0.  */
1338 static nlink_t trivial_link_count;
1339
1340 \f
1341 /* Main functions of this module.  */
1342
1343 void
1344 create_archive (void)
1345 {
1346   struct name const *p;
1347
1348   trivial_link_count = name_count <= 1 && ! dereference_option;
1349
1350   open_archive (ACCESS_WRITE);
1351   buffer_write_global_xheader ();
1352
1353   if (incremental_option)
1354     {
1355       size_t buffer_size = 1000;
1356       char *buffer = xmalloc (buffer_size);
1357       const char *q;
1358
1359       collect_and_sort_names ();
1360
1361       while ((p = name_from_list ()) != NULL)
1362         if (!excluded_name (p->name, NULL))
1363           dump_file (0, p->name, p->name);
1364
1365       blank_name_list ();
1366       while ((p = name_from_list ()) != NULL)
1367         if (!excluded_name (p->name, NULL))
1368           {
1369             struct tar_stat_info st;
1370             size_t plen = strlen (p->name);
1371             if (buffer_size <= plen)
1372               {
1373                 while ((buffer_size *= 2) <= plen)
1374                   continue;
1375                 buffer = xrealloc (buffer, buffer_size);
1376               }
1377             memcpy (buffer, p->name, plen);
1378             if (! ISSLASH (buffer[plen - 1]))
1379               buffer[plen++] = DIRECTORY_SEPARATOR;
1380             tar_stat_init (&st);
1381             q = directory_contents (p->directory);
1382             if (q)
1383               while (*q)
1384                 {
1385                   size_t qlen = strlen (q);
1386                   if (*q == 'Y')
1387                     {
1388                       if (! st.orig_file_name)
1389                         {
1390                           int fd = openat (chdir_fd, p->name,
1391                                            open_searchdir_flags);
1392                           if (fd < 0)
1393                             {
1394                               open_diag (p->name);
1395                               break;
1396                             }
1397                           st.fd = fd;
1398                           if (fstat (fd, &st.stat) != 0)
1399                             {
1400                               stat_diag (p->name);
1401                               break;
1402                             }
1403                           st.orig_file_name = xstrdup (p->name);
1404                         }
1405                       if (buffer_size < plen + qlen)
1406                         {
1407                           while ((buffer_size *=2 ) < plen + qlen)
1408                             continue;
1409                           buffer = xrealloc (buffer, buffer_size);
1410                         }
1411                       strcpy (buffer + plen, q + 1);
1412                       dump_file (&st, q + 1, buffer);
1413                     }
1414                   q += qlen + 1;
1415                 }
1416             tar_stat_destroy (&st);
1417           }
1418       free (buffer);
1419     }
1420   else
1421     {
1422       const char *name;
1423       while ((name = name_next (1)) != NULL)
1424         if (!excluded_name (name, NULL))
1425           dump_file (0, name, name);
1426     }
1427
1428   write_eot ();
1429   close_archive ();
1430   finish_deferred_unlinks ();
1431   if (listed_incremental_option)
1432     write_directory_file ();
1433 }
1434
1435
1436 /* Calculate the hash of a link.  */
1437 static size_t
1438 hash_link (void const *entry, size_t n_buckets)
1439 {
1440   struct link const *l = entry;
1441   uintmax_t num = l->dev ^ l->ino;
1442   return num % n_buckets;
1443 }
1444
1445 /* Compare two links for equality.  */
1446 static bool
1447 compare_links (void const *entry1, void const *entry2)
1448 {
1449   struct link const *link1 = entry1;
1450   struct link const *link2 = entry2;
1451   return ((link1->dev ^ link2->dev) | (link1->ino ^ link2->ino)) == 0;
1452 }
1453
1454 static void
1455 unknown_file_error (char const *p)
1456 {
1457   WARNOPT (WARN_FILE_IGNORED,
1458            (0, 0, _("%s: Unknown file type; file ignored"),
1459             quotearg_colon (p)));
1460   if (!ignore_failed_read_option)
1461     set_exit_status (TAREXIT_FAILURE);
1462 }
1463
1464 \f
1465 /* Handling of hard links */
1466
1467 /* Table of all non-directories that we've written so far.  Any time
1468    we see another, we check the table and avoid dumping the data
1469    again if we've done it once already.  */
1470 static Hash_table *link_table;
1471
1472 /* Try to dump stat as a hard link to another file in the archive.
1473    Return true if successful.  */
1474 static bool
1475 dump_hard_link (struct tar_stat_info *st)
1476 {
1477   if (link_table
1478       && (trivial_link_count < st->stat.st_nlink || remove_files_option))
1479     {
1480       struct link lp;
1481       struct link *duplicate;
1482       off_t block_ordinal;
1483       union block *blk;
1484
1485       lp.ino = st->stat.st_ino;
1486       lp.dev = st->stat.st_dev;
1487
1488       if ((duplicate = hash_lookup (link_table, &lp)))
1489         {
1490           /* We found a link.  */
1491           char const *link_name = safer_name_suffix (duplicate->name, true,
1492                                                      absolute_names_option);
1493           if (duplicate->nlink)
1494             duplicate->nlink--;
1495
1496           block_ordinal = current_block_ordinal ();
1497           assign_string (&st->link_name, link_name);
1498           if (NAME_FIELD_SIZE - (archive_format == OLDGNU_FORMAT)
1499               < strlen (link_name))
1500             write_long_link (st);
1501
1502           st->stat.st_size = 0;
1503           blk = start_header (st);
1504           if (!blk)
1505             return false;
1506           tar_copy_str (blk->header.linkname, link_name, NAME_FIELD_SIZE);
1507
1508           blk->header.typeflag = LNKTYPE;
1509           finish_header (st, blk, block_ordinal);
1510
1511           if (remove_files_option)
1512             queue_deferred_unlink (st->orig_file_name, false);
1513
1514           return true;
1515         }
1516     }
1517   return false;
1518 }
1519
1520 static void
1521 file_count_links (struct tar_stat_info *st)
1522 {
1523   if (hard_dereference_option)
1524     return;
1525   if (trivial_link_count < st->stat.st_nlink)
1526     {
1527       struct link *duplicate;
1528       char *linkname = NULL;
1529       struct link *lp;
1530
1531       assign_string (&linkname, st->orig_file_name);
1532       transform_name (&linkname, XFORM_LINK);
1533
1534       lp = xmalloc (offsetof (struct link, name)
1535                                  + strlen (linkname) + 1);
1536       lp->ino = st->stat.st_ino;
1537       lp->dev = st->stat.st_dev;
1538       lp->nlink = st->stat.st_nlink;
1539       strcpy (lp->name, linkname);
1540       free (linkname);
1541
1542       if (! ((link_table
1543               || (link_table = hash_initialize (0, 0, hash_link,
1544                                                 compare_links, 0)))
1545              && (duplicate = hash_insert (link_table, lp))))
1546         xalloc_die ();
1547
1548       if (duplicate != lp)
1549         abort ();
1550       lp->nlink--;
1551     }
1552 }
1553
1554 /* For each dumped file, check if all its links were dumped. Emit
1555    warnings if it is not so. */
1556 void
1557 check_links (void)
1558 {
1559   struct link *lp;
1560
1561   if (!link_table)
1562     return;
1563
1564   for (lp = hash_get_first (link_table); lp;
1565        lp = hash_get_next (link_table, lp))
1566     {
1567       if (lp->nlink)
1568         {
1569           WARN ((0, 0, _("Missing links to %s."), quote (lp->name)));
1570         }
1571     }
1572 }
1573
1574 /* Assuming DIR is the working directory, open FILE, using FLAGS to
1575    control the open.  A null DIR means to use ".".  If we are low on
1576    file descriptors, try to release one or more from DIR's parents to
1577    reuse it.  */
1578 int
1579 subfile_open (struct tar_stat_info const *dir, char const *file, int flags)
1580 {
1581   int fd;
1582
1583   static bool initialized;
1584   if (! initialized)
1585     {
1586       /* Initialize any tables that might be needed when file
1587          descriptors are exhausted, and whose initialization might
1588          require a file descriptor.  This includes the system message
1589          catalog and tar's message catalog.  */
1590       initialized = true;
1591       strerror (ENOENT);
1592       gettext ("");
1593     }
1594
1595   while ((fd = openat (dir ? dir->fd : chdir_fd, file, flags)) < 0
1596          && open_failure_recover (dir))
1597     continue;
1598   return fd;
1599 }
1600
1601 /* Restore the file descriptor for ST->parent, if it was temporarily
1602    closed to conserve file descriptors.  On failure, set the file
1603    descriptor to the negative of the corresponding errno value.  Call
1604    this every time a subdirectory is ascended from.  */
1605 void
1606 restore_parent_fd (struct tar_stat_info const *st)
1607 {
1608   struct tar_stat_info *parent = st->parent;
1609   if (parent && ! parent->fd)
1610     {
1611       int parentfd = openat (st->fd, "..", open_searchdir_flags);
1612       struct stat parentstat;
1613
1614       if (parentfd < 0)
1615         parentfd = - errno;
1616       else if (! (fstat (parentfd, &parentstat) == 0
1617                   && parent->stat.st_ino == parentstat.st_ino
1618                   && parent->stat.st_dev == parentstat.st_dev))
1619         {
1620           close (parentfd);
1621           parentfd = IMPOSTOR_ERRNO;
1622         }
1623
1624       if (parentfd < 0)
1625         {
1626           int origfd = openat (chdir_fd, parent->orig_file_name,
1627                                open_searchdir_flags);
1628           if (0 <= origfd)
1629             {
1630               if (fstat (parentfd, &parentstat) == 0
1631                   && parent->stat.st_ino == parentstat.st_ino
1632                   && parent->stat.st_dev == parentstat.st_dev)
1633                 parentfd = origfd;
1634               else
1635                 close (origfd);
1636             }
1637         }
1638
1639       parent->fd = parentfd;
1640     }
1641 }
1642
1643 /* Dump a single file, recursing on directories.  ST is the file's
1644    status info, NAME its name relative to the parent directory, and P
1645    its full name (which may be relative to the working directory).  */
1646
1647 /* FIXME: One should make sure that for *every* path leading to setting
1648    exit_status to failure, a clear diagnostic has been issued.  */
1649
1650 static void
1651 dump_file0 (struct tar_stat_info *st, char const *name, char const *p)
1652 {
1653   union block *header;
1654   char type;
1655   off_t original_size;
1656   struct timespec original_ctime;
1657   off_t block_ordinal = -1;
1658   int fd = 0;
1659   bool is_dir;
1660   struct tar_stat_info const *parent = st->parent;
1661   bool top_level = ! parent;
1662   int parentfd = top_level ? chdir_fd : parent->fd;
1663   void (*diag) (char const *) = 0;
1664
1665   if (interactive_option && !confirm ("add", p))
1666     return;
1667
1668   assign_string (&st->orig_file_name, p);
1669   assign_string (&st->file_name,
1670                  safer_name_suffix (p, false, absolute_names_option));
1671
1672   transform_name (&st->file_name, XFORM_REGFILE);
1673
1674   if (parentfd < 0 && ! top_level)
1675     {
1676       errno = - parentfd;
1677       diag = open_diag;
1678     }
1679   else if (fstatat (parentfd, name, &st->stat, fstatat_flags) != 0)
1680     diag = stat_diag;
1681   else if (file_dumpable_p (&st->stat))
1682     {
1683       fd = subfile_open (parent, name, open_read_flags);
1684       if (fd < 0)
1685         diag = open_diag;
1686       else
1687         {
1688           st->fd = fd;
1689           if (fstat (fd, &st->stat) != 0)
1690             diag = stat_diag;
1691         }
1692     }
1693   if (diag)
1694     {
1695       file_removed_diag (p, top_level, diag);
1696       return;
1697     }
1698
1699   st->archive_file_size = original_size = st->stat.st_size;
1700   st->atime = get_stat_atime (&st->stat);
1701   st->mtime = get_stat_mtime (&st->stat);
1702   st->ctime = original_ctime = get_stat_ctime (&st->stat);
1703
1704 #ifdef S_ISHIDDEN
1705   if (S_ISHIDDEN (st->stat.st_mode))
1706     {
1707       char *new = (char *) alloca (strlen (p) + 2);
1708       if (new)
1709         {
1710           strcpy (new, p);
1711           strcat (new, "@");
1712           p = new;
1713         }
1714     }
1715 #endif
1716
1717   /* See if we want only new files, and check if this one is too old to
1718      put in the archive.
1719
1720      This check is omitted if incremental_option is set *and* the
1721      requested file is not explicitly listed in the command line.  */
1722
1723   if (! (incremental_option && ! top_level)
1724       && !S_ISDIR (st->stat.st_mode)
1725       && OLDER_TAR_STAT_TIME (*st, m)
1726       && (!after_date_option || OLDER_TAR_STAT_TIME (*st, c)))
1727     {
1728       if (!incremental_option && verbose_option)
1729         WARNOPT (WARN_FILE_UNCHANGED,
1730                  (0, 0, _("%s: file is unchanged; not dumped"),
1731                   quotearg_colon (p)));
1732       return;
1733     }
1734
1735   /* See if we are trying to dump the archive.  */
1736   if (sys_file_is_archive (st))
1737     {
1738       WARNOPT (WARN_IGNORE_ARCHIVE,
1739                (0, 0, _("%s: file is the archive; not dumped"),
1740                 quotearg_colon (p)));
1741       return;
1742     }
1743
1744   is_dir = S_ISDIR (st->stat.st_mode) != 0;
1745
1746   if (!is_dir && dump_hard_link (st))
1747     return;
1748
1749   if (is_dir || S_ISREG (st->stat.st_mode) || S_ISCTG (st->stat.st_mode))
1750     {
1751       bool ok;
1752       struct stat final_stat;
1753
1754       xattrs_acls_get (parentfd, name, st, 0, !is_dir);
1755       xattrs_selinux_get (parentfd, name, st, fd);
1756       xattrs_xattrs_get (parentfd, name, st, fd);
1757
1758       if (is_dir)
1759         {
1760           const char *tag_file_name;
1761           ensure_slash (&st->orig_file_name);
1762           ensure_slash (&st->file_name);
1763
1764           if (check_exclusion_tags (st, &tag_file_name) == exclusion_tag_all)
1765             {
1766               exclusion_tag_warning (st->orig_file_name, tag_file_name,
1767                                      _("directory not dumped"));
1768               return;
1769             }
1770
1771           ok = dump_dir (st);
1772
1773           fd = st->fd;
1774           parentfd = top_level ? chdir_fd : parent->fd;
1775         }
1776       else
1777         {
1778           enum dump_status status;
1779
1780           if (fd && sparse_option && ST_IS_SPARSE (st->stat))
1781             {
1782               status = sparse_dump_file (fd, st);
1783               if (status == dump_status_not_implemented)
1784                 status = dump_regular_file (fd, st);
1785             }
1786           else
1787             status = dump_regular_file (fd, st);
1788
1789           switch (status)
1790             {
1791             case dump_status_ok:
1792             case dump_status_short:
1793               file_count_links (st);
1794               break;
1795
1796             case dump_status_fail:
1797               break;
1798
1799             case dump_status_not_implemented:
1800               abort ();
1801             }
1802
1803           ok = status == dump_status_ok;
1804         }
1805
1806       if (ok)
1807         {
1808           if (fd < 0)
1809             {
1810               errno = - fd;
1811               ok = false;
1812             }
1813           else if (fd == 0)
1814             {
1815               if (parentfd < 0 && ! top_level)
1816                 {
1817                   errno = - parentfd;
1818                   ok = false;
1819                 }
1820               else
1821                 ok = fstatat (parentfd, name, &final_stat, fstatat_flags) == 0;
1822             }
1823           else
1824             ok = fstat (fd, &final_stat) == 0;
1825
1826           if (! ok)
1827             file_removed_diag (p, top_level, stat_diag);
1828         }
1829
1830       if (ok)
1831         {
1832           if ((timespec_cmp (get_stat_ctime (&final_stat), original_ctime) != 0
1833                /* Original ctime will change if the file is a directory and
1834                   --remove-files is given */
1835                && !(remove_files_option && is_dir))
1836               || original_size < final_stat.st_size)
1837             {
1838               WARNOPT (WARN_FILE_CHANGED,
1839                        (0, 0, _("%s: file changed as we read it"),
1840                         quotearg_colon (p)));
1841               set_exit_status (TAREXIT_DIFFERS);
1842             }
1843           else if (atime_preserve_option == replace_atime_preserve
1844                    && fd && (is_dir || original_size != 0)
1845                    && set_file_atime (fd, parentfd, name, st->atime) != 0)
1846             utime_error (p);
1847         }
1848
1849       ok &= tar_stat_close (st);
1850       if (ok && remove_files_option)
1851         queue_deferred_unlink (p, is_dir);
1852
1853       return;
1854     }
1855 #ifdef HAVE_READLINK
1856   else if (S_ISLNK (st->stat.st_mode))
1857     {
1858       st->link_name = areadlinkat_with_size (parentfd, name, st->stat.st_size);
1859       if (!st->link_name)
1860         {
1861           if (errno == ENOMEM)
1862             xalloc_die ();
1863           file_removed_diag (p, top_level, readlink_diag);
1864           return;
1865         }
1866       transform_name (&st->link_name, XFORM_SYMLINK);
1867       if (NAME_FIELD_SIZE - (archive_format == OLDGNU_FORMAT)
1868           < strlen (st->link_name))
1869         write_long_link (st);
1870
1871       xattrs_selinux_get (parentfd, name, st, 0);
1872       xattrs_xattrs_get (parentfd, name, st, 0);
1873
1874       block_ordinal = current_block_ordinal ();
1875       st->stat.st_size = 0;     /* force 0 size on symlink */
1876       header = start_header (st);
1877       if (!header)
1878         return;
1879       tar_copy_str (header->header.linkname, st->link_name, NAME_FIELD_SIZE);
1880       header->header.typeflag = SYMTYPE;
1881       finish_header (st, header, block_ordinal);
1882       /* nothing more to do to it */
1883
1884       if (remove_files_option)
1885         queue_deferred_unlink (p, false);
1886
1887       file_count_links (st);
1888       return;
1889     }
1890 #endif
1891   else if (S_ISCHR (st->stat.st_mode))
1892     {
1893       type = CHRTYPE;
1894       xattrs_acls_get (parentfd, name, st, 0, true);
1895       xattrs_selinux_get (parentfd, name, st, 0);
1896       xattrs_xattrs_get (parentfd, name, st, 0);
1897     }
1898   else if (S_ISBLK (st->stat.st_mode))
1899     {
1900       type = BLKTYPE;
1901       xattrs_acls_get (parentfd, name, st, 0, true);
1902       xattrs_selinux_get (parentfd, name, st, 0);
1903       xattrs_xattrs_get (parentfd, name, st, 0);
1904     }
1905   else if (S_ISFIFO (st->stat.st_mode))
1906     {
1907       type = FIFOTYPE;
1908       xattrs_acls_get (parentfd, name, st, 0, true);
1909       xattrs_selinux_get (parentfd, name, st, 0);
1910       xattrs_xattrs_get (parentfd, name, st, 0);
1911     }
1912   else if (S_ISSOCK (st->stat.st_mode))
1913     {
1914       WARNOPT (WARN_FILE_IGNORED,
1915                (0, 0, _("%s: socket ignored"), quotearg_colon (p)));
1916       return;
1917     }
1918   else if (S_ISDOOR (st->stat.st_mode))
1919     {
1920       WARNOPT (WARN_FILE_IGNORED,
1921                (0, 0, _("%s: door ignored"), quotearg_colon (p)));
1922       return;
1923     }
1924   else
1925     {
1926       unknown_file_error (p);
1927       return;
1928     }
1929
1930   if (archive_format == V7_FORMAT)
1931     {
1932       unknown_file_error (p);
1933       return;
1934     }
1935
1936   block_ordinal = current_block_ordinal ();
1937   st->stat.st_size = 0; /* force 0 size */
1938   header = start_header (st);
1939   if (!header)
1940     return;
1941   header->header.typeflag = type;
1942
1943   if (type != FIFOTYPE)
1944     {
1945       MAJOR_TO_CHARS (major (st->stat.st_rdev),
1946                       header->header.devmajor);
1947       MINOR_TO_CHARS (minor (st->stat.st_rdev),
1948                       header->header.devminor);
1949     }
1950
1951   finish_header (st, header, block_ordinal);
1952   if (remove_files_option)
1953     queue_deferred_unlink (p, false);
1954 }
1955
1956 /* Dump a file, recursively.  PARENT describes the file's parent
1957    directory, NAME is the file's name relative to PARENT, and FULLNAME
1958    its full name, possibly relative to the working directory.  NAME
1959    may contain slashes at the top level of invocation.  */
1960
1961 void
1962 dump_file (struct tar_stat_info *parent, char const *name,
1963            char const *fullname)
1964 {
1965   struct tar_stat_info st;
1966   tar_stat_init (&st);
1967   st.parent = parent;
1968   dump_file0 (&st, name, fullname);
1969   if (parent && listed_incremental_option)
1970     update_parent_directory (parent);
1971   tar_stat_destroy (&st);
1972 }