1 /* remove.c -- core functions for removing files and directories
2 Copyright (C) 88, 90, 91, 1994-2005 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 /* If anyone knows of another system for which unlink can never
50 remove a directory, please report it to bug-coreutils@gnu.org.
51 The code below is slightly more efficient if it *knows* that
52 unlink(2) cannot possibly unlink a directory. */
54 # define UNLINK_CAN_UNLINK_DIRS 0 /* Good! */
56 # define UNLINK_CAN_UNLINK_DIRS 1 /* Less efficient. */
59 /* This is the maximum number of consecutive readdir/unlink calls that
60 can be made (with no intervening rewinddir or closedir/opendir)
61 before triggering a bug that makes readdir return NULL even though
62 some directory entries have not been processed. The bug afflicts
63 SunOS's readdir when applied to ufs file systems and Darwin 6.5's
64 (and OSX v.10.3.8's) HFS+. This maximum is conservative in that
65 demonstrating the problem seems to require a directory containing
66 at least 254 deletable entries (which doesn't count . and ..), so
67 we could conceivably increase the maximum value to 254. */
70 CONSECUTIVE_READDIR_UNLINK_THRESHOLD = 200
79 typedef enum Ternary Ternary;
81 /* The prompt function may be called twice for a given directory.
82 The first time, we ask whether to descend into it, and the
83 second time, we ask whether to remove it. */
86 PA_DESCEND_INTO_DIR = 2,
90 /* On systems with an lstat function that accepts the empty string,
91 arrange to make lstat calls go through the wrapper function. */
92 #if HAVE_LSTAT_EMPTY_STRING_BUG
93 int rpl_lstat (const char *, struct stat *);
94 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
97 /* Initial capacity of per-directory hash table of entries that have
98 been processed but not been deleted. */
99 #define HT_UNREMOVABLE_INITIAL_CAPACITY 13
101 /* An entry in the active directory stack.
102 Each entry corresponds to an `active' directory. */
105 /* For a given active directory, this is the set of names of
106 entries in that directory that could/should not be removed.
107 For example, `.' and `..', as well as files/dirs for which
108 unlink/rmdir failed e.g., due to access restrictions. */
109 Hash_table *unremovable;
111 /* Record the status for a given active directory; we need to know
112 whether an entry was not removed, either because of an error or
113 because the user declined. */
114 enum RM_status status;
116 /* The directory's dev/ino. Used to ensure that `chdir some-subdir', then
117 `chdir ..' takes us back to the same directory from which we started).
118 (valid for all but the bottommost entry on the stack. */
119 struct dev_ino dev_ino;
122 extern char *program_name;
124 struct dirstack_state
126 /* The name of the directory (starting with and relative to a command
127 line argument) being processed. When a subdirectory is entered, a new
128 component is appended (pushed). Remove (pop) the top component
129 upon chdir'ing out of a directory. This is used to form the full
130 name of the current directory or a file therein, when necessary. */
131 struct obstack dir_stack;
133 /* Stack of lengths of directory names (including trailing slash)
134 appended to dir_stack. We have to have a separate stack of lengths
135 (rather than just popping back to previous slash) because the first
136 element pushed onto the dir stack may contain slashes. */
137 struct obstack len_stack;
139 /* Stack of active directory entries.
140 The first `active' directory is the initial working directory.
141 Additional active dirs are pushed onto the stack as we `chdir'
142 into each directory to be processed. When finished with the
143 hierarchy under a directory, pop the active dir stack. */
144 struct obstack Active_dir;
146 /* Used to detect cycles. */
147 struct cycle_check_state cycle_check_state;
149 /* Target of a longjmp in case rm has to stop processing the current
150 command-line argument. This happens 1) when rm detects a directory
151 cycle or 2) when it has processed one or more directories, but then
152 is unable to return to the initial working directory to process
153 additional `.'-relative command-line arguments. */
154 jmp_buf current_arg_jumpbuf;
156 typedef struct dirstack_state Dirstack_state;
160 /* The value of errno after a failed save_cwd or restore_cwd. */
163 /* Information (open file descriptor or absolute directory name)
164 required in order to restore the initial working directory. */
165 struct saved_cwd saved_cwd;
168 static Dirstack_state *
171 Dirstack_state *ds = xmalloc (sizeof *ds);
172 obstack_init (&ds->dir_stack);
173 obstack_init (&ds->len_stack);
174 obstack_init (&ds->Active_dir);
179 ds_free (Dirstack_state *ds)
181 obstack_free (&ds->dir_stack, NULL);
182 obstack_free (&ds->len_stack, NULL);
183 obstack_free (&ds->Active_dir, NULL);
194 hash_compare_strings (void const *x, void const *y)
196 return STREQ (x, y) ? true : false;
200 push_dir (Dirstack_state *ds, const char *dir_name)
202 size_t len = strlen (dir_name);
204 /* Append the string onto the stack. */
205 obstack_grow (&ds->dir_stack, dir_name, len);
207 /* Append a trailing slash. */
208 obstack_1grow (&ds->dir_stack, '/');
210 /* Add one for the slash. */
213 /* Push the length (including slash) onto its stack. */
214 obstack_grow (&ds->len_stack, &len, sizeof (len));
217 /* Return the entry name of the directory on the top of the stack
218 in malloc'd storage. */
220 top_dir (Dirstack_state const *ds)
222 size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
223 size_t *length = obstack_base (&ds->len_stack);
224 size_t top_len = length[n_lengths - 1];
225 char const *p = obstack_next_free (&ds->dir_stack) - top_len;
226 char *q = xmalloc (top_len);
227 memcpy (q, p, top_len - 1);
233 pop_dir (Dirstack_state *ds)
235 size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
236 size_t *length = obstack_base (&ds->len_stack);
239 assert (n_lengths > 0);
240 top_len = length[n_lengths - 1];
241 assert (top_len >= 2);
243 /* Pop off the specified length of pathname. */
244 assert (obstack_object_size (&ds->dir_stack) >= top_len);
245 obstack_blank (&ds->dir_stack, -top_len);
247 /* Pop the length stack, too. */
248 assert (obstack_object_size (&ds->len_stack) >= sizeof (size_t));
249 obstack_blank (&ds->len_stack, -(int) sizeof (size_t));
252 /* Copy the SRC_LEN bytes of data beginning at SRC into the DST_LEN-byte
253 buffer, DST, so that the last source byte is at the end of the destination
254 buffer. If SRC_LEN is longer than DST_LEN, then set *TRUNCATED.
255 Set *RESULT to point to the beginning of (the portion of) the source data
256 in DST. Return the number of bytes remaining in the destination buffer. */
259 right_justify (char *dst, size_t dst_len, const char *src, size_t src_len,
260 char **result, bool *truncated)
265 if (src_len <= dst_len)
268 dp = dst + (dst_len - src_len);
273 sp = src + (src_len - dst_len);
279 *result = memcpy (dp, sp, src_len);
280 return dst_len - src_len;
283 /* Using the global directory name obstack, create the full path to FILENAME.
284 Return it in sometimes-realloc'd space that should not be freed by the
285 caller. Realloc as necessary. If realloc fails, use a static buffer
286 and put as long a suffix in that buffer as possible. */
288 #define full_filename(Filename) full_filename_ (ds, Filename)
290 full_filename_ (Dirstack_state const *ds, const char *filename)
292 static char *buf = NULL;
293 static size_t n_allocated = 0;
295 size_t dir_len = obstack_object_size (&ds->dir_stack);
296 char *dir_name = obstack_base (&ds->dir_stack);
297 size_t n_bytes_needed;
300 filename_len = strlen (filename);
301 n_bytes_needed = dir_len + filename_len + 1;
303 if (n_allocated < n_bytes_needed)
305 /* This code requires that realloc accept NULL as the first arg.
306 This function must not use xrealloc. Otherwise, an out-of-memory
307 error involving a file name to be expanded here wouldn't ever
308 be issued. Use realloc and fall back on using a static buffer
309 if memory allocation fails. */
310 char *new_buf = realloc (buf, n_bytes_needed);
311 n_allocated = n_bytes_needed;
315 #define SBUF_SIZE 512
316 #define ELLIPSES_PREFIX "[...]"
317 static char static_buf[SBUF_SIZE];
323 len = right_justify (static_buf, SBUF_SIZE, filename,
324 filename_len + 1, &p, &truncated);
325 right_justify (static_buf, len, dir_name, dir_len, &p, &truncated);
328 memcpy (static_buf, ELLIPSES_PREFIX,
329 sizeof (ELLIPSES_PREFIX) - 1);
337 if (filename_len == 1 && *filename == '.' && dir_len)
339 /* FILENAME is just `.' and dir_len is nonzero.
340 Copy the directory part, omitting the trailing slash,
341 and append a trailing zero byte. */
342 char *p = mempcpy (buf, dir_name, dir_len - 1);
347 /* Copy the directory part, including trailing slash, and then
348 append the filename part, including a trailing zero byte. */
349 memcpy (mempcpy (buf, dir_name, dir_len), filename, filename_len + 1);
350 assert (strlen (buf) + 1 == n_bytes_needed);
357 AD_stack_height (Dirstack_state const *ds)
359 return obstack_object_size (&ds->Active_dir) / sizeof (struct AD_ent);
362 static struct AD_ent *
363 AD_stack_top (Dirstack_state const *ds)
365 return (struct AD_ent *)
366 ((char *) obstack_next_free (&ds->Active_dir) - sizeof (struct AD_ent));
370 AD_stack_pop (Dirstack_state *ds)
372 /* operate on Active_dir. pop and free top entry */
373 struct AD_ent *top = AD_stack_top (ds);
374 if (top->unremovable)
375 hash_free (top->unremovable);
376 obstack_blank (&ds->Active_dir, -(int) sizeof (struct AD_ent));
380 /* chdir `up' one level.
381 Whenever using chdir '..', verify that the post-chdir
382 dev/ino numbers for `.' match the saved ones.
383 If they don't match, exit nonzero.
384 Set *PREV_DIR to the name (in malloc'd storage) of the
385 directory (usually now empty) from which we're coming.
386 If we're at the bottom of the AD stack (about to return
387 to the initial working directory), then use CWD.
388 If that restore_cwd fails, set CWD_STATE->saved_errno. */
390 AD_pop_and_chdir (Dirstack_state *ds, char **prev_dir,
391 struct cwd_state *cwd_state)
393 enum RM_status old_status = AD_stack_top(ds)->status;
396 /* Get the name of the current (but soon to be `previous') directory
397 from the top of the stack. */
398 *prev_dir = top_dir (ds);
401 top = AD_stack_top (ds);
403 /* Propagate any failure to parent. */
404 UPDATE_STATUS (top->status, old_status);
406 assert (AD_stack_height (ds));
408 if (1 < AD_stack_height (ds))
412 /* We can give a better diagnostic here, since the target is relative. */
413 if (chdir ("..") != 0)
415 error (EXIT_FAILURE, errno,
416 _("cannot chdir from %s to .."),
417 quote (full_filename (".")));
420 if (lstat (".", &sb))
421 error (EXIT_FAILURE, errno,
422 _("cannot lstat `.' in %s"), quote (full_filename (".")));
424 /* Ensure that post-chdir dev/ino match the stored ones. */
425 if ( ! SAME_INODE (sb, top->dev_ino))
426 error (EXIT_FAILURE, 0,
427 _("%s changed dev/ino"), quote (full_filename (".")));
431 if (restore_cwd (&cwd_state->saved_cwd) != 0)
433 /* We've failed to return to the initial working directory.
434 That failure may be harmless if x->require_restore_cwd is false,
435 but we do have to remember that fact, including the errno value,
436 so we can give an accurate diagnostic when reporting the failure
437 to remove a subsequent relative-named command-line argument. */
438 cwd_state->saved_errno = errno;
443 /* Initialize *HT if it is NULL.
444 Insert FILENAME into HT. */
446 AD_mark_helper (Hash_table **ht, char const *filename)
450 *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw,
451 hash_compare_strings, hash_freer);
455 if (! hash_insert (*ht, filename))
459 /* Mark FILENAME (in current directory) as unremovable. */
461 AD_mark_as_unremovable (Dirstack_state *ds, char const *filename)
463 AD_mark_helper (&AD_stack_top(ds)->unremovable, xstrdup (filename));
466 /* Mark the current directory as unremovable. I.e., mark the entry
467 in the parent directory corresponding to `.'.
468 This happens e.g., when an opendir fails and the only name
469 the caller has conveniently at hand is `.'. */
471 AD_mark_current_as_unremovable (Dirstack_state *ds)
473 struct AD_ent *top = AD_stack_top (ds);
474 const char *curr = top_dir (ds);
476 assert (1 < AD_stack_height (ds));
479 AD_mark_helper (&top->unremovable, curr);
482 /* Push an initial dummy entry onto the stack.
483 This will always be the bottommost entry on the stack. */
485 AD_push_initial (Dirstack_state *ds)
489 /* Extend the stack. */
490 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
492 /* Fill in the new values. */
493 top = AD_stack_top (ds);
494 top->unremovable = NULL;
496 /* These should never be used.
497 Give them values that might look suspicious
498 in a debugger or in a diagnostic. */
499 top->dev_ino.st_dev = TYPE_MAXIMUM (dev_t);
500 top->dev_ino.st_ino = TYPE_MAXIMUM (ino_t);
503 /* Push info about the current working directory (".") onto the
504 active directory stack. DIR is the ./-relative name through
505 which we've just `chdir'd to this directory. DIR_SB_FROM_PARENT
506 is the result of calling lstat on DIR from the parent of DIR. */
508 AD_push (Dirstack_state *ds, char const *dir,
509 struct stat const *dir_sb_from_parent)
516 if (lstat (".", &sb))
517 error (EXIT_FAILURE, errno,
518 _("cannot lstat `.' in %s"), quote (full_filename (".")));
520 if ( ! SAME_INODE (sb, *dir_sb_from_parent))
521 error (EXIT_FAILURE, 0,
522 _("%s changed dev/ino"), quote (full_filename (".")));
524 /* Extend the stack. */
525 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
527 /* Fill in the new values. */
528 top = AD_stack_top (ds);
529 top->dev_ino.st_dev = sb.st_dev;
530 top->dev_ino.st_ino = sb.st_ino;
531 top->unremovable = NULL;
535 AD_is_removable (Dirstack_state const *ds, char const *file)
537 struct AD_ent *top = AD_stack_top (ds);
538 return ! (top->unremovable && hash_lookup (top->unremovable, file));
541 /* Return true if DIR is determined to be an empty directory
542 or if opendir or readdir fails. */
544 is_empty_dir (char const *dir)
546 DIR *dirp = opendir (dir);
547 struct dirent const *dp;
554 dp = readdir_ignoring_dot_and_dotdot (dirp);
559 return saved_errno == 0 ? true : false;
562 /* Return true if FILE is not a symbolic link and it is not writable.
563 Also return true if FILE cannot be lstat'ed. Otherwise, return false.
564 If lstat succeeds, set *BUF_P to BUF.
565 This is to avoid calling euidaccess when FILE is a symlink. */
567 write_protected_non_symlink (char const *file,
571 if (lstat (file, buf) != 0)
574 if (S_ISLNK (buf->st_mode))
576 return euidaccess (file, W_OK) == -1 && errno == EACCES;
579 /* Prompt whether to remove FILENAME, if required via a combination of
580 the options specified by X and/or file attributes. If the file may
581 be removed, return RM_OK. If the user declines to remove the file,
582 return RM_USER_DECLINED. If not ignoring missing files and we
583 cannot lstat FILENAME, then return RM_ERROR.
585 Depending on MODE, ask whether to `descend into' or to `remove' the
586 directory FILENAME. MODE is ignored when FILENAME is not a directory.
587 Set *IS_EMPTY to T_YES if FILENAME is an empty directory, and it is
588 appropriate to try to remove it with rmdir (e.g. recursive mode).
589 Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR.
590 Set *IS_DIR to T_YES or T_NO if we happen to determine whether
591 FILENAME is a directory. */
592 static enum RM_status
593 prompt (Dirstack_state const *ds, char const *filename,
594 struct rm_options const *x, enum Prompt_action mode,
595 Ternary *is_dir, Ternary *is_empty)
597 bool write_protected = false;
598 struct stat *sbuf = NULL;
601 *is_empty = T_UNKNOWN;
604 if (((!x->ignore_missing_files & (x->interactive | x->stdin_tty))
605 && (write_protected = write_protected_non_symlink (filename,
612 if (lstat (filename, sbuf))
614 /* lstat failed. This happens e.g., with `rm '''. */
615 error (0, errno, _("cannot lstat %s"),
616 quote (full_filename (filename)));
621 if (S_ISDIR (sbuf->st_mode) && !x->recursive)
623 error (0, EISDIR, _("cannot remove directory %s"),
624 quote (full_filename (filename)));
628 /* Using permissions doesn't make sense for symlinks. */
629 if (S_ISLNK (sbuf->st_mode))
631 if ( ! x->interactive)
633 write_protected = false;
636 /* Issue the prompt. */
638 char const *quoted_name = quote (full_filename (filename));
640 *is_dir = (S_ISDIR (sbuf->st_mode) ? T_YES : T_NO);
642 /* FIXME: use a variant of error (instead of fprintf) that doesn't
643 append a newline. Then we won't have to declare program_name in
645 if (S_ISDIR (sbuf->st_mode)
647 && mode == PA_DESCEND_INTO_DIR
648 && ((*is_empty = (is_empty_dir (filename) ? T_YES : T_NO))
652 ? _("%s: descend into write-protected directory %s? ")
653 : _("%s: descend into directory %s? ")),
654 program_name, quoted_name);
657 /* TRANSLATORS: You may find it more convenient to translate
658 the equivalent of _("%s: remove %s (write-protected) %s? ").
659 It should avoid grammatical problems with the output
663 ? _("%s: remove write-protected %s %s? ")
664 : _("%s: remove %s %s? ")),
665 program_name, file_type (sbuf), quoted_name);
669 return RM_USER_DECLINED;
675 #if HAVE_STRUCT_DIRENT_D_TYPE
676 # define DT_IS_DIR(D) ((D)->d_type == DT_DIR)
678 /* Use this only if the member exists -- i.e., don't return 0. */
679 # define DT_IS_DIR(D) do_not_use_this_macro
682 #define DO_UNLINK(Filename, X) \
685 if (unlink (Filename) == 0) \
688 printf (_("removed %s\n"), quote (full_filename (Filename))); \
692 if (errno == ENOENT && (X)->ignore_missing_files) \
697 #define DO_RMDIR(Filename, X) \
700 if (rmdir (Filename) == 0) \
703 printf (_("removed directory: %s\n"), \
704 quote (full_filename (Filename))); \
708 if (errno == ENOENT && (X)->ignore_missing_files) \
711 if (errno == ENOTEMPTY || errno == EEXIST) \
712 return RM_NONEMPTY_DIR; \
716 /* Remove the file or directory specified by FILENAME.
717 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
718 But if FILENAME specifies a non-empty directory, return RM_NONEMPTY_DIR. */
720 static enum RM_status
721 remove_entry (Dirstack_state const *ds, char const *filename,
722 struct rm_options const *x, struct dirent const *dp)
725 Ternary is_empty_directory;
726 enum RM_status s = prompt (ds, filename, x, PA_DESCEND_INTO_DIR,
727 &is_dir, &is_empty_directory);
732 /* Why bother with the following #if/#else block? Because on systems with
733 an unlink function that *can* unlink directories, we must determine the
734 type of each entry before removing it. Otherwise, we'd risk unlinking
735 an entire directory tree simply by unlinking a single directory; then
736 all the storage associated with that hierarchy would not be freed until
737 the next reboot. Not nice. To avoid that, on such slightly losing
738 systems, we need to call lstat to determine the type of each entry,
739 and that represents extra overhead that -- it turns out -- we can
740 avoid on GNU-libc-based systems, since there, unlink will never remove
741 a directory. Also, on systems where unlink may unlink directories,
742 we're forced to allow a race condition: we lstat a non-directory, then
743 go to unlink it, but in the mean time, a malicious someone has replaced
744 it with a directory. */
746 #if UNLINK_CAN_UNLINK_DIRS
748 /* If we don't already know whether FILENAME is a directory, find out now.
749 Then, if it's a non-directory, we can use unlink on it. */
750 if (is_dir == T_UNKNOWN)
752 # if HAVE_STRUCT_DIRENT_D_TYPE
753 if (dp && dp->d_type != DT_UNKNOWN)
754 is_dir = DT_IS_DIR (dp) ? T_YES : T_NO;
759 if (lstat (filename, &sbuf))
761 if (errno == ENOENT && x->ignore_missing_files)
765 _("cannot lstat %s"), quote (full_filename (filename)));
769 is_dir = S_ISDIR (sbuf.st_mode) ? T_YES : T_NO;
775 /* At this point, barring race conditions, FILENAME is known
776 to be a non-directory, so it's ok to try to unlink it. */
777 DO_UNLINK (filename, x);
779 /* unlink failed with some other error code. report it. */
780 error (0, errno, _("cannot remove %s"),
781 quote (full_filename (filename)));
787 error (0, EISDIR, _("cannot remove directory %s"),
788 quote (full_filename (filename)));
792 if (is_empty_directory == T_YES)
794 DO_RMDIR (filename, x);
795 /* Don't diagnose any failure here.
796 It'll be detected when the caller tries another way. */
800 #else /* ! UNLINK_CAN_UNLINK_DIRS */
802 if (is_dir == T_YES && ! x->recursive)
804 error (0, EISDIR, _("cannot remove directory %s"),
805 quote (full_filename (filename)));
809 /* is_empty_directory is set iff it's ok to use rmdir.
810 Note that it's set only in interactive mode -- in which case it's
811 an optimization that arranges so that the user is asked just
812 once whether to remove the directory. */
813 if (is_empty_directory == T_YES)
814 DO_RMDIR (filename, x);
816 /* If we happen to know that FILENAME is a directory, return now
817 and let the caller remove it -- this saves the overhead of a failed
818 unlink call. If FILENAME is a command-line argument, then dp is NULL,
819 so we'll first try to unlink it. Using unlink here is ok, because it
820 cannot remove a directory. */
821 if ((dp && DT_IS_DIR (dp)) || is_dir == T_YES)
822 return RM_NONEMPTY_DIR;
824 DO_UNLINK (filename, x);
827 || errno == ENOENT || errno == ENOTDIR
828 || errno == ELOOP || errno == ENAMETOOLONG)
830 /* Either --recursive is not in effect, or the file cannot be a
831 directory. Report the unlink problem and fail. */
832 error (0, errno, _("cannot remove %s"),
833 quote (full_filename (filename)));
838 return RM_NONEMPTY_DIR;
841 /* Remove entries in `.', the current working directory (cwd).
842 Upon finding a directory that is both non-empty and that can be chdir'd
843 into, return RM_OK and set *SUBDIR and fill in SUBDIR_SB, where
844 SUBDIR is the malloc'd name of the subdirectory if the chdir succeeded,
845 NULL otherwise (e.g., if opendir failed or if there was no subdirectory).
846 Likewise, SUBDIR_SB is the result of calling lstat on SUBDIR.
847 Return RM_OK if all entries are removed. Return RM_ERROR if any
848 entry cannot be removed. Otherwise, return RM_USER_DECLINED if
849 the user declines to remove at least one entry. Remove as much as
850 possible, continuing even if we fail to remove some entries. */
851 static enum RM_status
852 remove_cwd_entries (Dirstack_state *ds, char **subdir, struct stat *subdir_sb,
853 struct rm_options const *x)
855 DIR *dirp = opendir (".");
856 struct AD_ent *top = AD_stack_top (ds);
857 enum RM_status status = top->status;
858 size_t n_unlinked_since_opendir_or_last_rewind = 0;
860 assert (VALID_STATUS (status));
865 if (errno != ENOENT || !x->ignore_missing_files)
867 error (0, errno, _("cannot open directory %s"),
868 quote (full_filename (".")));
875 struct dirent const *dp;
876 enum RM_status tmp_status;
879 /* Set errno to zero so we can distinguish between a readdir failure
880 and when readdir simply finds that there are no more entries. */
882 if ((dp = readdir_ignoring_dot_and_dotdot (dirp)) == NULL)
886 /* Save/restore errno across closedir call. */
891 /* Arrange to give a diagnostic after exiting this loop. */
894 else if (CONSECUTIVE_READDIR_UNLINK_THRESHOLD
895 < n_unlinked_since_opendir_or_last_rewind)
897 /* Call rewinddir if we've called unlink or rmdir so many times
898 (since the opendir or the previous rewinddir) that this
899 NULL-return may be the symptom of a buggy readdir. */
901 n_unlinked_since_opendir_or_last_rewind = 0;
909 /* Skip files we've already tried/failed to remove. */
910 if ( ! AD_is_removable (ds, f))
913 /* Pass dp->d_type info to remove_entry so the non-glibc
914 case can decide whether to use unlink or chdir.
915 Systems without the d_type member will have to endure
916 the performance hit of first calling lstat F. */
917 tmp_status = remove_entry (ds, f, x, dp);
921 /* Count how many files we've unlinked since the initial
922 opendir or the last rewinddir. On buggy systems, if you
923 remove too many, readdir return NULL even though there
924 remain unprocessed directory entries. */
925 ++n_unlinked_since_opendir_or_last_rewind;
929 case RM_USER_DECLINED:
930 AD_mark_as_unremovable (ds, f);
931 UPDATE_STATUS (status, tmp_status);
934 case RM_NONEMPTY_DIR:
936 /* Save a copy of errno, in case the preceding unlink (from
937 remove_entry's DO_UNLINK) of a non-directory failed. */
938 int saved_errno = errno;
940 /* Record dev/ino of F so that we can compare
941 that with dev/ino of `.' after the chdir.
942 This dev/ino pair is also used in cycle detection. */
943 if (lstat (f, subdir_sb))
944 error (EXIT_FAILURE, errno, _("cannot lstat %s"),
945 quote (full_filename (f)));
948 if (! S_ISDIR (subdir_sb->st_mode) || chdir (f) != 0)
950 /* It is much more common that we reach this point for an
951 inaccessible directory. Hence the second diagnostic, below.
952 However it is also possible that F is a non-directory.
953 That can happen when we use the `! UNLINK_CAN_UNLINK_DIRS'
954 block of code and when DO_UNLINK fails due to EPERM.
955 In that case, give a better diagnostic. */
956 if (errno == ENOTDIR)
957 error (0, saved_errno, _("cannot remove %s"),
958 quote (full_filename (f)));
960 error (0, errno, _("cannot chdir from %s to %s"),
961 quote_n (0, full_filename (".")), quote_n (1, f));
962 AD_mark_as_unremovable (ds, f);
966 if (cycle_check (&ds->cycle_check_state, subdir_sb))
969 WARNING: Circular directory structure.\n\
970 This almost certainly means that you have a corrupted file system.\n\
971 NOTIFY YOUR SYSTEM MANAGER.\n\
972 The following directory is part of the cycle:\n %s\n"),
973 quote (full_filename (".")));
974 longjmp (ds->current_arg_jumpbuf, 1);
977 *subdir = xstrdup (f);
982 /* Record status for this directory. */
983 UPDATE_STATUS (top->status, status);
989 if (dirp == NULL || CLOSEDIR (dirp) != 0)
991 /* Note that this diagnostic serves for both readdir
992 and closedir failures. */
993 error (0, errno, _("reading directory %s"), quote (full_filename (".")));
1000 /* Do this after each call to AD_push or AD_push_initial.
1001 Because the status = RM_OK bit is too remove-specific to
1002 go into the general-purpose AD_* package. */
1003 #define AD_INIT_OTHER_MEMBERS() \
1006 AD_stack_top(ds)->status = RM_OK; \
1010 /* Remove the hierarchy rooted at DIR.
1011 Do that by changing into DIR, then removing its contents, then
1012 returning to the original working directory and removing DIR itself.
1013 Don't use recursion. Be careful when using chdir ".." that we
1014 return to the same directory from which we came, if necessary.
1015 Return 1 for success, 0 if some file cannot be removed or if
1017 If the initial working directory cannot be saved or restored,
1018 record the offending errno value in (*CWD_STATE)->saved_errno. */
1020 static enum RM_status
1021 remove_dir (Dirstack_state *ds, char const *dir, struct cwd_state **cwd_state,
1022 struct rm_options const *x)
1024 enum RM_status status;
1027 /* Save any errno (from caller's failed remove_entry call), in case DIR
1028 is not a directory, so that we can give a reasonable diagnostic. */
1029 int saved_errno = errno;
1031 if (*cwd_state == NULL)
1033 *cwd_state = xmalloc (sizeof **cwd_state);
1035 if (save_cwd (&(*cwd_state)->saved_cwd) != 0)
1037 (*cwd_state)->saved_errno = errno;
1038 assert (errno != 0);
1040 /* Pretend we started from "/". That is fine as long as there
1041 is no requirement to return to the original working directory.
1042 Use "/", not ".", so that we chdir out of a non-root target
1043 directory before attempting to remove it: some hosts don't let
1044 you remove a working directory. */
1045 (*cwd_state)->saved_cwd.name = xstrdup ("/");
1048 (*cwd_state)->saved_errno = 0;
1050 AD_push_initial (ds);
1051 AD_INIT_OTHER_MEMBERS ();
1054 /* If we've failed to record and/or restore the initial working directory,
1055 and we're now trying to access a `.'-relative file name, then give a
1056 diagnostic, record the failure, and proceed with any subsequent
1057 command-line arguments. */
1058 if ((*cwd_state)->saved_errno && IS_RELATIVE_FILE_NAME (dir))
1060 error (0, (*cwd_state)->saved_errno, _("cannot remove directory %s"),
1061 quote (full_filename (dir)));
1062 longjmp (ds->current_arg_jumpbuf, 1);
1065 /* There is a race condition in that an attacker could replace the nonempty
1066 directory, DIR, with a symlink between the preceding call to rmdir
1067 (in our caller) and the chdir below. However, the following lstat,
1068 along with the `stat (".",...' and dev/ino comparison in AD_push
1069 ensure that we detect it and fail. */
1071 if (lstat (dir, &dir_sb))
1074 _("cannot lstat %s"), quote (full_filename (dir)));
1079 if (! S_ISDIR (dir_sb.st_mode) || chdir (dir) != 0)
1081 if (errno == ENOTDIR)
1083 error (0, saved_errno,
1084 _("cannot remove %s"), quote (full_filename (dir)));
1089 _("cannot chdir from %s to %s"),
1090 quote_n (0, full_filename (".")), quote_n (1, dir));
1095 if (ROOT_DEV_INO_CHECK (x->root_dev_ino, &dir_sb))
1097 ROOT_DEV_INO_WARN (full_filename (dir));
1101 AD_push (ds, dir, &dir_sb);
1102 AD_INIT_OTHER_MEMBERS ();
1108 char *subdir = NULL;
1109 struct stat subdir_sb;
1110 enum RM_status tmp_status = remove_cwd_entries (ds,
1111 &subdir, &subdir_sb, x);
1112 if (tmp_status != RM_OK)
1114 UPDATE_STATUS (status, tmp_status);
1115 AD_mark_current_as_unremovable (ds);
1119 AD_push (ds, subdir, &subdir_sb);
1120 AD_INIT_OTHER_MEMBERS ();
1126 /* Execution reaches this point when we've removed the last
1127 removable entry from the current directory. */
1129 /* This is the name of the directory that we have just
1130 returned from, after nominally removing all of its contents. */
1133 AD_pop_and_chdir (ds, &empty_dir, *cwd_state);
1135 /* Try to remove D only if remove_cwd_entries succeeded. */
1136 if (tmp_status == RM_OK)
1138 /* This does a little more work than necessary when it actually
1139 prompts the user. E.g., we already know that D is a directory
1140 and that it's almost certainly empty, yet we lstat it.
1141 But that's no big deal since we're interactive. */
1144 enum RM_status s = prompt (ds, empty_dir, x, PA_REMOVE_DIR,
1145 &is_dir, &is_empty);
1153 if (rmdir (empty_dir) == 0)
1156 printf (_("removed directory: %s\n"),
1157 quote (full_filename (empty_dir)));
1161 error (0, errno, _("cannot remove directory %s"),
1162 quote (full_filename (empty_dir)));
1163 AD_mark_as_unremovable (ds, empty_dir);
1165 UPDATE_STATUS (AD_stack_top(ds)->status, status);
1171 if (AD_stack_height (ds) == 1)
1179 /* Remove the file or directory specified by FILENAME.
1180 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
1181 On input, the first time this function is called, CWD_STATE should be
1182 the address of a NULL pointer. Do not modify it for any subsequent calls.
1183 On output, it is either that same NULL pointer or the address of
1184 a malloc'd `struct saved_cwd' that may be freed. */
1186 static enum RM_status
1187 rm_1 (Dirstack_state *ds, char const *filename,
1188 struct rm_options const *x, struct cwd_state **cwd_state)
1190 char *base = base_name (filename);
1191 enum RM_status status;
1193 if (DOT_OR_DOTDOT (base))
1195 error (0, 0, _("cannot remove `.' or `..'"));
1199 if (*cwd_state && (*cwd_state)->saved_errno
1200 && IS_RELATIVE_FILE_NAME (filename))
1202 error (0, (*cwd_state)->saved_errno,
1203 _("cannot remove %s"), quote (filename));
1207 status = remove_entry (ds, filename, x, NULL);
1208 if (status != RM_NONEMPTY_DIR)
1211 return remove_dir (ds, filename, cwd_state, x);
1214 /* Remove all files and/or directories specified by N_FILES and FILE.
1215 Apply the options in X. If X->require_restore_cwd is false, then
1216 this function may return RM_OK even though it is unable to restore
1217 the initial working directory. */
1218 extern enum RM_status
1219 rm (size_t n_files, char const *const *file, struct rm_options const *x)
1221 struct cwd_state *cwd_state = NULL;
1224 /* Put the following two variables in static storage, so they can't
1225 be clobbered by the potential longjmp into this function. */
1226 static enum RM_status status = RM_OK;
1231 for (i = 0; i < n_files; i++)
1234 cycle_check_init (&ds->cycle_check_state);
1235 /* In the event that rm_1->remove_dir->remove_cwd_entries detects
1236 a directory cycle, arrange to fail, give up on this FILE, but
1237 continue on with any other arguments. */
1238 if (setjmp (ds->current_arg_jumpbuf))
1241 s = rm_1 (ds, file[i], x, &cwd_state);
1242 assert (VALID_STATUS (s));
1243 UPDATE_STATUS (status, s);
1246 if (x->require_restore_cwd && cwd_state && cwd_state->saved_errno != 0)
1248 error (0, cwd_state->saved_errno,
1249 _("cannot restore current working directory"));
1255 if (cwd_state && cwd_state->saved_errno == 0)
1256 free_cwd (&cwd_state->saved_cwd);