xref: /freebsd/bin/rm/rm.c (revision 5819c3eb8a1e2ac0a4f96a3aff5fefac276ae581)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1990, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #if 0
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1990, 1993, 1994\n\
36 	The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38 
39 #ifndef lint
40 static char sccsid[] = "@(#)rm.c	8.5 (Berkeley) 4/18/94";
41 #endif /* not lint */
42 #endif
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 #include <sys/stat.h>
47 #include <sys/param.h>
48 #include <sys/mount.h>
49 
50 #include <err.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <fts.h>
54 #include <grp.h>
55 #include <locale.h>
56 #include <pwd.h>
57 #include <stdint.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <sysexits.h>
62 #include <unistd.h>
63 
64 static int dflag, eval, fflag, iflag, Pflag, vflag, Wflag, stdin_ok;
65 static int rflag, Iflag, xflag;
66 static uid_t uid;
67 static volatile sig_atomic_t info;
68 
69 static int	check(const char *, const char *, struct stat *);
70 static int	check2(char **);
71 static void	checkdot(char **);
72 static void	checkslash(char **);
73 static void	rm_file(char **);
74 static int	rm_overwrite(const char *, struct stat *);
75 static void	rm_tree(char **);
76 static void siginfo(int __unused);
77 static void	usage(void);
78 
79 /*
80  * rm --
81  *	This rm is different from historic rm's, but is expected to match
82  *	POSIX 1003.2 behavior.	The most visible difference is that -f
83  *	has two specific effects now, ignore non-existent files and force
84  *	file removal.
85  */
86 int
87 main(int argc, char *argv[])
88 {
89 	int ch;
90 	char *p;
91 
92 	(void)setlocale(LC_ALL, "");
93 
94 	/*
95 	 * Test for the special case where the utility is called as
96 	 * "unlink", for which the functionality provided is greatly
97 	 * simplified.
98 	 */
99 	if ((p = strrchr(argv[0], '/')) == NULL)
100 		p = argv[0];
101 	else
102 		++p;
103 	if (strcmp(p, "unlink") == 0) {
104 		while (getopt(argc, argv, "") != -1)
105 			usage();
106 		argc -= optind;
107 		argv += optind;
108 		if (argc != 1)
109 			usage();
110 		rm_file(&argv[0]);
111 		exit(eval);
112 	}
113 
114 	Pflag = rflag = xflag = 0;
115 	while ((ch = getopt(argc, argv, "dfiIPRrvWx")) != -1)
116 		switch(ch) {
117 		case 'd':
118 			dflag = 1;
119 			break;
120 		case 'f':
121 			fflag = 1;
122 			iflag = 0;
123 			break;
124 		case 'i':
125 			fflag = 0;
126 			iflag = 1;
127 			break;
128 		case 'I':
129 			Iflag = 1;
130 			break;
131 		case 'P':
132 			Pflag = 1;
133 			break;
134 		case 'R':
135 		case 'r':			/* Compatibility. */
136 			rflag = 1;
137 			break;
138 		case 'v':
139 			vflag = 1;
140 			break;
141 		case 'W':
142 			Wflag = 1;
143 			break;
144 		case 'x':
145 			xflag = 1;
146 			break;
147 		default:
148 			usage();
149 		}
150 	argc -= optind;
151 	argv += optind;
152 
153 	if (argc < 1) {
154 		if (fflag)
155 			return (0);
156 		usage();
157 	}
158 
159 	checkdot(argv);
160 	checkslash(argv);
161 	uid = geteuid();
162 
163 	(void)signal(SIGINFO, siginfo);
164 	if (*argv) {
165 		stdin_ok = isatty(STDIN_FILENO);
166 
167 		if (Iflag) {
168 			if (check2(argv) == 0)
169 				exit (1);
170 		}
171 		if (rflag)
172 			rm_tree(argv);
173 		else
174 			rm_file(argv);
175 	}
176 
177 	exit (eval);
178 }
179 
180 static void
181 rm_tree(char **argv)
182 {
183 	FTS *fts;
184 	FTSENT *p;
185 	int needstat;
186 	int flags;
187 	int rval;
188 
189 	/*
190 	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
191 	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
192 	 */
193 	needstat = !uid || (!fflag && !iflag && stdin_ok);
194 
195 	/*
196 	 * If the -i option is specified, the user can skip on the pre-order
197 	 * visit.  The fts_number field flags skipped directories.
198 	 */
199 #define	SKIPPED	1
200 
201 	flags = FTS_PHYSICAL;
202 	if (!needstat)
203 		flags |= FTS_NOSTAT;
204 	if (Wflag)
205 		flags |= FTS_WHITEOUT;
206 	if (xflag)
207 		flags |= FTS_XDEV;
208 	if (!(fts = fts_open(argv, flags, NULL))) {
209 		if (fflag && errno == ENOENT)
210 			return;
211 		err(1, "fts_open");
212 	}
213 	while ((p = fts_read(fts)) != NULL) {
214 		switch (p->fts_info) {
215 		case FTS_DNR:
216 			if (!fflag || p->fts_errno != ENOENT) {
217 				warnx("%s: %s",
218 				    p->fts_path, strerror(p->fts_errno));
219 				eval = 1;
220 			}
221 			continue;
222 		case FTS_ERR:
223 			errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
224 		case FTS_NS:
225 			/*
226 			 * Assume that since fts_read() couldn't stat the
227 			 * file, it can't be unlinked.
228 			 */
229 			if (!needstat)
230 				break;
231 			if (!fflag || p->fts_errno != ENOENT) {
232 				warnx("%s: %s",
233 				    p->fts_path, strerror(p->fts_errno));
234 				eval = 1;
235 			}
236 			continue;
237 		case FTS_D:
238 			/* Pre-order: give user chance to skip. */
239 			if (!fflag && !check(p->fts_path, p->fts_accpath,
240 			    p->fts_statp)) {
241 				(void)fts_set(fts, p, FTS_SKIP);
242 				p->fts_number = SKIPPED;
243 			}
244 			else if (!uid &&
245 				 (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
246 				 !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
247 				 lchflags(p->fts_accpath,
248 					 p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE)) < 0)
249 				goto err;
250 			continue;
251 		case FTS_DP:
252 			/* Post-order: see if user skipped. */
253 			if (p->fts_number == SKIPPED)
254 				continue;
255 			break;
256 		default:
257 			if (!fflag &&
258 			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
259 				continue;
260 		}
261 
262 		rval = 0;
263 		if (!uid &&
264 		    (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
265 		    !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)))
266 			rval = lchflags(p->fts_accpath,
267 				       p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
268 		if (rval == 0) {
269 			/*
270 			 * If we can't read or search the directory, may still be
271 			 * able to remove it.  Don't print out the un{read,search}able
272 			 * message unless the remove fails.
273 			 */
274 			switch (p->fts_info) {
275 			case FTS_DP:
276 			case FTS_DNR:
277 				rval = rmdir(p->fts_accpath);
278 				if (rval == 0 || (fflag && errno == ENOENT)) {
279 					if (rval == 0 && vflag)
280 						(void)printf("%s\n",
281 						    p->fts_path);
282 					if (rval == 0 && info) {
283 						info = 0;
284 						(void)printf("%s\n",
285 						    p->fts_path);
286 					}
287 					continue;
288 				}
289 				break;
290 
291 			case FTS_W:
292 				rval = undelete(p->fts_accpath);
293 				if (rval == 0 && (fflag && errno == ENOENT)) {
294 					if (vflag)
295 						(void)printf("%s\n",
296 						    p->fts_path);
297 					if (info) {
298 						info = 0;
299 						(void)printf("%s\n",
300 						    p->fts_path);
301 					}
302 					continue;
303 				}
304 				break;
305 
306 			case FTS_NS:
307 				/*
308 				 * Assume that since fts_read() couldn't stat
309 				 * the file, it can't be unlinked.
310 				 */
311 				if (fflag)
312 					continue;
313 				/* FALLTHROUGH */
314 
315 			case FTS_F:
316 			case FTS_NSOK:
317 				if (Pflag)
318 					if (!rm_overwrite(p->fts_accpath, p->fts_info ==
319 					    FTS_NSOK ? NULL : p->fts_statp))
320 						continue;
321 				/* FALLTHROUGH */
322 
323 			default:
324 				rval = unlink(p->fts_accpath);
325 				if (rval == 0 || (fflag && errno == ENOENT)) {
326 					if (rval == 0 && vflag)
327 						(void)printf("%s\n",
328 						    p->fts_path);
329 					if (rval == 0 && info) {
330 						info = 0;
331 						(void)printf("%s\n",
332 						    p->fts_path);
333 					}
334 					continue;
335 				}
336 			}
337 		}
338 err:
339 		warn("%s", p->fts_path);
340 		eval = 1;
341 	}
342 	if (!fflag && errno)
343 		err(1, "fts_read");
344 	fts_close(fts);
345 }
346 
347 static void
348 rm_file(char **argv)
349 {
350 	struct stat sb;
351 	int rval;
352 	char *f;
353 
354 	/*
355 	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
356 	 * to remove a directory is an error, so must always stat the file.
357 	 */
358 	while ((f = *argv++) != NULL) {
359 		/* Assume if can't stat the file, can't unlink it. */
360 		if (lstat(f, &sb)) {
361 			if (Wflag) {
362 				sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
363 			} else {
364 				if (!fflag || errno != ENOENT) {
365 					warn("%s", f);
366 					eval = 1;
367 				}
368 				continue;
369 			}
370 		} else if (Wflag) {
371 			warnx("%s: %s", f, strerror(EEXIST));
372 			eval = 1;
373 			continue;
374 		}
375 
376 		if (S_ISDIR(sb.st_mode) && !dflag) {
377 			warnx("%s: is a directory", f);
378 			eval = 1;
379 			continue;
380 		}
381 		if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
382 			continue;
383 		rval = 0;
384 		if (!uid && !S_ISWHT(sb.st_mode) &&
385 		    (sb.st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
386 		    !(sb.st_flags & (SF_APPEND|SF_IMMUTABLE)))
387 			rval = lchflags(f, sb.st_flags & ~(UF_APPEND|UF_IMMUTABLE));
388 		if (rval == 0) {
389 			if (S_ISWHT(sb.st_mode))
390 				rval = undelete(f);
391 			else if (S_ISDIR(sb.st_mode))
392 				rval = rmdir(f);
393 			else {
394 				if (Pflag)
395 					if (!rm_overwrite(f, &sb))
396 						continue;
397 				rval = unlink(f);
398 			}
399 		}
400 		if (rval && (!fflag || errno != ENOENT)) {
401 			warn("%s", f);
402 			eval = 1;
403 		}
404 		if (vflag && rval == 0)
405 			(void)printf("%s\n", f);
406 		if (info && rval == 0) {
407 			info = 0;
408 			(void)printf("%s\n", f);
409 		}
410 	}
411 }
412 
413 /*
414  * rm_overwrite --
415  *	Overwrite the file 3 times with varying bit patterns.
416  *
417  * XXX
418  * This is a cheap way to *really* delete files.  Note that only regular
419  * files are deleted, directories (and therefore names) will remain.
420  * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
421  * System V file system).  In a logging or COW file system, you'll have to
422  * have kernel support.
423  */
424 static int
425 rm_overwrite(const char *file, struct stat *sbp)
426 {
427 	struct stat sb, sb2;
428 	struct statfs fsb;
429 	off_t len;
430 	int bsize, fd, wlen;
431 	char *buf = NULL;
432 
433 	fd = -1;
434 	if (sbp == NULL) {
435 		if (lstat(file, &sb))
436 			goto err;
437 		sbp = &sb;
438 	}
439 	if (!S_ISREG(sbp->st_mode))
440 		return (1);
441 	if (sbp->st_nlink > 1 && !fflag) {
442 		warnx("%s (inode %ju): not overwritten due to multiple links",
443 		    file, (uintmax_t)sbp->st_ino);
444 		return (0);
445 	}
446 	if ((fd = open(file, O_WRONLY|O_NONBLOCK|O_NOFOLLOW, 0)) == -1)
447 		goto err;
448 	if (fstat(fd, &sb2))
449 		goto err;
450 	if (sb2.st_dev != sbp->st_dev || sb2.st_ino != sbp->st_ino ||
451 	    !S_ISREG(sb2.st_mode)) {
452 		errno = EPERM;
453 		goto err;
454 	}
455 	if (fstatfs(fd, &fsb) == -1)
456 		goto err;
457 	bsize = MAX(fsb.f_iosize, 1024);
458 	if ((buf = malloc(bsize)) == NULL)
459 		err(1, "%s: malloc", file);
460 
461 #define	PASS(byte) {							\
462 	memset(buf, byte, bsize);					\
463 	for (len = sbp->st_size; len > 0; len -= wlen) {		\
464 		wlen = len < bsize ? len : bsize;			\
465 		if (write(fd, buf, wlen) != wlen)			\
466 			goto err;					\
467 	}								\
468 }
469 	PASS(0xff);
470 	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
471 		goto err;
472 	PASS(0x00);
473 	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
474 		goto err;
475 	PASS(0xff);
476 	if (!fsync(fd) && !close(fd)) {
477 		free(buf);
478 		return (1);
479 	}
480 
481 err:	eval = 1;
482 	if (buf)
483 		free(buf);
484 	if (fd != -1)
485 		close(fd);
486 	warn("%s", file);
487 	return (0);
488 }
489 
490 
491 static int
492 check(const char *path, const char *name, struct stat *sp)
493 {
494 	int ch, first;
495 	char modep[15], *flagsp;
496 
497 	/* Check -i first. */
498 	if (iflag)
499 		(void)fprintf(stderr, "remove %s? ", path);
500 	else {
501 		/*
502 		 * If it's not a symbolic link and it's unwritable and we're
503 		 * talking to a terminal, ask.  Symbolic links are excluded
504 		 * because their permissions are meaningless.  Check stdin_ok
505 		 * first because we may not have stat'ed the file.
506 		 */
507 		if (!stdin_ok || S_ISLNK(sp->st_mode) ||
508 		    (!access(name, W_OK) &&
509 		    !(sp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
510 		    (!(sp->st_flags & (UF_APPEND|UF_IMMUTABLE)) || !uid)))
511 			return (1);
512 		strmode(sp->st_mode, modep);
513 		if ((flagsp = fflagstostr(sp->st_flags)) == NULL)
514 			err(1, "fflagstostr");
515 		if (Pflag)
516 			errx(1,
517 			    "%s: -P was specified, but file is not writable",
518 			    path);
519 		(void)fprintf(stderr, "override %s%s%s/%s %s%sfor %s? ",
520 		    modep + 1, modep[10] == ' ' ? "" : " ",
521 		    user_from_uid(sp->st_uid, 0),
522 		    group_from_gid(sp->st_gid, 0),
523 		    *flagsp ? flagsp : "", *flagsp ? " " : "",
524 		    path);
525 		free(flagsp);
526 	}
527 	(void)fflush(stderr);
528 
529 	first = ch = getchar();
530 	while (ch != '\n' && ch != EOF)
531 		ch = getchar();
532 	return (first == 'y' || first == 'Y');
533 }
534 
535 #define ISSLASH(a)	((a)[0] == '/' && (a)[1] == '\0')
536 static void
537 checkslash(char **argv)
538 {
539 	char **t, **u;
540 	int complained;
541 
542 	complained = 0;
543 	for (t = argv; *t;) {
544 		if (ISSLASH(*t)) {
545 			if (!complained++)
546 				warnx("\"/\" may not be removed");
547 			eval = 1;
548 			for (u = t; u[0] != NULL; ++u)
549 				u[0] = u[1];
550 		} else {
551 			++t;
552 		}
553 	}
554 }
555 
556 static int
557 check2(char **argv)
558 {
559 	struct stat st;
560 	int first;
561 	int ch;
562 	int fcount = 0;
563 	int dcount = 0;
564 	int i;
565 	const char *dname = NULL;
566 
567 	for (i = 0; argv[i]; ++i) {
568 		if (lstat(argv[i], &st) == 0) {
569 			if (S_ISDIR(st.st_mode)) {
570 				++dcount;
571 				dname = argv[i];    /* only used if 1 dir */
572 			} else {
573 				++fcount;
574 			}
575 		}
576 	}
577 	first = 0;
578 	while (first != 'n' && first != 'N' && first != 'y' && first != 'Y') {
579 		if (dcount && rflag) {
580 			fprintf(stderr, "recursively remove");
581 			if (dcount == 1)
582 				fprintf(stderr, " %s", dname);
583 			else
584 				fprintf(stderr, " %d dirs", dcount);
585 			if (fcount == 1)
586 				fprintf(stderr, " and 1 file");
587 			else if (fcount > 1)
588 				fprintf(stderr, " and %d files", fcount);
589 		} else if (dcount + fcount > 3) {
590 			fprintf(stderr, "remove %d files", dcount + fcount);
591 		} else {
592 			return(1);
593 		}
594 		fprintf(stderr, "? ");
595 		fflush(stderr);
596 
597 		first = ch = getchar();
598 		while (ch != '\n' && ch != EOF)
599 			ch = getchar();
600 		if (ch == EOF)
601 			break;
602 	}
603 	return (first == 'y' || first == 'Y');
604 }
605 
606 #define ISDOT(a)	((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
607 static void
608 checkdot(char **argv)
609 {
610 	char *p, **save, **t;
611 	int complained;
612 
613 	complained = 0;
614 	for (t = argv; *t;) {
615 		if ((p = strrchr(*t, '/')) != NULL)
616 			++p;
617 		else
618 			p = *t;
619 		if (ISDOT(p)) {
620 			if (!complained++)
621 				warnx("\".\" and \"..\" may not be removed");
622 			eval = 1;
623 			for (save = t; (t[0] = t[1]) != NULL; ++t)
624 				continue;
625 			t = save;
626 		} else
627 			++t;
628 	}
629 }
630 
631 static void
632 usage(void)
633 {
634 
635 	(void)fprintf(stderr, "%s\n%s\n",
636 	    "usage: rm [-f | -i] [-dIPRrvWx] file ...",
637 	    "       unlink file");
638 	exit(EX_USAGE);
639 }
640 
641 static void
642 siginfo(int sig __unused)
643 {
644 
645 	info = 1;
646 }
647