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