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