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