rm.c revision 1.1
1/*	$OpenBSD: rm.c,v 1.1 2015/11/17 17:24:26 tedu 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 <locale.h>
38#include <err.h>
39#include <errno.h>
40#include <fcntl.h>
41#include <fts.h>
42#include <stdio.h>
43#include <stdlib.h>
44#include <string.h>
45#include <unistd.h>
46#include <limits.h>
47#include <pwd.h>
48#include <grp.h>
49
50#define MAXIMUM(a, b)	(((a) > (b)) ? (a) : (b))
51
52extern char *__progname;
53
54static int dflag, eval, fflag, iflag, Pflag, stdin_ok;
55
56static int	check(char *, char *, struct stat *);
57static void	checkdot(char **);
58static void	rm_file(char **);
59static int	rm_overwrite(char *, struct stat *);
60static int	pass(int, off_t, char *, size_t);
61static void	rm_tree(char **);
62
63static void __dead
64usage(void)
65{
66	(void)fprintf(stderr, "usage: %s [-dfiPRr] file ...\n", __progname);
67	exit(1);
68}
69
70/*
71 * rm --
72 *	This rm is different from historic rm's, but is expected to match
73 *	POSIX 1003.2 behavior.  The most visible difference is that -f
74 *	has two specific effects now, ignore non-existent files and force
75 * 	file removal.
76 */
77int
78rmmain(int argc, char *argv[])
79{
80	int ch, rflag;
81
82	setlocale(LC_ALL, "");
83
84	Pflag = rflag = 0;
85	while ((ch = getopt(argc, argv, "dfiPRr")) != -1) {
86		switch(ch) {
87		case 'd':
88			dflag = 1;
89			break;
90		case 'f':
91			fflag = 1;
92			iflag = 0;
93			break;
94		case 'i':
95			fflag = 0;
96			iflag = 1;
97			break;
98		case 'P':
99			Pflag = 1;
100			break;
101		case 'R':
102		case 'r':			/* Compatibility. */
103			rflag = 1;
104			break;
105		default:
106			usage();
107		}
108	}
109	argc -= optind;
110	argv += optind;
111
112	if (Pflag) {
113		if (pledge("stdio rpath wpath cpath", NULL) == -1)
114			err(1, "pledge");
115	} else {
116		if (pledge("stdio rpath cpath", NULL) == -1)
117			err(1, "pledge");
118	}
119
120	if (argc < 1 && fflag == 0)
121		usage();
122
123	checkdot(argv);
124
125	if (*argv) {
126		stdin_ok = isatty(STDIN_FILENO);
127
128		if (rflag)
129			rm_tree(argv);
130		else
131			rm_file(argv);
132	}
133
134	return (eval);
135}
136
137static void
138rm_tree(char **argv)
139{
140	FTS *fts;
141	FTSENT *p;
142	int needstat;
143	int flags;
144
145	/*
146	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
147	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
148	 */
149	needstat = !fflag && !iflag && stdin_ok;
150
151	/*
152	 * If the -i option is specified, the user can skip on the pre-order
153	 * visit.  The fts_number field flags skipped directories.
154	 */
155#define	SKIPPED	1
156
157	flags = FTS_PHYSICAL;
158	if (!needstat)
159		flags |= FTS_NOSTAT;
160	if (!(fts = fts_open(argv, flags, NULL)))
161		err(1, NULL);
162	while ((p = fts_read(fts)) != NULL) {
163		switch (p->fts_info) {
164		case FTS_DNR:
165			if (!fflag || p->fts_errno != ENOENT) {
166				warnx("%s: %s",
167				    p->fts_path, strerror(p->fts_errno));
168				eval = 1;
169			}
170			continue;
171		case FTS_ERR:
172			errc(1, p->fts_errno, "%s", p->fts_path);
173		case FTS_NS:
174			/*
175			 * FTS_NS: assume that if can't stat the file, it
176			 * can't be unlinked.
177			 */
178			if (!needstat)
179				break;
180			if (!fflag || p->fts_errno != ENOENT) {
181				warnx("%s: %s",
182				    p->fts_path, strerror(p->fts_errno));
183				eval = 1;
184			}
185			continue;
186		case FTS_D:
187			/* Pre-order: give user chance to skip. */
188			if (!fflag && !check(p->fts_path, p->fts_accpath,
189			    p->fts_statp)) {
190				(void)fts_set(fts, p, FTS_SKIP);
191				p->fts_number = SKIPPED;
192			}
193			continue;
194		case FTS_DP:
195			/* Post-order: see if user skipped. */
196			if (p->fts_number == SKIPPED)
197				continue;
198			break;
199		default:
200			if (!fflag &&
201			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
202				continue;
203		}
204
205		/*
206		 * If we can't read or search the directory, may still be
207		 * able to remove it.  Don't print out the un{read,search}able
208		 * message unless the remove fails.
209		 */
210		switch (p->fts_info) {
211		case FTS_DP:
212		case FTS_DNR:
213			if (!rmdir(p->fts_accpath) ||
214			    (fflag && errno == ENOENT))
215				continue;
216			break;
217
218		case FTS_F:
219		case FTS_NSOK:
220			if (Pflag)
221				rm_overwrite(p->fts_accpath, p->fts_info ==
222				    FTS_NSOK ? NULL : p->fts_statp);
223			/* FALLTHROUGH */
224		default:
225			if (!unlink(p->fts_accpath) ||
226			    (fflag && errno == ENOENT))
227				continue;
228		}
229		warn("%s", p->fts_path);
230		eval = 1;
231	}
232	if (errno)
233		err(1, "fts_read");
234	fts_close(fts);
235}
236
237static void
238rm_file(char **argv)
239{
240	struct stat sb;
241	int rval;
242	char *f;
243
244	/*
245	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
246	 * to remove a directory is an error, so must always stat the file.
247	 */
248	while ((f = *argv++) != NULL) {
249		/* Assume if can't stat the file, can't unlink it. */
250		if (lstat(f, &sb)) {
251			if (!fflag || errno != ENOENT) {
252				warn("%s", f);
253				eval = 1;
254			}
255			continue;
256		}
257
258		if (S_ISDIR(sb.st_mode) && !dflag) {
259			warnx("%s: is a directory", f);
260			eval = 1;
261			continue;
262		}
263		if (!fflag && !check(f, f, &sb))
264			continue;
265		else if (S_ISDIR(sb.st_mode))
266			rval = rmdir(f);
267		else {
268			if (Pflag)
269				rm_overwrite(f, &sb);
270			rval = unlink(f);
271		}
272		if (rval && (!fflag || errno != ENOENT)) {
273			warn("%s", f);
274			eval = 1;
275		}
276	}
277}
278
279/*
280 * rm_overwrite --
281 *	Overwrite the file with varying bit patterns.
282 *
283 * XXX
284 * This is a cheap way to *really* delete files.  Note that only regular
285 * files are deleted, directories (and therefore names) will remain.
286 * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
287 * System V file system).  In a logging file system, you'll have to have
288 * kernel support.
289 * Returns 1 for success.
290 */
291static int
292rm_overwrite(char *file, struct stat *sbp)
293{
294	struct stat sb, sb2;
295	struct statfs fsb;
296	size_t bsize;
297	int fd;
298	char *buf = NULL;
299
300	fd = -1;
301	if (sbp == NULL) {
302		if (lstat(file, &sb))
303			goto err;
304		sbp = &sb;
305	}
306	if (!S_ISREG(sbp->st_mode))
307		return (1);
308	if (sbp->st_nlink > 1) {
309		warnx("%s (inode %llu): not overwritten due to multiple links",
310		    file, (unsigned long long)sbp->st_ino);
311		return (0);
312	}
313	if ((fd = open(file, O_WRONLY|O_NONBLOCK|O_NOFOLLOW, 0)) == -1)
314		goto err;
315	if (fstat(fd, &sb2))
316		goto err;
317	if (sb2.st_dev != sbp->st_dev || sb2.st_ino != sbp->st_ino ||
318	    !S_ISREG(sb2.st_mode)) {
319		errno = EPERM;
320		goto err;
321	}
322	if (fstatfs(fd, &fsb) == -1)
323		goto err;
324	bsize = MAXIMUM(fsb.f_iosize, 1024U);
325	if ((buf = malloc(bsize)) == NULL)
326		err(1, "%s: malloc", file);
327
328	if (!pass(fd, sbp->st_size, buf, bsize))
329		goto err;
330	if (fsync(fd))
331		goto err;
332	close(fd);
333	free(buf);
334	return (1);
335
336err:
337	warn("%s", file);
338	close(fd);
339	eval = 1;
340	free(buf);
341	return (0);
342}
343
344static int
345pass(int fd, off_t len, char *buf, size_t bsize)
346{
347	size_t wlen;
348
349	for (; len > 0; len -= wlen) {
350		wlen = len < bsize ? len : bsize;
351		arc4random_buf(buf, wlen);
352		if (write(fd, buf, wlen) != wlen)
353			return (0);
354	}
355	return (1);
356}
357
358static int
359check(char *path, char *name, struct stat *sp)
360{
361	int ch, first;
362	char modep[15];
363
364	/* Check -i first. */
365	if (iflag)
366		(void)fprintf(stderr, "remove %s? ", path);
367	else {
368		/*
369		 * If it's not a symbolic link and it's unwritable and we're
370		 * talking to a terminal, ask.  Symbolic links are excluded
371		 * because their permissions are meaningless.  Check stdin_ok
372		 * first because we may not have stat'ed the file.
373		 */
374		if (!stdin_ok || S_ISLNK(sp->st_mode) || !access(name, W_OK) ||
375		    errno != EACCES)
376			return (1);
377		strmode(sp->st_mode, modep);
378		(void)fprintf(stderr, "override %s%s%s/%s for %s? ",
379		    modep + 1, modep[9] == ' ' ? "" : " ",
380		    user_from_uid(sp->st_uid, 0),
381		    group_from_gid(sp->st_gid, 0), path);
382	}
383	(void)fflush(stderr);
384
385	first = ch = getchar();
386	while (ch != '\n' && ch != EOF)
387		ch = getchar();
388	return (first == 'y' || first == 'Y');
389}
390
391/*
392 * POSIX.2 requires that if "." or ".." are specified as the basename
393 * portion of an operand, a diagnostic message be written to standard
394 * error and nothing more be done with such operands.
395 *
396 * Since POSIX.2 defines basename as the final portion of a path after
397 * trailing slashes have been removed, we'll remove them here.
398 */
399#define ISDOT(a)	((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
400static void
401checkdot(char **argv)
402{
403	char *p, **save, **t;
404	int complained;
405
406	complained = 0;
407	for (t = argv; *t;) {
408		/* strip trailing slashes */
409		p = strrchr (*t, '\0');
410		while (--p > *t && *p == '/')
411			*p = '\0';
412
413		/* extract basename */
414		if ((p = strrchr(*t, '/')) != NULL)
415			++p;
416		else
417			p = *t;
418
419		if (ISDOT(p)) {
420			if (!complained++)
421				warnx("\".\" and \"..\" may not be removed");
422			eval = 1;
423			for (save = t; (t[0] = t[1]) != NULL; ++t)
424				continue;
425			t = save;
426		} else
427			++t;
428	}
429}
430