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