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