rm.c revision 51230
189495Snyan/*-
289495Snyan * Copyright (c) 1990, 1993, 1994
3125625Snyan *	The Regents of the University of California.  All rights reserved.
4125778Snyan *
5125625Snyan * Redistribution and use in source and binary forms, with or without
6125625Snyan * modification, are permitted provided that the following conditions
7139103Sru * are met:
8125563Snyan * 1. Redistributions of source code must retain the above copyright
9117053Sru *    notice, this list of conditions and the following disclaimer.
10125567Sru * 2. Redistributions in binary form must reproduce the above copyright
1189495Snyan *    notice, this list of conditions and the following disclaimer in the
12125625Snyan *    documentation and/or other materials provided with the distribution.
13125625Snyan * 3. All advertising materials mentioning features or use of this software
1489495Snyan *    must display the following acknowledgement:
1589495Snyan *	This product includes software developed by the University of
1689495Snyan *	California, Berkeley and its contributors.
1789495Snyan * 4. Neither the name of the University nor the names of its contributors
18125625Snyan *    may be used to endorse or promote products derived from this software
19125625Snyan *    without specific prior written permission.
20104234Speter *
2189495Snyan * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22117053Sru * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1990, 1993, 1994\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)rm.c	8.5 (Berkeley) 4/18/94";
43#else
44static const char rcsid[] =
45  "$FreeBSD: head/bin/rm/rm.c 51230 1999-09-13 15:12:30Z bde $";
46#endif
47#endif /* not lint */
48
49#include <sys/types.h>
50#include <sys/stat.h>
51#include <sys/param.h>
52#include <sys/mount.h>
53
54#include <err.h>
55#include <errno.h>
56#include <fcntl.h>
57#include <fts.h>
58#include <stdio.h>
59#include <stdlib.h>
60#include <string.h>
61#include <sysexits.h>
62#include <unistd.h>
63
64extern char *flags_to_string __P((u_long, char *));
65
66int dflag, eval, fflag, iflag, Pflag, vflag, Wflag, stdin_ok;
67uid_t uid;
68
69int	check __P((char *, char *, struct stat *));
70void	checkdot __P((char **));
71void	rm_file __P((char **));
72void	rm_overwrite __P((char *, struct stat *));
73void	rm_tree __P((char **));
74void	usage __P((void));
75
76/*
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.
82 */
83int
84main(argc, argv)
85	int argc;
86	char *argv[];
87{
88	int ch, rflag;
89
90	Pflag = rflag = 0;
91	while ((ch = getopt(argc, argv, "dfiPRrvW")) != -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		case 'v':
112			vflag = 1;
113			break;
114		case 'W':
115			Wflag = 1;
116			break;
117		default:
118			usage();
119		}
120	argc -= optind;
121	argv += optind;
122
123	if (argc < 1) {
124		if (fflag)
125			return 0;
126		usage();
127	}
128
129	checkdot(argv);
130	uid = geteuid();
131
132	if (*argv) {
133		stdin_ok = isatty(STDIN_FILENO);
134
135		if (rflag)
136			rm_tree(argv);
137		else
138			rm_file(argv);
139	}
140
141	exit (eval);
142}
143
144void
145rm_tree(argv)
146	char **argv;
147{
148	FTS *fts;
149	FTSENT *p;
150	int needstat;
151	int flags;
152	int rval;
153	int e;
154
155	/*
156	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
157	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
158	 */
159	needstat = !uid || (!fflag && !iflag && stdin_ok);
160
161	/*
162	 * If the -i option is specified, the user can skip on the pre-order
163	 * visit.  The fts_number field flags skipped directories.
164	 */
165#define	SKIPPED	1
166
167	flags = FTS_PHYSICAL;
168	if (!needstat)
169		flags |= FTS_NOSTAT;
170	if (Wflag)
171		flags |= FTS_WHITEOUT;
172	if (!(fts = fts_open(argv, flags, (int (*)())NULL)))
173		err(1, NULL);
174	while ((p = fts_read(fts)) != NULL) {
175		switch (p->fts_info) {
176		case FTS_DNR:
177			if (!fflag || p->fts_errno != ENOENT) {
178				warnx("%s: %s",
179				    p->fts_path, strerror(p->fts_errno));
180				eval = 1;
181			}
182			continue;
183		case FTS_ERR:
184			errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
185		case FTS_NS:
186			/*
187			 * FTS_NS: assume that if can't stat the file, it
188			 * can't be unlinked.
189			 */
190			if (!needstat)
191				break;
192			if (!fflag || p->fts_errno != ENOENT) {
193				warnx("%s: %s",
194				    p->fts_path, strerror(p->fts_errno));
195				eval = 1;
196			}
197			continue;
198		case FTS_D:
199			/* Pre-order: give user chance to skip. */
200			if (!fflag && !check(p->fts_path, p->fts_accpath,
201			    p->fts_statp)) {
202				(void)fts_set(fts, p, FTS_SKIP);
203				p->fts_number = SKIPPED;
204			}
205			else if (!uid &&
206				 (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
207				 !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
208				 chflags(p->fts_accpath,
209					 p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE)) < 0)
210				goto err;
211			continue;
212		case FTS_DP:
213			/* Post-order: see if user skipped. */
214			if (p->fts_number == SKIPPED)
215				continue;
216			break;
217		default:
218			if (!fflag &&
219			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
220				continue;
221		}
222
223		rval = 0;
224		if (!uid &&
225		    (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
226		    !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)))
227			rval = chflags(p->fts_accpath,
228				       p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
229		if (!rval) {
230			/*
231			 * If we can't read or search the directory, may still be
232			 * able to remove it.  Don't print out the un{read,search}able
233			 * message unless the remove fails.
234			 */
235			switch (p->fts_info) {
236			case FTS_DP:
237			case FTS_DNR:
238				e = rmdir(p->fts_accpath);
239				if (e == 0 || (fflag && errno == ENOENT)) {
240					if (e == 0 && vflag)
241						(void)printf("%s\n",
242						    p->fts_accpath);
243					continue;
244				}
245				break;
246
247			case FTS_W:
248				e = undelete(p->fts_accpath);
249				if (e == 0 || (fflag && errno == ENOENT)) {
250					if (e == 0 && vflag)
251						(void)printf("%s\n",
252						    p->fts_accpath);
253					continue;
254				}
255				break;
256
257			default:
258				if (Pflag)
259					rm_overwrite(p->fts_accpath, NULL);
260				e = unlink(p->fts_accpath);
261				if (e == 0 || (fflag && errno == ENOENT)) {
262					if (e == 0 && vflag)
263						(void)printf("%s\n",
264						    p->fts_accpath);
265					continue;
266				}
267			}
268		}
269err:
270		warn("%s", p->fts_path);
271		eval = 1;
272	}
273	if (errno)
274		err(1, "fts_read");
275}
276
277void
278rm_file(argv)
279	char **argv;
280{
281	struct stat sb;
282	int rval;
283	char *f;
284
285	/*
286	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
287	 * to remove a directory is an error, so must always stat the file.
288	 */
289	while ((f = *argv++) != NULL) {
290		/* Assume if can't stat the file, can't unlink it. */
291		if (lstat(f, &sb)) {
292			if (Wflag) {
293				sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
294			} else {
295				if (!fflag || errno != ENOENT) {
296					warn("%s", f);
297					eval = 1;
298				}
299				continue;
300			}
301		} else if (Wflag) {
302			warnx("%s: %s", f, strerror(EEXIST));
303			eval = 1;
304			continue;
305		}
306
307		if (S_ISDIR(sb.st_mode) && !dflag) {
308			warnx("%s: is a directory", f);
309			eval = 1;
310			continue;
311		}
312		if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
313			continue;
314		rval = 0;
315		if (!uid &&
316		    (sb.st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
317		    !(sb.st_flags & (SF_APPEND|SF_IMMUTABLE)))
318			rval = chflags(f, sb.st_flags & ~(UF_APPEND|UF_IMMUTABLE));
319		if (!rval) {
320			if (S_ISWHT(sb.st_mode))
321				rval = undelete(f);
322			else if (S_ISDIR(sb.st_mode))
323				rval = rmdir(f);
324			else {
325				if (Pflag)
326					rm_overwrite(f, &sb);
327				rval = unlink(f);
328			}
329		}
330		if (rval && (!fflag || errno != ENOENT)) {
331			warn("%s", f);
332			eval = 1;
333		}
334		if (vflag)
335			(void)printf("%s\n", f);
336	}
337}
338
339/*
340 * rm_overwrite --
341 *	Overwrite the file 3 times with varying bit patterns.
342 *
343 * XXX
344 * This is a cheap way to *really* delete files.  Note that only regular
345 * files are deleted, directories (and therefore names) will remain.
346 * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
347 * System V file system).  In a logging file system, you'll have to have
348 * kernel support.
349 */
350void
351rm_overwrite(file, sbp)
352	char *file;
353	struct stat *sbp;
354{
355	struct stat sb;
356	struct statfs fsb;
357	off_t len;
358	int bsize, fd, wlen;
359	char *buf = NULL;
360
361	fd = -1;
362	if (sbp == NULL) {
363		if (lstat(file, &sb))
364			goto err;
365		sbp = &sb;
366	}
367	if (!S_ISREG(sbp->st_mode))
368		return;
369	if ((fd = open(file, O_WRONLY, 0)) == -1)
370		goto err;
371	if (fstatfs(fd, &fsb) == -1)
372		goto err;
373	bsize = MAX(fsb.f_iosize, 1024);
374	if ((buf = malloc(bsize)) == NULL)
375		err(1, "malloc");
376
377#define	PASS(byte) {							\
378	memset(buf, byte, bsize);					\
379	for (len = sbp->st_size; len > 0; len -= wlen) {		\
380		wlen = len < bsize ? len : bsize;			\
381		if (write(fd, buf, wlen) != wlen)			\
382			goto err;					\
383	}								\
384}
385	PASS(0xff);
386	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
387		goto err;
388	PASS(0x00);
389	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
390		goto err;
391	PASS(0xff);
392	if (!fsync(fd) && !close(fd)) {
393		free(buf);
394		return;
395	}
396
397err:	eval = 1;
398	if (buf)
399		free(buf);
400	warn("%s", file);
401}
402
403
404int
405check(path, name, sp)
406	char *path, *name;
407	struct stat *sp;
408{
409	int ch, first;
410	char modep[15], flagsp[128];
411
412	/* Check -i first. */
413	if (iflag)
414		(void)fprintf(stderr, "remove %s? ", path);
415	else {
416		/*
417		 * If it's not a symbolic link and it's unwritable and we're
418		 * talking to a terminal, ask.  Symbolic links are excluded
419		 * because their permissions are meaningless.  Check stdin_ok
420		 * first because we may not have stat'ed the file.
421		 */
422		if (!stdin_ok || S_ISLNK(sp->st_mode) ||
423		    (!access(name, W_OK) &&
424		    !(sp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
425		    (!(sp->st_flags & (UF_APPEND|UF_IMMUTABLE)) || !uid)))
426			return (1);
427		strmode(sp->st_mode, modep);
428		strcpy(flagsp, flags_to_string(sp->st_flags, NULL));
429		if (*flagsp)
430			strcat(flagsp, " ");
431		(void)fprintf(stderr, "override %s%s%s/%s %sfor %s? ",
432		    modep + 1, modep[9] == ' ' ? "" : " ",
433		    user_from_uid(sp->st_uid, 0),
434		    group_from_gid(sp->st_gid, 0),
435		    *flagsp ? flagsp : "",
436		    path);
437	}
438	(void)fflush(stderr);
439
440	first = ch = getchar();
441	while (ch != '\n' && ch != EOF)
442		ch = getchar();
443	return (first == 'y' || first == 'Y');
444}
445
446#define ISDOT(a)	((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
447void
448checkdot(argv)
449	char **argv;
450{
451	char *p, **save, **t;
452	int complained;
453
454	complained = 0;
455	for (t = argv; *t;) {
456		if ((p = strrchr(*t, '/')) != NULL)
457			++p;
458		else
459			p = *t;
460		if (ISDOT(p)) {
461			if (!complained++)
462				warnx("\".\" and \"..\" may not be removed");
463			eval = 1;
464			for (save = t; (t[0] = t[1]) != NULL; ++t)
465				continue;
466			t = save;
467		} else
468			++t;
469	}
470}
471
472void
473usage()
474{
475	(void)fprintf(stderr, "usage: rm [-f | -i] [-dPRrvW] file ...\n");
476	exit(EX_USAGE);
477}
478