Debian Codegraph @

src/create.c

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