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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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"
39 #include "root-dev-ino.h"
40 #include "unlinkdir.h"
43 /* Avoid shadowing warnings because these are functions declared
44 in dirname.h as well as locals used below. */
45 #define dir_name rm_dir_name
46 #define dir_len rm_dir_len
48 #define obstack_chunk_alloc malloc
49 #define obstack_chunk_free free
51 /* This is the maximum number of consecutive readdir/unlink calls that
52 can be made (with no intervening rewinddir or closedir/opendir)
53 before triggering a bug that makes readdir return NULL even though
54 some directory entries have not been processed. The bug afflicts
55 SunOS's readdir when applied to ufs file systems and Darwin 6.5's
56 (and OSX v.10.3.8's) HFS+. This maximum is conservative in that
57 demonstrating the problem seems to require a directory containing
58 at least 254 deletable entries (which doesn't count . and ..), so
59 we could conceivably increase the maximum value to 254. */
62 CONSECUTIVE_READDIR_UNLINK_THRESHOLD = 200
71 typedef enum Ternary Ternary;
73 /* The prompt function may be called twice for a given directory.
74 The first time, we ask whether to descend into it, and the
75 second time, we ask whether to remove it. */
78 PA_DESCEND_INTO_DIR = 2,
82 /* Initial capacity of per-directory hash table of entries that have
83 been processed but not been deleted. */
84 #define HT_UNREMOVABLE_INITIAL_CAPACITY 13
86 /* An entry in the active directory stack.
87 Each entry corresponds to an `active' directory. */
90 /* For a given active directory, this is the set of names of
91 entries in that directory that could/should not be removed.
92 For example, `.' and `..', as well as files/dirs for which
93 unlink/rmdir failed e.g., due to access restrictions. */
94 Hash_table *unremovable;
96 /* Record the status for a given active directory; we need to know
97 whether an entry was not removed, either because of an error or
98 because the user declined. */
99 enum RM_status status;
101 /* The directory's dev/ino. Used to ensure that `chdir some-subdir', then
102 `chdir ..' takes us back to the same directory from which we started).
103 (valid for all but the bottommost entry on the stack. */
104 struct dev_ino dev_ino;
107 extern char *program_name;
109 struct dirstack_state
111 /* The name of the directory (starting with and relative to a command
112 line argument) being processed. When a subdirectory is entered, a new
113 component is appended (pushed). Remove (pop) the top component
114 upon chdir'ing out of a directory. This is used to form the full
115 name of the current directory or a file therein, when necessary. */
116 struct obstack dir_stack;
118 /* Stack of lengths of directory names (including trailing slash)
119 appended to dir_stack. We have to have a separate stack of lengths
120 (rather than just popping back to previous slash) because the first
121 element pushed onto the dir stack may contain slashes. */
122 struct obstack len_stack;
124 /* Stack of active directory entries.
125 The first `active' directory is the initial working directory.
126 Additional active dirs are pushed onto the stack as we `chdir'
127 into each directory to be processed. When finished with the
128 hierarchy under a directory, pop the active dir stack. */
129 struct obstack Active_dir;
131 /* Used to detect cycles. */
132 struct cycle_check_state cycle_check_state;
134 /* Target of a longjmp in case rm has to stop processing the current
135 command-line argument. This happens 1) when rm detects a directory
136 cycle or 2) when it has processed one or more directories, but then
137 is unable to return to the initial working directory to process
138 additional `.'-relative command-line arguments. */
139 jmp_buf current_arg_jumpbuf;
141 typedef struct dirstack_state Dirstack_state;
145 /* The value of errno after a failed save_cwd or restore_cwd. */
148 /* Information (open file descriptor or absolute directory name)
149 required in order to restore the initial working directory. */
150 struct saved_cwd saved_cwd;
153 static Dirstack_state *
156 Dirstack_state *ds = xmalloc (sizeof *ds);
157 obstack_init (&ds->dir_stack);
158 obstack_init (&ds->len_stack);
159 obstack_init (&ds->Active_dir);
164 ds_free (Dirstack_state *ds)
166 obstack_free (&ds->dir_stack, NULL);
167 obstack_free (&ds->len_stack, NULL);
168 obstack_free (&ds->Active_dir, NULL);
179 hash_compare_strings (void const *x, void const *y)
181 return STREQ (x, y) ? true : false;
185 push_dir (Dirstack_state *ds, const char *dir_name)
187 size_t len = strlen (dir_name);
189 /* Append the string onto the stack. */
190 obstack_grow (&ds->dir_stack, dir_name, len);
192 /* Append a trailing slash. */
193 obstack_1grow (&ds->dir_stack, '/');
195 /* Add one for the slash. */
198 /* Push the length (including slash) onto its stack. */
199 obstack_grow (&ds->len_stack, &len, sizeof (len));
202 /* Return the entry name of the directory on the top of the stack
203 in malloc'd storage. */
205 top_dir (Dirstack_state const *ds)
207 size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
208 size_t *length = obstack_base (&ds->len_stack);
209 size_t top_len = length[n_lengths - 1];
210 char const *p = obstack_next_free (&ds->dir_stack) - top_len;
211 char *q = xmalloc (top_len);
212 memcpy (q, p, top_len - 1);
218 pop_dir (Dirstack_state *ds)
220 size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
221 size_t *length = obstack_base (&ds->len_stack);
224 assert (n_lengths > 0);
225 top_len = length[n_lengths - 1];
226 assert (top_len >= 2);
228 /* Pop the specified length of file name. */
229 assert (obstack_object_size (&ds->dir_stack) >= top_len);
230 obstack_blank (&ds->dir_stack, -top_len);
232 /* Pop the length stack, too. */
233 assert (obstack_object_size (&ds->len_stack) >= sizeof (size_t));
234 obstack_blank (&ds->len_stack, -(int) sizeof (size_t));
237 /* Copy the SRC_LEN bytes of data beginning at SRC into the DST_LEN-byte
238 buffer, DST, so that the last source byte is at the end of the destination
239 buffer. If SRC_LEN is longer than DST_LEN, then set *TRUNCATED.
240 Set *RESULT to point to the beginning of (the portion of) the source data
241 in DST. Return the number of bytes remaining in the destination buffer. */
244 right_justify (char *dst, size_t dst_len, const char *src, size_t src_len,
245 char **result, bool *truncated)
250 if (src_len <= dst_len)
253 dp = dst + (dst_len - src_len);
258 sp = src + (src_len - dst_len);
264 *result = memcpy (dp, sp, src_len);
265 return dst_len - src_len;
268 /* Using the global directory name obstack, create the full name FILENAME.
269 Return it in sometimes-realloc'd space that should not be freed by the
270 caller. Realloc as necessary. If realloc fails, use a static buffer
271 and put as long a suffix in that buffer as possible. */
273 #define full_filename(Filename) full_filename_ (ds, Filename)
275 full_filename_ (Dirstack_state const *ds, const char *filename)
277 static char *buf = NULL;
278 static size_t n_allocated = 0;
280 size_t dir_len = obstack_object_size (&ds->dir_stack);
281 char *dir_name = obstack_base (&ds->dir_stack);
282 size_t n_bytes_needed;
285 filename_len = strlen (filename);
286 n_bytes_needed = dir_len + filename_len + 1;
288 if (n_allocated < n_bytes_needed)
290 /* This code requires that realloc accept NULL as the first arg.
291 This function must not use xrealloc. Otherwise, an out-of-memory
292 error involving a file name to be expanded here wouldn't ever
293 be issued. Use realloc and fall back on using a static buffer
294 if memory allocation fails. */
295 char *new_buf = realloc (buf, n_bytes_needed);
296 n_allocated = n_bytes_needed;
300 #define SBUF_SIZE 512
301 #define ELLIPSES_PREFIX "[...]"
302 static char static_buf[SBUF_SIZE];
308 len = right_justify (static_buf, SBUF_SIZE, filename,
309 filename_len + 1, &p, &truncated);
310 right_justify (static_buf, len, dir_name, dir_len, &p, &truncated);
313 memcpy (static_buf, ELLIPSES_PREFIX,
314 sizeof (ELLIPSES_PREFIX) - 1);
322 if (filename_len == 1 && *filename == '.' && dir_len)
324 /* FILENAME is just `.' and dir_len is nonzero.
325 Copy the directory part, omitting the trailing slash,
326 and append a trailing zero byte. */
327 char *p = mempcpy (buf, dir_name, dir_len - 1);
332 /* Copy the directory part, including trailing slash, and then
333 append the filename part, including a trailing zero byte. */
334 memcpy (mempcpy (buf, dir_name, dir_len), filename, filename_len + 1);
335 assert (strlen (buf) + 1 == n_bytes_needed);
342 AD_stack_height (Dirstack_state const *ds)
344 return obstack_object_size (&ds->Active_dir) / sizeof (struct AD_ent);
347 static struct AD_ent *
348 AD_stack_top (Dirstack_state const *ds)
350 return (struct AD_ent *)
351 ((char *) obstack_next_free (&ds->Active_dir) - sizeof (struct AD_ent));
355 AD_stack_pop (Dirstack_state *ds)
357 /* operate on Active_dir. pop and free top entry */
358 struct AD_ent *top = AD_stack_top (ds);
359 if (top->unremovable)
360 hash_free (top->unremovable);
361 obstack_blank (&ds->Active_dir, -(int) sizeof (struct AD_ent));
365 /* chdir `up' one level.
366 Whenever using chdir '..', verify that the post-chdir
367 dev/ino numbers for `.' match the saved ones.
368 If they don't match, exit nonzero.
369 Set *PREV_DIR to the name (in malloc'd storage) of the
370 directory (usually now empty) from which we're coming.
371 If we're at the bottom of the AD stack (about to return
372 to the initial working directory), then use CWD.
373 If that restore_cwd fails, set CWD_STATE->saved_errno. */
375 AD_pop_and_chdir (Dirstack_state *ds, char **prev_dir,
376 struct cwd_state *cwd_state)
378 enum RM_status old_status = AD_stack_top(ds)->status;
381 /* Get the name of the current (but soon to be `previous') directory
382 from the top of the stack. */
383 *prev_dir = top_dir (ds);
386 top = AD_stack_top (ds);
388 /* Propagate any failure to parent. */
389 UPDATE_STATUS (top->status, old_status);
391 assert (AD_stack_height (ds));
393 if (1 < AD_stack_height (ds))
397 /* We can give a better diagnostic here, since the target is relative. */
398 if (chdir ("..") != 0)
400 error (EXIT_FAILURE, errno,
401 _("cannot chdir from %s to .."),
402 quote (full_filename (".")));
405 if (lstat (".", &sb))
406 error (EXIT_FAILURE, errno,
407 _("cannot lstat `.' in %s"), quote (full_filename (".")));
409 /* Ensure that post-chdir dev/ino match the stored ones. */
410 if ( ! SAME_INODE (sb, top->dev_ino))
411 error (EXIT_FAILURE, 0,
412 _("%s changed dev/ino"), quote (full_filename (".")));
416 if (restore_cwd (&cwd_state->saved_cwd) != 0)
418 /* We've failed to return to the initial working directory.
419 That failure may be harmless if x->require_restore_cwd is false,
420 but we do have to remember that fact, including the errno value,
421 so we can give an accurate diagnostic when reporting the failure
422 to remove a subsequent relative-named command-line argument. */
423 cwd_state->saved_errno = errno;
428 /* Initialize *HT if it is NULL.
429 Insert FILENAME into HT. */
431 AD_mark_helper (Hash_table **ht, char *filename)
435 *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw,
436 hash_compare_strings, hash_freer);
440 if (! hash_insert (*ht, filename))
444 /* Mark FILENAME (in current directory) as unremovable. */
446 AD_mark_as_unremovable (Dirstack_state *ds, char const *filename)
448 AD_mark_helper (&AD_stack_top(ds)->unremovable, xstrdup (filename));
451 /* Mark the current directory as unremovable. I.e., mark the entry
452 in the parent directory corresponding to `.'.
453 This happens e.g., when an opendir fails and the only name
454 the caller has conveniently at hand is `.'. */
456 AD_mark_current_as_unremovable (Dirstack_state *ds)
458 struct AD_ent *top = AD_stack_top (ds);
459 char *curr = top_dir (ds);
461 assert (1 < AD_stack_height (ds));
464 AD_mark_helper (&top->unremovable, curr);
467 /* Push an initial dummy entry onto the stack.
468 This will always be the bottommost entry on the stack. */
470 AD_push_initial (Dirstack_state *ds)
474 /* Extend the stack. */
475 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
477 /* Fill in the new values. */
478 top = AD_stack_top (ds);
479 top->unremovable = NULL;
481 /* These should never be used.
482 Give them values that might look suspicious
483 in a debugger or in a diagnostic. */
484 top->dev_ino.st_dev = TYPE_MAXIMUM (dev_t);
485 top->dev_ino.st_ino = TYPE_MAXIMUM (ino_t);
488 /* Push info about the current working directory (".") onto the
489 active directory stack. DIR is the ./-relative name through
490 which we've just `chdir'd to this directory. DIR_SB_FROM_PARENT
491 is the result of calling lstat on DIR from the parent of DIR. */
493 AD_push (Dirstack_state *ds, char const *dir,
494 struct stat const *dir_sb_from_parent)
501 if (lstat (".", &sb))
502 error (EXIT_FAILURE, errno,
503 _("cannot lstat `.' in %s"), quote (full_filename (".")));
505 if ( ! SAME_INODE (sb, *dir_sb_from_parent))
506 error (EXIT_FAILURE, 0,
507 _("%s changed dev/ino"), quote (full_filename (".")));
509 /* Extend the stack. */
510 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
512 /* Fill in the new values. */
513 top = AD_stack_top (ds);
514 top->dev_ino.st_dev = sb.st_dev;
515 top->dev_ino.st_ino = sb.st_ino;
516 top->unremovable = NULL;
520 AD_is_removable (Dirstack_state const *ds, char const *file)
522 struct AD_ent *top = AD_stack_top (ds);
523 return ! (top->unremovable && hash_lookup (top->unremovable, file));
526 /* Return true if DIR is determined to be an empty directory
527 or if opendir or readdir fails. */
529 is_empty_dir (char const *dir)
531 DIR *dirp = opendir (dir);
532 struct dirent const *dp;
539 dp = readdir_ignoring_dot_and_dotdot (dirp);
544 return saved_errno == 0 ? true : false;
547 /* Return true if FILE is determined to be an unwritable non-symlink.
548 Otherwise, return false (including when lstat'ing it fails).
549 If lstat succeeds, set *BUF_P to BUF.
550 This is to avoid calling euidaccess when FILE is a symlink. */
552 write_protected_non_symlink (char const *file,
556 if (lstat (file, buf) != 0)
559 if (S_ISLNK (buf->st_mode))
561 return euidaccess (file, W_OK) == -1 && errno == EACCES;
564 /* Prompt whether to remove FILENAME, if required via a combination of
565 the options specified by X and/or file attributes. If the file may
566 be removed, return RM_OK. If the user declines to remove the file,
567 return RM_USER_DECLINED. If not ignoring missing files and we
568 cannot lstat FILENAME, then return RM_ERROR.
570 Depending on MODE, ask whether to `descend into' or to `remove' the
571 directory FILENAME. MODE is ignored when FILENAME is not a directory.
572 Set *IS_EMPTY to T_YES if FILENAME is an empty directory, and it is
573 appropriate to try to remove it with rmdir (e.g. recursive mode).
574 Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR.
575 Set *IS_DIR to T_YES or T_NO if we happen to determine whether
576 FILENAME is a directory. */
577 static enum RM_status
578 prompt (Dirstack_state const *ds, char const *filename,
579 struct rm_options const *x, enum Prompt_action mode,
580 Ternary *is_dir, Ternary *is_empty)
582 bool write_protected = false;
583 struct stat *sbuf = NULL;
586 *is_empty = T_UNKNOWN;
589 if (((!x->ignore_missing_files & (x->interactive | x->stdin_tty))
590 && (write_protected = write_protected_non_symlink (filename,
597 if (lstat (filename, sbuf))
599 /* lstat failed. This happens e.g., with `rm '''. */
600 error (0, errno, _("cannot lstat %s"),
601 quote (full_filename (filename)));
606 if (S_ISDIR (sbuf->st_mode) && !x->recursive)
608 error (0, EISDIR, _("cannot remove directory %s"),
609 quote (full_filename (filename)));
613 /* Using permissions doesn't make sense for symlinks. */
614 if (S_ISLNK (sbuf->st_mode))
616 if ( ! x->interactive)
618 write_protected = false;
621 /* Issue the prompt. */
623 char const *quoted_name = quote (full_filename (filename));
625 *is_dir = (S_ISDIR (sbuf->st_mode) ? T_YES : T_NO);
627 /* FIXME: use a variant of error (instead of fprintf) that doesn't
628 append a newline. Then we won't have to declare program_name in
630 if (S_ISDIR (sbuf->st_mode)
632 && mode == PA_DESCEND_INTO_DIR
633 && ((*is_empty = (is_empty_dir (filename) ? T_YES : T_NO))
637 ? _("%s: descend into write-protected directory %s? ")
638 : _("%s: descend into directory %s? ")),
639 program_name, quoted_name);
642 /* TRANSLATORS: You may find it more convenient to translate
643 the equivalent of _("%s: remove %s (write-protected) %s? ").
644 It should avoid grammatical problems with the output
648 ? _("%s: remove write-protected %s %s? ")
649 : _("%s: remove %s %s? ")),
650 program_name, file_type (sbuf), quoted_name);
654 return RM_USER_DECLINED;
660 #if HAVE_STRUCT_DIRENT_D_TYPE
662 /* True if the type of the directory entry D is known. */
663 # define DT_IS_KNOWN(d) ((d)->d_type != DT_UNKNOWN)
665 /* True if the type of the directory entry D must be T. */
666 # define DT_MUST_BE(d, t) ((d)->d_type == (t))
669 # define DT_IS_KNOWN(d) false
670 # define DT_MUST_BE(d, t) false
673 #define DO_UNLINK(Filename, X) \
676 if (unlink (Filename) == 0) \
679 printf (_("removed %s\n"), quote (full_filename (Filename))); \
683 if (errno == ENOENT && (X)->ignore_missing_files) \
688 #define DO_RMDIR(Filename, X) \
691 if (rmdir (Filename) == 0) \
694 printf (_("removed directory: %s\n"), \
695 quote (full_filename (Filename))); \
699 if (errno == ENOENT && (X)->ignore_missing_files) \
702 if (errno == ENOTEMPTY || errno == EEXIST) \
703 return RM_NONEMPTY_DIR; \
707 /* Remove the file or directory specified by FILENAME.
708 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
709 But if FILENAME specifies a non-empty directory, return RM_NONEMPTY_DIR. */
711 static enum RM_status
712 remove_entry (Dirstack_state const *ds, char const *filename,
713 struct rm_options const *x, struct dirent const *dp)
716 Ternary is_empty_directory;
717 enum RM_status s = prompt (ds, filename, x, PA_DESCEND_INTO_DIR,
718 &is_dir, &is_empty_directory);
723 /* Why bother with the following if/else block? Because on systems with
724 an unlink function that *can* unlink directories, we must determine the
725 type of each entry before removing it. Otherwise, we'd risk unlinking
726 an entire directory tree simply by unlinking a single directory; then
727 all the storage associated with that hierarchy would not be freed until
728 the next fsck. Not nice. To avoid that, on such slightly losing
729 systems, we need to call lstat to determine the type of each entry,
730 and that represents extra overhead that -- it turns out -- we can
731 avoid on non-losing systems, since there, unlink will never remove
732 a directory. Also, on systems where unlink may unlink directories,
733 we're forced to allow a race condition: we lstat a non-directory, then
734 go to unlink it, but in the mean time, a malicious someone has replaced
735 it with a directory. */
737 if (cannot_unlink_dir ())
739 if (is_dir == T_YES && ! x->recursive)
741 error (0, EISDIR, _("cannot remove directory %s"),
742 quote (full_filename (filename)));
746 /* is_empty_directory is set iff it's ok to use rmdir.
747 Note that it's set only in interactive mode -- in which case it's
748 an optimization that arranges so that the user is asked just
749 once whether to remove the directory. */
750 if (is_empty_directory == T_YES)
751 DO_RMDIR (filename, x);
753 /* If we happen to know that FILENAME is a directory, return now
754 and let the caller remove it -- this saves the overhead of a failed
755 unlink call. If FILENAME is a command-line argument, then dp is NULL,
756 so we'll first try to unlink it. Using unlink here is ok, because it
757 cannot remove a directory. */
758 if ((dp && DT_MUST_BE (dp, DT_DIR)) || is_dir == T_YES)
759 return RM_NONEMPTY_DIR;
761 DO_UNLINK (filename, x);
764 || errno == ENOENT || errno == ENOTDIR
765 || errno == ELOOP || errno == ENAMETOOLONG)
767 /* Either --recursive is not in effect, or the file cannot be a
768 directory. Report the unlink problem and fail. */
769 error (0, errno, _("cannot remove %s"),
770 quote (full_filename (filename)));
776 /* If we don't already know whether FILENAME is a directory, find out now.
777 Then, if it's a non-directory, we can use unlink on it. */
778 if (is_dir == T_UNKNOWN)
780 if (dp && DT_IS_KNOWN (dp))
781 is_dir = DT_MUST_BE (dp, DT_DIR) ? T_YES : T_NO;
785 if (lstat (filename, &sbuf))
787 if (errno == ENOENT && x->ignore_missing_files)
790 error (0, errno, _("cannot lstat %s"),
791 quote (full_filename (filename)));
795 is_dir = S_ISDIR (sbuf.st_mode) ? T_YES : T_NO;
801 /* At this point, barring race conditions, FILENAME is known
802 to be a non-directory, so it's ok to try to unlink it. */
803 DO_UNLINK (filename, x);
805 /* unlink failed with some other error code. report it. */
806 error (0, errno, _("cannot remove %s"),
807 quote (full_filename (filename)));
813 error (0, EISDIR, _("cannot remove directory %s"),
814 quote (full_filename (filename)));
818 if (is_empty_directory == T_YES)
820 DO_RMDIR (filename, x);
821 /* Don't diagnose any failure here.
822 It'll be detected when the caller tries another way. */
826 return RM_NONEMPTY_DIR;
829 /* Remove entries in `.', the current working directory (cwd).
830 Upon finding a directory that is both non-empty and that can be chdir'd
831 into, return RM_OK and set *SUBDIR and fill in SUBDIR_SB, where
832 SUBDIR is the malloc'd name of the subdirectory if the chdir succeeded,
833 NULL otherwise (e.g., if opendir failed or if there was no subdirectory).
834 Likewise, SUBDIR_SB is the result of calling lstat on SUBDIR.
835 Return RM_OK if all entries are removed. Return RM_ERROR if any
836 entry cannot be removed. Otherwise, return RM_USER_DECLINED if
837 the user declines to remove at least one entry. Remove as much as
838 possible, continuing even if we fail to remove some entries. */
839 static enum RM_status
840 remove_cwd_entries (Dirstack_state *ds, char **subdir, struct stat *subdir_sb,
841 struct rm_options const *x)
843 DIR *dirp = opendir (".");
844 struct AD_ent *top = AD_stack_top (ds);
845 enum RM_status status = top->status;
846 size_t n_unlinked_since_opendir_or_last_rewind = 0;
848 assert (VALID_STATUS (status));
853 if (errno != ENOENT || !x->ignore_missing_files)
855 error (0, errno, _("cannot open directory %s"),
856 quote (full_filename (".")));
863 struct dirent const *dp;
864 enum RM_status tmp_status;
867 /* Set errno to zero so we can distinguish between a readdir failure
868 and when readdir simply finds that there are no more entries. */
870 dp = readdir_ignoring_dot_and_dotdot (dirp);
875 /* Save/restore errno across closedir call. */
880 /* Arrange to give a diagnostic after exiting this loop. */
883 else if (CONSECUTIVE_READDIR_UNLINK_THRESHOLD
884 < n_unlinked_since_opendir_or_last_rewind)
886 /* Call rewinddir if we've called unlink or rmdir so many times
887 (since the opendir or the previous rewinddir) that this
888 NULL-return may be the symptom of a buggy readdir. */
890 n_unlinked_since_opendir_or_last_rewind = 0;
898 /* Skip files we've already tried/failed to remove. */
899 if ( ! AD_is_removable (ds, f))
902 /* Pass dp->d_type info to remove_entry so the non-glibc
903 case can decide whether to use unlink or chdir.
904 Systems without the d_type member will have to endure
905 the performance hit of first calling lstat F. */
906 tmp_status = remove_entry (ds, f, x, dp);
910 /* Count how many files we've unlinked since the initial
911 opendir or the last rewinddir. On buggy systems, if you
912 remove too many, readdir returns NULL even though there
913 remain unprocessed directory entries. */
914 ++n_unlinked_since_opendir_or_last_rewind;
918 case RM_USER_DECLINED:
919 AD_mark_as_unremovable (ds, f);
920 UPDATE_STATUS (status, tmp_status);
923 case RM_NONEMPTY_DIR:
925 /* Save a copy of errno, in case the preceding unlink (from
926 remove_entry's DO_UNLINK) of a non-directory failed. */
927 int saved_errno = errno;
929 /* Record dev/ino of F so that we can compare
930 that with dev/ino of `.' after the chdir.
931 This dev/ino pair is also used in cycle detection. */
932 if (lstat (f, subdir_sb))
933 error (EXIT_FAILURE, errno, _("cannot lstat %s"),
934 quote (full_filename (f)));
937 if (! S_ISDIR (subdir_sb->st_mode) || chdir (f) != 0)
939 /* It is much more common that we reach this point for an
940 inaccessible directory. Hence the second diagnostic, below.
941 However it is also possible that F is a non-directory.
942 That can happen when we use the `! UNLINK_CAN_UNLINK_DIRS'
943 block of code and when DO_UNLINK fails due to EPERM.
944 In that case, give a better diagnostic. */
945 if (errno == ENOTDIR)
946 error (0, saved_errno, _("cannot remove %s"),
947 quote (full_filename (f)));
949 error (0, errno, _("cannot chdir from %s to %s"),
950 quote_n (0, full_filename (".")), quote_n (1, f));
951 AD_mark_as_unremovable (ds, f);
955 if (cycle_check (&ds->cycle_check_state, subdir_sb))
958 WARNING: Circular directory structure.\n\
959 This almost certainly means that you have a corrupted file system.\n\
960 NOTIFY YOUR SYSTEM MANAGER.\n\
961 The following directory is part of the cycle:\n %s\n"),
962 quote (full_filename (".")));
963 longjmp (ds->current_arg_jumpbuf, 1);
966 *subdir = xstrdup (f);
971 /* Record status for this directory. */
972 UPDATE_STATUS (top->status, status);
978 if (dirp == NULL || CLOSEDIR (dirp) != 0)
980 /* Note that this diagnostic serves for both readdir
981 and closedir failures. */
982 error (0, errno, _("reading directory %s"), quote (full_filename (".")));
989 /* Do this after each call to AD_push or AD_push_initial.
990 Because the status = RM_OK bit is too remove-specific to
991 go into the general-purpose AD_* package. */
992 #define AD_INIT_OTHER_MEMBERS() \
995 AD_stack_top(ds)->status = RM_OK; \
999 /* Remove the hierarchy rooted at DIR.
1000 Do that by changing into DIR, then removing its contents, then
1001 returning to the original working directory and removing DIR itself.
1002 Don't use recursion. Be careful when using chdir ".." that we
1003 return to the same directory from which we came, if necessary.
1004 Return 1 for success, 0 if some file cannot be removed or if
1006 If the initial working directory cannot be saved or restored,
1007 record the offending errno value in (*CWD_STATE)->saved_errno. */
1009 static enum RM_status
1010 remove_dir (Dirstack_state *ds, char const *dir, struct cwd_state **cwd_state,
1011 struct rm_options const *x)
1013 enum RM_status status;
1016 /* Save any errno (from caller's failed remove_entry call), in case DIR
1017 is not a directory, so that we can give a reasonable diagnostic. */
1018 int saved_errno = errno;
1020 if (*cwd_state == NULL)
1022 *cwd_state = xmalloc (sizeof **cwd_state);
1024 if (save_cwd (&(*cwd_state)->saved_cwd) != 0)
1026 (*cwd_state)->saved_errno = errno;
1027 assert (errno != 0);
1029 /* Pretend we started from "/". That is fine as long as there
1030 is no requirement to return to the original working directory.
1031 Use "/", not ".", so that we chdir out of a non-root target
1032 directory before attempting to remove it: some hosts don't let
1033 you remove a working directory. */
1034 (*cwd_state)->saved_cwd.name = xstrdup ("/");
1037 (*cwd_state)->saved_errno = 0;
1039 AD_push_initial (ds);
1040 AD_INIT_OTHER_MEMBERS ();
1043 /* If we've failed to record and/or restore the initial working directory,
1044 and we're now trying to access a `.'-relative file name, then give a
1045 diagnostic, record the failure, and proceed with any subsequent
1046 command-line arguments. */
1047 if ((*cwd_state)->saved_errno && IS_RELATIVE_FILE_NAME (dir))
1049 error (0, (*cwd_state)->saved_errno, _("cannot remove directory %s"),
1050 quote (full_filename (dir)));
1051 longjmp (ds->current_arg_jumpbuf, 1);
1054 /* There is a race condition in that an attacker could replace the nonempty
1055 directory, DIR, with a symlink between the preceding call to rmdir
1056 (in our caller) and the chdir below. However, the following lstat,
1057 along with the `stat (".",...' and dev/ino comparison in AD_push
1058 ensure that we detect it and fail. */
1060 if (lstat (dir, &dir_sb))
1063 _("cannot lstat %s"), quote (full_filename (dir)));
1068 if (! S_ISDIR (dir_sb.st_mode) || chdir (dir) != 0)
1070 if (errno == ENOTDIR)
1072 error (0, saved_errno,
1073 _("cannot remove %s"), quote (full_filename (dir)));
1078 _("cannot chdir from %s to %s"),
1079 quote_n (0, full_filename (".")), quote_n (1, dir));
1084 if (ROOT_DEV_INO_CHECK (x->root_dev_ino, &dir_sb))
1086 ROOT_DEV_INO_WARN (full_filename (dir));
1090 AD_push (ds, dir, &dir_sb);
1091 AD_INIT_OTHER_MEMBERS ();
1097 char *subdir = NULL;
1098 struct stat subdir_sb;
1099 enum RM_status tmp_status = remove_cwd_entries (ds,
1100 &subdir, &subdir_sb, x);
1101 if (tmp_status != RM_OK)
1103 UPDATE_STATUS (status, tmp_status);
1104 AD_mark_current_as_unremovable (ds);
1108 AD_push (ds, subdir, &subdir_sb);
1109 AD_INIT_OTHER_MEMBERS ();
1115 /* Execution reaches this point when we've removed the last
1116 removable entry from the current directory. */
1118 /* This is the name of the directory that we have just
1119 returned from, after nominally removing all of its contents. */
1122 AD_pop_and_chdir (ds, &empty_dir, *cwd_state);
1124 /* Try to remove D only if remove_cwd_entries succeeded. */
1125 if (tmp_status == RM_OK)
1127 /* This does a little more work than necessary when it actually
1128 prompts the user. E.g., we already know that D is a directory
1129 and that it's almost certainly empty, yet we lstat it.
1130 But that's no big deal since we're interactive. */
1133 enum RM_status s = prompt (ds, empty_dir, x, PA_REMOVE_DIR,
1134 &is_dir, &is_empty);
1142 if (rmdir (empty_dir) == 0)
1145 printf (_("removed directory: %s\n"),
1146 quote (full_filename (empty_dir)));
1150 error (0, errno, _("cannot remove directory %s"),
1151 quote (full_filename (empty_dir)));
1152 AD_mark_as_unremovable (ds, empty_dir);
1154 UPDATE_STATUS (AD_stack_top(ds)->status, status);
1160 if (AD_stack_height (ds) == 1)
1168 /* Remove the file or directory specified by FILENAME.
1169 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
1170 On input, the first time this function is called, CWD_STATE should be
1171 the address of a NULL pointer. Do not modify it for any subsequent calls.
1172 On output, it is either that same NULL pointer or the address of
1173 a malloc'd `struct saved_cwd' that may be freed. */
1175 static enum RM_status
1176 rm_1 (Dirstack_state *ds, char const *filename,
1177 struct rm_options const *x, struct cwd_state **cwd_state)
1179 char *base = base_name (filename);
1180 enum RM_status status;
1182 if (DOT_OR_DOTDOT (base))
1184 error (0, 0, _("cannot remove `.' or `..'"));
1188 if (*cwd_state && (*cwd_state)->saved_errno
1189 && IS_RELATIVE_FILE_NAME (filename))
1191 error (0, (*cwd_state)->saved_errno,
1192 _("cannot remove %s"), quote (filename));
1196 status = remove_entry (ds, filename, x, NULL);
1197 if (status != RM_NONEMPTY_DIR)
1200 return remove_dir (ds, filename, cwd_state, x);
1203 /* Remove all files and/or directories specified by N_FILES and FILE.
1204 Apply the options in X. If X->require_restore_cwd is false, then
1205 this function may return RM_OK even though it is unable to restore
1206 the initial working directory. */
1207 extern enum RM_status
1208 rm (size_t n_files, char const *const *file, struct rm_options const *x)
1210 struct cwd_state *cwd_state = NULL;
1213 /* Put the following two variables in static storage, so they can't
1214 be clobbered by the potential longjmp into this function. */
1215 static enum RM_status status = RM_OK;
1220 for (i = 0; i < n_files; i++)
1223 cycle_check_init (&ds->cycle_check_state);
1224 /* In the event that rm_1->remove_dir->remove_cwd_entries detects
1225 a directory cycle, arrange to fail, give up on this FILE, but
1226 continue on with any other arguments. */
1227 if (setjmp (ds->current_arg_jumpbuf))
1230 s = rm_1 (ds, file[i], x, &cwd_state);
1231 assert (VALID_STATUS (s));
1232 UPDATE_STATUS (status, s);
1235 if (x->require_restore_cwd && cwd_state && cwd_state->saved_errno != 0)
1237 error (0, cwd_state->saved_errno,
1238 _("cannot restore current working directory"));
1244 if (cwd_state && cwd_state->saved_errno == 0)
1245 free_cwd (&cwd_state->saved_cwd);