Debian Codegraph @

src/create.c

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