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