1 /* remove.c -- core functions for removing files and directories
2 Copyright (C) 88, 90, 91, 1994-2004 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Extracted from rm.c and librarified, then rewritten by Jim Meyering. */
22 #include <sys/types.h>
28 #include "cycle-check.h"
31 #include "euidaccess.h"
32 #include "file-type.h"
38 #include "root-dev-ino.h"
41 /* Avoid shadowing warnings because these are functions declared
42 in dirname.h as well as locals used below. */
43 #define dir_name rm_dir_name
44 #define dir_len rm_dir_len
46 #define obstack_chunk_alloc malloc
47 #define obstack_chunk_free free
49 /* FIXME: if possible, use autoconf... */
51 # define ROOT_CAN_UNLINK_DIRS 0
53 # define ROOT_CAN_UNLINK_DIRS 1
56 #ifndef HAVE_WORKING_READDIR
57 # define HAVE_WORKING_READDIR 0
66 typedef enum Ternary Ternary;
68 /* The prompt function may be called twice for a given directory.
69 The first time, we ask whether to descend into it, and the
70 second time, we ask whether to remove it. */
73 PA_DESCEND_INTO_DIR = 2,
77 /* On systems with an lstat function that accepts the empty string,
78 arrange to make lstat calls go through the wrapper function. */
79 #if HAVE_LSTAT_EMPTY_STRING_BUG
80 int rpl_lstat (const char *, struct stat *);
81 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
84 /* Initial capacity of per-directory hash table of entries that have
85 been processed but not been deleted. */
86 #define HT_UNREMOVABLE_INITIAL_CAPACITY 13
88 /* An entry in the active directory stack.
89 Each entry corresponds to an `active' directory. */
92 /* For a given active directory, this is the set of names of
93 entries in that directory that could/should not be removed.
94 For example, `.' and `..', as well as files/dirs for which
95 unlink/rmdir failed e.g., due to access restrictions. */
96 Hash_table *unremovable;
98 /* Record the status for a given active directory; we need to know
99 whether an entry was not removed, either because of an error or
100 because the user declined. */
101 enum RM_status status;
105 /* The directory's dev/ino. Used to ensure that `chdir some-subdir', then
106 `chdir ..' takes us back to the same directory from which we started).
107 (valid for all but the bottommost entry on the stack. */
110 /* Enough information to restore the initial working directory.
111 (valid only for the bottommost entry on the stack) */
112 struct saved_cwd saved_cwd;
116 extern char *program_name;
118 struct dirstack_state
120 /* The name of the directory (starting with and relative to a command
121 line argument) being processed. When a subdirectory is entered, a new
122 component is appended (pushed). Remove (pop) the top component
123 upon chdir'ing out of a directory. This is used to form the full
124 name of the current directory or a file therein, when necessary. */
125 struct obstack dir_stack;
127 /* Stack of lengths of directory names (including trailing slash)
128 appended to dir_stack. We have to have a separate stack of lengths
129 (rather than just popping back to previous slash) because the first
130 element pushed onto the dir stack may contain slashes. */
131 struct obstack len_stack;
133 /* Stack of active directory entries.
134 The first `active' directory is the initial working directory.
135 Additional active dirs are pushed onto the stack as we `chdir'
136 into each directory to be processed. When finished with the
137 hierarchy under a directory, pop the active dir stack. */
138 struct obstack Active_dir;
140 /* Used to detect cycles. */
141 struct cycle_check_state cycle_check_state;
143 /* Target of a longjmp in case rm has to stop processing the current
144 command-line argument. This happens 1) when rm detects a directory
145 cycle or 2) when it has processed one or more directories, but then
146 is unable to return to the initial working directory to process
147 additional `.'-relative command-line arguments. */
148 jmp_buf current_arg_jumpbuf;
150 typedef struct dirstack_state Dirstack_state;
154 /* The value of errno after a failed save_cwd or restore_cwd. */
157 /* Information (open file descriptor or absolute directory name)
158 required in order to restore the initial working directory. */
159 struct saved_cwd saved_cwd;
162 static Dirstack_state *
165 Dirstack_state *ds = xmalloc (sizeof *ds);
166 obstack_init (&ds->dir_stack);
167 obstack_init (&ds->len_stack);
168 obstack_init (&ds->Active_dir);
173 ds_free (Dirstack_state *ds)
175 obstack_free (&ds->dir_stack, NULL);
176 obstack_free (&ds->len_stack, NULL);
177 obstack_free (&ds->Active_dir, NULL);
188 hash_compare_strings (void const *x, void const *y)
190 return STREQ (x, y) ? true : false;
194 push_dir (Dirstack_state *ds, const char *dir_name)
196 size_t len = strlen (dir_name);
198 /* Append the string onto the stack. */
199 obstack_grow (&ds->dir_stack, dir_name, len);
201 /* Append a trailing slash. */
202 obstack_1grow (&ds->dir_stack, '/');
204 /* Add one for the slash. */
207 /* Push the length (including slash) onto its stack. */
208 obstack_grow (&ds->len_stack, &len, sizeof (len));
211 /* Return the entry name of the directory on the top of the stack
212 in malloc'd storage. */
214 top_dir (Dirstack_state const *ds)
216 size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
217 size_t *length = obstack_base (&ds->len_stack);
218 size_t top_len = length[n_lengths - 1];
219 char const *p = obstack_next_free (&ds->dir_stack) - top_len;
220 char *q = xmalloc (top_len);
221 memcpy (q, p, top_len - 1);
227 pop_dir (Dirstack_state *ds)
229 size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
230 size_t *length = obstack_base (&ds->len_stack);
233 assert (n_lengths > 0);
234 top_len = length[n_lengths - 1];
235 assert (top_len >= 2);
237 /* Pop off the specified length of pathname. */
238 assert (obstack_object_size (&ds->dir_stack) >= top_len);
239 obstack_blank (&ds->dir_stack, -top_len);
241 /* Pop the length stack, too. */
242 assert (obstack_object_size (&ds->len_stack) >= sizeof (size_t));
243 obstack_blank (&ds->len_stack, -(int) sizeof (size_t));
246 /* Copy the SRC_LEN bytes of data beginning at SRC into the DST_LEN-byte
247 buffer, DST, so that the last source byte is at the end of the destination
248 buffer. If SRC_LEN is longer than DST_LEN, then set *TRUNCATED.
249 Set *RESULT to point to the beginning of (the portion of) the source data
250 in DST. Return the number of bytes remaining in the destination buffer. */
253 right_justify (char *dst, size_t dst_len, const char *src, size_t src_len,
254 char **result, bool *truncated)
259 if (src_len <= dst_len)
262 dp = dst + (dst_len - src_len);
267 sp = src + (src_len - dst_len);
273 *result = memcpy (dp, sp, src_len);
274 return dst_len - src_len;
277 /* Using the global directory name obstack, create the full path to FILENAME.
278 Return it in sometimes-realloc'd space that should not be freed by the
279 caller. Realloc as necessary. If realloc fails, use a static buffer
280 and put as long a suffix in that buffer as possible. */
282 #define full_filename(Filename) full_filename_ (ds, Filename)
284 full_filename_ (Dirstack_state const *ds, const char *filename)
286 static char *buf = NULL;
287 static size_t n_allocated = 0;
289 size_t dir_len = obstack_object_size (&ds->dir_stack);
290 char *dir_name = obstack_base (&ds->dir_stack);
291 size_t n_bytes_needed;
294 filename_len = strlen (filename);
295 n_bytes_needed = dir_len + filename_len + 1;
297 if (n_allocated < n_bytes_needed)
299 /* This code requires that realloc accept NULL as the first arg.
300 This function must not use xrealloc. Otherwise, an out-of-memory
301 error involving a file name to be expanded here wouldn't ever
302 be issued. Use realloc and fall back on using a static buffer
303 if memory allocation fails. */
304 char *new_buf = realloc (buf, n_bytes_needed);
305 n_allocated = n_bytes_needed;
309 #define SBUF_SIZE 512
310 #define ELLIPSES_PREFIX "[...]"
311 static char static_buf[SBUF_SIZE];
317 len = right_justify (static_buf, SBUF_SIZE, filename,
318 filename_len + 1, &p, &truncated);
319 right_justify (static_buf, len, dir_name, dir_len, &p, &truncated);
322 memcpy (static_buf, ELLIPSES_PREFIX,
323 sizeof (ELLIPSES_PREFIX) - 1);
331 if (filename_len == 1 && *filename == '.' && dir_len)
333 /* FILENAME is just `.' and dir_len is nonzero.
334 Copy the directory part, omitting the trailing slash,
335 and append a trailing zero byte. */
336 char *p = mempcpy (buf, dir_name, dir_len - 1);
341 /* Copy the directory part, including trailing slash, and then
342 append the filename part, including a trailing zero byte. */
343 memcpy (mempcpy (buf, dir_name, dir_len), filename, filename_len + 1);
344 assert (strlen (buf) + 1 == n_bytes_needed);
351 AD_stack_height (Dirstack_state const *ds)
353 return obstack_object_size (&ds->Active_dir) / sizeof (struct AD_ent);
356 static struct AD_ent *
357 AD_stack_top (Dirstack_state const *ds)
359 return (struct AD_ent *)
360 ((char *) obstack_next_free (&ds->Active_dir) - sizeof (struct AD_ent));
364 AD_stack_pop (Dirstack_state *ds)
366 /* operate on Active_dir. pop and free top entry */
367 struct AD_ent *top = AD_stack_top (ds);
368 if (top->unremovable)
369 hash_free (top->unremovable);
370 obstack_blank (&ds->Active_dir, -(int) sizeof (struct AD_ent));
374 /* chdir `up' one level.
375 Whenever using chdir '..', verify that the post-chdir
376 dev/ino numbers for `.' match the saved ones.
377 Set *PREV_DIR to the name (in malloc'd storage) of the
378 directory (usually now empty) from which we're coming.
379 Return true if successful. */
381 AD_pop_and_chdir (Dirstack_state *ds, char **prev_dir)
383 enum RM_status old_status = AD_stack_top(ds)->status;
386 /* Get the name of the current (but soon to be `previous') directory
387 from the top of the stack. */
388 *prev_dir = top_dir (ds);
391 top = AD_stack_top (ds);
393 /* Propagate any failure to parent. */
394 UPDATE_STATUS (top->status, old_status);
396 assert (AD_stack_height (ds));
398 if (1 < AD_stack_height (ds))
402 /* We can give a better diagnostic here, since the target is relative. */
403 if (chdir ("..") != 0)
405 error (EXIT_FAILURE, errno,
406 _("cannot chdir from %s to .."),
407 quote (full_filename (".")));
410 if (lstat (".", &sb))
411 error (EXIT_FAILURE, errno,
412 _("cannot lstat `.' in %s"), quote (full_filename (".")));
414 /* Ensure that post-chdir dev/ino match the stored ones. */
415 if ( ! SAME_INODE (sb, top->u.a))
416 error (EXIT_FAILURE, 0,
417 _("%s changed dev/ino"), quote (full_filename (".")));
421 if (restore_cwd (&top->u.saved_cwd) != 0)
423 /* failed to return to initial working directory */
431 /* Initialize *HT if it is NULL.
432 Insert FILENAME into HT. */
434 AD_mark_helper (Hash_table **ht, char const *filename)
438 *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw,
439 hash_compare_strings, hash_freer);
443 if (! hash_insert (*ht, filename))
447 /* Mark FILENAME (in current directory) as unremovable. */
449 AD_mark_as_unremovable (Dirstack_state *ds, char const *filename)
451 AD_mark_helper (&AD_stack_top(ds)->unremovable, xstrdup (filename));
454 /* Mark the current directory as unremovable. I.e., mark the entry
455 in the parent directory corresponding to `.'.
456 This happens e.g., when an opendir fails and the only name
457 the caller has conveniently at hand is `.'. */
459 AD_mark_current_as_unremovable (Dirstack_state *ds)
461 struct AD_ent *top = AD_stack_top (ds);
462 const char *curr = top_dir (ds);
464 assert (1 < AD_stack_height (ds));
467 AD_mark_helper (&top->unremovable, curr);
470 /* Push the initial cwd info onto the stack.
471 This will always be the bottommost entry on the stack. */
473 AD_push_initial (Dirstack_state *ds, struct saved_cwd const *cwd)
477 /* Extend the stack. */
478 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
480 /* Fill in the new values. */
481 top = AD_stack_top (ds);
482 top->u.saved_cwd = *cwd;
483 top->unremovable = NULL;
486 /* Push info about the current working directory (".") onto the
487 active directory stack. DIR is the ./-relative name through
488 which we've just `chdir'd to this directory. DIR_SB_FROM_PARENT
489 is the result of calling lstat on DIR from the parent of DIR. */
491 AD_push (Dirstack_state *ds, char const *dir,
492 struct stat const *dir_sb_from_parent)
499 if (lstat (".", &sb))
500 error (EXIT_FAILURE, errno,
501 _("cannot lstat `.' in %s"), quote (full_filename (".")));
503 if ( ! SAME_INODE (sb, *dir_sb_from_parent))
504 error (EXIT_FAILURE, 0,
505 _("%s changed dev/ino"), quote (full_filename (".")));
507 /* Extend the stack. */
508 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
510 /* Fill in the new values. */
511 top = AD_stack_top (ds);
512 top->u.a.st_dev = sb.st_dev;
513 top->u.a.st_ino = sb.st_ino;
514 top->unremovable = NULL;
518 AD_is_removable (Dirstack_state const *ds, char const *file)
520 struct AD_ent *top = AD_stack_top (ds);
521 return ! (top->unremovable && hash_lookup (top->unremovable, file));
524 /* Return true if DIR is determined to be an empty directory
525 or if opendir or readdir fails. */
527 is_empty_dir (char const *dir)
529 DIR *dirp = opendir (dir);
530 struct dirent const *dp;
537 dp = readdir_ignoring_dot_and_dotdot (dirp);
542 return saved_errno == 0 ? true : false;
545 /* Return true if FILE is not a symbolic link and it is not writable.
546 Also return true if FILE cannot be lstat'ed. Otherwise, return false.
547 If lstat succeeds, set *BUF_P to BUF.
548 This is to avoid calling euidaccess when FILE is a symlink. */
550 write_protected_non_symlink (char const *file,
554 if (lstat (file, buf) != 0)
557 if (S_ISLNK (buf->st_mode))
559 return euidaccess (file, W_OK) == -1 && errno == EACCES;
562 /* Prompt whether to remove FILENAME, if required via a combination of
563 the options specified by X and/or file attributes. If the file may
564 be removed, return RM_OK. If the user declines to remove the file,
565 return RM_USER_DECLINED. If not ignoring missing files and we
566 cannot lstat FILENAME, then return RM_ERROR.
568 Depending on MODE, ask whether to `descend into' or to `remove' the
569 directory FILENAME. MODE is ignored when FILENAME is not a directory.
570 Set *IS_EMPTY to T_YES if FILENAME is an empty directory, and it is
571 appropriate to try to remove it with rmdir (e.g. recursive mode).
572 Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR.
573 Set *IS_DIR to T_YES or T_NO if we happen to determine whether
574 FILENAME is a directory. */
575 static enum RM_status
576 prompt (Dirstack_state const *ds, char const *filename,
577 struct rm_options const *x, enum Prompt_action mode,
578 Ternary *is_dir, Ternary *is_empty)
580 bool write_protected = false;
581 struct stat *sbuf = NULL;
584 *is_empty = T_UNKNOWN;
587 if (((!x->ignore_missing_files & (x->interactive | x->stdin_tty))
588 && (write_protected = write_protected_non_symlink (filename,
595 if (lstat (filename, sbuf))
597 /* lstat failed. This happens e.g., with `rm '''. */
598 error (0, errno, _("cannot lstat %s"),
599 quote (full_filename (filename)));
604 if (S_ISDIR (sbuf->st_mode) && !x->recursive)
606 error (0, EISDIR, _("cannot remove directory %s"),
607 quote (full_filename (filename)));
611 /* Using permissions doesn't make sense for symlinks. */
612 if (S_ISLNK (sbuf->st_mode))
614 if ( ! x->interactive)
616 write_protected = false;
619 /* Issue the prompt. */
621 char const *quoted_name = quote (full_filename (filename));
623 *is_dir = (S_ISDIR (sbuf->st_mode) ? T_YES : T_NO);
625 /* FIXME: use a variant of error (instead of fprintf) that doesn't
626 append a newline. Then we won't have to declare program_name in
628 if (S_ISDIR (sbuf->st_mode)
630 && mode == PA_DESCEND_INTO_DIR
631 && ((*is_empty = (is_empty_dir (filename) ? T_YES : T_NO))
635 ? _("%s: descend into write-protected directory %s? ")
636 : _("%s: descend into directory %s? ")),
637 program_name, quoted_name);
640 /* TRANSLATORS: You may find it more convenient to translate
641 the equivalent of _("%s: remove %s (write-protected) %s? ").
642 It should avoid grammatical problems with the output
646 ? _("%s: remove write-protected %s %s? ")
647 : _("%s: remove %s %s? ")),
648 program_name, file_type (sbuf), quoted_name);
652 return RM_USER_DECLINED;
658 #if HAVE_STRUCT_DIRENT_D_TYPE
659 # define DT_IS_DIR(D) ((D)->d_type == DT_DIR)
661 /* Use this only if the member exists -- i.e., don't return 0. */
662 # define DT_IS_DIR(D) do_not_use_this_macro
665 #define DO_UNLINK(Filename, X) \
668 if (unlink (Filename) == 0) \
671 printf (_("removed %s\n"), quote (full_filename (Filename))); \
675 if (errno == ENOENT && (X)->ignore_missing_files) \
680 #define DO_RMDIR(Filename, X) \
683 if (rmdir (Filename) == 0) \
686 printf (_("removed directory: %s\n"), \
687 quote (full_filename (Filename))); \
691 if (errno == ENOENT && (X)->ignore_missing_files) \
694 if (errno == ENOTEMPTY || errno == EEXIST) \
695 return RM_NONEMPTY_DIR; \
699 /* Remove the file or directory specified by FILENAME.
700 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
701 But if FILENAME specifies a non-empty directory, return RM_NONEMPTY_DIR. */
703 static enum RM_status
704 remove_entry (Dirstack_state const *ds, char const *filename,
705 struct rm_options const *x, struct dirent const *dp)
708 Ternary is_empty_directory;
709 enum RM_status s = prompt (ds, filename, x, PA_DESCEND_INTO_DIR,
710 &is_dir, &is_empty_directory);
715 /* Why bother with the following #if/#else block? Because on systems with
716 an unlink function that *can* unlink directories, we must determine the
717 type of each entry before removing it. Otherwise, we'd risk unlinking an
718 entire directory tree simply by unlinking a single directory; then all
719 the storage associated with that hierarchy would not be freed until the
720 next reboot. Not nice. To avoid that, on such slightly losing systems, we
721 need to call lstat to determine the type of each entry, and that represents
722 extra overhead that -- it turns out -- we can avoid on GNU-libc-based
723 systems, since there, unlink will never remove a directory. */
725 #if ROOT_CAN_UNLINK_DIRS
727 /* If we don't already know whether FILENAME is a directory, find out now.
728 Then, if it's a non-directory, we can use unlink on it. */
729 if (is_dir == T_UNKNOWN)
731 # if HAVE_STRUCT_DIRENT_D_TYPE
732 if (dp && dp->d_type != DT_UNKNOWN)
733 is_dir = DT_IS_DIR (dp) ? T_YES : T_NO;
738 if (lstat (filename, &sbuf))
740 if (errno == ENOENT && x->ignore_missing_files)
744 _("cannot lstat %s"), quote (full_filename (filename)));
748 is_dir = S_ISDIR (sbuf.st_mode) ? T_YES : T_NO;
754 /* At this point, barring race conditions, FILENAME is known
755 to be a non-directory, so it's ok to try to unlink it. */
756 DO_UNLINK (filename, x);
758 /* unlink failed with some other error code. report it. */
759 error (0, errno, _("cannot remove %s"),
760 quote (full_filename (filename)));
766 error (0, EISDIR, _("cannot remove directory %s"),
767 quote (full_filename (filename)));
771 if (is_empty_directory == T_YES)
773 DO_RMDIR (filename, x);
774 /* Don't diagnose any failure here.
775 It'll be detected when the caller tries another way. */
779 #else /* ! ROOT_CAN_UNLINK_DIRS */
781 if (is_dir == T_YES && ! x->recursive)
783 error (0, EISDIR, _("cannot remove directory %s"),
784 quote (full_filename (filename)));
788 /* is_empty_directory is set iff it's ok to use rmdir.
789 Note that it's set only in interactive mode -- in which case it's
790 an optimization that arranges so that the user is asked just
791 once whether to remove the directory. */
792 if (is_empty_directory == T_YES)
793 DO_RMDIR (filename, x);
795 /* If we happen to know that FILENAME is a directory, return now
796 and let the caller remove it -- this saves the overhead of a failed
797 unlink call. If FILENAME is a command-line argument, then dp is NULL,
798 so we'll first try to unlink it. Using unlink here is ok, because it
799 cannot remove a directory. */
800 if ((dp && DT_IS_DIR (dp)) || is_dir == T_YES)
801 return RM_NONEMPTY_DIR;
803 DO_UNLINK (filename, x);
806 || errno == ENOENT || errno == ENOTDIR
807 || errno == ELOOP || errno == ENAMETOOLONG)
809 /* Either --recursive is not in effect, or the file cannot be a
810 directory. Report the unlink problem and fail. */
811 error (0, errno, _("cannot remove %s"),
812 quote (full_filename (filename)));
817 return RM_NONEMPTY_DIR;
820 /* Remove entries in `.', the current working directory (cwd).
821 Upon finding a directory that is both non-empty and that can be chdir'd
822 into, return RM_OK and set *SUBDIR and fill in SUBDIR_SB, where
823 SUBDIR is the malloc'd name of the subdirectory if the chdir succeeded,
824 NULL otherwise (e.g., if opendir failed or if there was no subdirectory).
825 Likewise, SUBDIR_SB is the result of calling lstat on SUBDIR.
826 Return RM_OK if all entries are removed. Return RM_ERROR if any
827 entry cannot be removed. Otherwise, return RM_USER_DECLINED if
828 the user declines to remove at least one entry. Remove as much as
829 possible, continuing even if we fail to remove some entries. */
830 static enum RM_status
831 remove_cwd_entries (Dirstack_state *ds, char **subdir, struct stat *subdir_sb,
832 struct rm_options const *x)
834 DIR *dirp = opendir (".");
835 struct AD_ent *top = AD_stack_top (ds);
836 enum RM_status status = top->status;
837 bool need_rewinddir = false;
839 assert (VALID_STATUS (status));
844 if (errno != ENOENT || !x->ignore_missing_files)
846 error (0, errno, _("cannot open directory %s"),
847 quote (full_filename (".")));
854 struct dirent const *dp;
855 enum RM_status tmp_status;
858 /* Set errno to zero so we can distinguish between a readdir failure
859 and when readdir simply finds that there are no more entries. */
861 if ((dp = readdir_ignoring_dot_and_dotdot (dirp)) == NULL)
865 /* Save/restore errno across closedir call. */
870 /* Arrange to give a diagnostic after exiting this loop. */
873 else if (need_rewinddir)
875 /* On buggy systems, call rewinddir if we've called unlink
876 or rmdir since the opendir or a previous rewinddir. */
878 need_rewinddir = false;
886 /* Skip files we've already tried/failed to remove. */
887 if ( ! AD_is_removable (ds, f))
890 /* Pass dp->d_type info to remove_entry so the non-glibc
891 case can decide whether to use unlink or chdir.
892 Systems without the d_type member will have to endure
893 the performance hit of first calling lstat F. */
894 tmp_status = remove_entry (ds, f, x, dp);
898 /* On buggy systems, record the fact that we've just
899 removed a directory entry. */
900 need_rewinddir = ! HAVE_WORKING_READDIR;
904 case RM_USER_DECLINED:
905 AD_mark_as_unremovable (ds, f);
906 UPDATE_STATUS (status, tmp_status);
909 case RM_NONEMPTY_DIR:
911 /* Save a copy of errno, in case the preceding unlink (from
912 remove_entry's DO_UNLINK) of a non-directory failed. */
913 int saved_errno = errno;
915 /* Record dev/ino of F so that we can compare
916 that with dev/ino of `.' after the chdir.
917 This dev/ino pair is also used in cycle detection. */
918 if (lstat (f, subdir_sb))
919 error (EXIT_FAILURE, errno, _("cannot lstat %s"),
920 quote (full_filename (f)));
923 if (! S_ISDIR (subdir_sb->st_mode) || chdir (f) != 0)
925 /* It is much more common that we reach this point for an
926 inaccessible directory. Hence the second diagnostic, below.
927 However it is also possible that F is a non-directory.
928 That can happen when we use the `! ROOT_CAN_UNLINK_DIRS'
929 block of code and when DO_UNLINK fails due to EPERM.
930 In that case, give a better diagnostic. */
931 if (errno == ENOTDIR)
932 error (0, saved_errno, _("cannot remove %s"),
933 quote (full_filename (f)));
935 error (0, errno, _("cannot chdir from %s to %s"),
936 quote_n (0, full_filename (".")), quote_n (1, f));
937 AD_mark_as_unremovable (ds, f);
941 if (cycle_check (&ds->cycle_check_state, subdir_sb))
944 WARNING: Circular directory structure.\n\
945 This almost certainly means that you have a corrupted file system.\n\
946 NOTIFY YOUR SYSTEM MANAGER.\n\
947 The following directory is part of the cycle:\n %s\n"),
948 quote (full_filename (".")));
949 longjmp (ds->current_arg_jumpbuf, 1);
952 *subdir = xstrdup (f);
957 /* Record status for this directory. */
958 UPDATE_STATUS (top->status, status);
964 if (dirp == NULL || CLOSEDIR (dirp) != 0)
966 /* Note that this diagnostic serves for both readdir
967 and closedir failures. */
968 error (0, errno, _("reading directory %s"), quote (full_filename (".")));
975 /* Do this after each call to AD_push or AD_push_initial.
976 Because the status = RM_OK bit is too remove-specific to
977 go into the general-purpose AD_* package. */
978 #define AD_INIT_OTHER_MEMBERS() \
981 AD_stack_top(ds)->status = RM_OK; \
985 /* Remove the hierarchy rooted at DIR.
986 Do that by changing into DIR, then removing its contents, then
987 returning to the original working directory and removing DIR itself.
988 Don't use recursion. Be careful when using chdir ".." that we
989 return to the same directory from which we came, if necessary.
990 Return 1 for success, 0 if some file cannot be removed or if
992 If the initial working directory cannot be saved or restored,
993 record the offending errno value in (*CWD_STATE)->saved_errno. */
995 static enum RM_status
996 remove_dir (Dirstack_state *ds, char const *dir, struct cwd_state **cwd_state,
997 struct rm_options const *x)
999 enum RM_status status;
1002 /* Save any errno (from caller's failed remove_entry call), in case DIR
1003 is not a directory, so that we can give a reasonable diagnostic. */
1004 int saved_errno = errno;
1006 if (*cwd_state == NULL)
1008 *cwd_state = xmalloc (sizeof **cwd_state);
1010 if (save_cwd (&(*cwd_state)->saved_cwd) != 0)
1012 (*cwd_state)->saved_errno = errno;
1013 assert (errno != 0);
1015 /* Pretend we started from "/". That is fine as long as there
1016 is no requirement to return to the original working directory.
1017 Use "/", not ".", so that we chdir out of a non-root target
1018 directory before attempting to remove it: some hosts don't let
1019 you remove a working directory. */
1020 (*cwd_state)->saved_cwd.name = xstrdup ("/");
1023 (*cwd_state)->saved_errno = 0;
1025 AD_push_initial (ds, &(*cwd_state)->saved_cwd);
1026 AD_INIT_OTHER_MEMBERS ();
1029 /* If we've failed to record and/or restore the initial working directory,
1030 and we're now trying to access a `.'-relative file name, then give a
1031 diagnostic, record the failure, and proceed with any subsequent
1032 command-line arguments. */
1033 if ((*cwd_state)->saved_errno && IS_RELATIVE_FILE_NAME (dir))
1035 error (0, (*cwd_state)->saved_errno, _("cannot remove directory %s"),
1036 quote (full_filename (dir)));
1037 longjmp (ds->current_arg_jumpbuf, 1);
1040 /* There is a race condition in that an attacker could replace the nonempty
1041 directory, DIR, with a symlink between the preceding call to rmdir
1042 (in our caller) and the chdir below. However, the following lstat,
1043 along with the `stat (".",...' and dev/ino comparison in AD_push
1044 ensure that we detect it and fail. */
1046 if (lstat (dir, &dir_sb))
1049 _("cannot lstat %s"), quote (full_filename (dir)));
1054 if (! S_ISDIR (dir_sb.st_mode) || chdir (dir) != 0)
1056 if (errno == ENOTDIR)
1058 error (0, saved_errno,
1059 _("cannot remove %s"), quote (full_filename (dir)));
1064 _("cannot chdir from %s to %s"),
1065 quote_n (0, full_filename (".")), quote_n (1, dir));
1070 if (ROOT_DEV_INO_CHECK (x->root_dev_ino, &dir_sb))
1072 ROOT_DEV_INO_WARN (full_filename (dir));
1076 AD_push (ds, dir, &dir_sb);
1077 AD_INIT_OTHER_MEMBERS ();
1083 char *subdir = NULL;
1084 struct stat subdir_sb;
1085 enum RM_status tmp_status = remove_cwd_entries (ds,
1086 &subdir, &subdir_sb, x);
1087 if (tmp_status != RM_OK)
1089 UPDATE_STATUS (status, tmp_status);
1090 AD_mark_current_as_unremovable (ds);
1094 AD_push (ds, subdir, &subdir_sb);
1095 AD_INIT_OTHER_MEMBERS ();
1101 /* Execution reaches this point when we've removed the last
1102 removable entry from the current directory. */
1104 /* This is the name of the directory that we have just
1105 returned from, after nominally removing all of its contents. */
1108 if (! AD_pop_and_chdir (ds, &empty_dir))
1109 (*cwd_state)->saved_errno = errno;
1111 /* Note: the above may have failed due to restore_cwd failure.
1112 That failure may be harmless if x->require_restore_cwd is false,
1113 but we do have to remember that fact, including the errno value,
1114 so we can give an accurate diagnostic when reporting the failure
1115 to remove a subsequent relative-named command-line argument. */
1117 /* Try to remove D only if remove_cwd_entries succeeded. */
1118 if (tmp_status == RM_OK)
1120 /* This does a little more work than necessary when it actually
1121 prompts the user. E.g., we already know that D is a directory
1122 and that it's almost certainly empty, yet we lstat it.
1123 But that's no big deal since we're interactive. */
1126 enum RM_status s = prompt (ds, empty_dir, x, PA_REMOVE_DIR,
1127 &is_dir, &is_empty);
1135 if (rmdir (empty_dir) == 0)
1138 printf (_("removed directory: %s\n"),
1139 quote (full_filename (empty_dir)));
1143 error (0, errno, _("cannot remove directory %s"),
1144 quote (full_filename (empty_dir)));
1145 AD_mark_as_unremovable (ds, empty_dir);
1147 UPDATE_STATUS (AD_stack_top(ds)->status, status);
1153 if (AD_stack_height (ds) == 1)
1161 /* Remove the file or directory specified by FILENAME.
1162 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
1163 On input, the first time this function is called, CWD_STATE should be
1164 the address of a NULL pointer. Do not modify it for any subsequent calls.
1165 On output, it is either that same NULL pointer or the address of
1166 a malloc'd `struct saved_cwd' that may be freed. */
1168 static enum RM_status
1169 rm_1 (Dirstack_state *ds, char const *filename,
1170 struct rm_options const *x, struct cwd_state **cwd_state)
1172 char *base = base_name (filename);
1173 enum RM_status status;
1175 if (DOT_OR_DOTDOT (base))
1177 error (0, 0, _("cannot remove `.' or `..'"));
1181 if (*cwd_state && (*cwd_state)->saved_errno
1182 && IS_RELATIVE_FILE_NAME (filename))
1184 error (0, (*cwd_state)->saved_errno,
1185 _("cannot remove %s"), quote (filename));
1189 status = remove_entry (ds, filename, x, NULL);
1190 if (status != RM_NONEMPTY_DIR)
1193 return remove_dir (ds, filename, cwd_state, x);
1196 /* Remove all files and/or directories specified by N_FILES and FILE.
1197 Apply the options in X. */
1198 extern enum RM_status
1199 rm (size_t n_files, char const *const *file, struct rm_options const *x)
1201 struct cwd_state *cwd_state = NULL;
1204 /* Put the following two variables in static storage, so they can't
1205 be clobbered by the potential longjmp into this function. */
1206 static enum RM_status status = RM_OK;
1211 for (i = 0; i < n_files; i++)
1214 cycle_check_init (&ds->cycle_check_state);
1215 /* In the event that rm_1->remove_dir->remove_cwd_entries detects
1216 a directory cycle, arrange to fail, give up on this FILE, but
1217 continue on with any other arguments. */
1218 if (setjmp (ds->current_arg_jumpbuf))
1221 s = rm_1 (ds, file[i], x, &cwd_state);
1222 assert (VALID_STATUS (s));
1223 UPDATE_STATUS (status, s);
1226 if (x->require_restore_cwd && cwd_state && cwd_state->saved_errno != 0)
1228 error (0, cwd_state->saved_errno,
1229 _("cannot restore current working directory"));
1235 if (cwd_state && cwd_state->saved_errno == 0)
1236 free_cwd (&cwd_state->saved_cwd);