1 /* remove.c -- core functions for removing files and directories
2 Copyright (C) 88, 90, 91, 1994-2008 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"
38 #include "root-dev-ino.h"
39 #include "unlinkdir.h"
40 #include "write-any-file.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 /* This is the maximum number of consecutive readdir/unlink calls that
49 can be made (with no intervening rewinddir or closedir/opendir) before
50 triggering a bug that makes readdir return NULL even though some
51 directory entries have not been processed. The bug afflicts SunOS's
52 readdir when applied to ufs file systems and Darwin 6.5's (and OSX
53 v.10.3.8's) HFS+. This maximum is conservative in that demonstrating
54 the problem requires a directory containing at least 16 deletable
55 entries (which doesn't count . and ..).
56 This problem also affects Darwin 7.9.0 (aka MacOS X 10.3.9) on HFS+
57 and NFS-mounted file systems, but not vfat ones. */
60 CONSECUTIVE_READDIR_UNLINK_THRESHOLD = 10
63 /* If the heuristics in preprocess_dir suggest that there
64 are fewer than this many entries in a directory, then it
65 skips the preprocessing altogether. */
68 INODE_SORT_DIR_ENTRIES_THRESHOLD = 10000
71 /* FIXME: in 2009, or whenever Darwin 7.9.0 (aka MacOS X 10.3.9) is no
72 longer relevant, remove this work-around code. Then, there will be
73 no need to perform the extra rewinddir call, ever. */
74 #define NEED_REWIND(readdir_unlink_count) \
75 (CONSECUTIVE_READDIR_UNLINK_THRESHOLD <= (readdir_unlink_count))
83 typedef enum Ternary Ternary;
85 /* The prompt function may be called twice for a given directory.
86 The first time, we ask whether to descend into it, and the
87 second time, we ask whether to remove it. */
90 PA_DESCEND_INTO_DIR = 2,
94 /* Initial capacity of per-directory hash table of entries that have
95 been processed but not been deleted. */
96 enum { HT_UNREMOVABLE_INITIAL_CAPACITY = 13 };
98 /* An entry in the active directory stack.
99 Each entry corresponds to an `active' directory. */
102 /* For a given active directory, this is the set of names of
103 entries in that directory that could/should not be removed.
104 For example, `.' and `..', as well as files/dirs for which
105 unlink/rmdir failed e.g., due to access restrictions. */
106 Hash_table *unremovable;
108 /* Record the status for a given active directory; we need to know
109 whether an entry was not removed, either because of an error or
110 because the user declined. */
111 enum RM_status status;
113 /* The directory's dev/ino. Used to ensure that a malicious user does
114 not replace a directory we're about to process with a symlink to
115 some other directory. */
116 struct dev_ino dev_ino;
119 /* D_TYPE(D) is the type of directory entry D if known, DT_UNKNOWN
121 #if HAVE_STRUCT_DIRENT_D_TYPE
122 # define D_TYPE(d) ((d)->d_type)
124 # define D_TYPE(d) DT_UNKNOWN
126 /* Any int values will do here, so long as they're distinct.
127 Undef any existing macros out of the way. */
131 # define DT_UNKNOWN 0
136 struct dirstack_state
138 /* The name of the directory (starting with and relative to a command
139 line argument) being processed. When a subdirectory is entered, a new
140 component is appended (pushed). Remove (pop) the top component
141 upon chdir'ing out of a directory. This is used to form the full
142 name of the current directory or a file therein, when necessary. */
143 struct obstack dir_stack;
145 /* Stack of lengths of directory names (including trailing slash)
146 appended to dir_stack. We have to have a separate stack of lengths
147 (rather than just popping back to previous slash) because the first
148 element pushed onto the dir stack may contain slashes. */
149 struct obstack len_stack;
151 /* Stack of active directory entries.
152 The first `active' directory is the initial working directory.
153 Additional active dirs are pushed onto the stack as we `chdir'
154 into each directory to be processed. When finished with the
155 hierarchy under a directory, pop the active dir stack. */
156 struct obstack Active_dir;
158 /* Used to detect cycles. */
159 struct cycle_check_state cycle_check_state;
161 /* Target of a longjmp in case rm has to stop processing the current
162 command-line argument. This happens 1) when rm detects a directory
163 cycle or 2) when it has processed one or more directories, but then
164 is unable to return to the initial working directory to process
165 additional `.'-relative command-line arguments. */
166 jmp_buf current_arg_jumpbuf;
168 typedef struct dirstack_state Dirstack_state;
170 /* A static buffer and its allocated size, these variables are used by
171 xfull_filename and full_filename to form full, relative file names. */
173 static size_t g_n_allocated;
175 /* Like fstatat, but cache the result. If ST->st_size is -1, the
176 status has not been gotten yet. If less than -1, fstatat failed
177 with errno == ST->st_ino. Otherwise, the status has already
178 been gotten, so return 0. */
180 cache_fstatat (int fd, char const *file, struct stat *st, int flag)
182 if (st->st_size == -1 && fstatat (fd, file, st, flag) != 0)
187 if (0 <= st->st_size)
189 errno = (int) st->st_ino;
193 /* Initialize a fstatat cache *ST. Return ST for convenience. */
194 static inline struct stat *
195 cache_stat_init (struct stat *st)
201 /* Return true if *ST has been statted. */
203 cache_statted (struct stat *st)
205 return (st->st_size != -1);
208 /* Return true if *ST has been statted successfully. */
210 cache_stat_ok (struct stat *st)
212 return (0 <= st->st_size);
223 hash_compare_strings (void const *x, void const *y)
225 return STREQ (x, y) ? true : false;
228 /* Obstack allocator: longjump on failure. */
230 rm_malloc (void *v_jumpbuf, long size)
232 jmp_buf *jumpbuf = v_jumpbuf;
233 void *p = malloc (size);
236 longjmp (*jumpbuf, 1);
239 /* With the 2-arg allocator, we must also provide a two-argument freer. */
241 rm_free (void *v_jumpbuf ATTRIBUTE_UNUSED, void *ptr)
247 push_dir (Dirstack_state *ds, const char *dir_name)
249 size_t len = strlen (dir_name);
251 /* Don't copy trailing slashes. */
252 while (1 < len && dir_name[len - 1] == '/')
255 /* Append the string onto the stack. */
256 obstack_grow (&ds->dir_stack, dir_name, len);
258 /* Append a trailing slash. */
259 obstack_1grow (&ds->dir_stack, '/');
261 /* Add one for the slash. */
264 /* Push the length (including slash) onto its stack. */
265 obstack_grow (&ds->len_stack, &len, sizeof (len));
268 /* Return the entry name of the directory on the top of the stack
269 in malloc'd storage. */
271 top_dir (Dirstack_state *ds)
273 size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
274 size_t *length = obstack_base (&ds->len_stack);
275 size_t top_len = length[n_lengths - 1];
276 char const *p = obstack_next_free (&ds->dir_stack) - top_len;
277 char *q = malloc (top_len);
279 longjmp (ds->current_arg_jumpbuf, 1);
280 memcpy (q, p, top_len - 1);
286 pop_dir (Dirstack_state *ds)
288 size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
289 size_t *length = obstack_base (&ds->len_stack);
291 assert (n_lengths > 0);
292 size_t top_len = length[n_lengths - 1];
293 assert (top_len >= 2);
295 /* Pop the specified length of file name. */
296 assert (obstack_object_size (&ds->dir_stack) >= top_len);
297 obstack_blank (&ds->dir_stack, -top_len);
299 /* Pop the length stack, too. */
300 assert (obstack_object_size (&ds->len_stack) >= sizeof (size_t));
301 obstack_blank (&ds->len_stack, -(int) sizeof (size_t));
304 /* Copy the SRC_LEN bytes of data beginning at SRC into the DST_LEN-byte
305 buffer, DST, so that the last source byte is at the end of the destination
306 buffer. If SRC_LEN is longer than DST_LEN, then set *TRUNCATED.
307 Set *RESULT to point to the beginning of (the portion of) the source data
308 in DST. Return the number of bytes remaining in the destination buffer. */
311 right_justify (char *dst, size_t dst_len, const char *src, size_t src_len,
312 char **result, bool *truncated)
317 if (src_len <= dst_len)
320 dp = dst + (dst_len - src_len);
325 sp = src + (src_len - dst_len);
331 *result = memcpy (dp, sp, src_len);
332 return dst_len - src_len;
335 /* Using the global directory name obstack, create the full name of FILENAME.
336 Return it in sometimes-realloc'd space that should not be freed by the
337 caller. Realloc as necessary. If realloc fails, return NULL. */
340 full_filename0 (Dirstack_state const *ds, const char *filename)
342 size_t dir_len = obstack_object_size (&ds->dir_stack);
343 char *dir_name = obstack_base (&ds->dir_stack);
344 size_t filename_len = strlen (filename);
345 size_t n_bytes_needed = dir_len + filename_len + 1;
347 if (g_n_allocated < n_bytes_needed)
349 char *new_buf = realloc (g_buf, n_bytes_needed);
354 g_n_allocated = n_bytes_needed;
357 if (STREQ (filename, ".") && dir_len)
359 /* FILENAME is just `.' and dir_len is nonzero.
360 Copy the directory part, omitting the trailing slash,
361 and append a trailing zero byte. */
362 char *p = mempcpy (g_buf, dir_name, dir_len - 1);
367 /* Copy the directory part, including trailing slash, and then
368 append the filename part, including a trailing zero byte. */
369 memcpy (mempcpy (g_buf, dir_name, dir_len), filename, filename_len + 1);
370 assert (strlen (g_buf) + 1 == n_bytes_needed);
376 /* Using the global directory name obstack, create the full name of FILENAME.
377 Return it in sometimes-realloc'd space that should not be freed by the
378 caller. Realloc as necessary. If realloc fails, die. */
381 xfull_filename (Dirstack_state const *ds, const char *filename)
383 char *buf = full_filename0 (ds, filename);
389 /* Using the global directory name obstack, create the full name FILENAME.
390 Return it in sometimes-realloc'd space that should not be freed by the
391 caller. Realloc as necessary. If realloc fails, use a static buffer
392 and put as long a suffix in that buffer as possible. Be careful not
395 #define full_filename(Filename) full_filename_ (ds, Filename)
397 full_filename_ (Dirstack_state const *ds, const char *filename)
399 int saved_errno = errno;
400 char *full_name = full_filename0 (ds, filename);
408 #define SBUF_SIZE 512
409 #define ELLIPSES_PREFIX "[...]"
410 static char static_buf[SBUF_SIZE];
413 size_t n_bytes_remaining;
415 char *dir_name = obstack_base (&ds->dir_stack);
416 size_t dir_len = obstack_object_size (&ds->dir_stack);
419 n_bytes_remaining = right_justify (static_buf, SBUF_SIZE, filename,
420 strlen (filename) + 1, &p,
422 right_justify (static_buf, n_bytes_remaining, dir_name, dir_len,
424 if (file_truncated || dir_truncated)
426 memcpy (static_buf, ELLIPSES_PREFIX,
427 sizeof (ELLIPSES_PREFIX) - 1);
435 AD_stack_height (Dirstack_state const *ds)
437 return obstack_object_size (&ds->Active_dir) / sizeof (struct AD_ent);
440 static inline struct AD_ent *
441 AD_stack_top (Dirstack_state const *ds)
443 return (struct AD_ent *)
444 ((char *) obstack_next_free (&ds->Active_dir) - sizeof (struct AD_ent));
448 AD_stack_pop (Dirstack_state *ds)
450 assert (0 < AD_stack_height (ds));
452 /* operate on Active_dir. pop and free top entry */
453 struct AD_ent *top = AD_stack_top (ds);
454 if (top->unremovable)
455 hash_free (top->unremovable);
456 obstack_blank (&ds->Active_dir, -(int) sizeof (struct AD_ent));
460 AD_stack_clear (Dirstack_state *ds)
462 while (0 < AD_stack_height (ds))
468 /* Initialize obstack O just enough so that it may be freed
469 with obstack_free. */
471 obstack_init_minimal (struct obstack *o)
477 ds_init (Dirstack_state *ds)
480 struct obstack *o[3];
481 o[0] = &ds->dir_stack;
482 o[1] = &ds->len_stack;
483 o[2] = &ds->Active_dir;
485 /* Ensure each of these is NULL, in case init/allocation
486 fails and we end up calling ds_free on all three while only
487 one or two has been initialized. */
488 for (i = 0; i < 3; i++)
489 obstack_init_minimal (o[i]);
491 for (i = 0; i < 3; i++)
492 obstack_specify_allocation_with_arg
493 (o[i], 0, 0, rm_malloc, rm_free, &ds->current_arg_jumpbuf);
497 ds_clear (Dirstack_state *ds)
499 obstack_free (&ds->dir_stack, obstack_finish (&ds->dir_stack));
500 obstack_free (&ds->len_stack, obstack_finish (&ds->len_stack));
501 while (0 < AD_stack_height (ds))
503 obstack_free (&ds->Active_dir, obstack_finish (&ds->Active_dir));
507 ds_free (Dirstack_state *ds)
509 obstack_free (&ds->dir_stack, NULL);
510 obstack_free (&ds->len_stack, NULL);
511 obstack_free (&ds->Active_dir, NULL);
514 /* Pop the active directory (AD) stack and prepare to move `up' one level,
515 safely. Moving `up' usually means opening `..', but when we've just
516 finished recursively processing a command-line directory argument,
517 there's nothing left on the stack, so set *FDP to AT_FDCWD in that case.
518 The idea is to return with *FDP opened on the parent directory,
519 assuming there are entries in that directory that we need to remove.
521 Note that we must not call opendir (or fdopendir) just yet, since
522 the caller must first remove the directory we're coming from.
523 That is because some file system implementations cache readdir
524 results at opendir time; so calling opendir, rmdir, readdir would
525 return an entry for the just-removed directory.
527 Whenever using chdir '..' (virtually, now, via openat), verify
528 that the post-chdir dev/ino numbers for `.' match the saved ones.
529 If any system call fails or if dev/ino don't match, then give a
530 diagnostic and longjump out.
531 Return the name (in malloc'd storage) of the
532 directory (usually now empty) from which we're coming, and which
533 corresponds to the input value of DIRP.
535 Finally, note that while this function's name is no longer as
536 accurate as it once was (it no longer calls chdir), it does open
537 the destination directory. */
539 AD_pop_and_chdir (DIR *dirp, int *fdp, Dirstack_state *ds)
541 struct AD_ent *leaf_dir_ent = AD_stack_top(ds);
542 struct dev_ino leaf_dev_ino = leaf_dir_ent->dev_ino;
543 enum RM_status old_status = leaf_dir_ent->status;
546 /* Get the name of the current (but soon to be `previous') directory
547 from the top of the stack. */
548 char *prev_dir = top_dir (ds);
552 top = AD_stack_top (ds);
554 /* If the directory we're about to leave (and try to rmdir)
555 is the one whose dev_ino is being used to detect a cycle,
556 reset cycle_check_state.dev_ino to that of the parent.
557 Otherwise, once that directory is removed, its dev_ino
558 could be reused in the creation (by some other process)
559 of a directory that this rm process would encounter,
560 which would result in a false-positive cycle indication. */
561 CYCLE_CHECK_REFLECT_CHDIR_UP (&ds->cycle_check_state,
562 top->dev_ino, leaf_dev_ino);
564 /* Propagate any failure to parent. */
565 UPDATE_STATUS (top->status, old_status);
567 assert (AD_stack_height (ds));
569 if (1 < AD_stack_height (ds))
572 int fd = openat (dirfd (dirp), "..", O_RDONLY);
573 if (closedir (dirp) != 0)
575 error (0, errno, _("FATAL: failed to close directory %s"),
576 quote (full_filename (prev_dir)));
577 goto next_cmdline_arg;
580 /* The above fails with EACCES when DIRP is readable but not
581 searchable, when using Solaris' openat. Without this openat
582 call, tests/rm2 would fail to remove directories a/2 and a/3. */
584 fd = openat (AT_FDCWD, xfull_filename (ds, "."), O_RDONLY);
588 error (0, errno, _("FATAL: cannot open .. from %s"),
589 quote (full_filename (prev_dir)));
590 goto next_cmdline_arg;
596 _("FATAL: cannot ensure %s (returned to via ..) is safe"),
597 quote (full_filename (".")));
601 /* Ensure that post-chdir dev/ino match the stored ones. */
602 if ( ! SAME_INODE (sb, top->dev_ino))
604 error (0, 0, _("FATAL: directory %s changed dev/ino"),
605 quote (full_filename (".")));
611 longjmp (ds->current_arg_jumpbuf, 1);
617 if (closedir (dirp) != 0)
619 error (0, errno, _("FATAL: failed to close directory %s"),
620 quote (full_filename (prev_dir)));
621 goto next_cmdline_arg;
629 /* Initialize *HT if it is NULL. Return *HT. */
631 AD_ensure_initialized (Hash_table **ht)
635 *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw,
636 hash_compare_strings, hash_freer);
644 /* Initialize *HT if it is NULL.
645 Insert FILENAME into HT. */
647 AD_mark_helper (Hash_table **ht, char *filename)
649 void *ent = hash_insert (AD_ensure_initialized (ht), filename);
659 /* Mark FILENAME (in current directory) as unremovable. */
661 AD_mark_as_unremovable (Dirstack_state *ds, char const *filename)
663 AD_mark_helper (&AD_stack_top(ds)->unremovable, xstrdup (filename));
666 /* Mark the current directory as unremovable. I.e., mark the entry
667 in the parent directory corresponding to `.'.
668 This happens e.g., when an opendir fails and the only name
669 the caller has conveniently at hand is `.'. */
671 AD_mark_current_as_unremovable (Dirstack_state *ds)
673 struct AD_ent *top = AD_stack_top (ds);
674 char *curr = top_dir (ds);
676 assert (1 < AD_stack_height (ds));
679 AD_mark_helper (&top->unremovable, curr);
682 /* Push an initial dummy entry onto the stack.
683 This will always be the bottommost entry on the stack. */
685 AD_push_initial (Dirstack_state *ds)
689 /* Extend the stack. */
690 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
692 /* Fill in the new values. */
693 top = AD_stack_top (ds);
694 top->unremovable = NULL;
696 /* These should never be used.
697 Give them values that might look suspicious
698 in a debugger or in a diagnostic. */
699 top->dev_ino.st_dev = TYPE_MAXIMUM (dev_t);
700 top->dev_ino.st_ino = TYPE_MAXIMUM (ino_t);
703 /* Push info about the current working directory (".") onto the
704 active directory stack. DIR is the ./-relative name through
705 which we've just `chdir'd to this directory. DIR_SB_FROM_PARENT
706 is the result of calling lstat on DIR from the parent of DIR.
707 Longjump out (skipping the entire command line argument we're
708 dealing with) if `fstat (FD_CWD, ...' fails or if someone has
709 replaced DIR with e.g., a symlink to some other directory. */
711 AD_push (int fd_cwd, Dirstack_state *ds, char const *dir,
712 struct stat const *dir_sb_from_parent)
718 /* If our uses of openat are guaranteed not to
719 follow a symlink, then we can skip this check. */
720 if (! HAVE_WORKING_O_NOFOLLOW)
723 if (fstat (fd_cwd, &sb) != 0)
725 error (0, errno, _("FATAL: cannot enter directory %s"),
726 quote (full_filename (".")));
727 longjmp (ds->current_arg_jumpbuf, 1);
730 if ( ! SAME_INODE (sb, *dir_sb_from_parent))
733 _("FATAL: just-changed-to directory %s changed dev/ino"),
734 quote (full_filename (".")));
735 longjmp (ds->current_arg_jumpbuf, 1);
739 if (cycle_check (&ds->cycle_check_state, dir_sb_from_parent))
742 WARNING: Circular directory structure.\n\
743 This almost certainly means that you have a corrupted file system.\n\
744 NOTIFY YOUR SYSTEM MANAGER.\n\
745 The following directory is part of the cycle:\n %s\n"),
746 quote (full_filename (".")));
747 longjmp (ds->current_arg_jumpbuf, 1);
750 /* Extend the stack. */
751 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
753 /* The active directory stack must be one larger than the length stack. */
754 assert (AD_stack_height (ds) ==
755 1 + obstack_object_size (&ds->len_stack) / sizeof (size_t));
757 /* Fill in the new values. */
758 top = AD_stack_top (ds);
759 top->dev_ino.st_dev = dir_sb_from_parent->st_dev;
760 top->dev_ino.st_ino = dir_sb_from_parent->st_ino;
761 top->unremovable = NULL;
765 AD_is_removable (Dirstack_state const *ds, char const *file)
767 struct AD_ent *top = AD_stack_top (ds);
768 return ! (top->unremovable && hash_lookup (top->unremovable, file));
771 /* Return 1 if FILE is an unwritable non-symlink,
772 0 if it is writable or some other type of file,
773 -1 and set errno if there is some problem in determining the answer.
774 Set *BUF to the file status.
775 This is to avoid calling euidaccess when FILE is a symlink. */
777 write_protected_non_symlink (int fd_cwd,
779 Dirstack_state const *ds,
782 if (can_write_any_file ())
784 if (cache_fstatat (fd_cwd, file, buf, AT_SYMLINK_NOFOLLOW) != 0)
786 if (S_ISLNK (buf->st_mode))
788 /* Here, we know FILE is not a symbolic link. */
790 /* In order to be reentrant -- i.e., to avoid changing the working
791 directory, and at the same time to be able to deal with alternate
792 access control mechanisms (ACLs, xattr-style attributes) and
793 arbitrarily deep trees -- we need a function like eaccessat, i.e.,
794 like Solaris' eaccess, but fd-relative, in the spirit of openat. */
796 /* In the absence of a native eaccessat function, here are some of
797 the implementation choices [#4 and #5 were suggested by Paul Eggert]:
798 1) call openat with O_WRONLY|O_NOCTTY
799 Disadvantage: may create the file and doesn't work for directory,
800 may mistakenly report `unwritable' for EROFS or ACLs even though
801 perm bits say the file is writable.
803 2) fake eaccessat (save_cwd, fchdir, call euidaccess, restore_cwd)
804 Disadvantage: changes working directory (not reentrant) and can't
805 work if save_cwd fails.
807 3) if (euidaccess (xfull_filename (file), W_OK) == 0)
808 Disadvantage: doesn't work if xfull_filename is too long.
809 Inefficient for very deep trees (O(Depth^2)).
811 4) If the full pathname is sufficiently short (say, less than
812 PATH_MAX or 8192 bytes, whichever is shorter):
813 use method (3) (i.e., euidaccess (xfull_filename (file), W_OK));
814 Otherwise: vfork, fchdir in the child, run euidaccess in the
815 child, then the child exits with a status that tells the parent
816 whether euidaccess succeeded.
818 This avoids the O(N**2) algorithm of method (3), and it also avoids
819 the failure-due-to-too-long-file-names of method (3), but it's fast
820 in the normal shallow case. It also avoids the lack-of-reentrancy
821 and the save_cwd problems.
822 Disadvantage; it uses a process slot for very-long file names,
823 and would be very slow for hierarchies with many such files.
825 5) If the full file name is sufficiently short (say, less than
826 PATH_MAX or 8192 bytes, whichever is shorter):
827 use method (3) (i.e., euidaccess (xfull_filename (file), W_OK));
828 Otherwise: look just at the file bits. Perhaps issue a warning
829 the first time this occurs.
831 This is like (4), except for the "Otherwise" case where it isn't as
832 "perfect" as (4) but is considerably faster. It conforms to current
833 POSIX, and is uniformly better than what Solaris and FreeBSD do (they
834 mess up with long file names). */
837 /* This implements #5: */
839 = obstack_object_size (&ds->dir_stack) + strlen (file);
841 if (MIN (PATH_MAX, 8192) <= file_name_len)
842 return ! euidaccess_stat (buf, W_OK);
843 if (euidaccess (xfull_filename (ds, file), W_OK) == 0)
851 /* Perhaps some other process has removed the file, or perhaps this
852 is a buggy NFS client. */
857 /* Prompt whether to remove FILENAME, if required via a combination of
858 the options specified by X and/or file attributes. If the file may
859 be removed, return RM_OK. If the user declines to remove the file,
860 return RM_USER_DECLINED. If not ignoring missing files and we
861 cannot lstat FILENAME, then return RM_ERROR.
863 *PDIRENT_TYPE is the type of the directory entry; update it to DT_DIR
864 or DT_LNK as needed. *SBUF is the file's status.
866 Depending on MODE, ask whether to `descend into' or to `remove' the
867 directory FILENAME. MODE is ignored when FILENAME is not a directory.
868 Set *IS_EMPTY to T_YES if FILENAME is an empty directory, and it is
869 appropriate to try to remove it with rmdir (e.g. recursive mode).
870 Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR. */
871 static enum RM_status
872 prompt (int fd_cwd, Dirstack_state const *ds, char const *filename,
873 int *pdirent_type, struct stat *sbuf,
874 struct rm_options const *x, enum Prompt_action mode,
877 int write_protected = 0;
878 int dirent_type = *pdirent_type;
880 *is_empty = T_UNKNOWN;
882 if (x->interactive == RMI_NEVER)
887 if (!x->ignore_missing_files
888 && ((x->interactive == RMI_ALWAYS) || x->stdin_tty)
889 && dirent_type != DT_LNK)
891 write_protected = write_protected_non_symlink (fd_cwd, filename, ds, sbuf);
895 if (write_protected || x->interactive == RMI_ALWAYS)
897 if (0 <= write_protected && dirent_type == DT_UNKNOWN)
899 if (cache_fstatat (fd_cwd, filename, sbuf, AT_SYMLINK_NOFOLLOW) == 0)
901 if (S_ISLNK (sbuf->st_mode))
902 dirent_type = DT_LNK;
903 else if (S_ISDIR (sbuf->st_mode))
904 dirent_type = DT_DIR;
905 /* Otherwise it doesn't matter, so leave it DT_UNKNOWN. */
906 *pdirent_type = dirent_type;
910 /* This happens, e.g., with `rm '''. */
911 write_protected = -1;
916 if (0 <= write_protected)
920 /* Using permissions doesn't make sense for symlinks. */
921 if (x->interactive != RMI_ALWAYS)
928 write_protected = -1;
934 char const *quoted_name = quote (full_filename (filename));
936 if (write_protected < 0)
938 error (0, wp_errno, _("cannot remove %s"), quoted_name);
942 /* Issue the prompt. */
943 /* FIXME: use a variant of error (instead of fprintf) that doesn't
944 append a newline. Then we won't have to declare program_name in
946 if (dirent_type == DT_DIR
947 && mode == PA_DESCEND_INTO_DIR
948 && ((*is_empty = (is_empty_dir (fd_cwd, filename) ? T_YES : T_NO))
952 ? _("%s: descend into write-protected directory %s? ")
953 : _("%s: descend into directory %s? ")),
954 program_name, quoted_name);
957 if (cache_fstatat (fd_cwd, filename, sbuf, AT_SYMLINK_NOFOLLOW) != 0)
959 error (0, errno, _("cannot remove %s"), quoted_name);
965 /* TRANSLATORS: You may find it more convenient to
966 translate "%s: remove %s (write-protected) %s? "
967 instead. It should avoid grammatical problems
968 with the output of file_type. */
969 ? _("%s: remove write-protected %s %s? ")
970 : _("%s: remove %s %s? ")),
971 program_name, file_type (sbuf), quoted_name);
975 return RM_USER_DECLINED;
980 /* Return true if FILENAME is a directory (and not a symlink to a directory).
981 Otherwise, including the case in which lstat fails, return false.
982 *ST is FILENAME's tstatus.
983 Do not modify errno. */
985 is_dir_lstat (int fd_cwd, char const *filename, struct stat *st)
987 int saved_errno = errno;
989 (cache_fstatat (fd_cwd, filename, st, AT_SYMLINK_NOFOLLOW) == 0
990 && S_ISDIR (st->st_mode));
995 /* Return true if FILENAME is a non-directory.
996 Otherwise, including the case in which lstat fails, return false.
997 *ST is FILENAME's tstatus.
998 Do not modify errno. */
1000 is_nondir_lstat (int fd_cwd, char const *filename, struct stat *st)
1002 int saved_errno = errno;
1004 (cache_fstatat (fd_cwd, filename, st, AT_SYMLINK_NOFOLLOW) == 0
1005 && !S_ISDIR (st->st_mode));
1006 errno = saved_errno;
1010 #define DO_UNLINK(Fd_cwd, Filename, X) \
1013 if (unlinkat (Fd_cwd, Filename, 0) == 0) \
1016 printf (_("removed %s\n"), quote (full_filename (Filename))); \
1020 if (ignorable_missing (X, errno)) \
1025 #define DO_RMDIR(Fd_cwd, Filename, X) \
1028 if (unlinkat (Fd_cwd, Filename, AT_REMOVEDIR) == 0) /* rmdir */ \
1031 printf (_("removed directory: %s\n"), \
1032 quote (full_filename (Filename))); \
1036 if (ignorable_missing (X, errno)) \
1039 if (errno == ENOTEMPTY || errno == EEXIST) \
1040 return RM_NONEMPTY_DIR; \
1044 /* When a function like unlink, rmdir, or fstatat fails with an errno
1045 value of ERRNUM, return true if the specified file system object
1046 is guaranteed not to exist; otherwise, return false. */
1048 nonexistent_file_errno (int errnum)
1050 /* Do not include ELOOP here, since the specified file may indeed
1051 exist, but be (in)accessible only via too long a symlink chain.
1052 Likewise for ENAMETOOLONG, since rm -f ./././.../foo may fail
1053 if the "..." part expands to a long enough sequence of "./"s,
1054 even though ./foo does indeed exist. */
1066 /* Encapsulate the test for whether the errno value, ERRNUM, is ignorable. */
1068 ignorable_missing (struct rm_options const *x, int errnum)
1070 return x->ignore_missing_files && nonexistent_file_errno (errnum);
1073 /* Remove the file or directory specified by FILENAME.
1074 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
1075 But if FILENAME specifies a non-empty directory, return RM_NONEMPTY_DIR. */
1077 static enum RM_status
1078 remove_entry (int fd_cwd, Dirstack_state const *ds, char const *filename,
1079 int dirent_type_arg, struct stat *st,
1080 struct rm_options const *x)
1082 Ternary is_empty_directory;
1083 enum RM_status s = prompt (fd_cwd, ds, filename, &dirent_type_arg, st, x,
1084 PA_DESCEND_INTO_DIR,
1085 &is_empty_directory);
1086 int dirent_type = dirent_type_arg;
1090 /* Why bother with the following if/else block? Because on systems with
1091 an unlink function that *can* unlink directories, we must determine the
1092 type of each entry before removing it. Otherwise, we'd risk unlinking
1093 an entire directory tree simply by unlinking a single directory; then
1094 all the storage associated with that hierarchy would not be freed until
1095 the next fsck. Not nice. To avoid that, on such slightly losing
1096 systems, we need to call lstat to determine the type of each entry,
1097 and that represents extra overhead that -- it turns out -- we can
1098 avoid on non-losing systems, since there, unlink will never remove
1099 a directory. Also, on systems where unlink may unlink directories,
1100 we're forced to allow a race condition: we lstat a non-directory, then
1101 go to unlink it, but in the mean time, a malicious someone could have
1102 replaced it with a directory. */
1104 if (cannot_unlink_dir ())
1106 if (dirent_type == DT_DIR && ! x->recursive)
1108 error (0, EISDIR, _("cannot remove %s"),
1109 quote (full_filename (filename)));
1113 /* is_empty_directory is set iff it's ok to use rmdir.
1114 Note that it's set only in interactive mode -- in which case it's
1115 an optimization that arranges so that the user is asked just
1116 once whether to remove the directory. */
1117 if (is_empty_directory == T_YES)
1118 DO_RMDIR (fd_cwd, filename, x);
1120 /* If we happen to know that FILENAME is a directory, return now
1121 and let the caller remove it -- this saves the overhead of a failed
1122 unlink call. If FILENAME is a command-line argument, then
1123 DIRENT_TYPE is DT_UNKNOWN so we'll first try to unlink it.
1124 Using unlink here is ok, because it cannot remove a
1126 if (dirent_type == DT_DIR)
1127 return RM_NONEMPTY_DIR;
1129 DO_UNLINK (fd_cwd, filename, x);
1131 /* Upon a failed attempt to unlink a directory, most non-Linux systems
1132 set errno to the POSIX-required value EPERM. In that case, change
1133 errno to EISDIR so that we emit a better diagnostic. */
1134 if (! x->recursive && errno == EPERM && is_dir_lstat (fd_cwd,
1139 || (cache_stat_ok (st) && !S_ISDIR (st->st_mode))
1140 || ((errno == EACCES || errno == EPERM)
1141 && is_nondir_lstat (fd_cwd, filename, st))
1144 if (ignorable_missing (x, errno))
1147 /* Either --recursive is not in effect, or the file cannot be a
1148 directory. Report the unlink problem and fail. */
1149 error (0, errno, _("cannot remove %s"),
1150 quote (full_filename (filename)));
1153 assert (!cache_stat_ok (st) || S_ISDIR (st->st_mode));
1157 /* If we don't already know whether FILENAME is a directory,
1158 find out now. Then, if it's a non-directory, we can use
1161 if (dirent_type == DT_UNKNOWN)
1163 if (fstatat (fd_cwd, filename, st, AT_SYMLINK_NOFOLLOW))
1165 if (ignorable_missing (x, errno))
1168 error (0, errno, _("cannot remove %s"),
1169 quote (full_filename (filename)));
1173 if (S_ISDIR (st->st_mode))
1174 dirent_type = DT_DIR;
1177 if (dirent_type != DT_DIR)
1179 /* At this point, barring race conditions, FILENAME is known
1180 to be a non-directory, so it's ok to try to unlink it. */
1181 DO_UNLINK (fd_cwd, filename, x);
1183 /* unlink failed with some other error code. report it. */
1184 error (0, errno, _("cannot remove %s"),
1185 quote (full_filename (filename)));
1191 error (0, EISDIR, _("cannot remove %s"),
1192 quote (full_filename (filename)));
1196 if (is_empty_directory == T_YES)
1198 DO_RMDIR (fd_cwd, filename, x);
1199 /* Don't diagnose any failure here.
1200 It'll be detected when the caller tries another way. */
1204 return RM_NONEMPTY_DIR;
1207 /* Given FD_CWD, the file descriptor for an open directory,
1208 open its subdirectory F (F is already `known' to be a directory,
1209 so if it is no longer one, someone is playing games), return a DIR*
1210 pointer for F, and put F's `stat' data in *SUBDIR_SB.
1211 Upon failure give a diagnostic and return NULL.
1212 If PREV_ERRNO is nonzero, it is the errno value from a preceding failed
1213 unlink- or rmdir-like system call -- use that value instead of ENOTDIR
1214 if an opened file turns out not to be a directory. This is important
1215 when the preceding non-dir-unlink failed due to e.g., EPERM or EACCES.
1216 The caller must use a nonnnull CWD_ERRNO the first
1217 time this function is called for each command-line-specified directory.
1218 If CWD_ERRNO is not null, set *CWD_ERRNO to the appropriate error number
1219 if this function fails to restore the initial working directory.
1220 If it is null, report an error and exit if the working directory
1223 fd_to_subdirp (int fd_cwd, char const *f,
1225 struct stat *subdir_sb,
1226 int *cwd_errno ATTRIBUTE_UNUSED)
1228 int open_flags = O_RDONLY | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK;
1229 int fd_sub = openat_permissive (fd_cwd, f, open_flags, 0, cwd_errno);
1232 /* Record dev/ino of F. We may compare them against saved values
1233 to thwart any attempt to subvert the traversal. They are also used
1234 to detect directory cycles. */
1237 else if (fstat (fd_sub, subdir_sb) != 0)
1238 saved_errno = errno;
1239 else if (S_ISDIR (subdir_sb->st_mode))
1241 DIR *subdir_dirp = fdopendir (fd_sub);
1244 saved_errno = errno;
1247 saved_errno = (prev_errno ? prev_errno : ENOTDIR);
1250 errno = saved_errno;
1257 char name[FLEXIBLE_ARRAY_MEMBER];
1260 #if HAVE_STRUCT_DIRENT_D_TYPE
1261 /* A comparison function to sort on increasing inode number. */
1263 compare_ino (void const *av, void const *bv)
1265 struct readdir_data const *const *a = av;
1266 struct readdir_data const *const *b = bv;
1267 return (a[0]->ino < b[0]->ino ? -1
1268 : b[0]->ino < a[0]->ino ? 1 : 0);
1271 /* Return an approximation of the maximum number of dirent entries
1272 in a directory with stat data *ST. */
1274 dirent_count (struct stat const *st)
1276 return st->st_size / 16;
1279 # if HAVE_SYS_VFS_H && HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE
1280 # include <sys/vfs.h>
1283 /* Return false if it is easy to determine the file system type of
1284 the directory on which DIR_FD is open, and sorting dirents on
1285 inode numbers is known not to improve traversal performance with
1286 that type of file system. Otherwise, return true. */
1288 dirent_inode_sort_may_be_useful (int dir_fd)
1290 /* Skip the sort only if we can determine efficiently
1291 that skipping it is the right thing to do.
1292 The cost of performing an unnecessary sort is negligible,
1293 while the cost of *not* performing it can be O(N^2) with
1294 a very large constant. */
1295 struct statfs fs_buf;
1297 /* If fstatfs fails, assume sorting would be useful. */
1298 if (fstatfs (dir_fd, &fs_buf) != 0)
1301 /* FIXME: what about when f_type is not an integral type?
1302 deal with that if/when it's encountered. */
1303 switch (fs_buf.f_type)
1307 /* On a file system of any of these types, sorting
1308 is unnecessary, and hence wasteful. */
1315 # else /* !HAVE_STRUCT_STATFS_F_TYPE */
1316 static bool dirent_inode_sort_may_be_useful (int dir_fd) { return true; }
1317 # endif /* !HAVE_STRUCT_STATFS_F_TYPE */
1318 #endif /* HAVE_STRUCT_DIRENT_D_TYPE */
1320 /* When a directory contains very many entries, operating on N entries in
1321 readdir order can be very seek-intensive (be it to unlink or even to
1322 merely stat each entry), to the point that it results in O(N^2) work.
1323 This is file-system-specific: ext3 and ext4 (as of 2008) are susceptible,
1324 but tmpfs is not. The general solution is to process entries in inode
1325 order. That means reading all entries, and sorting them before operating
1326 on any. As such, it is useful only on systems with useful dirent.d_ino.
1327 Since 'rm -r's removal process must traverse into directories and since
1328 this preprocessing phase can allocate O(N) storage, here we store and
1329 sort only non-directory entries, and then remove all of those, so that we
1330 can free all allocated storage before traversing into any subdirectory.
1331 Perform this optimization only when not interactive and not in verbose
1332 mode, to keep the implementation simple and to minimize duplication.
1333 Upon failure, simply free any resources and return. */
1335 preprocess_dir (DIR **dirp, struct rm_options const *x)
1337 #if HAVE_STRUCT_DIRENT_D_TYPE
1340 /* There are many reasons to return right away, skipping this
1341 optimization. The penalty for being wrong is that we will
1342 perform a small amount of extra work.
1344 Skip this optimization if... */
1346 int dir_fd = dirfd (*dirp);
1347 if (/* - there is a chance of interactivity */
1348 x->interactive != RMI_NEVER
1350 /* - we're in verbose mode */
1353 /* - privileged users can unlink nonempty directories.
1354 Otherwise, there'd be a race condition between the readdir
1355 call (in which we learn dirent.d_type) and the unlink, by
1356 which time the non-directory may be replaced with a directory. */
1357 || ! cannot_unlink_dir ()
1359 /* - we can't fstat the file descriptor */
1360 || fstat (dir_fd, &st) != 0
1362 /* - the directory is smaller than some threshold.
1363 Estimate the number of inodes with a heuristic.
1364 There's no significant benefit to sorting if there are
1366 || dirent_count (&st) < INODE_SORT_DIR_ENTRIES_THRESHOLD
1368 /* Sort only if it might help. */
1369 || ! dirent_inode_sort_may_be_useful (dir_fd))
1372 /* FIXME: maybe test file system type, too; skip if it's tmpfs: see fts.c */
1374 struct obstack o_readdir_data; /* readdir data: inode,name pairs */
1375 struct obstack o_p; /* an array of pointers to each inode,name pair */
1377 /* Arrange to longjmp upon obstack allocation failure. */
1378 jmp_buf readdir_jumpbuf;
1379 if (setjmp (readdir_jumpbuf))
1382 obstack_init_minimal (&o_readdir_data);
1383 obstack_init_minimal (&o_p);
1385 obstack_specify_allocation_with_arg (&o_readdir_data, 0, 0,
1386 rm_malloc, rm_free, &readdir_jumpbuf);
1387 obstack_specify_allocation_with_arg (&o_p, 0, 0,
1388 rm_malloc, rm_free, &readdir_jumpbuf);
1390 /* Read all entries, storing <d_ino, d_name> for each non-dir one.
1391 Maintain a parallel list of pointers into the primary buffer. */
1394 struct dirent const *dp;
1395 dp = readdir_ignoring_dot_and_dotdot (*dirp);
1396 /* no need to distinguish EOF from failure */
1400 /* Skip known-directory and type-unknown entries. */
1401 if (D_TYPE (dp) == DT_UNKNOWN || D_TYPE (dp) == DT_DIR)
1404 size_t name_len = strlen (dp->d_name);
1405 size_t ent_len = offsetof (struct readdir_data, name) + name_len + 1;
1406 struct readdir_data *v = obstack_alloc (&o_readdir_data, ent_len);
1407 v->ino = D_INO (dp);
1408 memcpy (v->name, dp->d_name, name_len + 1);
1410 /* Append V to the list of pointers. */
1411 obstack_ptr_grow (&o_p, v);
1414 /* Compute size and finalize VV. */
1415 size_t n = obstack_object_size (&o_p) / sizeof (void *);
1416 struct readdir_data **vv = obstack_finish (&o_p);
1418 /* Sort on inode number. */
1419 qsort(vv, n, sizeof *vv, compare_ino);
1421 /* Iterate through those pointers, unlinking each name. */
1422 for (size_t i = 0; i < n; i++)
1424 /* ignore failure */
1425 (void) unlinkat (dir_fd, vv[i]->name, 0);
1429 obstack_free (&o_readdir_data, NULL);
1430 obstack_free (&o_p, NULL);
1435 /* Remove entries in the directory open on DIRP
1436 Upon finding a directory that is both non-empty and that can be chdir'd
1437 into, return RM_OK and set *SUBDIR and fill in SUBDIR_SB, where
1438 SUBDIR is the malloc'd name of the subdirectory if the chdir succeeded,
1439 NULL otherwise (e.g., if opendir failed or if there was no subdirectory).
1440 Likewise, SUBDIR_SB is the result of calling lstat on SUBDIR.
1441 Return RM_OK if all entries are removed. Return RM_ERROR if any
1442 entry cannot be removed. Otherwise, return RM_USER_DECLINED if
1443 the user declines to remove at least one entry. Remove as much as
1444 possible, continuing even if we fail to remove some entries. */
1445 static enum RM_status
1446 remove_cwd_entries (DIR **dirp,
1447 Dirstack_state *ds, char **subdir, struct stat *subdir_sb,
1448 struct rm_options const *x)
1450 struct AD_ent *top = AD_stack_top (ds);
1451 enum RM_status status = top->status;
1452 size_t n_unlinked_since_opendir_or_last_rewind = 0;
1454 assert (VALID_STATUS (status));
1457 /* This is just an optimization.
1458 It's not a fatal problem if it fails. */
1459 preprocess_dir (dirp, x);
1463 struct dirent const *dp;
1464 enum RM_status tmp_status;
1467 /* Set errno to zero so we can distinguish between a readdir failure
1468 and when readdir simply finds that there are no more entries. */
1470 dp = readdir_ignoring_dot_and_dotdot (*dirp);
1477 else if (NEED_REWIND (n_unlinked_since_opendir_or_last_rewind))
1479 /* Call rewinddir if we've called unlink or rmdir so many times
1480 (since the opendir or the previous rewinddir) that this
1481 NULL-return may be the symptom of a buggy readdir. */
1483 n_unlinked_since_opendir_or_last_rewind = 0;
1491 /* Skip files we've already tried/failed to remove. */
1492 if ( ! AD_is_removable (ds, f))
1495 /* Pass dp->d_type info to remove_entry so the non-glibc
1496 case can decide whether to use unlink or chdir.
1497 Systems without the d_type member will have to endure
1498 the performance hit of first calling lstat F. */
1499 cache_stat_init (subdir_sb);
1500 tmp_status = remove_entry (dirfd (*dirp), ds, f,
1501 D_TYPE (dp), subdir_sb, x);
1505 /* Count how many files we've unlinked since the initial
1506 opendir or the last rewinddir. On buggy systems, if you
1507 remove too many, readdir returns NULL even though there
1508 remain unprocessed directory entries. */
1509 ++n_unlinked_since_opendir_or_last_rewind;
1513 case RM_USER_DECLINED:
1514 AD_mark_as_unremovable (ds, f);
1515 UPDATE_STATUS (status, tmp_status);
1518 case RM_NONEMPTY_DIR:
1520 DIR *subdir_dirp = fd_to_subdirp (dirfd (*dirp), f,
1521 errno, subdir_sb, NULL);
1522 if (subdir_dirp == NULL)
1526 /* CAUTION: this test and diagnostic are identical to
1527 those following the other use of fd_to_subdirp. */
1528 if (ignorable_missing (x, errno))
1530 /* With -f, don't report "file not found". */
1534 /* Upon fd_to_subdirp failure, try to remove F directly,
1535 in case it's just an empty directory. */
1536 int saved_errno = errno;
1537 if (unlinkat (dirfd (*dirp), f, AT_REMOVEDIR) == 0)
1540 error (0, saved_errno,
1541 _("cannot remove %s"), quote (full_filename (f)));
1544 if (status == RM_ERROR)
1545 AD_mark_as_unremovable (ds, f);
1549 *subdir = xstrdup (f);
1550 if (closedir (*dirp) != 0)
1552 error (0, 0, _("failed to close directory %s"),
1553 quote (full_filename (".")));
1556 *dirp = subdir_dirp;
1562 /* Record status for this directory. */
1563 UPDATE_STATUS (top->status, status);
1569 /* Ensure that *dirp is not NULL and that its file descriptor is valid. */
1570 assert (*dirp != NULL);
1571 assert (0 <= fcntl (dirfd (*dirp), F_GETFD));
1576 /* Do this after each call to AD_push or AD_push_initial.
1577 Because the status = RM_OK bit is too remove-specific to
1578 go into the general-purpose AD_* package. */
1579 #define AD_INIT_OTHER_MEMBERS() \
1582 AD_stack_top(ds)->status = RM_OK; \
1586 /* Remove the hierarchy rooted at DIR.
1587 Do that by changing into DIR, then removing its contents, then
1588 returning to the original working directory and removing DIR itself.
1589 Don't use recursion. Be careful when using chdir ".." that we
1590 return to the same directory from which we came, if necessary.
1591 Return an RM_status value to indicate success or failure. */
1593 static enum RM_status
1594 remove_dir (int fd_cwd, Dirstack_state *ds, char const *dir,
1595 struct stat *dir_st,
1596 struct rm_options const *x, int *cwd_errno)
1598 enum RM_status status;
1599 dev_t current_dev = dir_st->st_dev;
1601 /* There is a race condition in that an attacker could replace the nonempty
1602 directory, DIR, with a symlink between the preceding call to rmdir
1603 (unlinkat, in our caller) and fd_to_subdirp's openat call. But on most
1604 systems, even those without openat, this isn't a problem, since we ensure
1605 that opening a symlink will fail, when that is possible. Otherwise,
1606 fd_to_subdirp's fstat, along with the `fstat' and the dev/ino
1607 comparison in AD_push ensure that we detect it and fail. */
1609 DIR *dirp = fd_to_subdirp (fd_cwd, dir, 0, dir_st, cwd_errno);
1613 /* CAUTION: this test and diagnostic are identical to
1614 those following the other use of fd_to_subdirp. */
1615 if (ignorable_missing (x, errno))
1617 /* With -f, don't report "file not found". */
1621 /* Upon fd_to_subdirp failure, try to remove DIR directly,
1622 in case it's just an empty directory. */
1623 int saved_errno = errno;
1624 if (unlinkat (fd_cwd, dir, AT_REMOVEDIR) == 0)
1627 error (0, saved_errno,
1628 _("cannot remove %s"), quote (full_filename (dir)));
1634 if (ROOT_DEV_INO_CHECK (x->root_dev_ino, dir_st))
1636 ROOT_DEV_INO_WARN (full_filename (dir));
1638 goto closedir_and_return;
1641 AD_push (dirfd (dirp), ds, dir, dir_st);
1642 AD_INIT_OTHER_MEMBERS ();
1648 char *subdir = NULL;
1649 struct stat subdir_sb;
1650 enum RM_status tmp_status;
1652 tmp_status = remove_cwd_entries (&dirp, ds, &subdir, &subdir_sb, x);
1654 if (tmp_status != RM_OK)
1656 UPDATE_STATUS (status, tmp_status);
1657 AD_mark_current_as_unremovable (ds);
1661 if ( ! x->one_file_system
1662 || subdir_sb.st_dev == current_dev)
1664 AD_push (dirfd (dirp), ds, subdir, &subdir_sb);
1665 AD_INIT_OTHER_MEMBERS ();
1670 /* Here, --one-file-system is in effect, and with remove_cwd_entries'
1671 traversal into the current directory, (known as SUBDIR, from ..),
1672 DIRP's device number is different from CURRENT_DEV. Arrange not
1673 to do anything more with this hierarchy. */
1674 error (0, 0, _("skipping %s, since it's on a different device"),
1675 quote (full_filename (subdir)));
1677 AD_mark_current_as_unremovable (ds);
1678 tmp_status = RM_ERROR;
1679 UPDATE_STATUS (status, tmp_status);
1682 /* Execution reaches this point when we've removed the last
1683 removable entry from the current directory -- or, with
1684 --one-file-system, when the current directory is on a
1685 different file system. */
1688 /* The name of the directory that we have just processed,
1689 nominally removing all of its contents. */
1690 char *empty_dir = AD_pop_and_chdir (dirp, &fd, ds);
1692 assert (fd != AT_FDCWD || AD_stack_height (ds) == 1);
1694 /* Try to remove EMPTY_DIR only if remove_cwd_entries succeeded. */
1695 if (tmp_status == RM_OK)
1697 struct stat empty_st;
1699 int dirent_type = DT_DIR;
1700 enum RM_status s = prompt (fd, ds, empty_dir, &dirent_type,
1701 cache_stat_init (&empty_st), x,
1702 PA_REMOVE_DIR, &is_empty);
1710 goto closedir_and_return;
1713 if (unlinkat (fd, empty_dir, AT_REMOVEDIR) == 0)
1716 printf (_("removed directory: %s\n"),
1717 quote (full_filename (empty_dir)));
1721 error (0, errno, _("cannot remove directory %s"),
1722 quote (full_filename (empty_dir)));
1723 AD_mark_as_unremovable (ds, empty_dir);
1725 UPDATE_STATUS (AD_stack_top(ds)->status, status);
1734 dirp = fdopendir (fd);
1737 error (0, errno, _("FATAL: cannot return to .. from %s"),
1738 quote (full_filename (".")));
1740 longjmp (ds->current_arg_jumpbuf, 1);
1745 /* If the first/final hash table of unremovable entries was used,
1749 closedir_and_return:;
1750 if (dirp != NULL && closedir (dirp) != 0)
1752 error (0, 0, _("failed to close directory %s"),
1753 quote (full_filename (".")));
1760 /* Remove the file or directory specified by FILENAME.
1761 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not. */
1763 static enum RM_status
1764 rm_1 (Dirstack_state *ds, char const *filename,
1765 struct rm_options const *x, int *cwd_errno)
1767 char const *base = last_component (filename);
1768 if (dot_or_dotdot (base))
1770 error (0, 0, _(base == filename
1771 ? N_("cannot remove directory %s")
1772 : N_("cannot remove %s directory %s")),
1773 quote_n (0, base), quote_n (1, filename));
1778 cache_stat_init (&st);
1779 cycle_check_init (&ds->cycle_check_state);
1780 if (x->root_dev_ino)
1782 if (cache_fstatat (AT_FDCWD, filename, &st, AT_SYMLINK_NOFOLLOW) != 0)
1784 if (ignorable_missing (x, errno))
1786 error (0, errno, _("cannot remove %s"), quote (filename));
1789 if (SAME_INODE (st, *(x->root_dev_ino)))
1791 error (0, 0, _("cannot remove root directory %s"), quote (filename));
1796 AD_push_initial (ds);
1797 AD_INIT_OTHER_MEMBERS ();
1799 enum RM_status status = remove_entry (AT_FDCWD, ds, filename,
1800 DT_UNKNOWN, &st, x);
1801 if (status == RM_NONEMPTY_DIR)
1803 /* In the event that remove_dir->remove_cwd_entries detects
1804 a directory cycle, arrange to fail, give up on this FILE, but
1805 continue on with any other arguments. */
1806 if (setjmp (ds->current_arg_jumpbuf))
1809 status = remove_dir (AT_FDCWD, ds, filename, &st, x, cwd_errno);
1811 AD_stack_clear (ds);
1818 /* Remove all files and/or directories specified by N_FILES and FILE.
1819 Apply the options in X. */
1820 extern enum RM_status
1821 rm (size_t n_files, char const *const *file, struct rm_options const *x)
1823 enum RM_status status = RM_OK;
1828 /* Arrange for obstack allocation failure to longjmp. */
1829 if (setjmp (ds.current_arg_jumpbuf))
1837 for (i = 0; i < n_files; i++)
1839 if (cwd_errno && IS_RELATIVE_FILE_NAME (file[i]))
1841 error (0, 0, _("cannot remove relative-named %s"), quote (file[i]));
1846 enum RM_status s = rm_1 (&ds, file[i], x, &cwd_errno);
1847 assert (VALID_STATUS (s));
1848 UPDATE_STATUS (status, s);
1852 if (x->require_restore_cwd && cwd_errno)
1854 error (0, cwd_errno,
1855 _("cannot restore current working directory"));