1 /* remove.c -- core functions for removing files and directories
2 Copyright (C) 88, 90, 91, 1994-2004 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Extracted from rm.c and librarified, then rewritten by Jim Meyering. */
22 #include <sys/types.h>
28 #include "cycle-check.h"
31 #include "euidaccess.h"
32 #include "file-type.h"
38 #include "root-dev-ino.h"
40 /* Avoid shadowing warnings because these are functions declared
41 in dirname.h as well as locals used below. */
42 #define dir_name rm_dir_name
43 #define dir_len rm_dir_len
45 #define obstack_chunk_alloc malloc
46 #define obstack_chunk_free free
48 /* FIXME: if possible, use autoconf... */
50 # define ROOT_CAN_UNLINK_DIRS 0
52 # define ROOT_CAN_UNLINK_DIRS 1
55 #ifndef HAVE_WORKING_READDIR
56 # define HAVE_WORKING_READDIR 0
65 typedef enum Ternary Ternary;
67 /* The prompt function may be called twice for a given directory.
68 The first time, we ask whether to descend into it, and the
69 second time, we ask whether to remove it. */
72 PA_DESCEND_INTO_DIR = 2,
76 /* On systems with an lstat function that accepts the empty string,
77 arrange to make lstat calls go through the wrapper function. */
78 #if HAVE_LSTAT_EMPTY_STRING_BUG
79 int rpl_lstat (const char *, struct stat *);
80 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
83 /* Initial capacity of per-directory hash table of entries that have
84 been processed but not been deleted. */
85 #define HT_UNREMOVABLE_INITIAL_CAPACITY 13
87 /* An entry in the active directory stack.
88 Each entry corresponds to an `active' directory. */
91 /* For a given active directory, this is the set of names of
92 entries in that directory that could/should not be removed.
93 For example, `.' and `..', as well as files/dirs for which
94 unlink/rmdir failed e.g., due to access restrictions. */
95 Hash_table *unremovable;
97 /* Record the status for a given active directory; we need to know
98 whether an entry was not removed, either because of an error or
99 because the user declined. */
100 enum RM_status status;
104 /* The directory's dev/ino. Used to ensure that `chdir some-subdir', then
105 `chdir ..' takes us back to the same directory from which we started).
106 (valid for all but the bottommost entry on the stack. */
109 /* Enough information to restore the initial working directory.
110 (valid only for the bottommost entry on the stack) */
111 struct saved_cwd saved_cwd;
117 extern char *program_name;
119 struct dirstack_state
121 /* The name of the directory (starting with and relative to a command
122 line argument) being processed. When a subdirectory is entered, a new
123 component is appended (pushed). Remove (pop) the top component
124 upon chdir'ing out of a directory. This is used to form the full
125 name of the current directory or a file therein, when necessary. */
126 struct obstack dir_stack;
128 /* Stack of lengths of directory names (including trailing slash)
129 appended to dir_stack. We have to have a separate stack of lengths
130 (rather than just popping back to previous slash) because the first
131 element pushed onto the dir stack may contain slashes. */
132 struct obstack len_stack;
134 /* Stack of active directory entries.
135 The first `active' directory is the initial working directory.
136 Additional active dirs are pushed onto the stack as we `chdir'
137 into each directory to be processed. When finished with the
138 hierarchy under a directory, pop the active dir stack. */
139 struct obstack Active_dir;
141 /* Used to detect cycles. */
142 struct cycle_check_state cycle_check_state;
144 /* Target of a longjmp in case rm detects a directory cycle. */
145 jmp_buf current_arg_jumpbuf;
147 typedef struct dirstack_state Dirstack_state;
151 /* The value of errno after a failed save_cwd or restore_cwd. */
154 /* Information (open file descriptor or absolute directory name)
155 required in order to restore the initial working directory. */
156 struct saved_cwd saved_cwd;
159 static Dirstack_state *
162 Dirstack_state *ds = xmalloc (sizeof *ds);
163 obstack_init (&ds->dir_stack);
164 obstack_init (&ds->len_stack);
165 obstack_init (&ds->Active_dir);
170 ds_free (Dirstack_state *ds)
172 obstack_free (&ds->dir_stack, NULL);
173 obstack_free (&ds->len_stack, NULL);
174 obstack_free (&ds->Active_dir, NULL);
185 hash_compare_strings (void const *x, void const *y)
187 return STREQ (x, y) ? true : false;
191 push_dir (Dirstack_state *ds, const char *dir_name)
193 size_t len = strlen (dir_name);
195 /* Append the string onto the stack. */
196 obstack_grow (&ds->dir_stack, dir_name, len);
198 /* Append a trailing slash. */
199 obstack_1grow (&ds->dir_stack, '/');
201 /* Add one for the slash. */
204 /* Push the length (including slash) onto its stack. */
205 obstack_grow (&ds->len_stack, &len, sizeof (len));
208 /* Return the entry name of the directory on the top of the stack
209 in malloc'd storage. */
211 top_dir (Dirstack_state const *ds)
213 int n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
214 size_t *length = (size_t *) obstack_base (&ds->len_stack);
215 size_t top_len = length[n_lengths - 1];
216 char const *p = obstack_next_free (&ds->dir_stack) - top_len;
217 char *q = xmalloc (top_len);
218 memcpy (q, p, top_len - 1);
224 pop_dir (Dirstack_state *ds)
226 int n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
227 size_t *length = (size_t *) obstack_base (&ds->len_stack);
230 assert (n_lengths > 0);
231 top_len = length[n_lengths - 1];
232 assert (top_len >= 2);
234 /* Pop off the specified length of pathname. */
235 assert (obstack_object_size (&ds->dir_stack) >= top_len);
236 obstack_blank (&ds->dir_stack, -top_len);
238 /* Pop the length stack, too. */
239 assert (obstack_object_size (&ds->len_stack) >= sizeof (size_t));
240 obstack_blank (&ds->len_stack, -(int) sizeof (size_t));
243 /* Copy the SRC_LEN bytes of data beginning at SRC into the DST_LEN-byte
244 buffer, DST, so that the last source byte is at the end of the destination
245 buffer. If SRC_LEN is longer than DST_LEN, then set *TRUNCATED to non-zero.
246 Set *RESULT to point to the beginning of (the portion of) the source data
247 in DST. Return the number of bytes remaining in the destination buffer. */
250 right_justify (char *dst, size_t dst_len, const char *src, size_t src_len,
251 char **result, int *truncated)
256 if (src_len <= dst_len)
259 dp = dst + (dst_len - src_len);
264 sp = src + (src_len - dst_len);
270 *result = memcpy (dp, sp, src_len);
271 return dst_len - src_len;
274 /* Using the global directory name obstack, create the full path to FILENAME.
275 Return it in sometimes-realloc'd space that should not be freed by the
276 caller. Realloc as necessary. If realloc fails, use a static buffer
277 and put as long a suffix in that buffer as possible. */
279 #define full_filename(Filename) full_filename_ (ds, Filename)
281 full_filename_ (Dirstack_state const *ds, const char *filename)
283 static char *buf = NULL;
284 static size_t n_allocated = 0;
286 int dir_len = obstack_object_size (&ds->dir_stack);
287 char *dir_name = (char *) obstack_base (&ds->dir_stack);
288 size_t n_bytes_needed;
291 filename_len = strlen (filename);
292 n_bytes_needed = dir_len + filename_len + 1;
294 if (n_allocated < n_bytes_needed)
296 /* This code requires that realloc accept NULL as the first arg.
297 This function must not use xrealloc. Otherwise, an out-of-memory
298 error involving a file name to be expanded here wouldn't ever
299 be issued. Use realloc and fall back on using a static buffer
300 if memory allocation fails. */
301 char *new_buf = realloc (buf, n_bytes_needed);
302 n_allocated = n_bytes_needed;
306 #define SBUF_SIZE 512
307 #define ELLIPSES_PREFIX "[...]"
308 static char static_buf[SBUF_SIZE];
314 len = right_justify (static_buf, SBUF_SIZE, filename,
315 filename_len + 1, &p, &truncated);
316 right_justify (static_buf, len, dir_name, dir_len, &p, &truncated);
319 memcpy (static_buf, ELLIPSES_PREFIX,
320 sizeof (ELLIPSES_PREFIX) - 1);
328 if (filename_len == 1 && *filename == '.' && dir_len)
330 /* FILENAME is just `.' and dir_len is nonzero.
331 Copy the directory part, omitting the trailing slash,
332 and append a trailing zero byte. */
333 char *p = mempcpy (buf, dir_name, dir_len - 1);
338 /* Copy the directory part, including trailing slash, and then
339 append the filename part, including a trailing zero byte. */
340 memcpy (mempcpy (buf, dir_name, dir_len), filename, filename_len + 1);
341 assert (strlen (buf) + 1 == n_bytes_needed);
348 AD_stack_height (Dirstack_state const *ds)
350 return obstack_object_size (&ds->Active_dir) / sizeof (struct AD_ent);
353 static struct AD_ent *
354 AD_stack_top (Dirstack_state const *ds)
356 return (struct AD_ent *)
357 ((char *) obstack_next_free (&ds->Active_dir) - sizeof (struct AD_ent));
361 AD_stack_pop (Dirstack_state *ds)
363 /* operate on Active_dir. pop and free top entry */
364 struct AD_ent *top = AD_stack_top (ds);
365 if (top->unremovable)
366 hash_free (top->unremovable);
367 obstack_blank (&ds->Active_dir, -(int) sizeof (struct AD_ent));
371 /* chdir `up' one level.
372 Whenever using chdir '..', verify that the post-chdir
373 dev/ino numbers for `.' match the saved ones.
374 Set *PREV_DIR to the name (in malloc'd storage) of the
375 directory (usually now empty) from which we're coming.
376 Return nonzero upon failure of restore_cwd. Otherwise, return 0. */
378 AD_pop_and_chdir (Dirstack_state *ds, char **prev_dir)
380 enum RM_status old_status = AD_stack_top(ds)->status;
383 /* Get the name of the current (but soon to be `previous') directory
384 from the top of the stack. */
385 *prev_dir = top_dir (ds);
388 top = AD_stack_top (ds);
390 /* Propagate any failure to parent. */
391 UPDATE_STATUS (top->status, old_status);
393 assert (AD_stack_height (ds));
395 if (1 < AD_stack_height (ds))
399 /* We can give a better diagnostic here, since the target is relative. */
400 if (chdir ("..") != 0)
402 error (EXIT_FAILURE, errno,
403 _("cannot chdir from %s to .."),
404 quote (full_filename (".")));
407 if (lstat (".", &sb))
408 error (EXIT_FAILURE, errno,
409 _("cannot lstat `.' in %s"), quote (full_filename (".")));
411 /* Ensure that post-chdir dev/ino match the stored ones. */
412 if ( ! SAME_INODE (sb, top->u.a))
413 error (EXIT_FAILURE, 0,
414 _("%s changed dev/ino"), quote (full_filename (".")));
418 if (restore_cwd (&top->u.saved_cwd) != 0)
420 /* failed to return to initial working directory */
428 /* Initialize *HT if it is NULL.
429 Insert FILENAME into HT. */
431 AD_mark_helper (Hash_table **ht, char const *filename)
435 *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw,
436 hash_compare_strings, hash_freer);
440 if (! hash_insert (*ht, filename))
444 /* Mark FILENAME (in current directory) as unremovable. */
446 AD_mark_as_unremovable (Dirstack_state *ds, char const *filename)
448 AD_mark_helper (&AD_stack_top(ds)->unremovable, xstrdup (filename));
451 /* Mark the current directory as unremovable. I.e., mark the entry
452 in the parent directory corresponding to `.'.
453 This happens e.g., when an opendir fails and the only name
454 the caller has conveniently at hand is `.'. */
456 AD_mark_current_as_unremovable (Dirstack_state *ds)
458 struct AD_ent *top = AD_stack_top (ds);
459 const char *curr = top_dir (ds);
461 assert (1 < AD_stack_height (ds));
464 AD_mark_helper (&top->unremovable, curr);
467 /* Push the initial cwd info onto the stack.
468 This will always be the bottommost entry on the stack. */
470 AD_push_initial (Dirstack_state *ds, struct saved_cwd const *cwd)
474 /* Extend the stack. */
475 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
477 /* Fill in the new values. */
478 top = AD_stack_top (ds);
479 top->u.saved_cwd = *cwd;
480 top->unremovable = NULL;
483 /* Push info about the current working directory (".") onto the
484 active directory stack. DIR is the ./-relative name through
485 which we've just `chdir'd to this directory. DIR_SB_FROM_PARENT
486 is the result of calling lstat on DIR from the parent of DIR. */
488 AD_push (Dirstack_state *ds, char const *dir,
489 struct stat const *dir_sb_from_parent)
496 if (lstat (".", &sb))
497 error (EXIT_FAILURE, errno,
498 _("cannot lstat `.' in %s"), quote (full_filename (".")));
500 if ( ! SAME_INODE (sb, *dir_sb_from_parent))
501 error (EXIT_FAILURE, 0,
502 _("%s changed dev/ino"), quote (full_filename (".")));
504 /* Extend the stack. */
505 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
507 /* Fill in the new values. */
508 top = AD_stack_top (ds);
509 top->u.a.st_dev = sb.st_dev;
510 top->u.a.st_ino = sb.st_ino;
511 top->unremovable = NULL;
515 AD_is_removable (Dirstack_state const *ds, char const *file)
517 struct AD_ent *top = AD_stack_top (ds);
518 return ! (top->unremovable && hash_lookup (top->unremovable, file));
521 /* Return true if DIR is determined to be an empty directory
522 or if opendir or readdir fails. */
524 is_empty_dir (char const *dir)
526 DIR *dirp = opendir (dir);
527 struct dirent const *dp;
534 dp = readdir_ignoring_dot_and_dotdot (dirp);
539 return saved_errno == 0 ? true : false;
542 /* Return true if FILE is not a symbolic link and it is not writable.
543 Also return true if FILE cannot be lstat'ed. Otherwise, return false.
544 If lstat succeeds, set *BUF_P to BUF.
545 This is to avoid calling euidaccess when FILE is a symlink. */
547 write_protected_non_symlink (char const *file,
551 if (lstat (file, buf) != 0)
554 if (S_ISLNK (buf->st_mode))
556 return euidaccess (file, W_OK) == -1 && errno == EACCES;
559 /* Prompt whether to remove FILENAME, if required via a combination of
560 the options specified by X and/or file attributes. If the file may
561 be removed, return RM_OK. If the user declines to remove the file,
562 return RM_USER_DECLINED. If not ignoring missing files and we
563 cannot lstat FILENAME, then return RM_ERROR.
565 Depending on MODE, ask whether to `descend into' or to `remove' the
566 directory FILENAME. MODE is ignored when FILENAME is not a directory.
567 Set *IS_EMPTY to T_YES if FILENAME is an empty directory, and it is
568 appropriate to try to remove it with rmdir (e.g. recursive mode).
569 Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR.
570 Set *IS_DIR to T_YES or T_NO if we happen to determine whether
571 FILENAME is a directory. */
572 static enum RM_status
573 prompt (Dirstack_state const *ds, char const *filename,
574 struct rm_options const *x, enum Prompt_action mode,
575 Ternary *is_dir, Ternary *is_empty)
577 int write_protected = 0;
578 struct stat *sbuf = NULL;
581 *is_empty = T_UNKNOWN;
584 if ((!x->ignore_missing_files && (x->interactive || x->stdin_tty)
585 && (write_protected = write_protected_non_symlink (filename,
592 if (lstat (filename, sbuf))
594 /* lstat failed. This happens e.g., with `rm '''. */
595 error (0, errno, _("cannot lstat %s"),
596 quote (full_filename (filename)));
601 if (S_ISDIR (sbuf->st_mode) && !x->recursive)
603 error (0, EISDIR, _("cannot remove directory %s"),
604 quote (full_filename (filename)));
608 /* Using permissions doesn't make sense for symlinks. */
609 if (S_ISLNK (sbuf->st_mode))
611 if ( ! x->interactive)
616 /* Issue the prompt. */
618 char const *quoted_name = quote (full_filename (filename));
620 *is_dir = (S_ISDIR (sbuf->st_mode) ? T_YES : T_NO);
622 /* FIXME: use a variant of error (instead of fprintf) that doesn't
623 append a newline. Then we won't have to declare program_name in
625 if (S_ISDIR (sbuf->st_mode)
627 && mode == PA_DESCEND_INTO_DIR
628 && ((*is_empty = (is_empty_dir (filename) ? T_YES : T_NO))
632 ? _("%s: descend into write-protected directory %s? ")
633 : _("%s: descend into directory %s? ")),
634 program_name, quoted_name);
637 /* TRANSLATORS: You may find it more convenient to translate
638 the equivalent of _("%s: remove %s (write-protected) %s? ").
639 It should avoid grammatical problems with the output
643 ? _("%s: remove write-protected %s %s? ")
644 : _("%s: remove %s %s? ")),
645 program_name, file_type (sbuf), quoted_name);
649 return RM_USER_DECLINED;
655 #if HAVE_STRUCT_DIRENT_D_TYPE
656 # define DT_IS_DIR(D) ((D)->d_type == DT_DIR)
658 /* Use this only if the member exists -- i.e., don't return 0. */
659 # define DT_IS_DIR(D) do_not_use_this_macro
662 #define DO_UNLINK(Filename, X) \
665 if (unlink (Filename) == 0) \
668 printf (_("removed %s\n"), quote (full_filename (Filename))); \
672 if (errno == ENOENT && (X)->ignore_missing_files) \
677 #define DO_RMDIR(Filename, X) \
680 if (rmdir (Filename) == 0) \
683 printf (_("removed directory: %s\n"), \
684 quote (full_filename (Filename))); \
688 if (errno == ENOENT && (X)->ignore_missing_files) \
691 if (errno == ENOTEMPTY || errno == EEXIST) \
692 return RM_NONEMPTY_DIR; \
696 /* Remove the file or directory specified by FILENAME.
697 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
698 But if FILENAME specifies a non-empty directory, return RM_NONEMPTY_DIR. */
700 static enum RM_status
701 remove_entry (Dirstack_state const *ds, char const *filename,
702 struct rm_options const *x, struct dirent const *dp)
705 Ternary is_empty_directory;
706 enum RM_status s = prompt (ds, filename, x, PA_DESCEND_INTO_DIR,
707 &is_dir, &is_empty_directory);
712 /* Why bother with the following #if/#else block? Because on systems with
713 an unlink function that *can* unlink directories, we must determine the
714 type of each entry before removing it. Otherwise, we'd risk unlinking an
715 entire directory tree simply by unlinking a single directory; then all
716 the storage associated with that hierarchy would not be freed until the
717 next reboot. Not nice. To avoid that, on such slightly losing systems, we
718 need to call lstat to determine the type of each entry, and that represents
719 extra overhead that -- it turns out -- we can avoid on GNU-libc-based
720 systems, since there, unlink will never remove a directory. */
722 #if ROOT_CAN_UNLINK_DIRS
724 /* If we don't already know whether FILENAME is a directory, find out now.
725 Then, if it's a non-directory, we can use unlink on it. */
726 if (is_dir == T_UNKNOWN)
728 # if HAVE_STRUCT_DIRENT_D_TYPE
729 if (dp && dp->d_type != DT_UNKNOWN)
730 is_dir = DT_IS_DIR (dp) ? T_YES : T_NO;
735 if (lstat (filename, &sbuf))
737 if (errno == ENOENT && x->ignore_missing_files)
741 _("cannot lstat %s"), quote (full_filename (filename)));
745 is_dir = S_ISDIR (sbuf.st_mode) ? T_YES : T_NO;
751 /* At this point, barring race conditions, FILENAME is known
752 to be a non-directory, so it's ok to try to unlink it. */
753 DO_UNLINK (filename, x);
755 /* unlink failed with some other error code. report it. */
756 error (0, errno, _("cannot remove %s"),
757 quote (full_filename (filename)));
763 error (0, EISDIR, _("cannot remove directory %s"),
764 quote (full_filename (filename)));
768 if (is_empty_directory == T_YES)
770 DO_RMDIR (filename, x);
771 /* Don't diagnose any failure here.
772 It'll be detected when the caller tries another way. */
776 #else /* ! ROOT_CAN_UNLINK_DIRS */
778 if (is_dir == T_YES && ! x->recursive)
780 error (0, EISDIR, _("cannot remove directory %s"),
781 quote (full_filename (filename)));
785 /* is_empty_directory is set iff it's ok to use rmdir.
786 Note that it's set only in interactive mode -- in which case it's
787 an optimization that arranges so that the user is asked just
788 once whether to remove the directory. */
789 if (is_empty_directory == T_YES)
790 DO_RMDIR (filename, x);
792 /* If we happen to know that FILENAME is a directory, return now
793 and let the caller remove it -- this saves the overhead of a failed
794 unlink call. If FILENAME is a command-line argument, then dp is NULL,
795 so we'll first try to unlink it. Using unlink here is ok, because it
796 cannot remove a directory. */
797 if ((dp && DT_IS_DIR (dp)) || is_dir == T_YES)
798 return RM_NONEMPTY_DIR;
800 DO_UNLINK (filename, x);
803 || errno == ENOENT || errno == ENOTDIR
804 || errno == ELOOP || errno == ENAMETOOLONG)
806 /* Either --recursive is not in effect, or the file cannot be a
807 directory. Report the unlink problem and fail. */
808 error (0, errno, _("cannot remove %s"),
809 quote (full_filename (filename)));
814 return RM_NONEMPTY_DIR;
817 /* Remove entries in `.', the current working directory (cwd).
818 Upon finding a directory that is both non-empty and that can be chdir'd
819 into, return RM_OK and set *SUBDIR and fill in SUBDIR_SB, where
820 SUBDIR is the malloc'd name of the subdirectory if the chdir succeeded,
821 NULL otherwise (e.g., if opendir failed or if there was no subdirectory).
822 Likewise, SUBDIR_SB is the result of calling lstat on SUBDIR.
823 Return RM_OK if all entries are removed. Return RM_ERROR if any
824 entry cannot be removed. Otherwise, return RM_USER_DECLINED if
825 the user declines to remove at least one entry. Remove as much as
826 possible, continuing even if we fail to remove some entries. */
827 static enum RM_status
828 remove_cwd_entries (Dirstack_state *ds, char **subdir, struct stat *subdir_sb,
829 struct rm_options const *x)
831 DIR *dirp = opendir (".");
832 struct AD_ent *top = AD_stack_top (ds);
833 enum RM_status status = top->status;
834 bool need_rewinddir = false;
836 assert (VALID_STATUS (status));
841 if (errno != ENOENT || !x->ignore_missing_files)
843 error (0, errno, _("cannot open directory %s"),
844 quote (full_filename (".")));
851 struct dirent const *dp;
852 enum RM_status tmp_status;
855 /* Set errno to zero so we can distinguish between a readdir failure
856 and when readdir simply finds that there are no more entries. */
858 if ((dp = readdir_ignoring_dot_and_dotdot (dirp)) == NULL)
862 /* Save/restore errno across closedir call. */
867 /* Arrange to give a diagnostic after exiting this loop. */
870 else if (need_rewinddir)
872 /* On buggy systems, call rewinddir if we've called unlink
873 or rmdir since the opendir or a previous rewinddir. */
875 need_rewinddir = false;
883 /* Skip files we've already tried/failed to remove. */
884 if ( ! AD_is_removable (ds, f))
887 /* Pass dp->d_type info to remove_entry so the non-glibc
888 case can decide whether to use unlink or chdir.
889 Systems without the d_type member will have to endure
890 the performance hit of first calling lstat F. */
891 tmp_status = remove_entry (ds, f, x, dp);
895 /* On buggy systems, record the fact that we've just
896 removed a directory entry. */
897 need_rewinddir = ! HAVE_WORKING_READDIR;
901 case RM_USER_DECLINED:
902 AD_mark_as_unremovable (ds, f);
903 UPDATE_STATUS (status, tmp_status);
906 case RM_NONEMPTY_DIR:
908 /* Save a copy of errno, in case the preceding unlink (from
909 remove_entry's DO_UNLINK) of a non-directory failed. */
910 int saved_errno = errno;
912 /* Record dev/ino of F so that we can compare
913 that with dev/ino of `.' after the chdir.
914 This dev/ino pair is also used in cycle detection. */
915 if (lstat (f, subdir_sb))
916 error (EXIT_FAILURE, errno, _("cannot lstat %s"),
917 quote (full_filename (f)));
920 if (! S_ISDIR (subdir_sb->st_mode) || chdir (f) != 0)
922 /* It is much more common that we reach this point for an
923 inaccessible directory. Hence the second diagnostic, below.
924 However it is also possible that F is a non-directory.
925 That can happen when we use the `! ROOT_CAN_UNLINK_DIRS'
926 block of code and when DO_UNLINK fails due to EPERM.
927 In that case, give a better diagnostic. */
928 if (errno == ENOTDIR)
929 error (0, saved_errno, _("cannot remove %s"),
930 quote (full_filename (f)));
932 error (0, errno, _("cannot chdir from %s to %s"),
933 quote_n (0, full_filename (".")), quote_n (1, f));
934 AD_mark_as_unremovable (ds, f);
938 if (cycle_check (&ds->cycle_check_state, subdir_sb))
941 WARNING: Circular directory structure.\n\
942 This almost certainly means that you have a corrupted file system.\n\
943 NOTIFY YOUR SYSTEM MANAGER.\n\
944 The following directory is part of the cycle:\n %s\n"),
945 quote (full_filename (".")));
946 longjmp (ds->current_arg_jumpbuf, 1);
949 *subdir = xstrdup (f);
954 /* Record status for this directory. */
955 UPDATE_STATUS (top->status, status);
961 if (dirp == NULL || CLOSEDIR (dirp) != 0)
963 /* Note that this diagnostic serves for both readdir
964 and closedir failures. */
965 error (0, errno, _("reading directory %s"), quote (full_filename (".")));
972 /* Do this after each call to AD_push or AD_push_initial.
973 Because the status = RM_OK bit is too remove-specific to
974 go into the general-purpose AD_* package. */
975 #define AD_INIT_OTHER_MEMBERS() \
978 AD_stack_top(ds)->status = RM_OK; \
982 /* Remove the hierarchy rooted at DIR.
983 Do that by changing into DIR, then removing its contents, then
984 returning to the original working directory and removing DIR itself.
985 Don't use recursion. Be careful when using chdir ".." that we
986 return to the same directory from which we came, if necessary.
987 Return 1 for success, 0 if some file cannot be removed or if
989 If the initial working directory cannot be saved or restored,
990 record the offending errno value in (*CWD_STATE)->saved_errno. */
992 static enum RM_status
993 remove_dir (Dirstack_state *ds, char const *dir, struct cwd_state **cwd_state,
994 struct rm_options const *x)
996 enum RM_status status;
999 /* Save any errno (from caller's failed remove_entry call), in case DIR
1000 is not a directory, so that we can give a reasonable diagnostic. */
1001 int saved_errno = errno;
1003 if (*cwd_state == NULL)
1005 *cwd_state = xmalloc (sizeof **cwd_state);
1007 if (save_cwd (&(*cwd_state)->saved_cwd) != 0)
1009 (*cwd_state)->saved_errno = errno;
1010 assert (errno != 0);
1012 /* Pretend we started from ".". That is fine as long as there
1013 is no requirement to return to the original working directory. */
1014 (*cwd_state)->saved_cwd.name = xstrdup (".");
1017 (*cwd_state)->saved_errno = 0;
1019 AD_push_initial (ds, &(*cwd_state)->saved_cwd);
1020 AD_INIT_OTHER_MEMBERS ();
1023 /* If we've failed to record and/or restore the initial working directory,
1024 and we're now trying to access a `.'-relative file name, then give a
1025 diagnostic, record the failure, and proceed with any subsequent
1026 command-line arguments. */
1027 if ((*cwd_state)->saved_errno && IS_RELATIVE_FILE_NAME (dir))
1029 error (0, (*cwd_state)->saved_errno, _("cannot remove directory %s"),
1030 quote (full_filename (dir)));
1031 longjmp (ds->current_arg_jumpbuf, 1);
1034 /* There is a race condition in that an attacker could replace the nonempty
1035 directory, DIR, with a symlink between the preceding call to rmdir
1036 (in our caller) and the chdir below. However, the following lstat,
1037 along with the `stat (".",...' and dev/ino comparison in AD_push
1038 ensure that we detect it and fail. */
1040 if (lstat (dir, &dir_sb))
1043 _("cannot lstat %s"), quote (full_filename (dir)));
1048 if (! S_ISDIR (dir_sb.st_mode) || chdir (dir) != 0)
1050 if (errno == ENOTDIR)
1052 error (0, saved_errno,
1053 _("cannot remove %s"), quote (full_filename (dir)));
1058 _("cannot chdir from %s to %s"),
1059 quote_n (0, full_filename (".")), quote_n (1, dir));
1064 if (ROOT_DEV_INO_CHECK (x->root_dev_ino, &dir_sb))
1066 ROOT_DEV_INO_WARN (full_filename (dir));
1070 AD_push (ds, dir, &dir_sb);
1071 AD_INIT_OTHER_MEMBERS ();
1077 char *subdir = NULL;
1078 struct stat subdir_sb;
1079 enum RM_status tmp_status = remove_cwd_entries (ds,
1080 &subdir, &subdir_sb, x);
1081 if (tmp_status != RM_OK)
1083 UPDATE_STATUS (status, tmp_status);
1084 AD_mark_current_as_unremovable (ds);
1088 AD_push (ds, subdir, &subdir_sb);
1089 AD_INIT_OTHER_MEMBERS ();
1095 /* Execution reaches this point when we've removed the last
1096 removable entry from the current directory. */
1098 /* This is the name of the directory that we have just
1099 returned from, after nominally removing all of its contents. */
1102 if (AD_pop_and_chdir (ds, &empty_dir) != 0)
1103 (*cwd_state)->saved_errno = errno;
1105 /* Note: the above may have failed due to restore_cwd failure.
1106 That failure may be harmless if x->require_restore_cwd is false,
1107 but we do have to remember that fact, including the errno value,
1108 so we can give an accurate diagnostic when reporting the failure
1109 to remove a subsequent relative-named command-line argument. */
1111 /* Try to remove D only if remove_cwd_entries succeeded. */
1112 if (tmp_status == RM_OK)
1114 /* This does a little more work than necessary when it actually
1115 prompts the user. E.g., we already know that D is a directory
1116 and that it's almost certainly empty, yet we lstat it.
1117 But that's no big deal since we're interactive. */
1120 enum RM_status s = prompt (ds, empty_dir, x, PA_REMOVE_DIR,
1121 &is_dir, &is_empty);
1129 if (rmdir (empty_dir) == 0)
1132 printf (_("removed directory: %s\n"),
1133 quote (full_filename (empty_dir)));
1137 error (0, errno, _("cannot remove directory %s"),
1138 quote (full_filename (empty_dir)));
1139 AD_mark_as_unremovable (ds, empty_dir);
1141 UPDATE_STATUS (AD_stack_top(ds)->status, status);
1147 if (AD_stack_height (ds) == 1)
1155 /* Remove the file or directory specified by FILENAME.
1156 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
1157 On input, the first time this function is called, CWD_STATE should be
1158 the address of a NULL pointer. Do not modify it for any subsequent calls.
1159 On output, it is either that same NULL pointer or the address of
1160 a malloc'd `struct saved_cwd' that may be freed. */
1162 static enum RM_status
1163 rm_1 (Dirstack_state *ds, char const *filename,
1164 struct rm_options const *x, struct cwd_state **cwd_state)
1166 char *base = base_name (filename);
1167 enum RM_status status;
1169 if (DOT_OR_DOTDOT (base))
1171 error (0, 0, _("cannot remove `.' or `..'"));
1175 if (*cwd_state && (*cwd_state)->saved_errno
1176 && IS_RELATIVE_FILE_NAME (filename))
1178 error (0, (*cwd_state)->saved_errno,
1179 _("cannot remove %s"), quote (filename));
1183 status = remove_entry (ds, filename, x, NULL);
1184 if (status != RM_NONEMPTY_DIR)
1187 return remove_dir (ds, filename, cwd_state, x);
1190 /* Remove all files and/or directories specified by N_FILES and FILE.
1191 Apply the options in X. */
1192 extern enum RM_status
1193 rm (size_t n_files, char const *const *file, struct rm_options const *x)
1195 struct cwd_state *cwd_state = NULL;
1198 /* Put the following two variables in static storage, so they can't
1199 be clobbered by the potential longjmp into this function. */
1200 static enum RM_status status = RM_OK;
1205 for (i = 0; i < n_files; i++)
1208 cycle_check_init (&ds->cycle_check_state);
1209 /* In the event that rm_1->remove_dir->remove_cwd_entries detects
1210 a directory cycle, arrange to fail, give up on this FILE, but
1211 continue on with any other arguments. */
1212 if (setjmp (ds->current_arg_jumpbuf))
1215 s = rm_1 (ds, file[i], x, &cwd_state);
1216 assert (VALID_STATUS (s));
1217 UPDATE_STATUS (status, s);
1220 if (x->require_restore_cwd && cwd_state && cwd_state->saved_errno != 0)
1222 error (0, cwd_state->saved_errno,
1223 _("cannot restore current working directory"));