spell author names consistently
[platform/upstream/coreutils.git] / src / rm.c
1 /* `rm' file deletion utility for GNU.
2    Copyright (C) 88, 90, 91, 1994-2008 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Paul Rubin, David MacKenzie, and Richard Stallman.
18    Reworked to use chdir and avoid recursion by Jim Meyering.  */
19
20 /* Implementation overview:
21
22    In the `usual' case, RM saves no state for directories it is processing.
23    When a removal fails (either due to an error or to an interactive `no'
24    reply), the failure is noted (see description of `ht' in remove.c's
25    remove_cwd_entries function) so that when/if the containing directory
26    is reopened, RM doesn't try to remove the entry again.
27
28    RM may delete arbitrarily deep hierarchies -- even ones in which file
29    names (from root to leaf) are longer than the system-imposed maximum.
30    It does this by using chdir to change to each directory in turn before
31    removing the entries in that directory.
32
33    RM detects directory cycles lazily.  See lib/cycle-check.c.
34
35    RM is careful to avoid forming full file names whenever possible.
36    A full file name is formed only when it is about to be used -- e.g.
37    in a diagnostic or in an interactive-mode prompt.
38
39    RM minimizes the number of lstat system calls it makes.  On systems
40    that have valid d_type data in directory entries, RM makes only one
41    lstat call per command line argument -- regardless of the depth of
42    the hierarchy.  */
43
44 #include <config.h>
45 #include <stdio.h>
46 #include <getopt.h>
47 #include <sys/types.h>
48 #include <assert.h>
49
50 #include "system.h"
51 #include "argmatch.h"
52 #include "error.h"
53 #include "lstat.h"
54 #include "quote.h"
55 #include "quotearg.h"
56 #include "remove.h"
57 #include "root-dev-ino.h"
58 #include "yesno.h"
59
60 /* The official name of this program (e.g., no `g' prefix).  */
61 #define PROGRAM_NAME "rm"
62
63 #define AUTHORS \
64   proper_name ("Paul Rubin"), \
65   proper_name ("David MacKenzie"), \
66   proper_name ("Richard M. Stallman"), \
67   proper_name ("Jim Meyering")
68
69 /* Name this program was run with.  */
70 char *program_name;
71
72 /* For long options that have no equivalent short option, use a
73    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
74 enum
75 {
76   INTERACTIVE_OPTION = CHAR_MAX + 1,
77   ONE_FILE_SYSTEM,
78   NO_PRESERVE_ROOT,
79   PRESERVE_ROOT,
80   PRESUME_INPUT_TTY_OPTION
81 };
82
83 enum interactive_type
84   {
85     interactive_never,          /* 0: no option or --interactive=never */
86     interactive_once,           /* 1: -I or --interactive=once */
87     interactive_always          /* 2: default, -i or --interactive=always */
88   };
89
90 static struct option const long_opts[] =
91 {
92   {"directory", no_argument, NULL, 'd'},
93   {"force", no_argument, NULL, 'f'},
94   {"interactive", optional_argument, NULL, INTERACTIVE_OPTION},
95
96   {"one-file-system", no_argument, NULL, ONE_FILE_SYSTEM},
97   {"no-preserve-root", no_argument, NULL, NO_PRESERVE_ROOT},
98   {"preserve-root", no_argument, NULL, PRESERVE_ROOT},
99
100   /* This is solely for testing.  Do not document.  */
101   /* It is relatively difficult to ensure that there is a tty on stdin.
102      Since rm acts differently depending on that, without this option,
103      it'd be harder to test the parts of rm that depend on that setting.  */
104   {"-presume-input-tty", no_argument, NULL, PRESUME_INPUT_TTY_OPTION},
105
106   {"recursive", no_argument, NULL, 'r'},
107   {"verbose", no_argument, NULL, 'v'},
108   {GETOPT_HELP_OPTION_DECL},
109   {GETOPT_VERSION_OPTION_DECL},
110   {NULL, 0, NULL, 0}
111 };
112
113 static char const *const interactive_args[] =
114 {
115   "never", "no", "none",
116   "once",
117   "always", "yes", NULL
118 };
119 static enum interactive_type const interactive_types[] =
120 {
121   interactive_never, interactive_never, interactive_never,
122   interactive_once,
123   interactive_always, interactive_always
124 };
125 ARGMATCH_VERIFY (interactive_args, interactive_types);
126
127 /* Advise the user about invalid usages like "rm -foo" if the file
128    "-foo" exists, assuming ARGC and ARGV are as with `main'.  */
129
130 static void
131 diagnose_leading_hyphen (int argc, char **argv)
132 {
133   /* OPTIND is unreliable, so iterate through the arguments looking
134      for a file name that looks like an option.  */
135   int i;
136
137   for (i = 1; i < argc; i++)
138     {
139       char const *arg = argv[i];
140       struct stat st;
141
142       if (arg[0] == '-' && arg[1] && lstat (arg, &st) == 0)
143         {
144           fprintf (stderr,
145                    _("Try `%s ./%s' to remove the file %s.\n"),
146                    argv[0],
147                    quotearg_n_style (1, shell_quoting_style, arg),
148                    quote (arg));
149           break;
150         }
151     }
152 }
153
154 void
155 usage (int status)
156 {
157   if (status != EXIT_SUCCESS)
158     fprintf (stderr, _("Try `%s --help' for more information.\n"),
159              program_name);
160   else
161     {
162       printf (_("Usage: %s [OPTION]... FILE...\n"), program_name);
163       fputs (_("\
164 Remove (unlink) the FILE(s).\n\
165 \n\
166   -f, --force           ignore nonexistent files, never prompt\n\
167   -i                    prompt before every removal\n\
168 "), stdout);
169       fputs (_("\
170   -I                    prompt once before removing more than three files, or\n\
171                           when removing recursively.  Less intrusive than -i,\n\
172                           while still giving protection against most mistakes\n\
173       --interactive[=WHEN]  prompt according to WHEN: never, once (-I), or\n\
174                           always (-i).  Without WHEN, prompt always\n\
175 "), stdout);
176       fputs (_("\
177       --one-file-system  when removing a hierarchy recursively, skip any\n\
178                           directory that is on a file system different from\n\
179                           that of the corresponding command line argument\n\
180 "), stdout);
181       fputs (_("\
182       --no-preserve-root  do not treat `/' specially\n\
183       --preserve-root   do not remove `/' (default)\n\
184   -r, -R, --recursive   remove directories and their contents recursively\n\
185   -v, --verbose         explain what is being done\n\
186 "), stdout);
187       fputs (HELP_OPTION_DESCRIPTION, stdout);
188       fputs (VERSION_OPTION_DESCRIPTION, stdout);
189       fputs (_("\
190 \n\
191 By default, rm does not remove directories.  Use the --recursive (-r or -R)\n\
192 option to remove each listed directory, too, along with all of its contents.\n\
193 "), stdout);
194       printf (_("\
195 \n\
196 To remove a file whose name starts with a `-', for example `-foo',\n\
197 use one of these commands:\n\
198   %s -- -foo\n\
199 \n\
200   %s ./-foo\n\
201 "),
202               program_name, program_name);
203       fputs (_("\
204 \n\
205 Note that if you use rm to remove a file, it is usually possible to recover\n\
206 the contents of that file.  If you want more assurance that the contents are\n\
207 truly unrecoverable, consider using shred.\n\
208 "), stdout);
209       emit_bug_reporting_address ();
210     }
211   exit (status);
212 }
213
214 static void
215 rm_option_init (struct rm_options *x)
216 {
217   x->ignore_missing_files = false;
218   x->interactive = RMI_SOMETIMES;
219   x->one_file_system = false;
220   x->recursive = false;
221   x->root_dev_ino = NULL;
222   x->stdin_tty = isatty (STDIN_FILENO);
223   x->verbose = false;
224
225   /* Since this program exits immediately after calling `rm', rm need not
226      expend unnecessary effort to preserve the initial working directory.  */
227   x->require_restore_cwd = false;
228 }
229
230 int
231 main (int argc, char **argv)
232 {
233   bool preserve_root = true;
234   struct rm_options x;
235   bool prompt_once = false;
236   int c;
237
238   initialize_main (&argc, &argv);
239   program_name = argv[0];
240   setlocale (LC_ALL, "");
241   bindtextdomain (PACKAGE, LOCALEDIR);
242   textdomain (PACKAGE);
243
244   atexit (close_stdin);
245
246   rm_option_init (&x);
247
248   while ((c = getopt_long (argc, argv, "dfirvIR", long_opts, NULL)) != -1)
249     {
250       switch (c)
251         {
252         case 'd':
253           /* Ignore this option, for backward compatibility with
254              coreutils 5.92.  FIXME: Some time after 2005, change this
255              to report an error (or perhaps behave like FreeBSD does)
256              instead of ignoring the option.  */
257           break;
258
259         case 'f':
260           x.interactive = RMI_NEVER;
261           x.ignore_missing_files = true;
262           prompt_once = false;
263           break;
264
265         case 'i':
266           x.interactive = RMI_ALWAYS;
267           x.ignore_missing_files = false;
268           prompt_once = false;
269           break;
270
271         case 'I':
272           x.interactive = RMI_NEVER;
273           x.ignore_missing_files = false;
274           prompt_once = true;
275           break;
276
277         case 'r':
278         case 'R':
279           x.recursive = true;
280           break;
281
282         case INTERACTIVE_OPTION:
283           {
284             int i;
285             if (optarg)
286               i = XARGMATCH ("--interactive", optarg, interactive_args,
287                              interactive_types);
288             else
289               i = interactive_always;
290             switch (i)
291               {
292               case interactive_never:
293                 x.interactive = RMI_NEVER;
294                 prompt_once = false;
295                 break;
296
297               case interactive_once:
298                 x.interactive = RMI_SOMETIMES;
299                 x.ignore_missing_files = false;
300                 prompt_once = true;
301                 break;
302
303               case interactive_always:
304                 x.interactive = RMI_ALWAYS;
305                 x.ignore_missing_files = false;
306                 prompt_once = false;
307                 break;
308               }
309             break;
310           }
311
312         case ONE_FILE_SYSTEM:
313           x.one_file_system = true;
314           break;
315
316         case NO_PRESERVE_ROOT:
317           preserve_root = false;
318           break;
319
320         case PRESERVE_ROOT:
321           preserve_root = true;
322           break;
323
324         case PRESUME_INPUT_TTY_OPTION:
325           x.stdin_tty = true;
326           break;
327
328         case 'v':
329           x.verbose = true;
330           break;
331
332         case_GETOPT_HELP_CHAR;
333         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
334         default:
335           diagnose_leading_hyphen (argc, argv);
336           usage (EXIT_FAILURE);
337         }
338     }
339
340   if (argc <= optind)
341     {
342       if (x.ignore_missing_files)
343         exit (EXIT_SUCCESS);
344       else
345         {
346           error (0, 0, _("missing operand"));
347           usage (EXIT_FAILURE);
348         }
349     }
350
351   if (x.recursive & preserve_root)
352     {
353       static struct dev_ino dev_ino_buf;
354       x.root_dev_ino = get_root_dev_ino (&dev_ino_buf);
355       if (x.root_dev_ino == NULL)
356         error (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
357                quote ("/"));
358     }
359
360   size_t n_files = argc - optind;
361   char const *const *file = (char const *const *) argv + optind;
362
363   if (prompt_once && (x.recursive || 3 < n_files))
364     {
365       fprintf (stderr,
366                (x.recursive
367                 ? _("%s: remove all arguments recursively? ")
368                 : _("%s: remove all arguments? ")),
369                program_name);
370       if (!yesno ())
371         exit (EXIT_SUCCESS);
372     }
373   enum RM_status status = rm (n_files, file, &x);
374   assert (VALID_STATUS (status));
375   exit (status == RM_ERROR ? EXIT_FAILURE : EXIT_SUCCESS);
376 }