1 /* remove.c -- core functions for removing files and directories
2 Copyright (C) 88, 90, 91, 1994-2007 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 3 of the License, or
7 (at your option) any later version.
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, see <http://www.gnu.org/licenses/>. */
17 /* Extracted from rm.c and librarified, then rewritten by Jim Meyering. */
21 #include <sys/types.h>
26 #include "cycle-check.h"
29 #include "euidaccess.h"
30 #include "euidaccess-stat.h"
31 #include "file-type.h"
39 #include "root-dev-ino.h"
40 #include "unlinkdir.h"
41 #include "write-any-file.h"
44 /* Avoid shadowing warnings because these are functions declared
45 in dirname.h as well as locals used below. */
46 #define dir_name rm_dir_name
47 #define dir_len rm_dir_len
49 #define obstack_chunk_alloc malloc
50 #define obstack_chunk_free free
52 /* This is the maximum number of consecutive readdir/unlink calls that
53 can be made (with no intervening rewinddir or closedir/opendir) before
54 triggering a bug that makes readdir return NULL even though some
55 directory entries have not been processed. The bug afflicts SunOS's
56 readdir when applied to ufs file systems and Darwin 6.5's (and OSX
57 v.10.3.8's) HFS+. This maximum is conservative in that demonstrating
58 the problem requires a directory containing at least 16 deletable
59 entries (which doesn't count . and ..).
60 This problem also affects Darwin 7.9.0 (aka MacOS X 10.3.9) on HFS+
61 and NFS-mounted file systems, but not vfat ones. */
64 CONSECUTIVE_READDIR_UNLINK_THRESHOLD = 10
67 /* FIXME: in 2009, or whenever Darwin 7.9.0 (aka MacOS X 10.3.9) is no
68 longer relevant, remove this work-around code. Then, there will be
69 no need to perform the extra rewinddir call, ever. */
70 #define NEED_REWIND(readdir_unlink_count) \
71 (CONSECUTIVE_READDIR_UNLINK_THRESHOLD <= (readdir_unlink_count))
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 /* Initial capacity of per-directory hash table of entries that have
91 been processed but not been deleted. */
92 enum { HT_UNREMOVABLE_INITIAL_CAPACITY = 13 };
94 /* An entry in the active directory stack.
95 Each entry corresponds to an `active' directory. */
98 /* For a given active directory, this is the set of names of
99 entries in that directory that could/should not be removed.
100 For example, `.' and `..', as well as files/dirs for which
101 unlink/rmdir failed e.g., due to access restrictions. */
102 Hash_table *unremovable;
104 /* Record the status for a given active directory; we need to know
105 whether an entry was not removed, either because of an error or
106 because the user declined. */
107 enum RM_status status;
109 /* The directory's dev/ino. Used to ensure that a malicious user does
110 not replace a directory we're about to process with a symlink to
111 some other directory. */
112 struct dev_ino dev_ino;
115 /* D_TYPE(D) is the type of directory entry D if known, DT_UNKNOWN
117 #if HAVE_STRUCT_DIRENT_D_TYPE
118 # define D_TYPE(d) ((d)->d_type)
120 # define D_TYPE(d) DT_UNKNOWN
122 /* Any int values will do here, so long as they're distinct.
123 Undef any existing macros out of the way. */
127 # define DT_UNKNOWN 0
132 extern char *program_name;
134 struct dirstack_state
136 /* The name of the directory (starting with and relative to a command
137 line argument) being processed. When a subdirectory is entered, a new
138 component is appended (pushed). Remove (pop) the top component
139 upon chdir'ing out of a directory. This is used to form the full
140 name of the current directory or a file therein, when necessary. */
141 struct obstack dir_stack;
143 /* Stack of lengths of directory names (including trailing slash)
144 appended to dir_stack. We have to have a separate stack of lengths
145 (rather than just popping back to previous slash) because the first
146 element pushed onto the dir stack may contain slashes. */
147 struct obstack len_stack;
149 /* Stack of active directory entries.
150 The first `active' directory is the initial working directory.
151 Additional active dirs are pushed onto the stack as we `chdir'
152 into each directory to be processed. When finished with the
153 hierarchy under a directory, pop the active dir stack. */
154 struct obstack Active_dir;
156 /* Used to detect cycles. */
157 struct cycle_check_state cycle_check_state;
159 /* Target of a longjmp in case rm has to stop processing the current
160 command-line argument. This happens 1) when rm detects a directory
161 cycle or 2) when it has processed one or more directories, but then
162 is unable to return to the initial working directory to process
163 additional `.'-relative command-line arguments. */
164 jmp_buf current_arg_jumpbuf;
166 typedef struct dirstack_state Dirstack_state;
168 /* Like fstatat, but cache the result. If ST->st_size is -1, the
169 status has not been gotten yet. If less than -1, fstatat failed
170 with errno == -1 - ST->st_size. Otherwise, the status has already
171 been gotten, so return 0. */
173 cache_fstatat (int fd, char const *file, struct stat *st, int flag)
175 if (st->st_size == -1 && fstatat (fd, file, st, flag) != 0)
176 st->st_size = -1 - errno;
177 if (0 <= st->st_size)
179 errno = -1 - st->st_size;
183 /* Initialize a fstatat cache *ST. Return ST for convenience. */
184 static inline struct stat *
185 cache_stat_init (struct stat *st)
191 /* Return true if *ST has been statted. */
193 cache_statted (struct stat *st)
195 return (st->st_size != -1);
198 /* Return true if *ST has been statted successfully. */
200 cache_stat_ok (struct stat *st)
202 return (0 <= st->st_size);
213 hash_compare_strings (void const *x, void const *y)
215 return STREQ (x, y) ? true : false;
219 push_dir (Dirstack_state *ds, const char *dir_name)
221 size_t len = strlen (dir_name);
223 /* Don't copy trailing slashes. */
224 while (1 < len && dir_name[len - 1] == '/')
227 /* Append the string onto the stack. */
228 obstack_grow (&ds->dir_stack, dir_name, len);
230 /* Append a trailing slash. */
231 obstack_1grow (&ds->dir_stack, '/');
233 /* Add one for the slash. */
236 /* Push the length (including slash) onto its stack. */
237 obstack_grow (&ds->len_stack, &len, sizeof (len));
240 /* Return the entry name of the directory on the top of the stack
241 in malloc'd storage. */
243 top_dir (Dirstack_state const *ds)
245 size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
246 size_t *length = obstack_base (&ds->len_stack);
247 size_t top_len = length[n_lengths - 1];
248 char const *p = obstack_next_free (&ds->dir_stack) - top_len;
249 char *q = xmalloc (top_len);
250 memcpy (q, p, top_len - 1);
256 pop_dir (Dirstack_state *ds)
258 size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
259 size_t *length = obstack_base (&ds->len_stack);
261 assert (n_lengths > 0);
262 size_t top_len = length[n_lengths - 1];
263 assert (top_len >= 2);
265 /* Pop the specified length of file name. */
266 assert (obstack_object_size (&ds->dir_stack) >= top_len);
267 obstack_blank (&ds->dir_stack, -top_len);
269 /* Pop the length stack, too. */
270 assert (obstack_object_size (&ds->len_stack) >= sizeof (size_t));
271 obstack_blank (&ds->len_stack, -(int) sizeof (size_t));
274 /* Copy the SRC_LEN bytes of data beginning at SRC into the DST_LEN-byte
275 buffer, DST, so that the last source byte is at the end of the destination
276 buffer. If SRC_LEN is longer than DST_LEN, then set *TRUNCATED.
277 Set *RESULT to point to the beginning of (the portion of) the source data
278 in DST. Return the number of bytes remaining in the destination buffer. */
281 right_justify (char *dst, size_t dst_len, const char *src, size_t src_len,
282 char **result, bool *truncated)
287 if (src_len <= dst_len)
290 dp = dst + (dst_len - src_len);
295 sp = src + (src_len - dst_len);
301 *result = memcpy (dp, sp, src_len);
302 return dst_len - src_len;
305 /* Using the global directory name obstack, create the full name FILENAME.
306 Return it in sometimes-realloc'd space that should not be freed by the
307 caller. Realloc as necessary. If realloc fails, use a static buffer
308 and put as long a suffix in that buffer as possible. */
310 #define full_filename(Filename) full_filename_ (ds, Filename)
312 full_filename_ (Dirstack_state const *ds, const char *filename)
314 static char *buf = NULL;
315 static size_t n_allocated = 0;
317 size_t dir_len = obstack_object_size (&ds->dir_stack);
318 char *dir_name = obstack_base (&ds->dir_stack);
319 size_t n_bytes_needed;
322 filename_len = strlen (filename);
323 n_bytes_needed = dir_len + filename_len + 1;
325 if (n_allocated < n_bytes_needed)
327 /* This code requires that realloc accept NULL as the first arg.
328 This function must not use xrealloc. Otherwise, an out-of-memory
329 error involving a file name to be expanded here wouldn't ever
330 be issued. Use realloc and fall back on using a static buffer
331 if memory allocation fails. */
332 char *new_buf = realloc (buf, n_bytes_needed);
333 n_allocated = n_bytes_needed;
337 #define SBUF_SIZE 512
338 #define ELLIPSES_PREFIX "[...]"
339 static char static_buf[SBUF_SIZE];
345 len = right_justify (static_buf, SBUF_SIZE, filename,
346 filename_len + 1, &p, &truncated);
347 right_justify (static_buf, len, dir_name, dir_len, &p, &truncated);
350 memcpy (static_buf, ELLIPSES_PREFIX,
351 sizeof (ELLIPSES_PREFIX) - 1);
359 if (filename_len == 1 && *filename == '.' && dir_len)
361 /* FILENAME is just `.' and dir_len is nonzero.
362 Copy the directory part, omitting the trailing slash,
363 and append a trailing zero byte. */
364 char *p = mempcpy (buf, dir_name, dir_len - 1);
369 /* Copy the directory part, including trailing slash, and then
370 append the filename part, including a trailing zero byte. */
371 memcpy (mempcpy (buf, dir_name, dir_len), filename, filename_len + 1);
372 assert (strlen (buf) + 1 == n_bytes_needed);
379 AD_stack_height (Dirstack_state const *ds)
381 return obstack_object_size (&ds->Active_dir) / sizeof (struct AD_ent);
384 static inline struct AD_ent *
385 AD_stack_top (Dirstack_state const *ds)
387 return (struct AD_ent *)
388 ((char *) obstack_next_free (&ds->Active_dir) - sizeof (struct AD_ent));
392 AD_stack_pop (Dirstack_state *ds)
394 assert (0 < AD_stack_height (ds));
396 /* operate on Active_dir. pop and free top entry */
397 struct AD_ent *top = AD_stack_top (ds);
398 if (top->unremovable)
399 hash_free (top->unremovable);
400 obstack_blank (&ds->Active_dir, -(int) sizeof (struct AD_ent));
404 AD_stack_clear (Dirstack_state *ds)
406 while (0 < AD_stack_height (ds))
412 static Dirstack_state *
415 Dirstack_state *ds = xmalloc (sizeof *ds);
416 obstack_init (&ds->dir_stack);
417 obstack_init (&ds->len_stack);
418 obstack_init (&ds->Active_dir);
423 ds_clear (Dirstack_state *ds)
425 obstack_free (&ds->dir_stack, obstack_finish (&ds->dir_stack));
426 obstack_free (&ds->len_stack, obstack_finish (&ds->len_stack));
427 while (0 < AD_stack_height (ds))
429 obstack_free (&ds->Active_dir, obstack_finish (&ds->Active_dir));
433 ds_free (Dirstack_state *ds)
435 obstack_free (&ds->dir_stack, NULL);
436 obstack_free (&ds->len_stack, NULL);
437 obstack_free (&ds->Active_dir, NULL);
441 /* Pop the active directory (AD) stack and prepare to move `up' one level,
442 safely. Moving `up' usually means opening `..', but when we've just
443 finished recursively processing a command-line directory argument,
444 there's nothing left on the stack, so set *FDP to AT_FDCWD in that case.
445 The idea is to return with *FDP opened on the parent directory,
446 assuming there are entries in that directory that we need to remove.
448 Note that we must not call opendir (or fdopendir) just yet, since
449 the caller must first remove the directory we're coming from.
450 That is because some file system implementations cache readdir
451 results at opendir time; so calling opendir, rmdir, readdir would
452 return an entry for the just-removed directory.
454 Whenever using chdir '..' (virtually, now, via openat), verify
455 that the post-chdir dev/ino numbers for `.' match the saved ones.
456 If any system call fails or if dev/ino don't match, then give a
457 diagnostic and longjump out.
458 Return the name (in malloc'd storage) of the
459 directory (usually now empty) from which we're coming, and which
460 corresponds to the input value of DIRP.
462 Finally, note that while this function's name is no longer as
463 accurate as it once was (it no longer calls chdir), it does open
464 the destination directory. */
466 AD_pop_and_chdir (DIR *dirp, int *fdp, Dirstack_state *ds)
468 struct AD_ent *leaf_dir_ent = AD_stack_top(ds);
469 struct dev_ino leaf_dev_ino = leaf_dir_ent->dev_ino;
470 enum RM_status old_status = leaf_dir_ent->status;
473 /* Get the name of the current (but soon to be `previous') directory
474 from the top of the stack. */
475 char *prev_dir = top_dir (ds);
479 top = AD_stack_top (ds);
481 /* If the directory we're about to leave (and try to rmdir)
482 is the one whose dev_ino is being used to detect a cycle,
483 reset cycle_check_state.dev_ino to that of the parent.
484 Otherwise, once that directory is removed, its dev_ino
485 could be reused in the creation (by some other process)
486 of a directory that this rm process would encounter,
487 which would result in a false-positive cycle indication. */
488 CYCLE_CHECK_REFLECT_CHDIR_UP (&ds->cycle_check_state,
489 top->dev_ino, leaf_dev_ino);
491 /* Propagate any failure to parent. */
492 UPDATE_STATUS (top->status, old_status);
494 assert (AD_stack_height (ds));
496 if (1 < AD_stack_height (ds))
499 int fd = openat (dirfd (dirp), "..", O_RDONLY);
500 if (closedir (dirp) != 0)
502 error (0, errno, _("FATAL: failed to close directory %s"),
503 quote (full_filename (prev_dir)));
504 goto next_cmdline_arg;
507 /* The above fails with EACCES when DIRP is readable but not
508 searchable, when using Solaris' openat. Without this openat
509 call, tests/rm2 would fail to remove directories a/2 and a/3. */
511 fd = openat (AT_FDCWD, full_filename ("."), O_RDONLY);
515 error (0, errno, _("FATAL: cannot open .. from %s"),
516 quote (full_filename (prev_dir)));
517 goto next_cmdline_arg;
523 _("FATAL: cannot ensure %s (returned to via ..) is safe"),
524 quote (full_filename (".")));
528 /* Ensure that post-chdir dev/ino match the stored ones. */
529 if ( ! SAME_INODE (sb, top->dev_ino))
531 error (0, 0, _("FATAL: directory %s changed dev/ino"),
532 quote (full_filename (".")));
538 longjmp (ds->current_arg_jumpbuf, 1);
544 if (closedir (dirp) != 0)
546 error (0, errno, _("FATAL: failed to close directory %s"),
547 quote (full_filename (prev_dir)));
548 goto next_cmdline_arg;
556 /* Initialize *HT if it is NULL. Return *HT. */
558 AD_ensure_initialized (Hash_table **ht)
562 *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw,
563 hash_compare_strings, hash_freer);
571 /* Initialize *HT if it is NULL.
572 Insert FILENAME into HT. */
574 AD_mark_helper (Hash_table **ht, char *filename)
576 void *ent = hash_insert (AD_ensure_initialized (ht), filename);
586 /* Mark FILENAME (in current directory) as unremovable. */
588 AD_mark_as_unremovable (Dirstack_state *ds, char const *filename)
590 AD_mark_helper (&AD_stack_top(ds)->unremovable, xstrdup (filename));
593 /* Mark the current directory as unremovable. I.e., mark the entry
594 in the parent directory corresponding to `.'.
595 This happens e.g., when an opendir fails and the only name
596 the caller has conveniently at hand is `.'. */
598 AD_mark_current_as_unremovable (Dirstack_state *ds)
600 struct AD_ent *top = AD_stack_top (ds);
601 char *curr = top_dir (ds);
603 assert (1 < AD_stack_height (ds));
606 AD_mark_helper (&top->unremovable, curr);
609 /* Push an initial dummy entry onto the stack.
610 This will always be the bottommost entry on the stack. */
612 AD_push_initial (Dirstack_state *ds)
616 /* Extend the stack. */
617 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
619 /* Fill in the new values. */
620 top = AD_stack_top (ds);
621 top->unremovable = NULL;
623 /* These should never be used.
624 Give them values that might look suspicious
625 in a debugger or in a diagnostic. */
626 top->dev_ino.st_dev = TYPE_MAXIMUM (dev_t);
627 top->dev_ino.st_ino = TYPE_MAXIMUM (ino_t);
630 /* Push info about the current working directory (".") onto the
631 active directory stack. DIR is the ./-relative name through
632 which we've just `chdir'd to this directory. DIR_SB_FROM_PARENT
633 is the result of calling lstat on DIR from the parent of DIR.
634 Longjump out (skipping the entire command line argument we're
635 dealing with) if `fstat (FD_CWD, ...' fails or if someone has
636 replaced DIR with e.g., a symlink to some other directory. */
638 AD_push (int fd_cwd, Dirstack_state *ds, char const *dir,
639 struct stat const *dir_sb_from_parent)
645 /* If our uses of openat are guaranteed not to
646 follow a symlink, then we can skip this check. */
647 if (! HAVE_WORKING_O_NOFOLLOW)
650 if (fstat (fd_cwd, &sb) != 0)
652 error (0, errno, _("FATAL: cannot enter directory %s"),
653 quote (full_filename (".")));
654 longjmp (ds->current_arg_jumpbuf, 1);
657 if ( ! SAME_INODE (sb, *dir_sb_from_parent))
660 _("FATAL: just-changed-to directory %s changed dev/ino"),
661 quote (full_filename (".")));
662 longjmp (ds->current_arg_jumpbuf, 1);
666 if (cycle_check (&ds->cycle_check_state, dir_sb_from_parent))
669 WARNING: Circular directory structure.\n\
670 This almost certainly means that you have a corrupted file system.\n\
671 NOTIFY YOUR SYSTEM MANAGER.\n\
672 The following directory is part of the cycle:\n %s\n"),
673 quote (full_filename (".")));
674 longjmp (ds->current_arg_jumpbuf, 1);
677 /* Extend the stack. */
678 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
680 /* The active directory stack must be one larger than the length stack. */
681 assert (AD_stack_height (ds) ==
682 1 + obstack_object_size (&ds->len_stack) / sizeof (size_t));
684 /* Fill in the new values. */
685 top = AD_stack_top (ds);
686 top->dev_ino.st_dev = dir_sb_from_parent->st_dev;
687 top->dev_ino.st_ino = dir_sb_from_parent->st_ino;
688 top->unremovable = NULL;
692 AD_is_removable (Dirstack_state const *ds, char const *file)
694 struct AD_ent *top = AD_stack_top (ds);
695 return ! (top->unremovable && hash_lookup (top->unremovable, file));
698 /* Return true if DIR is determined to be an empty directory. */
700 is_empty_dir (int fd_cwd, char const *dir)
703 struct dirent const *dp;
705 int fd = openat (fd_cwd, dir,
706 (O_RDONLY | O_DIRECTORY
707 | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK));
712 dirp = fdopendir (fd);
720 dp = readdir_ignoring_dot_and_dotdot (dirp);
725 return saved_errno == 0 ? true : false;
728 /* Return -1 if FILE is an unwritable non-symlink,
729 0 if it is writable or some other type of file,
730 a positive error number if there is some problem in determining the answer.
731 Set *BUF to the file status.
732 This is to avoid calling euidaccess when FILE is a symlink. */
734 write_protected_non_symlink (int fd_cwd,
736 Dirstack_state const *ds,
739 if (can_write_any_file ())
741 if (cache_fstatat (fd_cwd, file, buf, AT_SYMLINK_NOFOLLOW) != 0)
743 if (S_ISLNK (buf->st_mode))
745 /* Here, we know FILE is not a symbolic link. */
747 /* In order to be reentrant -- i.e., to avoid changing the working
748 directory, and at the same time to be able to deal with alternate
749 access control mechanisms (ACLs, xattr-style attributes) and
750 arbitrarily deep trees -- we need a function like eaccessat, i.e.,
751 like Solaris' eaccess, but fd-relative, in the spirit of openat. */
753 /* In the absence of a native eaccessat function, here are some of
754 the implementation choices [#4 and #5 were suggested by Paul Eggert]:
755 1) call openat with O_WRONLY|O_NOCTTY
756 Disadvantage: may create the file and doesn't work for directory,
757 may mistakenly report `unwritable' for EROFS or ACLs even though
758 perm bits say the file is writable.
760 2) fake eaccessat (save_cwd, fchdir, call euidaccess, restore_cwd)
761 Disadvantage: changes working directory (not reentrant) and can't
762 work if save_cwd fails.
764 3) if (euidaccess (full_filename (file), W_OK) == 0)
765 Disadvantage: doesn't work if full_filename is too long.
766 Inefficient for very deep trees (O(Depth^2)).
768 4) If the full pathname is sufficiently short (say, less than
769 PATH_MAX or 8192 bytes, whichever is shorter):
770 use method (3) (i.e., euidaccess (full_filename (file), W_OK));
771 Otherwise: vfork, fchdir in the child, run euidaccess in the
772 child, then the child exits with a status that tells the parent
773 whether euidaccess succeeded.
775 This avoids the O(N**2) algorithm of method (3), and it also avoids
776 the failure-due-to-too-long-file-names of method (3), but it's fast
777 in the normal shallow case. It also avoids the lack-of-reentrancy
778 and the save_cwd problems.
779 Disadvantage; it uses a process slot for very-long file names,
780 and would be very slow for hierarchies with many such files.
782 5) If the full file name is sufficiently short (say, less than
783 PATH_MAX or 8192 bytes, whichever is shorter):
784 use method (3) (i.e., euidaccess (full_filename (file), W_OK));
785 Otherwise: look just at the file bits. Perhaps issue a warning
786 the first time this occurs.
788 This is like (4), except for the "Otherwise" case where it isn't as
789 "perfect" as (4) but is considerably faster. It conforms to current
790 POSIX, and is uniformly better than what Solaris and FreeBSD do (they
791 mess up with long file names). */
794 /* This implements #5: */
796 = obstack_object_size (&ds->dir_stack) + strlen (file);
798 if (MIN (PATH_MAX, 8192) <= file_name_len)
799 return - euidaccess_stat (buf, W_OK);
800 if (euidaccess (full_filename (file), W_OK) == 0)
805 /* Perhaps some other process has removed the file, or perhaps this
806 is a buggy NFS client. */
811 /* Prompt whether to remove FILENAME, if required via a combination of
812 the options specified by X and/or file attributes. If the file may
813 be removed, return RM_OK. If the user declines to remove the file,
814 return RM_USER_DECLINED. If not ignoring missing files and we
815 cannot lstat FILENAME, then return RM_ERROR.
817 *PDIRENT_TYPE is the type of the directory entry; update it to DT_DIR
818 or DT_LNK as needed. *SBUF is the file's status.
820 Depending on MODE, ask whether to `descend into' or to `remove' the
821 directory FILENAME. MODE is ignored when FILENAME is not a directory.
822 Set *IS_EMPTY to T_YES if FILENAME is an empty directory, and it is
823 appropriate to try to remove it with rmdir (e.g. recursive mode).
824 Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR. */
825 static enum RM_status
826 prompt (int fd_cwd, Dirstack_state const *ds, char const *filename,
827 int *pdirent_type, struct stat *sbuf,
828 struct rm_options const *x, enum Prompt_action mode,
831 int write_protected = 0;
832 int dirent_type = *pdirent_type;
834 *is_empty = T_UNKNOWN;
836 if (x->interactive == RMI_NEVER)
839 if (!x->ignore_missing_files
840 && ((x->interactive == RMI_ALWAYS) || x->stdin_tty)
841 && dirent_type != DT_LNK)
842 write_protected = write_protected_non_symlink (fd_cwd, filename, ds, sbuf);
844 if (write_protected || x->interactive == RMI_ALWAYS)
846 if (write_protected <= 0 && dirent_type == DT_UNKNOWN)
848 if (cache_fstatat (fd_cwd, filename, sbuf, AT_SYMLINK_NOFOLLOW) == 0)
850 if (S_ISLNK (sbuf->st_mode))
851 dirent_type = DT_LNK;
852 else if (S_ISDIR (sbuf->st_mode))
853 dirent_type = DT_DIR;
854 /* Otherwise it doesn't matter, so leave it DT_UNKNOWN. */
855 *pdirent_type = dirent_type;
859 /* This happens, e.g., with `rm '''. */
860 write_protected = errno;
864 if (write_protected <= 0)
868 /* Using permissions doesn't make sense for symlinks. */
869 if (x->interactive != RMI_ALWAYS)
875 write_protected = EISDIR;
879 char const *quoted_name = quote (full_filename (filename));
881 if (0 < write_protected)
883 error (0, write_protected, _("cannot remove %s"), quoted_name);
887 /* Issue the prompt. */
888 /* FIXME: use a variant of error (instead of fprintf) that doesn't
889 append a newline. Then we won't have to declare program_name in
891 if (dirent_type == DT_DIR
892 && mode == PA_DESCEND_INTO_DIR
893 && ((*is_empty = (is_empty_dir (fd_cwd, filename) ? T_YES : T_NO))
897 ? _("%s: descend into write-protected directory %s? ")
898 : _("%s: descend into directory %s? ")),
899 program_name, quoted_name);
902 if (cache_fstatat (fd_cwd, filename, sbuf, AT_SYMLINK_NOFOLLOW) != 0)
904 error (0, errno, _("cannot remove %s"), quoted_name);
908 /* TRANSLATORS: You may find it more convenient to translate
909 the equivalent of _("%s: remove %s (write-protected) %s? ").
910 It should avoid grammatical problems with the output
914 ? _("%s: remove write-protected %s %s? ")
915 : _("%s: remove %s %s? ")),
916 program_name, file_type (sbuf), quoted_name);
920 return RM_USER_DECLINED;
925 /* Return true if FILENAME is a directory (and not a symlink to a directory).
926 Otherwise, including the case in which lstat fails, return false.
927 *ST is FILENAME's tstatus.
928 Do not modify errno. */
930 is_dir_lstat (int fd_cwd, char const *filename, struct stat *st)
932 int saved_errno = errno;
934 (cache_fstatat (fd_cwd, filename, st, AT_SYMLINK_NOFOLLOW) == 0
935 && S_ISDIR (st->st_mode));
940 #define DO_UNLINK(Fd_cwd, Filename, X) \
943 if (unlinkat (Fd_cwd, Filename, 0) == 0) \
946 printf (_("removed %s\n"), quote (full_filename (Filename))); \
950 if (ignorable_missing (X, errno)) \
955 #define DO_RMDIR(Fd_cwd, Filename, X) \
958 if (unlinkat (Fd_cwd, Filename, AT_REMOVEDIR) == 0) /* rmdir */ \
961 printf (_("removed directory: %s\n"), \
962 quote (full_filename (Filename))); \
966 if (ignorable_missing (X, errno)) \
969 if (errno == ENOTEMPTY || errno == EEXIST) \
970 return RM_NONEMPTY_DIR; \
974 /* When a function like unlink, rmdir, or fstatat fails with an errno
975 value of ERRNUM, return true if the specified file system object
976 is guaranteed not to exist; otherwise, return false. */
978 nonexistent_file_errno (int errnum)
980 /* Do not include ELOOP here, since the specified file may indeed
981 exist, but be (in)accessible only via too long a symlink chain.
982 Likewise for ENAMETOOLONG, since rm -f ./././.../foo may fail
983 if the "..." part expands to a long enough sequence of "./"s,
984 even though ./foo does indeed exist. */
996 /* Encapsulate the test for whether the errno value, ERRNUM, is ignorable. */
998 ignorable_missing (struct rm_options const *x, int errnum)
1000 return x->ignore_missing_files && nonexistent_file_errno (errnum);
1003 /* Remove the file or directory specified by FILENAME.
1004 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
1005 But if FILENAME specifies a non-empty directory, return RM_NONEMPTY_DIR. */
1007 static enum RM_status
1008 remove_entry (int fd_cwd, Dirstack_state const *ds, char const *filename,
1009 int dirent_type_arg, struct stat *st,
1010 struct rm_options const *x)
1012 Ternary is_empty_directory;
1013 enum RM_status s = prompt (fd_cwd, ds, filename, &dirent_type_arg, st, x,
1014 PA_DESCEND_INTO_DIR,
1015 &is_empty_directory);
1016 int dirent_type = dirent_type_arg;
1020 /* Why bother with the following if/else block? Because on systems with
1021 an unlink function that *can* unlink directories, we must determine the
1022 type of each entry before removing it. Otherwise, we'd risk unlinking
1023 an entire directory tree simply by unlinking a single directory; then
1024 all the storage associated with that hierarchy would not be freed until
1025 the next fsck. Not nice. To avoid that, on such slightly losing
1026 systems, we need to call lstat to determine the type of each entry,
1027 and that represents extra overhead that -- it turns out -- we can
1028 avoid on non-losing systems, since there, unlink will never remove
1029 a directory. Also, on systems where unlink may unlink directories,
1030 we're forced to allow a race condition: we lstat a non-directory, then
1031 go to unlink it, but in the mean time, a malicious someone could have
1032 replaced it with a directory. */
1034 if (cannot_unlink_dir ())
1036 if (dirent_type == DT_DIR && ! x->recursive)
1038 error (0, EISDIR, _("cannot remove %s"),
1039 quote (full_filename (filename)));
1043 /* is_empty_directory is set iff it's ok to use rmdir.
1044 Note that it's set only in interactive mode -- in which case it's
1045 an optimization that arranges so that the user is asked just
1046 once whether to remove the directory. */
1047 if (is_empty_directory == T_YES)
1048 DO_RMDIR (fd_cwd, filename, x);
1050 /* If we happen to know that FILENAME is a directory, return now
1051 and let the caller remove it -- this saves the overhead of a failed
1052 unlink call. If FILENAME is a command-line argument, then
1053 DIRENT_TYPE is DT_UNKNOWN so we'll first try to unlink it.
1054 Using unlink here is ok, because it cannot remove a
1056 if (dirent_type == DT_DIR)
1057 return RM_NONEMPTY_DIR;
1059 DO_UNLINK (fd_cwd, filename, x);
1061 /* Upon a failed attempt to unlink a directory, most non-Linux systems
1062 set errno to the POSIX-required value EPERM. In that case, change
1063 errno to EISDIR so that we emit a better diagnostic. */
1064 if (! x->recursive && errno == EPERM && is_dir_lstat (fd_cwd,
1069 || (cache_stat_ok (st) && !S_ISDIR (st->st_mode)))
1071 if (ignorable_missing (x, errno))
1074 /* Either --recursive is not in effect, or the file cannot be a
1075 directory. Report the unlink problem and fail. */
1076 error (0, errno, _("cannot remove %s"),
1077 quote (full_filename (filename)));
1080 assert (!cache_stat_ok (st) || S_ISDIR (st->st_mode));
1084 /* If we don't already know whether FILENAME is a directory,
1085 find out now. Then, if it's a non-directory, we can use
1088 if (dirent_type == DT_UNKNOWN)
1090 if (fstatat (fd_cwd, filename, st, AT_SYMLINK_NOFOLLOW))
1092 if (ignorable_missing (x, errno))
1095 error (0, errno, _("cannot remove %s"),
1096 quote (full_filename (filename)));
1100 if (S_ISDIR (st->st_mode))
1101 dirent_type = DT_DIR;
1104 if (dirent_type == DT_DIR)
1106 /* At this point, barring race conditions, FILENAME is known
1107 to be a non-directory, so it's ok to try to unlink it. */
1108 DO_UNLINK (fd_cwd, filename, x);
1110 /* unlink failed with some other error code. report it. */
1111 error (0, errno, _("cannot remove %s"),
1112 quote (full_filename (filename)));
1118 error (0, EISDIR, _("cannot remove %s"),
1119 quote (full_filename (filename)));
1123 if (is_empty_directory == T_YES)
1125 DO_RMDIR (fd_cwd, filename, x);
1126 /* Don't diagnose any failure here.
1127 It'll be detected when the caller tries another way. */
1131 return RM_NONEMPTY_DIR;
1134 /* Given FD_CWD, the file descriptor for an open directory,
1135 open its subdirectory F (F is already `known' to be a directory,
1136 so if it is no longer one, someone is playing games), return a DIR*
1137 pointer for F, and put F's `stat' data in *SUBDIR_SB.
1138 Upon failure give a diagnostic and return NULL.
1139 If PREV_ERRNO is nonzero, it is the errno value from a preceding failed
1140 unlink- or rmdir-like system call -- use that value instead of ENOTDIR
1141 if an opened file turns out not to be a directory. This is important
1142 when the preceding non-dir-unlink failed due to e.g., EPERM or EACCES.
1143 The caller must use a nonnnull CWD_ERRNO the first
1144 time this function is called for each command-line-specified directory.
1145 If CWD_ERRNO is not null, set *CWD_ERRNO to the appropriate error number
1146 if this function fails to restore the initial working directory.
1147 If it is null, report an error and exit if the working directory
1150 fd_to_subdirp (int fd_cwd, char const *f,
1151 struct rm_options const *x, int prev_errno,
1152 struct stat *subdir_sb,
1153 int *cwd_errno ATTRIBUTE_UNUSED)
1155 int open_flags = O_RDONLY | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK;
1156 int fd_sub = openat_permissive (fd_cwd, f, open_flags, 0, cwd_errno);
1159 /* Record dev/ino of F. We may compare them against saved values
1160 to thwart any attempt to subvert the traversal. They are also used
1161 to detect directory cycles. */
1164 else if (fstat (fd_sub, subdir_sb) != 0)
1165 saved_errno = errno;
1166 else if (S_ISDIR (subdir_sb->st_mode))
1168 DIR *subdir_dirp = fdopendir (fd_sub);
1171 saved_errno = errno;
1174 saved_errno = (prev_errno ? prev_errno : ENOTDIR);
1177 errno = saved_errno;
1181 /* Remove entries in the directory open on DIRP
1182 Upon finding a directory that is both non-empty and that can be chdir'd
1183 into, return RM_OK and set *SUBDIR and fill in SUBDIR_SB, where
1184 SUBDIR is the malloc'd name of the subdirectory if the chdir succeeded,
1185 NULL otherwise (e.g., if opendir failed or if there was no subdirectory).
1186 Likewise, SUBDIR_SB is the result of calling lstat on SUBDIR.
1187 Return RM_OK if all entries are removed. Return RM_ERROR if any
1188 entry cannot be removed. Otherwise, return RM_USER_DECLINED if
1189 the user declines to remove at least one entry. Remove as much as
1190 possible, continuing even if we fail to remove some entries. */
1191 static enum RM_status
1192 remove_cwd_entries (DIR **dirp,
1193 Dirstack_state *ds, char **subdir, struct stat *subdir_sb,
1194 struct rm_options const *x)
1196 struct AD_ent *top = AD_stack_top (ds);
1197 enum RM_status status = top->status;
1198 size_t n_unlinked_since_opendir_or_last_rewind = 0;
1200 assert (VALID_STATUS (status));
1205 struct dirent const *dp;
1206 enum RM_status tmp_status;
1209 /* Set errno to zero so we can distinguish between a readdir failure
1210 and when readdir simply finds that there are no more entries. */
1212 dp = readdir_ignoring_dot_and_dotdot (*dirp);
1219 else if (NEED_REWIND (n_unlinked_since_opendir_or_last_rewind))
1221 /* Call rewinddir if we've called unlink or rmdir so many times
1222 (since the opendir or the previous rewinddir) that this
1223 NULL-return may be the symptom of a buggy readdir. */
1225 n_unlinked_since_opendir_or_last_rewind = 0;
1233 /* Skip files we've already tried/failed to remove. */
1234 if ( ! AD_is_removable (ds, f))
1237 /* Pass dp->d_type info to remove_entry so the non-glibc
1238 case can decide whether to use unlink or chdir.
1239 Systems without the d_type member will have to endure
1240 the performance hit of first calling lstat F. */
1241 cache_stat_init (subdir_sb);
1242 tmp_status = remove_entry (dirfd (*dirp), ds, f,
1243 D_TYPE (dp), subdir_sb, x);
1247 /* Count how many files we've unlinked since the initial
1248 opendir or the last rewinddir. On buggy systems, if you
1249 remove too many, readdir returns NULL even though there
1250 remain unprocessed directory entries. */
1251 ++n_unlinked_since_opendir_or_last_rewind;
1255 case RM_USER_DECLINED:
1256 AD_mark_as_unremovable (ds, f);
1257 UPDATE_STATUS (status, tmp_status);
1260 case RM_NONEMPTY_DIR:
1262 DIR *subdir_dirp = fd_to_subdirp (dirfd (*dirp), f,
1263 x, errno, subdir_sb, NULL);
1264 if (subdir_dirp == NULL)
1268 /* CAUTION: this test and diagnostic are identical to
1269 those following the other use of fd_to_subdirp. */
1270 if (ignorable_missing (x, errno))
1272 /* With -f, don't report "file not found". */
1276 /* Upon fd_to_subdirp failure, try to remove F directly,
1277 in case it's just an empty directory. */
1278 int saved_errno = errno;
1279 if (unlinkat (dirfd (*dirp), f, AT_REMOVEDIR) == 0)
1282 error (0, saved_errno,
1283 _("cannot remove %s"), quote (full_filename (f)));
1286 if (status == RM_ERROR)
1287 AD_mark_as_unremovable (ds, f);
1291 *subdir = xstrdup (f);
1292 if (closedir (*dirp) != 0)
1294 error (0, 0, _("failed to close directory %s"),
1295 quote (full_filename (".")));
1298 *dirp = subdir_dirp;
1304 /* Record status for this directory. */
1305 UPDATE_STATUS (top->status, status);
1311 /* Ensure that *dirp is not NULL and that its file descriptor is valid. */
1312 assert (*dirp != NULL);
1313 assert (0 <= fcntl (dirfd (*dirp), F_GETFD));
1318 /* Do this after each call to AD_push or AD_push_initial.
1319 Because the status = RM_OK bit is too remove-specific to
1320 go into the general-purpose AD_* package. */
1321 #define AD_INIT_OTHER_MEMBERS() \
1324 AD_stack_top(ds)->status = RM_OK; \
1328 /* Remove the hierarchy rooted at DIR.
1329 Do that by changing into DIR, then removing its contents, then
1330 returning to the original working directory and removing DIR itself.
1331 Don't use recursion. Be careful when using chdir ".." that we
1332 return to the same directory from which we came, if necessary.
1333 Return an RM_status value to indicate success or failure. */
1335 static enum RM_status
1336 remove_dir (int fd_cwd, Dirstack_state *ds, char const *dir,
1337 struct stat *dir_st,
1338 struct rm_options const *x, int *cwd_errno)
1340 enum RM_status status;
1341 dev_t current_dev = dir_st->st_dev;
1343 /* There is a race condition in that an attacker could replace the nonempty
1344 directory, DIR, with a symlink between the preceding call to rmdir
1345 (unlinkat, in our caller) and fd_to_subdirp's openat call. But on most
1346 systems, even those without openat, this isn't a problem, since we ensure
1347 that opening a symlink will fail, when that is possible. Otherwise,
1348 fd_to_subdirp's fstat, along with the `fstat' and the dev/ino
1349 comparison in AD_push ensure that we detect it and fail. */
1351 DIR *dirp = fd_to_subdirp (fd_cwd, dir, x, 0, dir_st, cwd_errno);
1355 /* CAUTION: this test and diagnostic are identical to
1356 those following the other use of fd_to_subdirp. */
1357 if (ignorable_missing (x, errno))
1359 /* With -f, don't report "file not found". */
1363 /* Upon fd_to_subdirp failure, try to remove DIR directly,
1364 in case it's just an empty directory. */
1365 int saved_errno = errno;
1366 if (unlinkat (fd_cwd, dir, AT_REMOVEDIR) == 0)
1369 error (0, saved_errno,
1370 _("cannot remove %s"), quote (full_filename (dir)));
1376 if (ROOT_DEV_INO_CHECK (x->root_dev_ino, dir_st))
1378 ROOT_DEV_INO_WARN (full_filename (dir));
1380 goto closedir_and_return;
1383 AD_push (dirfd (dirp), ds, dir, dir_st);
1384 AD_INIT_OTHER_MEMBERS ();
1390 char *subdir = NULL;
1391 struct stat subdir_sb;
1392 enum RM_status tmp_status;
1394 tmp_status = remove_cwd_entries (&dirp, ds, &subdir, &subdir_sb, x);
1396 if (tmp_status != RM_OK)
1398 UPDATE_STATUS (status, tmp_status);
1399 AD_mark_current_as_unremovable (ds);
1403 if ( ! x->one_file_system
1404 || subdir_sb.st_dev == current_dev)
1406 AD_push (dirfd (dirp), ds, subdir, &subdir_sb);
1407 AD_INIT_OTHER_MEMBERS ();
1412 /* Here, --one-file-system is in effect, and with remove_cwd_entries'
1413 traversal into the current directory, (known as SUBDIR, from ..),
1414 DIRP's device number is different from CURRENT_DEV. Arrange not
1415 to do anything more with this hierarchy. */
1416 error (0, 0, _("skipping %s, since it's on a different device"),
1417 quote (full_filename (subdir)));
1419 AD_mark_current_as_unremovable (ds);
1420 tmp_status = RM_ERROR;
1421 UPDATE_STATUS (status, tmp_status);
1424 /* Execution reaches this point when we've removed the last
1425 removable entry from the current directory -- or, with
1426 --one-file-system, when the current directory is on a
1427 different file system. */
1430 /* The name of the directory that we have just processed,
1431 nominally removing all of its contents. */
1432 char *empty_dir = AD_pop_and_chdir (dirp, &fd, ds);
1434 assert (fd != AT_FDCWD || AD_stack_height (ds) == 1);
1436 /* Try to remove EMPTY_DIR only if remove_cwd_entries succeeded. */
1437 if (tmp_status == RM_OK)
1439 struct stat empty_st;
1441 int dirent_type = DT_DIR;
1442 enum RM_status s = prompt (fd, ds, empty_dir, &dirent_type,
1443 cache_stat_init (&empty_st), x,
1444 PA_REMOVE_DIR, &is_empty);
1452 goto closedir_and_return;
1455 if (unlinkat (fd, empty_dir, AT_REMOVEDIR) == 0)
1458 printf (_("removed directory: %s\n"),
1459 quote (full_filename (empty_dir)));
1463 error (0, errno, _("cannot remove directory %s"),
1464 quote (full_filename (empty_dir)));
1465 AD_mark_as_unremovable (ds, empty_dir);
1467 UPDATE_STATUS (AD_stack_top(ds)->status, status);
1476 dirp = fdopendir (fd);
1479 error (0, errno, _("FATAL: cannot return to .. from %s"),
1480 quote (full_filename (".")));
1482 longjmp (ds->current_arg_jumpbuf, 1);
1487 /* If the first/final hash table of unremovable entries was used,
1491 closedir_and_return:;
1492 if (dirp != NULL && closedir (dirp) != 0)
1494 error (0, 0, _("failed to close directory %s"),
1495 quote (full_filename (".")));
1502 /* Remove the file or directory specified by FILENAME.
1503 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not. */
1505 static enum RM_status
1506 rm_1 (Dirstack_state *ds, char const *filename,
1507 struct rm_options const *x, int *cwd_errno)
1509 char const *base = last_component (filename);
1510 if (dot_or_dotdot (base))
1512 error (0, 0, _(base == filename
1513 ? "cannot remove directory %s"
1514 : "cannot remove %s directory %s"),
1515 quote_n (0, base), quote_n (1, filename));
1520 cache_stat_init (&st);
1521 cycle_check_init (&ds->cycle_check_state);
1522 if (x->root_dev_ino)
1524 if (cache_fstatat (AT_FDCWD, filename, &st, AT_SYMLINK_NOFOLLOW) != 0)
1526 if (ignorable_missing (x, errno))
1528 error (0, errno, _("cannot remove %s"), quote (filename));
1531 if (SAME_INODE (st, *(x->root_dev_ino)))
1533 error (0, 0, _("cannot remove root directory %s"), quote (filename));
1538 AD_push_initial (ds);
1539 AD_INIT_OTHER_MEMBERS ();
1541 enum RM_status status = remove_entry (AT_FDCWD, ds, filename,
1542 DT_UNKNOWN, &st, x);
1543 if (status == RM_NONEMPTY_DIR)
1545 /* In the event that remove_dir->remove_cwd_entries detects
1546 a directory cycle, arrange to fail, give up on this FILE, but
1547 continue on with any other arguments. */
1548 if (setjmp (ds->current_arg_jumpbuf))
1551 status = remove_dir (AT_FDCWD, ds, filename, &st, x, cwd_errno);
1553 AD_stack_clear (ds);
1560 /* Remove all files and/or directories specified by N_FILES and FILE.
1561 Apply the options in X. */
1562 extern enum RM_status
1563 rm (size_t n_files, char const *const *file, struct rm_options const *x)
1565 enum RM_status status = RM_OK;
1566 Dirstack_state *ds = ds_init ();
1570 for (i = 0; i < n_files; i++)
1572 if (cwd_errno && IS_RELATIVE_FILE_NAME (file[i]))
1574 error (0, 0, _("cannot remove relative-named %s"), quote (file[i]));
1579 enum RM_status s = rm_1 (ds, file[i], x, &cwd_errno);
1580 assert (VALID_STATUS (s));
1581 UPDATE_STATUS (status, s);
1585 if (x->require_restore_cwd && cwd_errno)
1587 error (0, cwd_errno,
1588 _("cannot restore current working directory"));