Correct my patch of 2004-10-18.
[platform/upstream/coreutils.git] / src / remove.c
1 /* remove.c -- core functions for removing files and directories
2    Copyright (C) 88, 90, 91, 1994-2004 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 "save-cwd.h"
27 #include "system.h"
28 #include "cycle-check.h"
29 #include "dirname.h"
30 #include "error.h"
31 #include "euidaccess.h"
32 #include "file-type.h"
33 #include "hash.h"
34 #include "hash-pjw.h"
35 #include "obstack.h"
36 #include "quote.h"
37 #include "remove.h"
38 #include "root-dev-ino.h"
39 #include "yesno.h"
40
41 /* Avoid shadowing warnings because these are functions declared
42    in dirname.h as well as locals used below.  */
43 #define dir_name rm_dir_name
44 #define dir_len rm_dir_len
45
46 #define obstack_chunk_alloc malloc
47 #define obstack_chunk_free free
48
49 /* FIXME: if possible, use autoconf...  */
50 #ifdef __GLIBC__
51 # define ROOT_CAN_UNLINK_DIRS 0
52 #else
53 # define ROOT_CAN_UNLINK_DIRS 1
54 #endif
55
56 #ifndef HAVE_WORKING_READDIR
57 # define HAVE_WORKING_READDIR 0
58 #endif
59
60 enum Ternary
61   {
62     T_UNKNOWN = 2,
63     T_NO,
64     T_YES
65   };
66 typedef enum Ternary Ternary;
67
68 /* The prompt function may be called twice for a given directory.
69    The first time, we ask whether to descend into it, and the
70    second time, we ask whether to remove it.  */
71 enum Prompt_action
72   {
73     PA_DESCEND_INTO_DIR = 2,
74     PA_REMOVE_DIR
75   };
76
77 /* On systems with an lstat function that accepts the empty string,
78    arrange to make lstat calls go through the wrapper function.  */
79 #if HAVE_LSTAT_EMPTY_STRING_BUG
80 int rpl_lstat (const char *, struct stat *);
81 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
82 #endif
83
84 /* Initial capacity of per-directory hash table of entries that have
85    been processed but not been deleted.  */
86 #define 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   union
104   {
105     /* The directory's dev/ino.  Used to ensure that `chdir some-subdir', then
106        `chdir ..' takes us back to the same directory from which we started).
107        (valid for all but the bottommost entry on the stack.  */
108     struct dev_ino a;
109
110     /* Enough information to restore the initial working directory.
111        (valid only for the bottommost entry on the stack)  */
112     struct saved_cwd saved_cwd;
113   } u;
114 };
115
116 extern char *program_name;
117
118 struct dirstack_state
119 {
120   /* The name of the directory (starting with and relative to a command
121      line argument) being processed.  When a subdirectory is entered, a new
122      component is appended (pushed).  Remove (pop) the top component
123      upon chdir'ing out of a directory.  This is used to form the full
124      name of the current directory or a file therein, when necessary.  */
125   struct obstack dir_stack;
126
127   /* Stack of lengths of directory names (including trailing slash)
128      appended to dir_stack.  We have to have a separate stack of lengths
129      (rather than just popping back to previous slash) because the first
130      element pushed onto the dir stack may contain slashes.  */
131   struct obstack len_stack;
132
133   /* Stack of active directory entries.
134      The first `active' directory is the initial working directory.
135      Additional active dirs are pushed onto the stack as we `chdir'
136      into each directory to be processed.  When finished with the
137      hierarchy under a directory, pop the active dir stack.  */
138   struct obstack Active_dir;
139
140   /* Used to detect cycles.  */
141   struct cycle_check_state cycle_check_state;
142
143   /* Target of a longjmp in case rm has to stop processing the current
144      command-line argument.  This happens 1) when rm detects a directory
145      cycle or 2) when it has processed one or more directories, but then
146      is unable to return to the initial working directory to process
147      additional `.'-relative command-line arguments.  */
148   jmp_buf current_arg_jumpbuf;
149 };
150 typedef struct dirstack_state Dirstack_state;
151
152 struct cwd_state
153 {
154   /* The value of errno after a failed save_cwd or restore_cwd.  */
155   int saved_errno;
156
157   /* Information (open file descriptor or absolute directory name)
158      required in order to restore the initial working directory.  */
159   struct saved_cwd saved_cwd;
160 };
161
162 static Dirstack_state *
163 ds_init ()
164 {
165   Dirstack_state *ds = xmalloc (sizeof *ds);
166   obstack_init (&ds->dir_stack);
167   obstack_init (&ds->len_stack);
168   obstack_init (&ds->Active_dir);
169   return ds;
170 }
171
172 static void
173 ds_free (Dirstack_state *ds)
174 {
175   obstack_free (&ds->dir_stack, NULL);
176   obstack_free (&ds->len_stack, NULL);
177   obstack_free (&ds->Active_dir, NULL);
178   free (ds);
179 }
180
181 static void
182 hash_freer (void *x)
183 {
184   free (x);
185 }
186
187 static bool
188 hash_compare_strings (void const *x, void const *y)
189 {
190   return STREQ (x, y) ? true : false;
191 }
192
193 static inline void
194 push_dir (Dirstack_state *ds, const char *dir_name)
195 {
196   size_t len = strlen (dir_name);
197
198   /* Append the string onto the stack.  */
199   obstack_grow (&ds->dir_stack, dir_name, len);
200
201   /* Append a trailing slash.  */
202   obstack_1grow (&ds->dir_stack, '/');
203
204   /* Add one for the slash.  */
205   ++len;
206
207   /* Push the length (including slash) onto its stack.  */
208   obstack_grow (&ds->len_stack, &len, sizeof (len));
209 }
210
211 /* Return the entry name of the directory on the top of the stack
212    in malloc'd storage.  */
213 static inline char *
214 top_dir (Dirstack_state const *ds)
215 {
216   size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
217   size_t *length = obstack_base (&ds->len_stack);
218   size_t top_len = length[n_lengths - 1];
219   char const *p = obstack_next_free (&ds->dir_stack) - top_len;
220   char *q = xmalloc (top_len);
221   memcpy (q, p, top_len - 1);
222   q[top_len - 1] = 0;
223   return q;
224 }
225
226 static inline void
227 pop_dir (Dirstack_state *ds)
228 {
229   size_t n_lengths = obstack_object_size (&ds->len_stack) / sizeof (size_t);
230   size_t *length = obstack_base (&ds->len_stack);
231   size_t top_len;
232
233   assert (n_lengths > 0);
234   top_len = length[n_lengths - 1];
235   assert (top_len >= 2);
236
237   /* Pop off the specified length of pathname.  */
238   assert (obstack_object_size (&ds->dir_stack) >= top_len);
239   obstack_blank (&ds->dir_stack, -top_len);
240
241   /* Pop the length stack, too.  */
242   assert (obstack_object_size (&ds->len_stack) >= sizeof (size_t));
243   obstack_blank (&ds->len_stack, -(int) sizeof (size_t));
244 }
245
246 /* Copy the SRC_LEN bytes of data beginning at SRC into the DST_LEN-byte
247    buffer, DST, so that the last source byte is at the end of the destination
248    buffer.  If SRC_LEN is longer than DST_LEN, then set *TRUNCATED.
249    Set *RESULT to point to the beginning of (the portion of) the source data
250    in DST.  Return the number of bytes remaining in the destination buffer.  */
251
252 static size_t
253 right_justify (char *dst, size_t dst_len, const char *src, size_t src_len,
254                char **result, bool *truncated)
255 {
256   const char *sp;
257   char *dp;
258
259   if (src_len <= dst_len)
260     {
261       sp = src;
262       dp = dst + (dst_len - src_len);
263       *truncated = false;
264     }
265   else
266     {
267       sp = src + (src_len - dst_len);
268       dp = dst;
269       src_len = dst_len;
270       *truncated = true;
271     }
272
273   *result = memcpy (dp, sp, src_len);
274   return dst_len - src_len;
275 }
276
277 /* Using the global directory name obstack, create the full path to FILENAME.
278    Return it in sometimes-realloc'd space that should not be freed by the
279    caller.  Realloc as necessary.  If realloc fails, use a static buffer
280    and put as long a suffix in that buffer as possible.  */
281
282 #define full_filename(Filename) full_filename_ (ds, Filename)
283 static char *
284 full_filename_ (Dirstack_state const *ds, const char *filename)
285 {
286   static char *buf = NULL;
287   static size_t n_allocated = 0;
288
289   size_t dir_len = obstack_object_size (&ds->dir_stack);
290   char *dir_name = obstack_base (&ds->dir_stack);
291   size_t n_bytes_needed;
292   size_t filename_len;
293
294   filename_len = strlen (filename);
295   n_bytes_needed = dir_len + filename_len + 1;
296
297   if (n_allocated < n_bytes_needed)
298     {
299       /* This code requires that realloc accept NULL as the first arg.
300          This function must not use xrealloc.  Otherwise, an out-of-memory
301          error involving a file name to be expanded here wouldn't ever
302          be issued.  Use realloc and fall back on using a static buffer
303          if memory allocation fails.  */
304       char *new_buf = realloc (buf, n_bytes_needed);
305       n_allocated = n_bytes_needed;
306
307       if (new_buf == NULL)
308         {
309 #define SBUF_SIZE 512
310 #define ELLIPSES_PREFIX "[...]"
311           static char static_buf[SBUF_SIZE];
312           bool truncated;
313           size_t len;
314           char *p;
315
316           free (buf);
317           len = right_justify (static_buf, SBUF_SIZE, filename,
318                                filename_len + 1, &p, &truncated);
319           right_justify (static_buf, len, dir_name, dir_len, &p, &truncated);
320           if (truncated)
321             {
322               memcpy (static_buf, ELLIPSES_PREFIX,
323                       sizeof (ELLIPSES_PREFIX) - 1);
324             }
325           return p;
326         }
327
328       buf = new_buf;
329     }
330
331   if (filename_len == 1 && *filename == '.' && dir_len)
332     {
333       /* FILENAME is just `.' and dir_len is nonzero.
334          Copy the directory part, omitting the trailing slash,
335          and append a trailing zero byte.  */
336       char *p = mempcpy (buf, dir_name, dir_len - 1);
337       *p = 0;
338     }
339   else
340     {
341       /* Copy the directory part, including trailing slash, and then
342          append the filename part, including a trailing zero byte.  */
343       memcpy (mempcpy (buf, dir_name, dir_len), filename, filename_len + 1);
344       assert (strlen (buf) + 1 == n_bytes_needed);
345     }
346
347   return buf;
348 }
349
350 static size_t
351 AD_stack_height (Dirstack_state const *ds)
352 {
353   return obstack_object_size (&ds->Active_dir) / sizeof (struct AD_ent);
354 }
355
356 static struct AD_ent *
357 AD_stack_top (Dirstack_state const *ds)
358 {
359   return (struct AD_ent *)
360     ((char *) obstack_next_free (&ds->Active_dir) - sizeof (struct AD_ent));
361 }
362
363 static void
364 AD_stack_pop (Dirstack_state *ds)
365 {
366   /* operate on Active_dir.  pop and free top entry */
367   struct AD_ent *top = AD_stack_top (ds);
368   if (top->unremovable)
369     hash_free (top->unremovable);
370   obstack_blank (&ds->Active_dir, -(int) sizeof (struct AD_ent));
371   pop_dir (ds);
372 }
373
374 /* chdir `up' one level.
375    Whenever using chdir '..', verify that the post-chdir
376    dev/ino numbers for `.' match the saved ones.
377    Set *PREV_DIR to the name (in malloc'd storage) of the
378    directory (usually now empty) from which we're coming.
379    Return true if successful.  */
380 static bool
381 AD_pop_and_chdir (Dirstack_state *ds, char **prev_dir)
382 {
383   enum RM_status old_status = AD_stack_top(ds)->status;
384   struct AD_ent *top;
385
386   /* Get the name of the current (but soon to be `previous') directory
387      from the top of the stack.  */
388   *prev_dir = top_dir (ds);
389
390   AD_stack_pop (ds);
391   top = AD_stack_top (ds);
392
393   /* Propagate any failure to parent.  */
394   UPDATE_STATUS (top->status, old_status);
395
396   assert (AD_stack_height (ds));
397
398   if (1 < AD_stack_height (ds))
399     {
400       struct stat sb;
401
402       /* We can give a better diagnostic here, since the target is relative. */
403       if (chdir ("..") != 0)
404         {
405           error (EXIT_FAILURE, errno,
406                  _("cannot chdir from %s to .."),
407                  quote (full_filename (".")));
408         }
409
410       if (lstat (".", &sb))
411         error (EXIT_FAILURE, errno,
412                _("cannot lstat `.' in %s"), quote (full_filename (".")));
413
414       /*  Ensure that post-chdir dev/ino match the stored ones.  */
415       if ( ! SAME_INODE (sb, top->u.a))
416         error (EXIT_FAILURE, 0,
417                _("%s changed dev/ino"), quote (full_filename (".")));
418     }
419   else
420     {
421       if (restore_cwd (&top->u.saved_cwd) != 0)
422         {
423           /* failed to return to initial working directory */
424           return false;
425         }
426     }
427
428   return true;
429 }
430
431 /* Initialize *HT if it is NULL.
432    Insert FILENAME into HT.  */
433 static void
434 AD_mark_helper (Hash_table **ht, char const *filename)
435 {
436   if (*ht == NULL)
437     {
438       *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw,
439                              hash_compare_strings, hash_freer);
440       if (*ht == NULL)
441         xalloc_die ();
442     }
443   if (! hash_insert (*ht, filename))
444     xalloc_die ();
445 }
446
447 /* Mark FILENAME (in current directory) as unremovable.  */
448 static void
449 AD_mark_as_unremovable (Dirstack_state *ds, char const *filename)
450 {
451   AD_mark_helper (&AD_stack_top(ds)->unremovable, xstrdup (filename));
452 }
453
454 /* Mark the current directory as unremovable.  I.e., mark the entry
455    in the parent directory corresponding to `.'.
456    This happens e.g., when an opendir fails and the only name
457    the caller has conveniently at hand is `.'.  */
458 static void
459 AD_mark_current_as_unremovable (Dirstack_state *ds)
460 {
461   struct AD_ent *top = AD_stack_top (ds);
462   const char *curr = top_dir (ds);
463
464   assert (1 < AD_stack_height (ds));
465
466   --top;
467   AD_mark_helper (&top->unremovable, curr);
468 }
469
470 /* Push the initial cwd info onto the stack.
471    This will always be the bottommost entry on the stack.  */
472 static void
473 AD_push_initial (Dirstack_state *ds, struct saved_cwd const *cwd)
474 {
475   struct AD_ent *top;
476
477   /* Extend the stack.  */
478   obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
479
480   /* Fill in the new values.  */
481   top = AD_stack_top (ds);
482   top->u.saved_cwd = *cwd;
483   top->unremovable = NULL;
484 }
485
486 /* Push info about the current working directory (".") onto the
487    active directory stack.  DIR is the ./-relative name through
488    which we've just `chdir'd to this directory.  DIR_SB_FROM_PARENT
489    is the result of calling lstat on DIR from the parent of DIR.  */
490 static void
491 AD_push (Dirstack_state *ds, char const *dir,
492          struct stat const *dir_sb_from_parent)
493 {
494   struct stat sb;
495   struct AD_ent *top;
496
497   push_dir (ds, dir);
498
499   if (lstat (".", &sb))
500     error (EXIT_FAILURE, errno,
501            _("cannot lstat `.' in %s"), quote (full_filename (".")));
502
503   if ( ! SAME_INODE (sb, *dir_sb_from_parent))
504     error (EXIT_FAILURE, 0,
505            _("%s changed dev/ino"), quote (full_filename (".")));
506
507   /* Extend the stack.  */
508   obstack_blank (&ds->Active_dir, sizeof (struct AD_ent));
509
510   /* Fill in the new values.  */
511   top = AD_stack_top (ds);
512   top->u.a.st_dev = sb.st_dev;
513   top->u.a.st_ino = sb.st_ino;
514   top->unremovable = NULL;
515 }
516
517 static bool
518 AD_is_removable (Dirstack_state const *ds, char const *file)
519 {
520   struct AD_ent *top = AD_stack_top (ds);
521   return ! (top->unremovable && hash_lookup (top->unremovable, file));
522 }
523
524 /* Return true if DIR is determined to be an empty directory
525    or if opendir or readdir fails.  */
526 static bool
527 is_empty_dir (char const *dir)
528 {
529   DIR *dirp = opendir (dir);
530   struct dirent const *dp;
531   int saved_errno;
532
533   if (dirp == NULL)
534     return false;
535
536   errno = 0;
537   dp = readdir_ignoring_dot_and_dotdot (dirp);
538   saved_errno = errno;
539   closedir (dirp);
540   if (dp != NULL)
541     return false;
542   return saved_errno == 0 ? true : false;
543 }
544
545 /* Return true if FILE is not a symbolic link and it is not writable.
546    Also return true if FILE cannot be lstat'ed.  Otherwise, return false.
547    If lstat succeeds, set *BUF_P to BUF.
548    This is to avoid calling euidaccess when FILE is a symlink.  */
549 static bool
550 write_protected_non_symlink (char const *file,
551                              struct stat **buf_p,
552                              struct stat *buf)
553 {
554   if (lstat (file, buf) != 0)
555     return false;
556   *buf_p = buf;
557   if (S_ISLNK (buf->st_mode))
558     return false;
559   return euidaccess (file, W_OK) == -1 && errno == EACCES;
560 }
561
562 /* Prompt whether to remove FILENAME, if required via a combination of
563    the options specified by X and/or file attributes.  If the file may
564    be removed, return RM_OK.  If the user declines to remove the file,
565    return RM_USER_DECLINED.  If not ignoring missing files and we
566    cannot lstat FILENAME, then return RM_ERROR.
567
568    Depending on MODE, ask whether to `descend into' or to `remove' the
569    directory FILENAME.  MODE is ignored when FILENAME is not a directory.
570    Set *IS_EMPTY to T_YES if FILENAME is an empty directory, and it is
571    appropriate to try to remove it with rmdir (e.g. recursive mode).
572    Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR.
573    Set *IS_DIR to T_YES or T_NO if we happen to determine whether
574    FILENAME is a directory.  */
575 static enum RM_status
576 prompt (Dirstack_state const *ds, char const *filename,
577         struct rm_options const *x, enum Prompt_action mode,
578         Ternary *is_dir, Ternary *is_empty)
579 {
580   bool write_protected = false;
581   struct stat *sbuf = NULL;
582   struct stat buf;
583
584   *is_empty = T_UNKNOWN;
585   *is_dir = T_UNKNOWN;
586
587   if (((!x->ignore_missing_files & (x->interactive | x->stdin_tty))
588        && (write_protected = write_protected_non_symlink (filename,
589                                                           &sbuf, &buf)))
590       || x->interactive)
591     {
592       if (sbuf == NULL)
593         {
594           sbuf = &buf;
595           if (lstat (filename, sbuf))
596             {
597               /* lstat failed.  This happens e.g., with `rm '''.  */
598               error (0, errno, _("cannot lstat %s"),
599                      quote (full_filename (filename)));
600               return RM_ERROR;
601             }
602         }
603
604       if (S_ISDIR (sbuf->st_mode) && !x->recursive)
605         {
606           error (0, EISDIR, _("cannot remove directory %s"),
607                  quote (full_filename (filename)));
608           return RM_ERROR;
609         }
610
611       /* Using permissions doesn't make sense for symlinks.  */
612       if (S_ISLNK (sbuf->st_mode))
613         {
614           if ( ! x->interactive)
615             return RM_OK;
616           write_protected = false;
617         }
618
619       /* Issue the prompt.  */
620       {
621         char const *quoted_name = quote (full_filename (filename));
622
623         *is_dir = (S_ISDIR (sbuf->st_mode) ? T_YES : T_NO);
624
625         /* FIXME: use a variant of error (instead of fprintf) that doesn't
626            append a newline.  Then we won't have to declare program_name in
627            this file.  */
628         if (S_ISDIR (sbuf->st_mode)
629             && x->recursive
630             && mode == PA_DESCEND_INTO_DIR
631             && ((*is_empty = (is_empty_dir (filename) ? T_YES : T_NO))
632                 == T_NO))
633           fprintf (stderr,
634                    (write_protected
635                     ? _("%s: descend into write-protected directory %s? ")
636                     : _("%s: descend into directory %s? ")),
637                    program_name, quoted_name);
638         else
639           {
640             /* TRANSLATORS: You may find it more convenient to translate
641                the equivalent of _("%s: remove %s (write-protected) %s? ").
642                It should avoid grammatical problems with the output
643                of file_type.  */
644             fprintf (stderr,
645                      (write_protected
646                       ? _("%s: remove write-protected %s %s? ")
647                       : _("%s: remove %s %s? ")),
648                      program_name, file_type (sbuf), quoted_name);
649           }
650
651         if (!yesno ())
652           return RM_USER_DECLINED;
653       }
654     }
655   return RM_OK;
656 }
657
658 #if HAVE_STRUCT_DIRENT_D_TYPE
659 # define DT_IS_DIR(D) ((D)->d_type == DT_DIR)
660 #else
661 /* Use this only if the member exists -- i.e., don't return 0.  */
662 # define DT_IS_DIR(D) do_not_use_this_macro
663 #endif
664
665 #define DO_UNLINK(Filename, X)                                          \
666   do                                                                    \
667     {                                                                   \
668       if (unlink (Filename) == 0)                                       \
669         {                                                               \
670           if ((X)->verbose)                                             \
671             printf (_("removed %s\n"), quote (full_filename (Filename))); \
672           return RM_OK;                                                 \
673         }                                                               \
674                                                                         \
675       if (errno == ENOENT && (X)->ignore_missing_files)                 \
676         return RM_OK;                                                   \
677     }                                                                   \
678   while (0)
679
680 #define DO_RMDIR(Filename, X)                           \
681   do                                                    \
682     {                                                   \
683       if (rmdir (Filename) == 0)                        \
684         {                                               \
685           if ((X)->verbose)                             \
686             printf (_("removed directory: %s\n"),       \
687                     quote (full_filename (Filename)));  \
688           return RM_OK;                                 \
689         }                                               \
690                                                         \
691       if (errno == ENOENT && (X)->ignore_missing_files) \
692         return RM_OK;                                   \
693                                                         \
694       if (errno == ENOTEMPTY || errno == EEXIST)        \
695         return RM_NONEMPTY_DIR;                         \
696     }                                                   \
697   while (0)
698
699 /* Remove the file or directory specified by FILENAME.
700    Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
701    But if FILENAME specifies a non-empty directory, return RM_NONEMPTY_DIR. */
702
703 static enum RM_status
704 remove_entry (Dirstack_state const *ds, char const *filename,
705               struct rm_options const *x, struct dirent const *dp)
706 {
707   Ternary is_dir;
708   Ternary is_empty_directory;
709   enum RM_status s = prompt (ds, filename, x, PA_DESCEND_INTO_DIR,
710                              &is_dir, &is_empty_directory);
711
712   if (s != RM_OK)
713     return s;
714
715   /* Why bother with the following #if/#else block?  Because on systems with
716      an unlink function that *can* unlink directories, we must determine the
717      type of each entry before removing it.  Otherwise, we'd risk unlinking an
718      entire directory tree simply by unlinking a single directory;  then all
719      the storage associated with that hierarchy would not be freed until the
720      next reboot.  Not nice.  To avoid that, on such slightly losing systems, we
721      need to call lstat to determine the type of each entry, and that represents
722      extra overhead that -- it turns out -- we can avoid on GNU-libc-based
723      systems, since there, unlink will never remove a directory.  */
724
725 #if ROOT_CAN_UNLINK_DIRS
726
727   /* If we don't already know whether FILENAME is a directory, find out now.
728      Then, if it's a non-directory, we can use unlink on it.  */
729   if (is_dir == T_UNKNOWN)
730     {
731 # if HAVE_STRUCT_DIRENT_D_TYPE
732       if (dp && dp->d_type != DT_UNKNOWN)
733         is_dir = DT_IS_DIR (dp) ? T_YES : T_NO;
734       else
735 # endif
736         {
737           struct stat sbuf;
738           if (lstat (filename, &sbuf))
739             {
740               if (errno == ENOENT && x->ignore_missing_files)
741                 return RM_OK;
742
743               error (0, errno,
744                      _("cannot lstat %s"), quote (full_filename (filename)));
745               return RM_ERROR;
746             }
747
748           is_dir = S_ISDIR (sbuf.st_mode) ? T_YES : T_NO;
749         }
750     }
751
752   if (is_dir == T_NO)
753     {
754       /* At this point, barring race conditions, FILENAME is known
755          to be a non-directory, so it's ok to try to unlink it.  */
756       DO_UNLINK (filename, x);
757
758       /* unlink failed with some other error code.  report it.  */
759       error (0, errno, _("cannot remove %s"),
760              quote (full_filename (filename)));
761       return RM_ERROR;
762     }
763
764   if (! x->recursive)
765     {
766       error (0, EISDIR, _("cannot remove directory %s"),
767              quote (full_filename (filename)));
768       return RM_ERROR;
769     }
770
771   if (is_empty_directory == T_YES)
772     {
773       DO_RMDIR (filename, x);
774       /* Don't diagnose any failure here.
775          It'll be detected when the caller tries another way.  */
776     }
777
778
779 #else /* ! ROOT_CAN_UNLINK_DIRS */
780
781   if (is_dir == T_YES && ! x->recursive)
782     {
783       error (0, EISDIR, _("cannot remove directory %s"),
784              quote (full_filename (filename)));
785       return RM_ERROR;
786     }
787
788   /* is_empty_directory is set iff it's ok to use rmdir.
789      Note that it's set only in interactive mode -- in which case it's
790      an optimization that arranges so that the user is asked just
791      once whether to remove the directory.  */
792   if (is_empty_directory == T_YES)
793     DO_RMDIR (filename, x);
794
795   /* If we happen to know that FILENAME is a directory, return now
796      and let the caller remove it -- this saves the overhead of a failed
797      unlink call.  If FILENAME is a command-line argument, then dp is NULL,
798      so we'll first try to unlink it.  Using unlink here is ok, because it
799      cannot remove a directory.  */
800   if ((dp && DT_IS_DIR (dp)) || is_dir == T_YES)
801     return RM_NONEMPTY_DIR;
802
803   DO_UNLINK (filename, x);
804
805   if (! x->recursive
806       || errno == ENOENT || errno == ENOTDIR
807       || errno == ELOOP || errno == ENAMETOOLONG)
808     {
809       /* Either --recursive is not in effect, or the file cannot be a
810          directory.  Report the unlink problem and fail.  */
811       error (0, errno, _("cannot remove %s"),
812              quote (full_filename (filename)));
813       return RM_ERROR;
814     }
815 #endif
816
817   return RM_NONEMPTY_DIR;
818 }
819
820 /* Remove entries in `.', the current working directory (cwd).
821    Upon finding a directory that is both non-empty and that can be chdir'd
822    into, return RM_OK and set *SUBDIR and fill in SUBDIR_SB, where
823    SUBDIR is the malloc'd name of the subdirectory if the chdir succeeded,
824    NULL otherwise (e.g., if opendir failed or if there was no subdirectory).
825    Likewise, SUBDIR_SB is the result of calling lstat on SUBDIR.
826    Return RM_OK if all entries are removed.  Return RM_ERROR if any
827    entry cannot be removed.  Otherwise, return RM_USER_DECLINED if
828    the user declines to remove at least one entry.  Remove as much as
829    possible, continuing even if we fail to remove some entries.  */
830 static enum RM_status
831 remove_cwd_entries (Dirstack_state *ds, char **subdir, struct stat *subdir_sb,
832                     struct rm_options const *x)
833 {
834   DIR *dirp = opendir (".");
835   struct AD_ent *top = AD_stack_top (ds);
836   enum RM_status status = top->status;
837   bool need_rewinddir = false;
838
839   assert (VALID_STATUS (status));
840   *subdir = NULL;
841
842   if (dirp == NULL)
843     {
844       if (errno != ENOENT || !x->ignore_missing_files)
845         {
846           error (0, errno, _("cannot open directory %s"),
847                  quote (full_filename (".")));
848           return RM_ERROR;
849         }
850     }
851
852   while (1)
853     {
854       struct dirent const *dp;
855       enum RM_status tmp_status;
856       const char *f;
857
858       /* Set errno to zero so we can distinguish between a readdir failure
859          and when readdir simply finds that there are no more entries.  */
860       errno = 0;
861       if ((dp = readdir_ignoring_dot_and_dotdot (dirp)) == NULL)
862         {
863           if (errno)
864             {
865               /* Save/restore errno across closedir call.  */
866               int e = errno;
867               closedir (dirp);
868               errno = e;
869
870               /* Arrange to give a diagnostic after exiting this loop.  */
871               dirp = NULL;
872             }
873           else if (need_rewinddir)
874             {
875               /* On buggy systems, call rewinddir if we've called unlink
876                  or rmdir since the opendir or a previous rewinddir.  */
877               rewinddir (dirp);
878               need_rewinddir = false;
879               continue;
880             }
881           break;
882         }
883
884       f = dp->d_name;
885
886       /* Skip files we've already tried/failed to remove.  */
887       if ( ! AD_is_removable (ds, f))
888         continue;
889
890       /* Pass dp->d_type info to remove_entry so the non-glibc
891          case can decide whether to use unlink or chdir.
892          Systems without the d_type member will have to endure
893          the performance hit of first calling lstat F. */
894       tmp_status = remove_entry (ds, f, x, dp);
895       switch (tmp_status)
896         {
897         case RM_OK:
898           /* On buggy systems, record the fact that we've just
899              removed a directory entry.  */
900           need_rewinddir = ! HAVE_WORKING_READDIR;
901           break;
902
903         case RM_ERROR:
904         case RM_USER_DECLINED:
905           AD_mark_as_unremovable (ds, f);
906           UPDATE_STATUS (status, tmp_status);
907           break;
908
909         case RM_NONEMPTY_DIR:
910           {
911             /* Save a copy of errno, in case the preceding unlink (from
912                remove_entry's DO_UNLINK) of a non-directory failed.  */
913             int saved_errno = errno;
914
915             /* Record dev/ino of F so that we can compare
916                that with dev/ino of `.' after the chdir.
917                This dev/ino pair is also used in cycle detection.  */
918             if (lstat (f, subdir_sb))
919               error (EXIT_FAILURE, errno, _("cannot lstat %s"),
920                      quote (full_filename (f)));
921
922             errno = ENOTDIR;
923             if (! S_ISDIR (subdir_sb->st_mode) || chdir (f) != 0)
924               {
925                 /* It is much more common that we reach this point for an
926                    inaccessible directory.  Hence the second diagnostic, below.
927                    However it is also possible that F is a non-directory.
928                    That can happen when we use the `! ROOT_CAN_UNLINK_DIRS'
929                    block of code and when DO_UNLINK fails due to EPERM.
930                    In that case, give a better diagnostic.  */
931                 if (errno == ENOTDIR)
932                   error (0, saved_errno, _("cannot remove %s"),
933                          quote (full_filename (f)));
934                 else
935                   error (0, errno, _("cannot chdir from %s to %s"),
936                          quote_n (0, full_filename (".")), quote_n (1, f));
937                 AD_mark_as_unremovable (ds, f);
938                 status = RM_ERROR;
939                 break;
940               }
941             if (cycle_check (&ds->cycle_check_state, subdir_sb))
942               {
943                 error (0, 0, _("\
944 WARNING: Circular directory structure.\n\
945 This almost certainly means that you have a corrupted file system.\n\
946 NOTIFY YOUR SYSTEM MANAGER.\n\
947 The following directory is part of the cycle:\n  %s\n"),
948                        quote (full_filename (".")));
949                 longjmp (ds->current_arg_jumpbuf, 1);
950               }
951
952             *subdir = xstrdup (f);
953             break;
954           }
955         }
956
957       /* Record status for this directory.  */
958       UPDATE_STATUS (top->status, status);
959
960       if (*subdir)
961         break;
962     }
963
964   if (dirp == NULL || CLOSEDIR (dirp) != 0)
965     {
966       /* Note that this diagnostic serves for both readdir
967          and closedir failures.  */
968       error (0, errno, _("reading directory %s"), quote (full_filename (".")));
969       status = RM_ERROR;
970     }
971
972   return status;
973 }
974
975 /* Do this after each call to AD_push or AD_push_initial.
976    Because the status = RM_OK bit is too remove-specific to
977    go into the general-purpose AD_* package.  */
978 #define AD_INIT_OTHER_MEMBERS()                 \
979   do                                            \
980     {                                           \
981       AD_stack_top(ds)->status = RM_OK;         \
982     }                                           \
983   while (0)
984
985 /*  Remove the hierarchy rooted at DIR.
986     Do that by changing into DIR, then removing its contents, then
987     returning to the original working directory and removing DIR itself.
988     Don't use recursion.  Be careful when using chdir ".." that we
989     return to the same directory from which we came, if necessary.
990     Return 1 for success, 0 if some file cannot be removed or if
991     a chdir fails.
992     If the initial working directory cannot be saved or restored,
993     record the offending errno value in (*CWD_STATE)->saved_errno.  */
994
995 static enum RM_status
996 remove_dir (Dirstack_state *ds, char const *dir, struct cwd_state **cwd_state,
997             struct rm_options const *x)
998 {
999   enum RM_status status;
1000   struct stat dir_sb;
1001
1002   /* Save any errno (from caller's failed remove_entry call), in case DIR
1003      is not a directory, so that we can give a reasonable diagnostic.  */
1004   int saved_errno = errno;
1005
1006   if (*cwd_state == NULL)
1007     {
1008       *cwd_state = xmalloc (sizeof **cwd_state);
1009
1010       if (save_cwd (&(*cwd_state)->saved_cwd) != 0)
1011         {
1012           (*cwd_state)->saved_errno = errno;
1013           assert (errno != 0);
1014
1015           /* Pretend we started from "/".  That is fine as long as there
1016              is no requirement to return to the original working directory.
1017              Use "/", not ".", so that we chdir out of a non-root target
1018              directory before attempting to remove it: some hosts don't let
1019              you remove a working directory.  */
1020           (*cwd_state)->saved_cwd.name = xstrdup ("/");
1021         }
1022       else
1023         (*cwd_state)->saved_errno = 0;
1024
1025       AD_push_initial (ds, &(*cwd_state)->saved_cwd);
1026       AD_INIT_OTHER_MEMBERS ();
1027     }
1028
1029   /* If we've failed to record and/or restore the initial working directory,
1030      and we're now trying to access a `.'-relative file name, then give a
1031      diagnostic, record the failure, and proceed with any subsequent
1032      command-line arguments.  */
1033   if ((*cwd_state)->saved_errno && IS_RELATIVE_FILE_NAME (dir))
1034     {
1035       error (0, (*cwd_state)->saved_errno, _("cannot remove directory %s"),
1036              quote (full_filename (dir)));
1037       longjmp (ds->current_arg_jumpbuf, 1);
1038     }
1039
1040   /* There is a race condition in that an attacker could replace the nonempty
1041      directory, DIR, with a symlink between the preceding call to rmdir
1042      (in our caller) and the chdir below.  However, the following lstat,
1043      along with the `stat (".",...' and dev/ino comparison in AD_push
1044      ensure that we detect it and fail.  */
1045
1046   if (lstat (dir, &dir_sb))
1047     {
1048       error (0, errno,
1049              _("cannot lstat %s"), quote (full_filename (dir)));
1050       return RM_ERROR;
1051     }
1052
1053   errno = ENOTDIR;
1054   if (! S_ISDIR (dir_sb.st_mode) || chdir (dir) != 0)
1055     {
1056       if (errno == ENOTDIR)
1057         {
1058           error (0, saved_errno,
1059                  _("cannot remove %s"), quote (full_filename (dir)));
1060         }
1061       else
1062         {
1063           error (0, errno,
1064                  _("cannot chdir from %s to %s"),
1065                  quote_n (0, full_filename (".")), quote_n (1, dir));
1066         }
1067       return RM_ERROR;
1068     }
1069
1070   if (ROOT_DEV_INO_CHECK (x->root_dev_ino, &dir_sb))
1071     {
1072       ROOT_DEV_INO_WARN (full_filename (dir));
1073       return 1;
1074     }
1075
1076   AD_push (ds, dir, &dir_sb);
1077   AD_INIT_OTHER_MEMBERS ();
1078
1079   status = RM_OK;
1080
1081   while (1)
1082     {
1083       char *subdir = NULL;
1084       struct stat subdir_sb;
1085       enum RM_status tmp_status = remove_cwd_entries (ds,
1086                                                       &subdir, &subdir_sb, x);
1087       if (tmp_status != RM_OK)
1088         {
1089           UPDATE_STATUS (status, tmp_status);
1090           AD_mark_current_as_unremovable (ds);
1091         }
1092       if (subdir)
1093         {
1094           AD_push (ds, subdir, &subdir_sb);
1095           AD_INIT_OTHER_MEMBERS ();
1096
1097           free (subdir);
1098           continue;
1099         }
1100
1101       /* Execution reaches this point when we've removed the last
1102          removable entry from the current directory.  */
1103       {
1104         /* This is the name of the directory that we have just
1105            returned from, after nominally removing all of its contents.  */
1106         char *empty_dir;
1107
1108         if (! AD_pop_and_chdir (ds, &empty_dir))
1109           (*cwd_state)->saved_errno = errno;
1110
1111         /* Note: the above may have failed due to restore_cwd failure.
1112            That failure may be harmless if x->require_restore_cwd is false,
1113            but we do have to remember that fact, including the errno value,
1114            so we can give an accurate diagnostic when reporting the failure
1115            to remove a subsequent relative-named command-line argument.  */
1116
1117         /* Try to remove D only if remove_cwd_entries succeeded.  */
1118         if (tmp_status == RM_OK)
1119           {
1120             /* This does a little more work than necessary when it actually
1121                prompts the user.  E.g., we already know that D is a directory
1122                and that it's almost certainly empty, yet we lstat it.
1123                But that's no big deal since we're interactive.  */
1124             Ternary is_dir;
1125             Ternary is_empty;
1126             enum RM_status s = prompt (ds, empty_dir, x, PA_REMOVE_DIR,
1127                                        &is_dir, &is_empty);
1128
1129             if (s != RM_OK)
1130               {
1131                 free (empty_dir);
1132                 return s;
1133               }
1134
1135             if (rmdir (empty_dir) == 0)
1136               {
1137                 if (x->verbose)
1138                   printf (_("removed directory: %s\n"),
1139                           quote (full_filename (empty_dir)));
1140               }
1141             else
1142               {
1143                 error (0, errno, _("cannot remove directory %s"),
1144                        quote (full_filename (empty_dir)));
1145                 AD_mark_as_unremovable (ds, empty_dir);
1146                 status = RM_ERROR;
1147                 UPDATE_STATUS (AD_stack_top(ds)->status, status);
1148               }
1149           }
1150
1151         free (empty_dir);
1152
1153         if (AD_stack_height (ds) == 1)
1154           break;
1155       }
1156     }
1157
1158   return status;
1159 }
1160
1161 /* Remove the file or directory specified by FILENAME.
1162    Return RM_OK if it is removed, and RM_ERROR or RM_USER_DECLINED if not.
1163    On input, the first time this function is called, CWD_STATE should be
1164    the address of a NULL pointer.  Do not modify it for any subsequent calls.
1165    On output, it is either that same NULL pointer or the address of
1166    a malloc'd `struct saved_cwd' that may be freed.  */
1167
1168 static enum RM_status
1169 rm_1 (Dirstack_state *ds, char const *filename,
1170       struct rm_options const *x, struct cwd_state **cwd_state)
1171 {
1172   char *base = base_name (filename);
1173   enum RM_status status;
1174
1175   if (DOT_OR_DOTDOT (base))
1176     {
1177       error (0, 0, _("cannot remove `.' or `..'"));
1178       return RM_ERROR;
1179     }
1180
1181   if (*cwd_state && (*cwd_state)->saved_errno
1182       && IS_RELATIVE_FILE_NAME (filename))
1183     {
1184       error (0, (*cwd_state)->saved_errno,
1185              _("cannot remove %s"), quote (filename));
1186       return RM_ERROR;
1187     }
1188
1189   status = remove_entry (ds, filename, x, NULL);
1190   if (status != RM_NONEMPTY_DIR)
1191     return status;
1192
1193   return remove_dir (ds, filename, cwd_state, x);
1194 }
1195
1196 /* Remove all files and/or directories specified by N_FILES and FILE.
1197    Apply the options in X.  */
1198 extern enum RM_status
1199 rm (size_t n_files, char const *const *file, struct rm_options const *x)
1200 {
1201   struct cwd_state *cwd_state = NULL;
1202   Dirstack_state *ds;
1203
1204   /* Put the following two variables in static storage, so they can't
1205      be clobbered by the potential longjmp into this function.  */
1206   static enum RM_status status = RM_OK;
1207   static size_t i;
1208
1209   ds = ds_init ();
1210
1211   for (i = 0; i < n_files; i++)
1212     {
1213       enum RM_status s;
1214       cycle_check_init (&ds->cycle_check_state);
1215       /* In the event that rm_1->remove_dir->remove_cwd_entries detects
1216          a directory cycle, arrange to fail, give up on this FILE, but
1217          continue on with any other arguments.  */
1218       if (setjmp (ds->current_arg_jumpbuf))
1219         s = RM_ERROR;
1220       else
1221         s = rm_1 (ds, file[i], x, &cwd_state);
1222       assert (VALID_STATUS (s));
1223       UPDATE_STATUS (status, s);
1224     }
1225
1226   if (x->require_restore_cwd && cwd_state && cwd_state->saved_errno != 0)
1227     {
1228       error (0, cwd_state->saved_errno,
1229              _("cannot restore current working directory"));
1230       status = RM_ERROR;
1231     }
1232
1233   ds_free (ds);
1234
1235   if (cwd_state && cwd_state->saved_errno == 0)
1236     free_cwd (&cwd_state->saved_cwd);
1237
1238   free (cwd_state);
1239
1240   return status;
1241 }