rm.c revision 2958
1/*-
2 * Copyright (c) 1990, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * 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 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
41static char sccsid[] = "@(#)rm.c	8.5 (Berkeley) 4/18/94";
42#endif /* not lint */
43
44#include <sys/types.h>
45#include <sys/stat.h>
46
47#include <err.h>
48#include <errno.h>
49#include <fcntl.h>
50#include <fts.h>
51#include <stdio.h>
52#include <stdlib.h>
53#include <string.h>
54#include <unistd.h>
55
56int dflag, eval, fflag, iflag, Pflag, stdin_ok;
57
58int	check __P((char *, char *, struct stat *));
59void	checkdot __P((char **));
60void	rm_file __P((char **));
61void	rm_overwrite __P((char *, struct stat *));
62void	rm_tree __P((char **));
63void	usage __P((void));
64
65/*
66 * rm --
67 *	This rm is different from historic rm's, but is expected to match
68 *	POSIX 1003.2 behavior.  The most visible difference is that -f
69 *	has two specific effects now, ignore non-existent files and force
70 * 	file removal.
71 */
72int
73main(argc, argv)
74	int argc;
75	char *argv[];
76{
77	int ch, rflag;
78
79	Pflag = rflag = 0;
80	while ((ch = getopt(argc, argv, "dfiPRr")) != EOF)
81		switch(ch) {
82		case 'd':
83			dflag = 1;
84			break;
85		case 'f':
86			fflag = 1;
87			iflag = 0;
88			break;
89		case 'i':
90			fflag = 0;
91			iflag = 1;
92			break;
93		case 'P':
94			Pflag = 1;
95			break;
96		case 'R':
97		case 'r':			/* Compatibility. */
98			rflag = 1;
99			break;
100		case '?':
101		default:
102			usage();
103		}
104	argc -= optind;
105	argv += optind;
106
107	if (argc < 1)
108		usage();
109
110	checkdot(argv);
111	if (!*argv)
112		exit (eval);
113
114	stdin_ok = isatty(STDIN_FILENO);
115
116	if (rflag)
117		rm_tree(argv);
118	else
119		rm_file(argv);
120	exit (eval);
121}
122
123void
124rm_tree(argv)
125	char **argv;
126{
127	FTS *fts;
128	FTSENT *p;
129	int needstat;
130
131	/*
132	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
133	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
134	 */
135	needstat = !fflag && !iflag && stdin_ok;
136
137	/*
138	 * If the -i option is specified, the user can skip on the pre-order
139	 * visit.  The fts_number field flags skipped directories.
140	 */
141#define	SKIPPED	1
142
143	if (!(fts = fts_open(argv,
144	    needstat ? FTS_PHYSICAL|FTS_NOCHDIR :
145		FTS_PHYSICAL|FTS_NOSTAT|FTS_NOCHDIR, (int (*)())NULL)))
146		err(1, NULL);
147	while ((p = fts_read(fts)) != NULL) {
148		switch (p->fts_info) {
149		case FTS_DNR:
150			if (!fflag || p->fts_errno != ENOENT) {
151				warnx("%s: %s",
152				    p->fts_path, strerror(p->fts_errno));
153				eval = 1;
154			}
155			continue;
156		case FTS_ERR:
157			errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
158		case FTS_NS:
159			/*
160			 * FTS_NS: assume that if can't stat the file, it
161			 * can't be unlinked.
162			 */
163			if (!needstat)
164				break;
165			if (!fflag || p->fts_errno != ENOENT) {
166				warnx("%s: %s",
167				    p->fts_path, strerror(p->fts_errno));
168				eval = 1;
169			}
170			continue;
171		case FTS_D:
172			/* Pre-order: give user chance to skip. */
173			if (iflag && !check(p->fts_path, p->fts_accpath,
174			    p->fts_statp)) {
175				(void)fts_set(fts, p, FTS_SKIP);
176				p->fts_number = SKIPPED;
177			}
178			continue;
179		case FTS_DP:
180			/* Post-order: see if user skipped. */
181			if (p->fts_number == SKIPPED)
182				continue;
183			break;
184		}
185		if (!fflag &&
186		    !check(p->fts_path, p->fts_accpath, p->fts_statp))
187			continue;
188
189		/*
190		 * If we can't read or search the directory, may still be
191		 * able to remove it.  Don't print out the un{read,search}able
192		 * message unless the remove fails.
193		 */
194		if (p->fts_info == FTS_DP || p->fts_info == FTS_DNR) {
195			if (!rmdir(p->fts_accpath))
196				continue;
197			if (errno == ENOENT) {
198				if (fflag)
199					continue;
200			} else if (p->fts_info != FTS_DP)
201				warnx("%s: unable to read", p->fts_path);
202		} else {
203			if (Pflag)
204				rm_overwrite(p->fts_accpath, NULL);
205			if (!unlink(p->fts_accpath) || (fflag && errno == ENOENT))
206				continue;
207		}
208		warn("%s", p->fts_path);
209		eval = 1;
210	}
211	if (errno)
212		err(1, "fts_read");
213}
214
215void
216rm_file(argv)
217	char **argv;
218{
219	struct stat sb;
220	int df, rval;
221	char *f;
222
223	df = dflag;
224	/*
225	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
226	 * to remove a directory is an error, so must always stat the file.
227	 */
228	while ((f = *argv++) != NULL) {
229		/* Assume if can't stat the file, can't unlink it. */
230		if (lstat(f, &sb)) {
231			if (!fflag || errno != ENOENT) {
232				warn("%s", f);
233				eval = 1;
234			}
235			continue;
236		}
237		if (S_ISDIR(sb.st_mode) && !df) {
238			warnx("%s: is a directory", f);
239			eval = 1;
240			continue;
241		}
242		if (!fflag && !check(f, f, &sb))
243			continue;
244		if (S_ISDIR(sb.st_mode))
245			rval = rmdir(f);
246		else {
247			if (Pflag)
248				rm_overwrite(f, &sb);
249			rval = unlink(f);
250		}
251		if (rval && (!fflag || errno != ENOENT)) {
252			warn("%s", f);
253			eval = 1;
254		}
255	}
256}
257
258/*
259 * rm_overwrite --
260 *	Overwrite the file 3 times with varying bit patterns.
261 *
262 * XXX
263 * This is a cheap way to *really* delete files.  Note that only regular
264 * files are deleted, directories (and therefore names) will remain.
265 * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
266 * System V file system).  In a logging file system, you'll have to have
267 * kernel support.
268 */
269void
270rm_overwrite(file, sbp)
271	char *file;
272	struct stat *sbp;
273{
274	struct stat sb;
275	off_t len;
276	int fd, wlen;
277	char buf[8 * 1024];
278
279	fd = -1;
280	if (sbp == NULL) {
281		if (lstat(file, &sb))
282			goto err;
283		sbp = &sb;
284	}
285	if (!S_ISREG(sbp->st_mode))
286		return;
287	if ((fd = open(file, O_WRONLY, 0)) == -1)
288		goto err;
289
290#define	PASS(byte) {							\
291	memset(buf, byte, sizeof(buf));					\
292	for (len = sbp->st_size; len > 0; len -= wlen) {		\
293		wlen = len < sizeof(buf) ? len : sizeof(buf);		\
294		if (write(fd, buf, wlen) != wlen)			\
295			goto err;					\
296	}								\
297}
298	PASS(0xff);
299	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
300		goto err;
301	PASS(0x00);
302	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
303		goto err;
304	PASS(0xff);
305	if (!fsync(fd) && !close(fd))
306		return;
307
308err:	eval = 1;
309	warn("%s", file);
310}
311
312
313int
314check(path, name, sp)
315	char *path, *name;
316	struct stat *sp;
317{
318	int ch, first;
319	char modep[15];
320
321	/* Check -i first. */
322	if (iflag)
323		(void)fprintf(stderr, "remove %s? ", path);
324	else {
325		/*
326		 * If it's not a symbolic link and it's unwritable and we're
327		 * talking to a terminal, ask.  Symbolic links are excluded
328		 * because their permissions are meaningless.  Check stdin_ok
329		 * first because we may not have stat'ed the file.
330		 */
331		if (!stdin_ok || S_ISLNK(sp->st_mode) || !access(name, W_OK))
332			return (1);
333		strmode(sp->st_mode, modep);
334		(void)fprintf(stderr, "override %s%s%s/%s for %s? ",
335		    modep + 1, modep[9] == ' ' ? "" : " ",
336		    user_from_uid(sp->st_uid, 0),
337		    group_from_gid(sp->st_gid, 0), path);
338	}
339	(void)fflush(stderr);
340
341	first = ch = getchar();
342	while (ch != '\n' && ch != EOF)
343		ch = getchar();
344	return (first == 'y');
345}
346
347#define ISDOT(a)	((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
348void
349checkdot(argv)
350	char **argv;
351{
352	char *p, **save, **t;
353	int complained;
354
355	complained = 0;
356	for (t = argv; *t;) {
357		if ((p = strrchr(*t, '/')) != NULL)
358			++p;
359		else
360			p = *t;
361		if (ISDOT(p)) {
362			if (!complained++)
363				warnx("\".\" and \"..\" may not be removed");
364			eval = 1;
365			for (save = t; (t[0] = t[1]) != NULL; ++t);
366			t = save;
367		} else
368			++t;
369	}
370}
371
372void
373usage()
374{
375
376	(void)fprintf(stderr, "usage: rm [-dfiRr] file ...\n");
377	exit(1);
378}
379