Initial import from FreeBSD RELENG_4:
[dragonfly.git] / contrib / tar / src / misc.c
1 /* Miscellaneous functions, not really specific to GNU tar.
2
3    Copyright 1988, 1992, 1994, 1995, 1996, 1997, 1999, 2000, 2001 Free
4    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 2, 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    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 /* $FreeBSD: src/contrib/tar/src/misc.c,v 1.2.2.2 2002/10/19 09:37:29 sobomax Exp $ */
21
22 #include "system.h"
23 #include "rmt.h"
24 #include "common.h"
25 #include <quotearg.h>
26 #include <save-cwd.h>
27
28 static void call_arg_fatal PARAMS ((char const *, char const *))
29      __attribute__ ((noreturn));
30 \f
31 /* Handling strings.  */
32
33 /* Assign STRING to a copy of VALUE if not zero, or to zero.  If
34    STRING was nonzero, it is freed first.  */
35 void
36 assign_string (char **string, const char *value)
37 {
38   if (*string)
39     free (*string);
40   *string = value ? xstrdup (value) : 0;
41 }
42
43 /* Allocate a copy of the string quoted as in C, and returns that.  If
44    the string does not have to be quoted, it returns a null pointer.
45    The allocated copy should normally be freed with free() after the
46    caller is done with it.
47
48    This is used in one context only: generating the directory file in
49    incremental dumps.  The quoted string is not intended for human
50    consumption; it is intended only for unquote_string.  The quoting
51    is locale-independent, so that users needn't worry about locale
52    when reading directory files.  This means that we can't use
53    quotearg, as quotearg is locale-dependent and is meant for human
54    consumption.  */
55 char *
56 quote_copy_string (const char *string)
57 {
58   const char *source = string;
59   char *destination = 0;
60   char *buffer = 0;
61   int copying = 0;
62
63   while (*source)
64     {
65       int character = *source++;
66
67       switch (character)
68         {
69         case '\n': case '\\':
70           if (!copying)
71             {
72               size_t length = (source - string) - 1;
73
74               copying = 1;
75               buffer = xmalloc (length + 2 + 2 * strlen (source) + 1);
76               memcpy (buffer, string, length);
77               destination = buffer + length;
78             }
79           *destination++ = '\\';
80           *destination++ = character == '\\' ? '\\' : 'n';
81           break;
82
83         default:
84           if (copying)
85             *destination++ = character;
86           break;
87         }
88     }
89   if (copying)
90     {
91       *destination = '\0';
92       return buffer;
93     }
94   return 0;
95 }
96
97 /* Takes a quoted C string (like those produced by quote_copy_string)
98    and turns it back into the un-quoted original.  This is done in
99    place.  Returns 0 only if the string was not properly quoted, but
100    completes the unquoting anyway.
101                                                                            
102    This is used for reading the saved directory file in incremental
103    dumps.  It is used for decoding old `N' records (demangling names).
104    But also, it is used for decoding file arguments, would they come
105    from the shell or a -T file, and for decoding the --exclude
106    argument.  */
107 int
108 unquote_string (char *string)
109 {
110   int result = 1;
111   char *source = string;
112   char *destination = string;
113
114   /* Escape sequences other than \\ and \n are no longer generated by
115      quote_copy_string, but accept them for backwards compatibility,
116      and also because unquote_string is used for purposes other than
117      parsing the output of quote_copy_string.  */
118
119   while (*source)
120     if (*source == '\\')
121       switch (*++source)
122         {
123         case '\\':
124           *destination++ = '\\';
125           source++;
126           break;
127
128         case 'n':
129           *destination++ = '\n';
130           source++;
131           break;
132
133         case 't':
134           *destination++ = '\t';
135           source++;
136           break;
137
138         case 'f':
139           *destination++ = '\f';
140           source++;
141           break;
142
143         case 'b':
144           *destination++ = '\b';
145           source++;
146           break;
147
148         case 'r':
149           *destination++ = '\r';
150           source++;
151           break;
152
153         case '?':
154           *destination++ = 0177;
155           source++;
156           break;
157
158         case '0':
159         case '1':
160         case '2':
161         case '3':
162         case '4':
163         case '5':
164         case '6':
165         case '7':
166           {
167             int value = *source++ - '0';
168
169             if (*source < '0' || *source > '7')
170               {
171                 *destination++ = value;
172                 break;
173               }
174             value = value * 8 + *source++ - '0';
175             if (*source < '0' || *source > '7')
176               {
177                 *destination++ = value;
178                 break;
179               }
180             value = value * 8 + *source++ - '0';
181             *destination++ = value;
182             break;
183           }
184
185         default:
186           result = 0;
187           *destination++ = '\\';
188           if (*source)
189             *destination++ = *source++;
190           break;
191         }
192     else if (source != destination)
193       *destination++ = *source++;
194     else
195       source++, destination++;
196
197   if (source != destination)
198     *destination = '\0';
199   return result;
200 }
201 \f
202 /* Return nonzero if NAME contains ".." as a path name component.  */
203 int
204 contains_dot_dot (char const *name)
205 {
206   char const *p = name + FILESYSTEM_PREFIX_LEN (name);
207
208   for (;;)
209     {
210       if (p[0] == '.' && p[1] == '.' && (ISSLASH (p[2]) || !p[2]))
211         return 1;
212
213       do
214         {
215           if (! *p++)
216             return 0;
217         }
218       while (! ISSLASH (*p));
219
220       do
221         {
222           if (! *p++)
223             return 0;
224         }
225       while ( ISSLASH (*p));
226     }
227 }
228 \f
229 /* File handling.  */
230
231 /* Saved names in case backup needs to be undone.  */
232 static char *before_backup_name;
233 static char *after_backup_name;
234
235 /* Some implementations of rmdir let you remove the working directory.
236    Report an error with errno set to zero for obvious cases of this;
237    otherwise call rmdir.  */
238 static int
239 safer_rmdir (const char *path)
240 {
241   while (path[0] == '.' && ISSLASH (path[1]))
242     {
243       path++;
244
245       do path++;
246       while (ISSLASH (*path));
247     }
248
249   if (! path[0] || (path[0] == '.' && ! path[1]))
250     {
251       errno = 0;
252       return -1;
253     }
254
255   return rmdir (path);
256 }
257
258 /* Remove PATH.  If PATH is a directory, then if RECURSE is set remove
259    it recursively; otherwise, remove it only if it is empty.  Return 0
260    on error, with errno set; if PATH is obviously the working
261    directory return zero with errno set to zero.  */
262 int
263 remove_any_file (const char *path, int recurse)
264 {
265   /* Try unlink first if we are not root, as this saves us a system
266      call in the common case where we're removing a non-directory.  */
267   if (! we_are_root)
268     {
269       if (unlink (path) == 0)
270         return 1;
271       if (errno != EPERM)
272         return 0;
273     }
274
275   if (safer_rmdir (path) == 0)
276     return 1;
277
278   switch (errno)
279     {
280     case ENOTDIR:
281       return we_are_root && unlink (path) == 0;
282
283     case 0:
284     case EEXIST:
285 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
286     case ENOTEMPTY:
287 #endif
288       if (recurse)
289         {
290           char *directory = savedir (path);
291           char const *entry;
292           size_t entrylen;
293
294           if (! directory)
295             return 0;
296
297           for (entry = directory;
298                (entrylen = strlen (entry)) != 0;
299                entry += entrylen + 1)
300             {
301               char *path_buffer = new_name (path, entry);
302               int r = remove_any_file (path_buffer, 1);
303               int e = errno;
304               free (path_buffer);
305
306               if (! r)
307                 {
308                   free (directory);
309                   errno = e;
310                   return 0;
311                 }
312             }
313
314           free (directory);
315           return safer_rmdir (path) == 0;
316         }
317       break;
318     }
319
320   return 0;
321 }
322
323 /* Check if PATH already exists and make a backup of it right now.
324    Return success (nonzero) only if the backup in either unneeded, or
325    successful.  For now, directories are considered to never need
326    backup.  If ARCHIVE is nonzero, this is the archive and so, we do
327    not have to backup block or character devices, nor remote entities.  */
328 int
329 maybe_backup_file (const char *path, int archive)
330 {
331   struct stat file_stat;
332
333   /* Check if we really need to backup the file.  */
334
335   if (archive && _remdev (path))
336     return 1;
337
338   if (stat (path, &file_stat))
339     {
340       if (errno == ENOENT)
341         return 1;
342
343       stat_error (path);
344       return 0;
345     }
346
347   if (S_ISDIR (file_stat.st_mode))
348     return 1;
349
350   if (archive && (S_ISBLK (file_stat.st_mode) || S_ISCHR (file_stat.st_mode)))
351     return 1;
352
353   assign_string (&before_backup_name, path);
354
355   /* A run situation may exist between Emacs or other GNU programs trying to
356      make a backup for the same file simultaneously.  If theoretically
357      possible, real problems are unlikely.  Doing any better would require a
358      convention, GNU-wide, for all programs doing backups.  */
359
360   assign_string (&after_backup_name, 0);
361   after_backup_name = find_backup_file_name (path, backup_type);
362   if (! after_backup_name)
363     xalloc_die ();
364
365   if (rename (before_backup_name, after_backup_name) == 0)
366     {
367       if (verbose_option)
368         fprintf (stdlis, _("Renaming %s to %s\n"),
369                  quote_n (0, before_backup_name),
370                  quote_n (1, after_backup_name));
371       return 1;
372     }
373   else
374     {
375       /* The backup operation failed.  */
376       int e = errno;
377       ERROR ((0, e, _("%s: Cannot rename to %s"),
378               quotearg_colon (before_backup_name),
379               quote_n (1, after_backup_name)));
380       assign_string (&after_backup_name, 0);
381       return 0;
382     }
383 }
384
385 /* Try to restore the recently backed up file to its original name.
386    This is usually only needed after a failed extraction.  */
387 void
388 undo_last_backup (void)
389 {
390   if (after_backup_name)
391     {
392       if (rename (after_backup_name, before_backup_name) != 0)
393         {
394           int e = errno;
395           ERROR ((0, e, _("%s: Cannot rename to %s"),
396                   quotearg_colon (after_backup_name),
397                   quote_n (1, before_backup_name)));
398         }
399       if (verbose_option)
400         fprintf (stdlis, _("Renaming %s back to %s\n"),
401                  quote_n (0, after_backup_name),
402                  quote_n (1, before_backup_name));
403       assign_string (&after_backup_name, 0);
404     }
405 }
406
407 /* Depending on DEREF, apply either stat or lstat to (NAME, BUF).  */
408 int
409 deref_stat (int deref, char const *name, struct stat *buf)
410 {
411   return deref ? stat (name, buf) : lstat (name, buf);
412 }
413
414 /* A description of a working directory.  */
415 struct wd
416 {
417   char const *name;
418   int saved;
419   struct saved_cwd saved_cwd;
420 };
421
422 /* A vector of chdir targets.  wd[0] is the initial working directory.  */
423 static struct wd *wd;
424
425 /* The number of working directories in the vector.  */
426 static size_t wds;
427
428 /* The allocated size of the vector.  */
429 static size_t wd_alloc;
430
431 /* DIR is the operand of a -C option; add it to vector of chdir targets,
432    and return the index of its location.  */
433 int
434 chdir_arg (char const *dir)
435 {
436   if (wds == wd_alloc)
437     {
438       wd_alloc = 2 * (wd_alloc + 1);
439       wd = xrealloc (wd, sizeof *wd * wd_alloc);
440       if (! wds)
441         {
442           wd[wds].name = ".";
443           wd[wds].saved = 0;
444           wds++;
445         }
446     }
447
448   /* Optimize the common special case of the working directory,
449      or the working directory as a prefix.  */
450   if (dir[0])
451     {
452       while (dir[0] == '.' && ISSLASH (dir[1]))
453         for (dir += 2;  ISSLASH (*dir);  dir++)
454           continue;
455       if (! dir[dir[0] == '.'])
456         return wds - 1;
457     }
458
459   wd[wds].name = dir;
460   wd[wds].saved = 0;
461   return wds++;
462 }
463
464 /* Change to directory I.  If I is 0, change to the initial working
465    directory; otherwise, I must be a value returned by chdir_arg.  */
466 void
467 chdir_do (int i)
468 {
469   static int previous;
470
471   if (previous != i)
472     {
473       struct wd *prev = &wd[previous];
474       struct wd *curr = &wd[i];
475
476       if (! prev->saved)
477         {
478           prev->saved = 1;
479           if (save_cwd (&prev->saved_cwd) != 0)
480             FATAL_ERROR ((0, 0, _("Cannot save working directory")));
481         }
482
483       if (curr->saved)
484         {
485           if (restore_cwd (&curr->saved_cwd, curr->name, prev->name))
486             FATAL_ERROR ((0, 0, _("Cannot change working directory")));
487         }
488       else
489         {
490           if (i && ! ISSLASH (curr->name[0]))
491             chdir_do (i - 1);
492           if (chdir (curr->name) != 0)
493             chdir_fatal (curr->name);
494         }
495
496       previous = i;
497     }
498 }
499 \f
500 /* Decode MODE from its binary form in a stat structure, and encode it
501    into a 9-byte string STRING, terminated with a NUL.  */
502
503 void
504 decode_mode (mode_t mode, char *string)
505 {
506   *string++ = mode & S_IRUSR ? 'r' : '-';
507   *string++ = mode & S_IWUSR ? 'w' : '-';
508   *string++ = (mode & S_ISUID
509                ? (mode & S_IXUSR ? 's' : 'S')
510                : (mode & S_IXUSR ? 'x' : '-'));
511   *string++ = mode & S_IRGRP ? 'r' : '-';
512   *string++ = mode & S_IWGRP ? 'w' : '-';
513   *string++ = (mode & S_ISGID
514                ? (mode & S_IXGRP ? 's' : 'S')
515                : (mode & S_IXGRP ? 'x' : '-'));
516   *string++ = mode & S_IROTH ? 'r' : '-';
517   *string++ = mode & S_IWOTH ? 'w' : '-';
518   *string++ = (mode & S_ISVTX
519                ? (mode & S_IXOTH ? 't' : 'T')
520                : (mode & S_IXOTH ? 'x' : '-'));
521   *string = '\0';
522 }
523
524 /* Report an error associated with the system call CALL and the
525    optional name NAME.  */
526 static void
527 call_arg_error (char const *call, char const *name)
528 {
529   int e = errno;
530   ERROR ((0, e, _("%s: Cannot %s"), quotearg_colon (name), call));
531 }
532
533 /* Report a fatal error associated with the system call CALL and
534    the optional file name NAME.  */
535 static void
536 call_arg_fatal (char const *call, char const *name)
537 {
538   int e = errno;
539   FATAL_ERROR ((0, e, _("%s: Cannot %s"), quotearg_colon (name),  call));
540 }
541
542 /* Report a warning associated with the system call CALL and
543    the optional file name NAME.  */
544 static void
545 call_arg_warn (char const *call, char const *name)
546 {
547   int e = errno;
548   WARN ((0, e, _("%s: Warning: Cannot %s"), quotearg_colon (name), call));
549 }
550
551 void
552 chdir_fatal (char const *name)
553 {
554   call_arg_fatal ("chdir", name);
555 }
556
557 void
558 chmod_error_details (char const *name, mode_t mode)
559 {
560   int e = errno;
561   ERROR ((0, e, _("%s: Cannot change mode to 0%o"),
562           quotearg_colon (name), mode));
563 }
564
565 void
566 chown_error_details (char const *name, uid_t uid, gid_t gid)
567 {
568   int e = errno;
569   ERROR ((0, e, _("%s: Cannot change ownership to uid %lu, gid %lu"),
570           quotearg_colon (name), (unsigned long) uid, (unsigned long) gid));
571 }
572
573 void
574 close_error (char const *name)
575 {
576   call_arg_error ("close", name);
577 }
578
579 void
580 close_fatal (char const *name)
581 {
582   call_arg_fatal ("close", name);
583 }
584
585 void
586 close_warn (char const *name)
587 {
588   call_arg_warn ("close", name);
589 }
590
591 void
592 exec_fatal (char const *name)
593 {
594   call_arg_fatal ("exec", name);
595 }
596
597 void
598 link_error (char const *target, char const *source)
599 {
600   int e = errno;
601   ERROR ((0, e, _("%s: Cannot hard link to %s"),
602           quotearg_colon (source), quote_n (1, target)));
603 }
604
605 void
606 mkdir_error (char const *name)
607 {
608   call_arg_error ("mkdir", name);
609 }
610
611 void
612 mkfifo_error (char const *name)
613 {
614   call_arg_error ("mkfifo", name);
615 }
616
617 void
618 mknod_error (char const *name)
619 {
620   call_arg_error ("mknod", name);
621 }
622
623 void
624 open_error (char const *name)
625 {
626   call_arg_error ("open", name);
627 }
628
629 void
630 open_fatal (char const *name)
631 {
632   call_arg_fatal ("open", name);
633 }
634
635 void
636 open_warn (char const *name)
637 {
638   call_arg_warn ("open", name);
639 }
640
641 void
642 read_error (char const *name)
643 {
644   call_arg_error ("read", name);
645 }
646
647 void
648 read_error_details (char const *name, off_t offset, size_t size)
649 {
650   char buf[UINTMAX_STRSIZE_BOUND];
651   int e = errno;
652   ERROR ((0, e,
653           _("%s: Read error at byte %s, reading %lu bytes"),
654           quotearg_colon (name), STRINGIFY_BIGINT (offset, buf),
655           (unsigned long) size));
656 }
657
658 void
659 read_warn_details (char const *name, off_t offset, size_t size)
660 {
661   char buf[UINTMAX_STRSIZE_BOUND];
662   int e = errno;
663   WARN ((0, e,
664          _("%s: Warning: Read error at byte %s, reading %lu bytes"),
665          quotearg_colon (name), STRINGIFY_BIGINT (offset, buf),
666          (unsigned long) size));
667 }
668
669 void
670 read_fatal (char const *name)
671 {
672   call_arg_fatal ("read", name);
673 }
674
675 void
676 read_fatal_details (char const *name, off_t offset, size_t size)
677 {
678   char buf[UINTMAX_STRSIZE_BOUND];
679   int e = errno;
680   FATAL_ERROR ((0, e,
681                 _("%s: Read error at byte %s, reading %lu bytes"),
682                 quotearg_colon (name), STRINGIFY_BIGINT (offset, buf),
683                 (unsigned long) size));
684 }
685
686 void
687 readlink_error (char const *name)
688 {
689   call_arg_error ("readlink", name);
690 }
691
692 void
693 readlink_warn (char const *name)
694 {
695   call_arg_warn ("readlink", name);
696 }
697
698 void
699 savedir_error (char const *name)
700 {
701   call_arg_error ("savedir", name);
702 }
703
704 void
705 savedir_warn (char const *name)
706 {
707   call_arg_warn ("savedir", name);
708 }
709
710 void
711 seek_error (char const *name)
712 {
713   call_arg_error ("seek", name);
714 }
715
716 void
717 seek_error_details (char const *name, off_t offset)
718 {
719   char buf[UINTMAX_STRSIZE_BOUND];
720   int e = errno;
721   ERROR ((0, e, _("%s: Cannot seek to %s"),
722           quotearg_colon (name),
723           STRINGIFY_BIGINT (offset, buf)));
724 }
725
726 void
727 seek_warn (char const *name)
728 {
729   call_arg_warn ("seek", name);
730 }
731
732 void
733 seek_warn_details (char const *name, off_t offset)
734 {
735   char buf[UINTMAX_STRSIZE_BOUND];
736   int e = errno;
737   WARN ((0, e, _("%s: Warning: Cannot seek to %s"),
738          quotearg_colon (name),
739          STRINGIFY_BIGINT (offset, buf)));
740 }
741
742 void
743 symlink_error (char const *contents, char const *name)
744 {
745   int e = errno;
746   ERROR ((0, e, _("%s: Cannot create symlink to %s"),
747           quotearg_colon (name), quote_n (1, contents)));
748 }
749
750 void
751 stat_error (char const *name)
752 {
753   call_arg_error ("stat", name);
754 }
755
756 void
757 stat_warn (char const *name)
758 {
759   call_arg_warn ("stat", name);
760 }
761
762 void
763 truncate_error (char const *name)
764 {
765   call_arg_error ("truncate", name);
766 }
767
768 void
769 truncate_warn (char const *name)
770 {
771   call_arg_warn ("truncate", name);
772 }
773
774 void
775 unlink_error (char const *name)
776 {
777   call_arg_error ("unlink", name);
778 }
779
780 void
781 utime_error (char const *name)
782 {
783   call_arg_error ("utime", name);
784 }
785
786 void
787 waitpid_error (char const *name)
788 {
789   call_arg_error ("waitpid", name);
790 }
791
792 void
793 write_error (char const *name)
794 {
795   call_arg_error ("write", name);
796 }
797
798 void
799 write_error_details (char const *name, ssize_t status, size_t size)
800 {
801   if (status < 0)
802     write_error (name);
803   else
804     ERROR ((0, 0, _("%s: Wrote only %lu of %lu bytes"),
805             name, (unsigned long) status, (unsigned long) record_size));
806 }
807
808 void
809 write_fatal (char const *name)
810 {
811   call_arg_fatal ("write", name);
812 }
813
814 void
815 write_fatal_details (char const *name, ssize_t status, size_t size)
816 {
817   write_error_details (name, status, size);
818   fatal_exit ();
819 }
820
821
822 /* Fork, aborting if unsuccessful.  */
823 pid_t
824 xfork (void)
825 {
826   pid_t p = fork ();
827   if (p == (pid_t) -1)
828     call_arg_fatal ("fork", _("child process"));
829   return p;
830 }
831
832 /* Create a pipe, aborting if unsuccessful.  */
833 void
834 xpipe (int fd[2])
835 {
836   if (pipe (fd) < 0)
837     call_arg_fatal ("pipe", _("interprocess channel"));
838 }
839
840 /* Return an unambiguous printable representation, allocated in slot N,
841    for NAME, suitable for diagnostics.  */
842 char const *
843 quote_n (int n, char const *name)
844 {
845   return quotearg_n_style (n, locale_quoting_style, name);
846 }
847
848 /* Return an unambiguous printable representation of NAME, suitable
849    for diagnostics.  */
850 char const *
851 quote (char const *name)
852 {
853   return quote_n (0, name);
854 }