rm: fix a tiny, nearly inconsequential bug.
[platform/upstream/coreutils.git] / src / remove.c
1 /* remove.c -- core functions for removing files and directories
2    Copyright (C) 88, 90, 91, 1994-2007 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 /* Extracted from rm.c and librarified, then rewritten by Jim Meyering.  */
18
19 #include <config.h>
20 #include <stdio.h>
21 #include <sys/types.h>
22 #include <setjmp.h>
23 #include <assert.h>
24
25 #include "system.h"
26 #include "cycle-check.h"
27 #include "dirfd.h"
28 #include "error.h"
29 #include "euidaccess.h"
30 #include "euidaccess-stat.h"
31 #include "file-type.h"
32 #include "hash.h"
33 #include "hash-pjw.h"
34 #include "lstat.h"
35 #include "obstack.h"
36 #include "openat.h"
37 #include "quote.h"
38 #include "remove.h"
39 #include "root-dev-ino.h"
40 #include "unlinkdir.h"
41 #include "write-any-file.h"
42 #include "yesno.h"
43
44 /* Avoid shadowing warnings because these are functions declared
45    in dirname.h as well as locals used below.  */
46 #define dir_name rm_dir_name
47 #define dir_len rm_dir_len
48
49 #define obstack_chunk_alloc malloc
50 #define obstack_chunk_free free
51
52 /* This is the maximum number of consecutive readdir/unlink calls that
53    can be made (with no intervening rewinddir or closedir/opendir) before
54    triggering a bug that makes readdir return NULL even though some
55    directory entries have not been processed.  The bug afflicts SunOS's
56    readdir when applied to ufs file systems and Darwin 6.5's (and OSX
57    v.10.3.8's) HFS+.  This maximum is conservative in that demonstrating
58    the problem requires a directory containing at least 16 deletable
59    entries (which doesn't count . and ..).
60    This problem also affects Darwin 7.9.0 (aka MacOS X 10.3.9) on HFS+
61    and NFS-mounted file systems, but not vfat ones.  */
62 enum
63   {
64     CONSECUTIVE_READDIR_UNLINK_THRESHOLD = 10
65   };
66
67 /* FIXME: in 2009, or whenever Darwin 7.9.0 (aka MacOS X 10.3.9) is no
68    longer relevant, remove this work-around code.  Then, there will be
69    no need to perform the extra rewinddir call, ever.  */
70 #define NEED_REWIND(readdir_unlink_count) \
71   (CONSECUTIVE_READDIR_UNLINK_THRESHOLD <= (readdir_unlink_count))
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 /* Initial capacity of per-directory hash table of entries that have
91    been processed but not been deleted.  */
92 enum { HT_UNREMOVABLE_INITIAL_CAPACITY = 13 };
93
94 /* An entry in the active directory stack.
95    Each entry corresponds to an `active' directory.  */
96 struct AD_ent
97 {
98   /* For a given active directory, this is the set of names of
99      entries in that directory that could/should not be removed.
100      For example, `.' and `..', as well as files/dirs for which
101      unlink/rmdir failed e.g., due to access restrictions.  */
102   Hash_table *unremovable;
103
104   /* Record the status for a given active directory; we need to know
105      whether an entry was not removed, either because of an error or
106      because the user declined.  */
107   enum RM_status status;
108
109   /* The directory's dev/ino.  Used to ensure that a malicious user does
110      not replace a directory we're about to process with a symlink to
111      some other directory.  */
112   struct dev_ino dev_ino;
113 };
114
115 /* D_TYPE(D) is the type of directory entry D if known, DT_UNKNOWN
116    otherwise.  */
117 #if HAVE_STRUCT_DIRENT_D_TYPE
118 # define D_TYPE(d) ((d)->d_type)
119 #else
120 # define D_TYPE(d) DT_UNKNOWN
121
122 /* Any int values will do here, so long as they're distinct.
123    Undef any existing macros out of the way.  */
124 # undef DT_UNKNOWN
125 # undef DT_DIR
126 # undef DT_LNK
127 # define DT_UNKNOWN 0
128 # define DT_DIR 1
129 # define DT_LNK 2
130 #endif
131
132 extern char *program_name;
133
134 struct dirstack_state
135 {
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).  Remove (pop) the top component
139      upon chdir'ing out of a directory.  This is used to form the full
140      name of the current directory or a file therein, when necessary.  */
141   struct obstack dir_stack;
142
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   struct obstack len_stack;
148
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 we `chdir'
152      into each directory to be processed.  When finished with the
153      hierarchy under a directory, pop the active dir stack.  */
154   struct obstack Active_dir;
155
156   /* Used to detect cycles.  */
157   struct cycle_check_state cycle_check_state;
158
159   /* Target of a longjmp in case rm has to stop processing the current
160      command-line argument.  This happens 1) when rm detects a directory
161      cycle or 2) when it has processed one or more directories, but then
162      is unable to return to the initial working directory to process
163      additional `.'-relative command-line arguments.  */
164   jmp_buf current_arg_jumpbuf;
165 };
166 typedef struct dirstack_state Dirstack_state;
167
168 /* Like fstatat, but cache the result.  If ST->st_size is -1, the
169    status has not been gotten yet.  If less than -1, fstatat failed
170    with errno == -1 - ST->st_size.  Otherwise, the status has already
171    been gotten, so return 0.  */
172 static int
173 cache_fstatat (int fd, char const *file, struct stat *st, int flag)
174 {
175   if (st->st_size == -1 && fstatat (fd, file, st, flag) != 0)
176     st->st_size = -1 - errno;
177   if (0 <= st->st_size)
178     return 0;
179   errno = -1 - st->st_size;
180   return -1;
181 }
182
183 /* Initialize a fstatat cache *ST.  Return ST for convenience.  */
184 static inline struct stat *
185 cache_stat_init (struct stat *st)
186 {
187   st->st_size = -1;
188   return st;
189 }
190
191 /* Return true if *ST has been statted.  */
192 static inline bool
193 cache_statted (struct stat *st)
194 {
195   return (st->st_size != -1);
196 }
197
198 /* Return true if *ST has been statted successfully.  */
199 static inline bool
200 cache_stat_ok (struct stat *st)
201 {
202   return (0 <= st->st_size);
203 }
204
205
206 static void
207 hash_freer (void *x)
208 {
209   free (x);
210 }
211
212 static bool
213 hash_compare_strings (void const *x, void const *y)
214 {
215   return STREQ (x, y) ? true : false;
216 }
217
218 static inline void
219 push_dir (Dirstack_state *ds, const char *dir_name)
220 {
221   size_t len = strlen (dir_name);
222
223   /* Don't copy trailing slashes.  */
224   while (1 < len && dir_name[len - 1] == '/')
225     --len;
226
227   /* Append the string onto the stack.  */
228   obstack_grow (&ds->dir_stack, dir_name, len);
229
230   /* Append a trailing slash.  */
231   obstack_1grow (&ds->dir_stack, '/');
232
233   /* Add one for the slash.  */
234   ++len;
235
236   /* Push the length (including slash) onto its stack.  */
237   obstack_grow (&ds->len_stack, &len, sizeof (len));
238 }
239
240 /* Return the entry name of the directory on the top of the stack
241    in malloc'd storage.  */
242 static inline char *
243 top_dir (Dirstack_state const *ds)
244 {
245   size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
246   size_t *length = obstack_base (&ds->len_stack);
247   size_t top_len = length[n_lengths - 1];
248   char const *p = obstack_next_free (&ds->dir_stack) - top_len;
249   char *q = xmalloc (top_len);
250   memcpy (q, p, top_len - 1);
251   q[top_len - 1] = 0;
252   return q;
253 }
254
255 static inline void
256 pop_dir (Dirstack_state *ds)
257 {
258   size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
259   size_t *length = obstack_base (&ds->len_stack);
260
261   assert (n_lengths > 0);
262   size_t top_len = length[n_lengths - 1];
263   assert (top_len >= 2);
264
265   /* Pop the specified length of file name.  */
266   assert (obstack_object_size (&ds->dir_stack) >= top_len);
267   obstack_blank (&ds->dir_stack, -top_len);
268
269   /* Pop the length stack, too.  */
270   assert (obstack_object_size (&ds->len_stack) >= sizeof (size_t));
271   obstack_blank (&ds->len_stack, -(int) sizeof (size_t));
272 }
273
274 /* Copy the SRC_LEN bytes of data beginning at SRC into the DST_LEN-byte
275    buffer, DST, so that the last source byte is at the end of the destination
276    buffer.  If SRC_LEN is longer than DST_LEN, then set *TRUNCATED.
277    Set *RESULT to point to the beginning of (the portion of) the source data
278    in DST.  Return the number of bytes remaining in the destination buffer.  */
279
280 static size_t
281 right_justify (char *dst, size_t dst_len, const char *src, size_t src_len,
282                char **result, bool *truncated)
283 {
284   const char *sp;
285   char *dp;
286
287   if (src_len <= dst_len)
288     {
289       sp = src;
290       dp = dst + (dst_len - src_len);
291       *truncated = false;
292     }
293   else
294     {
295       sp = src + (src_len - dst_len);
296       dp = dst;
297       src_len = dst_len;
298       *truncated = true;
299     }
300
301   *result = memcpy (dp, sp, src_len);
302   return dst_len - src_len;
303 }
304
305 /* Using the global directory name obstack, create the full name FILENAME.
306    Return it in sometimes-realloc'd space that should not be freed by the
307    caller.  Realloc as necessary.  If realloc fails, use a static buffer
308    and put as long a suffix in that buffer as possible.  */
309
310 #define full_filename(Filename) full_filename_ (ds, Filename)
311 static char *
312 full_filename_ (Dirstack_state const *ds, const char *filename)
313 {
314   static char *buf = NULL;
315   static size_t n_allocated = 0;
316
317   size_t dir_len = obstack_object_size (&ds->dir_stack);
318   char *dir_name = obstack_base (&ds->dir_stack);
319   size_t n_bytes_needed;
320   size_t filename_len;
321
322   filename_len = strlen (filename);
323   n_bytes_needed = dir_len + filename_len + 1;
324
325   if (n_allocated < n_bytes_needed)
326     {
327       /* This code requires that realloc accept NULL as the first arg.
328          This function must not use xrealloc.  Otherwise, an out-of-memory
329          error involving a file name to be expanded here wouldn't ever
330          be issued.  Use realloc and fall back on using a static buffer
331          if memory allocation fails.  */
332       char *new_buf = realloc (buf, n_bytes_needed);
333       n_allocated = n_bytes_needed;
334
335       if (new_buf == NULL)
336         {
337 #define SBUF_SIZE 512
338 #define ELLIPSES_PREFIX "[...]"
339           static char static_buf[SBUF_SIZE];
340           bool truncated;
341           size_t len;
342           char *p;
343
344           free (buf);
345           len = right_justify (static_buf, SBUF_SIZE, filename,
346                                filename_len + 1, &p, &truncated);
347           right_justify (static_buf, len, dir_name, dir_len, &p, &truncated);
348           if (truncated)
349             {
350               memcpy (static_buf, ELLIPSES_PREFIX,
351                       sizeof (ELLIPSES_PREFIX) - 1);
352             }
353           return p;
354         }
355
356       buf = new_buf;
357     }
358
359   if (filename_len == 1 && *filename == '.' && dir_len)
360     {
361       /* FILENAME is just `.' and dir_len is nonzero.
362          Copy the directory part, omitting the trailing slash,
363          and append a trailing zero byte.  */
364       char *p = mempcpy (buf, dir_name, dir_len - 1);
365       *p = 0;
366     }
367   else
368     {
369       /* Copy the directory part, including trailing slash, and then
370          append the filename part, including a trailing zero byte.  */
371       memcpy (mempcpy (buf, dir_name, dir_len), filename, filename_len + 1);
372       assert (strlen (buf) + 1 == n_bytes_needed);
373     }
374
375   return buf;
376 }
377
378 static inline size_t
379 AD_stack_height (Dirstack_state const *ds)
380 {
381   return obstack_object_size (&ds->Active_dir) / sizeof (struct AD_ent);
382 }
383
384 static inline struct AD_ent *
385 AD_stack_top (Dirstack_state const *ds)
386 {
387   return (struct AD_ent *)
388     ((char *) obstack_next_free (&ds->Active_dir) - sizeof (struct AD_ent));
389 }
390
391 static void
392 AD_stack_pop (Dirstack_state *ds)
393 {
394   assert (0 < AD_stack_height (ds));
395
396   /* operate on Active_dir.  pop and free top entry */
397   struct AD_ent *top = AD_stack_top (ds);
398   if (top->unremovable)
399     hash_free (top->unremovable);
400   obstack_blank (&ds->Active_dir, -(int) sizeof (struct AD_ent));
401 }
402
403 static void
404 AD_stack_clear (Dirstack_state *ds)
405 {
406   while (0 < AD_stack_height (ds))
407     {
408       AD_stack_pop (ds);
409     }
410 }
411
412 static Dirstack_state *
413 ds_init (void)
414 {
415   Dirstack_state *ds = xmalloc (sizeof *ds);
416   obstack_init (&ds->dir_stack);
417   obstack_init (&ds->len_stack);
418   obstack_init (&ds->Active_dir);
419   return ds;
420 }
421
422 static void
423 ds_clear (Dirstack_state *ds)
424 {
425   obstack_free (&ds->dir_stack, obstack_finish (&ds->dir_stack));
426   obstack_free (&ds->len_stack, obstack_finish (&ds->len_stack));
427   while (0 < AD_stack_height (ds))
428     AD_stack_pop (ds);
429   obstack_free (&ds->Active_dir, obstack_finish (&ds->Active_dir));
430 }
431
432 static void
433 ds_free (Dirstack_state *ds)
434 {
435   obstack_free (&ds->dir_stack, NULL);
436   obstack_free (&ds->len_stack, NULL);
437   obstack_free (&ds->Active_dir, NULL);
438   free (ds);
439 }
440
441 /* Pop the active directory (AD) stack and prepare to move `up' one level,
442    safely.  Moving `up' usually means opening `..', but when we've just
443    finished recursively processing a command-line directory argument,
444    there's nothing left on the stack, so set *FDP to AT_FDCWD in that case.
445    The idea is to return with *FDP opened on the parent directory,
446    assuming there are entries in that directory that we need to remove.
447
448    Note that we must not call opendir (or fdopendir) just yet, since
449    the caller must first remove the directory we're coming from.
450    That is because some file system implementations cache readdir
451    results at opendir time; so calling opendir, rmdir, readdir would
452    return an entry for the just-removed directory.
453
454    Whenever using chdir '..' (virtually, now, via openat), verify
455    that the post-chdir dev/ino numbers for `.' match the saved ones.
456    If any system call fails or if dev/ino don't match, then give a
457    diagnostic and longjump out.
458    Return the name (in malloc'd storage) of the
459    directory (usually now empty) from which we're coming, and which
460    corresponds to the input value of DIRP.
461
462    Finally, note that while this function's name is no longer as
463    accurate as it once was (it no longer calls chdir), it does open
464    the destination directory.  */
465 static char *
466 AD_pop_and_chdir (DIR *dirp, int *fdp, Dirstack_state *ds)
467 {
468   struct AD_ent *leaf_dir_ent = AD_stack_top(ds);
469   struct dev_ino leaf_dev_ino = leaf_dir_ent->dev_ino;
470   enum RM_status old_status = leaf_dir_ent->status;
471   struct AD_ent *top;
472
473   /* Get the name of the current (but soon to be `previous') directory
474      from the top of the stack.  */
475   char *prev_dir = top_dir (ds);
476
477   AD_stack_pop (ds);
478   pop_dir (ds);
479   top = AD_stack_top (ds);
480
481   /* If the directory we're about to leave (and try to rmdir)
482      is the one whose dev_ino is being used to detect a cycle,
483      reset cycle_check_state.dev_ino to that of the parent.
484      Otherwise, once that directory is removed, its dev_ino
485      could be reused in the creation (by some other process)
486      of a directory that this rm process would encounter,
487      which would result in a false-positive cycle indication.  */
488   CYCLE_CHECK_REFLECT_CHDIR_UP (&ds->cycle_check_state,
489                                 top->dev_ino, leaf_dev_ino);
490
491   /* Propagate any failure to parent.  */
492   UPDATE_STATUS (top->status, old_status);
493
494   assert (AD_stack_height (ds));
495
496   if (1 < AD_stack_height (ds))
497     {
498       struct stat sb;
499       int fd = openat (dirfd (dirp), "..", O_RDONLY);
500       if (closedir (dirp) != 0)
501         {
502           error (0, errno, _("FATAL: failed to close directory %s"),
503                  quote (full_filename (prev_dir)));
504           goto next_cmdline_arg;
505         }
506
507       /* The above fails with EACCES when DIRP is readable but not
508          searchable, when using Solaris' openat.  Without this openat
509          call, tests/rm2 would fail to remove directories a/2 and a/3.  */
510       if (fd < 0)
511         fd = openat (AT_FDCWD, full_filename ("."), O_RDONLY);
512
513       if (fd < 0)
514         {
515           error (0, errno, _("FATAL: cannot open .. from %s"),
516                  quote (full_filename (prev_dir)));
517           goto next_cmdline_arg;
518         }
519
520       if (fstat (fd, &sb))
521         {
522           error (0, errno,
523                  _("FATAL: cannot ensure %s (returned to via ..) is safe"),
524                  quote (full_filename (".")));
525           goto close_and_next;
526         }
527
528       /*  Ensure that post-chdir dev/ino match the stored ones.  */
529       if ( ! SAME_INODE (sb, top->dev_ino))
530         {
531           error (0, 0, _("FATAL: directory %s changed dev/ino"),
532                  quote (full_filename (".")));
533         close_and_next:;
534           close (fd);
535
536         next_cmdline_arg:;
537           free (prev_dir);
538           longjmp (ds->current_arg_jumpbuf, 1);
539         }
540       *fdp = fd;
541     }
542   else
543     {
544       if (closedir (dirp) != 0)
545         {
546           error (0, errno, _("FATAL: failed to close directory %s"),
547                  quote (full_filename (prev_dir)));
548           goto next_cmdline_arg;
549         }
550       *fdp = AT_FDCWD;
551     }
552
553   return prev_dir;
554 }
555
556 /* Initialize *HT if it is NULL.  Return *HT.  */
557 static Hash_table *
558 AD_ensure_initialized (Hash_table **ht)
559 {
560   if (*ht == NULL)
561     {
562       *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw,
563                              hash_compare_strings, hash_freer);
564       if (*ht == NULL)
565         xalloc_die ();
566     }
567
568   return *ht;
569 }
570
571 /* Initialize *HT if it is NULL.
572    Insert FILENAME into HT.  */
573 static void
574 AD_mark_helper (Hash_table **ht, char *filename)
575 {
576   void *ent = hash_insert (AD_ensure_initialized (ht), filename);
577   if (ent == NULL)
578     xalloc_die ();
579   else
580     {
581       if (ent != filename)
582         free (filename);
583     }
584 }
585
586 /* Mark FILENAME (in current directory) as unremovable.  */
587 static void
588 AD_mark_as_unremovable (Dirstack_state *ds, char const *filename)
589 {
590   AD_mark_helper (&AD_stack_top(ds)->unremovable, xstrdup (filename));
591 }
592
593 /* Mark the current directory as unremovable.  I.e., mark the entry
594    in the parent directory corresponding to `.'.
595    This happens e.g., when an opendir fails and the only name
596    the caller has conveniently at hand is `.'.  */
597 static void
598 AD_mark_current_as_unremovable (Dirstack_state *ds)
599 {
600   struct AD_ent *top = AD_stack_top (ds);
601   char *curr = top_dir (ds);
602
603   assert (1 < AD_stack_height (ds));
604
605   --top;
606   AD_mark_helper (&top->unremovable, curr);
607 }
608
609 /* Push an initial dummy entry onto the stack.
610    This will always be the bottommost entry on the stack.  */
611 static void
612 AD_push_initial (Dirstack_state *ds)
613 {
614   struct AD_ent *top;
615
616   /* Extend the stack.  */
617   obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
618
619   /* Fill in the new values.  */
620   top = AD_stack_top (ds);
621   top->unremovable = NULL;
622
623   /* These should never be used.
624      Give them values that might look suspicious
625      in a debugger or in a diagnostic.  */
626   top->dev_ino.st_dev = TYPE_MAXIMUM (dev_t);
627   top->dev_ino.st_ino = TYPE_MAXIMUM (ino_t);
628 }
629
630 /* Push info about the current working directory (".") onto the
631    active directory stack.  DIR is the ./-relative name through
632    which we've just `chdir'd to this directory.  DIR_SB_FROM_PARENT
633    is the result of calling lstat on DIR from the parent of DIR.
634    Longjump out (skipping the entire command line argument we're
635    dealing with) if `fstat (FD_CWD, ...' fails or if someone has
636    replaced DIR with e.g., a symlink to some other directory.  */
637 static void
638 AD_push (int fd_cwd, Dirstack_state *ds, char const *dir,
639          struct stat const *dir_sb_from_parent)
640 {
641   struct AD_ent *top;
642
643   push_dir (ds, dir);
644
645   /* If our uses of openat are guaranteed not to
646      follow a symlink, then we can skip this check.  */
647   if (! HAVE_WORKING_O_NOFOLLOW)
648     {
649       struct stat sb;
650       if (fstat (fd_cwd, &sb) != 0)
651         {
652           error (0, errno, _("FATAL: cannot enter directory %s"),
653                  quote (full_filename (".")));
654           longjmp (ds->current_arg_jumpbuf, 1);
655         }
656
657       if ( ! SAME_INODE (sb, *dir_sb_from_parent))
658         {
659           error (0, 0,
660                  _("FATAL: just-changed-to directory %s changed dev/ino"),
661                  quote (full_filename (".")));
662           longjmp (ds->current_arg_jumpbuf, 1);
663         }
664     }
665
666   if (cycle_check (&ds->cycle_check_state, dir_sb_from_parent))
667     {
668       error (0, 0, _("\
669 WARNING: Circular directory structure.\n\
670 This almost certainly means that you have a corrupted file system.\n\
671 NOTIFY YOUR SYSTEM MANAGER.\n\
672 The following directory is part of the cycle:\n  %s\n"),
673              quote (full_filename (".")));
674       longjmp (ds->current_arg_jumpbuf, 1);
675     }
676
677   /* Extend the stack.  */
678   obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
679
680   /* The active directory stack must be one larger than the length stack.  */
681   assert (AD_stack_height (ds) ==
682           1 + obstack_object_size (&ds->len_stack) / sizeof (size_t));
683
684   /* Fill in the new values.  */
685   top = AD_stack_top (ds);
686   top->dev_ino.st_dev = dir_sb_from_parent->st_dev;
687   top->dev_ino.st_ino = dir_sb_from_parent->st_ino;
688   top->unremovable = NULL;
689 }
690
691 static inline bool
692 AD_is_removable (Dirstack_state const *ds, char const *file)
693 {
694   struct AD_ent *top = AD_stack_top (ds);
695   return ! (top->unremovable && hash_lookup (top->unremovable, file));
696 }
697
698 /* Return true if DIR is determined to be an empty directory.  */
699 static bool
700 is_empty_dir (int fd_cwd, char const *dir)
701 {
702   DIR *dirp;
703   struct dirent const *dp;
704   int saved_errno;
705   int fd = openat (fd_cwd, dir,
706                    (O_RDONLY | O_DIRECTORY
707                     | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK));
708
709   if (fd < 0)
710     return false;
711
712   dirp = fdopendir (fd);
713   if (dirp == NULL)
714     {
715       close (fd);
716       return false;
717     }
718
719   errno = 0;
720   dp = readdir_ignoring_dot_and_dotdot (dirp);
721   saved_errno = errno;
722   closedir (dirp);
723   if (dp != NULL)
724     return false;
725   return saved_errno == 0 ? true : false;
726 }
727
728 /* Return -1 if FILE is an unwritable non-symlink,
729    0 if it is writable or some other type of file,
730    a positive error number if there is some problem in determining the answer.
731    Set *BUF to the file status.
732    This is to avoid calling euidaccess when FILE is a symlink.  */
733 static int
734 write_protected_non_symlink (int fd_cwd,
735                              char const *file,
736                              Dirstack_state const *ds,
737                              struct stat *buf)
738 {
739   if (can_write_any_file ())
740     return 0;
741   if (cache_fstatat (fd_cwd, file, buf, AT_SYMLINK_NOFOLLOW) != 0)
742     return errno;
743   if (S_ISLNK (buf->st_mode))
744     return 0;
745   /* Here, we know FILE is not a symbolic link.  */
746
747   /* In order to be reentrant -- i.e., to avoid changing the working
748      directory, and at the same time to be able to deal with alternate
749      access control mechanisms (ACLs, xattr-style attributes) and
750      arbitrarily deep trees -- we need a function like eaccessat, i.e.,
751      like Solaris' eaccess, but fd-relative, in the spirit of openat.  */
752
753   /* In the absence of a native eaccessat function, here are some of
754      the implementation choices [#4 and #5 were suggested by Paul Eggert]:
755      1) call openat with O_WRONLY|O_NOCTTY
756         Disadvantage: may create the file and doesn't work for directory,
757         may mistakenly report `unwritable' for EROFS or ACLs even though
758         perm bits say the file is writable.
759
760      2) fake eaccessat (save_cwd, fchdir, call euidaccess, restore_cwd)
761         Disadvantage: changes working directory (not reentrant) and can't
762         work if save_cwd fails.
763
764      3) if (euidaccess (full_filename (file), W_OK) == 0)
765         Disadvantage: doesn't work if full_filename is too long.
766         Inefficient for very deep trees (O(Depth^2)).
767
768      4) If the full pathname is sufficiently short (say, less than
769         PATH_MAX or 8192 bytes, whichever is shorter):
770         use method (3) (i.e., euidaccess (full_filename (file), W_OK));
771         Otherwise: vfork, fchdir in the child, run euidaccess in the
772         child, then the child exits with a status that tells the parent
773         whether euidaccess succeeded.
774
775         This avoids the O(N**2) algorithm of method (3), and it also avoids
776         the failure-due-to-too-long-file-names of method (3), but it's fast
777         in the normal shallow case.  It also avoids the lack-of-reentrancy
778         and the save_cwd problems.
779         Disadvantage; it uses a process slot for very-long file names,
780         and would be very slow for hierarchies with many such files.
781
782      5) If the full file name is sufficiently short (say, less than
783         PATH_MAX or 8192 bytes, whichever is shorter):
784         use method (3) (i.e., euidaccess (full_filename (file), W_OK));
785         Otherwise: look just at the file bits.  Perhaps issue a warning
786         the first time this occurs.
787
788         This is like (4), except for the "Otherwise" case where it isn't as
789         "perfect" as (4) but is considerably faster.  It conforms to current
790         POSIX, and is uniformly better than what Solaris and FreeBSD do (they
791         mess up with long file names). */
792
793   {
794     /* This implements #5: */
795     size_t file_name_len
796       = obstack_object_size (&ds->dir_stack) + strlen (file);
797
798     if (MIN (PATH_MAX, 8192) <= file_name_len)
799       return - euidaccess_stat (buf, W_OK);
800     if (euidaccess (full_filename (file), W_OK) == 0)
801       return 0;
802     if (errno == EACCES)
803       return -1;
804
805     /* Perhaps some other process has removed the file, or perhaps this
806        is a buggy NFS client.  */
807     return errno;
808   }
809 }
810
811 /* Prompt whether to remove FILENAME, if required via a combination of
812    the options specified by X and/or file attributes.  If the file may
813    be removed, return RM_OK.  If the user declines to remove the file,
814    return RM_USER_DECLINED.  If not ignoring missing files and we
815    cannot lstat FILENAME, then return RM_ERROR.
816
817    *PDIRENT_TYPE is the type of the directory entry; update it to DT_DIR
818    or DT_LNK as needed.  *SBUF is the file's status.
819
820    Depending on MODE, ask whether to `descend into' or to `remove' the
821    directory FILENAME.  MODE is ignored when FILENAME is not a directory.
822    Set *IS_EMPTY to T_YES if FILENAME is an empty directory, and it is
823    appropriate to try to remove it with rmdir (e.g. recursive mode).
824    Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR.  */
825 static enum RM_status
826 prompt (int fd_cwd, Dirstack_state const *ds, char const *filename,
827         int *pdirent_type, struct stat *sbuf,
828         struct rm_options const *x, enum Prompt_action mode,
829         Ternary *is_empty)
830 {
831   int write_protected = 0;
832   int dirent_type = *pdirent_type;
833
834   *is_empty = T_UNKNOWN;
835
836   if (x->interactive == RMI_NEVER)
837     return RM_OK;
838
839   if (!x->ignore_missing_files
840       && ((x->interactive == RMI_ALWAYS) || x->stdin_tty)
841       && dirent_type != DT_LNK)
842     write_protected = write_protected_non_symlink (fd_cwd, filename, ds, sbuf);
843
844   if (write_protected || x->interactive == RMI_ALWAYS)
845     {
846       if (write_protected <= 0 && dirent_type == DT_UNKNOWN)
847         {
848           if (cache_fstatat (fd_cwd, filename, sbuf, AT_SYMLINK_NOFOLLOW) == 0)
849             {
850               if (S_ISLNK (sbuf->st_mode))
851                 dirent_type = DT_LNK;
852               else if (S_ISDIR (sbuf->st_mode))
853                 dirent_type = DT_DIR;
854               /* Otherwise it doesn't matter, so leave it DT_UNKNOWN.  */
855               *pdirent_type = dirent_type;
856             }
857           else
858             {
859               /* This happens, e.g., with `rm '''.  */
860               write_protected = errno;
861             }
862         }
863
864       if (write_protected <= 0)
865         switch (dirent_type)
866           {
867           case DT_LNK:
868             /* Using permissions doesn't make sense for symlinks.  */
869             if (x->interactive != RMI_ALWAYS)
870               return RM_OK;
871             break;
872
873           case DT_DIR:
874             if (!x->recursive)
875               write_protected = EISDIR;
876             break;
877           }
878
879       char const *quoted_name = quote (full_filename (filename));
880
881       if (0 < write_protected)
882         {
883           error (0, write_protected, _("cannot remove %s"), quoted_name);
884           return RM_ERROR;
885         }
886
887       /* Issue the prompt.  */
888       /* FIXME: use a variant of error (instead of fprintf) that doesn't
889          append a newline.  Then we won't have to declare program_name in
890          this file.  */
891       if (dirent_type == DT_DIR
892           && mode == PA_DESCEND_INTO_DIR
893           && ((*is_empty = (is_empty_dir (fd_cwd, filename) ? T_YES : T_NO))
894               == T_NO))
895         fprintf (stderr,
896                  (write_protected
897                   ? _("%s: descend into write-protected directory %s? ")
898                   : _("%s: descend into directory %s? ")),
899                  program_name, quoted_name);
900       else
901         {
902           if (cache_fstatat (fd_cwd, filename, sbuf, AT_SYMLINK_NOFOLLOW) != 0)
903             {
904               error (0, errno, _("cannot remove %s"), quoted_name);
905               return RM_ERROR;
906             }
907
908           /* TRANSLATORS: You may find it more convenient to translate
909              the equivalent of _("%s: remove %s (write-protected) %s? ").
910              It should avoid grammatical problems with the output
911              of file_type.  */
912           fprintf (stderr,
913                    (write_protected
914                     ? _("%s: remove write-protected %s %s? ")
915                     : _("%s: remove %s %s? ")),
916                    program_name, file_type (sbuf), quoted_name);
917         }
918
919       if (!yesno ())
920         return RM_USER_DECLINED;
921     }
922   return RM_OK;
923 }
924
925 /* Return true if FILENAME is a directory (and not a symlink to a directory).
926    Otherwise, including the case in which lstat fails, return false.
927    *ST is FILENAME's tstatus.
928    Do not modify errno.  */
929 static inline bool
930 is_dir_lstat (int fd_cwd, char const *filename, struct stat *st)
931 {
932   int saved_errno = errno;
933   bool is_dir =
934     (cache_fstatat (fd_cwd, filename, st, AT_SYMLINK_NOFOLLOW) == 0
935      && S_ISDIR (st->st_mode));
936   errno = saved_errno;
937   return is_dir;
938 }
939
940 #define DO_UNLINK(Fd_cwd, Filename, X)                                  \
941   do                                                                    \
942     {                                                                   \
943       if (unlinkat (Fd_cwd, Filename, 0) == 0)                          \
944         {                                                               \
945           if ((X)->verbose)                                             \
946             printf (_("removed %s\n"), quote (full_filename (Filename))); \
947           return RM_OK;                                                 \
948         }                                                               \
949                                                                         \
950       if (ignorable_missing (X, errno))                                 \
951         return RM_OK;                                                   \
952     }                                                                   \
953   while (0)
954
955 #define DO_RMDIR(Fd_cwd, Filename, X)                   \
956   do                                                    \
957     {                                                   \
958       if (unlinkat (Fd_cwd, Filename, AT_REMOVEDIR) == 0) /* rmdir */ \
959         {                                               \
960           if ((X)->verbose)                             \
961             printf (_("removed directory: %s\n"),       \
962                     quote (full_filename (Filename)));  \
963           return RM_OK;                                 \
964         }                                               \
965                                                         \
966       if (ignorable_missing (X, errno))                 \
967         return RM_OK;                                   \
968                                                         \
969       if (errno == ENOTEMPTY || errno == EEXIST)        \
970         return RM_NONEMPTY_DIR;                         \
971     }                                                   \
972   while (0)
973
974 /* When a function like unlink, rmdir, or fstatat fails with an errno
975    value of ERRNUM, return true if the specified file system object
976    is guaranteed not to exist;  otherwise, return false.  */
977 static inline bool
978 nonexistent_file_errno (int errnum)
979 {
980   /* Do not include ELOOP here, since the specified file may indeed
981      exist, but be (in)accessible only via too long a symlink chain.
982      Likewise for ENAMETOOLONG, since rm -f ./././.../foo may fail
983      if the "..." part expands to a long enough sequence of "./"s,
984      even though ./foo does indeed exist.  */
985
986   switch (errnum)
987     {
988     case ENOENT:
989     case ENOTDIR:
990       return true;
991     default:
992       return false;
993     }
994 }
995
996 /* Encapsulate the test for whether the errno value, ERRNUM, is ignorable.  */
997 static inline bool
998 ignorable_missing (struct rm_options const *x, int errnum)
999 {
1000   return x->ignore_missing_files && nonexistent_file_errno (errnum);
1001 }
1002
1003 /* Remove the file or directory specified by FILENAME.
1004    Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
1005    But if FILENAME specifies a non-empty directory, return RM_NONEMPTY_DIR. */
1006
1007 static enum RM_status
1008 remove_entry (int fd_cwd, Dirstack_state const *ds, char const *filename,
1009               int dirent_type_arg, struct stat *st,
1010               struct rm_options const *x)
1011 {
1012   Ternary is_empty_directory;
1013   enum RM_status s = prompt (fd_cwd, ds, filename, &dirent_type_arg, st, x,
1014                              PA_DESCEND_INTO_DIR,
1015                              &is_empty_directory);
1016   int dirent_type = dirent_type_arg;
1017   if (s != RM_OK)
1018     return s;
1019
1020   /* Why bother with the following if/else block?  Because on systems with
1021      an unlink function that *can* unlink directories, we must determine the
1022      type of each entry before removing it.  Otherwise, we'd risk unlinking
1023      an entire directory tree simply by unlinking a single directory;  then
1024      all the storage associated with that hierarchy would not be freed until
1025      the next fsck.  Not nice.  To avoid that, on such slightly losing
1026      systems, we need to call lstat to determine the type of each entry,
1027      and that represents extra overhead that -- it turns out -- we can
1028      avoid on non-losing systems, since there, unlink will never remove
1029      a directory.  Also, on systems where unlink may unlink directories,
1030      we're forced to allow a race condition: we lstat a non-directory, then
1031      go to unlink it, but in the mean time, a malicious someone could have
1032      replaced it with a directory.  */
1033
1034   if (cannot_unlink_dir ())
1035     {
1036       if (dirent_type == DT_DIR && ! x->recursive)
1037         {
1038           error (0, EISDIR, _("cannot remove %s"),
1039                  quote (full_filename (filename)));
1040           return RM_ERROR;
1041         }
1042
1043       /* is_empty_directory is set iff it's ok to use rmdir.
1044          Note that it's set only in interactive mode -- in which case it's
1045          an optimization that arranges so that the user is asked just
1046          once whether to remove the directory.  */
1047       if (is_empty_directory == T_YES)
1048         DO_RMDIR (fd_cwd, filename, x);
1049
1050       /* If we happen to know that FILENAME is a directory, return now
1051          and let the caller remove it -- this saves the overhead of a failed
1052          unlink call.  If FILENAME is a command-line argument, then
1053          DIRENT_TYPE is DT_UNKNOWN so we'll first try to unlink it.
1054          Using unlink here is ok, because it cannot remove a
1055          directory.  */
1056       if (dirent_type == DT_DIR)
1057         return RM_NONEMPTY_DIR;
1058
1059       DO_UNLINK (fd_cwd, filename, x);
1060
1061       /* Upon a failed attempt to unlink a directory, most non-Linux systems
1062          set errno to the POSIX-required value EPERM.  In that case, change
1063          errno to EISDIR so that we emit a better diagnostic.  */
1064       if (! x->recursive && errno == EPERM && is_dir_lstat (fd_cwd,
1065                                                             filename, st))
1066         errno = EISDIR;
1067
1068       if (! x->recursive
1069           || (cache_stat_ok (st) && !S_ISDIR (st->st_mode)))
1070         {
1071           if (ignorable_missing (x, errno))
1072             return RM_OK;
1073
1074           /* Either --recursive is not in effect, or the file cannot be a
1075              directory.  Report the unlink problem and fail.  */
1076           error (0, errno, _("cannot remove %s"),
1077                  quote (full_filename (filename)));
1078           return RM_ERROR;
1079         }
1080       assert (!cache_stat_ok (st) || S_ISDIR (st->st_mode));
1081     }
1082   else
1083     {
1084       /* If we don't already know whether FILENAME is a directory,
1085          find out now.  Then, if it's a non-directory, we can use
1086          unlink on it.  */
1087
1088       if (dirent_type == DT_UNKNOWN)
1089         {
1090           if (fstatat (fd_cwd, filename, st, AT_SYMLINK_NOFOLLOW))
1091             {
1092               if (ignorable_missing (x, errno))
1093                 return RM_OK;
1094
1095               error (0, errno, _("cannot remove %s"),
1096                      quote (full_filename (filename)));
1097               return RM_ERROR;
1098             }
1099
1100           if (S_ISDIR (st->st_mode))
1101             dirent_type = DT_DIR;
1102         }
1103
1104       if (dirent_type == DT_DIR)
1105         {
1106           /* At this point, barring race conditions, FILENAME is known
1107              to be a non-directory, so it's ok to try to unlink it.  */
1108           DO_UNLINK (fd_cwd, filename, x);
1109
1110           /* unlink failed with some other error code.  report it.  */
1111           error (0, errno, _("cannot remove %s"),
1112                  quote (full_filename (filename)));
1113           return RM_ERROR;
1114         }
1115
1116       if (! x->recursive)
1117         {
1118           error (0, EISDIR, _("cannot remove %s"),
1119                  quote (full_filename (filename)));
1120           return RM_ERROR;
1121         }
1122
1123       if (is_empty_directory == T_YES)
1124         {
1125           DO_RMDIR (fd_cwd, filename, x);
1126           /* Don't diagnose any failure here.
1127              It'll be detected when the caller tries another way.  */
1128         }
1129     }
1130
1131   return RM_NONEMPTY_DIR;
1132 }
1133
1134 /* Given FD_CWD, the file descriptor for an open directory,
1135    open its subdirectory F (F is already `known' to be a directory,
1136    so if it is no longer one, someone is playing games), return a DIR*
1137    pointer for F, and put F's `stat' data in *SUBDIR_SB.
1138    Upon failure give a diagnostic and return NULL.
1139    If PREV_ERRNO is nonzero, it is the errno value from a preceding failed
1140    unlink- or rmdir-like system call -- use that value instead of ENOTDIR
1141    if an opened file turns out not to be a directory.  This is important
1142    when the preceding non-dir-unlink failed due to e.g., EPERM or EACCES.
1143    The caller must use a nonnnull CWD_ERRNO the first
1144    time this function is called for each command-line-specified directory.
1145    If CWD_ERRNO is not null, set *CWD_ERRNO to the appropriate error number
1146    if this function fails to restore the initial working directory.
1147    If it is null, report an error and exit if the working directory
1148    isn't restored.  */
1149 static DIR *
1150 fd_to_subdirp (int fd_cwd, char const *f,
1151                struct rm_options const *x, int prev_errno,
1152                struct stat *subdir_sb,
1153                int *cwd_errno ATTRIBUTE_UNUSED)
1154 {
1155   int open_flags = O_RDONLY | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK;
1156   int fd_sub = openat_permissive (fd_cwd, f, open_flags, 0, cwd_errno);
1157   int saved_errno;
1158
1159   /* Record dev/ino of F.  We may compare them against saved values
1160      to thwart any attempt to subvert the traversal.  They are also used
1161      to detect directory cycles.  */
1162   if (fd_sub < 0)
1163     return NULL;
1164   else if (fstat (fd_sub, subdir_sb) != 0)
1165     saved_errno = errno;
1166   else if (S_ISDIR (subdir_sb->st_mode))
1167     {
1168       DIR *subdir_dirp = fdopendir (fd_sub);
1169       if (subdir_dirp)
1170         return subdir_dirp;
1171       saved_errno = errno;
1172     }
1173   else
1174     saved_errno = (prev_errno ? prev_errno : ENOTDIR);
1175
1176   close (fd_sub);
1177   errno = saved_errno;
1178   return NULL;
1179 }
1180
1181 /* Remove entries in the directory open on DIRP
1182    Upon finding a directory that is both non-empty and that can be chdir'd
1183    into, return RM_OK and set *SUBDIR and fill in SUBDIR_SB, where
1184    SUBDIR is the malloc'd name of the subdirectory if the chdir succeeded,
1185    NULL otherwise (e.g., if opendir failed or if there was no subdirectory).
1186    Likewise, SUBDIR_SB is the result of calling lstat on SUBDIR.
1187    Return RM_OK if all entries are removed.  Return RM_ERROR if any
1188    entry cannot be removed.  Otherwise, return RM_USER_DECLINED if
1189    the user declines to remove at least one entry.  Remove as much as
1190    possible, continuing even if we fail to remove some entries.  */
1191 static enum RM_status
1192 remove_cwd_entries (DIR **dirp,
1193                     Dirstack_state *ds, char **subdir, struct stat *subdir_sb,
1194                     struct rm_options const *x)
1195 {
1196   struct AD_ent *top = AD_stack_top (ds);
1197   enum RM_status status = top->status;
1198   size_t n_unlinked_since_opendir_or_last_rewind = 0;
1199
1200   assert (VALID_STATUS (status));
1201   *subdir = NULL;
1202
1203   while (1)
1204     {
1205       struct dirent const *dp;
1206       enum RM_status tmp_status;
1207       const char *f;
1208
1209       /* Set errno to zero so we can distinguish between a readdir failure
1210          and when readdir simply finds that there are no more entries.  */
1211       errno = 0;
1212       dp = readdir_ignoring_dot_and_dotdot (*dirp);
1213       if (dp == NULL)
1214         {
1215           if (errno)
1216             {
1217               /* fall through */
1218             }
1219           else if (NEED_REWIND (n_unlinked_since_opendir_or_last_rewind))
1220             {
1221               /* Call rewinddir if we've called unlink or rmdir so many times
1222                  (since the opendir or the previous rewinddir) that this
1223                  NULL-return may be the symptom of a buggy readdir.  */
1224               rewinddir (*dirp);
1225               n_unlinked_since_opendir_or_last_rewind = 0;
1226               continue;
1227             }
1228           break;
1229         }
1230
1231       f = dp->d_name;
1232
1233       /* Skip files we've already tried/failed to remove.  */
1234       if ( ! AD_is_removable (ds, f))
1235         continue;
1236
1237       /* Pass dp->d_type info to remove_entry so the non-glibc
1238          case can decide whether to use unlink or chdir.
1239          Systems without the d_type member will have to endure
1240          the performance hit of first calling lstat F. */
1241       cache_stat_init (subdir_sb);
1242       tmp_status = remove_entry (dirfd (*dirp), ds, f,
1243                                  D_TYPE (dp), subdir_sb, x);
1244       switch (tmp_status)
1245         {
1246         case RM_OK:
1247           /* Count how many files we've unlinked since the initial
1248              opendir or the last rewinddir.  On buggy systems, if you
1249              remove too many, readdir returns NULL even though there
1250              remain unprocessed directory entries.  */
1251           ++n_unlinked_since_opendir_or_last_rewind;
1252           break;
1253
1254         case RM_ERROR:
1255         case RM_USER_DECLINED:
1256           AD_mark_as_unremovable (ds, f);
1257           UPDATE_STATUS (status, tmp_status);
1258           break;
1259
1260         case RM_NONEMPTY_DIR:
1261           {
1262             DIR *subdir_dirp = fd_to_subdirp (dirfd (*dirp), f,
1263                                               x, errno, subdir_sb, NULL);
1264             if (subdir_dirp == NULL)
1265               {
1266                 status = RM_ERROR;
1267
1268                 /* CAUTION: this test and diagnostic are identical to
1269                    those following the other use of fd_to_subdirp.  */
1270                 if (ignorable_missing (x, errno))
1271                   {
1272                     /* With -f, don't report "file not found".  */
1273                   }
1274                 else
1275                   {
1276                     /* Upon fd_to_subdirp failure, try to remove F directly,
1277                        in case it's just an empty directory.  */
1278                     int saved_errno = errno;
1279                     if (unlinkat (dirfd (*dirp), f, AT_REMOVEDIR) == 0)
1280                       status = RM_OK;
1281                     else
1282                       error (0, saved_errno,
1283                              _("cannot remove %s"), quote (full_filename (f)));
1284                   }
1285
1286                 if (status == RM_ERROR)
1287                   AD_mark_as_unremovable (ds, f);
1288                 break;
1289               }
1290
1291             *subdir = xstrdup (f);
1292             if (closedir (*dirp) != 0)
1293               {
1294                 error (0, 0, _("failed to close directory %s"),
1295                        quote (full_filename (".")));
1296                 status = RM_ERROR;
1297               }
1298             *dirp = subdir_dirp;
1299
1300             break;
1301           }
1302         }
1303
1304       /* Record status for this directory.  */
1305       UPDATE_STATUS (top->status, status);
1306
1307       if (*subdir)
1308         break;
1309     }
1310
1311   /* Ensure that *dirp is not NULL and that its file descriptor is valid.  */
1312   assert (*dirp != NULL);
1313   assert (0 <= fcntl (dirfd (*dirp), F_GETFD));
1314
1315   return status;
1316 }
1317
1318 /* Do this after each call to AD_push or AD_push_initial.
1319    Because the status = RM_OK bit is too remove-specific to
1320    go into the general-purpose AD_* package.  */
1321 #define AD_INIT_OTHER_MEMBERS()                 \
1322   do                                            \
1323     {                                           \
1324       AD_stack_top(ds)->status = RM_OK;         \
1325     }                                           \
1326   while (0)
1327
1328 /*  Remove the hierarchy rooted at DIR.
1329     Do that by changing into DIR, then removing its contents, then
1330     returning to the original working directory and removing DIR itself.
1331     Don't use recursion.  Be careful when using chdir ".." that we
1332     return to the same directory from which we came, if necessary.
1333     Return an RM_status value to indicate success or failure.  */
1334
1335 static enum RM_status
1336 remove_dir (int fd_cwd, Dirstack_state *ds, char const *dir,
1337             struct stat *dir_st,
1338             struct rm_options const *x, int *cwd_errno)
1339 {
1340   enum RM_status status;
1341   dev_t current_dev = dir_st->st_dev;
1342
1343   /* There is a race condition in that an attacker could replace the nonempty
1344      directory, DIR, with a symlink between the preceding call to rmdir
1345      (unlinkat, in our caller) and fd_to_subdirp's openat call.  But on most
1346      systems, even those without openat, this isn't a problem, since we ensure
1347      that opening a symlink will fail, when that is possible.  Otherwise,
1348      fd_to_subdirp's fstat, along with the `fstat' and the dev/ino
1349      comparison in AD_push ensure that we detect it and fail.  */
1350
1351   DIR *dirp = fd_to_subdirp (fd_cwd, dir, x, 0, dir_st, cwd_errno);
1352
1353   if (dirp == NULL)
1354     {
1355       /* CAUTION: this test and diagnostic are identical to
1356          those following the other use of fd_to_subdirp.  */
1357       if (ignorable_missing (x, errno))
1358         {
1359           /* With -f, don't report "file not found".  */
1360         }
1361       else
1362         {
1363           /* Upon fd_to_subdirp failure, try to remove DIR directly,
1364              in case it's just an empty directory.  */
1365           int saved_errno = errno;
1366           if (unlinkat (fd_cwd, dir, AT_REMOVEDIR) == 0)
1367             return RM_OK;
1368
1369           error (0, saved_errno,
1370                  _("cannot remove %s"), quote (full_filename (dir)));
1371         }
1372
1373       return RM_ERROR;
1374     }
1375
1376   if (ROOT_DEV_INO_CHECK (x->root_dev_ino, dir_st))
1377     {
1378       ROOT_DEV_INO_WARN (full_filename (dir));
1379       status = RM_ERROR;
1380       goto closedir_and_return;
1381     }
1382
1383   AD_push (dirfd (dirp), ds, dir, dir_st);
1384   AD_INIT_OTHER_MEMBERS ();
1385
1386   status = RM_OK;
1387
1388   while (1)
1389     {
1390       char *subdir = NULL;
1391       struct stat subdir_sb;
1392       enum RM_status tmp_status;
1393
1394       tmp_status = remove_cwd_entries (&dirp, ds, &subdir, &subdir_sb, x);
1395
1396       if (tmp_status != RM_OK)
1397         {
1398           UPDATE_STATUS (status, tmp_status);
1399           AD_mark_current_as_unremovable (ds);
1400         }
1401       if (subdir)
1402         {
1403           if ( ! x->one_file_system
1404                || subdir_sb.st_dev == current_dev)
1405             {
1406               AD_push (dirfd (dirp), ds, subdir, &subdir_sb);
1407               AD_INIT_OTHER_MEMBERS ();
1408               free (subdir);
1409               continue;
1410             }
1411
1412           /* Here, --one-file-system is in effect, and with remove_cwd_entries'
1413              traversal into the current directory, (known as SUBDIR, from ..),
1414              DIRP's device number is different from CURRENT_DEV.  Arrange not
1415              to do anything more with this hierarchy.  */
1416           error (0, 0, _("skipping %s, since it's on a different device"),
1417                  quote (full_filename (subdir)));
1418           free (subdir);
1419           AD_mark_current_as_unremovable (ds);
1420           tmp_status = RM_ERROR;
1421           UPDATE_STATUS (status, tmp_status);
1422         }
1423
1424       /* Execution reaches this point when we've removed the last
1425          removable entry from the current directory -- or, with
1426          --one-file-system, when the current directory is on a
1427          different file system.  */
1428       {
1429         int fd;
1430         /* The name of the directory that we have just processed,
1431            nominally removing all of its contents.  */
1432         char *empty_dir = AD_pop_and_chdir (dirp, &fd, ds);
1433         dirp = NULL;
1434         assert (fd != AT_FDCWD || AD_stack_height (ds) == 1);
1435
1436         /* Try to remove EMPTY_DIR only if remove_cwd_entries succeeded.  */
1437         if (tmp_status == RM_OK)
1438           {
1439             struct stat empty_st;
1440             Ternary is_empty;
1441             int dirent_type = DT_DIR;
1442             enum RM_status s = prompt (fd, ds, empty_dir, &dirent_type,
1443                                        cache_stat_init (&empty_st), x,
1444                                        PA_REMOVE_DIR, &is_empty);
1445
1446             if (s != RM_OK)
1447               {
1448                 free (empty_dir);
1449                 status = s;
1450                 if (fd != AT_FDCWD)
1451                   close (fd);
1452                 goto closedir_and_return;
1453               }
1454
1455             if (unlinkat (fd, empty_dir, AT_REMOVEDIR) == 0)
1456               {
1457                 if (x->verbose)
1458                   printf (_("removed directory: %s\n"),
1459                           quote (full_filename (empty_dir)));
1460               }
1461             else
1462               {
1463                 error (0, errno, _("cannot remove directory %s"),
1464                        quote (full_filename (empty_dir)));
1465                 AD_mark_as_unremovable (ds, empty_dir);
1466                 status = RM_ERROR;
1467                 UPDATE_STATUS (AD_stack_top(ds)->status, status);
1468               }
1469           }
1470
1471         free (empty_dir);
1472
1473         if (fd == AT_FDCWD)
1474           break;
1475
1476         dirp = fdopendir (fd);
1477         if (dirp == NULL)
1478           {
1479             error (0, errno, _("FATAL: cannot return to .. from %s"),
1480                    quote (full_filename (".")));
1481             close (fd);
1482             longjmp (ds->current_arg_jumpbuf, 1);
1483           }
1484       }
1485     }
1486
1487   /* If the first/final hash table of unremovable entries was used,
1488      free it here.  */
1489   AD_stack_pop (ds);
1490
1491  closedir_and_return:;
1492   if (dirp != NULL && closedir (dirp) != 0)
1493     {
1494       error (0, 0, _("failed to close directory %s"),
1495              quote (full_filename (".")));
1496       status = RM_ERROR;
1497     }
1498
1499   return status;
1500 }
1501
1502 /* Remove the file or directory specified by FILENAME.
1503    Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.  */
1504
1505 static enum RM_status
1506 rm_1 (Dirstack_state *ds, char const *filename,
1507       struct rm_options const *x, int *cwd_errno)
1508 {
1509   char const *base = last_component (filename);
1510   if (dot_or_dotdot (base))
1511     {
1512       error (0, 0, _(base == filename
1513                      ? "cannot remove directory %s"
1514                      : "cannot remove %s directory %s"),
1515              quote_n (0, base), quote_n (1, filename));
1516       return RM_ERROR;
1517     }
1518
1519   struct stat st;
1520   cache_stat_init (&st);
1521   cycle_check_init (&ds->cycle_check_state);
1522   if (x->root_dev_ino)
1523     {
1524       if (cache_fstatat (AT_FDCWD, filename, &st, AT_SYMLINK_NOFOLLOW) != 0)
1525         {
1526           if (ignorable_missing (x, errno))
1527             return RM_OK;
1528           error (0, errno, _("cannot remove %s"), quote (filename));
1529           return RM_ERROR;
1530         }
1531       if (SAME_INODE (st, *(x->root_dev_ino)))
1532         {
1533           error (0, 0, _("cannot remove root directory %s"), quote (filename));
1534           return RM_ERROR;
1535         }
1536     }
1537
1538   AD_push_initial (ds);
1539   AD_INIT_OTHER_MEMBERS ();
1540
1541   enum RM_status status = remove_entry (AT_FDCWD, ds, filename,
1542                                         DT_UNKNOWN, &st, x);
1543   if (status == RM_NONEMPTY_DIR)
1544     {
1545       /* In the event that remove_dir->remove_cwd_entries detects
1546          a directory cycle, arrange to fail, give up on this FILE, but
1547          continue on with any other arguments.  */
1548       if (setjmp (ds->current_arg_jumpbuf))
1549         status = RM_ERROR;
1550       else
1551         status = remove_dir (AT_FDCWD, ds, filename, &st, x, cwd_errno);
1552
1553       AD_stack_clear (ds);
1554     }
1555
1556   ds_clear (ds);
1557   return status;
1558 }
1559
1560 /* Remove all files and/or directories specified by N_FILES and FILE.
1561    Apply the options in X.  */
1562 extern enum RM_status
1563 rm (size_t n_files, char const *const *file, struct rm_options const *x)
1564 {
1565   enum RM_status status = RM_OK;
1566   Dirstack_state *ds = ds_init ();
1567   int cwd_errno = 0;
1568   size_t i;
1569
1570   for (i = 0; i < n_files; i++)
1571     {
1572       if (cwd_errno && IS_RELATIVE_FILE_NAME (file[i]))
1573         {
1574           error (0, 0, _("cannot remove relative-named %s"), quote (file[i]));
1575           status = RM_ERROR;
1576         }
1577       else
1578         {
1579           enum RM_status s = rm_1 (ds, file[i], x, &cwd_errno);
1580           assert (VALID_STATUS (s));
1581           UPDATE_STATUS (status, s);
1582         }
1583     }
1584
1585   if (x->require_restore_cwd && cwd_errno)
1586     {
1587       error (0, cwd_errno,
1588              _("cannot restore current working directory"));
1589       status = RM_ERROR;
1590     }
1591
1592   ds_free (ds);
1593
1594   return status;
1595 }