Home | History | Annotate | Line # | Download | only in rm
rm.c revision 1.36
      1 /* $NetBSD: rm.c,v 1.36 2003/08/07 09:05:28 agc Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 1990, 1993, 1994, 2003
      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. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\n\
     35 	The Regents of the University of California.  All rights reserved.\n");
     36 #endif /* not lint */
     37 
     38 #ifndef lint
     39 #if 0
     40 static char sccsid[] = "@(#)rm.c	8.8 (Berkeley) 4/27/95";
     41 #else
     42 __RCSID("$NetBSD: rm.c,v 1.36 2003/08/07 09:05:28 agc Exp $");
     43 #endif
     44 #endif /* not lint */
     45 
     46 #include <sys/param.h>
     47 #include <sys/stat.h>
     48 #include <sys/types.h>
     49 
     50 #include <err.h>
     51 #include <errno.h>
     52 #include <fcntl.h>
     53 #include <fts.h>
     54 #include <grp.h>
     55 #include <locale.h>
     56 #include <pwd.h>
     57 #include <stdio.h>
     58 #include <stdlib.h>
     59 #include <string.h>
     60 #include <unistd.h>
     61 #include <vis.h>
     62 
     63 int dflag, eval, fflag, iflag, Pflag, stdin_ok, stdout_ok, vflag, Wflag;
     64 
     65 int	check(char *, char *, struct stat *);
     66 void	checkdot(char **);
     67 char 	*printescaped(const char *);
     68 void	rm_file(char **);
     69 void	rm_overwrite(char *, struct stat *);
     70 void	rm_tree(char **);
     71 void	usage(void);
     72 int	main(int, char *[]);
     73 
     74 /*
     75  * For the sake of the `-f' flag, check whether an error number indicates the
     76  * failure of an operation due to an non-existent file, either per se (ENOENT)
     77  * or because its filename argument was illegal (ENAMETOOLONG, ENOTDIR).
     78  */
     79 #define NONEXISTENT(x) \
     80     ((x) == ENOENT || (x) == ENAMETOOLONG || (x) == ENOTDIR)
     81 
     82 /*
     83  * rm --
     84  *	This rm is different from historic rm's, but is expected to match
     85  *	POSIX 1003.2 behavior.  The most visible difference is that -f
     86  *	has two specific effects now, ignore non-existent files and force
     87  * 	file removal.
     88  */
     89 int
     90 main(int argc, char *argv[])
     91 {
     92 	int ch, rflag;
     93 
     94 	setprogname(argv[0]);
     95 	(void)setlocale(LC_ALL, "");
     96 
     97 	Pflag = rflag = 0;
     98 	while ((ch = getopt(argc, argv, "dfiPRrvW")) != -1)
     99 		switch (ch) {
    100 		case 'd':
    101 			dflag = 1;
    102 			break;
    103 		case 'f':
    104 			fflag = 1;
    105 			iflag = 0;
    106 			break;
    107 		case 'i':
    108 			fflag = 0;
    109 			iflag = 1;
    110 			break;
    111 		case 'P':
    112 			Pflag = 1;
    113 			break;
    114 		case 'R':
    115 		case 'r':			/* Compatibility. */
    116 			rflag = 1;
    117 			break;
    118 		case 'v':
    119 			vflag = 1;
    120 			break;
    121 		case 'W':
    122 			Wflag = 1;
    123 			break;
    124 		case '?':
    125 		default:
    126 			usage();
    127 		}
    128 	argc -= optind;
    129 	argv += optind;
    130 
    131 	if (argc < 1)
    132 		usage();
    133 
    134 	checkdot(argv);
    135 
    136 	if (*argv) {
    137 		stdin_ok = isatty(STDIN_FILENO);
    138 		stdout_ok = isatty(STDOUT_FILENO);
    139 
    140 		if (rflag)
    141 			rm_tree(argv);
    142 		else
    143 			rm_file(argv);
    144 	}
    145 
    146 	exit(eval);
    147 	/* NOTREACHED */
    148 }
    149 
    150 void
    151 rm_tree(char **argv)
    152 {
    153 	FTS *fts;
    154 	FTSENT *p;
    155 	int flags, needstat, rval;
    156 	char *fn;
    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 = !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;
    171 	if (!needstat)
    172 		flags |= FTS_NOSTAT;
    173 	if (Wflag)
    174 		flags |= FTS_WHITEOUT;
    175 	if (!(fts = fts_open(argv, flags,
    176 	    (int (*)(const FTSENT **, const FTSENT **))NULL)))
    177 		err(1, NULL);
    178 	while ((p = fts_read(fts)) != NULL) {
    179 
    180 		switch (p->fts_info) {
    181 		case FTS_DNR:
    182 			if (!fflag || p->fts_errno != ENOENT) {
    183 				fn = printescaped(p->fts_path);
    184 				warnx("%s: %s", fn, strerror(p->fts_errno));
    185 				free(fn);
    186 				eval = 1;
    187 			}
    188 			continue;
    189 		case FTS_ERR:
    190 			errx(EXIT_FAILURE, "%s: %s", printescaped(p->fts_path),
    191 					strerror(p->fts_errno));
    192 			/* NOTREACHED */
    193 		case FTS_NS:
    194 			/*
    195 			 * FTS_NS: assume that if can't stat the file, it
    196 			 * can't be unlinked.
    197 			 */
    198 			if (fflag && NONEXISTENT(p->fts_errno))
    199 				continue;
    200 			if (needstat) {
    201 				fn = printescaped(p->fts_path);
    202 				warnx("%s: %s", fn, strerror(p->fts_errno));
    203 				free(fn);
    204 				eval = 1;
    205 				continue;
    206 			}
    207 			break;
    208 		case FTS_D:
    209 			/* Pre-order: give user chance to skip. */
    210 			if (!fflag && !check(p->fts_path, p->fts_accpath,
    211 			    p->fts_statp)) {
    212 				(void)fts_set(fts, p, FTS_SKIP);
    213 				p->fts_number = SKIPPED;
    214 			}
    215 			continue;
    216 		case FTS_DP:
    217 			/* Post-order: see if user skipped. */
    218 			if (p->fts_number == SKIPPED)
    219 				continue;
    220 			break;
    221 		default:
    222 			if (!fflag &&
    223 			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
    224 				continue;
    225 		}
    226 
    227 		rval = 0;
    228 		/*
    229 		 * If we can't read or search the directory, may still be
    230 		 * able to remove it.  Don't print out the un{read,search}able
    231 		 * message unless the remove fails.
    232 		 */
    233 		switch (p->fts_info) {
    234 		case FTS_DP:
    235 		case FTS_DNR:
    236 			rval = rmdir(p->fts_accpath);
    237 			if (rval != 0 && fflag && errno == ENOENT)
    238 				continue;
    239 			break;
    240 
    241 		case FTS_W:
    242 			rval = undelete(p->fts_accpath);
    243 			if (rval != 0 && fflag && errno == ENOENT)
    244 				continue;
    245 			break;
    246 
    247 		default:
    248 			if (Pflag)
    249 				rm_overwrite(p->fts_accpath, NULL);
    250 			rval = unlink(p->fts_accpath);
    251 			if (rval != 0 && fflag && NONEXISTENT(errno))
    252 				continue;
    253 			break;
    254 		}
    255 		if (rval != 0) {
    256 			fn = printescaped(p->fts_path);
    257 			warn("%s", fn);
    258 			free(fn);
    259 			eval = 1;
    260 		} else if (vflag) {
    261 			fn = printescaped(p->fts_path);
    262 			(void)printf("%s\n", fn);
    263 			free(fn);
    264 		}
    265 	}
    266 	if (errno)
    267 		err(1, "fts_read");
    268 }
    269 
    270 void
    271 rm_file(char **argv)
    272 {
    273 	struct stat sb;
    274 	int rval;
    275 	char *f, *fn;
    276 
    277 	/*
    278 	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
    279 	 * to remove a directory is an error, so must always stat the file.
    280 	 */
    281 	while ((f = *argv++) != NULL) {
    282 		/* Assume if can't stat the file, can't unlink it. */
    283 		if (lstat(f, &sb)) {
    284 			if (Wflag) {
    285 				sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
    286 			} else {
    287 				if (!fflag || !NONEXISTENT(errno)) {
    288 					fn = printescaped(f);
    289 					warn("%s", fn);
    290 					free(fn);
    291 					eval = 1;
    292 				}
    293 				continue;
    294 			}
    295 		} else if (Wflag) {
    296 			fn = printescaped(f);
    297 			warnx("%s: %s", fn, strerror(EEXIST));
    298 			free(fn);
    299 			eval = 1;
    300 			continue;
    301 		}
    302 
    303 		if (S_ISDIR(sb.st_mode) && !dflag) {
    304 			fn = printescaped(f);
    305 			warnx("%s: is a directory", fn);
    306 			free(fn);
    307 			eval = 1;
    308 			continue;
    309 		}
    310 		if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
    311 			continue;
    312 		if (S_ISWHT(sb.st_mode))
    313 			rval = undelete(f);
    314 		else if (S_ISDIR(sb.st_mode))
    315 			rval = rmdir(f);
    316 		else {
    317 			if (Pflag)
    318 				rm_overwrite(f, &sb);
    319 			rval = unlink(f);
    320 		}
    321 		if (rval && (!fflag || !NONEXISTENT(errno))) {
    322 			fn = printescaped(f);
    323 			warn("%s", fn);
    324 			free(fn);
    325 			eval = 1;
    326 		}
    327 		if (vflag && rval == 0) {
    328 			fn = printescaped(f);
    329 			(void)printf("%s\n", fn);
    330 			free(fn);
    331 		}
    332 	}
    333 }
    334 
    335 /*
    336  * rm_overwrite --
    337  *	Overwrite the file 3 times with varying bit patterns.
    338  *
    339  * XXX
    340  * This is a cheap way to *really* delete files.  Note that only regular
    341  * files are deleted, directories (and therefore names) will remain.
    342  * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
    343  * System V file system).  In a logging file system, you'll have to have
    344  * kernel support.
    345  */
    346 void
    347 rm_overwrite(char *file, struct stat *sbp)
    348 {
    349 	struct stat sb;
    350 	off_t len;
    351 	int fd, wlen;
    352 	char buf[8 * 1024];
    353 	char *fn;
    354 
    355 	fd = -1;
    356 	if (sbp == NULL) {
    357 		if (lstat(file, &sb))
    358 			goto err;
    359 		sbp = &sb;
    360 	}
    361 	if (!S_ISREG(sbp->st_mode))
    362 		return;
    363 	if ((fd = open(file, O_WRONLY, 0)) == -1)
    364 		goto err;
    365 
    366 #define	PASS(byte) do {							\
    367 	memset(buf, byte, sizeof(buf));					\
    368 	for (len = sbp->st_size; len > 0; len -= wlen) {		\
    369 		wlen = len < sizeof(buf) ? len : sizeof(buf);		\
    370 		if (write(fd, buf, wlen) != wlen)			\
    371 			goto err;					\
    372 	}								\
    373 } while (/* CONSTCOND */ 0)
    374 	PASS(0xff);
    375 	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
    376 		goto err;
    377 	PASS(0x00);
    378 	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))
    379 		goto err;
    380 	PASS(0xff);
    381 	if (!fsync(fd) && !close(fd))
    382 		return;
    383 
    384 err:	eval = 1;
    385 	fn = printescaped(file);
    386 	warn("%s", fn);
    387 	free(fn);
    388 }
    389 
    390 int
    391 check(char *path, char *name, struct stat *sp)
    392 {
    393 	int ch, first;
    394 	char modep[15];
    395 	char *fn;
    396 
    397 	/* Check -i first. */
    398 	if (iflag) {
    399 		fn = printescaped(path);
    400 		(void)fprintf(stderr, "remove '%s'? ", fn);
    401 		free(fn);
    402 	} else {
    403 		/*
    404 		 * If it's not a symbolic link and it's unwritable and we're
    405 		 * talking to a terminal, ask.  Symbolic links are excluded
    406 		 * because their permissions are meaningless.  Check stdin_ok
    407 		 * first because we may not have stat'ed the file.
    408 		 */
    409 		if (!stdin_ok || S_ISLNK(sp->st_mode) ||
    410 		    !(access(name, W_OK) && (errno != ETXTBSY)))
    411 			return (1);
    412 		strmode(sp->st_mode, modep);
    413 		fn =  printescaped(path);
    414 		(void)fprintf(stderr, "override %s%s%s/%s for '%s'? ",
    415 		    modep + 1, modep[9] == ' ' ? "" : " ",
    416 		    user_from_uid(sp->st_uid, 0),
    417 		    group_from_gid(sp->st_gid, 0), fn);
    418 		free(fn);
    419 	}
    420 	(void)fflush(stderr);
    421 
    422 	first = ch = getchar();
    423 	while (ch != '\n' && ch != EOF)
    424 		ch = getchar();
    425 	return (first == 'y' || first == 'Y');
    426 }
    427 
    428 /*
    429  * POSIX.2 requires that if "." or ".." are specified as the basename
    430  * portion of an operand, a diagnostic message be written to standard
    431  * error and nothing more be done with such operands.
    432  *
    433  * Since POSIX.2 defines basename as the final portion of a path after
    434  * trailing slashes have been removed, we'll remove them here.
    435  */
    436 #define ISDOT(a) ((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
    437 void
    438 checkdot(char **argv)
    439 {
    440 	char *p, **save, **t;
    441 	int complained;
    442 
    443 	complained = 0;
    444 	for (t = argv; *t;) {
    445 		/* strip trailing slashes */
    446 		p = strrchr(*t, '\0');
    447 		while (--p > *t && *p == '/')
    448 			*p = '\0';
    449 
    450 		/* extract basename */
    451 		if ((p = strrchr(*t, '/')) != NULL)
    452 			++p;
    453 		else
    454 			p = *t;
    455 
    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 char *
    469 printescaped(const char *src)
    470 {
    471 	size_t len;
    472 	char *retval;
    473 
    474 	len = strlen(src);
    475 	if (len != 0 && SIZE_T_MAX/len <= 4) {
    476 		errx(EXIT_FAILURE, "%s: name too long", src);
    477 		/* NOTREACHED */
    478 	}
    479 
    480 	retval = (char *)malloc(4*len+1);
    481 	if (retval != NULL) {
    482 		if (stdout_ok)
    483 			(void)strvis(retval, src, VIS_NL | VIS_CSTYLE);
    484 		else
    485 			(void)strcpy(retval, src);
    486 		return retval;
    487 	} else
    488 		errx(EXIT_FAILURE, "out of memory!");
    489 		/* NOTREACHED */
    490 }
    491 
    492 void
    493 usage(void)
    494 {
    495 
    496 	(void)fprintf(stderr, "usage: %s [-f|-i] [-dPRrvW] file ...\n",
    497 	    getprogname());
    498 	exit(1);
    499 	/* NOTREACHED */
    500 }
    501