Improve listed incremental dumps.
[debian/tar] / src / misc.c
1 /* Miscellaneous functions, not really specific to GNU tar.
2
3    Copyright (C) 1988, 1992, 1994, 1995, 1996, 1997, 1999, 2000, 2001,
4    2003, 2004, 2005, 2006, 2007, 2009 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, write to the Free Software Foundation, Inc.,
18    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
19
20 #include <system.h>
21 #include <rmt.h>
22 #include "common.h"
23 #include <quotearg.h>
24 #include <save-cwd.h>
25 #include <xgetcwd.h>
26 #include <unlinkdir.h>
27 #include <utimens.h>
28 #include <canonicalize.h>
29
30 #if HAVE_STROPTS_H
31 # include <stropts.h>
32 #endif
33 #if HAVE_SYS_FILIO_H
34 # include <sys/filio.h>
35 #endif
36
37 \f
38 /* Handling strings.  */
39
40 /* Assign STRING to a copy of VALUE if not zero, or to zero.  If
41    STRING was nonzero, it is freed first.  */
42 void
43 assign_string (char **string, const char *value)
44 {
45   if (*string)
46     free (*string);
47   *string = value ? xstrdup (value) : 0;
48 }
49
50 /* Allocate a copy of the string quoted as in C, and returns that.  If
51    the string does not have to be quoted, it returns a null pointer.
52    The allocated copy should normally be freed with free() after the
53    caller is done with it.
54
55    This is used in one context only: generating the directory file in
56    incremental dumps.  The quoted string is not intended for human
57    consumption; it is intended only for unquote_string.  The quoting
58    is locale-independent, so that users needn't worry about locale
59    when reading directory files.  This means that we can't use
60    quotearg, as quotearg is locale-dependent and is meant for human
61    consumption.  */
62 char *
63 quote_copy_string (const char *string)
64 {
65   const char *source = string;
66   char *destination = 0;
67   char *buffer = 0;
68   int copying = 0;
69
70   while (*source)
71     {
72       int character = *source++;
73
74       switch (character)
75         {
76         case '\n': case '\\':
77           if (!copying)
78             {
79               size_t length = (source - string) - 1;
80
81               copying = 1;
82               buffer = xmalloc (length + 2 + 2 * strlen (source) + 1);
83               memcpy (buffer, string, length);
84               destination = buffer + length;
85             }
86           *destination++ = '\\';
87           *destination++ = character == '\\' ? '\\' : 'n';
88           break;
89
90         default:
91           if (copying)
92             *destination++ = character;
93           break;
94         }
95     }
96   if (copying)
97     {
98       *destination = '\0';
99       return buffer;
100     }
101   return 0;
102 }
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 char *
234 normalize_filename (const char *name)
235 {
236   return zap_slashes (canonicalize_filename_mode (name, CAN_MISSING));
237 }
238
239 \f
240 /* Handling numbers.  */
241
242 /* Output fraction and trailing digits appropriate for a nanoseconds
243    count equal to NS, but don't output unnecessary '.' or trailing
244    zeros.  */
245
246 void
247 code_ns_fraction (int ns, char *p)
248 {
249   if (ns == 0)
250     *p = '\0';
251   else
252     {
253       int i = 9;
254       *p++ = '.';
255
256       while (ns % 10 == 0)
257         {
258           ns /= 10;
259           i--;
260         }
261
262       p[i] = '\0';
263
264       for (;;)
265         {
266           p[--i] = '0' + ns % 10;
267           if (i == 0)
268             break;
269           ns /= 10;
270         }
271     }
272 }
273
274 char const *
275 code_timespec (struct timespec t, char sbuf[TIMESPEC_STRSIZE_BOUND])
276 {
277   time_t s = t.tv_sec;
278   int ns = t.tv_nsec;
279   char *np;
280   bool negative = s < 0;
281
282   if (negative && ns != 0)
283     {
284       s++;
285       ns = BILLION - ns;
286     }
287
288   np = umaxtostr (negative ? - (uintmax_t) s : (uintmax_t) s, sbuf + 1);
289   if (negative)
290     *--np = '-';
291   code_ns_fraction (ns, sbuf + UINTMAX_STRSIZE_BOUND);
292   return np;
293 }
294 \f
295 /* File handling.  */
296
297 /* Saved names in case backup needs to be undone.  */
298 static char *before_backup_name;
299 static char *after_backup_name;
300
301 /* Return 1 if FILE_NAME is obviously "." or "/".  */
302 static bool
303 must_be_dot_or_slash (char const *file_name)
304 {
305   file_name += FILE_SYSTEM_PREFIX_LEN (file_name);
306
307   if (ISSLASH (file_name[0]))
308     {
309       for (;;)
310         if (ISSLASH (file_name[1]))
311           file_name++;
312         else if (file_name[1] == '.'
313                  && ISSLASH (file_name[2 + (file_name[2] == '.')]))
314           file_name += 2 + (file_name[2] == '.');
315         else
316           return ! file_name[1];
317     }
318   else
319     {
320       while (file_name[0] == '.' && ISSLASH (file_name[1]))
321         {
322           file_name += 2;
323           while (ISSLASH (*file_name))
324             file_name++;
325         }
326
327       return ! file_name[0] || (file_name[0] == '.' && ! file_name[1]);
328     }
329 }
330
331 /* Some implementations of rmdir let you remove '.' or '/'.
332    Report an error with errno set to zero for obvious cases of this;
333    otherwise call rmdir.  */
334 static int
335 safer_rmdir (const char *file_name)
336 {
337   if (must_be_dot_or_slash (file_name))
338     {
339       errno = 0;
340       return -1;
341     }
342
343   return rmdir (file_name);
344 }
345
346 /* Remove FILE_NAME, returning 1 on success.  If FILE_NAME is a directory,
347    then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
348    recursively; otherwise, remove it only if it is empty.  If FILE_NAME is
349    a directory that cannot be removed (e.g., because it is nonempty)
350    and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
351    Return 0 on error, with errno set; if FILE_NAME is obviously the working
352    directory return zero with errno set to zero.  */
353 int
354 remove_any_file (const char *file_name, enum remove_option option)
355 {
356   /* Try unlink first if we cannot unlink directories, as this saves
357      us a system call in the common case where we're removing a
358      non-directory.  */
359   bool try_unlink_first = cannot_unlink_dir ();
360
361   if (try_unlink_first)
362     {
363       if (unlink (file_name) == 0)
364         return 1;
365
366       /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
367          directory without appropriate privileges, but many Linux
368          kernels return the more-sensible EISDIR.  */
369       if (errno != EPERM && errno != EISDIR)
370         return 0;
371     }
372
373   if (safer_rmdir (file_name) == 0)
374     return 1;
375
376   switch (errno)
377     {
378     case ENOTDIR:
379       return !try_unlink_first && unlink (file_name) == 0;
380
381     case 0:
382     case EEXIST:
383 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
384     case ENOTEMPTY:
385 #endif
386       switch (option)
387         {
388         case ORDINARY_REMOVE_OPTION:
389           break;
390
391         case WANT_DIRECTORY_REMOVE_OPTION:
392           return -1;
393
394         case RECURSIVE_REMOVE_OPTION:
395           {
396             char *directory = savedir (file_name);
397             char const *entry;
398             size_t entrylen;
399
400             if (! directory)
401               return 0;
402
403             for (entry = directory;
404                  (entrylen = strlen (entry)) != 0;
405                  entry += entrylen + 1)
406               {
407                 char *file_name_buffer = new_name (file_name, entry);
408                 int r = remove_any_file (file_name_buffer,
409                                          RECURSIVE_REMOVE_OPTION);
410                 int e = errno;
411                 free (file_name_buffer);
412
413                 if (! r)
414                   {
415                     free (directory);
416                     errno = e;
417                     return 0;
418                   }
419               }
420
421             free (directory);
422             return safer_rmdir (file_name) == 0;
423           }
424         }
425       break;
426     }
427
428   return 0;
429 }
430
431 /* Check if FILE_NAME already exists and make a backup of it right now.
432    Return success (nonzero) only if the backup is either unneeded, or
433    successful.  For now, directories are considered to never need
434    backup.  If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
435    so, we do not have to backup block or character devices, nor remote
436    entities.  */
437 bool
438 maybe_backup_file (const char *file_name, bool this_is_the_archive)
439 {
440   struct stat file_stat;
441
442   assign_string (&before_backup_name, file_name);
443
444   /* A run situation may exist between Emacs or other GNU programs trying to
445      make a backup for the same file simultaneously.  If theoretically
446      possible, real problems are unlikely.  Doing any better would require a
447      convention, GNU-wide, for all programs doing backups.  */
448
449   assign_string (&after_backup_name, 0);
450
451   /* Check if we really need to backup the file.  */
452
453   if (this_is_the_archive && _remdev (file_name))
454     return true;
455
456   if (stat (file_name, &file_stat))
457     {
458       if (errno == ENOENT)
459         return true;
460
461       stat_error (file_name);
462       return false;
463     }
464
465   if (S_ISDIR (file_stat.st_mode))
466     return true;
467
468   if (this_is_the_archive
469       && (S_ISBLK (file_stat.st_mode) || S_ISCHR (file_stat.st_mode)))
470     return true;
471
472   after_backup_name = find_backup_file_name (file_name, backup_type);
473   if (! after_backup_name)
474     xalloc_die ();
475
476   if (rename (before_backup_name, after_backup_name) == 0)
477     {
478       if (verbose_option)
479         fprintf (stdlis, _("Renaming %s to %s\n"),
480                  quote_n (0, before_backup_name),
481                  quote_n (1, after_backup_name));
482       return true;
483     }
484   else
485     {
486       /* The backup operation failed.  */
487       int e = errno;
488       ERROR ((0, e, _("%s: Cannot rename to %s"),
489               quotearg_colon (before_backup_name),
490               quote_n (1, after_backup_name)));
491       assign_string (&after_backup_name, 0);
492       return false;
493     }
494 }
495
496 /* Try to restore the recently backed up file to its original name.
497    This is usually only needed after a failed extraction.  */
498 void
499 undo_last_backup (void)
500 {
501   if (after_backup_name)
502     {
503       if (rename (after_backup_name, before_backup_name) != 0)
504         {
505           int e = errno;
506           ERROR ((0, e, _("%s: Cannot rename to %s"),
507                   quotearg_colon (after_backup_name),
508                   quote_n (1, before_backup_name)));
509         }
510       if (verbose_option)
511         fprintf (stdlis, _("Renaming %s back to %s\n"),
512                  quote_n (0, after_backup_name),
513                  quote_n (1, before_backup_name));
514       assign_string (&after_backup_name, 0);
515     }
516 }
517
518 /* Depending on DEREF, apply either stat or lstat to (NAME, BUF).  */
519 int
520 deref_stat (bool deref, char const *name, struct stat *buf)
521 {
522   return deref ? stat (name, buf) : lstat (name, buf);
523 }
524
525 /* Set FD's (i.e., FILE's) access time to TIMESPEC[0].  If that's not
526    possible to do by itself, set its access and data modification
527    times to TIMESPEC[0] and TIMESPEC[1], respectively.  */
528 int
529 set_file_atime (int fd, char const *file, struct timespec const timespec[2])
530 {
531 #ifdef _FIOSATIME
532   if (0 <= fd)
533     {
534       struct timeval timeval;
535       timeval.tv_sec = timespec[0].tv_sec;
536       timeval.tv_usec = timespec[0].tv_nsec / 1000;
537       if (ioctl (fd, _FIOSATIME, &timeval) == 0)
538         return 0;
539     }
540 #endif
541
542   return gl_futimens (fd, file, timespec);
543 }
544
545 /* A description of a working directory.  */
546 struct wd
547 {
548   char const *name;
549   int saved;
550   struct saved_cwd saved_cwd;
551 };
552
553 /* A vector of chdir targets.  wd[0] is the initial working directory.  */
554 static struct wd *wd;
555
556 /* The number of working directories in the vector.  */
557 static size_t wd_count;
558
559 /* The allocated size of the vector.  */
560 static size_t wd_alloc;
561
562 int
563 chdir_count ()
564 {
565   if (wd_count == 0)
566     return wd_count;
567   return wd_count - 1;
568 }
569
570 /* DIR is the operand of a -C option; add it to vector of chdir targets,
571    and return the index of its location.  */
572 int
573 chdir_arg (char const *dir)
574 {
575   if (wd_count == wd_alloc)
576     {
577       if (wd_alloc == 0)
578         {
579           wd_alloc = 2;
580           wd = xmalloc (sizeof *wd * wd_alloc);
581         }
582       else
583         wd = x2nrealloc (wd, &wd_alloc, sizeof *wd);
584
585       if (! wd_count)
586         {
587           wd[wd_count].name = ".";
588           wd[wd_count].saved = 0;
589           wd_count++;
590         }
591     }
592
593   /* Optimize the common special case of the working directory,
594      or the working directory as a prefix.  */
595   if (dir[0])
596     {
597       while (dir[0] == '.' && ISSLASH (dir[1]))
598         for (dir += 2;  ISSLASH (*dir);  dir++)
599           continue;
600       if (! dir[dir[0] == '.'])
601         return wd_count - 1;
602     }
603
604   wd[wd_count].name = dir;
605   wd[wd_count].saved = 0;
606   return wd_count++;
607 }
608
609 /* Change to directory I.  If I is 0, change to the initial working
610    directory; otherwise, I must be a value returned by chdir_arg.  */
611 void
612 chdir_do (int i)
613 {
614   static int previous;
615
616   if (previous != i)
617     {
618       struct wd *prev = &wd[previous];
619       struct wd *curr = &wd[i];
620
621       if (! prev->saved)
622         {
623           int err = 0;
624           prev->saved = 1;
625           if (save_cwd (&prev->saved_cwd) != 0)
626             err = errno;
627           else if (0 <= prev->saved_cwd.desc)
628             {
629               /* Make sure we still have at least one descriptor available.  */
630               int fd1 = prev->saved_cwd.desc;
631               int fd2 = dup (fd1);
632               if (0 <= fd2)
633                 close (fd2);
634               else if (errno == EMFILE)
635                 {
636                   /* Force restore_cwd to use chdir_long.  */
637                   close (fd1);
638                   prev->saved_cwd.desc = -1;
639                   prev->saved_cwd.name = xgetcwd ();
640                 }
641               else
642                 err = errno;
643             }
644
645           if (err)
646             FATAL_ERROR ((0, err, _("Cannot save working directory")));
647         }
648
649       if (curr->saved)
650         {
651           if (restore_cwd (&curr->saved_cwd))
652             FATAL_ERROR ((0, 0, _("Cannot change working directory")));
653         }
654       else
655         {
656           if (i && ! ISSLASH (curr->name[0]))
657             chdir_do (i - 1);
658           if (chdir (curr->name) != 0)
659             chdir_fatal (curr->name);
660         }
661
662       previous = i;
663     }
664 }
665 \f
666 void
667 close_diag (char const *name)
668 {
669   if (ignore_failed_read_option)
670     close_warn (name);
671   else
672     close_error (name);
673 }
674
675 void
676 open_diag (char const *name)
677 {
678   if (ignore_failed_read_option)
679     open_warn (name);
680   else
681     open_error (name);
682 }
683
684 void
685 read_diag_details (char const *name, off_t offset, size_t size)
686 {
687   if (ignore_failed_read_option)
688     read_warn_details (name, offset, size);
689   else
690     read_error_details (name, offset, size);
691 }
692
693 void
694 readlink_diag (char const *name)
695 {
696   if (ignore_failed_read_option)
697     readlink_warn (name);
698   else
699     readlink_error (name);
700 }
701
702 void
703 savedir_diag (char const *name)
704 {
705   if (ignore_failed_read_option)
706     savedir_warn (name);
707   else
708     savedir_error (name);
709 }
710
711 void
712 seek_diag_details (char const *name, off_t offset)
713 {
714   if (ignore_failed_read_option)
715     seek_warn_details (name, offset);
716   else
717     seek_error_details (name, offset);
718 }
719
720 void
721 stat_diag (char const *name)
722 {
723   if (ignore_failed_read_option)
724     stat_warn (name);
725   else
726     stat_error (name);
727 }
728
729 void
730 write_fatal_details (char const *name, ssize_t status, size_t size)
731 {
732   write_error_details (name, status, size);
733   fatal_exit ();
734 }
735
736 /* Fork, aborting if unsuccessful.  */
737 pid_t
738 xfork (void)
739 {
740   pid_t p = fork ();
741   if (p == (pid_t) -1)
742     call_arg_fatal ("fork", _("child process"));
743   return p;
744 }
745
746 /* Create a pipe, aborting if unsuccessful.  */
747 void
748 xpipe (int fd[2])
749 {
750   if (pipe (fd) < 0)
751     call_arg_fatal ("pipe", _("interprocess channel"));
752 }
753
754 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
755    ALIGNMENT must be nonzero.  The caller must arrange for ((char *)
756    PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
757    locations.  */
758
759 static inline void *
760 ptr_align (void *ptr, size_t alignment)
761 {
762   char *p0 = ptr;
763   char *p1 = p0 + alignment - 1;
764   return p1 - (size_t) p1 % alignment;
765 }
766
767 /* Return the address of a page-aligned buffer of at least SIZE bytes.
768    The caller should free *PTR when done with the buffer.  */
769
770 void *
771 page_aligned_alloc (void **ptr, size_t size)
772 {
773   size_t alignment = getpagesize ();
774   size_t size1 = size + alignment;
775   if (size1 < size)
776     xalloc_die ();
777   *ptr = xmalloc (size1);
778   return ptr_align (*ptr, alignment);
779 }