rm.c revision 191670
1306196Sjkim/*-
2160819Ssimon * Copyright (c) 1990, 1993, 1994
3160819Ssimon *	The Regents of the University of California.  All rights reserved.
4160819Ssimon *
5160819Ssimon * Redistribution and use in source and binary forms, with or without
6160819Ssimon * modification, are permitted provided that the following conditions
7160819Ssimon * are met:
8160819Ssimon * 1. Redistributions of source code must retain the above copyright
9160819Ssimon *    notice, this list of conditions and the following disclaimer.
10160819Ssimon * 2. Redistributions in binary form must reproduce the above copyright
11160819Ssimon *    notice, this list of conditions and the following disclaimer in the
12160819Ssimon *    documentation and/or other materials provided with the distribution.
13160819Ssimon * 4. Neither the name of the University nor the names of its contributors
14160819Ssimon *    may be used to endorse or promote products derived from this software
15160819Ssimon *    without specific prior written permission.
16160819Ssimon *
17160819Ssimon * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18160819Ssimon * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19160819Ssimon * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20215698Ssimon * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21215698Ssimon * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22215698Ssimon * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23215698Ssimon * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24215698Ssimon * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25160819Ssimon * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26160819Ssimon * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27160819Ssimon * SUCH DAMAGE.
28160819Ssimon */
29160819Ssimon
30160819Ssimon#if 0
31160819Ssimon#ifndef lint
32160819Ssimonstatic const char copyright[] =
33160819Ssimon"@(#) Copyright (c) 1990, 1993, 1994\n\
34160819Ssimon	The Regents of the University of California.  All rights reserved.\n";
35160819Ssimon#endif /* not lint */
36160819Ssimon
37160819Ssimon#ifndef lint
38160819Ssimonstatic char sccsid[] = "@(#)rm.c	8.5 (Berkeley) 4/18/94";
39160819Ssimon#endif /* not lint */
40160819Ssimon#endif
41276864Sjkim#include <sys/cdefs.h>
42276864Sjkim__FBSDID("$FreeBSD: head/bin/rm/rm.c 191670 2009-04-29 18:08:18Z imp $");
43160819Ssimon
44160819Ssimon#include <sys/stat.h>
45215698Ssimon#include <sys/param.h>
46215698Ssimon#include <sys/mount.h>
47215698Ssimon
48215698Ssimon#include <err.h>
49160819Ssimon#include <errno.h>
50215698Ssimon#include <fcntl.h>
51160819Ssimon#include <fts.h>
52160819Ssimon#include <grp.h>
53276864Sjkim#include <pwd.h>
54276864Sjkim#include <stdio.h>
55276864Sjkim#include <stdlib.h>
56160819Ssimon#include <string.h>
57276864Sjkim#include <sysexits.h>
58276864Sjkim#include <unistd.h>
59276864Sjkim
60276864Sjkimint dflag, eval, fflag, iflag, Pflag, vflag, Wflag, stdin_ok;
61276864Sjkimint rflag, Iflag;
62276864Sjkimuid_t uid;
63215698Ssimonvolatile sig_atomic_t info;
64276864Sjkim
65276864Sjkimint	check(char *, char *, struct stat *);
66276864Sjkimint	check2(char **);
67276864Sjkimvoid	checkdot(char **);
68276864Sjkimvoid	checkslash(char **);
69215698Ssimonvoid	rm_file(char **);
70276864Sjkimint	rm_overwrite(char *, struct stat *);
71160819Ssimonvoid	rm_tree(char **);
72160819Ssimonstatic void siginfo(int __unused);
73160819Ssimonvoid	usage(void);
74160819Ssimon
75160819Ssimon/*
76160819Ssimon * rm --
77160819Ssimon *	This rm is different from historic rm's, but is expected to match
78160819Ssimon *	POSIX 1003.2 behavior.	The most visible difference is that -f
79160819Ssimon *	has two specific effects now, ignore non-existent files and force
80160819Ssimon *	file removal.
81160819Ssimon */
82160819Ssimonint
83160819Ssimonmain(int argc, char *argv[])
84160819Ssimon{
85160819Ssimon	int ch;
86160819Ssimon	char *p;
87160819Ssimon
88160819Ssimon	/*
89160819Ssimon	 * Test for the special case where the utility is called as
90160819Ssimon	 * "unlink", for which the functionality provided is greatly
91160819Ssimon	 * simplified.
92160819Ssimon	 */
93160819Ssimon	if ((p = rindex(argv[0], '/')) == NULL)
94160819Ssimon		p = argv[0];
95160819Ssimon	else
96160819Ssimon		++p;
97160819Ssimon	if (strcmp(p, "unlink") == 0) {
98160819Ssimon		while (getopt(argc, argv, "") != -1)
99160819Ssimon			usage();
100160819Ssimon		argc -= optind;
101160819Ssimon		argv += optind;
102160819Ssimon		if (argc != 1)
103160819Ssimon			usage();
104160819Ssimon		rm_file(&argv[0]);
105160819Ssimon		exit(eval);
106160819Ssimon	}
107160819Ssimon
108160819Ssimon	Pflag = rflag = 0;
109160819Ssimon	while ((ch = getopt(argc, argv, "dfiIPRrvW")) != -1)
110160819Ssimon		switch(ch) {
111160819Ssimon		case 'd':
112160819Ssimon			dflag = 1;
113160819Ssimon			break;
114160819Ssimon		case 'f':
115160819Ssimon			fflag = 1;
116160819Ssimon			iflag = 0;
117160819Ssimon			break;
118160819Ssimon		case 'i':
119160819Ssimon			fflag = 0;
120160819Ssimon			iflag = 1;
121160819Ssimon			break;
122160819Ssimon		case 'I':
123160819Ssimon			Iflag = 1;
124160819Ssimon			break;
125160819Ssimon		case 'P':
126160819Ssimon			Pflag = 1;
127160819Ssimon			break;
128160819Ssimon		case 'R':
129160819Ssimon		case 'r':			/* Compatibility. */
130160819Ssimon			rflag = 1;
131160819Ssimon			break;
132160819Ssimon		case 'v':
133160819Ssimon			vflag = 1;
134160819Ssimon			break;
135160819Ssimon		case 'W':
136306196Sjkim			Wflag = 1;
137215698Ssimon			break;
138215698Ssimon		default:
139215698Ssimon			usage();
140215698Ssimon		}
141160819Ssimon	argc -= optind;
142160819Ssimon	argv += optind;
143160819Ssimon
144160819Ssimon	if (argc < 1) {
145160819Ssimon		if (fflag)
146160819Ssimon			return (0);
147160819Ssimon		usage();
148160819Ssimon	}
149160819Ssimon
150160819Ssimon	checkdot(argv);
151160819Ssimon	if (getenv("POSIXLY_CORRECT") == NULL)
152160819Ssimon		checkslash(argv);
153160819Ssimon	uid = geteuid();
154160819Ssimon
155269686Sjkim	(void)signal(SIGINFO, siginfo);
156160819Ssimon	if (*argv) {
157160819Ssimon		stdin_ok = isatty(STDIN_FILENO);
158160819Ssimon
159160819Ssimon		if (Iflag) {
160160819Ssimon			if (check2(argv) == 0)
161160819Ssimon				exit (1);
162160819Ssimon		}
163160819Ssimon		if (rflag)
164160819Ssimon			rm_tree(argv);
165160819Ssimon		else
166160819Ssimon			rm_file(argv);
167160819Ssimon	}
168160819Ssimon
169276864Sjkim	exit (eval);
170276864Sjkim}
171160819Ssimon
172160819Ssimonvoid
173160819Ssimonrm_tree(char **argv)
174160819Ssimon{
175160819Ssimon	FTS *fts;
176160819Ssimon	FTSENT *p;
177160819Ssimon	int needstat;
178160819Ssimon	int flags;
179160819Ssimon	int rval;
180160819Ssimon
181160819Ssimon	/*
182160819Ssimon	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
183160819Ssimon	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
184160819Ssimon	 */
185160819Ssimon	needstat = !uid || (!fflag && !iflag && stdin_ok);
186160819Ssimon
187160819Ssimon	/*
188160819Ssimon	 * If the -i option is specified, the user can skip on the pre-order
189160819Ssimon	 * visit.  The fts_number field flags skipped directories.
190160819Ssimon	 */
191160819Ssimon#define	SKIPPED	1
192160819Ssimon
193160819Ssimon	flags = FTS_PHYSICAL;
194160819Ssimon	if (!needstat)
195160819Ssimon		flags |= FTS_NOSTAT;
196160819Ssimon	if (Wflag)
197160819Ssimon		flags |= FTS_WHITEOUT;
198160819Ssimon	if (!(fts = fts_open(argv, flags, NULL))) {
199160819Ssimon		if (fflag && errno == ENOENT)
200160819Ssimon			return;
201160819Ssimon		err(1, "fts_open");
202160819Ssimon	}
203160819Ssimon	while ((p = fts_read(fts)) != NULL) {
204160819Ssimon		switch (p->fts_info) {
205160819Ssimon		case FTS_DNR:
206160819Ssimon			if (!fflag || p->fts_errno != ENOENT) {
207160819Ssimon				warnx("%s: %s",
208160819Ssimon				    p->fts_path, strerror(p->fts_errno));
209160819Ssimon				eval = 1;
210160819Ssimon			}
211160819Ssimon			continue;
212160819Ssimon		case FTS_ERR:
213160819Ssimon			errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
214160819Ssimon		case FTS_NS:
215160819Ssimon			/*
216160819Ssimon			 * Assume that since fts_read() couldn't stat the
217160819Ssimon			 * file, it can't be unlinked.
218160819Ssimon			 */
219160819Ssimon			if (!needstat)
220276864Sjkim				break;
221276864Sjkim			if (!fflag || p->fts_errno != ENOENT) {
222160819Ssimon				warnx("%s: %s",
223276864Sjkim				    p->fts_path, strerror(p->fts_errno));
224160819Ssimon				eval = 1;
225160819Ssimon			}
226160819Ssimon			continue;
227160819Ssimon		case FTS_D:
228276864Sjkim			/* Pre-order: give user chance to skip. */
229160819Ssimon			if (!fflag && !check(p->fts_path, p->fts_accpath,
230160819Ssimon			    p->fts_statp)) {
231160819Ssimon				(void)fts_set(fts, p, FTS_SKIP);
232160819Ssimon				p->fts_number = SKIPPED;
233160819Ssimon			}
234160819Ssimon			else if (!uid &&
235160819Ssimon				 (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
236160819Ssimon				 !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
237215698Ssimon				 chflags(p->fts_accpath,
238160819Ssimon					 p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE)) < 0)
239160819Ssimon				goto err;
240160819Ssimon			continue;
241238405Sjkim		case FTS_DP:
242160819Ssimon			/* Post-order: see if user skipped. */
243160819Ssimon			if (p->fts_number == SKIPPED)
244160819Ssimon				continue;
245160819Ssimon			break;
246160819Ssimon		default:
247160819Ssimon			if (!fflag &&
248160819Ssimon			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
249160819Ssimon				continue;
250215698Ssimon		}
251215698Ssimon
252160819Ssimon		rval = 0;
253160819Ssimon		if (!uid &&
254160819Ssimon		    (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
255215698Ssimon		    !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)))
256160819Ssimon			rval = chflags(p->fts_accpath,
257160819Ssimon				       p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
258160819Ssimon		if (rval == 0) {
259160819Ssimon			/*
260160819Ssimon			 * If we can't read or search the directory, may still be
261215698Ssimon			 * able to remove it.  Don't print out the un{read,search}able
262160819Ssimon			 * message unless the remove fails.
263160819Ssimon			 */
264160819Ssimon			switch (p->fts_info) {
265160819Ssimon			case FTS_DP:
266160819Ssimon			case FTS_DNR:
267215698Ssimon				rval = rmdir(p->fts_accpath);
268160819Ssimon				if (rval == 0 || (fflag && errno == ENOENT)) {
269160819Ssimon					if (rval == 0 && vflag)
270160819Ssimon						(void)printf("%s\n",
271160819Ssimon						    p->fts_path);
272160819Ssimon					if (rval == 0 && info) {
273215698Ssimon						info = 0;
274160819Ssimon						(void)printf("%s\n",
275160819Ssimon						    p->fts_path);
276160819Ssimon					}
277160819Ssimon					continue;
278160819Ssimon				}
279215698Ssimon				break;
280160819Ssimon
281160819Ssimon			case FTS_W:
282160819Ssimon				rval = undelete(p->fts_accpath);
283160819Ssimon				if (rval == 0 && (fflag && errno == ENOENT)) {
284160819Ssimon					if (vflag)
285215698Ssimon						(void)printf("%s\n",
286160819Ssimon						    p->fts_path);
287160819Ssimon					if (info) {
288160819Ssimon						info = 0;
289160819Ssimon						(void)printf("%s\n",
290160819Ssimon						    p->fts_path);
291215698Ssimon					}
292160819Ssimon					continue;
293160819Ssimon				}
294160819Ssimon				break;
295160819Ssimon
296160819Ssimon			case FTS_NS:
297160819Ssimon				/*
298160819Ssimon				 * Assume that since fts_read() couldn't stat
299160819Ssimon				 * the file, it can't be unlinked.
300160819Ssimon				 */
301160819Ssimon				if (fflag)
302					continue;
303				/* FALLTHROUGH */
304			default:
305				if (Pflag)
306					if (!rm_overwrite(p->fts_accpath, NULL))
307						continue;
308				rval = unlink(p->fts_accpath);
309				if (rval == 0 || (fflag && errno == ENOENT)) {
310					if (rval == 0 && vflag)
311						(void)printf("%s\n",
312						    p->fts_path);
313					if (rval == 0 && info) {
314						info = 0;
315						(void)printf("%s\n",
316						    p->fts_path);
317					}
318					continue;
319				}
320			}
321		}
322err:
323		warn("%s", p->fts_path);
324		eval = 1;
325	}
326	if (errno)
327		err(1, "fts_read");
328	fts_close(fts);
329}
330
331void
332rm_file(char **argv)
333{
334	struct stat sb;
335	int rval;
336	char *f;
337
338	/*
339	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
340	 * to remove a directory is an error, so must always stat the file.
341	 */
342	while ((f = *argv++) != NULL) {
343		/* Assume if can't stat the file, can't unlink it. */
344		if (lstat(f, &sb)) {
345			if (Wflag) {
346				sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
347			} else {
348				if (!fflag || errno != ENOENT) {
349					warn("%s", f);
350					eval = 1;
351				}
352				continue;
353			}
354		} else if (Wflag) {
355			warnx("%s: %s", f, strerror(EEXIST));
356			eval = 1;
357			continue;
358		}
359
360		if (S_ISDIR(sb.st_mode) && !dflag) {
361			warnx("%s: is a directory", f);
362			eval = 1;
363			continue;
364		}
365		if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
366			continue;
367		rval = 0;
368		if (!uid && !S_ISWHT(sb.st_mode) &&
369		    (sb.st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
370		    !(sb.st_flags & (SF_APPEND|SF_IMMUTABLE)))
371			rval = chflags(f, sb.st_flags & ~(UF_APPEND|UF_IMMUTABLE));
372		if (rval == 0) {
373			if (S_ISWHT(sb.st_mode))
374				rval = undelete(f);
375			else if (S_ISDIR(sb.st_mode))
376				rval = rmdir(f);
377			else {
378				if (Pflag)
379					if (!rm_overwrite(f, &sb))
380						continue;
381				rval = unlink(f);
382			}
383		}
384		if (rval && (!fflag || errno != ENOENT)) {
385			warn("%s", f);
386			eval = 1;
387		}
388		if (vflag && rval == 0)
389			(void)printf("%s\n", f);
390		if (info && rval == 0) {
391			info = 0;
392			(void)printf("%s\n", f);
393		}
394	}
395}
396
397/*
398 * rm_overwrite --
399 *	Overwrite the file 3 times with varying bit patterns.
400 *
401 * XXX
402 * This is a cheap way to *really* delete files.  Note that only regular
403 * files are deleted, directories (and therefore names) will remain.
404 * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
405 * System V file system).  In a logging file system, you'll have to have
406 * kernel support.
407 */
408int
409rm_overwrite(char *file, struct stat *sbp)
410{
411	struct stat sb;
412	struct statfs fsb;
413	off_t len;
414	int bsize, fd, wlen;
415	char *buf = NULL;
416
417	fd = -1;
418	if (sbp == NULL) {
419		if (lstat(file, &sb))
420			goto err;
421		sbp = &sb;
422	}
423	if (!S_ISREG(sbp->st_mode))
424		return (1);
425	if (sbp->st_nlink > 1 && !fflag) {
426		warnx("%s (inode %u): not overwritten due to multiple links",
427		    file, sbp->st_ino);
428		return (0);
429	}
430	if ((fd = open(file, O_WRONLY, 0)) == -1)
431		goto err;
432	if (fstatfs(fd, &fsb) == -1)
433		goto err;
434	bsize = MAX(fsb.f_iosize, 1024);
435	if ((buf = malloc(bsize)) == NULL)
436		err(1, "%s: malloc", file);
437
438#define	PASS(byte) {							\
439	memset(buf, byte, bsize);					\
440	for (len = sbp->st_size; len > 0; len -= wlen) {		\
441		wlen = len < bsize ? len : bsize;			\
442		if (write(fd, buf, wlen) != wlen)			\
443			goto err;					\
444	}								\
445}
446	PASS(0xff);
447	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
448		goto err;
449	PASS(0x00);
450	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
451		goto err;
452	PASS(0xff);
453	if (!fsync(fd) && !close(fd)) {
454		free(buf);
455		return (1);
456	}
457
458err:	eval = 1;
459	if (buf)
460		free(buf);
461	if (fd != -1)
462		close(fd);
463	warn("%s", file);
464	return (0);
465}
466
467
468int
469check(char *path, char *name, struct stat *sp)
470{
471	int ch, first;
472	char modep[15], *flagsp;
473
474	/* Check -i first. */
475	if (iflag)
476		(void)fprintf(stderr, "remove %s? ", path);
477	else {
478		/*
479		 * If it's not a symbolic link and it's unwritable and we're
480		 * talking to a terminal, ask.	Symbolic links are excluded
481		 * because their permissions are meaningless.  Check stdin_ok
482		 * first because we may not have stat'ed the file.
483		 */
484		if (!stdin_ok || S_ISLNK(sp->st_mode) ||
485		    (!access(name, W_OK) &&
486		    !(sp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
487		    (!(sp->st_flags & (UF_APPEND|UF_IMMUTABLE)) || !uid)))
488			return (1);
489		strmode(sp->st_mode, modep);
490		if ((flagsp = fflagstostr(sp->st_flags)) == NULL)
491			err(1, "fflagstostr");
492		if (Pflag)
493			errx(1,
494			    "%s: -P was specified, but file is not writable",
495			    path);
496		(void)fprintf(stderr, "override %s%s%s/%s %s%sfor %s? ",
497		    modep + 1, modep[9] == ' ' ? "" : " ",
498		    user_from_uid(sp->st_uid, 0),
499		    group_from_gid(sp->st_gid, 0),
500		    *flagsp ? flagsp : "", *flagsp ? " " : "",
501		    path);
502		free(flagsp);
503	}
504	(void)fflush(stderr);
505
506	first = ch = getchar();
507	while (ch != '\n' && ch != EOF)
508		ch = getchar();
509	return (first == 'y' || first == 'Y');
510}
511
512#define ISSLASH(a)	((a)[0] == '/' && (a)[1] == '\0')
513void
514checkslash(char **argv)
515{
516	char **t, **u;
517	int complained;
518
519	complained = 0;
520	for (t = argv; *t;) {
521		if (ISSLASH(*t)) {
522			if (!complained++)
523				warnx("\"/\" may not be removed");
524			eval = 1;
525			for (u = t; u[0] != NULL; ++u)
526				u[0] = u[1];
527		} else {
528			++t;
529		}
530	}
531}
532
533int
534check2(char **argv)
535{
536	struct stat st;
537	int first;
538	int ch;
539	int fcount = 0;
540	int dcount = 0;
541	int i;
542	const char *dname = NULL;
543
544	for (i = 0; argv[i]; ++i) {
545		if (lstat(argv[i], &st) == 0) {
546			if (S_ISDIR(st.st_mode)) {
547				++dcount;
548				dname = argv[i];    /* only used if 1 dir */
549			} else {
550				++fcount;
551			}
552		}
553	}
554	first = 0;
555	while (first != 'n' && first != 'N' && first != 'y' && first != 'Y') {
556		if (dcount && rflag) {
557			fprintf(stderr, "recursively remove");
558			if (dcount == 1)
559				fprintf(stderr, " %s", dname);
560			else
561				fprintf(stderr, " %d dirs", dcount);
562			if (fcount == 1)
563				fprintf(stderr, " and 1 file");
564			else if (fcount > 1)
565				fprintf(stderr, " and %d files", fcount);
566		} else if (dcount + fcount > 3) {
567			fprintf(stderr, "remove %d files", dcount + fcount);
568		} else {
569			return(1);
570		}
571		fprintf(stderr, "? ");
572		fflush(stderr);
573
574		first = ch = getchar();
575		while (ch != '\n' && ch != EOF)
576			ch = getchar();
577		if (ch == EOF)
578			break;
579	}
580	return (first == 'y' || first == 'Y');
581}
582
583#define ISDOT(a)	((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
584void
585checkdot(char **argv)
586{
587	char *p, **save, **t;
588	int complained;
589
590	complained = 0;
591	for (t = argv; *t;) {
592		if ((p = strrchr(*t, '/')) != NULL)
593			++p;
594		else
595			p = *t;
596		if (ISDOT(p)) {
597			if (!complained++)
598				warnx("\".\" and \"..\" may not be removed");
599			eval = 1;
600			for (save = t; (t[0] = t[1]) != NULL; ++t)
601				continue;
602			t = save;
603		} else
604			++t;
605	}
606}
607
608void
609usage(void)
610{
611
612	(void)fprintf(stderr, "%s\n%s\n",
613	    "usage: rm [-f | -i] [-dIPRrvW] file ...",
614	    "       unlink file");
615	exit(EX_USAGE);
616}
617
618static void
619siginfo(int sig __unused)
620{
621
622	info = 1;
623}
624