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 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>
37 /* Handling strings. */
39 /* Assign STRING to a copy of VALUE if not zero, or to zero. If
40 STRING was nonzero, it is freed first. */
42 assign_string (char **string
, const char *value
)
46 *string
= value
? xstrdup (value
) : 0;
49 /* Allocate a copy of the string quoted as in C, and returns that. If
50 the string does not have to be quoted, it returns a null pointer.
51 The allocated copy should normally be freed with free() after the
52 caller is done with it.
54 This is used in one context only: generating the directory file in
55 incremental dumps. The quoted string is not intended for human
56 consumption; it is intended only for unquote_string. The quoting
57 is locale-independent, so that users needn't worry about locale
58 when reading directory files. This means that we can't use
59 quotearg, as quotearg is locale-dependent and is meant for human
62 quote_copy_string (const char *string
)
64 const char *source
= string
;
65 char *destination
= 0;
71 int character
= *source
++;
78 size_t length
= (source
- string
) - 1;
81 buffer
= xmalloc (length
+ 2 + 2 * strlen (source
) + 1);
82 memcpy (buffer
, string
, length
);
83 destination
= buffer
+ length
;
85 *destination
++ = '\\';
86 *destination
++ = character
== '\\' ? '\\' : 'n';
91 *destination
++ = character
;
103 /* Takes a quoted C string (like those produced by quote_copy_string)
104 and turns it back into the un-quoted original. This is done in
105 place. Returns 0 only if the string was not properly quoted, but
106 completes the unquoting anyway.
108 This is used for reading the saved directory file in incremental
109 dumps. It is used for decoding old `N' records (demangling names).
110 But also, it is used for decoding file arguments, would they come
111 from the shell or a -T file, and for decoding the --exclude
114 unquote_string (char *string
)
117 char *source
= string
;
118 char *destination
= string
;
120 /* Escape sequences other than \\ and \n are no longer generated by
121 quote_copy_string, but accept them for backwards compatibility,
122 and also because unquote_string is used for purposes other than
123 parsing the output of quote_copy_string. */
130 *destination
++ = '\\';
135 *destination
++ = '\a';
140 *destination
++ = '\b';
145 *destination
++ = '\f';
150 *destination
++ = '\n';
155 *destination
++ = '\r';
160 *destination
++ = '\t';
165 *destination
++ = '\v';
170 *destination
++ = 0177;
183 int value
= *source
++ - '0';
185 if (*source
< '0' || *source
> '7')
187 *destination
++ = value
;
190 value
= value
* 8 + *source
++ - '0';
191 if (*source
< '0' || *source
> '7')
193 *destination
++ = value
;
196 value
= value
* 8 + *source
++ - '0';
197 *destination
++ = value
;
203 *destination
++ = '\\';
205 *destination
++ = *source
++;
208 else if (source
!= destination
)
209 *destination
++ = *source
++;
211 source
++, destination
++;
213 if (source
!= destination
)
218 /* Handling numbers. */
220 /* Output fraction and trailing digits appropriate for a nanoseconds
221 count equal to NS, but don't output unnecessary '.' or trailing
225 code_ns_fraction (int ns
, char *p
)
244 p
[--i
] = '0' + ns
% 10;
253 code_timespec (struct timespec t
, char sbuf
[TIMESPEC_STRSIZE_BOUND
])
258 bool negative
= s
< 0;
260 if (negative
&& ns
!= 0)
266 np
= umaxtostr (negative
? - (uintmax_t) s
: (uintmax_t) s
, sbuf
+ 1);
269 code_ns_fraction (ns
, sbuf
+ UINTMAX_STRSIZE_BOUND
);
275 /* Saved names in case backup needs to be undone. */
276 static char *before_backup_name
;
277 static char *after_backup_name
;
279 /* Return 1 if FILE_NAME is obviously "." or "/". */
281 must_be_dot_or_slash (char const *file_name
)
283 file_name
+= FILE_SYSTEM_PREFIX_LEN (file_name
);
285 if (ISSLASH (file_name
[0]))
288 if (ISSLASH (file_name
[1]))
290 else if (file_name
[1] == '.'
291 && ISSLASH (file_name
[2 + (file_name
[2] == '.')]))
292 file_name
+= 2 + (file_name
[2] == '.');
294 return ! file_name
[1];
298 while (file_name
[0] == '.' && ISSLASH (file_name
[1]))
301 while (ISSLASH (*file_name
))
305 return ! file_name
[0] || (file_name
[0] == '.' && ! file_name
[1]);
309 /* Some implementations of rmdir let you remove '.' or '/'.
310 Report an error with errno set to zero for obvious cases of this;
311 otherwise call rmdir. */
313 safer_rmdir (const char *file_name
)
315 if (must_be_dot_or_slash (file_name
))
321 return rmdir (file_name
);
324 /* Remove FILE_NAME, returning 1 on success. If FILE_NAME is a directory,
325 then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
326 recursively; otherwise, remove it only if it is empty. If FILE_NAME is
327 a directory that cannot be removed (e.g., because it is nonempty)
328 and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
329 Return 0 on error, with errno set; if FILE_NAME is obviously the working
330 directory return zero with errno set to zero. */
332 remove_any_file (const char *file_name
, enum remove_option option
)
334 /* Try unlink first if we cannot unlink directories, as this saves
335 us a system call in the common case where we're removing a
337 bool try_unlink_first
= cannot_unlink_dir ();
339 if (try_unlink_first
)
341 if (unlink (file_name
) == 0)
344 /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
345 directory without appropriate privileges, but many Linux
346 kernels return the more-sensible EISDIR. */
347 if (errno
!= EPERM
&& errno
!= EISDIR
)
351 if (safer_rmdir (file_name
) == 0)
357 return !try_unlink_first
&& unlink (file_name
) == 0;
361 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
366 case ORDINARY_REMOVE_OPTION
:
369 case WANT_DIRECTORY_REMOVE_OPTION
:
372 case RECURSIVE_REMOVE_OPTION
:
374 char *directory
= savedir (file_name
);
381 for (entry
= directory
;
382 (entrylen
= strlen (entry
)) != 0;
383 entry
+= entrylen
+ 1)
385 char *file_name_buffer
= new_name (file_name
, entry
);
386 int r
= remove_any_file (file_name_buffer
,
387 RECURSIVE_REMOVE_OPTION
);
389 free (file_name_buffer
);
400 return safer_rmdir (file_name
) == 0;
409 /* Check if FILE_NAME already exists and make a backup of it right now.
410 Return success (nonzero) only if the backup is either unneeded, or
411 successful. For now, directories are considered to never need
412 backup. If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
413 so, we do not have to backup block or character devices, nor remote
416 maybe_backup_file (const char *file_name
, bool this_is_the_archive
)
418 struct stat file_stat
;
420 assign_string (&before_backup_name
, file_name
);
422 /* A run situation may exist between Emacs or other GNU programs trying to
423 make a backup for the same file simultaneously. If theoretically
424 possible, real problems are unlikely. Doing any better would require a
425 convention, GNU-wide, for all programs doing backups. */
427 assign_string (&after_backup_name
, 0);
429 /* Check if we really need to backup the file. */
431 if (this_is_the_archive
&& _remdev (file_name
))
434 if (stat (file_name
, &file_stat
))
439 stat_error (file_name
);
443 if (S_ISDIR (file_stat
.st_mode
))
446 if (this_is_the_archive
447 && (S_ISBLK (file_stat
.st_mode
) || S_ISCHR (file_stat
.st_mode
)))
450 after_backup_name
= find_backup_file_name (file_name
, backup_type
);
451 if (! after_backup_name
)
454 if (rename (before_backup_name
, after_backup_name
) == 0)
457 fprintf (stdlis
, _("Renaming %s to %s\n"),
458 quote_n (0, before_backup_name
),
459 quote_n (1, after_backup_name
));
464 /* The backup operation failed. */
466 ERROR ((0, e
, _("%s: Cannot rename to %s"),
467 quotearg_colon (before_backup_name
),
468 quote_n (1, after_backup_name
)));
469 assign_string (&after_backup_name
, 0);
474 /* Try to restore the recently backed up file to its original name.
475 This is usually only needed after a failed extraction. */
477 undo_last_backup (void)
479 if (after_backup_name
)
481 if (rename (after_backup_name
, before_backup_name
) != 0)
484 ERROR ((0, e
, _("%s: Cannot rename to %s"),
485 quotearg_colon (after_backup_name
),
486 quote_n (1, before_backup_name
)));
489 fprintf (stdlis
, _("Renaming %s back to %s\n"),
490 quote_n (0, after_backup_name
),
491 quote_n (1, before_backup_name
));
492 assign_string (&after_backup_name
, 0);
496 /* Depending on DEREF, apply either stat or lstat to (NAME, BUF). */
498 deref_stat (bool deref
, char const *name
, struct stat
*buf
)
500 return deref
? stat (name
, buf
) : lstat (name
, buf
);
503 /* Set FD's (i.e., FILE's) access time to TIMESPEC[0]. If that's not
504 possible to do by itself, set its access and data modification
505 times to TIMESPEC[0] and TIMESPEC[1], respectively. */
507 set_file_atime (int fd
, char const *file
, struct timespec
const timespec
[2])
512 struct timeval timeval
;
513 timeval
.tv_sec
= timespec
[0].tv_sec
;
514 timeval
.tv_usec
= timespec
[0].tv_nsec
/ 1000;
515 if (ioctl (fd
, _FIOSATIME
, &timeval
) == 0)
520 return gl_futimens (fd
, file
, timespec
);
523 /* A description of a working directory. */
528 struct saved_cwd saved_cwd
;
531 /* A vector of chdir targets. wd[0] is the initial working directory. */
532 static struct wd
*wd
;
534 /* The number of working directories in the vector. */
537 /* The allocated size of the vector. */
538 static size_t wd_alloc
;
540 /* DIR is the operand of a -C option; add it to vector of chdir targets,
541 and return the index of its location. */
543 chdir_arg (char const *dir
)
550 wd
= xmalloc (sizeof *wd
* wd_alloc
);
553 wd
= x2nrealloc (wd
, &wd_alloc
, sizeof *wd
);
563 /* Optimize the common special case of the working directory,
564 or the working directory as a prefix. */
567 while (dir
[0] == '.' && ISSLASH (dir
[1]))
568 for (dir
+= 2; ISSLASH (*dir
); dir
++)
570 if (! dir
[dir
[0] == '.'])
579 /* Change to directory I. If I is 0, change to the initial working
580 directory; otherwise, I must be a value returned by chdir_arg. */
588 struct wd
*prev
= &wd
[previous
];
589 struct wd
*curr
= &wd
[i
];
595 if (save_cwd (&prev
->saved_cwd
) != 0)
597 else if (0 <= prev
->saved_cwd
.desc
)
599 /* Make sure we still have at least one descriptor available. */
600 int fd1
= prev
->saved_cwd
.desc
;
604 else if (errno
== EMFILE
)
606 /* Force restore_cwd to use chdir_long. */
608 prev
->saved_cwd
.desc
= -1;
609 prev
->saved_cwd
.name
= xgetcwd ();
616 FATAL_ERROR ((0, err
, _("Cannot save working directory")));
621 if (restore_cwd (&curr
->saved_cwd
))
622 FATAL_ERROR ((0, 0, _("Cannot change working directory")));
626 if (i
&& ! ISSLASH (curr
->name
[0]))
628 if (chdir (curr
->name
) != 0)
629 chdir_fatal (curr
->name
);
637 close_diag (char const *name
)
639 if (ignore_failed_read_option
)
646 open_diag (char const *name
)
648 if (ignore_failed_read_option
)
655 read_diag_details (char const *name
, off_t offset
, size_t size
)
657 if (ignore_failed_read_option
)
658 read_warn_details (name
, offset
, size
);
660 read_error_details (name
, offset
, size
);
664 readlink_diag (char const *name
)
666 if (ignore_failed_read_option
)
667 readlink_warn (name
);
669 readlink_error (name
);
673 savedir_diag (char const *name
)
675 if (ignore_failed_read_option
)
678 savedir_error (name
);
682 seek_diag_details (char const *name
, off_t offset
)
684 if (ignore_failed_read_option
)
685 seek_warn_details (name
, offset
);
687 seek_error_details (name
, offset
);
691 stat_diag (char const *name
)
693 if (ignore_failed_read_option
)
700 write_fatal_details (char const *name
, ssize_t status
, size_t size
)
702 write_error_details (name
, status
, size
);
706 /* Fork, aborting if unsuccessful. */
712 call_arg_fatal ("fork", _("child process"));
716 /* Create a pipe, aborting if unsuccessful. */
721 call_arg_fatal ("pipe", _("interprocess channel"));
724 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
725 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
726 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
730 ptr_align (void *ptr
, size_t alignment
)
733 char *p1
= p0
+ alignment
- 1;
734 return p1
- (size_t) p1
% alignment
;
737 /* Return the address of a page-aligned buffer of at least SIZE bytes.
738 The caller should free *PTR when done with the buffer. */
741 page_aligned_alloc (void **ptr
, size_t size
)
743 size_t alignment
= getpagesize ();
744 size_t size1
= size
+ alignment
;
747 *ptr
= xmalloc (size1
);
748 return ptr_align (*ptr
, alignment
);