* NEWS: `rm -r' now removes all of the files it should, even on
[platform/upstream/coreutils.git] / src / remove.c
1 /* remove.c -- core functions for removing files and directories
2    Copyright (C) 88, 90, 91, 1994-2005 Free Software Foundation, Inc.
3
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.
8
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.
13
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.  */
17
18 /* Extracted from rm.c and librarified, then rewritten by Jim Meyering.  */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <setjmp.h>
24 #include <assert.h>
25
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"
39 #include "yesno.h"
40
41 /* Avoid shadowing warnings because these are functions declared
42    in dirname.h as well as locals used below.  */
43 #define dir_name rm_dir_name
44 #define dir_len rm_dir_len
45
46 #define obstack_chunk_alloc malloc
47 #define obstack_chunk_free free
48
49 /* If anyone knows of another system for which unlink can never
50    remove a directory, please report it to bug-coreutils@gnu.org.
51    The code below is slightly more efficient if it *knows* that
52    unlink(2) cannot possibly unlink a directory.  */
53 #ifdef __GLIBC__
54 # define UNLINK_CAN_UNLINK_DIRS 0  /* Good!  */
55 #else
56 # define UNLINK_CAN_UNLINK_DIRS 1  /* Less efficient.  */
57 #endif
58
59 /* This is the maximum number of consecutive readdir/unlink calls that
60    can be made (with no intervening rewinddir or closedir/opendir)
61    before triggering a bug that makes readdir return NULL even though
62    some directory entries have not been processed.  The bug afflicts
63    SunOS's readdir when applied to ufs file systems and Darwin 6.5's
64    (and OSX v.10.3.8's) HFS+.  This maximum is conservative in that
65    demonstrating the problem seems to require a directory containing
66    at least 254 deletable entries (which doesn't count . and ..), so
67    we could conceivably increase the maximum value to 254.  */
68 enum
69   {
70     CONSECUTIVE_READDIR_UNLINK_THRESHOLD = 200
71   };
72
73 enum Ternary
74   {
75     T_UNKNOWN = 2,
76     T_NO,
77     T_YES
78   };
79 typedef enum Ternary Ternary;
80
81 /* The prompt function may be called twice for a given directory.
82    The first time, we ask whether to descend into it, and the
83    second time, we ask whether to remove it.  */
84 enum Prompt_action
85   {
86     PA_DESCEND_INTO_DIR = 2,
87     PA_REMOVE_DIR
88   };
89
90 /* On systems with an lstat function that accepts the empty string,
91    arrange to make lstat calls go through the wrapper function.  */
92 #if HAVE_LSTAT_EMPTY_STRING_BUG
93 int rpl_lstat (const char *, struct stat *);
94 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
95 #endif
96
97 /* Initial capacity of per-directory hash table of entries that have
98    been processed but not been deleted.  */
99 #define HT_UNREMOVABLE_INITIAL_CAPACITY 13
100
101 /* An entry in the active directory stack.
102    Each entry corresponds to an `active' directory.  */
103 struct AD_ent
104 {
105   /* For a given active directory, this is the set of names of
106      entries in that directory that could/should not be removed.
107      For example, `.' and `..', as well as files/dirs for which
108      unlink/rmdir failed e.g., due to access restrictions.  */
109   Hash_table *unremovable;
110
111   /* Record the status for a given active directory; we need to know
112      whether an entry was not removed, either because of an error or
113      because the user declined.  */
114   enum RM_status status;
115
116   /* The directory's dev/ino.  Used to ensure that `chdir some-subdir', then
117      `chdir ..' takes us back to the same directory from which we started).
118      (valid for all but the bottommost entry on the stack.  */
119   struct dev_ino dev_ino;
120 };
121
122 extern char *program_name;
123
124 struct dirstack_state
125 {
126   /* The name of the directory (starting with and relative to a command
127      line argument) being processed.  When a subdirectory is entered, a new
128      component is appended (pushed).  Remove (pop) the top component
129      upon chdir'ing out of a directory.  This is used to form the full
130      name of the current directory or a file therein, when necessary.  */
131   struct obstack dir_stack;
132
133   /* Stack of lengths of directory names (including trailing slash)
134      appended to dir_stack.  We have to have a separate stack of lengths
135      (rather than just popping back to previous slash) because the first
136      element pushed onto the dir stack may contain slashes.  */
137   struct obstack len_stack;
138
139   /* Stack of active directory entries.
140      The first `active' directory is the initial working directory.
141      Additional active dirs are pushed onto the stack as we `chdir'
142      into each directory to be processed.  When finished with the
143      hierarchy under a directory, pop the active dir stack.  */
144   struct obstack Active_dir;
145
146   /* Used to detect cycles.  */
147   struct cycle_check_state cycle_check_state;
148
149   /* Target of a longjmp in case rm has to stop processing the current
150      command-line argument.  This happens 1) when rm detects a directory
151      cycle or 2) when it has processed one or more directories, but then
152      is unable to return to the initial working directory to process
153      additional `.'-relative command-line arguments.  */
154   jmp_buf current_arg_jumpbuf;
155 };
156 typedef struct dirstack_state Dirstack_state;
157
158 struct cwd_state
159 {
160   /* The value of errno after a failed save_cwd or restore_cwd.  */
161   int saved_errno;
162
163   /* Information (open file descriptor or absolute directory name)
164      required in order to restore the initial working directory.  */
165   struct saved_cwd saved_cwd;
166 };
167
168 static Dirstack_state *
169 ds_init (void)
170 {
171   Dirstack_state *ds = xmalloc (sizeof *ds);
172   obstack_init (&ds->dir_stack);
173   obstack_init (&ds->len_stack);
174   obstack_init (&ds->Active_dir);
175   return ds;
176 }
177
178 static void
179 ds_free (Dirstack_state *ds)
180 {
181   obstack_free (&ds->dir_stack, NULL);
182   obstack_free (&ds->len_stack, NULL);
183   obstack_free (&ds->Active_dir, NULL);
184   free (ds);
185 }
186
187 static void
188 hash_freer (void *x)
189 {
190   free (x);
191 }
192
193 static bool
194 hash_compare_strings (void const *x, void const *y)
195 {
196   return STREQ (x, y) ? true : false;
197 }
198
199 static inline void
200 push_dir (Dirstack_state *ds, const char *dir_name)
201 {
202   size_t len = strlen (dir_name);
203
204   /* Append the string onto the stack.  */
205   obstack_grow (&ds->dir_stack, dir_name, len);
206
207   /* Append a trailing slash.  */
208   obstack_1grow (&ds->dir_stack, '/');
209
210   /* Add one for the slash.  */
211   ++len;
212
213   /* Push the length (including slash) onto its stack.  */
214   obstack_grow (&ds->len_stack, &len, sizeof (len));
215 }
216
217 /* Return the entry name of the directory on the top of the stack
218    in malloc'd storage.  */
219 static inline char *
220 top_dir (Dirstack_state const *ds)
221 {
222   size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
223   size_t *length = obstack_base (&ds->len_stack);
224   size_t top_len = length[n_lengths - 1];
225   char const *p = obstack_next_free (&ds->dir_stack) - top_len;
226   char *q = xmalloc (top_len);
227   memcpy (q, p, top_len - 1);
228   q[top_len - 1] = 0;
229   return q;
230 }
231
232 static inline void
233 pop_dir (Dirstack_state *ds)
234 {
235   size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
236   size_t *length = obstack_base (&ds->len_stack);
237   size_t top_len;
238
239   assert (n_lengths > 0);
240   top_len = length[n_lengths - 1];
241   assert (top_len >= 2);
242
243   /* Pop off the specified length of pathname.  */
244   assert (obstack_object_size (&ds->dir_stack) >= top_len);
245   obstack_blank (&ds->dir_stack, -top_len);
246
247   /* Pop the length stack, too.  */
248   assert (obstack_object_size (&ds->len_stack) >= sizeof (size_t));
249   obstack_blank (&ds->len_stack, -(int) sizeof (size_t));
250 }
251
252 /* Copy the SRC_LEN bytes of data beginning at SRC into the DST_LEN-byte
253    buffer, DST, so that the last source byte is at the end of the destination
254    buffer.  If SRC_LEN is longer than DST_LEN, then set *TRUNCATED.
255    Set *RESULT to point to the beginning of (the portion of) the source data
256    in DST.  Return the number of bytes remaining in the destination buffer.  */
257
258 static size_t
259 right_justify (char *dst, size_t dst_len, const char *src, size_t src_len,
260                char **result, bool *truncated)
261 {
262   const char *sp;
263   char *dp;
264
265   if (src_len <= dst_len)
266     {
267       sp = src;
268       dp = dst + (dst_len - src_len);
269       *truncated = false;
270     }
271   else
272     {
273       sp = src + (src_len - dst_len);
274       dp = dst;
275       src_len = dst_len;
276       *truncated = true;
277     }
278
279   *result = memcpy (dp, sp, src_len);
280   return dst_len - src_len;
281 }
282
283 /* Using the global directory name obstack, create the full path to FILENAME.
284    Return it in sometimes-realloc'd space that should not be freed by the
285    caller.  Realloc as necessary.  If realloc fails, use a static buffer
286    and put as long a suffix in that buffer as possible.  */
287
288 #define full_filename(Filename) full_filename_ (ds, Filename)
289 static char *
290 full_filename_ (Dirstack_state const *ds, const char *filename)
291 {
292   static char *buf = NULL;
293   static size_t n_allocated = 0;
294
295   size_t dir_len = obstack_object_size (&ds->dir_stack);
296   char *dir_name = obstack_base (&ds->dir_stack);
297   size_t n_bytes_needed;
298   size_t filename_len;
299
300   filename_len = strlen (filename);
301   n_bytes_needed = dir_len + filename_len + 1;
302
303   if (n_allocated < n_bytes_needed)
304     {
305       /* This code requires that realloc accept NULL as the first arg.
306          This function must not use xrealloc.  Otherwise, an out-of-memory
307          error involving a file name to be expanded here wouldn't ever
308          be issued.  Use realloc and fall back on using a static buffer
309          if memory allocation fails.  */
310       char *new_buf = realloc (buf, n_bytes_needed);
311       n_allocated = n_bytes_needed;
312
313       if (new_buf == NULL)
314         {
315 #define SBUF_SIZE 512
316 #define ELLIPSES_PREFIX "[...]"
317           static char static_buf[SBUF_SIZE];
318           bool truncated;
319           size_t len;
320           char *p;
321
322           free (buf);
323           len = right_justify (static_buf, SBUF_SIZE, filename,
324                                filename_len + 1, &p, &truncated);
325           right_justify (static_buf, len, dir_name, dir_len, &p, &truncated);
326           if (truncated)
327             {
328               memcpy (static_buf, ELLIPSES_PREFIX,
329                       sizeof (ELLIPSES_PREFIX) - 1);
330             }
331           return p;
332         }
333
334       buf = new_buf;
335     }
336
337   if (filename_len == 1 && *filename == '.' && dir_len)
338     {
339       /* FILENAME is just `.' and dir_len is nonzero.
340          Copy the directory part, omitting the trailing slash,
341          and append a trailing zero byte.  */
342       char *p = mempcpy (buf, dir_name, dir_len - 1);
343       *p = 0;
344     }
345   else
346     {
347       /* Copy the directory part, including trailing slash, and then
348          append the filename part, including a trailing zero byte.  */
349       memcpy (mempcpy (buf, dir_name, dir_len), filename, filename_len + 1);
350       assert (strlen (buf) + 1 == n_bytes_needed);
351     }
352
353   return buf;
354 }
355
356 static size_t
357 AD_stack_height (Dirstack_state const *ds)
358 {
359   return obstack_object_size (&ds->Active_dir) / sizeof (struct AD_ent);
360 }
361
362 static struct AD_ent *
363 AD_stack_top (Dirstack_state const *ds)
364 {
365   return (struct AD_ent *)
366     ((char *) obstack_next_free (&ds->Active_dir) - sizeof (struct AD_ent));
367 }
368
369 static void
370 AD_stack_pop (Dirstack_state *ds)
371 {
372   /* operate on Active_dir.  pop and free top entry */
373   struct AD_ent *top = AD_stack_top (ds);
374   if (top->unremovable)
375     hash_free (top->unremovable);
376   obstack_blank (&ds->Active_dir, -(int) sizeof (struct AD_ent));
377   pop_dir (ds);
378 }
379
380 /* chdir `up' one level.
381    Whenever using chdir '..', verify that the post-chdir
382    dev/ino numbers for `.' match the saved ones.
383    If they don't match, exit nonzero.
384    Set *PREV_DIR to the name (in malloc'd storage) of the
385    directory (usually now empty) from which we're coming.
386    If we're at the bottom of the AD stack (about to return
387    to the initial working directory), then use CWD.
388    If that restore_cwd fails, set CWD_STATE->saved_errno.  */
389 static void
390 AD_pop_and_chdir (Dirstack_state *ds, char **prev_dir,
391                   struct cwd_state *cwd_state)
392 {
393   enum RM_status old_status = AD_stack_top(ds)->status;
394   struct AD_ent *top;
395
396   /* Get the name of the current (but soon to be `previous') directory
397      from the top of the stack.  */
398   *prev_dir = top_dir (ds);
399
400   AD_stack_pop (ds);
401   top = AD_stack_top (ds);
402
403   /* Propagate any failure to parent.  */
404   UPDATE_STATUS (top->status, old_status);
405
406   assert (AD_stack_height (ds));
407
408   if (1 < AD_stack_height (ds))
409     {
410       struct stat sb;
411
412       /* We can give a better diagnostic here, since the target is relative. */
413       if (chdir ("..") != 0)
414         {
415           error (EXIT_FAILURE, errno,
416                  _("cannot chdir from %s to .."),
417                  quote (full_filename (".")));
418         }
419
420       if (lstat (".", &sb))
421         error (EXIT_FAILURE, errno,
422                _("cannot lstat `.' in %s"), quote (full_filename (".")));
423
424       /*  Ensure that post-chdir dev/ino match the stored ones.  */
425       if ( ! SAME_INODE (sb, top->dev_ino))
426         error (EXIT_FAILURE, 0,
427                _("%s changed dev/ino"), quote (full_filename (".")));
428     }
429   else
430     {
431       if (restore_cwd (&cwd_state->saved_cwd) != 0)
432         {
433           /* We've failed to return to the initial working directory.
434              That failure may be harmless if x->require_restore_cwd is false,
435              but we do have to remember that fact, including the errno value,
436              so we can give an accurate diagnostic when reporting the failure
437              to remove a subsequent relative-named command-line argument.  */
438           cwd_state->saved_errno = errno;
439         }
440     }
441 }
442
443 /* Initialize *HT if it is NULL.
444    Insert FILENAME into HT.  */
445 static void
446 AD_mark_helper (Hash_table **ht, char const *filename)
447 {
448   if (*ht == NULL)
449     {
450       *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw,
451                              hash_compare_strings, hash_freer);
452       if (*ht == NULL)
453         xalloc_die ();
454     }
455   if (! hash_insert (*ht, filename))
456     xalloc_die ();
457 }
458
459 /* Mark FILENAME (in current directory) as unremovable.  */
460 static void
461 AD_mark_as_unremovable (Dirstack_state *ds, char const *filename)
462 {
463   AD_mark_helper (&AD_stack_top(ds)->unremovable, xstrdup (filename));
464 }
465
466 /* Mark the current directory as unremovable.  I.e., mark the entry
467    in the parent directory corresponding to `.'.
468    This happens e.g., when an opendir fails and the only name
469    the caller has conveniently at hand is `.'.  */
470 static void
471 AD_mark_current_as_unremovable (Dirstack_state *ds)
472 {
473   struct AD_ent *top = AD_stack_top (ds);
474   const char *curr = top_dir (ds);
475
476   assert (1 < AD_stack_height (ds));
477
478   --top;
479   AD_mark_helper (&top->unremovable, curr);
480 }
481
482 /* Push an initial dummy entry onto the stack.
483    This will always be the bottommost entry on the stack.  */
484 static void
485 AD_push_initial (Dirstack_state *ds)
486 {
487   struct AD_ent *top;
488
489   /* Extend the stack.  */
490   obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
491
492   /* Fill in the new values.  */
493   top = AD_stack_top (ds);
494   top->unremovable = NULL;
495
496   /* These should never be used.
497      Give them values that might look suspicious
498      in a debugger or in a diagnostic.  */
499   top->dev_ino.st_dev = TYPE_MAXIMUM (dev_t);
500   top->dev_ino.st_ino = TYPE_MAXIMUM (ino_t);
501 }
502
503 /* Push info about the current working directory (".") onto the
504    active directory stack.  DIR is the ./-relative name through
505    which we've just `chdir'd to this directory.  DIR_SB_FROM_PARENT
506    is the result of calling lstat on DIR from the parent of DIR.  */
507 static void
508 AD_push (Dirstack_state *ds, char const *dir,
509          struct stat const *dir_sb_from_parent)
510 {
511   struct stat sb;
512   struct AD_ent *top;
513
514   push_dir (ds, dir);
515
516   if (lstat (".", &sb))
517     error (EXIT_FAILURE, errno,
518            _("cannot lstat `.' in %s"), quote (full_filename (".")));
519
520   if ( ! SAME_INODE (sb, *dir_sb_from_parent))
521     error (EXIT_FAILURE, 0,
522            _("%s changed dev/ino"), quote (full_filename (".")));
523
524   /* Extend the stack.  */
525   obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
526
527   /* Fill in the new values.  */
528   top = AD_stack_top (ds);
529   top->dev_ino.st_dev = sb.st_dev;
530   top->dev_ino.st_ino = sb.st_ino;
531   top->unremovable = NULL;
532 }
533
534 static bool
535 AD_is_removable (Dirstack_state const *ds, char const *file)
536 {
537   struct AD_ent *top = AD_stack_top (ds);
538   return ! (top->unremovable && hash_lookup (top->unremovable, file));
539 }
540
541 /* Return true if DIR is determined to be an empty directory
542    or if opendir or readdir fails.  */
543 static bool
544 is_empty_dir (char const *dir)
545 {
546   DIR *dirp = opendir (dir);
547   struct dirent const *dp;
548   int saved_errno;
549
550   if (dirp == NULL)
551     return false;
552
553   errno = 0;
554   dp = readdir_ignoring_dot_and_dotdot (dirp);
555   saved_errno = errno;
556   closedir (dirp);
557   if (dp != NULL)
558     return false;
559   return saved_errno == 0 ? true : false;
560 }
561
562 /* Return true if FILE is not a symbolic link and it is not writable.
563    Also return true if FILE cannot be lstat'ed.  Otherwise, return false.
564    If lstat succeeds, set *BUF_P to BUF.
565    This is to avoid calling euidaccess when FILE is a symlink.  */
566 static bool
567 write_protected_non_symlink (char const *file,
568                              struct stat **buf_p,
569                              struct stat *buf)
570 {
571   if (lstat (file, buf) != 0)
572     return false;
573   *buf_p = buf;
574   if (S_ISLNK (buf->st_mode))
575     return false;
576   return euidaccess (file, W_OK) == -1 && errno == EACCES;
577 }
578
579 /* Prompt whether to remove FILENAME, if required via a combination of
580    the options specified by X and/or file attributes.  If the file may
581    be removed, return RM_OK.  If the user declines to remove the file,
582    return RM_USER_DECLINED.  If not ignoring missing files and we
583    cannot lstat FILENAME, then return RM_ERROR.
584
585    Depending on MODE, ask whether to `descend into' or to `remove' the
586    directory FILENAME.  MODE is ignored when FILENAME is not a directory.
587    Set *IS_EMPTY to T_YES if FILENAME is an empty directory, and it is
588    appropriate to try to remove it with rmdir (e.g. recursive mode).
589    Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR.
590    Set *IS_DIR to T_YES or T_NO if we happen to determine whether
591    FILENAME is a directory.  */
592 static enum RM_status
593 prompt (Dirstack_state const *ds, char const *filename,
594         struct rm_options const *x, enum Prompt_action mode,
595         Ternary *is_dir, Ternary *is_empty)
596 {
597   bool write_protected = false;
598   struct stat *sbuf = NULL;
599   struct stat buf;
600
601   *is_empty = T_UNKNOWN;
602   *is_dir = T_UNKNOWN;
603
604   if (((!x->ignore_missing_files & (x->interactive | x->stdin_tty))
605        && (write_protected = write_protected_non_symlink (filename,
606                                                           &sbuf, &buf)))
607       || x->interactive)
608     {
609       if (sbuf == NULL)
610         {
611           sbuf = &buf;
612           if (lstat (filename, sbuf))
613             {
614               /* lstat failed.  This happens e.g., with `rm '''.  */
615               error (0, errno, _("cannot lstat %s"),
616                      quote (full_filename (filename)));
617               return RM_ERROR;
618             }
619         }
620
621       if (S_ISDIR (sbuf->st_mode) && !x->recursive)
622         {
623           error (0, EISDIR, _("cannot remove directory %s"),
624                  quote (full_filename (filename)));
625           return RM_ERROR;
626         }
627
628       /* Using permissions doesn't make sense for symlinks.  */
629       if (S_ISLNK (sbuf->st_mode))
630         {
631           if ( ! x->interactive)
632             return RM_OK;
633           write_protected = false;
634         }
635
636       /* Issue the prompt.  */
637       {
638         char const *quoted_name = quote (full_filename (filename));
639
640         *is_dir = (S_ISDIR (sbuf->st_mode) ? T_YES : T_NO);
641
642         /* FIXME: use a variant of error (instead of fprintf) that doesn't
643            append a newline.  Then we won't have to declare program_name in
644            this file.  */
645         if (S_ISDIR (sbuf->st_mode)
646             && x->recursive
647             && mode == PA_DESCEND_INTO_DIR
648             && ((*is_empty = (is_empty_dir (filename) ? T_YES : T_NO))
649                 == T_NO))
650           fprintf (stderr,
651                    (write_protected
652                     ? _("%s: descend into write-protected directory %s? ")
653                     : _("%s: descend into directory %s? ")),
654                    program_name, quoted_name);
655         else
656           {
657             /* TRANSLATORS: You may find it more convenient to translate
658                the equivalent of _("%s: remove %s (write-protected) %s? ").
659                It should avoid grammatical problems with the output
660                of file_type.  */
661             fprintf (stderr,
662                      (write_protected
663                       ? _("%s: remove write-protected %s %s? ")
664                       : _("%s: remove %s %s? ")),
665                      program_name, file_type (sbuf), quoted_name);
666           }
667
668         if (!yesno ())
669           return RM_USER_DECLINED;
670       }
671     }
672   return RM_OK;
673 }
674
675 #if HAVE_STRUCT_DIRENT_D_TYPE
676 # define DT_IS_DIR(D) ((D)->d_type == DT_DIR)
677 #else
678 /* Use this only if the member exists -- i.e., don't return 0.  */
679 # define DT_IS_DIR(D) do_not_use_this_macro
680 #endif
681
682 #define DO_UNLINK(Filename, X)                                          \
683   do                                                                    \
684     {                                                                   \
685       if (unlink (Filename) == 0)                                       \
686         {                                                               \
687           if ((X)->verbose)                                             \
688             printf (_("removed %s\n"), quote (full_filename (Filename))); \
689           return RM_OK;                                                 \
690         }                                                               \
691                                                                         \
692       if (errno == ENOENT && (X)->ignore_missing_files)                 \
693         return RM_OK;                                                   \
694     }                                                                   \
695   while (0)
696
697 #define DO_RMDIR(Filename, X)                           \
698   do                                                    \
699     {                                                   \
700       if (rmdir (Filename) == 0)                        \
701         {                                               \
702           if ((X)->verbose)                             \
703             printf (_("removed directory: %s\n"),       \
704                     quote (full_filename (Filename)));  \
705           return RM_OK;                                 \
706         }                                               \
707                                                         \
708       if (errno == ENOENT && (X)->ignore_missing_files) \
709         return RM_OK;                                   \
710                                                         \
711       if (errno == ENOTEMPTY || errno == EEXIST)        \
712         return RM_NONEMPTY_DIR;                         \
713     }                                                   \
714   while (0)
715
716 /* Remove the file or directory specified by FILENAME.
717    Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
718    But if FILENAME specifies a non-empty directory, return RM_NONEMPTY_DIR. */
719
720 static enum RM_status
721 remove_entry (Dirstack_state const *ds, char const *filename,
722               struct rm_options const *x, struct dirent const *dp)
723 {
724   Ternary is_dir;
725   Ternary is_empty_directory;
726   enum RM_status s = prompt (ds, filename, x, PA_DESCEND_INTO_DIR,
727                              &is_dir, &is_empty_directory);
728
729   if (s != RM_OK)
730     return s;
731
732   /* Why bother with the following #if/#else block?  Because on systems with
733      an unlink function that *can* unlink directories, we must determine the
734      type of each entry before removing it.  Otherwise, we'd risk unlinking
735      an entire directory tree simply by unlinking a single directory;  then
736      all the storage associated with that hierarchy would not be freed until
737      the next reboot.  Not nice.  To avoid that, on such slightly losing
738      systems, we need to call lstat to determine the type of each entry,
739      and that represents extra overhead that -- it turns out -- we can
740      avoid on GNU-libc-based systems, since there, unlink will never remove
741      a directory.  Also, on systems where unlink may unlink directories,
742      we're forced to allow a race condition: we lstat a non-directory, then
743      go to unlink it, but in the mean time, a malicious someone has replaced
744      it with a directory.  */
745
746 #if UNLINK_CAN_UNLINK_DIRS
747
748   /* If we don't already know whether FILENAME is a directory, find out now.
749      Then, if it's a non-directory, we can use unlink on it.  */
750   if (is_dir == T_UNKNOWN)
751     {
752 # if HAVE_STRUCT_DIRENT_D_TYPE
753       if (dp && dp->d_type != DT_UNKNOWN)
754         is_dir = DT_IS_DIR (dp) ? T_YES : T_NO;
755       else
756 # endif
757         {
758           struct stat sbuf;
759           if (lstat (filename, &sbuf))
760             {
761               if (errno == ENOENT && x->ignore_missing_files)
762                 return RM_OK;
763
764               error (0, errno,
765                      _("cannot lstat %s"), quote (full_filename (filename)));
766               return RM_ERROR;
767             }
768
769           is_dir = S_ISDIR (sbuf.st_mode) ? T_YES : T_NO;
770         }
771     }
772
773   if (is_dir == T_NO)
774     {
775       /* At this point, barring race conditions, FILENAME is known
776          to be a non-directory, so it's ok to try to unlink it.  */
777       DO_UNLINK (filename, x);
778
779       /* unlink failed with some other error code.  report it.  */
780       error (0, errno, _("cannot remove %s"),
781              quote (full_filename (filename)));
782       return RM_ERROR;
783     }
784
785   if (! x->recursive)
786     {
787       error (0, EISDIR, _("cannot remove directory %s"),
788              quote (full_filename (filename)));
789       return RM_ERROR;
790     }
791
792   if (is_empty_directory == T_YES)
793     {
794       DO_RMDIR (filename, x);
795       /* Don't diagnose any failure here.
796          It'll be detected when the caller tries another way.  */
797     }
798
799
800 #else /* ! UNLINK_CAN_UNLINK_DIRS */
801
802   if (is_dir == T_YES && ! x->recursive)
803     {
804       error (0, EISDIR, _("cannot remove directory %s"),
805              quote (full_filename (filename)));
806       return RM_ERROR;
807     }
808
809   /* is_empty_directory is set iff it's ok to use rmdir.
810      Note that it's set only in interactive mode -- in which case it's
811      an optimization that arranges so that the user is asked just
812      once whether to remove the directory.  */
813   if (is_empty_directory == T_YES)
814     DO_RMDIR (filename, x);
815
816   /* If we happen to know that FILENAME is a directory, return now
817      and let the caller remove it -- this saves the overhead of a failed
818      unlink call.  If FILENAME is a command-line argument, then dp is NULL,
819      so we'll first try to unlink it.  Using unlink here is ok, because it
820      cannot remove a directory.  */
821   if ((dp && DT_IS_DIR (dp)) || is_dir == T_YES)
822     return RM_NONEMPTY_DIR;
823
824   DO_UNLINK (filename, x);
825
826   if (! x->recursive
827       || errno == ENOENT || errno == ENOTDIR
828       || errno == ELOOP || errno == ENAMETOOLONG)
829     {
830       /* Either --recursive is not in effect, or the file cannot be a
831          directory.  Report the unlink problem and fail.  */
832       error (0, errno, _("cannot remove %s"),
833              quote (full_filename (filename)));
834       return RM_ERROR;
835     }
836 #endif
837
838   return RM_NONEMPTY_DIR;
839 }
840
841 /* Remove entries in `.', the current working directory (cwd).
842    Upon finding a directory that is both non-empty and that can be chdir'd
843    into, return RM_OK and set *SUBDIR and fill in SUBDIR_SB, where
844    SUBDIR is the malloc'd name of the subdirectory if the chdir succeeded,
845    NULL otherwise (e.g., if opendir failed or if there was no subdirectory).
846    Likewise, SUBDIR_SB is the result of calling lstat on SUBDIR.
847    Return RM_OK if all entries are removed.  Return RM_ERROR if any
848    entry cannot be removed.  Otherwise, return RM_USER_DECLINED if
849    the user declines to remove at least one entry.  Remove as much as
850    possible, continuing even if we fail to remove some entries.  */
851 static enum RM_status
852 remove_cwd_entries (Dirstack_state *ds, char **subdir, struct stat *subdir_sb,
853                     struct rm_options const *x)
854 {
855   DIR *dirp = opendir (".");
856   struct AD_ent *top = AD_stack_top (ds);
857   enum RM_status status = top->status;
858   size_t n_unlinked_since_opendir_or_last_rewind = 0;
859
860   assert (VALID_STATUS (status));
861   *subdir = NULL;
862
863   if (dirp == NULL)
864     {
865       if (errno != ENOENT || !x->ignore_missing_files)
866         {
867           error (0, errno, _("cannot open directory %s"),
868                  quote (full_filename (".")));
869           return RM_ERROR;
870         }
871     }
872
873   while (1)
874     {
875       struct dirent const *dp;
876       enum RM_status tmp_status;
877       const char *f;
878
879       /* Set errno to zero so we can distinguish between a readdir failure
880          and when readdir simply finds that there are no more entries.  */
881       errno = 0;
882       if ((dp = readdir_ignoring_dot_and_dotdot (dirp)) == NULL)
883         {
884           if (errno)
885             {
886               /* Save/restore errno across closedir call.  */
887               int e = errno;
888               closedir (dirp);
889               errno = e;
890
891               /* Arrange to give a diagnostic after exiting this loop.  */
892               dirp = NULL;
893             }
894           else if (CONSECUTIVE_READDIR_UNLINK_THRESHOLD
895                    < n_unlinked_since_opendir_or_last_rewind)
896             {
897               /* Call rewinddir if we've called unlink or rmdir so many times
898                  (since the opendir or the previous rewinddir) that this
899                  NULL-return may be the symptom of a buggy readdir.  */
900               rewinddir (dirp);
901               n_unlinked_since_opendir_or_last_rewind = 0;
902               continue;
903             }
904           break;
905         }
906
907       f = dp->d_name;
908
909       /* Skip files we've already tried/failed to remove.  */
910       if ( ! AD_is_removable (ds, f))
911         continue;
912
913       /* Pass dp->d_type info to remove_entry so the non-glibc
914          case can decide whether to use unlink or chdir.
915          Systems without the d_type member will have to endure
916          the performance hit of first calling lstat F. */
917       tmp_status = remove_entry (ds, f, x, dp);
918       switch (tmp_status)
919         {
920         case RM_OK:
921           /* Count how many files we've unlinked since the initial
922              opendir or the last rewinddir.  On buggy systems, if you
923              remove too many, readdir return NULL even though there
924              remain unprocessed directory entries.  */
925           ++n_unlinked_since_opendir_or_last_rewind;
926           break;
927
928         case RM_ERROR:
929         case RM_USER_DECLINED:
930           AD_mark_as_unremovable (ds, f);
931           UPDATE_STATUS (status, tmp_status);
932           break;
933
934         case RM_NONEMPTY_DIR:
935           {
936             /* Save a copy of errno, in case the preceding unlink (from
937                remove_entry's DO_UNLINK) of a non-directory failed.  */
938             int saved_errno = errno;
939
940             /* Record dev/ino of F so that we can compare
941                that with dev/ino of `.' after the chdir.
942                This dev/ino pair is also used in cycle detection.  */
943             if (lstat (f, subdir_sb))
944               error (EXIT_FAILURE, errno, _("cannot lstat %s"),
945                      quote (full_filename (f)));
946
947             errno = ENOTDIR;
948             if (! S_ISDIR (subdir_sb->st_mode) || chdir (f) != 0)
949               {
950                 /* It is much more common that we reach this point for an
951                    inaccessible directory.  Hence the second diagnostic, below.
952                    However it is also possible that F is a non-directory.
953                    That can happen when we use the `! UNLINK_CAN_UNLINK_DIRS'
954                    block of code and when DO_UNLINK fails due to EPERM.
955                    In that case, give a better diagnostic.  */
956                 if (errno == ENOTDIR)
957                   error (0, saved_errno, _("cannot remove %s"),
958                          quote (full_filename (f)));
959                 else
960                   error (0, errno, _("cannot chdir from %s to %s"),
961                          quote_n (0, full_filename (".")), quote_n (1, f));
962                 AD_mark_as_unremovable (ds, f);
963                 status = RM_ERROR;
964                 break;
965               }
966             if (cycle_check (&ds->cycle_check_state, subdir_sb))
967               {
968                 error (0, 0, _("\
969 WARNING: Circular directory structure.\n\
970 This almost certainly means that you have a corrupted file system.\n\
971 NOTIFY YOUR SYSTEM MANAGER.\n\
972 The following directory is part of the cycle:\n  %s\n"),
973                        quote (full_filename (".")));
974                 longjmp (ds->current_arg_jumpbuf, 1);
975               }
976
977             *subdir = xstrdup (f);
978             break;
979           }
980         }
981
982       /* Record status for this directory.  */
983       UPDATE_STATUS (top->status, status);
984
985       if (*subdir)
986         break;
987     }
988
989   if (dirp == NULL || CLOSEDIR (dirp) != 0)
990     {
991       /* Note that this diagnostic serves for both readdir
992          and closedir failures.  */
993       error (0, errno, _("reading directory %s"), quote (full_filename (".")));
994       status = RM_ERROR;
995     }
996
997   return status;
998 }
999
1000 /* Do this after each call to AD_push or AD_push_initial.
1001    Because the status = RM_OK bit is too remove-specific to
1002    go into the general-purpose AD_* package.  */
1003 #define AD_INIT_OTHER_MEMBERS()                 \
1004   do                                            \
1005     {                                           \
1006       AD_stack_top(ds)->status = RM_OK;         \
1007     }                                           \
1008   while (0)
1009
1010 /*  Remove the hierarchy rooted at DIR.
1011     Do that by changing into DIR, then removing its contents, then
1012     returning to the original working directory and removing DIR itself.
1013     Don't use recursion.  Be careful when using chdir ".." that we
1014     return to the same directory from which we came, if necessary.
1015     Return 1 for success, 0 if some file cannot be removed or if
1016     a chdir fails.
1017     If the initial working directory cannot be saved or restored,
1018     record the offending errno value in (*CWD_STATE)->saved_errno.  */
1019
1020 static enum RM_status
1021 remove_dir (Dirstack_state *ds, char const *dir, struct cwd_state **cwd_state,
1022             struct rm_options const *x)
1023 {
1024   enum RM_status status;
1025   struct stat dir_sb;
1026
1027   /* Save any errno (from caller's failed remove_entry call), in case DIR
1028      is not a directory, so that we can give a reasonable diagnostic.  */
1029   int saved_errno = errno;
1030
1031   if (*cwd_state == NULL)
1032     {
1033       *cwd_state = xmalloc (sizeof **cwd_state);
1034
1035       if (save_cwd (&(*cwd_state)->saved_cwd) != 0)
1036         {
1037           (*cwd_state)->saved_errno = errno;
1038           assert (errno != 0);
1039
1040           /* Pretend we started from "/".  That is fine as long as there
1041              is no requirement to return to the original working directory.
1042              Use "/", not ".", so that we chdir out of a non-root target
1043              directory before attempting to remove it: some hosts don't let
1044              you remove a working directory.  */
1045           (*cwd_state)->saved_cwd.name = xstrdup ("/");
1046         }
1047       else
1048         (*cwd_state)->saved_errno = 0;
1049
1050       AD_push_initial (ds);
1051       AD_INIT_OTHER_MEMBERS ();
1052     }
1053
1054   /* If we've failed to record and/or restore the initial working directory,
1055      and we're now trying to access a `.'-relative file name, then give a
1056      diagnostic, record the failure, and proceed with any subsequent
1057      command-line arguments.  */
1058   if ((*cwd_state)->saved_errno && IS_RELATIVE_FILE_NAME (dir))
1059     {
1060       error (0, (*cwd_state)->saved_errno, _("cannot remove directory %s"),
1061              quote (full_filename (dir)));
1062       longjmp (ds->current_arg_jumpbuf, 1);
1063     }
1064
1065   /* There is a race condition in that an attacker could replace the nonempty
1066      directory, DIR, with a symlink between the preceding call to rmdir
1067      (in our caller) and the chdir below.  However, the following lstat,
1068      along with the `stat (".",...' and dev/ino comparison in AD_push
1069      ensure that we detect it and fail.  */
1070
1071   if (lstat (dir, &dir_sb))
1072     {
1073       error (0, errno,
1074              _("cannot lstat %s"), quote (full_filename (dir)));
1075       return RM_ERROR;
1076     }
1077
1078   errno = ENOTDIR;
1079   if (! S_ISDIR (dir_sb.st_mode) || chdir (dir) != 0)
1080     {
1081       if (errno == ENOTDIR)
1082         {
1083           error (0, saved_errno,
1084                  _("cannot remove %s"), quote (full_filename (dir)));
1085         }
1086       else
1087         {
1088           error (0, errno,
1089                  _("cannot chdir from %s to %s"),
1090                  quote_n (0, full_filename (".")), quote_n (1, dir));
1091         }
1092       return RM_ERROR;
1093     }
1094
1095   if (ROOT_DEV_INO_CHECK (x->root_dev_ino, &dir_sb))
1096     {
1097       ROOT_DEV_INO_WARN (full_filename (dir));
1098       return 1;
1099     }
1100
1101   AD_push (ds, dir, &dir_sb);
1102   AD_INIT_OTHER_MEMBERS ();
1103
1104   status = RM_OK;
1105
1106   while (1)
1107     {
1108       char *subdir = NULL;
1109       struct stat subdir_sb;
1110       enum RM_status tmp_status = remove_cwd_entries (ds,
1111                                                       &subdir, &subdir_sb, x);
1112       if (tmp_status != RM_OK)
1113         {
1114           UPDATE_STATUS (status, tmp_status);
1115           AD_mark_current_as_unremovable (ds);
1116         }
1117       if (subdir)
1118         {
1119           AD_push (ds, subdir, &subdir_sb);
1120           AD_INIT_OTHER_MEMBERS ();
1121
1122           free (subdir);
1123           continue;
1124         }
1125
1126       /* Execution reaches this point when we've removed the last
1127          removable entry from the current directory.  */
1128       {
1129         /* This is the name of the directory that we have just
1130            returned from, after nominally removing all of its contents.  */
1131         char *empty_dir;
1132
1133         AD_pop_and_chdir (ds, &empty_dir, *cwd_state);
1134
1135         /* Try to remove D only if remove_cwd_entries succeeded.  */
1136         if (tmp_status == RM_OK)
1137           {
1138             /* This does a little more work than necessary when it actually
1139                prompts the user.  E.g., we already know that D is a directory
1140                and that it's almost certainly empty, yet we lstat it.
1141                But that's no big deal since we're interactive.  */
1142             Ternary is_dir;
1143             Ternary is_empty;
1144             enum RM_status s = prompt (ds, empty_dir, x, PA_REMOVE_DIR,
1145                                        &is_dir, &is_empty);
1146
1147             if (s != RM_OK)
1148               {
1149                 free (empty_dir);
1150                 return s;
1151               }
1152
1153             if (rmdir (empty_dir) == 0)
1154               {
1155                 if (x->verbose)
1156                   printf (_("removed directory: %s\n"),
1157                           quote (full_filename (empty_dir)));
1158               }
1159             else
1160               {
1161                 error (0, errno, _("cannot remove directory %s"),
1162                        quote (full_filename (empty_dir)));
1163                 AD_mark_as_unremovable (ds, empty_dir);
1164                 status = RM_ERROR;
1165                 UPDATE_STATUS (AD_stack_top(ds)->status, status);
1166               }
1167           }
1168
1169         free (empty_dir);
1170
1171         if (AD_stack_height (ds) == 1)
1172           break;
1173       }
1174     }
1175
1176   return status;
1177 }
1178
1179 /* Remove the file or directory specified by FILENAME.
1180    Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
1181    On input, the first time this function is called, CWD_STATE should be
1182    the address of a NULL pointer.  Do not modify it for any subsequent calls.
1183    On output, it is either that same NULL pointer or the address of
1184    a malloc'd `struct saved_cwd' that may be freed.  */
1185
1186 static enum RM_status
1187 rm_1 (Dirstack_state *ds, char const *filename,
1188       struct rm_options const *x, struct cwd_state **cwd_state)
1189 {
1190   char *base = base_name (filename);
1191   enum RM_status status;
1192
1193   if (DOT_OR_DOTDOT (base))
1194     {
1195       error (0, 0, _("cannot remove `.' or `..'"));
1196       return RM_ERROR;
1197     }
1198
1199   if (*cwd_state && (*cwd_state)->saved_errno
1200       && IS_RELATIVE_FILE_NAME (filename))
1201     {
1202       error (0, (*cwd_state)->saved_errno,
1203              _("cannot remove %s"), quote (filename));
1204       return RM_ERROR;
1205     }
1206
1207   status = remove_entry (ds, filename, x, NULL);
1208   if (status != RM_NONEMPTY_DIR)
1209     return status;
1210
1211   return remove_dir (ds, filename, cwd_state, x);
1212 }
1213
1214 /* Remove all files and/or directories specified by N_FILES and FILE.
1215    Apply the options in X.  If X->require_restore_cwd is false, then
1216    this function may return RM_OK even though it is unable to restore
1217    the initial working directory.  */
1218 extern enum RM_status
1219 rm (size_t n_files, char const *const *file, struct rm_options const *x)
1220 {
1221   struct cwd_state *cwd_state = NULL;
1222   Dirstack_state *ds;
1223
1224   /* Put the following two variables in static storage, so they can't
1225      be clobbered by the potential longjmp into this function.  */
1226   static enum RM_status status = RM_OK;
1227   static size_t i;
1228
1229   ds = ds_init ();
1230
1231   for (i = 0; i < n_files; i++)
1232     {
1233       enum RM_status s;
1234       cycle_check_init (&ds->cycle_check_state);
1235       /* In the event that rm_1->remove_dir->remove_cwd_entries detects
1236          a directory cycle, arrange to fail, give up on this FILE, but
1237          continue on with any other arguments.  */
1238       if (setjmp (ds->current_arg_jumpbuf))
1239         s = RM_ERROR;
1240       else
1241         s = rm_1 (ds, file[i], x, &cwd_state);
1242       assert (VALID_STATUS (s));
1243       UPDATE_STATUS (status, s);
1244     }
1245
1246   if (x->require_restore_cwd && cwd_state && cwd_state->saved_errno != 0)
1247     {
1248       error (0, cwd_state->saved_errno,
1249              _("cannot restore current working directory"));
1250       status = RM_ERROR;
1251     }
1252
1253   ds_free (ds);
1254
1255   if (cwd_state && cwd_state->saved_errno == 0)
1256     free_cwd (&cwd_state->saved_cwd);
1257
1258   free (cwd_state);
1259
1260   return status;
1261 }