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