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;
53 /* Allocate a copy of the string quoted as in C, and returns that. If
54 the string does not have to be quoted, it returns a null pointer.
55 The allocated copy should normally be freed with free() after the
56 caller is done with it.
58 This is used in one context only: generating the directory file in
59 incremental dumps. The quoted string is not intended for human
60 consumption; it is intended only for unquote_string. The quoting
61 is locale-independent, so that users needn't worry about locale
62 when reading directory files. This means that we can't use
63 quotearg, as quotearg is locale-dependent and is meant for human
66 quote_copy_string (const char *string
)
68 const char *source
= string
;
69 char *destination
= 0;
75 int character
= *source
++;
82 size_t length
= (source
- string
) - 1;
85 buffer
= xmalloc (length
+ 2 + 2 * strlen (source
) + 1);
86 memcpy (buffer
, string
, length
);
87 destination
= buffer
+ length
;
89 *destination
++ = '\\';
90 *destination
++ = character
== '\\' ? '\\' : 'n';
95 *destination
++ = character
;
107 /* Takes a quoted C string (like those produced by quote_copy_string)
108 and turns it back into the un-quoted original. This is done in
109 place. Returns 0 only if the string was not properly quoted, but
110 completes the unquoting anyway.
112 This is used for reading the saved directory file in incremental
113 dumps. It is used for decoding old `N' records (demangling names).
114 But also, it is used for decoding file arguments, would they come
115 from the shell or a -T file, and for decoding the --exclude
118 unquote_string (char *string
)
121 char *source
= string
;
122 char *destination
= string
;
124 /* Escape sequences other than \\ and \n are no longer generated by
125 quote_copy_string, but accept them for backwards compatibility,
126 and also because unquote_string is used for purposes other than
127 parsing the output of quote_copy_string. */
134 *destination
++ = '\\';
139 *destination
++ = '\a';
144 *destination
++ = '\b';
149 *destination
++ = '\f';
154 *destination
++ = '\n';
159 *destination
++ = '\r';
164 *destination
++ = '\t';
169 *destination
++ = '\v';
174 *destination
++ = 0177;
187 int value
= *source
++ - '0';
189 if (*source
< '0' || *source
> '7')
191 *destination
++ = value
;
194 value
= value
* 8 + *source
++ - '0';
195 if (*source
< '0' || *source
> '7')
197 *destination
++ = value
;
200 value
= value
* 8 + *source
++ - '0';
201 *destination
++ = value
;
207 *destination
++ = '\\';
209 *destination
++ = *source
++;
212 else if (source
!= destination
)
213 *destination
++ = *source
++;
215 source
++, destination
++;
217 if (source
!= destination
)
222 /* Zap trailing slashes. */
224 zap_slashes (char *name
)
228 if (!name
|| *name
== 0)
230 q
= name
+ strlen (name
) - 1;
231 while (q
> name
&& ISSLASH (*q
))
236 /* Normalize FILE_NAME by removing redundant slashes and "."
237 components, including redundant trailing slashes. Leave ".."
238 alone, as it may be significant in the presence of symlinks and on
239 platforms where "/.." != "/". Destructive version: modifies its
242 normalize_filename_x (char *file_name
)
244 char *name
= file_name
+ FILE_SYSTEM_PREFIX_LEN (file_name
);
249 /* Don't squeeze leading "//" to "/", on hosts where they're distinct. */
250 name
+= (DOUBLE_SLASH_IS_DISTINCT_ROOT
251 && ISSLASH (*name
) && ISSLASH (name
[1]) && ! ISSLASH (name
[2]));
253 /* Omit redundant leading "." components. */
254 for (q
= p
= name
; (*p
= *q
) == '.' && ISSLASH (q
[1]); p
+= !*q
)
255 for (q
+= 2; ISSLASH (*q
); q
++)
258 /* Copy components from Q to P, omitting redundant slashes and
259 internal "." components. */
260 while ((*p
++ = c
= *q
++) != '\0')
262 while (ISSLASH (q
[*q
== '.']))
263 q
+= (*q
== '.') + 1;
265 /* Omit redundant trailing "." component and slash. */
268 p
-= p
[-2] == '.' && ISSLASH (p
[-3]);
269 p
-= 2 < p
- name
&& ISSLASH (p
[-2]);
274 /* Normalize NAME by removing redundant slashes and "." components,
275 including redundant trailing slashes. Return a normalized
276 newly-allocated copy. */
279 normalize_filename (const char *name
)
281 char *copy
= xstrdup (name
);
282 normalize_filename_x (copy
);
288 replace_prefix (char **pname
, const char *samp
, size_t slen
,
289 const char *repl
, size_t rlen
)
292 size_t nlen
= strlen (name
);
293 if (nlen
> slen
&& memcmp (name
, samp
, slen
) == 0 && ISSLASH (name
[slen
]))
297 name
= xrealloc (name
, nlen
- slen
+ rlen
+ 1);
300 memmove (name
+ rlen
, name
+ slen
, nlen
- slen
+ 1);
301 memcpy (name
, repl
, rlen
);
306 /* Handling numbers. */
308 /* Output fraction and trailing digits appropriate for a nanoseconds
309 count equal to NS, but don't output unnecessary '.' or trailing
313 code_ns_fraction (int ns
, char *p
)
332 p
[--i
] = '0' + ns
% 10;
341 code_timespec (struct timespec t
, char sbuf
[TIMESPEC_STRSIZE_BOUND
])
346 bool negative
= s
< 0;
348 /* ignore invalid values of ns */
349 if (BILLION
<= ns
|| ns
< 0)
352 if (negative
&& ns
!= 0)
358 np
= umaxtostr (negative
? - (uintmax_t) s
: (uintmax_t) s
, sbuf
+ 1);
361 code_ns_fraction (ns
, sbuf
+ UINTMAX_STRSIZE_BOUND
);
367 /* Saved names in case backup needs to be undone. */
368 static char *before_backup_name
;
369 static char *after_backup_name
;
371 /* Return 1 if FILE_NAME is obviously "." or "/". */
373 must_be_dot_or_slash (char const *file_name
)
375 file_name
+= FILE_SYSTEM_PREFIX_LEN (file_name
);
377 if (ISSLASH (file_name
[0]))
380 if (ISSLASH (file_name
[1]))
382 else if (file_name
[1] == '.'
383 && ISSLASH (file_name
[2 + (file_name
[2] == '.')]))
384 file_name
+= 2 + (file_name
[2] == '.');
386 return ! file_name
[1];
390 while (file_name
[0] == '.' && ISSLASH (file_name
[1]))
393 while (ISSLASH (*file_name
))
397 return ! file_name
[0] || (file_name
[0] == '.' && ! file_name
[1]);
401 /* Some implementations of rmdir let you remove '.' or '/'.
402 Report an error with errno set to zero for obvious cases of this;
403 otherwise call rmdir. */
405 safer_rmdir (const char *file_name
)
407 if (must_be_dot_or_slash (file_name
))
413 return rmdir (file_name
);
416 /* Remove FILE_NAME, returning 1 on success. If FILE_NAME is a directory,
417 then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
418 recursively; otherwise, remove it only if it is empty. If FILE_NAME is
419 a directory that cannot be removed (e.g., because it is nonempty)
420 and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
421 Return 0 on error, with errno set; if FILE_NAME is obviously the working
422 directory return zero with errno set to zero. */
424 remove_any_file (const char *file_name
, enum remove_option option
)
426 /* Try unlink first if we cannot unlink directories, as this saves
427 us a system call in the common case where we're removing a
429 bool try_unlink_first
= cannot_unlink_dir ();
431 if (try_unlink_first
)
433 if (unlink (file_name
) == 0)
436 /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
437 directory without appropriate privileges, but many Linux
438 kernels return the more-sensible EISDIR. */
439 if (errno
!= EPERM
&& errno
!= EISDIR
)
443 if (safer_rmdir (file_name
) == 0)
449 return !try_unlink_first
&& unlink (file_name
) == 0;
453 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
458 case ORDINARY_REMOVE_OPTION
:
461 case WANT_DIRECTORY_REMOVE_OPTION
:
464 case RECURSIVE_REMOVE_OPTION
:
466 char *directory
= savedir (file_name
);
473 for (entry
= directory
;
474 (entrylen
= strlen (entry
)) != 0;
475 entry
+= entrylen
+ 1)
477 char *file_name_buffer
= new_name (file_name
, entry
);
478 int r
= remove_any_file (file_name_buffer
,
479 RECURSIVE_REMOVE_OPTION
);
481 free (file_name_buffer
);
492 return safer_rmdir (file_name
) == 0;
501 /* Check if FILE_NAME already exists and make a backup of it right now.
502 Return success (nonzero) only if the backup is either unneeded, or
503 successful. For now, directories are considered to never need
504 backup. If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
505 so, we do not have to backup block or character devices, nor remote
508 maybe_backup_file (const char *file_name
, bool this_is_the_archive
)
510 struct stat file_stat
;
512 assign_string (&before_backup_name
, file_name
);
514 /* A run situation may exist between Emacs or other GNU programs trying to
515 make a backup for the same file simultaneously. If theoretically
516 possible, real problems are unlikely. Doing any better would require a
517 convention, GNU-wide, for all programs doing backups. */
519 assign_string (&after_backup_name
, 0);
521 /* Check if we really need to backup the file. */
523 if (this_is_the_archive
&& _remdev (file_name
))
526 if (stat (file_name
, &file_stat
))
531 stat_error (file_name
);
535 if (S_ISDIR (file_stat
.st_mode
))
538 if (this_is_the_archive
539 && (S_ISBLK (file_stat
.st_mode
) || S_ISCHR (file_stat
.st_mode
)))
542 after_backup_name
= find_backup_file_name (file_name
, backup_type
);
543 if (! after_backup_name
)
546 if (rename (before_backup_name
, after_backup_name
) == 0)
549 fprintf (stdlis
, _("Renaming %s to %s\n"),
550 quote_n (0, before_backup_name
),
551 quote_n (1, after_backup_name
));
556 /* The backup operation failed. */
558 ERROR ((0, e
, _("%s: Cannot rename to %s"),
559 quotearg_colon (before_backup_name
),
560 quote_n (1, after_backup_name
)));
561 assign_string (&after_backup_name
, 0);
566 /* Try to restore the recently backed up file to its original name.
567 This is usually only needed after a failed extraction. */
569 undo_last_backup (void)
571 if (after_backup_name
)
573 if (rename (after_backup_name
, before_backup_name
) != 0)
576 ERROR ((0, e
, _("%s: Cannot rename to %s"),
577 quotearg_colon (after_backup_name
),
578 quote_n (1, before_backup_name
)));
581 fprintf (stdlis
, _("Renaming %s back to %s\n"),
582 quote_n (0, after_backup_name
),
583 quote_n (1, before_backup_name
));
584 assign_string (&after_backup_name
, 0);
588 /* Depending on DEREF, apply either stat or lstat to (NAME, BUF). */
590 deref_stat (bool deref
, char const *name
, struct stat
*buf
)
592 return deref
? stat (name
, buf
) : lstat (name
, buf
);
595 /* Set FD's (i.e., FILE's) access time to TIMESPEC[0]. If that's not
596 possible to do by itself, set its access and data modification
597 times to TIMESPEC[0] and TIMESPEC[1], respectively. */
599 set_file_atime (int fd
, char const *file
, struct timespec
const timespec
[2])
604 struct timeval timeval
;
605 timeval
.tv_sec
= timespec
[0].tv_sec
;
606 timeval
.tv_usec
= timespec
[0].tv_nsec
/ 1000;
607 if (ioctl (fd
, _FIOSATIME
, &timeval
) == 0)
612 return gl_futimens (fd
, file
, timespec
);
615 /* A description of a working directory. */
620 struct saved_cwd saved_cwd
;
623 /* A vector of chdir targets. wd[0] is the initial working directory. */
624 static struct wd
*wd
;
626 /* The number of working directories in the vector. */
627 static size_t wd_count
;
629 /* The allocated size of the vector. */
630 static size_t wd_alloc
;
640 /* DIR is the operand of a -C option; add it to vector of chdir targets,
641 and return the index of its location. */
643 chdir_arg (char const *dir
)
645 if (wd_count
== wd_alloc
)
650 wd
= xmalloc (sizeof *wd
* wd_alloc
);
653 wd
= x2nrealloc (wd
, &wd_alloc
, sizeof *wd
);
657 wd
[wd_count
].name
= ".";
658 wd
[wd_count
].saved
= 0;
663 /* Optimize the common special case of the working directory,
664 or the working directory as a prefix. */
667 while (dir
[0] == '.' && ISSLASH (dir
[1]))
668 for (dir
+= 2; ISSLASH (*dir
); dir
++)
670 if (! dir
[dir
[0] == '.'])
674 wd
[wd_count
].name
= dir
;
675 wd
[wd_count
].saved
= 0;
679 /* Change to directory I. If I is 0, change to the initial working
680 directory; otherwise, I must be a value returned by chdir_arg. */
688 struct wd
*prev
= &wd
[previous
];
689 struct wd
*curr
= &wd
[i
];
695 if (save_cwd (&prev
->saved_cwd
) != 0)
697 else if (0 <= prev
->saved_cwd
.desc
)
699 /* Make sure we still have at least one descriptor available. */
700 int fd1
= prev
->saved_cwd
.desc
;
704 else if (errno
== EMFILE
)
706 /* Force restore_cwd to use chdir_long. */
708 prev
->saved_cwd
.desc
= -1;
709 prev
->saved_cwd
.name
= xgetcwd ();
710 if (! prev
->saved_cwd
.name
)
718 FATAL_ERROR ((0, err
, _("Cannot save working directory")));
723 if (restore_cwd (&curr
->saved_cwd
))
724 FATAL_ERROR ((0, 0, _("Cannot change working directory")));
728 if (i
&& ! ISSLASH (curr
->name
[0]))
730 if (chdir (curr
->name
) != 0)
731 chdir_fatal (curr
->name
);
739 close_diag (char const *name
)
741 if (ignore_failed_read_option
)
748 open_diag (char const *name
)
750 if (ignore_failed_read_option
)
757 read_diag_details (char const *name
, off_t offset
, size_t size
)
759 if (ignore_failed_read_option
)
760 read_warn_details (name
, offset
, size
);
762 read_error_details (name
, offset
, size
);
766 readlink_diag (char const *name
)
768 if (ignore_failed_read_option
)
769 readlink_warn (name
);
771 readlink_error (name
);
775 savedir_diag (char const *name
)
777 if (ignore_failed_read_option
)
780 savedir_error (name
);
784 seek_diag_details (char const *name
, off_t offset
)
786 if (ignore_failed_read_option
)
787 seek_warn_details (name
, offset
);
789 seek_error_details (name
, offset
);
793 stat_diag (char const *name
)
795 if (ignore_failed_read_option
)
802 file_removed_diag (const char *name
, bool top_level
,
803 void (*diagfn
) (char const *name
))
805 if (!top_level
&& errno
== ENOENT
)
807 WARNOPT (WARN_FILE_REMOVED
,
808 (0, 0, _("%s: File removed before we read it"),
809 quotearg_colon (name
)));
810 set_exit_status (TAREXIT_DIFFERS
);
817 dir_removed_diag (const char *name
, bool top_level
,
818 void (*diagfn
) (char const *name
))
820 if (!top_level
&& errno
== ENOENT
)
822 WARNOPT (WARN_FILE_REMOVED
,
823 (0, 0, _("%s: Directory removed before we read it"),
824 quotearg_colon (name
)));
825 set_exit_status (TAREXIT_DIFFERS
);
832 write_fatal_details (char const *name
, ssize_t status
, size_t size
)
834 write_error_details (name
, status
, size
);
838 /* Fork, aborting if unsuccessful. */
844 call_arg_fatal ("fork", _("child process"));
848 /* Create a pipe, aborting if unsuccessful. */
853 call_arg_fatal ("pipe", _("interprocess channel"));
856 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
857 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
858 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
862 ptr_align (void *ptr
, size_t alignment
)
865 char *p1
= p0
+ alignment
- 1;
866 return p1
- (size_t) p1
% alignment
;
869 /* Return the address of a page-aligned buffer of at least SIZE bytes.
870 The caller should free *PTR when done with the buffer. */
873 page_aligned_alloc (void **ptr
, size_t size
)
875 size_t alignment
= getpagesize ();
876 size_t size1
= size
+ alignment
;
879 *ptr
= xmalloc (size1
);
880 return ptr_align (*ptr
, alignment
);
887 char *buffer
; /* directory, `/', and directory member */
888 size_t buffer_size
; /* allocated size of name_buffer */
889 size_t dir_length
; /* length of directory part in buffer */
893 namebuf_create (const char *dir
)
895 namebuf_t buf
= xmalloc (sizeof (*buf
));
896 buf
->buffer_size
= strlen (dir
) + 2;
897 buf
->buffer
= xmalloc (buf
->buffer_size
);
898 strcpy (buf
->buffer
, dir
);
899 buf
->dir_length
= strlen (buf
->buffer
);
900 if (!ISSLASH (buf
->buffer
[buf
->dir_length
- 1]))
901 buf
->buffer
[buf
->dir_length
++] = DIRECTORY_SEPARATOR
;
906 namebuf_free (namebuf_t buf
)
913 namebuf_name (namebuf_t buf
, const char *name
)
915 size_t len
= strlen (name
);
916 while (buf
->dir_length
+ len
+ 1 >= buf
->buffer_size
)
917 buf
->buffer
= x2realloc (buf
->buffer
, &buf
->buffer_size
);
918 strcpy (buf
->buffer
+ buf
->dir_length
, name
);