Initial support for recursive deletion.
[zero.git] / rm.c
blob37aaba962e2270cd60740cf06e71c2cbcce72c98
1 /* $OpenBSD: rm.c,v 1.21 2007/06/06 00:08:57 ray Exp $ */
2 /* $NetBSD: rm.c,v 1.19 1995/09/07 06:48:50 jtc Exp $ */
4 /*-
5 * Copyright (c) 1990, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
33 #ifndef lint
34 static char copyright[] =
35 "@(#) Copyright (c) 1990, 1993, 1994\n\
36 The Regents of the University of California. All rights reserved.\n";
37 #endif /* not lint */
39 #ifndef lint
40 #if 0
41 static char sccsid[] = "@(#)rm.c 8.8 (Berkeley) 4/27/95";
42 #else
43 static char rcsid[] = "$OpenBSD: rm.c,v 1.21 2007/06/06 00:08:57 ray Exp $";
44 #endif
45 #endif /* not lint */
47 #include <sys/types.h>
48 #include <sys/stat.h>
49 #include <sys/param.h>
50 #include <sys/mount.h>
52 #include <locale.h>
53 #include <err.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <fts.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
61 #include <pwd.h>
62 #include <grp.h>
64 extern char *__progname;
66 int dflag, eval, fflag, iflag, Pflag, stdin_ok;
68 int check(char *, char *, struct stat *);
69 void checkdot(char **);
70 void rm_file(char **);
71 int rm_overwrite(char *, struct stat *);
72 int pass(int, int, off_t, char *, size_t);
73 void rm_tree(char **);
74 void usage(void);
77 * rm --
78 * This rm is different from historic rm's, but is expected to match
79 * POSIX 1003.2 behavior. The most visible difference is that -f
80 * has two specific effects now, ignore non-existent files and force
81 * file removal.
83 int
84 main(int argc, char *argv[])
86 int ch, rflag;
88 setlocale(LC_ALL, "");
90 Pflag = rflag = 0;
91 while ((ch = getopt(argc, argv, "dfiPRr")) != -1)
92 switch(ch) {
93 case 'd':
94 dflag = 1;
95 break;
96 case 'f':
97 fflag = 1;
98 iflag = 0;
99 break;
100 case 'i':
101 fflag = 0;
102 iflag = 1;
103 break;
104 case 'P':
105 Pflag = 1;
106 break;
107 case 'R':
108 case 'r': /* Compatibility. */
109 rflag = 1;
110 break;
111 default:
112 usage();
114 argc -= optind;
115 argv += optind;
117 if (argc < 1 && fflag == 0)
118 usage();
120 checkdot(argv);
122 if (*argv) {
123 stdin_ok = isatty(STDIN_FILENO);
125 if (rflag)
126 rm_tree(argv);
127 else
128 rm_file(argv);
131 exit (eval);
134 void
135 rm_tree(char **argv)
137 FTS *fts;
138 FTSENT *p;
139 int needstat;
140 int flags;
143 * Remove a file hierarchy. If forcing removal (-f), or interactive
144 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
146 needstat = !fflag && !iflag && stdin_ok;
149 * If the -i option is specified, the user can skip on the pre-order
150 * visit. The fts_number field flags skipped directories.
152 #define SKIPPED 1
154 flags = FTS_PHYSICAL;
155 if (!needstat)
156 flags |= FTS_NOSTAT;
157 if (!(fts = fts_open(argv, flags, NULL)))
158 err(1, NULL);
159 while ((p = fts_read(fts)) != NULL) {
160 switch (p->fts_info) {
161 case FTS_DNR:
162 if (!fflag || p->fts_errno != ENOENT) {
163 warnx("%s: %s",
164 p->fts_path, strerror(p->fts_errno));
165 eval = 1;
167 continue;
168 case FTS_ERR:
169 errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
170 case FTS_NS:
172 * FTS_NS: assume that if can't stat the file, it
173 * can't be unlinked.
175 if (!needstat)
176 break;
177 if (!fflag || p->fts_errno != ENOENT) {
178 warnx("%s: %s",
179 p->fts_path, strerror(p->fts_errno));
180 eval = 1;
182 continue;
183 case FTS_D:
184 /* Pre-order: give user chance to skip. */
185 if (!fflag && !check(p->fts_path, p->fts_accpath,
186 p->fts_statp)) {
187 (void)fts_set(fts, p, FTS_SKIP);
188 p->fts_number = SKIPPED;
190 continue;
191 case FTS_DP:
192 /* Post-order: see if user skipped. */
193 if (p->fts_number == SKIPPED)
194 continue;
195 break;
196 default:
197 if (!fflag &&
198 !check(p->fts_path, p->fts_accpath, p->fts_statp))
199 continue;
203 * If we can't read or search the directory, may still be
204 * able to remove it. Don't print out the un{read,search}able
205 * message unless the remove fails.
207 switch (p->fts_info) {
208 case FTS_DP:
209 case FTS_DNR:
210 if (!rmdir(p->fts_accpath) ||
211 (fflag && errno == ENOENT))
212 continue;
213 break;
215 default:
216 if (Pflag)
217 rm_overwrite(p->fts_accpath, NULL);
218 if (!unlink(p->fts_accpath) ||
219 (fflag && errno == ENOENT))
220 continue;
222 warn("%s", p->fts_path);
223 eval = 1;
225 if (errno)
226 err(1, "fts_read");
227 fts_close(fts);
230 void
231 rm_file(char **argv)
233 struct stat sb;
234 int rval;
235 char *f;
238 * Remove a file. POSIX 1003.2 states that, by default, attempting
239 * to remove a directory is an error, so must always stat the file.
241 while ((f = *argv++) != NULL) {
242 /* Assume if can't stat the file, can't unlink it. */
243 if (lstat(f, &sb)) {
244 if (!fflag || errno != ENOENT) {
245 warn("%s", f);
246 eval = 1;
248 continue;
251 if (S_ISDIR(sb.st_mode) && !dflag) {
252 warnx("%s: is a directory", f);
253 eval = 1;
254 continue;
256 if (!fflag && !check(f, f, &sb))
257 continue;
258 else if (S_ISDIR(sb.st_mode))
259 rval = rmdir(f);
260 else {
261 if (Pflag)
262 rm_overwrite(f, &sb);
263 rval = unlink(f);
265 if (rval && (!fflag || errno != ENOENT)) {
266 warn("%s", f);
267 eval = 1;
273 * rm_overwrite --
274 * Overwrite the file 3 times with varying bit patterns.
276 * XXX
277 * This is a cheap way to *really* delete files. Note that only regular
278 * files are deleted, directories (and therefore names) will remain.
279 * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
280 * System V file system). In a logging file system, you'll have to have
281 * kernel support.
282 * Returns 1 for success.
285 rm_overwrite(char *file, struct stat *sbp)
287 struct stat sb;
288 struct statfs fsb;
289 size_t bsize;
290 int fd;
291 char *buf = NULL;
293 fd = -1;
294 if (sbp == NULL) {
295 if (lstat(file, &sb))
296 goto err;
297 sbp = &sb;
299 if (!S_ISREG(sbp->st_mode))
300 return (1);
301 if (sbp->st_nlink > 1) {
302 warnx("%s (inode %u): not overwritten due to multiple links",
303 file, sbp->st_ino);
304 return (0);
306 if ((fd = open(file, O_WRONLY, 0)) == -1)
307 goto err;
308 if (fstatfs(fd, &fsb) == -1)
309 goto err;
310 bsize = MAX(fsb.f_iosize, 1024U);
311 if ((buf = malloc(bsize)) == NULL)
312 err(1, "%s: malloc", file);
314 if (!pass(0xff, fd, sbp->st_size, buf, bsize) || fsync(fd) ||
315 lseek(fd, (off_t)0, SEEK_SET))
316 goto err;
317 if (!pass(0x00, fd, sbp->st_size, buf, bsize) || fsync(fd) ||
318 lseek(fd, (off_t)0, SEEK_SET))
319 goto err;
320 if (!pass(0xff, fd, sbp->st_size, buf, bsize) || fsync(fd))
321 goto err;
322 close(fd);
323 free(buf);
324 return (1);
326 err:
327 warn("%s", file);
328 close(fd);
329 eval = 1;
330 free(buf);
331 return (0);
335 pass(int val, int fd, off_t len, char *buf, size_t bsize)
337 size_t wlen;
339 memset(buf, val, bsize);
340 for (; len > 0; len -= wlen) {
341 wlen = len < bsize ? len : bsize;
342 if (write(fd, buf, wlen) != wlen)
343 return (0);
345 return (1);
349 check(char *path, char *name, struct stat *sp)
351 int ch, first;
352 char modep[15];
354 /* Check -i first. */
355 if (iflag)
356 (void)fprintf(stderr, "remove %s? ", path);
357 else {
359 * If it's not a symbolic link and it's unwritable and we're
360 * talking to a terminal, ask. Symbolic links are excluded
361 * because their permissions are meaningless. Check stdin_ok
362 * first because we may not have stat'ed the file.
364 if (!stdin_ok || S_ISLNK(sp->st_mode) || !access(name, W_OK))
365 return (1);
366 strmode(sp->st_mode, modep);
367 (void)fprintf(stderr, "override %s%s%s/%s for %s? ",
368 modep + 1, modep[9] == ' ' ? "" : " ",
369 user_from_uid(sp->st_uid, 0),
370 group_from_gid(sp->st_gid, 0), path);
372 (void)fflush(stderr);
374 first = ch = getchar();
375 while (ch != '\n' && ch != EOF)
376 ch = getchar();
377 return (first == 'y' || first == 'Y');
381 * POSIX.2 requires that if "." or ".." are specified as the basename
382 * portion of an operand, a diagnostic message be written to standard
383 * error and nothing more be done with such operands.
385 * Since POSIX.2 defines basename as the final portion of a path after
386 * trailing slashes have been removed, we'll remove them here.
388 #define ISDOT(a) ((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
389 void
390 checkdot(char **argv)
392 char *p, **save, **t;
393 int complained;
395 complained = 0;
396 for (t = argv; *t;) {
397 /* strip trailing slashes */
398 p = strrchr (*t, '\0');
399 while (--p > *t && *p == '/')
400 *p = '\0';
402 /* extract basename */
403 if ((p = strrchr(*t, '/')) != NULL)
404 ++p;
405 else
406 p = *t;
408 if (ISDOT(p)) {
409 if (!complained++)
410 warnx("\".\" and \"..\" may not be removed");
411 eval = 1;
412 for (save = t; (t[0] = t[1]) != NULL; ++t)
413 continue;
414 t = save;
415 } else
416 ++t;
420 void
421 usage(void)
423 (void)fprintf(stderr, "usage: %s [-dfiPRr] file ...\n", __progname);
424 exit(1);