Home | History | Annotate | Line # | Download | only in rm
rm.c revision 1.40
      1 /* $NetBSD: rm.c,v 1.40 2004/01/11 02:04:05 tls 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.40 2004/01/11 02:04:05 tls 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 
     62 int dflag, eval, fflag, iflag, Pflag, stdin_ok, vflag, Wflag;
     63 
     64 int	check(char *, char *, struct stat *);
     65 void	checkdot(char **);
     66 void	rm_file(char **);
     67 void	rm_overwrite(char *, struct stat *);
     68 void	rm_tree(char **);
     69 void	usage(void);
     70 int	main(int, char *[]);
     71 
     72 /*
     73  * For the sake of the `-f' flag, check whether an error number indicates the
     74  * failure of an operation due to an non-existent file, either per se (ENOENT)
     75  * or because its filename argument was illegal (ENAMETOOLONG, ENOTDIR).
     76  */
     77 #define NONEXISTENT(x) \
     78     ((x) == ENOENT || (x) == ENAMETOOLONG || (x) == ENOTDIR)
     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(int argc, char *argv[])
     89 {
     90 	int ch, rflag;
     91 
     92 	setprogname(argv[0]);
     93 	(void)setlocale(LC_ALL, "");
     94 
     95 	Pflag = rflag = 0;
     96 	while ((ch = getopt(argc, argv, "dfiPRrvW")) != -1)
     97 		switch (ch) {
     98 		case 'd':
     99 			dflag = 1;
    100 			break;
    101 		case 'f':
    102 			fflag = 1;
    103 			iflag = 0;
    104 			break;
    105 		case 'i':
    106 			fflag = 0;
    107 			iflag = 1;
    108 			break;
    109 		case 'P':
    110 			Pflag = 1;
    111 			break;
    112 		case 'R':
    113 		case 'r':			/* Compatibility. */
    114 			rflag = 1;
    115 			break;
    116 		case 'v':
    117 			vflag = 1;
    118 			break;
    119 		case 'W':
    120 			Wflag = 1;
    121 			break;
    122 		case '?':
    123 		default:
    124 			usage();
    125 		}
    126 	argc -= optind;
    127 	argv += optind;
    128 
    129 	if (argc < 1)
    130 		usage();
    131 
    132 	checkdot(argv);
    133 
    134 	if (*argv) {
    135 		stdin_ok = isatty(STDIN_FILENO);
    136 
    137 		if (rflag)
    138 			rm_tree(argv);
    139 		else
    140 			rm_file(argv);
    141 	}
    142 
    143 	exit(eval);
    144 	/* NOTREACHED */
    145 }
    146 
    147 void
    148 rm_tree(char **argv)
    149 {
    150 	FTS *fts;
    151 	FTSENT *p;
    152 	int flags, needstat, rval;
    153 
    154 	/*
    155 	 * Remove a file hierarchy.  If forcing removal (-f), or interactive
    156 	 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
    157 	 */
    158 	needstat = !fflag && !iflag && stdin_ok;
    159 
    160 	/*
    161 	 * If the -i option is specified, the user can skip on the pre-order
    162 	 * visit.  The fts_number field flags skipped directories.
    163 	 */
    164 #define	SKIPPED	1
    165 
    166 	flags = FTS_PHYSICAL;
    167 	if (!needstat)
    168 		flags |= FTS_NOSTAT;
    169 	if (Wflag)
    170 		flags |= FTS_WHITEOUT;
    171 	if (!(fts = fts_open(argv, flags,
    172 	    (int (*)(const FTSENT **, const FTSENT **))NULL)))
    173 		err(1, NULL);
    174 	while ((p = fts_read(fts)) != NULL) {
    175 
    176 		switch (p->fts_info) {
    177 		case FTS_DNR:
    178 			if (!fflag || p->fts_errno != ENOENT) {
    179 				warnx("%s: %s", p->fts_path,
    180 						strerror(p->fts_errno));
    181 				eval = 1;
    182 			}
    183 			continue;
    184 		case FTS_ERR:
    185 			errx(EXIT_FAILURE, "%s: %s", p->fts_path,
    186 					strerror(p->fts_errno));
    187 			/* NOTREACHED */
    188 		case FTS_NS:
    189 			/*
    190 			 * FTS_NS: assume that if can't stat the file, it
    191 			 * can't be unlinked.
    192 			 */
    193 			if (fflag && NONEXISTENT(p->fts_errno))
    194 				continue;
    195 			if (needstat) {
    196 				warnx("%s: %s", p->fts_path,
    197 						strerror(p->fts_errno));
    198 				eval = 1;
    199 				continue;
    200 			}
    201 			break;
    202 		case FTS_D:
    203 			/* Pre-order: give user chance to skip. */
    204 			if (!fflag && !check(p->fts_path, p->fts_accpath,
    205 			    p->fts_statp)) {
    206 				(void)fts_set(fts, p, FTS_SKIP);
    207 				p->fts_number = SKIPPED;
    208 			}
    209 			continue;
    210 		case FTS_DP:
    211 			/* Post-order: see if user skipped. */
    212 			if (p->fts_number == SKIPPED)
    213 				continue;
    214 			break;
    215 		default:
    216 			if (!fflag &&
    217 			    !check(p->fts_path, p->fts_accpath, p->fts_statp))
    218 				continue;
    219 		}
    220 
    221 		rval = 0;
    222 		/*
    223 		 * If we can't read or search the directory, may still be
    224 		 * able to remove it.  Don't print out the un{read,search}able
    225 		 * message unless the remove fails.
    226 		 */
    227 		switch (p->fts_info) {
    228 		case FTS_DP:
    229 		case FTS_DNR:
    230 			rval = rmdir(p->fts_accpath);
    231 			if (rval != 0 && fflag && errno == ENOENT)
    232 				continue;
    233 			break;
    234 
    235 		case FTS_W:
    236 			rval = undelete(p->fts_accpath);
    237 			if (rval != 0 && fflag && errno == ENOENT)
    238 				continue;
    239 			break;
    240 
    241 		default:
    242 			if (Pflag)
    243 				rm_overwrite(p->fts_accpath, NULL);
    244 			rval = unlink(p->fts_accpath);
    245 			if (rval != 0 && fflag && NONEXISTENT(errno))
    246 				continue;
    247 			break;
    248 		}
    249 		if (rval != 0) {
    250 			warn("%s", p->fts_path);
    251 			eval = 1;
    252 		} else if (vflag)
    253 			(void)printf("%s\n", p->fts_path);
    254 	}
    255 	if (errno)
    256 		err(1, "fts_read");
    257 }
    258 
    259 void
    260 rm_file(char **argv)
    261 {
    262 	struct stat sb;
    263 	int rval;
    264 	char *f;
    265 
    266 	/*
    267 	 * Remove a file.  POSIX 1003.2 states that, by default, attempting
    268 	 * to remove a directory is an error, so must always stat the file.
    269 	 */
    270 	while ((f = *argv++) != NULL) {
    271 		/* Assume if can't stat the file, can't unlink it. */
    272 		if (lstat(f, &sb)) {
    273 			if (Wflag) {
    274 				sb.st_mode = S_IFWHT|S_IWUSR|S_IRUSR;
    275 			} else {
    276 				if (!fflag || !NONEXISTENT(errno)) {
    277 					warn("%s", f);
    278 					eval = 1;
    279 				}
    280 				continue;
    281 			}
    282 		} else if (Wflag) {
    283 			warnx("%s: %s", f, strerror(EEXIST));
    284 			eval = 1;
    285 			continue;
    286 		}
    287 
    288 		if (S_ISDIR(sb.st_mode) && !dflag) {
    289 			warnx("%s: is a directory", f);
    290 			eval = 1;
    291 			continue;
    292 		}
    293 		if (!fflag && !S_ISWHT(sb.st_mode) && !check(f, f, &sb))
    294 			continue;
    295 		if (S_ISWHT(sb.st_mode))
    296 			rval = undelete(f);
    297 		else if (S_ISDIR(sb.st_mode))
    298 			rval = rmdir(f);
    299 		else {
    300 			if (Pflag)
    301 				rm_overwrite(f, &sb);
    302 			rval = unlink(f);
    303 		}
    304 		if (rval && (!fflag || !NONEXISTENT(errno))) {
    305 			warn("%s", f);
    306 			eval = 1;
    307 		}
    308 		if (vflag && rval == 0)
    309 			(void)printf("%s\n", f);
    310 	}
    311 }
    312 
    313 /*
    314  * rm_overwrite --
    315  *	Overwrite the file 3 times with varying bit patterns.
    316  *
    317  * This is a cheap way to *really* delete files.  Note that only regular
    318  * files are deleted, directories (and therefore names) will remain.
    319  * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
    320  * System V file system).  In a logging file system, you'll have to have
    321  * kernel support.
    322  *
    323  * A note on standards:  U.S. DoD 5220.22-M "National Industrial Security
    324  * Program Operating Manual" ("NISPOM") is often cited as a reference
    325  * for clearing and sanitizing magnetic media.  In fact, a matrix of
    326  * "clearing" and "sanitization" methods for various media was given in
    327  * Chapter 8 of the original 1995 version of NISPOM.  However, that
    328  * matrix was *removed from the document* when Chapter 8 was rewritten
    329  * in Change 2 to the document in 2001.  Recently, the Defense Security
    330  * Service has made a revised clearing and sanitization matrix available
    331  * in Microsoft Word format on the DSS web site.  The standardization
    332  * status of this matrix is unclear.  Furthermore, one must be very
    333  * careful when referring to this matrix: it is intended for the "clearing"
    334  * prior to reuse or "sanitization" prior to disposal of *entire media*,
    335  * not individual files and the only non-physically-destructive method of
    336  * "sanitization" that is permitted for magnetic disks of any kind is
    337  * specifically noted to be prohibited for media that have contained
    338  * Top Secret data.
    339  *
    340  * It is impossible to actually conform to the exact procedure given in
    341  * the matrix if one is overwriting a file, not an entire disk, because
    342  * the procedure requires examination and comparison of the disk's defect
    343  * lists.  Any program that claims to securely erase *files* while
    344  * conforming to the standard, then, is not correct.  We do everything
    345  *
    346  * Furthermore, the presence of track caches, disk and controller write
    347  * caches, and so forth make it extremely difficult to ensure that data
    348  * have actuolly been written to the disk, particularly when one tries
    349  * to repeatedly overwrite the same sectors in quick succession.  We call
    350  * fsync(), but controllers with nonvolatile cache, as well as IDE disks
    351  * that just plain lie about the stable storage of data, will defeat this.
    352  *
    353  * Finally, widely respected research suggests that the given procedure
    354  * is nowhere near sufficient to prevent the recovery of data using special
    355  * forensic equipment and techniques that are well-known.  This is
    356  * presumably one reason that the matrix requires physical media destruction,
    357  * rather than any technique of the sort attempted here, for secret data.
    358  *
    359  * Caveat Emptor.
    360  */
    361 
    362 void
    363 rm_overwrite(char *file, struct stat *sbp)
    364 {
    365 	struct stat sb;
    366 	int fd, randint;
    367 	char randchar;
    368 
    369 	fd = -1;
    370 	if (sbp == NULL) {
    371 		if (lstat(file, &sb))
    372 			goto err;
    373 		sbp = &sb;
    374 	}
    375 	if (!S_ISREG(sbp->st_mode))
    376 		return;
    377 
    378 	/* flags to try to defeat hidden caching by forcing seeks */
    379 	if ((fd = open(file, O_RDWR|O_SYNC|O_RSYNC, 0)) == -1)
    380 		goto err;
    381 
    382 #define RAND_BYTES	1
    383 #define THIS_BYTE	0
    384 
    385 #define	WRITE_PASS(mode, byte) do {					\
    386 	off_t len;							\
    387 	int wlen, i;							\
    388 	char buf[8 * 1024];						\
    389 									\
    390 	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))			\
    391 		goto err;						\
    392 									\
    393 	if (mode == THIS_BYTE)						\
    394 		memset(buf, byte, sizeof(buf));				\
    395 	for (len = sbp->st_size; len > 0; len -= wlen) {		\
    396 		if (mode == RAND_BYTES) {				\
    397 			for (i = 0; i < sizeof(buf); 			\
    398 			    i+= sizeof(u_int32_t))			\
    399 				*(int *)(buf + i) = arc4random();	\
    400 		}							\
    401 		wlen = len < sizeof(buf) ? len : sizeof(buf);		\
    402 		if (write(fd, buf, wlen) != wlen)			\
    403 			goto err;					\
    404 	}								\
    405 	sync();		/* another poke at hidden caches */		\
    406 } while (/* CONSTCOND */ 0)
    407 
    408 #define READ_PASS(byte) do {						\
    409 	off_t len;							\
    410 	int rlen;							\
    411 	char pattern[8 * 1024];						\
    412 	char buf[8 * 1024];						\
    413 									\
    414 	if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET))			\
    415 		goto err;						\
    416 									\
    417 	memset(pattern, byte, sizeof(pattern));				\
    418 	for(len = sbp->st_size; len > 0; len -= rlen) {			\
    419 		rlen = len < sizeof(buf) ? len : sizeof(buf);		\
    420 		if(read(fd, buf, rlen) != rlen)				\
    421 			goto err;					\
    422 		if(memcmp(buf, pattern, rlen))				\
    423 			goto err;					\
    424 	}								\
    425 	sync();		/* another poke at hidden caches */		\
    426 } while (/* CONSTCOND */ 0)
    427 
    428 	/*
    429 	 * DSS sanitization matrix "clear" for magnetic disks:
    430 	 * option 'c' "Overwrite all addressable locations with a single
    431 	 * character."
    432 	 */
    433 	randint = arc4random();
    434 	randchar = *(char *)&randint;
    435 	WRITE_PASS(THIS_BYTE, randchar);
    436 
    437 	/*
    438 	 * DSS sanitization matrix "sanitize" for magnetic disks:
    439 	 * option 'd', sub 2 "Overwrite all addressable locations with a
    440 	 * character, then its complement.  Verify "complement" character
    441 	 * was written successfully to all addressable locations, then
    442 	 * overwrite all addressable locations with random characters; or
    443 	 * verify third overwrite of random characters."  The rest of the
    444 	 * text in d-sub-2 specifies requirements for overwriting spared
    445 	 * sectors; we cannot conform to it when erasing only a file, thus
    446 	 * we do not conform to the standard.
    447 	 */
    448 
    449 	/* 1. "a character" */
    450 	WRITE_PASS(THIS_BYTE, 0xff);
    451 
    452 	/* 2. "its complement" */
    453 	WRITE_PASS(THIS_BYTE, 0x00);
    454 
    455 	/* 3. "Verify 'complement' character" */
    456 	READ_PASS(0x00);
    457 
    458 	/* 4. "overwrite all addressable locations with random characters" */
    459 
    460 	WRITE_PASS(RAND_BYTES, 0x00);
    461 
    462 	/*
    463 	 * As the file might be huge, and we note that this revision of
    464 	 * the matrix says "random characters", not "a random character"
    465 	 * as the original did, we do not verify the random-character
    466 	 * write; the "or" in the standard allows this.
    467 	 */
    468 
    469 	if (!close(fd))
    470 		return;
    471 
    472 err:	eval = 1;
    473 	warn("%s", file);
    474 }
    475 
    476 int
    477 check(char *path, char *name, struct stat *sp)
    478 {
    479 	int ch, first;
    480 	char modep[15];
    481 
    482 	/* Check -i first. */
    483 	if (iflag)
    484 		(void)fprintf(stderr, "remove '%s'? ", path);
    485 	else {
    486 		/*
    487 		 * If it's not a symbolic link and it's unwritable and we're
    488 		 * talking to a terminal, ask.  Symbolic links are excluded
    489 		 * because their permissions are meaningless.  Check stdin_ok
    490 		 * first because we may not have stat'ed the file.
    491 		 */
    492 		if (!stdin_ok || S_ISLNK(sp->st_mode) ||
    493 		    !(access(name, W_OK) && (errno != ETXTBSY)))
    494 			return (1);
    495 		strmode(sp->st_mode, modep);
    496 		(void)fprintf(stderr, "override %s%s%s/%s for '%s'? ",
    497 		    modep + 1, modep[9] == ' ' ? "" : " ",
    498 		    user_from_uid(sp->st_uid, 0),
    499 		    group_from_gid(sp->st_gid, 0), path);
    500 	}
    501 	(void)fflush(stderr);
    502 
    503 	first = ch = getchar();
    504 	while (ch != '\n' && ch != EOF)
    505 		ch = getchar();
    506 	return (first == 'y' || first == 'Y');
    507 }
    508 
    509 /*
    510  * POSIX.2 requires that if "." or ".." are specified as the basename
    511  * portion of an operand, a diagnostic message be written to standard
    512  * error and nothing more be done with such operands.
    513  *
    514  * Since POSIX.2 defines basename as the final portion of a path after
    515  * trailing slashes have been removed, we'll remove them here.
    516  */
    517 #define ISDOT(a) ((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
    518 void
    519 checkdot(char **argv)
    520 {
    521 	char *p, **save, **t;
    522 	int complained;
    523 
    524 	complained = 0;
    525 	for (t = argv; *t;) {
    526 		/* strip trailing slashes */
    527 		p = strrchr(*t, '\0');
    528 		while (--p > *t && *p == '/')
    529 			*p = '\0';
    530 
    531 		/* extract basename */
    532 		if ((p = strrchr(*t, '/')) != NULL)
    533 			++p;
    534 		else
    535 			p = *t;
    536 
    537 		if (ISDOT(p)) {
    538 			if (!complained++)
    539 				warnx("\".\" and \"..\" may not be removed");
    540 			eval = 1;
    541 			for (save = t; (t[0] = t[1]) != NULL; ++t)
    542 				continue;
    543 			t = save;
    544 		} else
    545 			++t;
    546 	}
    547 }
    548 
    549 void
    550 usage(void)
    551 {
    552 
    553 	(void)fprintf(stderr, "usage: %s [-f|-i] [-dPRrvW] file ...\n",
    554 	    getprogname());
    555 	exit(1);
    556 	/* NOTREACHED */
    557 }
    558