Debian Codegraph @

src/create.c

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