xref: /netbsd-src/bin/rm/rm.c (revision 76dfffe33547c37f8bdd446e3e4ab0f3c16cea4b)
1 /*	$NetBSD: rm.c,v 1.19 1995/09/07 06:48:50 jtc Exp $	*/
2 
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. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #ifndef lint
37 static char copyright[] =
38 "@(#) Copyright (c) 1990, 1993, 1994\n\
39 	The Regents of the University of California.  All rights reserved.\n";
40 #endif /* not lint */
41 
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)rm.c	8.8 (Berkeley) 4/27/95";
45 #else
46 static char rcsid[] = "$NetBSD: rm.c,v 1.19 1995/09/07 06:48:50 jtc Exp $";
47 #endif
48 #endif /* not lint */
49 
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 
53 #include <locale.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <fts.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 
63 int dflag, eval, fflag, iflag, Pflag, Wflag, stdin_ok;
64 
65 int	check __P((char *, char *, struct stat *));
66 void	checkdot __P((char **));
67 void	rm_file __P((char **));
68 void	rm_overwrite __P((char *, struct stat *));
69 void	rm_tree __P((char **));
70 void	usage __P((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(argc, argv)
81 	int argc;
82 	char *argv[];
83 {
84 	int ch, rflag;
85 
86 	setlocale(LC_ALL, "");
87 
88 	Pflag = rflag = 0;
89 	while ((ch = getopt(argc, argv, "dfiPRrW")) != -1)
90 		switch(ch) {
91 		case 'd':
92 			dflag = 1;
93 			break;
94 		case 'f':
95 			fflag = 1;
96 			iflag = 0;
97 			break;
98 		case 'i':
99 			fflag = 0;
100 			iflag = 1;
101 			break;
102 		case 'P':
103 			Pflag = 1;
104 			break;
105 		case 'R':
106 		case 'r':			/* Compatibility. */
107 			rflag = 1;
108 			break;
109 		case 'W':
110 			Wflag = 1;
111 			break;
112 		case '?':
113 		default:
114 			usage();
115 		}
116 	argc -= optind;
117 	argv += optind;
118 
119 	if (argc < 1)
120 		usage();
121 
122 	checkdot(argv);
123 
124 	if (*argv) {
125 		stdin_ok = isatty(STDIN_FILENO);
126 
127 		if (rflag)
128 			rm_tree(argv);
129 		else
130 			rm_file(argv);
131 	}
132 
133 	exit (eval);
134 }
135 
136 void
137 rm_tree(argv)
138 	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 (Wflag)
161 		flags |= FTS_WHITEOUT;
162 	if (!(fts = fts_open(argv, flags, (int (*)())NULL)))
163 		err(1, NULL);
164 	while ((p = fts_read(fts)) != NULL) {
165 		switch (p->fts_info) {
166 		case FTS_DNR:
167 			if (!fflag || p->fts_errno != ENOENT) {
168 				warnx("%s: %s",
169 				    p->fts_path, strerror(p->fts_errno));
170 				eval = 1;
171 			}
172 			continue;
173 		case FTS_ERR:
174 			errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
175 		case FTS_NS:
176 			/*
177 			 * FTS_NS: assume that if can't stat the file, it
178 			 * can't be unlinked.
179 			 */
180 			if (!needstat)
181 				break;
182 			if (!fflag || p->fts_errno != ENOENT) {
183 				warnx("%s: %s",
184 				    p->fts_path, strerror(p->fts_errno));
185 				eval = 1;
186 			}
187 			continue;
188 		case FTS_D:
189 			/* Pre-order: give user chance to skip. */
190 			if (!fflag && !check(p->fts_path, p->fts_accpath,
191 			    p->fts_statp)) {
192 				(void)fts_set(fts, p, FTS_SKIP);
193 				p->fts_number = SKIPPED;
194 			}
195 			continue;
196 		case FTS_DP:
197 			/* Post-order: see if user skipped. */
198 			if (p->fts_number == SKIPPED)
199 				continue;
200 			break;
201 		default:
202 			if (!fflag &&
203 			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
204 				continue;
205 		}
206 
207 		/*
208 		 * If we can't read or search the directory, may still be
209 		 * able to remove it.  Don't print out the un{read,search}able
210 		 * message unless the remove fails.
211 		 */
212 		switch (p->fts_info) {
213 		case FTS_DP:
214 		case FTS_DNR:
215 			if (!rmdir(p->fts_accpath) || fflag && errno == ENOENT)
216 				continue;
217 			break;
218 
219 		case FTS_W:
220 			if (!undelete(p->fts_accpath) ||
221 			    fflag && errno == ENOENT)
222 				continue;
223 			break;
224 
225 		default:
226 			if (Pflag)
227 				rm_overwrite(p->fts_accpath, NULL);
228 			if (!unlink(p->fts_accpath) || fflag && errno == ENOENT)
229 				continue;
230 		}
231 		warn("%s", p->fts_path);
232 		eval = 1;
233 	}
234 	if (errno)
235 		err(1, "fts_read");
236 }
237 
238 void
239 rm_file(argv)
240 	char **argv;
241 {
242 	struct stat sb;
243 	int rval;
244 	char *f;
245 
246 	/*
247 	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
248 	 * to remove a directory is an error, so must always stat the file.
249 	 */
250 	while ((f = *argv++) != NULL) {
251 		/* Assume if can't stat the file, can't unlink it. */
252 		if (lstat(f, &sb)) {
253 			if (Wflag) {
254 				sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
255 			} else {
256 				if (!fflag || errno != ENOENT) {
257 					warn("%s", f);
258 					eval = 1;
259 				}
260 				continue;
261 			}
262 		} else if (Wflag) {
263 			warnx("%s: %s", f, strerror(EEXIST));
264 			eval = 1;
265 			continue;
266 		}
267 
268 		if (S_ISDIR(sb.st_mode) && !dflag) {
269 			warnx("%s: is a directory", f);
270 			eval = 1;
271 			continue;
272 		}
273 		if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
274 			continue;
275 		if (S_ISWHT(sb.st_mode))
276 			rval = undelete(f);
277 		else if (S_ISDIR(sb.st_mode))
278 			rval = rmdir(f);
279 		else {
280 			if (Pflag)
281 				rm_overwrite(f, &sb);
282 			rval = unlink(f);
283 		}
284 		if (rval && (!fflag || errno != ENOENT)) {
285 			warn("%s", f);
286 			eval = 1;
287 		}
288 	}
289 }
290 
291 /*
292  * rm_overwrite --
293  *	Overwrite the file 3 times with varying bit patterns.
294  *
295  * XXX
296  * This is a cheap way to *really* delete files.  Note that only regular
297  * files are deleted, directories (and therefore names) will remain.
298  * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
299  * System V file system).  In a logging file system, you'll have to have
300  * kernel support.
301  */
302 void
303 rm_overwrite(file, sbp)
304 	char *file;
305 	struct stat *sbp;
306 {
307 	struct stat sb;
308 	off_t len;
309 	int fd, wlen;
310 	char buf[8 * 1024];
311 
312 	fd = -1;
313 	if (sbp == NULL) {
314 		if (lstat(file, &sb))
315 			goto err;
316 		sbp = &sb;
317 	}
318 	if (!S_ISREG(sbp->st_mode))
319 		return;
320 	if ((fd = open(file, O_WRONLY, 0)) == -1)
321 		goto err;
322 
323 #define	PASS(byte) {							\
324 	memset(buf, byte, sizeof(buf));					\
325 	for (len = sbp->st_size; len > 0; len -= wlen) {		\
326 		wlen = len < sizeof(buf) ? len : sizeof(buf);		\
327 		if (write(fd, buf, wlen) != wlen)			\
328 			goto err;					\
329 	}								\
330 }
331 	PASS(0xff);
332 	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
333 		goto err;
334 	PASS(0x00);
335 	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
336 		goto err;
337 	PASS(0xff);
338 	if (!fsync(fd) && !close(fd))
339 		return;
340 
341 err:	eval = 1;
342 	warn("%s", file);
343 }
344 
345 
346 int
347 check(path, name, sp)
348 	char *path, *name;
349 	struct stat *sp;
350 {
351 	int ch, first;
352 	char modep[15];
353 
354 	/* Check -i first. */
355 	if (iflag)
356 		(void)fprintf(stderr, "remove %s? ", path);
357 	else {
358 		/*
359 		 * If it's not a symbolic link and it's unwritable and we're
360 		 * talking to a terminal, ask.  Symbolic links are excluded
361 		 * because their permissions are meaningless.  Check stdin_ok
362 		 * first because we may not have stat'ed the file.
363 		 */
364 		if (!stdin_ok || S_ISLNK(sp->st_mode) || !access(name, W_OK))
365 			return (1);
366 		strmode(sp->st_mode, modep);
367 		(void)fprintf(stderr, "override %s%s%s/%s for %s? ",
368 		    modep + 1, modep[9] == ' ' ? "" : " ",
369 		    user_from_uid(sp->st_uid, 0),
370 		    group_from_gid(sp->st_gid, 0), path);
371 	}
372 	(void)fflush(stderr);
373 
374 	first = ch = getchar();
375 	while (ch != '\n' && ch != EOF)
376 		ch = getchar();
377 	return (first == 'y' || first == 'Y');
378 }
379 
380 /*
381  * POSIX.2 requires that if "." or ".." are specified as the basename
382  * portion of an operand, a diagnostic message be written to standard
383  * error and nothing more be done with such operands.
384  *
385  * Since POSIX.2 defines basename as the final portion of a path after
386  * trailing slashes have been removed, we'll remove them here.
387  */
388 #define ISDOT(a)	((a)[0] == '.' && (!(a)[1] || (a)[1] == '.' && !(a)[2]))
389 void
390 checkdot(argv)
391 	char **argv;
392 {
393 	char *p, **save, **t;
394 	int complained;
395 
396 	complained = 0;
397 	for (t = argv; *t;) {
398 		/* strip trailing slashes */
399 		p = strrchr (*t, '\0');
400 		while (--p > *t && *p == '/')
401 			*p = '\0';
402 
403 		/* extract basename */
404 		if ((p = strrchr(*t, '/')) != NULL)
405 			++p;
406 		else
407 			p = *t;
408 
409 		if (ISDOT(p)) {
410 			if (!complained++)
411 				warnx("\".\" and \"..\" may not be removed");
412 			eval = 1;
413 			for (save = t; (t[0] = t[1]) != NULL; ++t)
414 				continue;
415 			t = save;
416 		} else
417 			++t;
418 	}
419 }
420 
421 void
422 usage()
423 {
424 
425 	(void)fprintf(stderr, "usage: rm [-dfiPRrW] file ...\n");
426 	exit(1);
427 }
428