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