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 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>
28 #include <canonicalize.h>
34 # include <sys/filio.h>
38 /* Handling strings. */
40 /* Assign STRING to a copy of VALUE if not zero, or to zero. If
41 STRING was nonzero, it is freed first. */
43 assign_string (char **string
, const char *value
)
47 *string
= value
? xstrdup (value
) : 0;
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.
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
63 quote_copy_string (const char *string
)
65 const char *source
= string
;
66 char *destination
= 0;
72 int character
= *source
++;
79 size_t length
= (source
- string
) - 1;
82 buffer
= xmalloc (length
+ 2 + 2 * strlen (source
) + 1);
83 memcpy (buffer
, string
, length
);
84 destination
= buffer
+ length
;
86 *destination
++ = '\\';
87 *destination
++ = character
== '\\' ? '\\' : 'n';
92 *destination
++ = character
;
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.
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
115 unquote_string (char *string
)
118 char *source
= string
;
119 char *destination
= string
;
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. */
131 *destination
++ = '\\';
136 *destination
++ = '\a';
141 *destination
++ = '\b';
146 *destination
++ = '\f';
151 *destination
++ = '\n';
156 *destination
++ = '\r';
161 *destination
++ = '\t';
166 *destination
++ = '\v';
171 *destination
++ = 0177;
184 int value
= *source
++ - '0';
186 if (*source
< '0' || *source
> '7')
188 *destination
++ = value
;
191 value
= value
* 8 + *source
++ - '0';
192 if (*source
< '0' || *source
> '7')
194 *destination
++ = value
;
197 value
= value
* 8 + *source
++ - '0';
198 *destination
++ = value
;
204 *destination
++ = '\\';
206 *destination
++ = *source
++;
209 else if (source
!= destination
)
210 *destination
++ = *source
++;
212 source
++, destination
++;
214 if (source
!= destination
)
219 /* Zap trailing slashes. */
221 zap_slashes (char *name
)
225 if (!name
|| *name
== 0)
227 q
= name
+ strlen (name
) - 1;
228 while (q
> name
&& ISSLASH (*q
))
234 normalize_filename (const char *name
)
236 return zap_slashes (canonicalize_filename_mode (name
, CAN_MISSING
));
241 replace_prefix (char **pname
, const char *samp
, size_t slen
,
242 const char *repl
, size_t rlen
)
245 size_t nlen
= strlen (name
);
246 if (nlen
> slen
&& memcmp (name
, samp
, slen
) == 0 && ISSLASH (name
[slen
]))
250 name
= xrealloc (name
, nlen
- slen
+ rlen
+ 1);
253 memmove (name
+ rlen
, name
+ slen
, nlen
- slen
+ 1);
254 memcpy (name
, repl
, rlen
);
259 /* Handling numbers. */
261 /* Output fraction and trailing digits appropriate for a nanoseconds
262 count equal to NS, but don't output unnecessary '.' or trailing
266 code_ns_fraction (int ns
, char *p
)
285 p
[--i
] = '0' + ns
% 10;
294 code_timespec (struct timespec t
, char sbuf
[TIMESPEC_STRSIZE_BOUND
])
299 bool negative
= s
< 0;
301 /* ignore invalid values of ns */
302 if (BILLION
<= ns
|| ns
< 0)
305 if (negative
&& ns
!= 0)
311 np
= umaxtostr (negative
? - (uintmax_t) s
: (uintmax_t) s
, sbuf
+ 1);
314 code_ns_fraction (ns
, sbuf
+ UINTMAX_STRSIZE_BOUND
);
320 /* Saved names in case backup needs to be undone. */
321 static char *before_backup_name
;
322 static char *after_backup_name
;
324 /* Return 1 if FILE_NAME is obviously "." or "/". */
326 must_be_dot_or_slash (char const *file_name
)
328 file_name
+= FILE_SYSTEM_PREFIX_LEN (file_name
);
330 if (ISSLASH (file_name
[0]))
333 if (ISSLASH (file_name
[1]))
335 else if (file_name
[1] == '.'
336 && ISSLASH (file_name
[2 + (file_name
[2] == '.')]))
337 file_name
+= 2 + (file_name
[2] == '.');
339 return ! file_name
[1];
343 while (file_name
[0] == '.' && ISSLASH (file_name
[1]))
346 while (ISSLASH (*file_name
))
350 return ! file_name
[0] || (file_name
[0] == '.' && ! file_name
[1]);
354 /* Some implementations of rmdir let you remove '.' or '/'.
355 Report an error with errno set to zero for obvious cases of this;
356 otherwise call rmdir. */
358 safer_rmdir (const char *file_name
)
360 if (must_be_dot_or_slash (file_name
))
366 return rmdir (file_name
);
369 /* Remove FILE_NAME, returning 1 on success. If FILE_NAME is a directory,
370 then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
371 recursively; otherwise, remove it only if it is empty. If FILE_NAME is
372 a directory that cannot be removed (e.g., because it is nonempty)
373 and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
374 Return 0 on error, with errno set; if FILE_NAME is obviously the working
375 directory return zero with errno set to zero. */
377 remove_any_file (const char *file_name
, enum remove_option option
)
379 /* Try unlink first if we cannot unlink directories, as this saves
380 us a system call in the common case where we're removing a
382 bool try_unlink_first
= cannot_unlink_dir ();
384 if (try_unlink_first
)
386 if (unlink (file_name
) == 0)
389 /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
390 directory without appropriate privileges, but many Linux
391 kernels return the more-sensible EISDIR. */
392 if (errno
!= EPERM
&& errno
!= EISDIR
)
396 if (safer_rmdir (file_name
) == 0)
402 return !try_unlink_first
&& unlink (file_name
) == 0;
406 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
411 case ORDINARY_REMOVE_OPTION
:
414 case WANT_DIRECTORY_REMOVE_OPTION
:
417 case RECURSIVE_REMOVE_OPTION
:
419 char *directory
= savedir (file_name
);
426 for (entry
= directory
;
427 (entrylen
= strlen (entry
)) != 0;
428 entry
+= entrylen
+ 1)
430 char *file_name_buffer
= new_name (file_name
, entry
);
431 int r
= remove_any_file (file_name_buffer
,
432 RECURSIVE_REMOVE_OPTION
);
434 free (file_name_buffer
);
445 return safer_rmdir (file_name
) == 0;
454 /* Check if FILE_NAME already exists and make a backup of it right now.
455 Return success (nonzero) only if the backup is either unneeded, or
456 successful. For now, directories are considered to never need
457 backup. If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
458 so, we do not have to backup block or character devices, nor remote
461 maybe_backup_file (const char *file_name
, bool this_is_the_archive
)
463 struct stat file_stat
;
465 assign_string (&before_backup_name
, file_name
);
467 /* A run situation may exist between Emacs or other GNU programs trying to
468 make a backup for the same file simultaneously. If theoretically
469 possible, real problems are unlikely. Doing any better would require a
470 convention, GNU-wide, for all programs doing backups. */
472 assign_string (&after_backup_name
, 0);
474 /* Check if we really need to backup the file. */
476 if (this_is_the_archive
&& _remdev (file_name
))
479 if (stat (file_name
, &file_stat
))
484 stat_error (file_name
);
488 if (S_ISDIR (file_stat
.st_mode
))
491 if (this_is_the_archive
492 && (S_ISBLK (file_stat
.st_mode
) || S_ISCHR (file_stat
.st_mode
)))
495 after_backup_name
= find_backup_file_name (file_name
, backup_type
);
496 if (! after_backup_name
)
499 if (rename (before_backup_name
, after_backup_name
) == 0)
502 fprintf (stdlis
, _("Renaming %s to %s\n"),
503 quote_n (0, before_backup_name
),
504 quote_n (1, after_backup_name
));
509 /* The backup operation failed. */
511 ERROR ((0, e
, _("%s: Cannot rename to %s"),
512 quotearg_colon (before_backup_name
),
513 quote_n (1, after_backup_name
)));
514 assign_string (&after_backup_name
, 0);
519 /* Try to restore the recently backed up file to its original name.
520 This is usually only needed after a failed extraction. */
522 undo_last_backup (void)
524 if (after_backup_name
)
526 if (rename (after_backup_name
, before_backup_name
) != 0)
529 ERROR ((0, e
, _("%s: Cannot rename to %s"),
530 quotearg_colon (after_backup_name
),
531 quote_n (1, before_backup_name
)));
534 fprintf (stdlis
, _("Renaming %s back to %s\n"),
535 quote_n (0, after_backup_name
),
536 quote_n (1, before_backup_name
));
537 assign_string (&after_backup_name
, 0);
541 /* Depending on DEREF, apply either stat or lstat to (NAME, BUF). */
543 deref_stat (bool deref
, char const *name
, struct stat
*buf
)
545 return deref
? stat (name
, buf
) : lstat (name
, buf
);
548 /* Set FD's (i.e., FILE's) access time to TIMESPEC[0]. If that's not
549 possible to do by itself, set its access and data modification
550 times to TIMESPEC[0] and TIMESPEC[1], respectively. */
552 set_file_atime (int fd
, char const *file
, struct timespec
const timespec
[2])
557 struct timeval timeval
;
558 timeval
.tv_sec
= timespec
[0].tv_sec
;
559 timeval
.tv_usec
= timespec
[0].tv_nsec
/ 1000;
560 if (ioctl (fd
, _FIOSATIME
, &timeval
) == 0)
565 return gl_futimens (fd
, file
, timespec
);
568 /* A description of a working directory. */
573 struct saved_cwd saved_cwd
;
576 /* A vector of chdir targets. wd[0] is the initial working directory. */
577 static struct wd
*wd
;
579 /* The number of working directories in the vector. */
580 static size_t wd_count
;
582 /* The allocated size of the vector. */
583 static size_t wd_alloc
;
593 /* DIR is the operand of a -C option; add it to vector of chdir targets,
594 and return the index of its location. */
596 chdir_arg (char const *dir
)
598 if (wd_count
== wd_alloc
)
603 wd
= xmalloc (sizeof *wd
* wd_alloc
);
606 wd
= x2nrealloc (wd
, &wd_alloc
, sizeof *wd
);
610 wd
[wd_count
].name
= ".";
611 wd
[wd_count
].saved
= 0;
616 /* Optimize the common special case of the working directory,
617 or the working directory as a prefix. */
620 while (dir
[0] == '.' && ISSLASH (dir
[1]))
621 for (dir
+= 2; ISSLASH (*dir
); dir
++)
623 if (! dir
[dir
[0] == '.'])
627 wd
[wd_count
].name
= dir
;
628 wd
[wd_count
].saved
= 0;
632 /* Change to directory I. If I is 0, change to the initial working
633 directory; otherwise, I must be a value returned by chdir_arg. */
641 struct wd
*prev
= &wd
[previous
];
642 struct wd
*curr
= &wd
[i
];
648 if (save_cwd (&prev
->saved_cwd
) != 0)
650 else if (0 <= prev
->saved_cwd
.desc
)
652 /* Make sure we still have at least one descriptor available. */
653 int fd1
= prev
->saved_cwd
.desc
;
657 else if (errno
== EMFILE
)
659 /* Force restore_cwd to use chdir_long. */
661 prev
->saved_cwd
.desc
= -1;
662 prev
->saved_cwd
.name
= xgetcwd ();
669 FATAL_ERROR ((0, err
, _("Cannot save working directory")));
674 if (restore_cwd (&curr
->saved_cwd
))
675 FATAL_ERROR ((0, 0, _("Cannot change working directory")));
679 if (i
&& ! ISSLASH (curr
->name
[0]))
681 if (chdir (curr
->name
) != 0)
682 chdir_fatal (curr
->name
);
690 close_diag (char const *name
)
692 if (ignore_failed_read_option
)
699 open_diag (char const *name
)
701 if (ignore_failed_read_option
)
708 read_diag_details (char const *name
, off_t offset
, size_t size
)
710 if (ignore_failed_read_option
)
711 read_warn_details (name
, offset
, size
);
713 read_error_details (name
, offset
, size
);
717 readlink_diag (char const *name
)
719 if (ignore_failed_read_option
)
720 readlink_warn (name
);
722 readlink_error (name
);
726 savedir_diag (char const *name
)
728 if (ignore_failed_read_option
)
731 savedir_error (name
);
735 seek_diag_details (char const *name
, off_t offset
)
737 if (ignore_failed_read_option
)
738 seek_warn_details (name
, offset
);
740 seek_error_details (name
, offset
);
744 stat_diag (char const *name
)
746 if (ignore_failed_read_option
)
753 file_removed_diag (const char *name
, bool top_level
,
754 void (*diagfn
) (char const *name
))
756 if (!top_level
&& errno
== ENOENT
)
758 WARNOPT (WARN_FILE_REMOVED
,
759 (0, 0, _("%s: File removed before we read it"),
760 quotearg_colon (name
)));
761 set_exit_status (TAREXIT_DIFFERS
);
768 dir_removed_diag (const char *name
, bool top_level
,
769 void (*diagfn
) (char const *name
))
771 if (!top_level
&& errno
== ENOENT
)
773 WARNOPT (WARN_FILE_REMOVED
,
774 (0, 0, _("%s: Directory removed before we read it"),
775 quotearg_colon (name
)));
776 set_exit_status (TAREXIT_DIFFERS
);
783 write_fatal_details (char const *name
, ssize_t status
, size_t size
)
785 write_error_details (name
, status
, size
);
789 /* Fork, aborting if unsuccessful. */
795 call_arg_fatal ("fork", _("child process"));
799 /* Create a pipe, aborting if unsuccessful. */
804 call_arg_fatal ("pipe", _("interprocess channel"));
807 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
808 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
809 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
813 ptr_align (void *ptr
, size_t alignment
)
816 char *p1
= p0
+ alignment
- 1;
817 return p1
- (size_t) p1
% alignment
;
820 /* Return the address of a page-aligned buffer of at least SIZE bytes.
821 The caller should free *PTR when done with the buffer. */
824 page_aligned_alloc (void **ptr
, size_t size
)
826 size_t alignment
= getpagesize ();
827 size_t size1
= size
+ alignment
;
830 *ptr
= xmalloc (size1
);
831 return ptr_align (*ptr
, alignment
);
838 char *buffer
; /* directory, `/', and directory member */
839 size_t buffer_size
; /* allocated size of name_buffer */
840 size_t dir_length
; /* length of directory part in buffer */
844 namebuf_create (const char *dir
)
846 namebuf_t buf
= xmalloc (sizeof (*buf
));
847 buf
->buffer_size
= strlen (dir
) + 2;
848 buf
->buffer
= xmalloc (buf
->buffer_size
);
849 strcpy (buf
->buffer
, dir
);
850 buf
->dir_length
= strlen (buf
->buffer
);
851 if (!ISSLASH (buf
->buffer
[buf
->dir_length
- 1]))
852 buf
->buffer
[buf
->dir_length
++] = DIRECTORY_SEPARATOR
;
857 namebuf_free (namebuf_t buf
)
864 namebuf_name (namebuf_t buf
, const char *name
)
866 size_t len
= strlen (name
);
867 while (buf
->dir_length
+ len
+ 1 >= buf
->buffer_size
)
868 buf
->buffer
= x2realloc (buf
->buffer
, &buf
->buffer_size
);
869 strcpy (buf
->buffer
+ buf
->dir_length
, name
);