xref: /freebsd/bin/rm/rm.c (revision 732a02b4e77866604a120a275c082bb6221bd2ff)
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, 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 void	rm_tree(char **);
75 static void siginfo(int __unused);
76 static void	usage(void);
77 
78 /*
79  * rm --
80  *	This rm is different from historic rm's, but is expected to match
81  *	POSIX 1003.2 behavior.	The most visible difference is that -f
82  *	has two specific effects now, ignore non-existent files and force
83  *	file removal.
84  */
85 int
86 main(int argc, char *argv[])
87 {
88 	int ch;
89 	char *p;
90 
91 	(void)setlocale(LC_ALL, "");
92 
93 	/*
94 	 * Test for the special case where the utility is called as
95 	 * "unlink", for which the functionality provided is greatly
96 	 * simplified.
97 	 */
98 	if ((p = strrchr(argv[0], '/')) == NULL)
99 		p = argv[0];
100 	else
101 		++p;
102 	if (strcmp(p, "unlink") == 0) {
103 		if (argc == 2)
104 			rm_file(&argv[1]);
105 		else if (argc == 3 && strcmp(argv[1], "--") == 0)
106 			rm_file(&argv[2]);
107 		else
108 			usage();
109 		exit(eval);
110 	}
111 
112 	rflag = xflag = 0;
113 	while ((ch = getopt(argc, argv, "dfiIPRrvWx")) != -1)
114 		switch(ch) {
115 		case 'd':
116 			dflag = 1;
117 			break;
118 		case 'f':
119 			fflag = 1;
120 			iflag = 0;
121 			break;
122 		case 'i':
123 			fflag = 0;
124 			iflag = 1;
125 			break;
126 		case 'I':
127 			Iflag = 1;
128 			break;
129 		case 'P':
130 			/* Compatibility no-op. */
131 			break;
132 		case 'R':
133 		case 'r':			/* Compatibility. */
134 			rflag = 1;
135 			break;
136 		case 'v':
137 			vflag = 1;
138 			break;
139 		case 'W':
140 			Wflag = 1;
141 			break;
142 		case 'x':
143 			xflag = 1;
144 			break;
145 		default:
146 			usage();
147 		}
148 	argc -= optind;
149 	argv += optind;
150 
151 	if (argc < 1) {
152 		if (fflag)
153 			return (0);
154 		usage();
155 	}
156 
157 	checkdot(argv);
158 	checkslash(argv);
159 	uid = geteuid();
160 
161 	(void)signal(SIGINFO, siginfo);
162 	if (*argv) {
163 		stdin_ok = isatty(STDIN_FILENO);
164 
165 		if (Iflag) {
166 			if (check2(argv) == 0)
167 				exit (1);
168 		}
169 		if (rflag)
170 			rm_tree(argv);
171 		else
172 			rm_file(argv);
173 	}
174 
175 	exit (eval);
176 }
177 
178 static void
179 rm_tree(char **argv)
180 {
181 	FTS *fts;
182 	FTSENT *p;
183 	int needstat;
184 	int flags;
185 	int rval;
186 
187 	/*
188 	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
189 	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
190 	 */
191 	needstat = !uid || (!fflag && !iflag && stdin_ok);
192 
193 	/*
194 	 * If the -i option is specified, the user can skip on the pre-order
195 	 * visit.  The fts_number field flags skipped directories.
196 	 */
197 #define	SKIPPED	1
198 
199 	flags = FTS_PHYSICAL;
200 	if (!needstat)
201 		flags |= FTS_NOSTAT;
202 	if (Wflag)
203 		flags |= FTS_WHITEOUT;
204 	if (xflag)
205 		flags |= FTS_XDEV;
206 	if (!(fts = fts_open(argv, flags, NULL))) {
207 		if (fflag && errno == ENOENT)
208 			return;
209 		err(1, "fts_open");
210 	}
211 	while ((p = fts_read(fts)) != NULL) {
212 		switch (p->fts_info) {
213 		case FTS_DNR:
214 			if (!fflag || p->fts_errno != ENOENT) {
215 				warnx("%s: %s",
216 				    p->fts_path, strerror(p->fts_errno));
217 				eval = 1;
218 			}
219 			continue;
220 		case FTS_ERR:
221 			errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
222 		case FTS_NS:
223 			/*
224 			 * Assume that since fts_read() couldn't stat the
225 			 * file, it can't be unlinked.
226 			 */
227 			if (!needstat)
228 				break;
229 			if (!fflag || p->fts_errno != ENOENT) {
230 				warnx("%s: %s",
231 				    p->fts_path, strerror(p->fts_errno));
232 				eval = 1;
233 			}
234 			continue;
235 		case FTS_D:
236 			/* Pre-order: give user chance to skip. */
237 			if (!fflag && !check(p->fts_path, p->fts_accpath,
238 			    p->fts_statp)) {
239 				(void)fts_set(fts, p, FTS_SKIP);
240 				p->fts_number = SKIPPED;
241 			}
242 			else if (!uid &&
243 				 (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
244 				 !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
245 				 lchflags(p->fts_accpath,
246 					 p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE)) < 0)
247 				goto err;
248 			continue;
249 		case FTS_DP:
250 			/* Post-order: see if user skipped. */
251 			if (p->fts_number == SKIPPED)
252 				continue;
253 			break;
254 		default:
255 			if (!fflag &&
256 			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
257 				continue;
258 		}
259 
260 		rval = 0;
261 		if (!uid &&
262 		    (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
263 		    !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)))
264 			rval = lchflags(p->fts_accpath,
265 				       p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
266 		if (rval == 0) {
267 			/*
268 			 * If we can't read or search the directory, may still be
269 			 * able to remove it.  Don't print out the un{read,search}able
270 			 * message unless the remove fails.
271 			 */
272 			switch (p->fts_info) {
273 			case FTS_DP:
274 			case FTS_DNR:
275 				rval = rmdir(p->fts_accpath);
276 				if (rval == 0 || (fflag && errno == ENOENT)) {
277 					if (rval == 0 && vflag)
278 						(void)printf("%s\n",
279 						    p->fts_path);
280 					if (rval == 0 && info) {
281 						info = 0;
282 						(void)printf("%s\n",
283 						    p->fts_path);
284 					}
285 					continue;
286 				}
287 				break;
288 
289 			case FTS_W:
290 				rval = undelete(p->fts_accpath);
291 				if (rval == 0 && (fflag && errno == ENOENT)) {
292 					if (vflag)
293 						(void)printf("%s\n",
294 						    p->fts_path);
295 					if (info) {
296 						info = 0;
297 						(void)printf("%s\n",
298 						    p->fts_path);
299 					}
300 					continue;
301 				}
302 				break;
303 
304 			case FTS_NS:
305 				/*
306 				 * Assume that since fts_read() couldn't stat
307 				 * the file, it can't be unlinked.
308 				 */
309 				if (fflag)
310 					continue;
311 				/* FALLTHROUGH */
312 
313 			case FTS_F:
314 			case FTS_NSOK:
315 			default:
316 				rval = unlink(p->fts_accpath);
317 				if (rval == 0 || (fflag && errno == ENOENT)) {
318 					if (rval == 0 && vflag)
319 						(void)printf("%s\n",
320 						    p->fts_path);
321 					if (rval == 0 && info) {
322 						info = 0;
323 						(void)printf("%s\n",
324 						    p->fts_path);
325 					}
326 					continue;
327 				}
328 			}
329 		}
330 err:
331 		warn("%s", p->fts_path);
332 		eval = 1;
333 	}
334 	if (!fflag && errno)
335 		err(1, "fts_read");
336 	fts_close(fts);
337 }
338 
339 static void
340 rm_file(char **argv)
341 {
342 	struct stat sb;
343 	int rval;
344 	char *f;
345 
346 	/*
347 	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
348 	 * to remove a directory is an error, so must always stat the file.
349 	 */
350 	while ((f = *argv++) != NULL) {
351 		/* Assume if can't stat the file, can't unlink it. */
352 		if (lstat(f, &sb)) {
353 			if (Wflag) {
354 				sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
355 			} else {
356 				if (!fflag || errno != ENOENT) {
357 					warn("%s", f);
358 					eval = 1;
359 				}
360 				continue;
361 			}
362 		} else if (Wflag) {
363 			warnx("%s: %s", f, strerror(EEXIST));
364 			eval = 1;
365 			continue;
366 		}
367 
368 		if (S_ISDIR(sb.st_mode) && !dflag) {
369 			warnx("%s: is a directory", f);
370 			eval = 1;
371 			continue;
372 		}
373 		if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
374 			continue;
375 		rval = 0;
376 		if (!uid && !S_ISWHT(sb.st_mode) &&
377 		    (sb.st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
378 		    !(sb.st_flags & (SF_APPEND|SF_IMMUTABLE)))
379 			rval = lchflags(f, sb.st_flags & ~(UF_APPEND|UF_IMMUTABLE));
380 		if (rval == 0) {
381 			if (S_ISWHT(sb.st_mode))
382 				rval = undelete(f);
383 			else if (S_ISDIR(sb.st_mode))
384 				rval = rmdir(f);
385 			else
386 				rval = unlink(f);
387 		}
388 		if (rval && (!fflag || errno != ENOENT)) {
389 			warn("%s", f);
390 			eval = 1;
391 		}
392 		if (vflag && rval == 0)
393 			(void)printf("%s\n", f);
394 		if (info && rval == 0) {
395 			info = 0;
396 			(void)printf("%s\n", f);
397 		}
398 	}
399 }
400 
401 static int
402 check(const char *path, const char *name, struct stat *sp)
403 {
404 	int ch, first;
405 	char modep[15], *flagsp;
406 
407 	/* Check -i first. */
408 	if (iflag)
409 		(void)fprintf(stderr, "remove %s? ", path);
410 	else {
411 		/*
412 		 * If it's not a symbolic link and it's unwritable and we're
413 		 * talking to a terminal, ask.  Symbolic links are excluded
414 		 * because their permissions are meaningless.  Check stdin_ok
415 		 * first because we may not have stat'ed the file.
416 		 */
417 		if (!stdin_ok || S_ISLNK(sp->st_mode) ||
418 		    (!access(name, W_OK) &&
419 		    !(sp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
420 		    (!(sp->st_flags & (UF_APPEND|UF_IMMUTABLE)) || !uid)))
421 			return (1);
422 		strmode(sp->st_mode, modep);
423 		if ((flagsp = fflagstostr(sp->st_flags)) == NULL)
424 			err(1, "fflagstostr");
425 		(void)fprintf(stderr, "override %s%s%s/%s %s%sfor %s? ",
426 		    modep + 1, modep[10] == ' ' ? "" : " ",
427 		    user_from_uid(sp->st_uid, 0),
428 		    group_from_gid(sp->st_gid, 0),
429 		    *flagsp ? flagsp : "", *flagsp ? " " : "",
430 		    path);
431 		free(flagsp);
432 	}
433 	(void)fflush(stderr);
434 
435 	first = ch = getchar();
436 	while (ch != '\n' && ch != EOF)
437 		ch = getchar();
438 	return (first == 'y' || first == 'Y');
439 }
440 
441 #define ISSLASH(a)	((a)[0] == '/' && (a)[1] == '\0')
442 static void
443 checkslash(char **argv)
444 {
445 	char **t, **u;
446 	int complained;
447 
448 	complained = 0;
449 	for (t = argv; *t;) {
450 		if (ISSLASH(*t)) {
451 			if (!complained++)
452 				warnx("\"/\" may not be removed");
453 			eval = 1;
454 			for (u = t; u[0] != NULL; ++u)
455 				u[0] = u[1];
456 		} else {
457 			++t;
458 		}
459 	}
460 }
461 
462 static int
463 check2(char **argv)
464 {
465 	struct stat st;
466 	int first;
467 	int ch;
468 	int fcount = 0;
469 	int dcount = 0;
470 	int i;
471 	const char *dname = NULL;
472 
473 	for (i = 0; argv[i]; ++i) {
474 		if (lstat(argv[i], &st) == 0) {
475 			if (S_ISDIR(st.st_mode)) {
476 				++dcount;
477 				dname = argv[i];    /* only used if 1 dir */
478 			} else {
479 				++fcount;
480 			}
481 		}
482 	}
483 	first = 0;
484 	while (first != 'n' && first != 'N' && first != 'y' && first != 'Y') {
485 		if (dcount && rflag) {
486 			fprintf(stderr, "recursively remove");
487 			if (dcount == 1)
488 				fprintf(stderr, " %s", dname);
489 			else
490 				fprintf(stderr, " %d dirs", dcount);
491 			if (fcount == 1)
492 				fprintf(stderr, " and 1 file");
493 			else if (fcount > 1)
494 				fprintf(stderr, " and %d files", fcount);
495 		} else if (dcount + fcount > 3) {
496 			fprintf(stderr, "remove %d files", dcount + fcount);
497 		} else {
498 			return(1);
499 		}
500 		fprintf(stderr, "? ");
501 		fflush(stderr);
502 
503 		first = ch = getchar();
504 		while (ch != '\n' && ch != EOF)
505 			ch = getchar();
506 		if (ch == EOF)
507 			break;
508 	}
509 	return (first == 'y' || first == 'Y');
510 }
511 
512 #define ISDOT(a)	((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
513 static void
514 checkdot(char **argv)
515 {
516 	char *p, **save, **t;
517 	int complained;
518 
519 	complained = 0;
520 	for (t = argv; *t;) {
521 		if ((p = strrchr(*t, '/')) != NULL)
522 			++p;
523 		else
524 			p = *t;
525 		if (ISDOT(p)) {
526 			if (!complained++)
527 				warnx("\".\" and \"..\" may not be removed");
528 			eval = 1;
529 			for (save = t; (t[0] = t[1]) != NULL; ++t)
530 				continue;
531 			t = save;
532 		} else
533 			++t;
534 	}
535 }
536 
537 static void
538 usage(void)
539 {
540 
541 	(void)fprintf(stderr, "%s\n%s\n",
542 	    "usage: rm [-f | -i] [-dIPRrvWx] file ...",
543 	    "       unlink [--] file");
544 	exit(EX_USAGE);
545 }
546 
547 static void
548 siginfo(int sig __unused)
549 {
550 
551 	info = 1;
552 }
553