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