.
[coreutils.git] / src / remove.c
blob06071677af9db7fbb50b31287688d2cd2ab89929
1 /* remove.c -- core functions for removing files and directories
2 Copyright (C) 88, 90, 91, 1994-2003 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)
7 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, 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. */
20 #include <config.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <setjmp.h>
24 #include <assert.h>
26 #include "save-cwd.h"
27 #include "system.h"
28 #include "cycle-check.h"
29 #include "dirname.h"
30 #include "error.h"
31 #include "euidaccess.h"
32 #include "file-type.h"
33 #include "hash.h"
34 #include "hash-pjw.h"
35 #include "obstack.h"
36 #include "quote.h"
37 #include "remove.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... */
49 #ifdef __GLIBC__
50 # define ROOT_CAN_UNLINK_DIRS 0
51 #else
52 # define ROOT_CAN_UNLINK_DIRS 1
53 #endif
55 #ifndef HAVE_WORKING_READDIR
56 # define HAVE_WORKING_READDIR 0
57 #endif
59 enum Ternary
61 T_UNKNOWN = 2,
62 T_NO,
63 T_YES
65 typedef enum Ternary Ternary;
67 /* The prompt function may be called twice 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. */
70 enum Prompt_action
72 PA_DESCEND_INTO_DIR = 2,
73 PA_REMOVE_DIR
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)
81 #endif
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. */
89 struct AD_ent
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;
102 union
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. */
107 struct dev_ino a;
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;
112 } u;
115 int yesno ();
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;
149 Dirstack_state *
150 ds_init ()
152 Dirstack_state *ds = XMALLOC (struct dirstack_state, 1);
153 obstack_init (&ds->dir_stack);
154 obstack_init (&ds->len_stack);
155 obstack_init (&ds->Active_dir);
156 return ds;
159 void
160 ds_free (Dirstack_state *ds)
162 obstack_free (&ds->dir_stack, NULL);
163 obstack_free (&ds->len_stack, NULL);
164 obstack_free (&ds->Active_dir, NULL);
167 static void
168 hash_freer (void *x)
170 free (x);
173 static bool
174 hash_compare_strings (void const *x, void const *y)
176 return STREQ (x, y) ? true : false;
179 static inline void
180 push_dir (Dirstack_state *ds, const char *dir_name)
182 size_t len;
184 len = strlen (dir_name);
186 /* Append the string onto the stack. */
187 obstack_grow (&ds->dir_stack, dir_name, len);
189 /* Append a trailing slash. */
190 obstack_1grow (&ds->dir_stack, '/');
192 /* Add one for the slash. */
193 ++len;
195 /* Push the length (including slash) onto its stack. */
196 obstack_grow (&ds->len_stack, &len, sizeof (len));
199 /* Return the entry name of the directory on the top of the stack
200 in malloc'd storage. */
201 static inline char *
202 top_dir (Dirstack_state const *ds)
204 int n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
205 size_t *length = (size_t *) obstack_base (&ds->len_stack);
206 size_t top_len = length[n_lengths - 1];
207 char const *p = obstack_next_free (&ds->dir_stack) - top_len;
208 char *q = xmalloc (top_len);
209 memcpy (q, p, top_len - 1);
210 q[top_len - 1] = 0;
211 return q;
214 static inline void
215 pop_dir (Dirstack_state *ds)
217 int n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
218 size_t *length = (size_t *) obstack_base (&ds->len_stack);
219 size_t top_len;
221 assert (n_lengths > 0);
222 top_len = length[n_lengths - 1];
223 assert (top_len >= 2);
225 /* Pop off the specified length of pathname. */
226 assert (obstack_object_size (&ds->dir_stack) >= top_len);
227 obstack_blank (&ds->dir_stack, -top_len);
229 /* Pop the length stack, too. */
230 assert (obstack_object_size (&ds->len_stack) >= sizeof (size_t));
231 obstack_blank (&ds->len_stack, -(int) sizeof (size_t));
234 /* Copy the SRC_LEN bytes of data beginning at SRC into the DST_LEN-byte
235 buffer, DST, so that the last source byte is at the end of the destination
236 buffer. If SRC_LEN is longer than DST_LEN, then set *TRUNCATED to non-zero.
237 Set *RESULT to point to the beginning of (the portion of) the source data
238 in DST. Return the number of bytes remaining in the destination buffer. */
240 static size_t
241 right_justify (char *dst, size_t dst_len, const char *src, size_t src_len,
242 char **result, int *truncated)
244 const char *sp;
245 char *dp;
247 if (src_len <= dst_len)
249 sp = src;
250 dp = dst + (dst_len - src_len);
251 *truncated = 0;
253 else
255 sp = src + (src_len - dst_len);
256 dp = dst;
257 src_len = dst_len;
258 *truncated = 1;
261 *result = memcpy (dp, sp, src_len);
262 return dst_len - src_len;
265 /* Using the global directory name obstack, create the full path to FILENAME.
266 Return it in sometimes-realloc'd space that should not be freed by the
267 caller. Realloc as necessary. If realloc fails, use a static buffer
268 and put as long a suffix in that buffer as possible. */
270 #define full_filename(Filename) full_filename_ (ds, Filename)
271 static char *
272 full_filename_ (Dirstack_state const *ds, const char *filename)
274 static char *buf = NULL;
275 static size_t n_allocated = 0;
277 int dir_len = obstack_object_size (&ds->dir_stack);
278 char *dir_name = (char *) obstack_base (&ds->dir_stack);
279 size_t n_bytes_needed;
280 size_t filename_len;
282 filename_len = strlen (filename);
283 n_bytes_needed = dir_len + filename_len + 1;
285 if (n_allocated < n_bytes_needed)
287 /* This code requires that realloc accept NULL as the first arg.
288 This function must not use xrealloc. Otherwise, an out-of-memory
289 error involving a file name to be expanded here wouldn't ever
290 be issued. Use realloc and fall back on using a static buffer
291 if memory allocation fails. */
292 buf = realloc (buf, n_bytes_needed);
293 n_allocated = n_bytes_needed;
295 if (buf == NULL)
297 #define SBUF_SIZE 512
298 #define ELLIPSES_PREFIX "[...]"
299 static char static_buf[SBUF_SIZE];
300 int truncated;
301 size_t len;
302 char *p;
304 len = right_justify (static_buf, SBUF_SIZE, filename,
305 filename_len + 1, &p, &truncated);
306 right_justify (static_buf, len, dir_name, dir_len, &p, &truncated);
307 if (truncated)
309 memcpy (static_buf, ELLIPSES_PREFIX,
310 sizeof (ELLIPSES_PREFIX) - 1);
312 return p;
316 if (filename_len == 1 && *filename == '.' && dir_len)
318 /* FILENAME is just `.' and dir_len is nonzero.
319 Copy the directory part, omitting the trailing slash,
320 and append a trailing zero byte. */
321 char *p = mempcpy (buf, dir_name, dir_len - 1);
322 *p = 0;
324 else
326 /* Copy the directory part, including trailing slash, and then
327 append the filename part, including a trailing zero byte. */
328 memcpy (mempcpy (buf, dir_name, dir_len), filename, filename_len + 1);
329 assert (strlen (buf) + 1 == n_bytes_needed);
332 return buf;
335 static size_t
336 AD_stack_height (Dirstack_state const *ds)
338 return obstack_object_size (&ds->Active_dir) / sizeof (struct AD_ent);
341 static struct AD_ent *
342 AD_stack_top (Dirstack_state const *ds)
344 return (struct AD_ent *)
345 ((char *) obstack_next_free (&ds->Active_dir) - sizeof (struct AD_ent));
348 static void
349 AD_stack_pop (Dirstack_state *ds)
351 /* operate on Active_dir. pop and free top entry */
352 struct AD_ent *top = AD_stack_top (ds);
353 if (top->unremovable)
354 hash_free (top->unremovable);
355 obstack_blank (&ds->Active_dir, -(int) sizeof (struct AD_ent));
356 pop_dir (ds);
359 /* chdir `up' one level.
360 Whenever using chdir '..', verify that the post-chdir
361 dev/ino numbers for `.' match the saved ones.
362 Return the name (in malloc'd storage) of the
363 directory (usually now empty) from which we're coming. */
364 static char *
365 AD_pop_and_chdir (Dirstack_state *ds)
367 /* Get the name of the current directory from the top of the stack. */
368 char *dir = top_dir (ds);
369 enum RM_status old_status = AD_stack_top(ds)->status;
370 struct stat sb;
371 struct AD_ent *top;
373 AD_stack_pop (ds);
375 /* Propagate any failure to parent. */
376 UPDATE_STATUS (AD_stack_top(ds)->status, old_status);
378 assert (AD_stack_height (ds));
380 top = AD_stack_top (ds);
381 if (1 < AD_stack_height (ds))
383 /* We can give a better diagnostic here, since the target is relative. */
384 if (chdir (".."))
386 error (EXIT_FAILURE, errno,
387 _("cannot chdir from %s to .."),
388 quote (full_filename (".")));
391 else
393 if (restore_cwd (&top->u.saved_cwd))
394 error (EXIT_FAILURE, errno,
395 _("failed to return to initial working directory"));
398 if (lstat (".", &sb))
399 error (EXIT_FAILURE, errno,
400 _("cannot lstat `.' in %s"), quote (full_filename (".")));
402 if (1 < AD_stack_height (ds))
404 /* Ensure that post-chdir dev/ino match the stored ones. */
405 if ( ! SAME_INODE (sb, top->u.a))
406 error (EXIT_FAILURE, 0,
407 _("%s changed dev/ino"), quote (full_filename (".")));
410 return dir;
413 /* Initialize *HT if it is NULL.
414 Insert FILENAME into HT. */
415 static void
416 AD_mark_helper (Hash_table **ht, char const *filename)
418 if (*ht == NULL)
419 *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw,
420 hash_compare_strings, hash_freer);
421 if (*ht == NULL)
422 xalloc_die ();
423 if (! hash_insert (*ht, filename))
424 xalloc_die ();
427 /* Mark FILENAME (in current directory) as unremovable. */
428 static void
429 AD_mark_as_unremovable (Dirstack_state *ds, char const *filename)
431 AD_mark_helper (&AD_stack_top(ds)->unremovable, xstrdup (filename));
434 /* Mark the current directory as unremovable. I.e., mark the entry
435 in the parent directory corresponding to `.'.
436 This happens e.g., when an opendir fails and the only name
437 the caller has conveniently at hand is `.'. */
438 static void
439 AD_mark_current_as_unremovable (Dirstack_state *ds)
441 struct AD_ent *top = AD_stack_top (ds);
442 const char *curr = top_dir (ds);
444 assert (1 < AD_stack_height (ds));
446 --top;
447 AD_mark_helper (&top->unremovable, curr);
450 /* Push the initial cwd info onto the stack.
451 This will always be the bottommost entry on the stack. */
452 static void
453 AD_push_initial (Dirstack_state *ds, struct saved_cwd const *cwd)
455 struct AD_ent *top;
457 /* Extend the stack. */
458 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
460 /* Fill in the new values. */
461 top = AD_stack_top (ds);
462 top->u.saved_cwd = *cwd;
463 top->unremovable = NULL;
466 /* Push info about the current working directory (".") onto the
467 active directory stack. DIR is the ./-relative name through
468 which we've just `chdir'd to this directory. DIR_SB_FROM_PARENT
469 is the result of calling lstat on DIR from the parent of DIR. */
470 static void
471 AD_push (Dirstack_state *ds, char const *dir,
472 struct stat const *dir_sb_from_parent)
474 struct stat sb;
475 struct AD_ent *top;
477 push_dir (ds, dir);
479 if (lstat (".", &sb))
480 error (EXIT_FAILURE, errno,
481 _("cannot lstat `.' in %s"), quote (full_filename (".")));
483 if ( ! SAME_INODE (sb, *dir_sb_from_parent))
484 error (EXIT_FAILURE, errno,
485 _("%s changed dev/ino"), quote (full_filename (".")));
487 /* Extend the stack. */
488 obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
490 /* Fill in the new values. */
491 top = AD_stack_top (ds);
492 top->u.a.st_dev = sb.st_dev;
493 top->u.a.st_ino = sb.st_ino;
494 top->unremovable = NULL;
497 static int
498 AD_is_removable (Dirstack_state const *ds, char const *file)
500 struct AD_ent *top = AD_stack_top (ds);
501 return ! (top->unremovable && hash_lookup (top->unremovable, file));
504 /* A wrapper for readdir so that callers don't see entries for `.' or `..'. */
505 static struct dirent *
506 readdir_ignoring_dotdirs (DIR *dirp)
508 while (1)
510 struct dirent *dp = readdir (dirp);
511 if (dp == NULL || ! DOT_OR_DOTDOT (dp->d_name))
512 return dp;
516 /* Return nonzero if DIR is determined to be an empty directory
517 or if opendir or readdir fails. */
518 static bool
519 is_empty_dir (char const *dir)
521 DIR *dirp = opendir (dir);
522 struct dirent *dp;
523 int saved_errno;
525 if (dirp == NULL)
526 return false;
528 errno = 0;
529 dp = readdir_ignoring_dotdirs (dirp);
530 saved_errno = errno;
531 closedir (dirp);
532 if (dp != NULL)
533 return false;
534 return saved_errno == 0 ? true : false;
537 /* Prompt whether to remove FILENAME, if required via a combination of
538 the options specified by X and/or file attributes. If the file may
539 be removed, return RM_OK. If the user declines to remove the file,
540 return RM_USER_DECLINED. If not ignoring missing files and we
541 cannot lstat FILENAME, then return RM_ERROR.
543 Depending on MODE, ask whether to `descend into' or to `remove' the
544 directory FILENAME. MODE is ignored when FILENAME is not a directory.
545 Set *IS_EMPTY to T_YES if FILENAME is an empty directory, and it is
546 appropriate to try to remove it with rmdir (e.g. recursive mode).
547 Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR.
548 Set *IS_DIR to T_YES or T_NO if we happen to determine whether
549 FILENAME is a directory. */
550 static enum RM_status
551 prompt (Dirstack_state const *ds, char const *filename,
552 struct rm_options const *x, enum Prompt_action mode,
553 Ternary *is_dir, Ternary *is_empty)
555 int write_protected = 0;
556 *is_empty = T_UNKNOWN;
557 *is_dir = T_UNKNOWN;
559 if ((!x->ignore_missing_files && (x->interactive || x->stdin_tty)
560 && (write_protected = (euidaccess (filename, W_OK) && errno == EACCES)))
561 || x->interactive)
563 struct stat sbuf;
564 if (lstat (filename, &sbuf))
566 /* lstat failed. This happens e.g., with `rm '''. */
567 error (0, errno, _("cannot lstat %s"),
568 quote (full_filename (filename)));
569 return RM_ERROR;
572 if (S_ISDIR (sbuf.st_mode) && !x->recursive)
574 error (0, EISDIR, _("cannot remove directory %s"),
575 quote (full_filename (filename)));
576 return RM_ERROR;
579 /* Using permissions doesn't make sense for symlinks. */
580 if (S_ISLNK (sbuf.st_mode))
582 if ( ! x->interactive)
583 return RM_OK;
584 write_protected = 0;
587 /* Issue the prompt. */
589 char const *quoted_name = quote (full_filename (filename));
591 *is_dir = (S_ISDIR (sbuf.st_mode) ? T_YES : T_NO);
593 /* FIXME: use a variant of error (instead of fprintf) that doesn't
594 append a newline. Then we won't have to declare program_name in
595 this file. */
596 if (S_ISDIR (sbuf.st_mode)
597 && x->recursive
598 && mode == PA_DESCEND_INTO_DIR
599 && ((*is_empty = (is_empty_dir (filename) ? T_YES : T_NO))
600 == T_NO))
601 fprintf (stderr,
602 (write_protected
603 ? _("%s: descend into write-protected directory %s? ")
604 : _("%s: descend into directory %s? ")),
605 program_name, quoted_name);
606 else
608 /* TRANSLATORS: You may find it more convenient to translate
609 the equivalent of _("%s: remove %s (write-protected) %s? ").
610 It should avoid grammatical problems with the output
611 of file_type. */
612 fprintf (stderr,
613 (write_protected
614 ? _("%s: remove write-protected %s %s? ")
615 : _("%s: remove %s %s? ")),
616 program_name, file_type (&sbuf), quoted_name);
619 if (!yesno ())
620 return RM_USER_DECLINED;
623 return RM_OK;
626 #if HAVE_STRUCT_DIRENT_D_TYPE
627 # define DT_IS_DIR(D) ((D)->d_type == DT_DIR)
628 #else
629 /* Use this only if the member exists -- i.e., don't return 0. */
630 # define DT_IS_DIR(D) do_not_use_this_macro
631 #endif
633 #define DO_UNLINK(Filename, X) \
634 do \
636 if (unlink (Filename) == 0) \
638 if ((X)->verbose) \
639 printf (_("removed %s\n"), quote (full_filename (Filename))); \
640 return RM_OK; \
643 if (errno == ENOENT && (X)->ignore_missing_files) \
644 return RM_OK; \
646 while (0)
648 #define DO_RMDIR(Filename, X) \
649 do \
651 if (rmdir (Filename) == 0) \
653 if ((X)->verbose) \
654 printf (_("removed directory: %s\n"), \
655 quote (full_filename (Filename))); \
656 return RM_OK; \
659 if (errno == ENOENT && (X)->ignore_missing_files) \
660 return RM_OK; \
662 if (errno == ENOTEMPTY || errno == EEXIST) \
663 return RM_NONEMPTY_DIR; \
665 while (0)
667 /* Remove the file or directory specified by FILENAME.
668 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
669 But if FILENAME specifies a non-empty directory, return RM_NONEMPTY_DIR. */
671 static enum RM_status
672 remove_entry (Dirstack_state const *ds, char const *filename,
673 struct rm_options const *x, struct dirent const *dp)
675 Ternary is_dir;
676 Ternary is_empty_directory;
677 enum RM_status s = prompt (ds, filename, x, PA_DESCEND_INTO_DIR,
678 &is_dir, &is_empty_directory);
680 if (s != RM_OK)
681 return s;
683 /* Why bother with the following #if/#else block? Because on systems with
684 an unlink function that *can* unlink directories, we must determine the
685 type of each entry before removing it. Otherwise, we'd risk unlinking an
686 entire directory tree simply by unlinking a single directory; then all
687 the storage associated with that hierarchy would not be freed until the
688 next reboot. Not nice. To avoid that, on such slightly losing systems, we
689 need to call lstat to determine the type of each entry, and that represents
690 extra overhead that -- it turns out -- we can avoid on GNU-libc-based
691 systems, since there, unlink will never remove a directory. */
693 #if ROOT_CAN_UNLINK_DIRS
695 /* If we don't already know whether FILENAME is a directory, find out now.
696 Then, if it's a non-directory, we can use unlink on it. */
697 if (is_dir == T_UNKNOWN)
699 # if HAVE_STRUCT_DIRENT_D_TYPE
700 if (dp && dp->d_type != DT_UNKNOWN)
701 is_dir = DT_IS_DIR (dp) ? T_YES : T_NO;
702 else
703 # endif
705 struct stat sbuf;
706 if (lstat (filename, &sbuf))
708 if (errno == ENOENT && x->ignore_missing_files)
709 return RM_OK;
711 error (0, errno,
712 _("cannot lstat %s"), quote (full_filename (filename)));
713 return RM_ERROR;
716 is_dir = S_ISDIR (sbuf.st_mode) ? T_YES : T_NO;
720 if (is_dir == T_NO)
722 /* At this point, barring race conditions, FILENAME is known
723 to be a non-directory, so it's ok to try to unlink it. */
724 DO_UNLINK (filename, x);
726 /* unlink failed with some other error code. report it. */
727 error (0, errno, _("cannot remove %s"),
728 quote (full_filename (filename)));
729 return RM_ERROR;
732 if (! x->recursive)
734 error (0, EISDIR, _("cannot remove directory %s"),
735 quote (full_filename (filename)));
736 return RM_ERROR;
739 if (is_empty_directory == T_YES)
741 DO_RMDIR (filename, x);
742 /* Don't diagnose any failure here.
743 It'll be detected when the caller tries another way. */
747 #else /* ! ROOT_CAN_UNLINK_DIRS */
749 if (is_dir == T_YES && ! x->recursive)
751 error (0, EISDIR, _("cannot remove directory %s"),
752 quote (full_filename (filename)));
753 return RM_ERROR;
756 /* is_empty_directory is set iff it's ok to use rmdir.
757 Note that it's set only in interactive mode -- in which case it's
758 an optimization that arranges so that the user is asked just
759 once whether to remove the directory. */
760 if (is_empty_directory == T_YES)
761 DO_RMDIR (filename, x);
763 /* If we happen to know that FILENAME is a directory, return now
764 and let the caller remove it -- this saves the overhead of a failed
765 unlink call. If FILENAME is a command-line argument, then dp is NULL,
766 so we'll first try to unlink it. Using unlink here is ok, because it
767 cannot remove a directory. */
768 if ((dp && DT_IS_DIR (dp)) || is_dir == T_YES)
769 return RM_NONEMPTY_DIR;
771 DO_UNLINK (filename, x);
773 /* Accept either EISDIR or EPERM as an indication that FILENAME may be
774 a directory. POSIX says that unlink must set errno to EPERM when it
775 fails to remove a directory, while Linux-2.4.18 sets it to EISDIR. */
776 if ((errno != EISDIR && errno != EPERM) || ! x->recursive)
778 /* some other error code. Report it and fail.
779 Likewise, if we're trying to remove a directory without
780 the --recursive option. */
781 error (0, errno, _("cannot remove %s"),
782 quote (full_filename (filename)));
783 return RM_ERROR;
785 #endif
787 return RM_NONEMPTY_DIR;
790 /* Remove entries in `.', the current working directory (cwd).
791 Upon finding a directory that is both non-empty and that can be chdir'd
792 into, return RM_OK and set *SUBDIR and fill in SUBDIR_SB, where
793 SUBDIR is the malloc'd name of the subdirectory if the chdir succeeded,
794 NULL otherwise (e.g., if opendir failed or if there was no subdirectory).
795 Likewise, SUBDIR_SB is the result of calling lstat on SUBDIR.
796 Return RM_OK if all entries are removed. Return RM_ERROR if any
797 entry cannot be removed. Otherwise, return RM_USER_DECLINED if
798 the user declines to remove at least one entry. Remove as much as
799 possible, continuing even if we fail to remove some entries. */
800 static enum RM_status
801 remove_cwd_entries (Dirstack_state *ds, char **subdir, struct stat *subdir_sb,
802 struct rm_options const *x)
804 DIR *dirp = opendir (".");
805 struct AD_ent *top = AD_stack_top (ds);
806 enum RM_status status = top->status;
807 bool need_rewinddir = false;
809 assert (VALID_STATUS (status));
810 *subdir = NULL;
812 if (dirp == NULL)
814 if (errno != ENOENT || !x->ignore_missing_files)
816 error (0, errno, _("cannot open directory %s"),
817 quote (full_filename (".")));
818 return RM_ERROR;
822 while (1)
824 struct dirent *dp;
825 enum RM_status tmp_status;
826 const char *f;
828 /* Set errno to zero so we can distinguish between a readdir failure
829 and when readdir simply finds that there are no more entries. */
830 errno = 0;
831 if ((dp = readdir_ignoring_dotdirs (dirp)) == NULL)
833 if (errno)
835 /* Save/restore errno across closedir call. */
836 int e = errno;
837 closedir (dirp);
838 errno = e;
840 /* Arrange to give a diagnostic after exiting this loop. */
841 dirp = NULL;
843 else if (need_rewinddir)
845 /* On buggy systems, call rewinddir if we've called unlink
846 or rmdir since the opendir or a previous rewinddir. */
847 rewinddir (dirp);
848 need_rewinddir = false;
849 continue;
851 break;
854 f = dp->d_name;
856 /* Skip files we've already tried/failed to remove. */
857 if ( ! AD_is_removable (ds, f))
858 continue;
860 /* Pass dp->d_type info to remove_entry so the non-glibc
861 case can decide whether to use unlink or chdir.
862 Systems without the d_type member will have to endure
863 the performance hit of first calling lstat F. */
864 tmp_status = remove_entry (ds, f, x, dp);
865 switch (tmp_status)
867 case RM_OK:
868 /* On buggy systems, record the fact that we've just
869 removed a directory entry. */
870 need_rewinddir = ! HAVE_WORKING_READDIR;
871 break;
873 case RM_ERROR:
874 case RM_USER_DECLINED:
875 AD_mark_as_unremovable (ds, f);
876 UPDATE_STATUS (status, tmp_status);
877 break;
879 case RM_NONEMPTY_DIR:
881 /* Save a copy of errno, in case the preceding unlink (from
882 remove_entry's DO_UNLINK) of a non-directory failed due
883 to EPERM. */
884 int saved_errno = errno;
886 /* Record dev/ino of F so that we can compare
887 that with dev/ino of `.' after the chdir.
888 This dev/ino pair is also used in cycle detection. */
889 if (lstat (f, subdir_sb))
890 error (EXIT_FAILURE, errno, _("cannot lstat %s"),
891 quote (full_filename (f)));
893 if (chdir (f))
895 /* It is much more common that we reach this point for an
896 inaccessible directory. Hence the second diagnostic, below.
897 However it is also possible that F is a non-directory.
898 That can happen when we use the `! ROOT_CAN_UNLINK_DIRS'
899 block of code and when DO_UNLINK fails due to EPERM.
900 In that case, give a better diagnostic. */
901 if (errno == ENOTDIR)
902 error (0, saved_errno, _("cannot remove %s"),
903 quote (full_filename (f)));
904 else
905 error (0, errno, _("cannot chdir from %s to %s"),
906 quote_n (0, full_filename (".")), quote_n (1, f));
907 AD_mark_as_unremovable (ds, f);
908 status = RM_ERROR;
909 break;
911 if (cycle_check (&ds->cycle_check_state, subdir_sb))
913 error (0, 0, _("\
914 WARNING: Circular directory structure.\n\
915 This almost certainly means that you have a corrupted file system.\n\
916 NOTIFY YOUR SYSTEM MANAGER.\n\
917 The following directory is part of the cycle:\n %s\n"),
918 quote (full_filename (".")));
919 longjmp (ds->current_arg_jumpbuf, 1);
922 *subdir = xstrdup (f);
923 break;
927 /* Record status for this directory. */
928 UPDATE_STATUS (top->status, status);
930 if (*subdir)
931 break;
934 if (dirp == NULL || CLOSEDIR (dirp) != 0)
936 /* Note that this diagnostic serves for both readdir
937 and closedir failures. */
938 error (0, errno, _("reading directory %s"), quote (full_filename (".")));
939 status = RM_ERROR;
942 return status;
945 /* Do this after each call to AD_push or AD_push_initial.
946 Because the status = RM_OK bit is too remove-specific to
947 go into the general-purpose AD_* package. */
948 #define AD_INIT_OTHER_MEMBERS() \
949 do \
951 AD_stack_top(ds)->status = RM_OK; \
953 while (0)
955 /* Remove the hierarchy rooted at DIR.
956 Do that by changing into DIR, then removing its contents, then
957 returning to the original working directory and removing DIR itself.
958 Don't use recursion. Be careful when using chdir ".." that we
959 return to the same directory from which we came, if necessary.
960 Return 1 for success, 0 if some file cannot be removed or if
961 a chdir fails.
962 If the working directory cannot be restored, exit immediately. */
964 static enum RM_status
965 remove_dir (Dirstack_state *ds, char const *dir, struct saved_cwd **cwd_state,
966 struct rm_options const *x)
968 enum RM_status status;
969 struct stat dir_sb;
971 /* Save any errno (from caller's failed remove_entry call), in case DIR
972 is not a directory, so that we can give a reasonable diagnostic. */
973 int saved_errno = errno;
975 if (*cwd_state == NULL)
977 *cwd_state = XMALLOC (struct saved_cwd, 1);
978 if (save_cwd (*cwd_state))
980 error (0, errno, _("cannot get current directory"));
981 return RM_ERROR;
983 AD_push_initial (ds, *cwd_state);
984 AD_INIT_OTHER_MEMBERS ();
987 /* There is a race condition in that an attacker could replace the nonempty
988 directory, DIR, with a symlink between the preceding call to rmdir
989 (in our caller) and the chdir below. However, the following lstat,
990 along with the `stat (".",...' and dev/ino comparison in AD_push
991 ensure that we detect it and fail. */
993 if (lstat (dir, &dir_sb))
995 error (0, errno,
996 _("cannot lstat %s"), quote (full_filename (dir)));
997 return RM_ERROR;
1000 if (chdir (dir))
1002 if (! S_ISDIR (dir_sb.st_mode))
1004 /* This happens on Linux-2.4.18 when a non-privileged user tries
1005 to delete a file that is owned by another user in a directory
1006 like /tmp that has the S_ISVTX flag set. */
1007 assert (saved_errno == EPERM);
1008 error (0, saved_errno,
1009 _("cannot remove %s"), quote (full_filename (dir)));
1011 else
1013 error (0, errno,
1014 _("cannot chdir from %s to %s"),
1015 quote_n (0, full_filename (".")), quote_n (1, dir));
1017 return RM_ERROR;
1020 if (ROOT_DEV_INO_CHECK (x->root_dev_ino, &dir_sb))
1022 ROOT_DEV_INO_WARN (full_filename (dir));
1023 return 1;
1026 AD_push (ds, dir, &dir_sb);
1027 AD_INIT_OTHER_MEMBERS ();
1029 status = RM_OK;
1031 while (1)
1033 char *subdir = NULL;
1034 struct stat subdir_sb;
1035 enum RM_status tmp_status = remove_cwd_entries (ds,
1036 &subdir, &subdir_sb, x);
1037 if (tmp_status != RM_OK)
1039 UPDATE_STATUS (status, tmp_status);
1040 AD_mark_current_as_unremovable (ds);
1042 if (subdir)
1044 AD_push (ds, subdir, &subdir_sb);
1045 AD_INIT_OTHER_MEMBERS ();
1047 free (subdir);
1048 continue;
1051 /* Execution reaches this point when we've removed the last
1052 removable entry from the current directory. */
1054 char *d = AD_pop_and_chdir (ds);
1056 /* Try to remove D only if remove_cwd_entries succeeded. */
1057 if (tmp_status == RM_OK)
1059 /* This does a little more work than necessary when it actually
1060 prompts the user. E.g., we already know that D is a directory
1061 and that it's almost certainly empty, yet we lstat it.
1062 But that's no big deal since we're interactive. */
1063 Ternary is_dir;
1064 Ternary is_empty;
1065 enum RM_status s = prompt (ds, d, x, PA_REMOVE_DIR,
1066 &is_dir, &is_empty);
1068 if (s != RM_OK)
1070 free (d);
1071 return s;
1074 if (rmdir (d) == 0)
1076 if (x->verbose)
1077 printf (_("removed directory: %s\n"),
1078 quote (full_filename (d)));
1080 else
1082 error (0, errno, _("cannot remove directory %s"),
1083 quote (full_filename (d)));
1084 AD_mark_as_unremovable (ds, d);
1085 status = RM_ERROR;
1086 UPDATE_STATUS (AD_stack_top(ds)->status, status);
1090 free (d);
1092 if (AD_stack_height (ds) == 1)
1093 break;
1097 return status;
1100 /* Remove the file or directory specified by FILENAME.
1101 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
1102 On input, the first time this function is called, CWD_STATE should be
1103 the address of a NULL pointer. Do not modify it for any subsequent calls.
1104 On output, it is either that same NULL pointer or the address of
1105 a malloc'd `struct saved_cwd' that may be freed. */
1107 static enum RM_status
1108 rm_1 (Dirstack_state *ds, char const *filename,
1109 struct rm_options const *x, struct saved_cwd **cwd_state)
1111 char *base = base_name (filename);
1112 enum RM_status status;
1114 if (DOT_OR_DOTDOT (base))
1116 error (0, 0, _("cannot remove `.' or `..'"));
1117 return RM_ERROR;
1120 status = remove_entry (ds, filename, x, NULL);
1121 if (status != RM_NONEMPTY_DIR)
1122 return status;
1124 return remove_dir (ds, filename, cwd_state, x);
1127 /* Remove all files and/or directories specified by N_FILES and FILE.
1128 Apply the options in X. */
1129 enum RM_status
1130 rm (size_t n_files, char const *const *file, struct rm_options const *x)
1132 struct saved_cwd *cwd_state = NULL;
1133 Dirstack_state *ds;
1135 /* Put the following two variables in static storage, so they can't
1136 be clobbered by the potential longjmp into this function. */
1137 static enum RM_status status = RM_OK;
1138 static size_t i;
1140 ds = ds_init ();
1142 for (i = 0; i < n_files; i++)
1144 enum RM_status s;
1145 cycle_check_init (&ds->cycle_check_state);
1146 /* In the event that rm_1->remove_dir->remove_cwd_entries detects
1147 a directory cycle, arrange to fail, give up on this FILE, but
1148 continue on with any other arguments. */
1149 if (setjmp (ds->current_arg_jumpbuf))
1150 s = RM_ERROR;
1151 else
1152 s = rm_1 (ds, file[i], x, &cwd_state);
1153 assert (VALID_STATUS (s));
1154 UPDATE_STATUS (status, s);
1157 ds_free (ds);
1159 XFREE (cwd_state);
1161 return status;