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 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 2, 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. */
22 #include <sys/resource.h>
28 #include <unlinkdir.h>
35 # include <sys/filio.h>
39 /* Handling strings. */
41 /* Assign STRING to a copy of VALUE if not zero, or to zero. If
42 STRING was nonzero, it is freed first. */
44 assign_string (char **string
, const char *value
)
48 *string
= value
? xstrdup (value
) : 0;
51 /* Allocate a copy of the string quoted as in C, and returns that. If
52 the string does not have to be quoted, it returns a null pointer.
53 The allocated copy should normally be freed with free() after the
54 caller is done with it.
56 This is used in one context only: generating the directory file in
57 incremental dumps. The quoted string is not intended for human
58 consumption; it is intended only for unquote_string. The quoting
59 is locale-independent, so that users needn't worry about locale
60 when reading directory files. This means that we can't use
61 quotearg, as quotearg is locale-dependent and is meant for human
64 quote_copy_string (const char *string
)
66 const char *source
= string
;
67 char *destination
= 0;
73 int character
= *source
++;
80 size_t length
= (source
- string
) - 1;
83 buffer
= xmalloc (length
+ 2 + 2 * strlen (source
) + 1);
84 memcpy (buffer
, string
, length
);
85 destination
= buffer
+ length
;
87 *destination
++ = '\\';
88 *destination
++ = character
== '\\' ? '\\' : 'n';
93 *destination
++ = character
;
105 /* Takes a quoted C string (like those produced by quote_copy_string)
106 and turns it back into the un-quoted original. This is done in
107 place. Returns 0 only if the string was not properly quoted, but
108 completes the unquoting anyway.
110 This is used for reading the saved directory file in incremental
111 dumps. It is used for decoding old `N' records (demangling names).
112 But also, it is used for decoding file arguments, would they come
113 from the shell or a -T file, and for decoding the --exclude
116 unquote_string (char *string
)
119 char *source
= string
;
120 char *destination
= string
;
122 /* Escape sequences other than \\ and \n are no longer generated by
123 quote_copy_string, but accept them for backwards compatibility,
124 and also because unquote_string is used for purposes other than
125 parsing the output of quote_copy_string. */
132 *destination
++ = '\\';
137 *destination
++ = '\a';
142 *destination
++ = '\b';
147 *destination
++ = '\f';
152 *destination
++ = '\n';
157 *destination
++ = '\r';
162 *destination
++ = '\t';
167 *destination
++ = '\v';
172 *destination
++ = 0177;
185 int value
= *source
++ - '0';
187 if (*source
< '0' || *source
> '7')
189 *destination
++ = value
;
192 value
= value
* 8 + *source
++ - '0';
193 if (*source
< '0' || *source
> '7')
195 *destination
++ = value
;
198 value
= value
* 8 + *source
++ - '0';
199 *destination
++ = value
;
205 *destination
++ = '\\';
207 *destination
++ = *source
++;
210 else if (source
!= destination
)
211 *destination
++ = *source
++;
213 source
++, destination
++;
215 if (source
!= destination
)
220 /* Handling numbers. */
222 /* Output fraction and trailing digits appropriate for a nanoseconds
223 count equal to NS, but don't output unnecessary '.' or trailing
227 code_ns_fraction (int ns
, char *p
)
246 p
[--i
] = '0' + ns
% 10;
255 code_timespec (struct timespec t
, char sbuf
[TIMESPEC_STRSIZE_BOUND
])
260 bool negative
= s
< 0;
262 if (negative
&& ns
!= 0)
268 np
= umaxtostr (negative
? - (uintmax_t) s
: (uintmax_t) s
, sbuf
+ 1);
271 code_ns_fraction (ns
, sbuf
+ UINTMAX_STRSIZE_BOUND
);
277 /* Saved names in case backup needs to be undone. */
278 static char *before_backup_name
;
279 static char *after_backup_name
;
281 /* Return 1 if FILE_NAME is obviously "." or "/". */
283 must_be_dot_or_slash (char const *file_name
)
285 file_name
+= FILE_SYSTEM_PREFIX_LEN (file_name
);
287 if (ISSLASH (file_name
[0]))
290 if (ISSLASH (file_name
[1]))
292 else if (file_name
[1] == '.'
293 && ISSLASH (file_name
[2 + (file_name
[2] == '.')]))
294 file_name
+= 2 + (file_name
[2] == '.');
296 return ! file_name
[1];
300 while (file_name
[0] == '.' && ISSLASH (file_name
[1]))
303 while (ISSLASH (*file_name
))
307 return ! file_name
[0] || (file_name
[0] == '.' && ! file_name
[1]);
311 /* Some implementations of rmdir let you remove '.' or '/'.
312 Report an error with errno set to zero for obvious cases of this;
313 otherwise call rmdir. */
315 safer_rmdir (const char *file_name
)
317 if (must_be_dot_or_slash (file_name
))
323 return rmdir (file_name
);
326 /* Remove FILE_NAME, returning 1 on success. If FILE_NAME is a directory,
327 then if OPTION is RECURSIVE_REMOVE_OPTION is set remove FILE_NAME
328 recursively; otherwise, remove it only if it is empty. If FILE_NAME is
329 a directory that cannot be removed (e.g., because it is nonempty)
330 and if OPTION is WANT_DIRECTORY_REMOVE_OPTION, then return -1.
331 Return 0 on error, with errno set; if FILE_NAME is obviously the working
332 directory return zero with errno set to zero. */
334 remove_any_file (const char *file_name
, enum remove_option option
)
336 /* Try unlink first if we cannot unlink directories, as this saves
337 us a system call in the common case where we're removing a
339 bool try_unlink_first
= cannot_unlink_dir ();
341 if (try_unlink_first
)
343 if (unlink (file_name
) == 0)
346 /* POSIX 1003.1-2001 requires EPERM when attempting to unlink a
347 directory without appropriate privileges, but many Linux
348 kernels return the more-sensible EISDIR. */
349 if (errno
!= EPERM
&& errno
!= EISDIR
)
353 if (safer_rmdir (file_name
) == 0)
359 return !try_unlink_first
&& unlink (file_name
) == 0;
363 #if defined ENOTEMPTY && ENOTEMPTY != EEXIST
368 case ORDINARY_REMOVE_OPTION
:
371 case WANT_DIRECTORY_REMOVE_OPTION
:
374 case RECURSIVE_REMOVE_OPTION
:
376 char *directory
= savedir (file_name
);
383 for (entry
= directory
;
384 (entrylen
= strlen (entry
)) != 0;
385 entry
+= entrylen
+ 1)
387 char *file_name_buffer
= new_name (file_name
, entry
);
388 int r
= remove_any_file (file_name_buffer
,
389 RECURSIVE_REMOVE_OPTION
);
391 free (file_name_buffer
);
402 return safer_rmdir (file_name
) == 0;
411 /* Check if FILE_NAME already exists and make a backup of it right now.
412 Return success (nonzero) only if the backup is either unneeded, or
413 successful. For now, directories are considered to never need
414 backup. If THIS_IS_THE_ARCHIVE is nonzero, this is the archive and
415 so, we do not have to backup block or character devices, nor remote
418 maybe_backup_file (const char *file_name
, bool this_is_the_archive
)
420 struct stat file_stat
;
422 /* Check if we really need to backup the file. */
424 if (this_is_the_archive
&& _remdev (file_name
))
427 if (stat (file_name
, &file_stat
))
432 stat_error (file_name
);
436 if (S_ISDIR (file_stat
.st_mode
))
439 if (this_is_the_archive
440 && (S_ISBLK (file_stat
.st_mode
) || S_ISCHR (file_stat
.st_mode
)))
443 assign_string (&before_backup_name
, file_name
);
445 /* A run situation may exist between Emacs or other GNU programs trying to
446 make a backup for the same file simultaneously. If theoretically
447 possible, real problems are unlikely. Doing any better would require a
448 convention, GNU-wide, for all programs doing backups. */
450 assign_string (&after_backup_name
, 0);
451 after_backup_name
= find_backup_file_name (file_name
, backup_type
);
452 if (! after_backup_name
)
455 if (rename (before_backup_name
, after_backup_name
) == 0)
458 fprintf (stdlis
, _("Renaming %s to %s\n"),
459 quote_n (0, before_backup_name
),
460 quote_n (1, after_backup_name
));
465 /* The backup operation failed. */
467 ERROR ((0, e
, _("%s: Cannot rename to %s"),
468 quotearg_colon (before_backup_name
),
469 quote_n (1, after_backup_name
)));
470 assign_string (&after_backup_name
, 0);
475 /* Try to restore the recently backed up file to its original name.
476 This is usually only needed after a failed extraction. */
478 undo_last_backup (void)
480 if (after_backup_name
)
482 if (rename (after_backup_name
, before_backup_name
) != 0)
485 ERROR ((0, e
, _("%s: Cannot rename to %s"),
486 quotearg_colon (after_backup_name
),
487 quote_n (1, before_backup_name
)));
490 fprintf (stdlis
, _("Renaming %s back to %s\n"),
491 quote_n (0, after_backup_name
),
492 quote_n (1, before_backup_name
));
493 assign_string (&after_backup_name
, 0);
497 /* Depending on DEREF, apply either stat or lstat to (NAME, BUF). */
499 deref_stat (bool deref
, char const *name
, struct stat
*buf
)
501 return deref
? stat (name
, buf
) : lstat (name
, buf
);
504 /* Set FD's (i.e., FILE's) access time to TIMESPEC[0]. If that's not
505 possible to do by itself, set its access and data modification
506 times to TIMESPEC[0] and TIMESPEC[1], respectively. */
508 set_file_atime (int fd
, char const *file
, struct timespec
const timespec
[2])
513 struct timeval timeval
;
514 timeval
.tv_sec
= timespec
[0].tv_sec
;
515 timeval
.tv_usec
= timespec
[0].tv_nsec
/ 1000;
516 if (ioctl (fd
, _FIOSATIME
, &timeval
) == 0)
521 return futimens (fd
, file
, timespec
);
524 /* A description of a working directory. */
529 struct saved_cwd saved_cwd
;
532 /* A vector of chdir targets. wd[0] is the initial working directory. */
533 static struct wd
*wd
;
535 /* The number of working directories in the vector. */
538 /* The allocated size of the vector. */
539 static size_t wd_alloc
;
541 /* DIR is the operand of a -C option; add it to vector of chdir targets,
542 and return the index of its location. */
544 chdir_arg (char const *dir
)
551 wd
= xmalloc (sizeof *wd
* wd_alloc
);
554 wd
= x2nrealloc (wd
, &wd_alloc
, sizeof *wd
);
564 /* Optimize the common special case of the working directory,
565 or the working directory as a prefix. */
568 while (dir
[0] == '.' && ISSLASH (dir
[1]))
569 for (dir
+= 2; ISSLASH (*dir
); dir
++)
571 if (! dir
[dir
[0] == '.'])
580 /* Return maximum number of open files */
582 get_max_open_files ()
584 #if defined _SC_OPEN_MAX
585 return sysconf (_SC_OPEN_MAX
);
586 #elif defined RLIMIT_NOFILE
589 if (getrlimit(RLIMIT_NOFILE
, &rlim
) == 0)
590 return rlim
.rlim_max
;
591 #elif defined HAVE_GETDTABLESIZE
592 return getdtablesize ();
597 /* Close all descriptors, except the first three */
603 for (i
= get_max_open_files () - 1; i
> 2; i
--)
607 /* Change to directory I. If I is 0, change to the initial working
608 directory; otherwise, I must be a value returned by chdir_arg. */
613 static int saved_count
;
617 struct wd
*prev
= &wd
[previous
];
618 struct wd
*curr
= &wd
[i
];
624 /* Make sure we still have at least one descriptor available */
625 if (saved_count
>= get_max_open_files () - 4)
627 /* Force restore_cwd to use chdir_long */
628 prev
->saved_cwd
.desc
= -1;
629 prev
->saved_cwd
.name
= xgetcwd ();
631 else if (save_cwd (&prev
->saved_cwd
) != 0)
632 FATAL_ERROR ((0, 0, _("Cannot save working directory")));
637 if (restore_cwd (&curr
->saved_cwd
))
638 FATAL_ERROR ((0, 0, _("Cannot change working directory")));
642 if (i
&& ! ISSLASH (curr
->name
[0]))
644 if (chdir (curr
->name
) != 0)
645 chdir_fatal (curr
->name
);
653 close_diag (char const *name
)
655 if (ignore_failed_read_option
)
662 open_diag (char const *name
)
664 if (ignore_failed_read_option
)
671 read_diag_details (char const *name
, off_t offset
, size_t size
)
673 if (ignore_failed_read_option
)
674 read_warn_details (name
, offset
, size
);
676 read_error_details (name
, offset
, size
);
680 readlink_diag (char const *name
)
682 if (ignore_failed_read_option
)
683 readlink_warn (name
);
685 readlink_error (name
);
689 savedir_diag (char const *name
)
691 if (ignore_failed_read_option
)
694 savedir_error (name
);
698 seek_diag_details (char const *name
, off_t offset
)
700 if (ignore_failed_read_option
)
701 seek_warn_details (name
, offset
);
703 seek_error_details (name
, offset
);
707 stat_diag (char const *name
)
709 if (ignore_failed_read_option
)
716 write_fatal_details (char const *name
, ssize_t status
, size_t size
)
718 write_error_details (name
, status
, size
);
722 /* Fork, aborting if unsuccessful. */
728 call_arg_fatal ("fork", _("child process"));
732 /* Create a pipe, aborting if unsuccessful. */
737 call_arg_fatal ("pipe", _("interprocess channel"));
740 /* Return PTR, aligned upward to the next multiple of ALIGNMENT.
741 ALIGNMENT must be nonzero. The caller must arrange for ((char *)
742 PTR) through ((char *) PTR + ALIGNMENT - 1) to be addressable
746 ptr_align (void *ptr
, size_t alignment
)
749 char *p1
= p0
+ alignment
- 1;
750 return p1
- (size_t) p1
% alignment
;
753 /* Return the address of a page-aligned buffer of at least SIZE bytes.
754 The caller should free *PTR when done with the buffer. */
757 page_aligned_alloc (void **ptr
, size_t size
)
759 size_t alignment
= getpagesize ();
760 size_t size1
= size
+ alignment
;
763 *ptr
= xmalloc (size1
);
764 return ptr_align (*ptr
, alignment
);