1 /* Miscellaneous functions, not really specific to GNU tar.
3 Copyright (C) 1988, 1992, 1994, 1995, 1996, 1997, 1999, 2000, 2001,
4 2003, 2004, 2005, 2006, 2007, 2009, 2010 Free Software Foundation, Inc.
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
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.
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. */
26 #include <unlinkdir.h>
33 # include <sys/filio.h>
36 #ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
37 # define DOUBLE_SLASH_IS_DISTINCT_ROOT 0
41 /* Handling strings. */
43 /* Assign STRING to a copy of VALUE if not zero, or to zero. If
44 STRING was nonzero, it is freed first. */
46 assign_string (char **string
, const char *value
)
50 *string
= value
? xstrdup (value
) : 0;
54 /* This function is currently unused; perhaps it should be removed? */
56 /* Allocate a copy of the string quoted as in C, and returns that. If
57 the string does not have to be quoted, it returns a null pointer.
58 The allocated copy should normally be freed with free() after the
59 caller is done with it.
61 This is used in one context only: generating the directory file in
62 incremental dumps. The quoted string is not intended for human
63 consumption; it is intended only for unquote_string. The quoting
64 is locale-independent, so that users needn't worry about locale
65 when reading directory files. This means that we can't use
66 quotearg, as quotearg is locale-dependent and is meant for human
69 quote_copy_string (const char *string
)
71 const char *source
= string
;
72 char *destination
= 0;
78 int character
= *source
++;
85 size_t length
= (source
- string
) - 1;
88 buffer
= xmalloc (length
+ 2 + 2 * strlen (source
) + 1);
89 memcpy (buffer
, string
, length
);
90 destination
= buffer
+ length
;
92 *destination
++ = '\\';
93 *destination
++ = character
== '\\' ? '\\' : 'n';
98 *destination
++ = character
;
111 /* Takes a quoted C string (like those produced by quote_copy_string)
112 and turns it back into the un-quoted original. This is done in
113 place. Returns 0 only if the string was not properly quoted, but
114 completes the unquoting anyway.
116 This is used for reading the saved directory file in incremental
117 dumps. It is used for decoding old `N' records (demangling names).
118 But also, it is used for decoding file arguments, would they come
119 from the shell or a -T file, and for decoding the --exclude
122 unquote_string (char *string
)
125 char *source
= string
;
126 char *destination
= string
;
128 /* Escape sequences other than \\ and \n are no longer generated by
129 quote_copy_string, but accept them for backwards compatibility,
130 and also because unquote_string is used for purposes other than
131 parsing the output of quote_copy_string. */
138 *destination
++ = '\\';
143 *destination
++ = '\a';
148 *destination
++ = '\b';
153 *destination
++ = '\f';
158 *destination
++ = '\n';
163 *destination
++ = '\r';
168 *destination
++ = '\t';
173 *destination
++ = '\v';
178 *destination
++ = 0177;
191 int value
= *source
++ - '0';
193 if (*source
< '0' || *source
> '7')
195 *destination
++ = value
;
198 value
= value
* 8 + *source
++ - '0';
199 if (*source
< '0' || *source
> '7')
201 *destination
++ = value
;
204 value
= value
* 8 + *source
++ - '0';
205 *destination
++ = value
;
211 *destination
++ = '\\';
213 *destination
++ = *source
++;
216 else if (source
!= destination
)
217 *destination
++ = *source
++;
219 source
++, destination
++;
221 if (source
!= destination
)
226 /* Zap trailing slashes. */
228 zap_slashes (char *name
)
232 if (!name
|| *name
== 0)
234 q
= name
+ strlen (name
) - 1;
235 while (q
> name
&& ISSLASH (*q
))
240 /* Normalize FILE_NAME by removing redundant slashes and "."
241 components, including redundant trailing slashes. Leave ".."
242 alone, as it may be significant in the presence of symlinks and on
243 platforms where "/.." != "/". Destructive version: modifies its
246 normalize_filename_x (char *file_name
)
248 char *name
= file_name
+ FILE_SYSTEM_PREFIX_LEN (file_name
);
253 /* Don't squeeze leading "//" to "/", on hosts where they're distinct. */
254 name
+= (DOUBLE_SLASH_IS_DISTINCT_ROOT
255 && ISSLASH (*name
) && ISSLASH (name
[1]) && ! ISSLASH (name
[2]));
257 /* Omit redundant leading "." components. */
258 for (q
= p
= name
; (*p
= *q
) == '.' && ISSLASH (q
[1]); p
+= !*q
)
259 for (q
+= 2; ISSLASH (*q
); q
++)
262 /* Copy components from Q to P, omitting redundant slashes and
263 internal "." components. */
264 while ((*p
++ = c
= *q
++) != '\0')
266 while (ISSLASH (q
[*q
== '.']))
267 q
+= (*q
== '.') + 1;
269 /* Omit redundant trailing "." component and slash. */
272 p
-= p
[-2] == '.' && ISSLASH (p
[-3]);
273 p
-= 2 < p
- name
&& ISSLASH (p
[-2]);
278 /* Normalize NAME by removing redundant slashes and "." components,
279 including redundant trailing slashes. Return a normalized
280 newly-allocated copy. */
283 normalize_filename (const char *name
)
287 if (IS_RELATIVE_FILE_NAME (name
))
289 /* Set COPY to the absolute file name if possible.
291 FIXME: There should be no need to get the absolute file name.
292 getcwd is slow, it might fail, and it does not necessarily
293 return a canonical name even when it succeeds. Perhaps we
294 can use dev+ino pairs instead of names? */
298 size_t copylen
= strlen (copy
);
299 bool need_separator
= ! (DOUBLE_SLASH_IS_DISTINCT_ROOT
300 && copylen
== 2 && ISSLASH (copy
[1]));
301 copy
= xrealloc (copy
, copylen
+ need_separator
+ strlen (name
) + 1);
302 copy
[copylen
] = DIRECTORY_SEPARATOR
;
303 strcpy (copy
+ copylen
+ need_separator
, name
);
306 WARN ((0, errno
, _("Cannot get working directory")));
310 copy
= xstrdup (name
);
311 normalize_filename_x (copy
);
317 replace_prefix (char **pname
, const char *samp
, size_t slen
,
318 const char *repl
, size_t rlen
)
321 size_t nlen
= strlen (name
);
322 if (nlen
> slen
&& memcmp (name
, samp
, slen
) == 0 && ISSLASH (name
[slen
]))
326 name
= xrealloc (name
, nlen
- slen
+ rlen
+ 1);
329 memmove (name
+ rlen
, name
+ slen
, nlen
- slen
+ 1);
330 memcpy (name
, repl
, rlen
);
335 /* Handling numbers. */
337 /* Output fraction and trailing digits appropriate for a nanoseconds
338 count equal to NS, but don't output unnecessary '.' or trailing
342 code_ns_fraction (int ns
, char *p
)
361 p
[--i
] = '0' + ns
% 10;
370 code_timespec (struct timespec t
, char sbuf
[TIMESPEC_STRSIZE_BOUND
])
375 bool negative
= s
< 0;
377 /* ignore invalid values of ns */
378 if (BILLION
<= ns
|| ns
< 0)
381 if (negative
&& ns
!= 0)
387 np
= umaxtostr (negative
? - (uintmax_t) s
: (uintmax_t) s
, sbuf
+ 1);
390 code_ns_fraction (ns
, sbuf
+ UINTMAX_STRSIZE_BOUND
);
396 /* Saved names in case backup needs to be undone. */
397 static char *before_backup_name
;
398 static char *after_backup_name
;
400 /* Return 1 if FILE_NAME is obviously "." or "/". */
402 must_be_dot_or_slash (char const *file_name
)
404 file_name
+= FILE_SYSTEM_PREFIX_LEN (file_name
);
406 if (ISSLASH (file_name
[0]))
409 if (ISSLASH (file_name
[1]))
411 else if (file_name
[1] == '.'
412 && ISSLASH (file_name
[2 + (file_name
[2] == '.')]))
413 file_name
+= 2 + (file_name
[2] == '.');
415 return ! file_name
[1];
419 while (file_name
[0] == '.' && ISSLASH (file_name
[1]))
422 while (ISSLASH (*file_name
))
426 return ! file_name
[0] || (file_name
[0] == '.' && ! file_name
[1]);
430 /* Some implementations of rmdir let you remove '.' or '/'.
431 Report an error with errno set to zero for obvious cases of this;
432 otherwise call rmdir. */
434 safer_rmdir (const char *file_name
)
436 if (must_be_dot_or_slash (file_name
))
442 return rmdir (file_name
);
445 /* Remove FILE_NAME, returning 1 on success. If FILE_NAME is a directory,
446 then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
447 recursively; otherwise, remove it only if it is empty. If FILE_NAME is
448 a directory that cannot be removed (e.g., because it is nonempty)
449 and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
450 Return 0 on error, with errno set; if FILE_NAME is obviously the working
451 directory return zero with errno set to zero. */
453 remove_any_file (const char *file_name
, enum remove_option option
)
455 /* Try unlink first if we cannot unlink directories, as this saves
456 us a system call in the common case where we're removing a
458 bool try_unlink_first
= cannot_unlink_dir ();
460 if (try_unlink_first
)
462 if (unlink (file_name
) == 0)
465 /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
466 directory without appropriate privileges, but many Linux
467 kernels return the more-sensible EISDIR. */
468 if (errno
!= EPERM
&& errno
!= EISDIR
)
472 if (safer_rmdir (file_name
) == 0)
478 return !try_unlink_first
&& unlink (file_name
) == 0;
482 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
487 case ORDINARY_REMOVE_OPTION
:
490 case WANT_DIRECTORY_REMOVE_OPTION
:
493 case RECURSIVE_REMOVE_OPTION
:
495 char *directory
= savedir (file_name
);
502 for (entry
= directory
;
503 (entrylen
= strlen (entry
)) != 0;
504 entry
+= entrylen
+ 1)
506 char *file_name_buffer
= new_name (file_name
, entry
);
507 int r
= remove_any_file (file_name_buffer
,
508 RECURSIVE_REMOVE_OPTION
);
510 free (file_name_buffer
);
521 return safer_rmdir (file_name
) == 0;
530 /* Check if FILE_NAME already exists and make a backup of it right now.
531 Return success (nonzero) only if the backup is either unneeded, or
532 successful. For now, directories are considered to never need
533 backup. If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
534 so, we do not have to backup block or character devices, nor remote
537 maybe_backup_file (const char *file_name
, bool this_is_the_archive
)
539 struct stat file_stat
;
541 assign_string (&before_backup_name
, file_name
);
543 /* A run situation may exist between Emacs or other GNU programs trying to
544 make a backup for the same file simultaneously. If theoretically
545 possible, real problems are unlikely. Doing any better would require a
546 convention, GNU-wide, for all programs doing backups. */
548 assign_string (&after_backup_name
, 0);
550 /* Check if we really need to backup the file. */
552 if (this_is_the_archive
&& _remdev (file_name
))
555 if (stat (file_name
, &file_stat
))
560 stat_error (file_name
);
564 if (S_ISDIR (file_stat
.st_mode
))
567 if (this_is_the_archive
568 && (S_ISBLK (file_stat
.st_mode
) || S_ISCHR (file_stat
.st_mode
)))
571 after_backup_name
= find_backup_file_name (file_name
, backup_type
);
572 if (! after_backup_name
)
575 if (rename (before_backup_name
, after_backup_name
) == 0)
578 fprintf (stdlis
, _("Renaming %s to %s\n"),
579 quote_n (0, before_backup_name
),
580 quote_n (1, after_backup_name
));
585 /* The backup operation failed. */
587 ERROR ((0, e
, _("%s: Cannot rename to %s"),
588 quotearg_colon (before_backup_name
),
589 quote_n (1, after_backup_name
)));
590 assign_string (&after_backup_name
, 0);
595 /* Try to restore the recently backed up file to its original name.
596 This is usually only needed after a failed extraction. */
598 undo_last_backup (void)
600 if (after_backup_name
)
602 if (rename (after_backup_name
, before_backup_name
) != 0)
605 ERROR ((0, e
, _("%s: Cannot rename to %s"),
606 quotearg_colon (after_backup_name
),
607 quote_n (1, before_backup_name
)));
610 fprintf (stdlis
, _("Renaming %s back to %s\n"),
611 quote_n (0, after_backup_name
),
612 quote_n (1, before_backup_name
));
613 assign_string (&after_backup_name
, 0);
617 /* Depending on DEREF, apply either stat or lstat to (NAME, BUF). */
619 deref_stat (bool deref
, char const *name
, struct stat
*buf
)
621 return deref
? stat (name
, buf
) : lstat (name
, buf
);
624 /* Set FD's (i.e., FILE's) access time to TIMESPEC[0]. If that's not
625 possible to do by itself, set its access and data modification
626 times to TIMESPEC[0] and TIMESPEC[1], respectively. */
628 set_file_atime (int fd
, char const *file
, struct timespec
const timespec
[2])
633 struct timeval timeval
;
634 timeval
.tv_sec
= timespec
[0].tv_sec
;
635 timeval
.tv_usec
= timespec
[0].tv_nsec
/ 1000;
636 if (ioctl (fd
, _FIOSATIME
, &timeval
) == 0)
641 return gl_futimens (fd
, file
, timespec
);
644 /* A description of a working directory. */
647 /* The directory's name. */
650 /* A negative value if no attempt has been made to save the
651 directory, 0 if it was saved successfully, and a positive errno
652 value if it was not saved successfully. */
655 /* The saved version of the directory, if ERR == 0. */
656 struct saved_cwd saved_cwd
;
659 /* A vector of chdir targets. wd[0] is the initial working directory. */
660 static struct wd
*wd
;
662 /* The number of working directories in the vector. */
663 static size_t wd_count
;
665 /* The allocated size of the vector. */
666 static size_t wd_alloc
;
676 /* DIR is the operand of a -C option; add it to vector of chdir targets,
677 and return the index of its location. */
679 chdir_arg (char const *dir
)
681 if (wd_count
== wd_alloc
)
686 wd
= xmalloc (sizeof *wd
* wd_alloc
);
689 wd
= x2nrealloc (wd
, &wd_alloc
, sizeof *wd
);
693 wd
[wd_count
].name
= ".";
694 wd
[wd_count
].err
= -1;
699 /* Optimize the common special case of the working directory,
700 or the working directory as a prefix. */
703 while (dir
[0] == '.' && ISSLASH (dir
[1]))
704 for (dir
+= 2; ISSLASH (*dir
); dir
++)
706 if (! dir
[dir
[0] == '.'])
710 wd
[wd_count
].name
= dir
;
711 wd
[wd_count
].err
= -1;
715 /* Change to directory I. If I is 0, change to the initial working
716 directory; otherwise, I must be a value returned by chdir_arg. */
724 struct wd
*prev
= &wd
[previous
];
725 struct wd
*curr
= &wd
[i
];
730 if (save_cwd (&prev
->saved_cwd
) != 0)
732 else if (0 <= prev
->saved_cwd
.desc
)
734 /* Make sure we still have at least one descriptor available. */
735 int fd1
= prev
->saved_cwd
.desc
;
739 else if (errno
== EMFILE
)
741 /* Force restore_cwd to use chdir_long. */
743 prev
->saved_cwd
.desc
= -1;
744 prev
->saved_cwd
.name
= xgetcwd ();
745 if (! prev
->saved_cwd
.name
)
756 if (err
== 0 && restore_cwd (&curr
->saved_cwd
) != 0)
759 FATAL_ERROR ((0, err
, _("Cannot restore working directory")));
763 if (i
&& ! ISSLASH (curr
->name
[0]))
765 if (chdir (curr
->name
) != 0)
766 chdir_fatal (curr
->name
);
774 close_diag (char const *name
)
776 if (ignore_failed_read_option
)
783 open_diag (char const *name
)
785 if (ignore_failed_read_option
)
792 read_diag_details (char const *name
, off_t offset
, size_t size
)
794 if (ignore_failed_read_option
)
795 read_warn_details (name
, offset
, size
);
797 read_error_details (name
, offset
, size
);
801 readlink_diag (char const *name
)
803 if (ignore_failed_read_option
)
804 readlink_warn (name
);
806 readlink_error (name
);
810 savedir_diag (char const *name
)
812 if (ignore_failed_read_option
)
815 savedir_error (name
);
819 seek_diag_details (char const *name
, off_t offset
)
821 if (ignore_failed_read_option
)
822 seek_warn_details (name
, offset
);
824 seek_error_details (name
, offset
);
828 stat_diag (char const *name
)
830 if (ignore_failed_read_option
)
837 file_removed_diag (const char *name
, bool top_level
,
838 void (*diagfn
) (char const *name
))
840 if (!top_level
&& errno
== ENOENT
)
842 WARNOPT (WARN_FILE_REMOVED
,
843 (0, 0, _("%s: File removed before we read it"),
844 quotearg_colon (name
)));
845 set_exit_status (TAREXIT_DIFFERS
);
852 dir_removed_diag (const char *name
, bool top_level
,
853 void (*diagfn
) (char const *name
))
855 if (!top_level
&& errno
== ENOENT
)
857 WARNOPT (WARN_FILE_REMOVED
,
858 (0, 0, _("%s: Directory removed before we read it"),
859 quotearg_colon (name
)));
860 set_exit_status (TAREXIT_DIFFERS
);
867 write_fatal_details (char const *name
, ssize_t status
, size_t size
)
869 write_error_details (name
, status
, size
);
873 /* Fork, aborting if unsuccessful. */
879 call_arg_fatal ("fork", _("child process"));
883 /* Create a pipe, aborting if unsuccessful. */
888 call_arg_fatal ("pipe", _("interprocess channel"));
891 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
892 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
893 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
897 ptr_align (void *ptr
, size_t alignment
)
900 char *p1
= p0
+ alignment
- 1;
901 return p1
- (size_t) p1
% alignment
;
904 /* Return the address of a page-aligned buffer of at least SIZE bytes.
905 The caller should free *PTR when done with the buffer. */
908 page_aligned_alloc (void **ptr
, size_t size
)
910 size_t alignment
= getpagesize ();
911 size_t size1
= size
+ alignment
;
914 *ptr
= xmalloc (size1
);
915 return ptr_align (*ptr
, alignment
);
922 char *buffer
; /* directory, `/', and directory member */
923 size_t buffer_size
; /* allocated size of name_buffer */
924 size_t dir_length
; /* length of directory part in buffer */
928 namebuf_create (const char *dir
)
930 namebuf_t buf
= xmalloc (sizeof (*buf
));
931 buf
->buffer_size
= strlen (dir
) + 2;
932 buf
->buffer
= xmalloc (buf
->buffer_size
);
933 strcpy (buf
->buffer
, dir
);
934 buf
->dir_length
= strlen (buf
->buffer
);
935 if (!ISSLASH (buf
->buffer
[buf
->dir_length
- 1]))
936 buf
->buffer
[buf
->dir_length
++] = DIRECTORY_SEPARATOR
;
941 namebuf_free (namebuf_t buf
)
948 namebuf_name (namebuf_t buf
, const char *name
)
950 size_t len
= strlen (name
);
951 while (buf
->dir_length
+ len
+ 1 >= buf
->buffer_size
)
952 buf
->buffer
= x2realloc (buf
->buffer
, &buf
->buffer_size
);
953 strcpy (buf
->buffer
+ buf
->dir_length
, name
);