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