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