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