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