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