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