]> Dogcows Code - chaz/tar/blob - src/misc.c
Revamp initial name collection functions to ensure proper argument ordering.
[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. Leave ".."
233 alone, as it may be significant in the presence of symlinks and on
234 platforms where "/.." != "/". Destructive version: modifies its
235 argument. */
236 static void
237 normalize_filename_x (char *file_name)
238 {
239 char *name = file_name + FILE_SYSTEM_PREFIX_LEN (file_name);
240 char *p;
241 char const *q;
242 char c;
243
244 /* Don't squeeze leading "//" to "/", on hosts where they're distinct. */
245 name += (DOUBLE_SLASH_IS_DISTINCT_ROOT
246 && ISSLASH (*name) && ISSLASH (name[1]) && ! ISSLASH (name[2]));
247
248 /* Omit redundant leading "." components. */
249 for (q = p = name; (*p = *q) == '.' && ISSLASH (q[1]); p += !*q)
250 for (q += 2; ISSLASH (*q); q++)
251 continue;
252
253 /* Copy components from Q to P, omitting redundant slashes and
254 internal "." components. */
255 while ((*p++ = c = *q++) != '\0')
256 if (ISSLASH (c))
257 while (ISSLASH (q[*q == '.']))
258 q += (*q == '.') + 1;
259
260 /* Omit redundant trailing "." component and slash. */
261 if (2 < p - name)
262 {
263 p -= p[-2] == '.' && ISSLASH (p[-3]);
264 p -= 2 < p - name && ISSLASH (p[-2]);
265 p[-1] = '\0';
266 }
267 }
268
269 /* Normalize NAME by removing redundant slashes and "." components,
270 including redundant trailing slashes. Return a normalized
271 newly-allocated copy. */
272
273 char *
274 normalize_filename (const char *name)
275 {
276 char *copy = NULL;
277
278 if (IS_RELATIVE_FILE_NAME (name))
279 {
280 /* Set COPY to the absolute file name if possible.
281
282 FIXME: There should be no need to get the absolute file name.
283 getcwd is slow, it might fail, and it does not necessarily
284 return a canonical name even when it succeeds. Perhaps we
285 can use dev+ino pairs instead of names? */
286 copy = xgetcwd ();
287 if (copy)
288 {
289 size_t copylen = strlen (copy);
290 bool need_separator = ! (DOUBLE_SLASH_IS_DISTINCT_ROOT
291 && copylen == 2 && ISSLASH (copy[1]));
292 copy = xrealloc (copy, copylen + need_separator + strlen (name) + 1);
293 copy[copylen] = DIRECTORY_SEPARATOR;
294 strcpy (copy + copylen + need_separator, name);
295 }
296 else
297 WARN ((0, errno, _("Cannot get working directory")));
298 }
299
300 if (! copy)
301 copy = xstrdup (name);
302 normalize_filename_x (copy);
303 return copy;
304 }
305
306 \f
307 void
308 replace_prefix (char **pname, const char *samp, size_t slen,
309 const char *repl, size_t rlen)
310 {
311 char *name = *pname;
312 size_t nlen = strlen (name);
313 if (nlen > slen && memcmp (name, samp, slen) == 0 && ISSLASH (name[slen]))
314 {
315 if (rlen > slen)
316 {
317 name = xrealloc (name, nlen - slen + rlen + 1);
318 *pname = name;
319 }
320 memmove (name + rlen, name + slen, nlen - slen + 1);
321 memcpy (name, repl, rlen);
322 }
323 }
324
325 \f
326 /* Handling numbers. */
327
328 /* Convert VALUE, which is converted from a system integer type whose
329 minimum value is MINVAL and maximum MINVAL, to an decimal
330 integer string. Use the storage in BUF and return a pointer to the
331 converted string. If VALUE is converted from a negative integer in
332 the range MINVAL .. -1, represent it with a string representation
333 of the negative integer, using leading '-'. */
334 #if ! (INTMAX_MAX <= UINTMAX_MAX / 2)
335 # error "sysinttostr: uintmax_t cannot represent all intmax_t values"
336 #endif
337 char *
338 sysinttostr (uintmax_t value, intmax_t minval, uintmax_t maxval,
339 char buf[SYSINT_BUFSIZE])
340 {
341 if (value <= maxval)
342 return umaxtostr (value, buf);
343 else
344 {
345 intmax_t i = value - minval;
346 return imaxtostr (i + minval, buf);
347 }
348 }
349
350 /* Convert a prefix of the string ARG to a system integer type whose
351 minimum value is MINVAL and maximum MAXVAL. If MINVAL is negative,
352 negative integers MINVAL .. -1 are assumed to be represented using
353 leading '-' in the usual way. If the represented value exceeds
354 INTMAX_MAX, return a negative integer V such that (uintmax_t) V
355 yields the represented value. If ARGLIM is nonnull, store into
356 *ARGLIM a pointer to the first character after the prefix.
357
358 This is the inverse of sysinttostr.
359
360 On a normal return, set errno = 0.
361 On conversion error, return 0 and set errno = EINVAL.
362 On overflow, return an extreme value and set errno = ERANGE. */
363 #if ! (INTMAX_MAX <= UINTMAX_MAX)
364 # error "strtosysint: nonnegative intmax_t does not fit in uintmax_t"
365 #endif
366 intmax_t
367 strtosysint (char const *arg, char **arglim, intmax_t minval, uintmax_t maxval)
368 {
369 errno = 0;
370 if (maxval <= INTMAX_MAX)
371 {
372 if (ISDIGIT (arg[*arg == '-']))
373 {
374 intmax_t i = strtoimax (arg, arglim, 10);
375 intmax_t imaxval = maxval;
376 if (minval <= i && i <= imaxval)
377 return i;
378 errno = ERANGE;
379 return i < minval ? minval : maxval;
380 }
381 }
382 else
383 {
384 if (ISDIGIT (*arg))
385 {
386 uintmax_t i = strtoumax (arg, arglim, 10);
387 if (i <= maxval)
388 return represent_uintmax (i);
389 errno = ERANGE;
390 return maxval;
391 }
392 }
393
394 errno = EINVAL;
395 return 0;
396 }
397
398 /* Output fraction and trailing digits appropriate for a nanoseconds
399 count equal to NS, but don't output unnecessary '.' or trailing
400 zeros. */
401
402 void
403 code_ns_fraction (int ns, char *p)
404 {
405 if (ns == 0)
406 *p = '\0';
407 else
408 {
409 int i = 9;
410 *p++ = '.';
411
412 while (ns % 10 == 0)
413 {
414 ns /= 10;
415 i--;
416 }
417
418 p[i] = '\0';
419
420 for (;;)
421 {
422 p[--i] = '0' + ns % 10;
423 if (i == 0)
424 break;
425 ns /= 10;
426 }
427 }
428 }
429
430 char const *
431 code_timespec (struct timespec t, char sbuf[TIMESPEC_STRSIZE_BOUND])
432 {
433 time_t s = t.tv_sec;
434 int ns = t.tv_nsec;
435 char *np;
436 bool negative = s < 0;
437
438 /* ignore invalid values of ns */
439 if (BILLION <= ns || ns < 0)
440 ns = 0;
441
442 if (negative && ns != 0)
443 {
444 s++;
445 ns = BILLION - ns;
446 }
447
448 np = umaxtostr (negative ? - (uintmax_t) s : (uintmax_t) s, sbuf + 1);
449 if (negative)
450 *--np = '-';
451 code_ns_fraction (ns, sbuf + UINTMAX_STRSIZE_BOUND);
452 return np;
453 }
454
455 struct timespec
456 decode_timespec (char const *arg, char **arg_lim, bool parse_fraction)
457 {
458 time_t s = TYPE_MINIMUM (time_t);
459 int ns = -1;
460 char const *p = arg;
461 bool negative = *arg == '-';
462 struct timespec r;
463
464 if (! ISDIGIT (arg[negative]))
465 errno = EINVAL;
466 else
467 {
468 errno = 0;
469
470 if (negative)
471 {
472 intmax_t i = strtoimax (arg, arg_lim, 10);
473 if (TYPE_SIGNED (time_t) ? TYPE_MINIMUM (time_t) <= i : 0 <= i)
474 s = i;
475 else
476 errno = ERANGE;
477 }
478 else
479 {
480 uintmax_t i = strtoumax (arg, arg_lim, 10);
481 if (i <= TYPE_MAXIMUM (time_t))
482 s = i;
483 else
484 errno = ERANGE;
485 }
486
487 p = *arg_lim;
488 ns = 0;
489
490 if (parse_fraction && *p == '.')
491 {
492 int digits = 0;
493 bool trailing_nonzero = false;
494
495 while (ISDIGIT (*++p))
496 if (digits < LOG10_BILLION)
497 digits++, ns = 10 * ns + (*p - '0');
498 else
499 trailing_nonzero |= *p != '0';
500
501 while (digits < LOG10_BILLION)
502 digits++, ns *= 10;
503
504 if (negative)
505 {
506 /* Convert "-1.10000000000001" to s == -2, ns == 89999999.
507 I.e., truncate time stamps towards minus infinity while
508 converting them to internal form. */
509 ns += trailing_nonzero;
510 if (ns != 0)
511 {
512 if (s == TYPE_MINIMUM (time_t))
513 ns = -1;
514 else
515 {
516 s--;
517 ns = BILLION - ns;
518 }
519 }
520 }
521 }
522
523 if (errno == ERANGE)
524 ns = -1;
525 }
526
527 *arg_lim = (char *) p;
528 r.tv_sec = s;
529 r.tv_nsec = ns;
530 return r;
531 }
532 \f
533 /* File handling. */
534
535 /* Saved names in case backup needs to be undone. */
536 static char *before_backup_name;
537 static char *after_backup_name;
538
539 /* Return 1 if FILE_NAME is obviously "." or "/". */
540 bool
541 must_be_dot_or_slash (char const *file_name)
542 {
543 file_name += FILE_SYSTEM_PREFIX_LEN (file_name);
544
545 if (ISSLASH (file_name[0]))
546 {
547 for (;;)
548 if (ISSLASH (file_name[1]))
549 file_name++;
550 else if (file_name[1] == '.'
551 && ISSLASH (file_name[2 + (file_name[2] == '.')]))
552 file_name += 2 + (file_name[2] == '.');
553 else
554 return ! file_name[1];
555 }
556 else
557 {
558 while (file_name[0] == '.' && ISSLASH (file_name[1]))
559 {
560 file_name += 2;
561 while (ISSLASH (*file_name))
562 file_name++;
563 }
564
565 return ! file_name[0] || (file_name[0] == '.' && ! file_name[1]);
566 }
567 }
568
569 /* Some implementations of rmdir let you remove '.' or '/'.
570 Report an error with errno set to zero for obvious cases of this;
571 otherwise call rmdir. */
572 static int
573 safer_rmdir (const char *file_name)
574 {
575 if (must_be_dot_or_slash (file_name))
576 {
577 errno = 0;
578 return -1;
579 }
580
581 return unlinkat (chdir_fd, file_name, AT_REMOVEDIR);
582 }
583
584 /* Remove FILE_NAME, returning 1 on success. If FILE_NAME is a directory,
585 then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
586 recursively; otherwise, remove it only if it is empty. If FILE_NAME is
587 a directory that cannot be removed (e.g., because it is nonempty)
588 and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
589 Return 0 on error, with errno set; if FILE_NAME is obviously the working
590 directory return zero with errno set to zero. */
591 int
592 remove_any_file (const char *file_name, enum remove_option option)
593 {
594 /* Try unlink first if we cannot unlink directories, as this saves
595 us a system call in the common case where we're removing a
596 non-directory. */
597 bool try_unlink_first = cannot_unlink_dir ();
598
599 if (try_unlink_first)
600 {
601 if (unlinkat (chdir_fd, file_name, 0) == 0)
602 return 1;
603
604 /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
605 directory without appropriate privileges, but many Linux
606 kernels return the more-sensible EISDIR. */
607 if (errno != EPERM && errno != EISDIR)
608 return 0;
609 }
610
611 if (safer_rmdir (file_name) == 0)
612 return 1;
613
614 switch (errno)
615 {
616 case ENOTDIR:
617 return !try_unlink_first && unlinkat (chdir_fd, file_name, 0) == 0;
618
619 case 0:
620 case EEXIST:
621 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
622 case ENOTEMPTY:
623 #endif
624 switch (option)
625 {
626 case ORDINARY_REMOVE_OPTION:
627 break;
628
629 case WANT_DIRECTORY_REMOVE_OPTION:
630 return -1;
631
632 case RECURSIVE_REMOVE_OPTION:
633 {
634 char *directory = savedir (file_name);
635 char const *entry;
636 size_t entrylen;
637
638 if (! directory)
639 return 0;
640
641 for (entry = directory;
642 (entrylen = strlen (entry)) != 0;
643 entry += entrylen + 1)
644 {
645 char *file_name_buffer = new_name (file_name, entry);
646 int r = remove_any_file (file_name_buffer,
647 RECURSIVE_REMOVE_OPTION);
648 int e = errno;
649 free (file_name_buffer);
650
651 if (! r)
652 {
653 free (directory);
654 errno = e;
655 return 0;
656 }
657 }
658
659 free (directory);
660 return safer_rmdir (file_name) == 0;
661 }
662 }
663 break;
664 }
665
666 return 0;
667 }
668
669 /* Check if FILE_NAME already exists and make a backup of it right now.
670 Return success (nonzero) only if the backup is either unneeded, or
671 successful. For now, directories are considered to never need
672 backup. If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
673 so, we do not have to backup block or character devices, nor remote
674 entities. */
675 bool
676 maybe_backup_file (const char *file_name, bool this_is_the_archive)
677 {
678 struct stat file_stat;
679
680 assign_string (&before_backup_name, file_name);
681
682 /* A run situation may exist between Emacs or other GNU programs trying to
683 make a backup for the same file simultaneously. If theoretically
684 possible, real problems are unlikely. Doing any better would require a
685 convention, GNU-wide, for all programs doing backups. */
686
687 assign_string (&after_backup_name, 0);
688
689 /* Check if we really need to backup the file. */
690
691 if (this_is_the_archive && _remdev (file_name))
692 return true;
693
694 if (deref_stat (file_name, &file_stat) != 0)
695 {
696 if (errno == ENOENT)
697 return true;
698
699 stat_error (file_name);
700 return false;
701 }
702
703 if (S_ISDIR (file_stat.st_mode))
704 return true;
705
706 if (this_is_the_archive
707 && (S_ISBLK (file_stat.st_mode) || S_ISCHR (file_stat.st_mode)))
708 return true;
709
710 after_backup_name = find_backup_file_name (file_name, backup_type);
711 if (! after_backup_name)
712 xalloc_die ();
713
714 if (renameat (chdir_fd, before_backup_name, chdir_fd, after_backup_name)
715 == 0)
716 {
717 if (verbose_option)
718 fprintf (stdlis, _("Renaming %s to %s\n"),
719 quote_n (0, before_backup_name),
720 quote_n (1, after_backup_name));
721 return true;
722 }
723 else
724 {
725 /* The backup operation failed. */
726 int e = errno;
727 ERROR ((0, e, _("%s: Cannot rename to %s"),
728 quotearg_colon (before_backup_name),
729 quote_n (1, after_backup_name)));
730 assign_string (&after_backup_name, 0);
731 return false;
732 }
733 }
734
735 /* Try to restore the recently backed up file to its original name.
736 This is usually only needed after a failed extraction. */
737 void
738 undo_last_backup (void)
739 {
740 if (after_backup_name)
741 {
742 if (renameat (chdir_fd, after_backup_name, chdir_fd, before_backup_name)
743 != 0)
744 {
745 int e = errno;
746 ERROR ((0, e, _("%s: Cannot rename to %s"),
747 quotearg_colon (after_backup_name),
748 quote_n (1, before_backup_name)));
749 }
750 if (verbose_option)
751 fprintf (stdlis, _("Renaming %s back to %s\n"),
752 quote_n (0, after_backup_name),
753 quote_n (1, before_backup_name));
754 assign_string (&after_backup_name, 0);
755 }
756 }
757
758 /* Apply either stat or lstat to (NAME, BUF), depending on the
759 presence of the --dereference option. NAME is relative to the
760 most-recent argument to chdir_do. */
761 int
762 deref_stat (char const *name, struct stat *buf)
763 {
764 return fstatat (chdir_fd, name, buf, fstatat_flags);
765 }
766
767 /* Read from FD into the buffer BUF with COUNT bytes. Attempt to fill
768 BUF. Wait until input is available; this matters because files are
769 opened O_NONBLOCK for security reasons, and on some file systems
770 this can cause read to fail with errno == EAGAIN. Return the
771 actual number of bytes read, zero for EOF, or
772 SAFE_READ_ERROR upon error. */
773 size_t
774 blocking_read (int fd, void *buf, size_t count)
775 {
776 size_t bytes = safe_read (fd, buf, count);
777
778 #if defined F_SETFL && O_NONBLOCK
779 if (bytes == SAFE_READ_ERROR && errno == EAGAIN)
780 {
781 int flags = fcntl (fd, F_GETFL);
782 if (0 <= flags && flags & O_NONBLOCK
783 && fcntl (fd, F_SETFL, flags & ~O_NONBLOCK) != -1)
784 bytes = safe_read (fd, buf, count);
785 }
786 #endif
787
788 return bytes;
789 }
790
791 /* Write to FD from the buffer BUF with COUNT bytes. Do a full write.
792 Wait until an output buffer is available; this matters because
793 files are opened O_NONBLOCK for security reasons, and on some file
794 systems this can cause write to fail with errno == EAGAIN. Return
795 the actual number of bytes written, setting errno if that is less
796 than COUNT. */
797 size_t
798 blocking_write (int fd, void const *buf, size_t count)
799 {
800 size_t bytes = full_write (fd, buf, count);
801
802 #if defined F_SETFL && O_NONBLOCK
803 if (bytes < count && errno == EAGAIN)
804 {
805 int flags = fcntl (fd, F_GETFL);
806 if (0 <= flags && flags & O_NONBLOCK
807 && fcntl (fd, F_SETFL, flags & ~O_NONBLOCK) != -1)
808 {
809 char const *buffer = buf;
810 bytes += full_write (fd, buffer + bytes, count - bytes);
811 }
812 }
813 #endif
814
815 return bytes;
816 }
817
818 /* Set FD's (i.e., assuming the working directory is PARENTFD, FILE's)
819 access time to ATIME. */
820 int
821 set_file_atime (int fd, int parentfd, char const *file, struct timespec atime)
822 {
823 struct timespec ts[2];
824 ts[0] = atime;
825 ts[1].tv_nsec = UTIME_OMIT;
826 return fdutimensat (fd, parentfd, file, ts, fstatat_flags);
827 }
828
829 /* A description of a working directory. */
830 struct wd
831 {
832 /* The directory's name. */
833 char const *name;
834
835 /* If nonzero, the file descriptor of the directory, or AT_FDCWD if
836 the working directory. If zero, the directory needs to be opened
837 to be used. */
838 int fd;
839 };
840
841 /* A vector of chdir targets. wd[0] is the initial working directory. */
842 static struct wd *wd;
843
844 /* The number of working directories in the vector. */
845 static size_t wd_count;
846
847 /* The allocated size of the vector. */
848 static size_t wd_alloc;
849
850 /* The maximum number of chdir targets with open directories.
851 Don't make it too large, as many operating systems have a small
852 limit on the number of open file descriptors. Also, the current
853 implementation does not scale well. */
854 enum { CHDIR_CACHE_SIZE = 16 };
855
856 /* Indexes into WD of chdir targets with open file descriptors, sorted
857 most-recently used first. Zero indexes are unused. */
858 static int wdcache[CHDIR_CACHE_SIZE];
859
860 /* Number of nonzero entries in WDCACHE. */
861 static size_t wdcache_count;
862
863 int
864 chdir_count (void)
865 {
866 if (wd_count == 0)
867 return wd_count;
868 return wd_count - 1;
869 }
870
871 /* DIR is the operand of a -C option; add it to vector of chdir targets,
872 and return the index of its location. */
873 int
874 chdir_arg (char const *dir)
875 {
876 if (wd_count == wd_alloc)
877 {
878 if (wd_alloc == 0)
879 {
880 wd_alloc = 2;
881 wd = xmalloc (sizeof *wd * wd_alloc);
882 }
883 else
884 wd = x2nrealloc (wd, &wd_alloc, sizeof *wd);
885
886 if (! wd_count)
887 {
888 wd[wd_count].name = ".";
889 wd[wd_count].fd = AT_FDCWD;
890 wd_count++;
891 }
892 }
893
894 /* Optimize the common special case of the working directory,
895 or the working directory as a prefix. */
896 if (dir[0])
897 {
898 while (dir[0] == '.' && ISSLASH (dir[1]))
899 for (dir += 2; ISSLASH (*dir); dir++)
900 continue;
901 if (! dir[dir[0] == '.'])
902 return wd_count - 1;
903 }
904
905 wd[wd_count].name = dir;
906 wd[wd_count].fd = 0;
907 return wd_count++;
908 }
909
910 /* Index of current directory. */
911 int chdir_current;
912
913 /* Value suitable for use as the first argument to openat, and in
914 similar locations for fstatat, etc. This is an open file
915 descriptor, or AT_FDCWD if the working directory is current. It is
916 valid until the next invocation of chdir_do. */
917 int chdir_fd = AT_FDCWD;
918
919 /* Change to directory I, in a virtual way. This does not actually
920 invoke chdir; it merely sets chdir_fd to an int suitable as the
921 first argument for openat, etc. If I is 0, change to the initial
922 working directory; otherwise, I must be a value returned by
923 chdir_arg. */
924 void
925 chdir_do (int i)
926 {
927 if (chdir_current != i)
928 {
929 struct wd *curr = &wd[i];
930 int fd = curr->fd;
931
932 if (! fd)
933 {
934 if (! IS_ABSOLUTE_FILE_NAME (curr->name))
935 chdir_do (i - 1);
936 fd = openat (chdir_fd, curr->name,
937 open_searchdir_flags & ~ O_NOFOLLOW);
938 if (fd < 0)
939 open_fatal (curr->name);
940
941 curr->fd = fd;
942
943 /* Add I to the cache, tossing out the lowest-ranking entry if the
944 cache is full. */
945 if (wdcache_count < CHDIR_CACHE_SIZE)
946 wdcache[wdcache_count++] = i;
947 else
948 {
949 struct wd *stale = &wd[wdcache[CHDIR_CACHE_SIZE - 1]];
950 if (close (stale->fd) != 0)
951 close_diag (stale->name);
952 stale->fd = 0;
953 wdcache[CHDIR_CACHE_SIZE - 1] = i;
954 }
955 }
956
957 if (0 < fd)
958 {
959 /* Move the i value to the front of the cache. This is
960 O(CHDIR_CACHE_SIZE), but the cache is small. */
961 size_t ci;
962 int prev = wdcache[0];
963 for (ci = 1; prev != i; ci++)
964 {
965 int cur = wdcache[ci];
966 wdcache[ci] = prev;
967 if (cur == i)
968 break;
969 prev = cur;
970 }
971 wdcache[0] = i;
972 }
973
974 chdir_current = i;
975 chdir_fd = fd;
976 }
977 }
978 \f
979 void
980 close_diag (char const *name)
981 {
982 if (ignore_failed_read_option)
983 close_warn (name);
984 else
985 close_error (name);
986 }
987
988 void
989 open_diag (char const *name)
990 {
991 if (ignore_failed_read_option)
992 open_warn (name);
993 else
994 open_error (name);
995 }
996
997 void
998 read_diag_details (char const *name, off_t offset, size_t size)
999 {
1000 if (ignore_failed_read_option)
1001 read_warn_details (name, offset, size);
1002 else
1003 read_error_details (name, offset, size);
1004 }
1005
1006 void
1007 readlink_diag (char const *name)
1008 {
1009 if (ignore_failed_read_option)
1010 readlink_warn (name);
1011 else
1012 readlink_error (name);
1013 }
1014
1015 void
1016 savedir_diag (char const *name)
1017 {
1018 if (ignore_failed_read_option)
1019 savedir_warn (name);
1020 else
1021 savedir_error (name);
1022 }
1023
1024 void
1025 seek_diag_details (char const *name, off_t offset)
1026 {
1027 if (ignore_failed_read_option)
1028 seek_warn_details (name, offset);
1029 else
1030 seek_error_details (name, offset);
1031 }
1032
1033 void
1034 stat_diag (char const *name)
1035 {
1036 if (ignore_failed_read_option)
1037 stat_warn (name);
1038 else
1039 stat_error (name);
1040 }
1041
1042 void
1043 file_removed_diag (const char *name, bool top_level,
1044 void (*diagfn) (char const *name))
1045 {
1046 if (!top_level && errno == ENOENT)
1047 {
1048 WARNOPT (WARN_FILE_REMOVED,
1049 (0, 0, _("%s: File removed before we read it"),
1050 quotearg_colon (name)));
1051 set_exit_status (TAREXIT_DIFFERS);
1052 }
1053 else
1054 diagfn (name);
1055 }
1056
1057 void
1058 write_fatal_details (char const *name, ssize_t status, size_t size)
1059 {
1060 write_error_details (name, status, size);
1061 fatal_exit ();
1062 }
1063
1064 /* Fork, aborting if unsuccessful. */
1065 pid_t
1066 xfork (void)
1067 {
1068 pid_t p = fork ();
1069 if (p == (pid_t) -1)
1070 call_arg_fatal ("fork", _("child process"));
1071 return p;
1072 }
1073
1074 /* Create a pipe, aborting if unsuccessful. */
1075 void
1076 xpipe (int fd[2])
1077 {
1078 if (pipe (fd) < 0)
1079 call_arg_fatal ("pipe", _("interprocess channel"));
1080 }
1081
1082 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
1083 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
1084 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
1085 locations. */
1086
1087 static inline void *
1088 ptr_align (void *ptr, size_t alignment)
1089 {
1090 char *p0 = ptr;
1091 char *p1 = p0 + alignment - 1;
1092 return p1 - (size_t) p1 % alignment;
1093 }
1094
1095 /* Return the address of a page-aligned buffer of at least SIZE bytes.
1096 The caller should free *PTR when done with the buffer. */
1097
1098 void *
1099 page_aligned_alloc (void **ptr, size_t size)
1100 {
1101 size_t alignment = getpagesize ();
1102 size_t size1 = size + alignment;
1103 if (size1 < size)
1104 xalloc_die ();
1105 *ptr = xmalloc (size1);
1106 return ptr_align (*ptr, alignment);
1107 }
1108
1109 \f
1110
1111 struct namebuf
1112 {
1113 char *buffer; /* directory, '/', and directory member */
1114 size_t buffer_size; /* allocated size of name_buffer */
1115 size_t dir_length; /* length of directory part in buffer */
1116 };
1117
1118 namebuf_t
1119 namebuf_create (const char *dir)
1120 {
1121 namebuf_t buf = xmalloc (sizeof (*buf));
1122 buf->buffer_size = strlen (dir) + 2;
1123 buf->buffer = xmalloc (buf->buffer_size);
1124 strcpy (buf->buffer, dir);
1125 buf->dir_length = strlen (buf->buffer);
1126 if (!ISSLASH (buf->buffer[buf->dir_length - 1]))
1127 buf->buffer[buf->dir_length++] = DIRECTORY_SEPARATOR;
1128 return buf;
1129 }
1130
1131 void
1132 namebuf_free (namebuf_t buf)
1133 {
1134 free (buf->buffer);
1135 free (buf);
1136 }
1137
1138 char *
1139 namebuf_name (namebuf_t buf, const char *name)
1140 {
1141 size_t len = strlen (name);
1142 while (buf->dir_length + len + 1 >= buf->buffer_size)
1143 buf->buffer = x2realloc (buf->buffer, &buf->buffer_size);
1144 strcpy (buf->buffer + buf->dir_length, name);
1145 return buf->buffer;
1146 }
This page took 0.083099 seconds and 4 git commands to generate.