*** empty log message ***
[coreutils.git] / src / remove.c
blob59368ac09abad70048256d43439cc92dd372134b
1 /* remove.c -- core functions for removing files and directories
2 Copyright (C) 88, 90, 91, 1994-2002 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 by Jim Meyering. */
20 #ifdef _AIX
21 #pragma alloca
22 #endif
24 #include <config.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <assert.h>
29 #include "save-cwd.h"
30 #include "system.h"
31 #include "dirname.h"
32 #include "error.h"
33 #include "file-type.h"
34 #include "hash.h"
35 #include "hash-pjw.h"
36 #include "obstack.h"
37 #include "quote.h"
38 #include "remove.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 #ifndef PARAMS
49 # if defined (__GNUC__) || __STDC__
50 # define PARAMS(args) args
51 # else
52 # define PARAMS(args) ()
53 # endif
54 #endif
56 /* FIXME: if possible, use autoconf... */
57 #ifdef __GLIBC__
58 # define ROOT_CAN_UNLINK_DIRS 0
59 #else
60 # define ROOT_CAN_UNLINK_DIRS 1
61 #endif
63 enum Ternary
65 T_UNKNOWN = 2,
66 T_NO,
67 T_YES
69 typedef enum Ternary Ternary;
71 /* The prompt function may be called twice a given directory.
72 The first time, we ask whether to descend into it, and the
73 second time, we ask whether to remove it. */
74 enum Prompt_action
76 PA_DESCEND_INTO_DIR = 2,
77 PA_REMOVE_DIR
80 /* On systems with an lstat function that accepts the empty string,
81 arrange to make lstat calls go through the wrapper function. */
82 #if HAVE_LSTAT_EMPTY_STRING_BUG
83 int rpl_lstat PARAMS((const char *, struct stat *));
84 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
85 #endif
87 #ifdef D_INO_IN_DIRENT
88 # define D_INO(dp) ((dp)->d_ino)
89 # define ENABLE_CYCLE_CHECK
90 #else
91 /* Some systems don't have inodes, so fake them to avoid lots of ifdefs. */
92 # define D_INO(dp) 1
93 #endif
95 #if !defined S_ISLNK
96 # define S_ISLNK(Mode) 0
97 #endif
99 /* Initial capacity of per-directory hash table of entries that have
100 been processed but not been deleted. */
101 #define HT_UNREMOVABLE_INITIAL_CAPACITY 13
103 /* An entry in the active directory stack.
104 Each entry corresponds to an `active' directory. */
105 struct AD_ent
107 /* For a given active directory, this is the set of names of
108 entries in that directory that could/should not be removed.
109 For example, `.' and `..', as well as files/dirs for which
110 unlink/rmdir failed e.g., due to access restrictions. */
111 Hash_table *unremovable;
113 /* Record the status for a given active directory; we need to know
114 whether an entry was not removed, either because of an error or
115 because the user declined. */
116 enum RM_status status;
118 union
120 /* The directory's dev/ino. Used to ensure that `chdir some-subdir', then
121 `chdir ..' takes us back to the same directory from which we started).
122 (valid for all but the bottommost entry on the stack. */
123 struct dev_ino a;
125 /* Enough information to restore the initial working directory.
126 (valid only for the bottommost entry on the stack) */
127 struct saved_cwd saved_cwd;
128 } u;
131 int euidaccess ();
132 int yesno ();
134 extern char *program_name;
136 /* The name of the directory (starting with and relative to a command
137 line argument) being processed. When a subdirectory is entered, a new
138 component is appended (pushed). When RM chdir's out of a directory,
139 the top component is removed (popped). This is used to form a full
140 file name when necessary. */
141 static struct obstack dir_stack;
143 /* Stack of lengths of directory names (including trailing slash)
144 appended to dir_stack. We have to have a separate stack of lengths
145 (rather than just popping back to previous slash) because the first
146 element pushed onto the dir stack may contain slashes. */
147 static struct obstack len_stack;
149 /* Stack of active directory entries.
150 The first `active' directory is the initial working directory.
151 Additional active dirs are pushed onto the stack as rm `chdir's
152 into each nonempty directory it must remove. When rm has finished
153 removing the hierarchy under a directory, it pops the active dir stack. */
154 static struct obstack Active_dir;
156 static void
157 hash_freer (void *x)
159 free (x);
162 static bool
163 hash_compare_strings (void const *x, void const *y)
165 return STREQ (x, y) ? true : false;
168 static inline void
169 push_dir (const char *dir_name)
171 size_t len;
173 len = strlen (dir_name);
175 /* Append the string onto the stack. */
176 obstack_grow (&dir_stack, dir_name, len);
178 /* Append a trailing slash. */
179 obstack_1grow (&dir_stack, '/');
181 /* Add one for the slash. */
182 ++len;
184 /* Push the length (including slash) onto its stack. */
185 obstack_grow (&len_stack, &len, sizeof (len));
188 /* Return the entry name of the directory on the top of the stack
189 in malloc'd storage. */
190 static inline char *
191 top_dir (void)
193 int n_lengths = obstack_object_size (&len_stack) / sizeof (size_t);
194 size_t *length = (size_t *) obstack_base (&len_stack);
195 size_t top_len = length[n_lengths - 1];
196 char const *p = obstack_next_free (&dir_stack) - top_len;
197 char *q = xmalloc (top_len);
198 memcpy (q, p, top_len - 1);
199 q[top_len - 1] = 0;
200 return q;
203 static inline void
204 pop_dir (void)
206 int n_lengths = obstack_object_size (&len_stack) / sizeof (size_t);
207 size_t *length = (size_t *) obstack_base (&len_stack);
208 size_t top_len;
210 assert (n_lengths > 0);
211 top_len = length[n_lengths - 1];
212 assert (top_len >= 2);
214 /* Pop off the specified length of pathname. */
215 assert (obstack_object_size (&dir_stack) >= top_len);
216 obstack_blank (&dir_stack, -top_len);
218 /* Pop the length stack, too. */
219 assert (obstack_object_size (&len_stack) >= sizeof (size_t));
220 obstack_blank (&len_stack, (int) -(sizeof (size_t)));
223 /* Copy the SRC_LEN bytes of data beginning at SRC into the DST_LEN-byte
224 buffer, DST, so that the last source byte is at the end of the destination
225 buffer. If SRC_LEN is longer than DST_LEN, then set *TRUNCATED to non-zero.
226 Set *RESULT to point to the beginning of (the portion of) the source data
227 in DST. Return the number of bytes remaining in the destination buffer. */
229 static size_t
230 right_justify (char *dst, size_t dst_len, const char *src, size_t src_len,
231 char **result, int *truncated)
233 const char *sp;
234 char *dp;
236 if (src_len <= dst_len)
238 sp = src;
239 dp = dst + (dst_len - src_len);
240 *truncated = 0;
242 else
244 sp = src + (src_len - dst_len);
245 dp = dst;
246 src_len = dst_len;
247 *truncated = 1;
250 *result = memcpy (dp, sp, src_len);
251 return dst_len - src_len;
254 /* Using the global directory name obstack, create the full path to FILENAME.
255 Return it in sometimes-realloc'd space that should not be freed by the
256 caller. Realloc as necessary. If realloc fails, use a static buffer
257 and put as long a suffix in that buffer as possible. */
259 static char *
260 full_filename (const char *filename)
262 static char *buf = NULL;
263 static size_t n_allocated = 0;
265 int dir_len = obstack_object_size (&dir_stack);
266 char *dir_name = (char *) obstack_base (&dir_stack);
267 size_t n_bytes_needed;
268 size_t filename_len;
270 filename_len = strlen (filename);
271 n_bytes_needed = dir_len + filename_len + 1;
273 if (n_bytes_needed > n_allocated)
275 /* This code requires that realloc accept NULL as the first arg.
276 This function must not use xrealloc. Otherwise, an out-of-memory
277 error involving a file name to be expanded here wouldn't ever
278 be issued. Use realloc and fall back on using a static buffer
279 if memory allocation fails. */
280 buf = realloc (buf, n_bytes_needed);
281 n_allocated = n_bytes_needed;
283 if (buf == NULL)
285 #define SBUF_SIZE 512
286 #define ELLIPSES_PREFIX "[...]"
287 static char static_buf[SBUF_SIZE];
288 int truncated;
289 size_t len;
290 char *p;
292 len = right_justify (static_buf, SBUF_SIZE, filename,
293 filename_len + 1, &p, &truncated);
294 right_justify (static_buf, len, dir_name, dir_len, &p, &truncated);
295 if (truncated)
297 memcpy (static_buf, ELLIPSES_PREFIX,
298 sizeof (ELLIPSES_PREFIX) - 1);
300 return p;
304 /* Copy directory part, including trailing slash, and then
305 append the filename part, including a trailing zero byte. */
306 memcpy (mempcpy (buf, dir_name, dir_len), filename, filename_len + 1);
308 assert (strlen (buf) + 1 == n_bytes_needed);
310 return buf;
313 static size_t
314 AD_stack_height (void)
316 return obstack_object_size (&Active_dir) / sizeof (struct AD_ent);
319 static struct AD_ent *
320 AD_stack_top (void)
322 return (struct AD_ent *)
323 ((char *) obstack_next_free (&Active_dir) - sizeof (struct AD_ent));
326 static void
327 AD_stack_pop (void)
329 /* operate on Active_dir. pop and free top entry */
330 struct AD_ent *top = AD_stack_top ();
331 if (top->unremovable)
332 hash_free (top->unremovable);
333 obstack_blank (&Active_dir, -sizeof (struct AD_ent));
334 pop_dir ();
337 /* chdir `up' one level.
338 Whenever using chdir '..', verify that the post-chdir
339 dev/ino numbers for `.' match the saved ones.
340 Return the name (in malloc'd storage) of the
341 directory (usually now empty) from which we're coming. */
342 static char *
343 AD_pop_and_chdir (void)
345 /* Get the name of the current directory from the top of the stack. */
346 char *dir = top_dir ();
347 enum RM_status old_status = AD_stack_top()->status;
348 struct stat sb;
349 struct AD_ent *top;
351 AD_stack_pop ();
353 /* Propagate any failure to parent. */
354 UPDATE_STATUS (AD_stack_top()->status, old_status);
356 assert (AD_stack_height ());
358 top = AD_stack_top ();
359 if (1 < AD_stack_height ())
361 /* We can give a better diagnostic here, since the target is relative. */
362 if (chdir (".."))
364 error (EXIT_FAILURE, errno,
365 _("cannot chdir from %s to .."),
366 quote (full_filename (".")));
369 else
371 if (restore_cwd (&top->u.saved_cwd, NULL, NULL))
372 exit (EXIT_FAILURE);
375 if (lstat (".", &sb))
376 error (EXIT_FAILURE, errno,
377 _("cannot lstat `.' in %s"), quote (full_filename (".")));
379 if (1 < AD_stack_height ())
381 /* Ensure that post-chdir dev/ino match the stored ones. */
382 if ( ! SAME_INODE (sb, top->u.a))
383 error (EXIT_FAILURE, 0,
384 _("%s changed dev/ino"), quote (full_filename (".")));
387 return dir;
390 /* Initialize *HT if it is NULL.
391 Insert FILENAME into HT. */
392 static void
393 AD_mark_helper (Hash_table **ht, char const *filename)
395 if (*ht == NULL)
396 *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw,
397 hash_compare_strings, hash_freer);
398 if (*ht == NULL)
399 xalloc_die ();
400 if (! hash_insert (*ht, filename))
401 xalloc_die ();
404 /* Mark FILENAME (in current directory) as unremovable. */
405 static void
406 AD_mark_as_unremovable (char const *filename)
408 AD_mark_helper (&AD_stack_top()->unremovable, xstrdup (filename));
411 /* Mark the current directory as unremovable. I.e., mark the entry
412 in the parent directory corresponding to `.'.
413 This happens e.g., when an opendir fails and the only name
414 the caller has conveniently at hand is `.'. */
415 static void
416 AD_mark_current_as_unremovable (void)
418 struct AD_ent *top = AD_stack_top ();
419 const char *curr = top_dir ();
421 assert (1 < AD_stack_height ());
423 --top;
424 AD_mark_helper (&top->unremovable, curr);
427 /* Push the initial cwd info onto the stack.
428 This will always be the bottommost entry on the stack. */
429 static void
430 AD_push_initial (struct saved_cwd const *cwd)
432 struct AD_ent *top;
434 /* Extend the stack. */
435 obstack_blank (&Active_dir, sizeof (struct AD_ent));
437 /* Fill in the new values. */
438 top = AD_stack_top ();
439 top->u.saved_cwd = *cwd;
440 top->status = RM_OK;
441 top->unremovable = NULL;
444 /* Push info about the current working directory (".") onto the
445 active directory stack. DIR is the ./-relative name through
446 which we've just `chdir'd to this directory. DIR_SB_FROM_PARENT
447 is the result of calling lstat on DIR from the parent of DIR. */
448 static void
449 AD_push (char const *dir, struct stat const *dir_sb_from_parent)
451 struct stat sb;
452 struct AD_ent *top;
454 push_dir (dir);
456 if (lstat (".", &sb))
457 error (EXIT_FAILURE, errno,
458 _("cannot lstat `.' in %s"), quote (full_filename (".")));
460 if ( ! SAME_INODE (sb, *dir_sb_from_parent))
461 error (EXIT_FAILURE, errno,
462 _("%s changed dev/ino"), quote (full_filename (".")));
464 /* Extend the stack. */
465 obstack_blank (&Active_dir, sizeof (struct AD_ent));
467 /* Fill in the new values. */
468 top = AD_stack_top ();
469 top->u.a.st_dev = sb.st_dev;
470 top->u.a.st_ino = sb.st_ino;
471 top->status = RM_OK;
472 top->unremovable = NULL;
475 static int
476 AD_is_removable (char const *file)
478 struct AD_ent *top = AD_stack_top ();
479 return ! (top->unremovable && hash_lookup (top->unremovable, file));
482 static inline bool
483 is_power_of_two (unsigned int i)
485 return (i & (i - 1)) == 0;
488 static void
489 cycle_check (struct stat const *sb)
491 #ifdef ENABLE_CYCLE_CHECK
492 /* If there is a directory cycle, detect it (lazily) and die. */
493 static struct dev_ino dir_cycle_detect_dev_ino;
494 static unsigned int chdir_counter;
496 /* If the current directory ever happens to be the same
497 as the one we last recorded for the cycle detection,
498 then it's obviously part of a cycle. */
499 if (chdir_counter && SAME_INODE (*sb, dir_cycle_detect_dev_ino))
501 error (0, 0, _("\
502 WARNING: Circular directory structure.\n\
503 This almost certainly means that you have a corrupted file system.\n\
504 NOTIFY YOUR SYSTEM MANAGER.\n\
505 The following directory is part of the cycle:\n %s\n"),
506 quote (full_filename (".")));
507 exit (EXIT_FAILURE);
510 /* If the number of `descending' chdir calls is a power of two,
511 record the dev/ino of the current directory. */
512 if (is_power_of_two (++chdir_counter))
514 dir_cycle_detect_dev_ino.st_dev = sb->st_dev;
515 dir_cycle_detect_dev_ino.st_ino = sb->st_ino;
517 #endif
520 static bool
521 is_empty_dir (char const *dir)
523 DIR *dirp = opendir (dir);
524 if (dirp == NULL)
525 return false;
527 while (1)
529 struct dirent *dp = readdir (dirp);
530 const char *f;
532 if (dp == NULL)
533 return true;
535 f = dp->d_name;
536 if ( ! DOT_OR_DOTDOT (f))
537 return false;
541 /* Prompt whether to remove FILENAME, if required via a combination of
542 the options specified by X and/or file attributes. If the file may
543 be removed, return RM_OK. If the user declines to remove the file,
544 return RM_USER_DECLINED. If not ignoring missing files and we
545 cannot lstat FILENAME, then return RM_ERROR.
547 Depending on MODE, ask whether to `descend into' or to `remove' the
548 directory FILENAME. MODE is ignored when FILENAME is not a directory.
549 Set *IS_EMPTY to T_YES if FILENAME is an empty directory, and it is
550 appropriate to try to remove it with rmdir (e.g. recursive mode).
551 Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR.
552 Set *IS_DIR to T_YES or T_NO if we happen to determine whether
553 FILENAME is a directory. */
554 static enum RM_status
555 prompt (char const *filename, struct rm_options const *x,
556 enum Prompt_action mode, Ternary *is_dir, Ternary *is_empty)
558 int write_protected = 0;
559 *is_empty = T_UNKNOWN;
560 *is_dir = T_UNKNOWN;
562 if ((!x->ignore_missing_files && (x->interactive || x->stdin_tty)
563 && (write_protected = (euidaccess (filename, W_OK) && errno == EACCES)))
564 || x->interactive)
566 struct stat sbuf;
567 if (lstat (filename, &sbuf))
569 /* lstat failed. This happens e.g., with `rm '''. */
570 error (0, errno, _("cannot lstat %s"),
571 quote (full_filename (filename)));
572 return RM_ERROR;
575 /* Using permissions doesn't make sense for symlinks. */
576 if (S_ISLNK (sbuf.st_mode))
578 if ( ! x->interactive)
579 return RM_OK;
580 write_protected = 0;
583 /* Issue the prompt. */
585 char const *quoted_name = quote (full_filename (filename));
587 *is_dir = (S_ISDIR (sbuf.st_mode) ? T_YES : T_NO);
589 /* FIXME: use a variant of error (instead of fprintf) that doesn't
590 append a newline. Then we won't have to declare program_name in
591 this file. */
592 if (S_ISDIR (sbuf.st_mode)
593 && x->recursive
594 && mode == PA_DESCEND_INTO_DIR
595 && ((*is_empty = (is_empty_dir (filename) ? T_YES : T_NO))
596 == T_NO))
597 fprintf (stderr,
598 (write_protected
599 ? _("%s: descend into write-protected directory %s? ")
600 : _("%s: descend into directory %s? ")),
601 program_name, quoted_name);
602 else
604 /* TRANSLATORS: You may find it more convenient to translate
605 the equivalent of _("%1$s: %3$s is write-protected and is
606 of type `%2$s'. Remove it? "). This is more verbose than
607 the original but it should avoid grammatical problems with
608 the output of file_type. */
609 fprintf (stderr,
610 (write_protected
611 ? _("%s: remove write-protected %s %s? ")
612 : _("%s: remove %s %s? ")),
613 program_name, file_type (&sbuf), quoted_name);
616 if (!yesno ())
617 return RM_USER_DECLINED;
620 return RM_OK;
623 #if HAVE_STRUCT_DIRENT_D_TYPE
624 # define DT_IS_DIR(D) ((D)->d_type == DT_DIR)
625 #else
626 /* Use this only if the member exists -- i.e., don't return 0. */
627 # define DT_IS_DIR(D) do_not_use_this_macro
628 #endif
630 #define DO_UNLINK(Filename, X) \
631 do \
633 if (unlink (Filename) == 0) \
635 if ((X)->verbose) \
636 printf (_("removed %s\n"), quote (full_filename (Filename))); \
637 return RM_OK; \
640 if (errno == ENOENT && (X)->ignore_missing_files) \
641 return RM_OK; \
643 while (0)
645 #define DO_RMDIR(Filename, X) \
646 do \
648 if (rmdir (Filename) == 0) \
650 if ((X)->verbose) \
651 printf (_("removed directory: %s\n"), \
652 quote (full_filename (Filename))); \
653 return RM_OK; \
656 if (errno == ENOENT && (X)->ignore_missing_files) \
657 return RM_OK; \
659 if (errno == ENOTEMPTY || errno == EEXIST) \
660 return RM_NONEMPTY_DIR; \
662 while (0)
664 /* Remove the file or directory specified by FILENAME.
665 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
666 But if FILENAME specifies a non-empty directory, return RM_NONEMPTY_DIR. */
668 static enum RM_status
669 remove_entry (char const *filename, struct rm_options const *x,
670 struct dirent const *dp)
672 Ternary is_dir;
673 Ternary is_empty_directory;
674 enum RM_status s = prompt (filename, x, PA_DESCEND_INTO_DIR,
675 &is_dir, &is_empty_directory);
677 if (s != RM_OK)
678 return s;
680 /* Why bother with the following #if/#else block? Because on systems with
681 an unlink function that *can* unlink directories, we must determine the
682 type of each entry before removing it. Otherwise, we'd risk unlinking an
683 entire directory tree simply by unlinking a single directory; then all
684 the storage associated with that hierarchy would not be freed until the
685 next reboot. Not nice. To avoid that, on such slightly losing systems, we
686 need to call lstat to determine the type of each entry, and that represents
687 extra overhead that -- it turns out -- we can avoid on GNU-libc-based
688 systems, since there, unlink will never remove a directory. */
690 #if ROOT_CAN_UNLINK_DIRS
692 /* If we don't already know whether FILENAME is a directory, find out now.
693 Then, if it's a non-directory, we can use unlink on it. */
694 if (is_dir == T_UNKNOWN)
696 # if HAVE_STRUCT_DIRENT_D_TYPE
697 if (dp)
698 is_dir = DT_IS_DIR (dp) ? T_YES : T_NO;
699 else
700 # endif
702 struct stat sbuf;
703 if (lstat (filename, &sbuf))
705 if (errno == ENOENT && x->ignore_missing_files)
706 return RM_OK;
708 error (0, errno,
709 _("cannot lstat %s"), quote (full_filename (filename)));
710 return RM_ERROR;
713 is_dir = S_ISDIR (sbuf.st_mode) ? T_YES : T_NO;
717 if (is_dir == T_NO)
719 /* At this point, barring race conditions, FILENAME is known
720 to be a non-directory, so it's ok to try to unlink it. */
721 DO_UNLINK (filename, x);
723 /* unlink failed with some other error code. report it. */
724 error (0, errno, _("cannot remove %s"),
725 quote (full_filename (filename)));
726 return RM_ERROR;
729 if (! x->recursive)
731 error (0, EISDIR, _("cannot remove directory %s"),
732 quote (full_filename (filename)));
733 return RM_ERROR;
736 if (is_empty_directory == T_YES)
738 DO_RMDIR (filename, x);
739 /* Don't diagnose any failure here.
740 It'll be detected when the caller tries another way. */
744 #else
746 /* is_empty_directory is set iff it's ok to use rmdir.
747 Note that it's set only in interactive mode -- in which case it's
748 an optimization that arranges so that the user is asked just
749 once whether to remove the directory. */
750 if (is_empty_directory == T_YES)
751 DO_RMDIR (filename, x);
753 /* If we happen to know that FILENAME is a directory, return now
754 and let the caller remove it -- this saves the overhead of a failed
755 unlink call. If FILENAME is a command-line argument, then dp is NULL,
756 so we'll first try to unlink it. Using unlink here is ok, because it
757 cannot remove a directory. */
758 if ((dp && DT_IS_DIR (dp)) || is_dir == T_YES)
759 return RM_NONEMPTY_DIR;
761 DO_UNLINK (filename, x);
763 /* Accept either EISDIR or EPERM as an indication that FILENAME may be
764 a directory. POSIX says that unlink must set errno to EPERM when it
765 fails to remove a directory, while Linux-2.4.18 sets it to EISDIR. */
766 if ((errno != EISDIR && errno != EPERM) || ! x->recursive)
768 /* some other error code. Report it and fail.
769 Likewise, if we're trying to remove a directory without
770 the --recursive option. */
771 error (0, errno, _("cannot remove %s"),
772 quote (full_filename (filename)));
773 return RM_ERROR;
775 #endif
777 return RM_NONEMPTY_DIR;
780 /* Remove entries in `.', the current working directory (cwd).
781 Upon finding a directory that is both non-empty and that can be chdir'd
782 into, return zero and set *SUBDIR and fill in SUBDIR_SB, where
783 SUBDIR is the malloc'd name of the subdirectory if the chdir succeeded,
784 NULL otherwise (e.g., if opendir failed or if there was no subdirectory).
785 Likewise, SUBDIR_SB is the result of calling lstat on SUBDIR.
786 Return RM_OK if all entries are removed. Remove RM_ERROR if any
787 entry cannot be removed. Otherwise, return RM_USER_DECLINED if
788 the user declines to remove at least one entry. Remove as much as
789 possible, continuing even if we fail to remove some entries. */
790 static enum RM_status
791 remove_cwd_entries (char **subdir, struct stat *subdir_sb,
792 struct rm_options const *x)
794 DIR *dirp = opendir (".");
795 struct AD_ent *top = AD_stack_top ();
796 enum RM_status status = top->status;
798 assert (VALID_STATUS (status));
799 *subdir = NULL;
801 if (dirp == NULL)
803 if (errno != ENOENT || !x->ignore_missing_files)
805 error (0, errno, _("cannot open directory %s"),
806 quote (full_filename (".")));
807 return RM_ERROR;
811 while (1)
813 struct dirent *dp = readdir (dirp);
814 enum RM_status tmp_status;
815 const char *f;
817 if (dp == NULL)
818 break;
820 f = dp->d_name;
821 if (DOT_OR_DOTDOT (f))
822 continue;
824 /* Skip files we've already tried/failed to remove. */
825 if ( ! AD_is_removable (f))
826 continue;
828 /* Pass dp->d_type info to remove_entry so the non-glibc
829 case can decide whether to use unlink or chdir.
830 Systems without the d_type member will have to endure
831 the performance hit of first calling lstat F. */
832 tmp_status = remove_entry (f, x, dp);
833 switch (tmp_status)
835 case RM_OK:
836 /* do nothing */
837 break;
839 case RM_ERROR:
840 case RM_USER_DECLINED:
841 AD_mark_as_unremovable (f);
842 UPDATE_STATUS (status, tmp_status);
843 break;
845 case RM_NONEMPTY_DIR:
846 /* Record dev/ino of F so that we can compare
847 that with dev/ino of `.' after the chdir.
848 This dev/ino pair is also used in cycle detection. */
849 if (lstat (f, subdir_sb))
850 error (EXIT_FAILURE, errno, _("cannot lstat %s"),
851 quote (full_filename (f)));
853 if (chdir (f))
855 error (0, errno, _("cannot chdir from %s to %s"),
856 quote_n (0, full_filename (".")), quote_n (1, f));
857 AD_mark_as_unremovable (f);
858 status = RM_ERROR;
859 break;
861 cycle_check (subdir_sb);
863 *subdir = xstrdup (f);
864 break;
867 /* Record status for this directory. */
868 UPDATE_STATUS (top->status, status);
870 if (*subdir)
871 break;
874 closedir (dirp);
876 return status;
879 /* Remove the hierarchy rooted at DIR.
880 Do that by changing into DIR, then removing its contents, then
881 returning to the original working directory and removing DIR itself.
882 Don't use recursion. Be careful when using chdir ".." that we
883 return to the same directory from which we came, if necessary.
884 Return 1 for success, 0 if some file cannot be removed or if
885 a chdir fails.
886 If the working directory cannot be restored, exit immediately. */
888 static enum RM_status
889 remove_dir (char const *dir, struct saved_cwd **cwd_state,
890 struct rm_options const *x)
892 enum RM_status status;
893 struct stat dir_sb;
895 /* Save any errno (from caller's failed remove_entry call), in case DIR
896 is not a directory, so that we can give a reasonable diagnostic. */
897 int saved_errno = errno;
899 if (*cwd_state == NULL)
901 *cwd_state = XMALLOC (struct saved_cwd, 1);
902 if (save_cwd (*cwd_state))
903 return RM_ERROR;
904 AD_push_initial (*cwd_state);
907 /* There is a race condition in that an attacker could replace the nonempty
908 directory, DIR, with a symlink between the preceding call to rmdir
909 (in our caller) and the chdir below. However, the following lstat,
910 along with the `stat (".",...' and dev/ino comparison in AD_push
911 ensure that we detect it and fail. */
913 if (lstat (dir, &dir_sb))
915 error (0, errno,
916 _("cannot lstat %s"), quote (full_filename (dir)));
917 return RM_ERROR;
920 if (chdir (dir))
922 if (! S_ISDIR (dir_sb.st_mode))
924 /* This happens on Linux-2.4.18 when a non-privileged user tries
925 to delete a file that is owned by another user in a directory
926 like /tmp that has the S_ISVTX flag set. */
927 assert (saved_errno == EPERM);
928 error (0, saved_errno,
929 _("cannot remove %s"), quote (full_filename (dir)));
931 else
933 error (0, errno,
934 _("cannot chdir from %s to %s"),
935 quote_n (0, full_filename (".")), quote_n (1, dir));
937 return RM_ERROR;
940 AD_push (dir, &dir_sb);
942 status = RM_OK;
944 while (1)
946 char *subdir = NULL;
947 struct stat subdir_sb;
948 enum RM_status tmp_status = remove_cwd_entries (&subdir, &subdir_sb, x);
949 if (tmp_status != RM_OK)
951 UPDATE_STATUS (status, tmp_status);
952 AD_mark_current_as_unremovable ();
954 if (subdir)
956 AD_push (subdir, &subdir_sb);
957 free (subdir);
958 continue;
961 /* Execution reaches this point when we've removed the last
962 removable entry from the current directory. */
964 char *d = AD_pop_and_chdir ();
966 /* Try to remove D only if remove_cwd_entries succeeded. */
967 if (tmp_status == RM_OK)
969 /* This does a little more work than necessary when it actually
970 prompts the user. E.g., we already know that D is a directory
971 and that it's almost certainly empty, yet we lstat it.
972 But that's no big deal since we're interactive. */
973 Ternary is_dir;
974 Ternary is_empty;
975 enum RM_status s = prompt (d, x, PA_REMOVE_DIR, &is_dir, &is_empty);
977 if (s != RM_OK)
979 free (d);
980 return s;
983 if (rmdir (d) == 0)
985 if (x->verbose)
986 printf (_("removed directory: %s\n"),
987 quote (full_filename (d)));
989 else
991 error (0, errno, _("cannot remove directory %s"),
992 quote (full_filename (d)));
993 AD_mark_as_unremovable (d);
994 status = RM_ERROR;
995 UPDATE_STATUS (AD_stack_top()->status, status);
999 free (d);
1001 if (AD_stack_height () == 1)
1002 break;
1006 return status;
1009 /* Remove the file or directory specified by FILENAME.
1010 Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
1011 On input, the first time this function is called, CWD_STATE should be
1012 the address of a NULL pointer. Do not modify it for any subsequent calls.
1013 On output, it is either that same NULL pointer or the address of
1014 a malloc'd `struct saved_cwd' that may be freed. */
1016 static enum RM_status
1017 rm_1 (char const *filename,
1018 struct rm_options const *x, struct saved_cwd **cwd_state)
1020 char *base = base_name (filename);
1021 enum RM_status status;
1023 if (DOT_OR_DOTDOT (base))
1025 error (0, 0, _("cannot remove `.' or `..'"));
1026 return RM_ERROR;
1029 status = remove_entry (filename, x, NULL);
1030 if (status != RM_NONEMPTY_DIR)
1031 return status;
1033 return remove_dir (filename, cwd_state, x);
1036 /* Remove all files and/or directories specified by N_FILES and FILE.
1037 Apply the options in X. */
1038 enum RM_status
1039 rm (size_t n_files, char const *const *file, struct rm_options const *x)
1041 struct saved_cwd *cwd_state = NULL;
1042 enum RM_status status = RM_OK;
1043 size_t i;
1045 obstack_init (&dir_stack);
1046 obstack_init (&len_stack);
1047 obstack_init (&Active_dir);
1049 for (i = 0; i < n_files; i++)
1051 enum RM_status s = rm_1 (file[i], x, &cwd_state);
1052 assert (VALID_STATUS (s));
1053 UPDATE_STATUS (status, s);
1056 obstack_free (&dir_stack, NULL);
1057 obstack_free (&len_stack, NULL);
1058 obstack_free (&Active_dir, NULL);
1060 XFREE (cwd_state);
1062 return status;