xref: /freebsd/bin/rm/rm.c (revision c3aac50f284c6cca5b4f2eb46aaa13812cb8b630)
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
35 static 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
42 static char sccsid[] = "@(#)rm.c	8.5 (Berkeley) 4/18/94";
43 #else
44 static const char rcsid[] =
45   "$FreeBSD$";
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 <unistd.h>
62 
63 extern char *flags_to_string __P((u_long, char *));
64 
65 int dflag, eval, fflag, iflag, Pflag, Wflag, stdin_ok;
66 uid_t uid;
67 
68 int	check __P((char *, char *, struct stat *));
69 void	checkdot __P((char **));
70 void	rm_file __P((char **));
71 void	rm_overwrite __P((char *, struct stat *));
72 void	rm_tree __P((char **));
73 void	usage __P((void));
74 
75 /*
76  * rm --
77  *	This rm is different from historic rm's, but is expected to match
78  *	POSIX 1003.2 behavior.  The most visible difference is that -f
79  *	has two specific effects now, ignore non-existent files and force
80  * 	file removal.
81  */
82 int
83 main(argc, argv)
84 	int argc;
85 	char *argv[];
86 {
87 	int ch, rflag;
88 
89 	Pflag = rflag = 0;
90 	while ((ch = getopt(argc, argv, "dfiPRrW")) != -1)
91 		switch(ch) {
92 		case 'd':
93 			dflag = 1;
94 			break;
95 		case 'f':
96 			fflag = 1;
97 			iflag = 0;
98 			break;
99 		case 'i':
100 			fflag = 0;
101 			iflag = 1;
102 			break;
103 		case 'P':
104 			Pflag = 1;
105 			break;
106 		case 'R':
107 		case 'r':			/* Compatibility. */
108 			rflag = 1;
109 			break;
110 		case 'W':
111 			Wflag = 1;
112 			break;
113 		default:
114 			usage();
115 		}
116 	argc -= optind;
117 	argv += optind;
118 
119 	if (argc < 1) {
120 		if (fflag)
121 			return 0;
122 		usage();
123 	}
124 
125 	checkdot(argv);
126 	uid = geteuid();
127 
128 	if (*argv) {
129 		stdin_ok = isatty(STDIN_FILENO);
130 
131 		if (rflag)
132 			rm_tree(argv);
133 		else
134 			rm_file(argv);
135 	}
136 
137 	exit (eval);
138 }
139 
140 void
141 rm_tree(argv)
142 	char **argv;
143 {
144 	FTS *fts;
145 	FTSENT *p;
146 	int needstat;
147 	int flags;
148 	int rval;
149 
150 	/*
151 	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
152 	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
153 	 */
154 	needstat = !uid || (!fflag && !iflag && stdin_ok);
155 
156 	/*
157 	 * If the -i option is specified, the user can skip on the pre-order
158 	 * visit.  The fts_number field flags skipped directories.
159 	 */
160 #define	SKIPPED	1
161 
162 	flags = FTS_PHYSICAL | FTS_NOCHDIR;
163 	if (!needstat)
164 		flags |= FTS_NOSTAT;
165 	if (Wflag)
166 		flags |= FTS_WHITEOUT;
167 	if (!(fts = fts_open(argv, flags, (int (*)())NULL)))
168 		err(1, NULL);
169 	while ((p = fts_read(fts)) != NULL) {
170 		switch (p->fts_info) {
171 		case FTS_DNR:
172 			if (!fflag || p->fts_errno != ENOENT) {
173 				warnx("%s: %s",
174 				    p->fts_path, strerror(p->fts_errno));
175 				eval = 1;
176 			}
177 			continue;
178 		case FTS_ERR:
179 			errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
180 		case FTS_NS:
181 			/*
182 			 * FTS_NS: assume that if can't stat the file, it
183 			 * can't be unlinked.
184 			 */
185 			if (!needstat)
186 				break;
187 			if (!fflag || p->fts_errno != ENOENT) {
188 				warnx("%s: %s",
189 				    p->fts_path, strerror(p->fts_errno));
190 				eval = 1;
191 			}
192 			continue;
193 		case FTS_D:
194 			/* Pre-order: give user chance to skip. */
195 			if (!fflag && !check(p->fts_path, p->fts_accpath,
196 			    p->fts_statp)) {
197 				(void)fts_set(fts, p, FTS_SKIP);
198 				p->fts_number = SKIPPED;
199 			}
200 			else if (!uid &&
201 				 (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
202 				 !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
203 				 chflags(p->fts_accpath,
204 					 p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE)) < 0)
205 				goto err;
206 			continue;
207 		case FTS_DP:
208 			/* Post-order: see if user skipped. */
209 			if (p->fts_number == SKIPPED)
210 				continue;
211 			break;
212 		default:
213 			if (!fflag &&
214 			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
215 				continue;
216 		}
217 
218 		rval = 0;
219 		if (!uid &&
220 		    (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
221 		    !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)))
222 			rval = chflags(p->fts_accpath,
223 				       p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
224 		if (!rval) {
225 			/*
226 			 * If we can't read or search the directory, may still be
227 			 * able to remove it.  Don't print out the un{read,search}able
228 			 * message unless the remove fails.
229 			 */
230 			switch (p->fts_info) {
231 			case FTS_DP:
232 			case FTS_DNR:
233 				if (!rmdir(p->fts_accpath) || (fflag && errno == ENOENT))
234 					continue;
235 				break;
236 
237 			case FTS_W:
238 				if (!undelete(p->fts_accpath) ||
239 			    	(fflag && errno == ENOENT))
240 					continue;
241 				break;
242 
243 			default:
244 				if (Pflag)
245 					rm_overwrite(p->fts_accpath, NULL);
246 				if (!unlink(p->fts_accpath) || (fflag && errno == ENOENT))
247 					continue;
248 			}
249 		}
250 err:
251 		warn("%s", p->fts_path);
252 		eval = 1;
253 	}
254 	if (errno)
255 		err(1, "fts_read");
256 }
257 
258 void
259 rm_file(argv)
260 	char **argv;
261 {
262 	struct stat sb;
263 	int rval;
264 	char *f;
265 
266 	/*
267 	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
268 	 * to remove a directory is an error, so must always stat the file.
269 	 */
270 	while ((f = *argv++) != NULL) {
271 		/* Assume if can't stat the file, can't unlink it. */
272 		if (lstat(f, &sb)) {
273 			if (Wflag) {
274 				sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
275 			} else {
276 				if (!fflag || errno != ENOENT) {
277 					warn("%s", f);
278 					eval = 1;
279 				}
280 				continue;
281 			}
282 		} else if (Wflag) {
283 			warnx("%s: %s", f, strerror(EEXIST));
284 			eval = 1;
285 			continue;
286 		}
287 
288 		if (S_ISDIR(sb.st_mode) && !dflag) {
289 			warnx("%s: is a directory", f);
290 			eval = 1;
291 			continue;
292 		}
293 		if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
294 			continue;
295 		rval = 0;
296 		if (!uid &&
297 		    (sb.st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
298 		    !(sb.st_flags & (SF_APPEND|SF_IMMUTABLE)))
299 			rval = chflags(f, sb.st_flags & ~(UF_APPEND|UF_IMMUTABLE));
300 		if (!rval) {
301 			if (S_ISWHT(sb.st_mode))
302 				rval = undelete(f);
303 			else if (S_ISDIR(sb.st_mode))
304 				rval = rmdir(f);
305 			else {
306 				if (Pflag)
307 					rm_overwrite(f, &sb);
308 				rval = unlink(f);
309 			}
310 		}
311 		if (rval && (!fflag || errno != ENOENT)) {
312 			warn("%s", f);
313 			eval = 1;
314 		}
315 	}
316 }
317 
318 /*
319  * rm_overwrite --
320  *	Overwrite the file 3 times with varying bit patterns.
321  *
322  * XXX
323  * This is a cheap way to *really* delete files.  Note that only regular
324  * files are deleted, directories (and therefore names) will remain.
325  * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
326  * System V file system).  In a logging file system, you'll have to have
327  * kernel support.
328  */
329 void
330 rm_overwrite(file, sbp)
331 	char *file;
332 	struct stat *sbp;
333 {
334 	struct stat sb;
335 	struct statfs fsb;
336 	off_t len;
337 	int bsize, fd, wlen;
338 	char *buf = NULL;
339 
340 	fd = -1;
341 	if (sbp == NULL) {
342 		if (lstat(file, &sb))
343 			goto err;
344 		sbp = &sb;
345 	}
346 	if (!S_ISREG(sbp->st_mode))
347 		return;
348 	if ((fd = open(file, O_WRONLY, 0)) == -1)
349 		goto err;
350 	if (fstatfs(fd, &fsb) == -1)
351 		goto err;
352 	bsize = MAX(fsb.f_iosize, 1024);
353 	if ((buf = malloc(bsize)) == NULL)
354 		err(1, "malloc");
355 
356 #define	PASS(byte) {							\
357 	memset(buf, byte, bsize);					\
358 	for (len = sbp->st_size; len > 0; len -= wlen) {		\
359 		wlen = len < bsize ? len : bsize;			\
360 		if (write(fd, buf, wlen) != wlen)			\
361 			goto err;					\
362 	}								\
363 }
364 	PASS(0xff);
365 	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
366 		goto err;
367 	PASS(0x00);
368 	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
369 		goto err;
370 	PASS(0xff);
371 	if (!fsync(fd) && !close(fd)) {
372 		free(buf);
373 		return;
374 	}
375 
376 err:	eval = 1;
377 	if (buf)
378 		free(buf);
379 	warn("%s", file);
380 }
381 
382 
383 int
384 check(path, name, sp)
385 	char *path, *name;
386 	struct stat *sp;
387 {
388 	int ch, first;
389 	char modep[15], flagsp[128];
390 
391 	/* Check -i first. */
392 	if (iflag)
393 		(void)fprintf(stderr, "remove %s? ", path);
394 	else {
395 		/*
396 		 * If it's not a symbolic link and it's unwritable and we're
397 		 * talking to a terminal, ask.  Symbolic links are excluded
398 		 * because their permissions are meaningless.  Check stdin_ok
399 		 * first because we may not have stat'ed the file.
400 		 */
401 		if (!stdin_ok || S_ISLNK(sp->st_mode) ||
402 		    (!access(name, W_OK) &&
403 		    !(sp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
404 		    (!(sp->st_flags & (UF_APPEND|UF_IMMUTABLE)) || !uid)))
405 			return (1);
406 		strmode(sp->st_mode, modep);
407 		strcpy(flagsp, flags_to_string(sp->st_flags, NULL));
408 		if (*flagsp)
409 			strcat(flagsp, " ");
410 		(void)fprintf(stderr, "override %s%s%s/%s %sfor %s? ",
411 		    modep + 1, modep[9] == ' ' ? "" : " ",
412 		    user_from_uid(sp->st_uid, 0),
413 		    group_from_gid(sp->st_gid, 0),
414 		    *flagsp ? flagsp : "",
415 		    path);
416 	}
417 	(void)fflush(stderr);
418 
419 	first = ch = getchar();
420 	while (ch != '\n' && ch != EOF)
421 		ch = getchar();
422 	return (first == 'y' || first == 'Y');
423 }
424 
425 #define ISDOT(a)	((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
426 void
427 checkdot(argv)
428 	char **argv;
429 {
430 	char *p, **save, **t;
431 	int complained;
432 
433 	complained = 0;
434 	for (t = argv; *t;) {
435 		if ((p = strrchr(*t, '/')) != NULL)
436 			++p;
437 		else
438 			p = *t;
439 		if (ISDOT(p)) {
440 			if (!complained++)
441 				warnx("\".\" and \"..\" may not be removed");
442 			eval = 1;
443 			for (save = t; (t[0] = t[1]) != NULL; ++t)
444 				continue;
445 			t = save;
446 		} else
447 			++t;
448 	}
449 }
450 
451 void
452 usage()
453 {
454 
455 	(void)fprintf(stderr, "usage: rm [-f | -i] [-dPRrW] file ...\n");
456 	exit(1);
457 }
458