xref: /openbsd/bin/rm/rm.c (revision f90e70de)
1 /*	$OpenBSD: rm.c,v 1.44 2022/08/16 13:52:41 deraadt Exp $	*/
2 /*	$NetBSD: rm.c,v 1.19 1995/09/07 06:48:50 jtc Exp $	*/
3 
4 /*-
5  * Copyright (c) 1990, 1993, 1994
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <sys/mount.h>
36 
37 #include <err.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <fts.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <limits.h>
46 #include <pwd.h>
47 #include <grp.h>
48 
49 #define MAXIMUM(a, b)	(((a) > (b)) ? (a) : (b))
50 
51 extern char *__progname;
52 
53 int dflag, eval, fflag, iflag, Pflag, vflag, stdin_ok;
54 
55 int	check(char *, char *, struct stat *);
56 void	checkdot(char **);
57 void	rm_file(char **);
58 int	rm_overwrite(char *, struct stat *);
59 int	pass(int, off_t, char *, size_t);
60 void	rm_tree(char **);
61 void	usage(void);
62 
63 /*
64  * rm --
65  *	This rm is different from historic rm's, but is expected to match
66  *	POSIX 1003.2 behavior.  The most visible difference is that -f
67  *	has two specific effects now, ignore non-existent files and force
68  * 	file removal.
69  */
70 int
main(int argc,char * argv[])71 main(int argc, char *argv[])
72 {
73 	int ch, rflag;
74 
75 	Pflag = rflag = 0;
76 	while ((ch = getopt(argc, argv, "dfiPRrv")) != -1)
77 		switch(ch) {
78 		case 'd':
79 			dflag = 1;
80 			break;
81 		case 'f':
82 			fflag = 1;
83 			iflag = 0;
84 			break;
85 		case 'i':
86 			fflag = 0;
87 			iflag = 1;
88 			break;
89 		case 'P':
90 			Pflag = 1;
91 			break;
92 		case 'R':
93 		case 'r':			/* Compatibility. */
94 			rflag = 1;
95 			break;
96 		case 'v':
97 			vflag = 1;
98 			break;
99 		default:
100 			usage();
101 		}
102 	argc -= optind;
103 	argv += optind;
104 
105 	if (Pflag) {
106 		if (pledge("stdio rpath wpath cpath getpw", NULL) == -1)
107 			err(1, "pledge");
108 	} else {
109 		if (pledge("stdio rpath cpath getpw", NULL) == -1)
110 			err(1, "pledge");
111 	}
112 
113 	if (argc < 1 && fflag == 0)
114 		usage();
115 
116 	checkdot(argv);
117 
118 	if (*argv) {
119 		stdin_ok = isatty(STDIN_FILENO);
120 
121 		if (rflag)
122 			rm_tree(argv);
123 		else
124 			rm_file(argv);
125 	}
126 
127 	return (eval);
128 }
129 
130 void
rm_tree(char ** argv)131 rm_tree(char **argv)
132 {
133 	FTS *fts;
134 	FTSENT *p;
135 	int needstat;
136 	int flags;
137 
138 	/*
139 	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
140 	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
141 	 */
142 	needstat = !fflag && !iflag && stdin_ok;
143 
144 	/*
145 	 * If the -i option is specified, the user can skip on the pre-order
146 	 * visit.  The fts_number field flags skipped directories.
147 	 */
148 #define	SKIPPED	1
149 
150 	flags = FTS_PHYSICAL;
151 	if (!needstat)
152 		flags |= FTS_NOSTAT;
153 	if (!(fts = fts_open(argv, flags, NULL)))
154 		err(1, NULL);
155 	while ((p = fts_read(fts)) != NULL) {
156 		switch (p->fts_info) {
157 		case FTS_DNR:
158 			if (!fflag || p->fts_errno != ENOENT) {
159 				warnx("%s: %s",
160 				    p->fts_path, strerror(p->fts_errno));
161 				eval = 1;
162 			}
163 			continue;
164 		case FTS_ERR:
165 			errc(1, p->fts_errno, "%s", p->fts_path);
166 		case FTS_NS:
167 			/*
168 			 * FTS_NS: assume that if can't stat the file, it
169 			 * can't be unlinked.
170 			 */
171 			if (!needstat)
172 				break;
173 			if (!fflag || p->fts_errno != ENOENT) {
174 				warnx("%s: %s",
175 				    p->fts_path, strerror(p->fts_errno));
176 				eval = 1;
177 			}
178 			continue;
179 		case FTS_D:
180 			/* Pre-order: give user chance to skip. */
181 			if (!fflag && !check(p->fts_path, p->fts_accpath,
182 			    p->fts_statp)) {
183 				(void)fts_set(fts, p, FTS_SKIP);
184 				p->fts_number = SKIPPED;
185 			}
186 			continue;
187 		case FTS_DP:
188 			/* Post-order: see if user skipped. */
189 			if (p->fts_number == SKIPPED)
190 				continue;
191 			break;
192 		default:
193 			if (!fflag &&
194 			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
195 				continue;
196 		}
197 
198 		/*
199 		 * If we can't read or search the directory, may still be
200 		 * able to remove it.  Don't print out the un{read,search}able
201 		 * message unless the remove fails.
202 		 */
203 		switch (p->fts_info) {
204 		case FTS_DP:
205 		case FTS_DNR:
206 			if (!rmdir(p->fts_accpath)) {
207 				if (vflag)
208 					fprintf(stdout, "%s\n", p->fts_path);
209 				continue;
210 			}
211 			if (fflag && errno == ENOENT)
212 				continue;
213 			break;
214 
215 		case FTS_F:
216 		case FTS_NSOK:
217 			if (Pflag)
218 				rm_overwrite(p->fts_accpath, p->fts_info ==
219 				    FTS_NSOK ? NULL : p->fts_statp);
220 			/* FALLTHROUGH */
221 		default:
222 			if (!unlink(p->fts_accpath)) {
223 				if (vflag)
224 					fprintf(stdout, "%s\n", p->fts_path);
225 				continue;
226 			}
227 			if (fflag && errno == ENOENT)
228 				continue;
229 		}
230 		warn("%s", p->fts_path);
231 		eval = 1;
232 	}
233 	if (errno)
234 		err(1, "fts_read");
235 	fts_close(fts);
236 }
237 
238 void
rm_file(char ** argv)239 rm_file(char **argv)
240 {
241 	struct stat sb;
242 	int rval;
243 	char *f;
244 
245 	/*
246 	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
247 	 * to remove a directory is an error, so must always stat the file.
248 	 */
249 	while ((f = *argv++) != NULL) {
250 		/* Assume if can't stat the file, can't unlink it. */
251 		if (lstat(f, &sb)) {
252 			if (!fflag || errno != ENOENT) {
253 				warn("%s", f);
254 				eval = 1;
255 			}
256 			continue;
257 		}
258 
259 		if (S_ISDIR(sb.st_mode) && !dflag) {
260 			warnx("%s: is a directory", f);
261 			eval = 1;
262 			continue;
263 		}
264 		if (!fflag && !check(f, f, &sb))
265 			continue;
266 		else if (S_ISDIR(sb.st_mode))
267 			rval = rmdir(f);
268 		else {
269 			if (Pflag)
270 				rm_overwrite(f, &sb);
271 			rval = unlink(f);
272 		}
273 		if (rval && (!fflag || errno != ENOENT)) {
274 			warn("%s", f);
275 			eval = 1;
276 		} else if (rval == 0 && vflag)
277 			(void)fprintf(stdout, "%s\n", f);
278 	}
279 }
280 
281 /*
282  * rm_overwrite --
283  *	Overwrite the file with varying bit patterns.
284  *
285  * XXX
286  * This is a cheap way to *really* delete files.  Note that only regular
287  * files are deleted, directories (and therefore names) will remain.
288  * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
289  * System V file system).  In a logging file system, you'll have to have
290  * kernel support.
291  * Returns 1 for success.
292  */
293 int
rm_overwrite(char * file,struct stat * sbp)294 rm_overwrite(char *file, struct stat *sbp)
295 {
296 	struct stat sb, sb2;
297 	struct statfs fsb;
298 	size_t bsize;
299 	int fd;
300 	char *buf = NULL;
301 
302 	fd = -1;
303 	if (sbp == NULL) {
304 		if (lstat(file, &sb))
305 			goto err;
306 		sbp = &sb;
307 	}
308 	if (!S_ISREG(sbp->st_mode))
309 		return (1);
310 	if (sbp->st_nlink > 1) {
311 		warnx("%s (inode %llu): not overwritten due to multiple links",
312 		    file, (unsigned long long)sbp->st_ino);
313 		return (0);
314 	}
315 	if ((fd = open(file, O_WRONLY|O_NONBLOCK|O_NOFOLLOW)) == -1)
316 		goto err;
317 	if (fstat(fd, &sb2))
318 		goto err;
319 	if (sb2.st_dev != sbp->st_dev || sb2.st_ino != sbp->st_ino ||
320 	    !S_ISREG(sb2.st_mode)) {
321 		errno = EPERM;
322 		goto err;
323 	}
324 	if (fstatfs(fd, &fsb) == -1)
325 		goto err;
326 	bsize = MAXIMUM(fsb.f_iosize, 1024U);
327 	if ((buf = malloc(bsize)) == NULL)
328 		err(1, "%s: malloc", file);
329 
330 	if (!pass(fd, sbp->st_size, buf, bsize))
331 		goto err;
332 	if (fsync(fd))
333 		goto err;
334 	close(fd);
335 	free(buf);
336 	return (1);
337 
338 err:
339 	warn("%s", file);
340 	close(fd);
341 	eval = 1;
342 	free(buf);
343 	return (0);
344 }
345 
346 int
pass(int fd,off_t len,char * buf,size_t bsize)347 pass(int fd, off_t len, char *buf, size_t bsize)
348 {
349 	size_t wlen;
350 
351 	for (; len > 0; len -= wlen) {
352 		wlen = len < bsize ? len : bsize;
353 		arc4random_buf(buf, wlen);
354 		if (write(fd, buf, wlen) != wlen)
355 			return (0);
356 	}
357 	return (1);
358 }
359 
360 int
check(char * path,char * name,struct stat * sp)361 check(char *path, char *name, struct stat *sp)
362 {
363 	int ch, first;
364 	char modep[15];
365 
366 	/* Check -i first. */
367 	if (iflag)
368 		(void)fprintf(stderr, "remove %s? ", path);
369 	else {
370 		/*
371 		 * If it's not a symbolic link and it's unwritable and we're
372 		 * talking to a terminal, ask.  Symbolic links are excluded
373 		 * because their permissions are meaningless.  Check stdin_ok
374 		 * first because we may not have stat'ed the file.
375 		 */
376 		if (!stdin_ok || S_ISLNK(sp->st_mode) || !access(name, W_OK) ||
377 		    errno != EACCES)
378 			return (1);
379 		strmode(sp->st_mode, modep);
380 		(void)fprintf(stderr, "override %s%s%s/%s for %s? ",
381 		    modep + 1, modep[9] == ' ' ? "" : " ",
382 		    user_from_uid(sp->st_uid, 0),
383 		    group_from_gid(sp->st_gid, 0), path);
384 	}
385 	(void)fflush(stderr);
386 
387 	first = ch = getchar();
388 	while (ch != '\n' && ch != EOF)
389 		ch = getchar();
390 	return (first == 'y' || first == 'Y');
391 }
392 
393 /*
394  * POSIX.2 requires that if "." or ".." are specified as the basename
395  * portion of an operand, a diagnostic message be written to standard
396  * error and nothing more be done with such operands.
397  *
398  * Since POSIX.2 defines basename as the final portion of a path after
399  * trailing slashes have been removed, we'll remove them here.
400  */
401 #define ISDOT(a) ((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
402 void
checkdot(char ** argv)403 checkdot(char **argv)
404 {
405 	char *p, **save, **t;
406 	int complained;
407 	struct stat sb, root;
408 
409 	stat("/", &root);
410 	complained = 0;
411 	for (t = argv; *t;) {
412 		if (lstat(*t, &sb) == 0 &&
413 		    root.st_ino == sb.st_ino && root.st_dev == sb.st_dev) {
414 			if (!complained++)
415 				warnx("\"/\" may not be removed");
416 			goto skip;
417 		}
418 		/* strip trailing slashes */
419 		p = strrchr(*t, '\0');
420 		while (--p > *t && *p == '/')
421 			*p = '\0';
422 
423 		/* extract basename */
424 		if ((p = strrchr(*t, '/')) != NULL)
425 			++p;
426 		else
427 			p = *t;
428 
429 		if (ISDOT(p)) {
430 			if (!complained++)
431 				warnx("\".\" and \"..\" may not be removed");
432 skip:
433 			eval = 1;
434 			for (save = t; (t[0] = t[1]) != NULL; ++t)
435 				continue;
436 			t = save;
437 		} else
438 			++t;
439 	}
440 }
441 
442 void
usage(void)443 usage(void)
444 {
445 	(void)fprintf(stderr, "usage: %s [-dfiPRrv] file ...\n", __progname);
446 	exit(1);
447 }
448