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