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