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
34static 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
40static 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
64static int dflag, eval, fflag, iflag, Pflag, vflag, Wflag, stdin_ok;
65static int rflag, Iflag, xflag;
66static uid_t uid;
67static volatile sig_atomic_t info;
68
69static int	check(const char *, const char *, struct stat *);
70static int	check2(char **);
71static void	checkdot(char **);
72static void	checkslash(char **);
73static void	rm_file(char **);
74static int	rm_overwrite(const char *, struct stat *);
75static void	rm_tree(char **);
76static void siginfo(int __unused);
77static 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 */
86int
87main(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		if (argc == 2)
105			rm_file(&argv[1]);
106		else if (argc == 3 && strcmp(argv[1], "--") == 0)
107			rm_file(&argv[2]);
108		else
109			usage();
110		exit(eval);
111	}
112
113	Pflag = rflag = xflag = 0;
114	while ((ch = getopt(argc, argv, "dfiIPRrvWx")) != -1)
115		switch(ch) {
116		case 'd':
117			dflag = 1;
118			break;
119		case 'f':
120			fflag = 1;
121			iflag = 0;
122			break;
123		case 'i':
124			fflag = 0;
125			iflag = 1;
126			break;
127		case 'I':
128			Iflag = 1;
129			break;
130		case 'P':
131			Pflag = 1;
132			break;
133		case 'R':
134		case 'r':			/* Compatibility. */
135			rflag = 1;
136			break;
137		case 'v':
138			vflag = 1;
139			break;
140		case 'W':
141			Wflag = 1;
142			break;
143		case 'x':
144			xflag = 1;
145			break;
146		default:
147			usage();
148		}
149	argc -= optind;
150	argv += optind;
151
152	if (argc < 1) {
153		if (fflag)
154			return (0);
155		usage();
156	}
157
158	checkdot(argv);
159	checkslash(argv);
160	uid = geteuid();
161
162	(void)signal(SIGINFO, siginfo);
163	if (*argv) {
164		stdin_ok = isatty(STDIN_FILENO);
165
166		if (Iflag) {
167			if (check2(argv) == 0)
168				exit (1);
169		}
170		if (rflag)
171			rm_tree(argv);
172		else
173			rm_file(argv);
174	}
175
176	exit (eval);
177}
178
179static void
180rm_tree(char **argv)
181{
182	FTS *fts;
183	FTSENT *p;
184	int needstat;
185	int flags;
186	int rval;
187
188	/*
189	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
190	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
191	 */
192	needstat = !uid || (!fflag && !iflag && stdin_ok);
193
194	/*
195	 * If the -i option is specified, the user can skip on the pre-order
196	 * visit.  The fts_number field flags skipped directories.
197	 */
198#define	SKIPPED	1
199
200	flags = FTS_PHYSICAL;
201	if (!needstat)
202		flags |= FTS_NOSTAT;
203	if (Wflag)
204		flags |= FTS_WHITEOUT;
205	if (xflag)
206		flags |= FTS_XDEV;
207	if (!(fts = fts_open(argv, flags, NULL))) {
208		if (fflag && errno == ENOENT)
209			return;
210		err(1, "fts_open");
211	}
212	while ((p = fts_read(fts)) != NULL) {
213		switch (p->fts_info) {
214		case FTS_DNR:
215			if (!fflag || p->fts_errno != ENOENT) {
216				warnx("%s: %s",
217				    p->fts_path, strerror(p->fts_errno));
218				eval = 1;
219			}
220			continue;
221		case FTS_ERR:
222			errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
223		case FTS_NS:
224			/*
225			 * Assume that since fts_read() couldn't stat the
226			 * file, it can't be unlinked.
227			 */
228			if (!needstat)
229				break;
230			if (!fflag || p->fts_errno != ENOENT) {
231				warnx("%s: %s",
232				    p->fts_path, strerror(p->fts_errno));
233				eval = 1;
234			}
235			continue;
236		case FTS_D:
237			/* Pre-order: give user chance to skip. */
238			if (!fflag && !check(p->fts_path, p->fts_accpath,
239			    p->fts_statp)) {
240				(void)fts_set(fts, p, FTS_SKIP);
241				p->fts_number = SKIPPED;
242			}
243			else if (!uid &&
244				 (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
245				 !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
246				 lchflags(p->fts_accpath,
247					 p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE)) < 0)
248				goto err;
249			continue;
250		case FTS_DP:
251			/* Post-order: see if user skipped. */
252			if (p->fts_number == SKIPPED)
253				continue;
254			break;
255		default:
256			if (!fflag &&
257			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
258				continue;
259		}
260
261		rval = 0;
262		if (!uid &&
263		    (p->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
264		    !(p->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)))
265			rval = lchflags(p->fts_accpath,
266				       p->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
267		if (rval == 0) {
268			/*
269			 * If we can't read or search the directory, may still be
270			 * able to remove it.  Don't print out the un{read,search}able
271			 * message unless the remove fails.
272			 */
273			switch (p->fts_info) {
274			case FTS_DP:
275			case FTS_DNR:
276				rval = rmdir(p->fts_accpath);
277				if (rval == 0 || (fflag && errno == ENOENT)) {
278					if (rval == 0 && vflag)
279						(void)printf("%s\n",
280						    p->fts_path);
281					if (rval == 0 && info) {
282						info = 0;
283						(void)printf("%s\n",
284						    p->fts_path);
285					}
286					continue;
287				}
288				break;
289
290			case FTS_W:
291				rval = undelete(p->fts_accpath);
292				if (rval == 0 && (fflag && errno == ENOENT)) {
293					if (vflag)
294						(void)printf("%s\n",
295						    p->fts_path);
296					if (info) {
297						info = 0;
298						(void)printf("%s\n",
299						    p->fts_path);
300					}
301					continue;
302				}
303				break;
304
305			case FTS_NS:
306				/*
307				 * Assume that since fts_read() couldn't stat
308				 * the file, it can't be unlinked.
309				 */
310				if (fflag)
311					continue;
312				/* FALLTHROUGH */
313
314			case FTS_F:
315			case FTS_NSOK:
316				if (Pflag)
317					if (!rm_overwrite(p->fts_accpath, p->fts_info ==
318					    FTS_NSOK ? NULL : p->fts_statp))
319						continue;
320				/* FALLTHROUGH */
321
322			default:
323				rval = unlink(p->fts_accpath);
324				if (rval == 0 || (fflag && errno == ENOENT)) {
325					if (rval == 0 && vflag)
326						(void)printf("%s\n",
327						    p->fts_path);
328					if (rval == 0 && info) {
329						info = 0;
330						(void)printf("%s\n",
331						    p->fts_path);
332					}
333					continue;
334				}
335			}
336		}
337err:
338		warn("%s", p->fts_path);
339		eval = 1;
340	}
341	if (!fflag && errno)
342		err(1, "fts_read");
343	fts_close(fts);
344}
345
346static void
347rm_file(char **argv)
348{
349	struct stat sb;
350	int rval;
351	char *f;
352
353	/*
354	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
355	 * to remove a directory is an error, so must always stat the file.
356	 */
357	while ((f = *argv++) != NULL) {
358		/* Assume if can't stat the file, can't unlink it. */
359		if (lstat(f, &sb)) {
360			if (Wflag) {
361				sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
362			} else {
363				if (!fflag || errno != ENOENT) {
364					warn("%s", f);
365					eval = 1;
366				}
367				continue;
368			}
369		} else if (Wflag) {
370			warnx("%s: %s", f, strerror(EEXIST));
371			eval = 1;
372			continue;
373		}
374
375		if (S_ISDIR(sb.st_mode) && !dflag) {
376			warnx("%s: is a directory", f);
377			eval = 1;
378			continue;
379		}
380		if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
381			continue;
382		rval = 0;
383		if (!uid && !S_ISWHT(sb.st_mode) &&
384		    (sb.st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
385		    !(sb.st_flags & (SF_APPEND|SF_IMMUTABLE)))
386			rval = lchflags(f, sb.st_flags & ~(UF_APPEND|UF_IMMUTABLE));
387		if (rval == 0) {
388			if (S_ISWHT(sb.st_mode))
389				rval = undelete(f);
390			else if (S_ISDIR(sb.st_mode))
391				rval = rmdir(f);
392			else {
393				if (Pflag)
394					if (!rm_overwrite(f, &sb))
395						continue;
396				rval = unlink(f);
397			}
398		}
399		if (rval && (!fflag || errno != ENOENT)) {
400			warn("%s", f);
401			eval = 1;
402		}
403		if (vflag && rval == 0)
404			(void)printf("%s\n", f);
405		if (info && rval == 0) {
406			info = 0;
407			(void)printf("%s\n", f);
408		}
409	}
410}
411
412/*
413 * rm_overwrite --
414 *	Overwrite the file 3 times with varying bit patterns.
415 *
416 * XXX
417 * This is a cheap way to *really* delete files.  Note that only regular
418 * files are deleted, directories (and therefore names) will remain.
419 * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
420 * System V file system).  In a logging or COW file system, you'll have to
421 * have kernel support.
422 */
423static int
424rm_overwrite(const char *file, struct stat *sbp)
425{
426	struct stat sb, sb2;
427	struct statfs fsb;
428	off_t len;
429	int bsize, fd, wlen;
430	char *buf = NULL;
431
432	fd = -1;
433	if (sbp == NULL) {
434		if (lstat(file, &sb))
435			goto err;
436		sbp = &sb;
437	}
438	if (!S_ISREG(sbp->st_mode))
439		return (1);
440	if (sbp->st_nlink > 1 && !fflag) {
441		warnx("%s (inode %ju): not overwritten due to multiple links",
442		    file, (uintmax_t)sbp->st_ino);
443		return (0);
444	}
445	if ((fd = open(file, O_WRONLY|O_NONBLOCK|O_NOFOLLOW, 0)) == -1)
446		goto err;
447	if (fstat(fd, &sb2))
448		goto err;
449	if (sb2.st_dev != sbp->st_dev || sb2.st_ino != sbp->st_ino ||
450	    !S_ISREG(sb2.st_mode)) {
451		errno = EPERM;
452		goto err;
453	}
454	if (fstatfs(fd, &fsb) == -1)
455		goto err;
456	bsize = MAX(fsb.f_iosize, 1024);
457	if ((buf = malloc(bsize)) == NULL)
458		err(1, "%s: malloc", file);
459
460#define	PASS(byte) {							\
461	memset(buf, byte, bsize);					\
462	for (len = sbp->st_size; len > 0; len -= wlen) {		\
463		wlen = len < bsize ? len : bsize;			\
464		if (write(fd, buf, wlen) != wlen)			\
465			goto err;					\
466	}								\
467}
468	PASS(0xff);
469	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
470		goto err;
471	PASS(0x00);
472	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
473		goto err;
474	PASS(0xff);
475	if (!fsync(fd) && !close(fd)) {
476		free(buf);
477		return (1);
478	}
479
480err:	eval = 1;
481	if (buf)
482		free(buf);
483	if (fd != -1)
484		close(fd);
485	warn("%s", file);
486	return (0);
487}
488
489
490static int
491check(const char *path, const char *name, struct stat *sp)
492{
493	int ch, first;
494	char modep[15], *flagsp;
495
496	/* Check -i first. */
497	if (iflag)
498		(void)fprintf(stderr, "remove %s? ", path);
499	else {
500		/*
501		 * If it's not a symbolic link and it's unwritable and we're
502		 * talking to a terminal, ask.  Symbolic links are excluded
503		 * because their permissions are meaningless.  Check stdin_ok
504		 * first because we may not have stat'ed the file.
505		 */
506		if (!stdin_ok || S_ISLNK(sp->st_mode) ||
507		    (!access(name, W_OK) &&
508		    !(sp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
509		    (!(sp->st_flags & (UF_APPEND|UF_IMMUTABLE)) || !uid)))
510			return (1);
511		strmode(sp->st_mode, modep);
512		if ((flagsp = fflagstostr(sp->st_flags)) == NULL)
513			err(1, "fflagstostr");
514		if (Pflag)
515			errx(1,
516			    "%s: -P was specified, but file is not writable",
517			    path);
518		(void)fprintf(stderr, "override %s%s%s/%s %s%sfor %s? ",
519		    modep + 1, modep[10] == ' ' ? "" : " ",
520		    user_from_uid(sp->st_uid, 0),
521		    group_from_gid(sp->st_gid, 0),
522		    *flagsp ? flagsp : "", *flagsp ? " " : "",
523		    path);
524		free(flagsp);
525	}
526	(void)fflush(stderr);
527
528	first = ch = getchar();
529	while (ch != '\n' && ch != EOF)
530		ch = getchar();
531	return (first == 'y' || first == 'Y');
532}
533
534#define ISSLASH(a)	((a)[0] == '/' && (a)[1] == '\0')
535static void
536checkslash(char **argv)
537{
538	char **t, **u;
539	int complained;
540
541	complained = 0;
542	for (t = argv; *t;) {
543		if (ISSLASH(*t)) {
544			if (!complained++)
545				warnx("\"/\" may not be removed");
546			eval = 1;
547			for (u = t; u[0] != NULL; ++u)
548				u[0] = u[1];
549		} else {
550			++t;
551		}
552	}
553}
554
555static int
556check2(char **argv)
557{
558	struct stat st;
559	int first;
560	int ch;
561	int fcount = 0;
562	int dcount = 0;
563	int i;
564	const char *dname = NULL;
565
566	for (i = 0; argv[i]; ++i) {
567		if (lstat(argv[i], &st) == 0) {
568			if (S_ISDIR(st.st_mode)) {
569				++dcount;
570				dname = argv[i];    /* only used if 1 dir */
571			} else {
572				++fcount;
573			}
574		}
575	}
576	first = 0;
577	while (first != 'n' && first != 'N' && first != 'y' && first != 'Y') {
578		if (dcount && rflag) {
579			fprintf(stderr, "recursively remove");
580			if (dcount == 1)
581				fprintf(stderr, " %s", dname);
582			else
583				fprintf(stderr, " %d dirs", dcount);
584			if (fcount == 1)
585				fprintf(stderr, " and 1 file");
586			else if (fcount > 1)
587				fprintf(stderr, " and %d files", fcount);
588		} else if (dcount + fcount > 3) {
589			fprintf(stderr, "remove %d files", dcount + fcount);
590		} else {
591			return(1);
592		}
593		fprintf(stderr, "? ");
594		fflush(stderr);
595
596		first = ch = getchar();
597		while (ch != '\n' && ch != EOF)
598			ch = getchar();
599		if (ch == EOF)
600			break;
601	}
602	return (first == 'y' || first == 'Y');
603}
604
605#define ISDOT(a)	((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
606static void
607checkdot(char **argv)
608{
609	char *p, **save, **t;
610	int complained;
611
612	complained = 0;
613	for (t = argv; *t;) {
614		if ((p = strrchr(*t, '/')) != NULL)
615			++p;
616		else
617			p = *t;
618		if (ISDOT(p)) {
619			if (!complained++)
620				warnx("\".\" and \"..\" may not be removed");
621			eval = 1;
622			for (save = t; (t[0] = t[1]) != NULL; ++t)
623				continue;
624			t = save;
625		} else
626			++t;
627	}
628}
629
630static void
631usage(void)
632{
633
634	(void)fprintf(stderr, "%s\n%s\n",
635	    "usage: rm [-f | -i] [-dIPRrvWx] file ...",
636	    "       unlink [--] file");
637	exit(EX_USAGE);
638}
639
640static void
641siginfo(int sig __unused)
642{
643
644	info = 1;
645}
646