]> Dogcows Code - chaz/tar/blob - src/misc.c
343d5f9ffdf3bf9e84b51c2295e4e92562ba2e6a
[chaz/tar] / src / misc.c
1 /* Miscellaneous functions, not really specific to GNU tar.
2
3 Copyright 1988, 1992, 1994-1997, 1999-2001, 2003-2007, 2009-2010,
4 2012-2013 Free Software Foundation, Inc.
5
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 This program is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
14 Public License for more details.
15
16 You should have received a copy of the GNU General Public License along
17 with this program. If not, see <http://www.gnu.org/licenses/>. */
18
19 #define COMMON_INLINE _GL_EXTERN_INLINE
20 #include <system.h>
21 #include <rmt.h>
22 #include "common.h"
23 #include <quotearg.h>
24 #include <xgetcwd.h>
25 #include <unlinkdir.h>
26 #include <utimens.h>
27
28 #ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
29 # define DOUBLE_SLASH_IS_DISTINCT_ROOT 0
30 #endif
31
32 \f
33 /* Handling strings. */
34
35 /* Assign STRING to a copy of VALUE if not zero, or to zero. If
36 STRING was nonzero, it is freed first. */
37 void
38 assign_string (char **string, const char *value)
39 {
40 free (*string);
41 *string = value ? xstrdup (value) : 0;
42 }
43
44 #if 0
45 /* This function is currently unused; perhaps it should be removed? */
46
47 /* Allocate a copy of the string quoted as in C, and returns that. If
48 the string does not have to be quoted, it returns a null pointer.
49 The allocated copy should normally be freed with free() after the
50 caller is done with it.
51
52 This is used in one context only: generating the directory file in
53 incremental dumps. The quoted string is not intended for human
54 consumption; it is intended only for unquote_string. The quoting
55 is locale-independent, so that users needn't worry about locale
56 when reading directory files. This means that we can't use
57 quotearg, as quotearg is locale-dependent and is meant for human
58 consumption. */
59 static char *
60 quote_copy_string (const char *string)
61 {
62 const char *source = string;
63 char *destination = 0;
64 char *buffer = 0;
65 int copying = 0;
66
67 while (*source)
68 {
69 int character = *source++;
70
71 switch (character)
72 {
73 case '\n': case '\\':
74 if (!copying)
75 {
76 size_t length = (source - string) - 1;
77
78 copying = 1;
79 buffer = xmalloc (length + 2 + 2 * strlen (source) + 1);
80 memcpy (buffer, string, length);
81 destination = buffer + length;
82 }
83 *destination++ = '\\';
84 *destination++ = character == '\\' ? '\\' : 'n';
85 break;
86
87 default:
88 if (copying)
89 *destination++ = character;
90 break;
91 }
92 }
93 if (copying)
94 {
95 *destination = '\0';
96 return buffer;
97 }
98 return 0;
99 }
100 #endif
101
102 /* Takes a quoted C string (like those produced by quote_copy_string)
103 and turns it back into the un-quoted original. This is done in
104 place. Returns 0 only if the string was not properly quoted, but
105 completes the unquoting anyway.
106
107 This is used for reading the saved directory file in incremental
108 dumps. It is used for decoding old 'N' records (demangling names).
109 But also, it is used for decoding file arguments, would they come
110 from the shell or a -T file, and for decoding the --exclude
111 argument. */
112 int
113 unquote_string (char *string)
114 {
115 int result = 1;
116 char *source = string;
117 char *destination = string;
118
119 /* Escape sequences other than \\ and \n are no longer generated by
120 quote_copy_string, but accept them for backwards compatibility,
121 and also because unquote_string is used for purposes other than
122 parsing the output of quote_copy_string. */
123
124 while (*source)
125 if (*source == '\\')
126 switch (*++source)
127 {
128 case '\\':
129 *destination++ = '\\';
130 source++;
131 break;
132
133 case 'a':
134 *destination++ = '\a';
135 source++;
136 break;
137
138 case 'b':
139 *destination++ = '\b';
140 source++;
141 break;
142
143 case 'f':
144 *destination++ = '\f';
145 source++;
146 break;
147
148 case 'n':
149 *destination++ = '\n';
150 source++;
151 break;
152
153 case 'r':
154 *destination++ = '\r';
155 source++;
156 break;
157
158 case 't':
159 *destination++ = '\t';
160 source++;
161 break;
162
163 case 'v':
164 *destination++ = '\v';
165 source++;
166 break;
167
168 case '?':
169 *destination++ = 0177;
170 source++;
171 break;
172
173 case '0':
174 case '1':
175 case '2':
176 case '3':
177 case '4':
178 case '5':
179 case '6':
180 case '7':
181 {
182 int value = *source++ - '0';
183
184 if (*source < '0' || *source > '7')
185 {
186 *destination++ = value;
187 break;
188 }
189 value = value * 8 + *source++ - '0';
190 if (*source < '0' || *source > '7')
191 {
192 *destination++ = value;
193 break;
194 }
195 value = value * 8 + *source++ - '0';
196 *destination++ = value;
197 break;
198 }
199
200 default:
201 result = 0;
202 *destination++ = '\\';
203 if (*source)
204 *destination++ = *source++;
205 break;
206 }
207 else if (source != destination)
208 *destination++ = *source++;
209 else
210 source++, destination++;
211
212 if (source != destination)
213 *destination = '\0';
214 return result;
215 }
216
217 /* Zap trailing slashes. */
218 char *
219 zap_slashes (char *name)
220 {
221 char *q;
222
223 if (!name || *name == 0)
224 return name;
225 q = name + strlen (name) - 1;
226 while (q > name && ISSLASH (*q))
227 *q-- = '\0';
228 return name;
229 }
230
231 /* Normalize FILE_NAME by removing redundant slashes and "."
232 components, including redundant trailing slashes.
233 Leave ".." alone, as it may be significant in the presence
234 of symlinks and on platforms where "/.." != "/".
235
236 Destructive version: modifies its argument. */
237 void
238 normalize_filename_x (char *file_name)
239 {
240 char *name = file_name + FILE_SYSTEM_PREFIX_LEN (file_name);
241 char *p;
242 char const *q;
243 char c;
244
245 /* Don't squeeze leading "//" to "/", on hosts where they're distinct. */
246 name += (DOUBLE_SLASH_IS_DISTINCT_ROOT
247 && ISSLASH (*name) && ISSLASH (name[1]) && ! ISSLASH (name[2]));
248
249 /* Omit redundant leading "." components. */
250 for (q = p = name; (*p = *q) == '.' && ISSLASH (q[1]); p += !*q)
251 for (q += 2; ISSLASH (*q); q++)
252 continue;
253
254 /* Copy components from Q to P, omitting redundant slashes and
255 internal "." components. */
256 while ((*p++ = c = *q++) != '\0')
257 if (ISSLASH (c))
258 while (ISSLASH (q[*q == '.']))
259 q += (*q == '.') + 1;
260
261 /* Omit redundant trailing "." component and slash. */
262 if (2 < p - name)
263 {
264 p -= p[-2] == '.' && ISSLASH (p[-3]);
265 p -= 2 < p - name && ISSLASH (p[-2]);
266 p[-1] = '\0';
267 }
268 }
269
270 /* Normalize NAME by removing redundant slashes and "." components,
271 including redundant trailing slashes.
272
273 Return a normalized newly-allocated copy. */
274
275 char *
276 normalize_filename (const char *name)
277 {
278 char *copy = NULL;
279
280 if (IS_RELATIVE_FILE_NAME (name))
281 {
282 /* Set COPY to the absolute file name if possible.
283
284 FIXME: There should be no need to get the absolute file name.
285 getcwd is slow, it might fail, and it does not necessarily
286 return a canonical name even when it succeeds. Perhaps we
287 can use dev+ino pairs instead of names? */
288 const char *cwd = tar_getcwd ();
289 size_t copylen;
290 bool need_separator;
291
292 copylen = strlen (cwd);
293 need_separator = ! (DOUBLE_SLASH_IS_DISTINCT_ROOT
294 && copylen == 2 && ISSLASH (cwd[1]));
295 copy = xmalloc (copylen + need_separator + strlen (name) + 1);
296 strcpy (copy, cwd);
297 copy[copylen] = DIRECTORY_SEPARATOR;
298 strcpy (copy + copylen + need_separator, name);
299 }
300
301 if (!copy)
302 copy = xstrdup (name);
303 normalize_filename_x (copy);
304 return copy;
305 }
306
307 \f
308 void
309 replace_prefix (char **pname, const char *samp, size_t slen,
310 const char *repl, size_t rlen)
311 {
312 char *name = *pname;
313 size_t nlen = strlen (name);
314 if (nlen > slen && memcmp (name, samp, slen) == 0 && ISSLASH (name[slen]))
315 {
316 if (rlen > slen)
317 {
318 name = xrealloc (name, nlen - slen + rlen + 1);
319 *pname = name;
320 }
321 memmove (name + rlen, name + slen, nlen - slen + 1);
322 memcpy (name, repl, rlen);
323 }
324 }
325
326 \f
327 /* Handling numbers. */
328
329 /* Convert VALUE, which is converted from a system integer type whose
330 minimum value is MINVAL and maximum MINVAL, to an decimal
331 integer string. Use the storage in BUF and return a pointer to the
332 converted string. If VALUE is converted from a negative integer in
333 the range MINVAL .. -1, represent it with a string representation
334 of the negative integer, using leading '-'. */
335 #if ! (INTMAX_MAX <= UINTMAX_MAX / 2)
336 # error "sysinttostr: uintmax_t cannot represent all intmax_t values"
337 #endif
338 char *
339 sysinttostr (uintmax_t value, intmax_t minval, uintmax_t maxval,
340 char buf[SYSINT_BUFSIZE])
341 {
342 if (value <= maxval)
343 return umaxtostr (value, buf);
344 else
345 {
346 intmax_t i = value - minval;
347 return imaxtostr (i + minval, buf);
348 }
349 }
350
351 /* Convert a prefix of the string ARG to a system integer type whose
352 minimum value is MINVAL and maximum MAXVAL. If MINVAL is negative,
353 negative integers MINVAL .. -1 are assumed to be represented using
354 leading '-' in the usual way. If the represented value exceeds
355 INTMAX_MAX, return a negative integer V such that (uintmax_t) V
356 yields the represented value. If ARGLIM is nonnull, store into
357 *ARGLIM a pointer to the first character after the prefix.
358
359 This is the inverse of sysinttostr.
360
361 On a normal return, set errno = 0.
362 On conversion error, return 0 and set errno = EINVAL.
363 On overflow, return an extreme value and set errno = ERANGE. */
364 #if ! (INTMAX_MAX <= UINTMAX_MAX)
365 # error "strtosysint: nonnegative intmax_t does not fit in uintmax_t"
366 #endif
367 intmax_t
368 strtosysint (char const *arg, char **arglim, intmax_t minval, uintmax_t maxval)
369 {
370 errno = 0;
371 if (maxval <= INTMAX_MAX)
372 {
373 if (ISDIGIT (arg[*arg == '-']))
374 {
375 intmax_t i = strtoimax (arg, arglim, 10);
376 intmax_t imaxval = maxval;
377 if (minval <= i && i <= imaxval)
378 return i;
379 errno = ERANGE;
380 return i < minval ? minval : maxval;
381 }
382 }
383 else
384 {
385 if (ISDIGIT (*arg))
386 {
387 uintmax_t i = strtoumax (arg, arglim, 10);
388 if (i <= maxval)
389 return represent_uintmax (i);
390 errno = ERANGE;
391 return maxval;
392 }
393 }
394
395 errno = EINVAL;
396 return 0;
397 }
398
399 /* Output fraction and trailing digits appropriate for a nanoseconds
400 count equal to NS, but don't output unnecessary '.' or trailing
401 zeros. */
402
403 void
404 code_ns_fraction (int ns, char *p)
405 {
406 if (ns == 0)
407 *p = '\0';
408 else
409 {
410 int i = 9;
411 *p++ = '.';
412
413 while (ns % 10 == 0)
414 {
415 ns /= 10;
416 i--;
417 }
418
419 p[i] = '\0';
420
421 for (;;)
422 {
423 p[--i] = '0' + ns % 10;
424 if (i == 0)
425 break;
426 ns /= 10;
427 }
428 }
429 }
430
431 char const *
432 code_timespec (struct timespec t, char sbuf[TIMESPEC_STRSIZE_BOUND])
433 {
434 time_t s = t.tv_sec;
435 int ns = t.tv_nsec;
436 char *np;
437 bool negative = s < 0;
438
439 /* ignore invalid values of ns */
440 if (BILLION <= ns || ns < 0)
441 ns = 0;
442
443 if (negative && ns != 0)
444 {
445 s++;
446 ns = BILLION - ns;
447 }
448
449 np = umaxtostr (negative ? - (uintmax_t) s : (uintmax_t) s, sbuf + 1);
450 if (negative)
451 *--np = '-';
452 code_ns_fraction (ns, sbuf + UINTMAX_STRSIZE_BOUND);
453 return np;
454 }
455
456 struct timespec
457 decode_timespec (char const *arg, char **arg_lim, bool parse_fraction)
458 {
459 time_t s = TYPE_MINIMUM (time_t);
460 int ns = -1;
461 char const *p = arg;
462 bool negative = *arg == '-';
463 struct timespec r;
464
465 if (! ISDIGIT (arg[negative]))
466 errno = EINVAL;
467 else
468 {
469 errno = 0;
470
471 if (negative)
472 {
473 intmax_t i = strtoimax (arg, arg_lim, 10);
474 if (TYPE_SIGNED (time_t) ? TYPE_MINIMUM (time_t) <= i : 0 <= i)
475 s = i;
476 else
477 errno = ERANGE;
478 }
479 else
480 {
481 uintmax_t i = strtoumax (arg, arg_lim, 10);
482 if (i <= TYPE_MAXIMUM (time_t))
483 s = i;
484 else
485 errno = ERANGE;
486 }
487
488 p = *arg_lim;
489 ns = 0;
490
491 if (parse_fraction && *p == '.')
492 {
493 int digits = 0;
494 bool trailing_nonzero = false;
495
496 while (ISDIGIT (*++p))
497 if (digits < LOG10_BILLION)
498 digits++, ns = 10 * ns + (*p - '0');
499 else
500 trailing_nonzero |= *p != '0';
501
502 while (digits < LOG10_BILLION)
503 digits++, ns *= 10;
504
505 if (negative)
506 {
507 /* Convert "-1.10000000000001" to s == -2, ns == 89999999.
508 I.e., truncate time stamps towards minus infinity while
509 converting them to internal form. */
510 ns += trailing_nonzero;
511 if (ns != 0)
512 {
513 if (s == TYPE_MINIMUM (time_t))
514 ns = -1;
515 else
516 {
517 s--;
518 ns = BILLION - ns;
519 }
520 }
521 }
522 }
523
524 if (errno == ERANGE)
525 ns = -1;
526 }
527
528 *arg_lim = (char *) p;
529 r.tv_sec = s;
530 r.tv_nsec = ns;
531 return r;
532 }
533 \f
534 /* File handling. */
535
536 /* Saved names in case backup needs to be undone. */
537 static char *before_backup_name;
538 static char *after_backup_name;
539
540 /* Return 1 if FILE_NAME is obviously "." or "/". */
541 bool
542 must_be_dot_or_slash (char const *file_name)
543 {
544 file_name += FILE_SYSTEM_PREFIX_LEN (file_name);
545
546 if (ISSLASH (file_name[0]))
547 {
548 for (;;)
549 if (ISSLASH (file_name[1]))
550 file_name++;
551 else if (file_name[1] == '.'
552 && ISSLASH (file_name[2 + (file_name[2] == '.')]))
553 file_name += 2 + (file_name[2] == '.');
554 else
555 return ! file_name[1];
556 }
557 else
558 {
559 while (file_name[0] == '.' && ISSLASH (file_name[1]))
560 {
561 file_name += 2;
562 while (ISSLASH (*file_name))
563 file_name++;
564 }
565
566 return ! file_name[0] || (file_name[0] == '.' && ! file_name[1]);
567 }
568 }
569
570 /* Some implementations of rmdir let you remove '.' or '/'.
571 Report an error with errno set to zero for obvious cases of this;
572 otherwise call rmdir. */
573 static int
574 safer_rmdir (const char *file_name)
575 {
576 if (must_be_dot_or_slash (file_name))
577 {
578 errno = 0;
579 return -1;
580 }
581
582 return unlinkat (chdir_fd, file_name, AT_REMOVEDIR);
583 }
584
585 /* Remove FILE_NAME, returning 1 on success. If FILE_NAME is a directory,
586 then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
587 recursively; otherwise, remove it only if it is empty. If FILE_NAME is
588 a directory that cannot be removed (e.g., because it is nonempty)
589 and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
590 Return 0 on error, with errno set; if FILE_NAME is obviously the working
591 directory return zero with errno set to zero. */
592 int
593 remove_any_file (const char *file_name, enum remove_option option)
594 {
595 /* Try unlink first if we cannot unlink directories, as this saves
596 us a system call in the common case where we're removing a
597 non-directory. */
598 bool try_unlink_first = cannot_unlink_dir ();
599
600 if (try_unlink_first)
601 {
602 if (unlinkat (chdir_fd, file_name, 0) == 0)
603 return 1;
604
605 /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
606 directory without appropriate privileges, but many Linux
607 kernels return the more-sensible EISDIR. */
608 if (errno != EPERM && errno != EISDIR)
609 return 0;
610 }
611
612 if (safer_rmdir (file_name) == 0)
613 return 1;
614
615 switch (errno)
616 {
617 case ENOTDIR:
618 return !try_unlink_first && unlinkat (chdir_fd, file_name, 0) == 0;
619
620 case 0:
621 case EEXIST:
622 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
623 case ENOTEMPTY:
624 #endif
625 switch (option)
626 {
627 case ORDINARY_REMOVE_OPTION:
628 break;
629
630 case WANT_DIRECTORY_REMOVE_OPTION:
631 return -1;
632
633 case RECURSIVE_REMOVE_OPTION:
634 {
635 char *directory = tar_savedir (file_name, 0);
636 char const *entry;
637 size_t entrylen;
638
639 if (! directory)
640 return 0;
641
642 for (entry = directory;
643 (entrylen = strlen (entry)) != 0;
644 entry += entrylen + 1)
645 {
646 char *file_name_buffer = new_name (file_name, entry);
647 int r = remove_any_file (file_name_buffer,
648 RECURSIVE_REMOVE_OPTION);
649 int e = errno;
650 free (file_name_buffer);
651
652 if (! r)
653 {
654 free (directory);
655 errno = e;
656 return 0;
657 }
658 }
659
660 free (directory);
661 return safer_rmdir (file_name) == 0;
662 }
663 }
664 break;
665 }
666
667 return 0;
668 }
669
670 /* Check if FILE_NAME already exists and make a backup of it right now.
671 Return success (nonzero) only if the backup is either unneeded, or
672 successful. For now, directories are considered to never need
673 backup. If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
674 so, we do not have to backup block or character devices, nor remote
675 entities. */
676 bool
677 maybe_backup_file (const char *file_name, bool this_is_the_archive)
678 {
679 struct stat file_stat;
680
681 assign_string (&before_backup_name, file_name);
682
683 /* A run situation may exist between Emacs or other GNU programs trying to
684 make a backup for the same file simultaneously. If theoretically
685 possible, real problems are unlikely. Doing any better would require a
686 convention, GNU-wide, for all programs doing backups. */
687
688 assign_string (&after_backup_name, 0);
689
690 /* Check if we really need to backup the file. */
691
692 if (this_is_the_archive && _remdev (file_name))
693 return true;
694
695 if (deref_stat (file_name, &file_stat) != 0)
696 {
697 if (errno == ENOENT)
698 return true;
699
700 stat_error (file_name);
701 return false;
702 }
703
704 if (S_ISDIR (file_stat.st_mode))
705 return true;
706
707 if (this_is_the_archive
708 && (S_ISBLK (file_stat.st_mode) || S_ISCHR (file_stat.st_mode)))
709 return true;
710
711 after_backup_name = find_backup_file_name (file_name, backup_type);
712 if (! after_backup_name)
713 xalloc_die ();
714
715 if (renameat (chdir_fd, before_backup_name, chdir_fd, after_backup_name)
716 == 0)
717 {
718 if (verbose_option)
719 fprintf (stdlis, _("Renaming %s to %s\n"),
720 quote_n (0, before_backup_name),
721 quote_n (1, after_backup_name));
722 return true;
723 }
724 else
725 {
726 /* The backup operation failed. */
727 int e = errno;
728 ERROR ((0, e, _("%s: Cannot rename to %s"),
729 quotearg_colon (before_backup_name),
730 quote_n (1, after_backup_name)));
731 assign_string (&after_backup_name, 0);
732 return false;
733 }
734 }
735
736 /* Try to restore the recently backed up file to its original name.
737 This is usually only needed after a failed extraction. */
738 void
739 undo_last_backup (void)
740 {
741 if (after_backup_name)
742 {
743 if (renameat (chdir_fd, after_backup_name, chdir_fd, before_backup_name)
744 != 0)
745 {
746 int e = errno;
747 ERROR ((0, e, _("%s: Cannot rename to %s"),
748 quotearg_colon (after_backup_name),
749 quote_n (1, before_backup_name)));
750 }
751 if (verbose_option)
752 fprintf (stdlis, _("Renaming %s back to %s\n"),
753 quote_n (0, after_backup_name),
754 quote_n (1, before_backup_name));
755 assign_string (&after_backup_name, 0);
756 }
757 }
758
759 /* Apply either stat or lstat to (NAME, BUF), depending on the
760 presence of the --dereference option. NAME is relative to the
761 most-recent argument to chdir_do. */
762 int
763 deref_stat (char const *name, struct stat *buf)
764 {
765 return fstatat (chdir_fd, name, buf, fstatat_flags);
766 }
767
768 /* Read from FD into the buffer BUF with COUNT bytes. Attempt to fill
769 BUF. Wait until input is available; this matters because files are
770 opened O_NONBLOCK for security reasons, and on some file systems
771 this can cause read to fail with errno == EAGAIN. Return the
772 actual number of bytes read, zero for EOF, or
773 SAFE_READ_ERROR upon error. */
774 size_t
775 blocking_read (int fd, void *buf, size_t count)
776 {
777 size_t bytes = safe_read (fd, buf, count);
778
779 #if defined F_SETFL && O_NONBLOCK
780 if (bytes == SAFE_READ_ERROR && errno == EAGAIN)
781 {
782 int flags = fcntl (fd, F_GETFL);
783 if (0 <= flags && flags & O_NONBLOCK
784 && fcntl (fd, F_SETFL, flags & ~O_NONBLOCK) != -1)
785 bytes = safe_read (fd, buf, count);
786 }
787 #endif
788
789 return bytes;
790 }
791
792 /* Write to FD from the buffer BUF with COUNT bytes. Do a full write.
793 Wait until an output buffer is available; this matters because
794 files are opened O_NONBLOCK for security reasons, and on some file
795 systems this can cause write to fail with errno == EAGAIN. Return
796 the actual number of bytes written, setting errno if that is less
797 than COUNT. */
798 size_t
799 blocking_write (int fd, void const *buf, size_t count)
800 {
801 size_t bytes = full_write (fd, buf, count);
802
803 #if defined F_SETFL && O_NONBLOCK
804 if (bytes < count && errno == EAGAIN)
805 {
806 int flags = fcntl (fd, F_GETFL);
807 if (0 <= flags && flags & O_NONBLOCK
808 && fcntl (fd, F_SETFL, flags & ~O_NONBLOCK) != -1)
809 {
810 char const *buffer = buf;
811 bytes += full_write (fd, buffer + bytes, count - bytes);
812 }
813 }
814 #endif
815
816 return bytes;
817 }
818
819 /* Set FD's (i.e., assuming the working directory is PARENTFD, FILE's)
820 access time to ATIME. */
821 int
822 set_file_atime (int fd, int parentfd, char const *file, struct timespec atime)
823 {
824 struct timespec ts[2];
825 ts[0] = atime;
826 ts[1].tv_nsec = UTIME_OMIT;
827 return fdutimensat (fd, parentfd, file, ts, fstatat_flags);
828 }
829
830 /* A description of a working directory. */
831 struct wd
832 {
833 /* The directory's name. */
834 char const *name;
835 /* Current working directory; initialized by tar_getcwd */
836 char *cwd;
837 /* If nonzero, the file descriptor of the directory, or AT_FDCWD if
838 the working directory. If zero, the directory needs to be opened
839 to be used. */
840 int fd;
841 };
842
843 /* A vector of chdir targets. wd[0] is the initial working directory. */
844 static struct wd *wd;
845
846 /* The number of working directories in the vector. */
847 static size_t wd_count;
848
849 /* The allocated size of the vector. */
850 static size_t wd_alloc;
851
852 /* The maximum number of chdir targets with open directories.
853 Don't make it too large, as many operating systems have a small
854 limit on the number of open file descriptors. Also, the current
855 implementation does not scale well. */
856 enum { CHDIR_CACHE_SIZE = 16 };
857
858 /* Indexes into WD of chdir targets with open file descriptors, sorted
859 most-recently used first. Zero indexes are unused. */
860 static int wdcache[CHDIR_CACHE_SIZE];
861
862 /* Number of nonzero entries in WDCACHE. */
863 static size_t wdcache_count;
864
865 int
866 chdir_count (void)
867 {
868 if (wd_count == 0)
869 return wd_count;
870 return wd_count - 1;
871 }
872
873 /* DIR is the operand of a -C option; add it to vector of chdir targets,
874 and return the index of its location. */
875 int
876 chdir_arg (char const *dir)
877 {
878 if (wd_count == wd_alloc)
879 {
880 if (wd_alloc == 0)
881 {
882 wd_alloc = 2;
883 wd = xmalloc (sizeof *wd * wd_alloc);
884 }
885 else
886 wd = x2nrealloc (wd, &wd_alloc, sizeof *wd);
887
888 if (! wd_count)
889 {
890 wd[wd_count].name = ".";
891 wd[wd_count].cwd = NULL;
892 wd[wd_count].fd = AT_FDCWD;
893 wd_count++;
894 }
895 }
896
897 /* Optimize the common special case of the working directory,
898 or the working directory as a prefix. */
899 if (dir[0])
900 {
901 while (dir[0] == '.' && ISSLASH (dir[1]))
902 for (dir += 2; ISSLASH (*dir); dir++)
903 continue;
904 if (! dir[dir[0] == '.'])
905 return wd_count - 1;
906 }
907
908 wd[wd_count].name = dir;
909 wd[wd_count].cwd = NULL;
910 wd[wd_count].fd = 0;
911 return wd_count++;
912 }
913
914 /* Index of current directory. */
915 int chdir_current;
916
917 /* Value suitable for use as the first argument to openat, and in
918 similar locations for fstatat, etc. This is an open file
919 descriptor, or AT_FDCWD if the working directory is current. It is
920 valid until the next invocation of chdir_do. */
921 int chdir_fd = AT_FDCWD;
922
923 /* Change to directory I, in a virtual way. This does not actually
924 invoke chdir; it merely sets chdir_fd to an int suitable as the
925 first argument for openat, etc. If I is 0, change to the initial
926 working directory; otherwise, I must be a value returned by
927 chdir_arg. */
928 void
929 chdir_do (int i)
930 {
931 if (chdir_current != i)
932 {
933 struct wd *curr = &wd[i];
934 int fd = curr->fd;
935
936 if (! fd)
937 {
938 if (! IS_ABSOLUTE_FILE_NAME (curr->name))
939 chdir_do (i - 1);
940 fd = openat (chdir_fd, curr->name,
941 open_searchdir_flags & ~ O_NOFOLLOW);
942 if (fd < 0)
943 open_fatal (curr->name);
944
945 curr->fd = fd;
946
947 /* Add I to the cache, tossing out the lowest-ranking entry if the
948 cache is full. */
949 if (wdcache_count < CHDIR_CACHE_SIZE)
950 wdcache[wdcache_count++] = i;
951 else
952 {
953 struct wd *stale = &wd[wdcache[CHDIR_CACHE_SIZE - 1]];
954 if (close (stale->fd) != 0)
955 close_diag (stale->name);
956 stale->fd = 0;
957 wdcache[CHDIR_CACHE_SIZE - 1] = i;
958 }
959 }
960
961 if (0 < fd)
962 {
963 /* Move the i value to the front of the cache. This is
964 O(CHDIR_CACHE_SIZE), but the cache is small. */
965 size_t ci;
966 int prev = wdcache[0];
967 for (ci = 1; prev != i; ci++)
968 {
969 int cur = wdcache[ci];
970 wdcache[ci] = prev;
971 if (cur == i)
972 break;
973 prev = cur;
974 }
975 wdcache[0] = i;
976 }
977
978 chdir_current = i;
979 chdir_fd = fd;
980 }
981 }
982 \f
983 const char *
984 tar_dirname (void)
985 {
986 return wd[chdir_current].name;
987 }
988
989 const char *
990 tar_getcwd (void)
991 {
992 static char *cwd;
993 namebuf_t nbuf;
994 int i;
995
996 if (!cwd)
997 cwd = xgetcwd ();
998 if (!wd)
999 return cwd;
1000
1001 if (0 == chdir_current || !wd[chdir_current].cwd)
1002 {
1003 if (IS_ABSOLUTE_FILE_NAME (wd[chdir_current].name))
1004 {
1005 wd[chdir_current].cwd = xstrdup (wd[chdir_current].name);
1006 return wd[chdir_current].cwd;
1007 }
1008 if (!wd[0].cwd)
1009 wd[0].cwd = cwd;
1010
1011 for (i = chdir_current - 1; i > 0; i--)
1012 if (wd[i].cwd)
1013 break;
1014
1015 nbuf = namebuf_create (wd[i].cwd);
1016 for (i++; i <= chdir_current; i++)
1017 namebuf_add_dir (nbuf, wd[i].name);
1018 wd[chdir_current].cwd = namebuf_finish (nbuf);
1019 }
1020 return wd[chdir_current].cwd;
1021 }
1022 \f
1023 void
1024 close_diag (char const *name)
1025 {
1026 if (ignore_failed_read_option)
1027 close_warn (name);
1028 else
1029 close_error (name);
1030 }
1031
1032 void
1033 open_diag (char const *name)
1034 {
1035 if (ignore_failed_read_option)
1036 open_warn (name);
1037 else
1038 open_error (name);
1039 }
1040
1041 void
1042 read_diag_details (char const *name, off_t offset, size_t size)
1043 {
1044 if (ignore_failed_read_option)
1045 read_warn_details (name, offset, size);
1046 else
1047 read_error_details (name, offset, size);
1048 }
1049
1050 void
1051 readlink_diag (char const *name)
1052 {
1053 if (ignore_failed_read_option)
1054 readlink_warn (name);
1055 else
1056 readlink_error (name);
1057 }
1058
1059 void
1060 savedir_diag (char const *name)
1061 {
1062 if (ignore_failed_read_option)
1063 savedir_warn (name);
1064 else
1065 savedir_error (name);
1066 }
1067
1068 void
1069 seek_diag_details (char const *name, off_t offset)
1070 {
1071 if (ignore_failed_read_option)
1072 seek_warn_details (name, offset);
1073 else
1074 seek_error_details (name, offset);
1075 }
1076
1077 void
1078 stat_diag (char const *name)
1079 {
1080 if (ignore_failed_read_option)
1081 stat_warn (name);
1082 else
1083 stat_error (name);
1084 }
1085
1086 void
1087 file_removed_diag (const char *name, bool top_level,
1088 void (*diagfn) (char const *name))
1089 {
1090 if (!top_level && errno == ENOENT)
1091 {
1092 WARNOPT (WARN_FILE_REMOVED,
1093 (0, 0, _("%s: File removed before we read it"),
1094 quotearg_colon (name)));
1095 set_exit_status (TAREXIT_DIFFERS);
1096 }
1097 else
1098 diagfn (name);
1099 }
1100
1101 void
1102 write_fatal_details (char const *name, ssize_t status, size_t size)
1103 {
1104 write_error_details (name, status, size);
1105 fatal_exit ();
1106 }
1107
1108 /* Fork, aborting if unsuccessful. */
1109 pid_t
1110 xfork (void)
1111 {
1112 pid_t p = fork ();
1113 if (p == (pid_t) -1)
1114 call_arg_fatal ("fork", _("child process"));
1115 return p;
1116 }
1117
1118 /* Create a pipe, aborting if unsuccessful. */
1119 void
1120 xpipe (int fd[2])
1121 {
1122 if (pipe (fd) < 0)
1123 call_arg_fatal ("pipe", _("interprocess channel"));
1124 }
1125
1126 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
1127 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
1128 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
1129 locations. */
1130
1131 static inline void *
1132 ptr_align (void *ptr, size_t alignment)
1133 {
1134 char *p0 = ptr;
1135 char *p1 = p0 + alignment - 1;
1136 return p1 - (size_t) p1 % alignment;
1137 }
1138
1139 /* Return the address of a page-aligned buffer of at least SIZE bytes.
1140 The caller should free *PTR when done with the buffer. */
1141
1142 void *
1143 page_aligned_alloc (void **ptr, size_t size)
1144 {
1145 size_t alignment = getpagesize ();
1146 size_t size1 = size + alignment;
1147 if (size1 < size)
1148 xalloc_die ();
1149 *ptr = xmalloc (size1);
1150 return ptr_align (*ptr, alignment);
1151 }
1152
1153 \f
1154
1155 struct namebuf
1156 {
1157 char *buffer; /* directory, '/', and directory member */
1158 size_t buffer_size; /* allocated size of name_buffer */
1159 size_t dir_length; /* length of directory part in buffer */
1160 };
1161
1162 namebuf_t
1163 namebuf_create (const char *dir)
1164 {
1165 namebuf_t buf = xmalloc (sizeof (*buf));
1166 buf->buffer_size = strlen (dir) + 2;
1167 buf->buffer = xmalloc (buf->buffer_size);
1168 strcpy (buf->buffer, dir);
1169 buf->dir_length = strlen (buf->buffer);
1170 if (!ISSLASH (buf->buffer[buf->dir_length - 1]))
1171 buf->buffer[buf->dir_length++] = DIRECTORY_SEPARATOR;
1172 return buf;
1173 }
1174
1175 void
1176 namebuf_free (namebuf_t buf)
1177 {
1178 free (buf->buffer);
1179 free (buf);
1180 }
1181
1182 char *
1183 namebuf_name (namebuf_t buf, const char *name)
1184 {
1185 size_t len = strlen (name);
1186 while (buf->dir_length + len + 1 >= buf->buffer_size)
1187 buf->buffer = x2realloc (buf->buffer, &buf->buffer_size);
1188 strcpy (buf->buffer + buf->dir_length, name);
1189 return buf->buffer;
1190 }
1191
1192 void
1193 namebuf_add_dir (namebuf_t buf, const char *name)
1194 {
1195 static char dirsep[] = { DIRECTORY_SEPARATOR, 0 };
1196 if (!ISSLASH (buf->buffer[buf->dir_length - 1]))
1197 {
1198 namebuf_name (buf, dirsep);
1199 buf->dir_length++;
1200 }
1201 namebuf_name (buf, name);
1202 buf->dir_length += strlen (name);
1203 }
1204
1205 char *
1206 namebuf_finish (namebuf_t buf)
1207 {
1208 char *res = buf->buffer;
1209
1210 if (ISSLASH (buf->buffer[buf->dir_length - 1]))
1211 buf->buffer[buf->dir_length] = 0;
1212 free (buf);
1213 return res;
1214 }
1215
1216 /* Return the filenames in directory NAME, relative to the chdir_fd.
1217 If the directory does not exist, report error if MUST_EXIST is
1218 true.
1219
1220 Return NULL on errors.
1221 */
1222 char *
1223 tar_savedir (const char *name, int must_exist)
1224 {
1225 char *ret = NULL;
1226 DIR *dir = NULL;
1227 int fd = openat (chdir_fd, name, open_read_flags | O_DIRECTORY);
1228 if (fd < 0)
1229 {
1230 if (!must_exist && errno == ENOENT)
1231 return NULL;
1232 open_error (name);
1233 }
1234 else if (! ((dir = fdopendir (fd))
1235 && (ret = streamsavedir (dir))))
1236 savedir_error (name);
1237
1238 if (dir ? closedir (dir) != 0 : 0 <= fd && close (fd) != 0)
1239 savedir_error (name);
1240
1241 return ret;
1242 }
This page took 0.086122 seconds and 3 git commands to generate.