]> git.cworth.org Git - tar/blob - src/misc.c
f81111f197d53c53c4321668f13e58ca2b9c4324
[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 void
241 replace_prefix (char **pname, const char *samp, size_t slen,
242                 const char *repl, size_t rlen)
243 {
244   char *name = *pname;
245   size_t nlen = strlen (name);
246   if (nlen > slen && memcmp (name, samp, slen) == 0 && ISSLASH (name[slen]))
247     {
248       if (rlen > slen)
249         {
250           name = xrealloc (name, nlen - slen + rlen + 1);
251           *pname = name;
252         }
253       memmove (name + rlen, name + slen, nlen - slen + 1);
254       memcpy (name, repl, rlen);
255     }
256 }
257
258 \f
259 /* Handling numbers.  */
260
261 /* Output fraction and trailing digits appropriate for a nanoseconds
262    count equal to NS, but don't output unnecessary '.' or trailing
263    zeros.  */
264
265 void
266 code_ns_fraction (int ns, char *p)
267 {
268   if (ns == 0)
269     *p = '\0';
270   else
271     {
272       int i = 9;
273       *p++ = '.';
274
275       while (ns % 10 == 0)
276         {
277           ns /= 10;
278           i--;
279         }
280
281       p[i] = '\0';
282
283       for (;;)
284         {
285           p[--i] = '0' + ns % 10;
286           if (i == 0)
287             break;
288           ns /= 10;
289         }
290     }
291 }
292
293 char const *
294 code_timespec (struct timespec t, char sbuf[TIMESPEC_STRSIZE_BOUND])
295 {
296   time_t s = t.tv_sec;
297   int ns = t.tv_nsec;
298   char *np;
299   bool negative = s < 0;
300
301   /* ignore invalid values of ns */
302   if (BILLION <= ns || ns < 0)
303     ns = 0;
304   
305   if (negative && ns != 0)
306     {
307       s++;
308       ns = BILLION - ns;
309     }
310
311   np = umaxtostr (negative ? - (uintmax_t) s : (uintmax_t) s, sbuf + 1);
312   if (negative)
313     *--np = '-';
314   code_ns_fraction (ns, sbuf + UINTMAX_STRSIZE_BOUND);
315   return np;
316 }
317 \f
318 /* File handling.  */
319
320 /* Saved names in case backup needs to be undone.  */
321 static char *before_backup_name;
322 static char *after_backup_name;
323
324 /* Return 1 if FILE_NAME is obviously "." or "/".  */
325 static bool
326 must_be_dot_or_slash (char const *file_name)
327 {
328   file_name += FILE_SYSTEM_PREFIX_LEN (file_name);
329
330   if (ISSLASH (file_name[0]))
331     {
332       for (;;)
333         if (ISSLASH (file_name[1]))
334           file_name++;
335         else if (file_name[1] == '.'
336                  && ISSLASH (file_name[2 + (file_name[2] == '.')]))
337           file_name += 2 + (file_name[2] == '.');
338         else
339           return ! file_name[1];
340     }
341   else
342     {
343       while (file_name[0] == '.' && ISSLASH (file_name[1]))
344         {
345           file_name += 2;
346           while (ISSLASH (*file_name))
347             file_name++;
348         }
349
350       return ! file_name[0] || (file_name[0] == '.' && ! file_name[1]);
351     }
352 }
353
354 /* Some implementations of rmdir let you remove '.' or '/'.
355    Report an error with errno set to zero for obvious cases of this;
356    otherwise call rmdir.  */
357 static int
358 safer_rmdir (const char *file_name)
359 {
360   if (must_be_dot_or_slash (file_name))
361     {
362       errno = 0;
363       return -1;
364     }
365
366   return rmdir (file_name);
367 }
368
369 /* Remove FILE_NAME, returning 1 on success.  If FILE_NAME is a directory,
370    then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
371    recursively; otherwise, remove it only if it is empty.  If FILE_NAME is
372    a directory that cannot be removed (e.g., because it is nonempty)
373    and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
374    Return 0 on error, with errno set; if FILE_NAME is obviously the working
375    directory return zero with errno set to zero.  */
376 int
377 remove_any_file (const char *file_name, enum remove_option option)
378 {
379   /* Try unlink first if we cannot unlink directories, as this saves
380      us a system call in the common case where we're removing a
381      non-directory.  */
382   bool try_unlink_first = cannot_unlink_dir ();
383
384   if (try_unlink_first)
385     {
386       if (unlink (file_name) == 0)
387         return 1;
388
389       /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
390          directory without appropriate privileges, but many Linux
391          kernels return the more-sensible EISDIR.  */
392       if (errno != EPERM && errno != EISDIR)
393         return 0;
394     }
395
396   if (safer_rmdir (file_name) == 0)
397     return 1;
398
399   switch (errno)
400     {
401     case ENOTDIR:
402       return !try_unlink_first && unlink (file_name) == 0;
403
404     case 0:
405     case EEXIST:
406 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
407     case ENOTEMPTY:
408 #endif
409       switch (option)
410         {
411         case ORDINARY_REMOVE_OPTION:
412           break;
413
414         case WANT_DIRECTORY_REMOVE_OPTION:
415           return -1;
416
417         case RECURSIVE_REMOVE_OPTION:
418           {
419             char *directory = savedir (file_name);
420             char const *entry;
421             size_t entrylen;
422
423             if (! directory)
424               return 0;
425
426             for (entry = directory;
427                  (entrylen = strlen (entry)) != 0;
428                  entry += entrylen + 1)
429               {
430                 char *file_name_buffer = new_name (file_name, entry);
431                 int r = remove_any_file (file_name_buffer,
432                                          RECURSIVE_REMOVE_OPTION);
433                 int e = errno;
434                 free (file_name_buffer);
435
436                 if (! r)
437                   {
438                     free (directory);
439                     errno = e;
440                     return 0;
441                   }
442               }
443
444             free (directory);
445             return safer_rmdir (file_name) == 0;
446           }
447         }
448       break;
449     }
450
451   return 0;
452 }
453
454 /* Check if FILE_NAME already exists and make a backup of it right now.
455    Return success (nonzero) only if the backup is either unneeded, or
456    successful.  For now, directories are considered to never need
457    backup.  If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
458    so, we do not have to backup block or character devices, nor remote
459    entities.  */
460 bool
461 maybe_backup_file (const char *file_name, bool this_is_the_archive)
462 {
463   struct stat file_stat;
464
465   assign_string (&before_backup_name, file_name);
466
467   /* A run situation may exist between Emacs or other GNU programs trying to
468      make a backup for the same file simultaneously.  If theoretically
469      possible, real problems are unlikely.  Doing any better would require a
470      convention, GNU-wide, for all programs doing backups.  */
471
472   assign_string (&after_backup_name, 0);
473
474   /* Check if we really need to backup the file.  */
475
476   if (this_is_the_archive && _remdev (file_name))
477     return true;
478
479   if (stat (file_name, &file_stat))
480     {
481       if (errno == ENOENT)
482         return true;
483
484       stat_error (file_name);
485       return false;
486     }
487
488   if (S_ISDIR (file_stat.st_mode))
489     return true;
490
491   if (this_is_the_archive
492       && (S_ISBLK (file_stat.st_mode) || S_ISCHR (file_stat.st_mode)))
493     return true;
494
495   after_backup_name = find_backup_file_name (file_name, backup_type);
496   if (! after_backup_name)
497     xalloc_die ();
498
499   if (rename (before_backup_name, after_backup_name) == 0)
500     {
501       if (verbose_option)
502         fprintf (stdlis, _("Renaming %s to %s\n"),
503                  quote_n (0, before_backup_name),
504                  quote_n (1, after_backup_name));
505       return true;
506     }
507   else
508     {
509       /* The backup operation failed.  */
510       int e = errno;
511       ERROR ((0, e, _("%s: Cannot rename to %s"),
512               quotearg_colon (before_backup_name),
513               quote_n (1, after_backup_name)));
514       assign_string (&after_backup_name, 0);
515       return false;
516     }
517 }
518
519 /* Try to restore the recently backed up file to its original name.
520    This is usually only needed after a failed extraction.  */
521 void
522 undo_last_backup (void)
523 {
524   if (after_backup_name)
525     {
526       if (rename (after_backup_name, before_backup_name) != 0)
527         {
528           int e = errno;
529           ERROR ((0, e, _("%s: Cannot rename to %s"),
530                   quotearg_colon (after_backup_name),
531                   quote_n (1, before_backup_name)));
532         }
533       if (verbose_option)
534         fprintf (stdlis, _("Renaming %s back to %s\n"),
535                  quote_n (0, after_backup_name),
536                  quote_n (1, before_backup_name));
537       assign_string (&after_backup_name, 0);
538     }
539 }
540
541 /* Depending on DEREF, apply either stat or lstat to (NAME, BUF).  */
542 int
543 deref_stat (bool deref, char const *name, struct stat *buf)
544 {
545   return deref ? stat (name, buf) : lstat (name, buf);
546 }
547
548 /* Set FD's (i.e., FILE's) access time to TIMESPEC[0].  If that's not
549    possible to do by itself, set its access and data modification
550    times to TIMESPEC[0] and TIMESPEC[1], respectively.  */
551 int
552 set_file_atime (int fd, char const *file, struct timespec const timespec[2])
553 {
554 #ifdef _FIOSATIME
555   if (0 <= fd)
556     {
557       struct timeval timeval;
558       timeval.tv_sec = timespec[0].tv_sec;
559       timeval.tv_usec = timespec[0].tv_nsec / 1000;
560       if (ioctl (fd, _FIOSATIME, &timeval) == 0)
561         return 0;
562     }
563 #endif
564
565   return gl_futimens (fd, file, timespec);
566 }
567
568 /* A description of a working directory.  */
569 struct wd
570 {
571   char const *name;
572   int saved;
573   struct saved_cwd saved_cwd;
574 };
575
576 /* A vector of chdir targets.  wd[0] is the initial working directory.  */
577 static struct wd *wd;
578
579 /* The number of working directories in the vector.  */
580 static size_t wd_count;
581
582 /* The allocated size of the vector.  */
583 static size_t wd_alloc;
584
585 int
586 chdir_count ()
587 {
588   if (wd_count == 0)
589     return wd_count;
590   return wd_count - 1;
591 }
592
593 /* DIR is the operand of a -C option; add it to vector of chdir targets,
594    and return the index of its location.  */
595 int
596 chdir_arg (char const *dir)
597 {
598   if (wd_count == wd_alloc)
599     {
600       if (wd_alloc == 0)
601         {
602           wd_alloc = 2;
603           wd = xmalloc (sizeof *wd * wd_alloc);
604         }
605       else
606         wd = x2nrealloc (wd, &wd_alloc, sizeof *wd);
607
608       if (! wd_count)
609         {
610           wd[wd_count].name = ".";
611           wd[wd_count].saved = 0;
612           wd_count++;
613         }
614     }
615
616   /* Optimize the common special case of the working directory,
617      or the working directory as a prefix.  */
618   if (dir[0])
619     {
620       while (dir[0] == '.' && ISSLASH (dir[1]))
621         for (dir += 2;  ISSLASH (*dir);  dir++)
622           continue;
623       if (! dir[dir[0] == '.'])
624         return wd_count - 1;
625     }
626
627   wd[wd_count].name = dir;
628   wd[wd_count].saved = 0;
629   return wd_count++;
630 }
631
632 /* Change to directory I.  If I is 0, change to the initial working
633    directory; otherwise, I must be a value returned by chdir_arg.  */
634 void
635 chdir_do (int i)
636 {
637   static int previous;
638
639   if (previous != i)
640     {
641       struct wd *prev = &wd[previous];
642       struct wd *curr = &wd[i];
643
644       if (! prev->saved)
645         {
646           int err = 0;
647           prev->saved = 1;
648           if (save_cwd (&prev->saved_cwd) != 0)
649             err = errno;
650           else if (0 <= prev->saved_cwd.desc)
651             {
652               /* Make sure we still have at least one descriptor available.  */
653               int fd1 = prev->saved_cwd.desc;
654               int fd2 = dup (fd1);
655               if (0 <= fd2)
656                 close (fd2);
657               else if (errno == EMFILE)
658                 {
659                   /* Force restore_cwd to use chdir_long.  */
660                   close (fd1);
661                   prev->saved_cwd.desc = -1;
662                   prev->saved_cwd.name = xgetcwd ();
663                 }
664               else
665                 err = errno;
666             }
667
668           if (err)
669             FATAL_ERROR ((0, err, _("Cannot save working directory")));
670         }
671
672       if (curr->saved)
673         {
674           if (restore_cwd (&curr->saved_cwd))
675             FATAL_ERROR ((0, 0, _("Cannot change working directory")));
676         }
677       else
678         {
679           if (i && ! ISSLASH (curr->name[0]))
680             chdir_do (i - 1);
681           if (chdir (curr->name) != 0)
682             chdir_fatal (curr->name);
683         }
684
685       previous = i;
686     }
687 }
688 \f
689 void
690 close_diag (char const *name)
691 {
692   if (ignore_failed_read_option)
693     close_warn (name);
694   else
695     close_error (name);
696 }
697
698 void
699 open_diag (char const *name)
700 {
701   if (ignore_failed_read_option)
702     open_warn (name);
703   else
704     open_error (name);
705 }
706
707 void
708 read_diag_details (char const *name, off_t offset, size_t size)
709 {
710   if (ignore_failed_read_option)
711     read_warn_details (name, offset, size);
712   else
713     read_error_details (name, offset, size);
714 }
715
716 void
717 readlink_diag (char const *name)
718 {
719   if (ignore_failed_read_option)
720     readlink_warn (name);
721   else
722     readlink_error (name);
723 }
724
725 void
726 savedir_diag (char const *name)
727 {
728   if (ignore_failed_read_option)
729     savedir_warn (name);
730   else
731     savedir_error (name);
732 }
733
734 void
735 seek_diag_details (char const *name, off_t offset)
736 {
737   if (ignore_failed_read_option)
738     seek_warn_details (name, offset);
739   else
740     seek_error_details (name, offset);
741 }
742
743 void
744 stat_diag (char const *name)
745 {
746   if (ignore_failed_read_option)
747     stat_warn (name);
748   else
749     stat_error (name);
750 }
751
752 void
753 file_removed_diag (const char *name, bool top_level,
754                    void (*diagfn) (char const *name))
755 {
756   if (!top_level && errno == ENOENT)
757     {
758       WARNOPT (WARN_FILE_REMOVED,
759                (0, 0, _("%s: File removed before we read it"),
760                 quotearg_colon (name)));
761       set_exit_status (TAREXIT_DIFFERS);
762     }      
763   else
764     diagfn (name);
765 }
766
767 void
768 dir_removed_diag (const char *name, bool top_level,
769                    void (*diagfn) (char const *name))
770 {
771   if (!top_level && errno == ENOENT)
772     {
773       WARNOPT (WARN_FILE_REMOVED,
774                (0, 0, _("%s: Directory removed before we read it"),
775                 quotearg_colon (name)));
776       set_exit_status (TAREXIT_DIFFERS);
777     }
778   else
779     diagfn (name);
780 }
781
782 void
783 write_fatal_details (char const *name, ssize_t status, size_t size)
784 {
785   write_error_details (name, status, size);
786   fatal_exit ();
787 }
788
789 /* Fork, aborting if unsuccessful.  */
790 pid_t
791 xfork (void)
792 {
793   pid_t p = fork ();
794   if (p == (pid_t) -1)
795     call_arg_fatal ("fork", _("child process"));
796   return p;
797 }
798
799 /* Create a pipe, aborting if unsuccessful.  */
800 void
801 xpipe (int fd[2])
802 {
803   if (pipe (fd) < 0)
804     call_arg_fatal ("pipe", _("interprocess channel"));
805 }
806
807 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
808    ALIGNMENT must be nonzero.  The caller must arrange for ((char *)
809    PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
810    locations.  */
811
812 static inline void *
813 ptr_align (void *ptr, size_t alignment)
814 {
815   char *p0 = ptr;
816   char *p1 = p0 + alignment - 1;
817   return p1 - (size_t) p1 % alignment;
818 }
819
820 /* Return the address of a page-aligned buffer of at least SIZE bytes.
821    The caller should free *PTR when done with the buffer.  */
822
823 void *
824 page_aligned_alloc (void **ptr, size_t size)
825 {
826   size_t alignment = getpagesize ();
827   size_t size1 = size + alignment;
828   if (size1 < size)
829     xalloc_die ();
830   *ptr = xmalloc (size1);
831   return ptr_align (*ptr, alignment);
832 }
833
834 \f
835
836 struct namebuf
837 {
838   char *buffer;         /* directory, `/', and directory member */
839   size_t buffer_size;   /* allocated size of name_buffer */
840   size_t dir_length;    /* length of directory part in buffer */
841 };
842
843 namebuf_t
844 namebuf_create (const char *dir)
845 {
846   namebuf_t buf = xmalloc (sizeof (*buf));
847   buf->buffer_size = strlen (dir) + 2;
848   buf->buffer = xmalloc (buf->buffer_size);
849   strcpy (buf->buffer, dir);
850   buf->dir_length = strlen (buf->buffer);
851   if (!ISSLASH (buf->buffer[buf->dir_length - 1]))
852     buf->buffer[buf->dir_length++] = DIRECTORY_SEPARATOR;
853   return buf;
854 }
855
856 void
857 namebuf_free (namebuf_t buf)
858 {
859   free (buf->buffer);
860   free (buf);
861 }
862
863 char *
864 namebuf_name (namebuf_t buf, const char *name)
865 {
866   size_t len = strlen (name);
867   while (buf->dir_length + len + 1 >= buf->buffer_size)
868     buf->buffer = x2realloc (buf->buffer, &buf->buffer_size);
869   strcpy (buf->buffer + buf->dir_length, name);
870   return buf->buffer;
871 }
872
873
874