1 /* $NetBSD: rm.c,v 1.48 2008/07/20 00:52:40 lukem Exp $ */
4 * Copyright (c) 1990, 1993, 1994, 2003
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
32 #include <sys/cdefs.h>
34 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\
35 The Regents of the University of California. All rights reserved.");
40 static char sccsid
[] = "@(#)rm.c 8.8 (Berkeley) 4/27/95";
42 __RCSID("$NetBSD: rm.c,v 1.48 2008/07/20 00:52:40 lukem Exp $");
46 #include <sys/param.h>
48 #include <sys/types.h>
62 int dflag
, eval
, fflag
, iflag
, Pflag
, stdin_ok
, vflag
, Wflag
;
64 int check(char *, char *, struct stat
*);
65 void checkdot(char **);
66 void rm_file(char **);
67 int rm_overwrite(char *, struct stat
*);
68 void rm_tree(char **);
70 int main(int, char *[]);
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).
77 #define NONEXISTENT(x) \
78 ((x) == ENOENT || (x) == ENAMETOOLONG || (x) == ENOTDIR)
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
88 main(int argc
, char *argv
[])
93 (void)setlocale(LC_ALL
, "");
96 while ((ch
= getopt(argc
, argv
, "dfiPRrvW")) != -1)
113 case 'r': /* Compatibility. */
138 stdin_ok
= isatty(STDIN_FILENO
);
155 int flags
, needstat
, rval
;
158 * Remove a file hierarchy. If forcing removal (-f), or interactive
159 * (-i) or can't ask anyway (stdin_ok), don't stat the file.
161 needstat
= !fflag
&& !iflag
&& stdin_ok
;
164 * If the -i option is specified, the user can skip on the pre-order
165 * visit. The fts_number field flags skipped directories.
169 flags
= FTS_PHYSICAL
;
173 flags
|= FTS_WHITEOUT
;
174 if ((fts
= fts_open(argv
, flags
, NULL
)) == NULL
)
175 err(1, "fts_open failed");
176 while ((p
= fts_read(fts
)) != NULL
) {
178 switch (p
->fts_info
) {
180 if (!fflag
|| p
->fts_errno
!= ENOENT
) {
181 warnx("%s: %s", p
->fts_path
,
182 strerror(p
->fts_errno
));
187 errx(EXIT_FAILURE
, "%s: %s", p
->fts_path
,
188 strerror(p
->fts_errno
));
192 * FTS_NS: assume that if can't stat the file, it
195 if (fflag
&& NONEXISTENT(p
->fts_errno
))
198 warnx("%s: %s", p
->fts_path
,
199 strerror(p
->fts_errno
));
205 /* Pre-order: give user chance to skip. */
206 if (!fflag
&& !check(p
->fts_path
, p
->fts_accpath
,
208 (void)fts_set(fts
, p
, FTS_SKIP
);
209 p
->fts_number
= SKIPPED
;
213 /* Post-order: see if user skipped. */
214 if (p
->fts_number
== SKIPPED
)
219 !check(p
->fts_path
, p
->fts_accpath
, p
->fts_statp
))
225 * If we can't read or search the directory, may still be
226 * able to remove it. Don't print out the un{read,search}able
227 * message unless the remove fails.
229 switch (p
->fts_info
) {
232 rval
= rmdir(p
->fts_accpath
);
233 if (rval
!= 0 && fflag
&& errno
== ENOENT
)
238 rval
= undelete(p
->fts_accpath
);
239 if (rval
!= 0 && fflag
&& errno
== ENOENT
)
245 if (rm_overwrite(p
->fts_accpath
, NULL
))
248 rval
= unlink(p
->fts_accpath
);
249 if (rval
!= 0 && fflag
&& NONEXISTENT(errno
))
254 warn("%s", p
->fts_path
);
257 (void)printf("%s\n", p
->fts_path
);
272 * Remove a file. POSIX 1003.2 states that, by default, attempting
273 * to remove a directory is an error, so must always stat the file.
275 while ((f
= *argv
++) != NULL
) {
276 /* Assume if can't stat the file, can't unlink it. */
279 sb
.st_mode
= S_IFWHT
|S_IWUSR
|S_IRUSR
;
281 if (!fflag
|| !NONEXISTENT(errno
)) {
288 warnx("%s: %s", f
, strerror(EEXIST
));
293 if (S_ISDIR(sb
.st_mode
) && !dflag
) {
294 warnx("%s: is a directory", f
);
298 if (!fflag
&& !S_ISWHT(sb
.st_mode
) && !check(f
, f
, &sb
))
300 if (S_ISWHT(sb
.st_mode
))
302 else if (S_ISDIR(sb
.st_mode
))
306 if (rm_overwrite(f
, &sb
))
311 if (rval
&& (!fflag
|| !NONEXISTENT(errno
))) {
315 if (vflag
&& rval
== 0)
316 (void)printf("%s\n", f
);
322 * Overwrite the file 3 times with varying bit patterns.
324 * This is an expensive way to keep people from recovering files from your
325 * non-snapshotted FFS filesystems using fsdb(8). Really. No more. Only
326 * regular files are deleted, directories (and therefore names) will remain.
327 * Also, this assumes a fixed-block file system (like FFS, or a V7 or a
328 * System V file system). In a logging file system, you'll have to have
331 * A note on standards: U.S. DoD 5220.22-M "National Industrial Security
332 * Program Operating Manual" ("NISPOM") is often cited as a reference
333 * for clearing and sanitizing magnetic media. In fact, a matrix of
334 * "clearing" and "sanitization" methods for various media was given in
335 * Chapter 8 of the original 1995 version of NISPOM. However, that
336 * matrix was *removed from the document* when Chapter 8 was rewritten
337 * in Change 2 to the document in 2001. Recently, the Defense Security
338 * Service has made a revised clearing and sanitization matrix available
339 * in Microsoft Word format on the DSS web site. The standardization
340 * status of this matrix is unclear. Furthermore, one must be very
341 * careful when referring to this matrix: it is intended for the "clearing"
342 * prior to reuse or "sanitization" prior to disposal of *entire media*,
343 * not individual files and the only non-physically-destructive method of
344 * "sanitization" that is permitted for magnetic disks of any kind is
345 * specifically noted to be prohibited for media that have contained
348 * It is impossible to actually conform to the exact procedure given in
349 * the matrix if one is overwriting a file, not an entire disk, because
350 * the procedure requires examination and comparison of the disk's defect
351 * lists. Any program that claims to securely erase *files* while
352 * conforming to the standard, then, is not correct. We do as much of
353 * what the standard requires as can actually be done when erasing a
354 * file, rather than an entire disk; but that does not make us conformant.
356 * Furthermore, the presence of track caches, disk and controller write
357 * caches, and so forth make it extremely difficult to ensure that data
358 * have actually been written to the disk, particularly when one tries
359 * to repeatedly overwrite the same sectors in quick succession. We call
360 * fsync(), but controllers with nonvolatile cache, as well as IDE disks
361 * that just plain lie about the stable storage of data, will defeat this.
363 * Finally, widely respected research suggests that the given procedure
364 * is nowhere near sufficient to prevent the recovery of data using special
365 * forensic equipment and techniques that are well-known. This is
366 * presumably one reason that the matrix requires physical media destruction,
367 * rather than any technique of the sort attempted here, for secret data.
371 * rm_overwrite will return 0 on success.
375 rm_overwrite(char *file
, struct stat
*sbp
)
383 if (lstat(file
, &sb
))
387 if (!S_ISREG(sbp
->st_mode
))
390 /* flags to try to defeat hidden caching by forcing seeks */
391 if ((fd
= open(file
, O_RDWR
|O_SYNC
|O_RSYNC
, 0)) == -1)
397 #define WRITE_PASS(mode, byte) do { \
400 char buf[8 * 1024]; \
402 if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET)) \
405 if (mode == THIS_BYTE) \
406 memset(buf, byte, sizeof(buf)); \
407 for (len = sbp->st_size; len > 0; len -= wlen) { \
408 if (mode == RAND_BYTES) { \
409 for (i = 0; i < sizeof(buf); \
410 i+= sizeof(u_int32_t)) \
411 *(int *)(buf + i) = arc4random(); \
413 wlen = len < (off_t)sizeof(buf) ? (size_t)len : sizeof(buf); \
414 if ((size_t)write(fd, buf, wlen) != wlen) \
417 sync(); /* another poke at hidden caches */ \
418 } while (/* CONSTCOND */ 0)
420 #define READ_PASS(byte) do { \
423 char pattern[8 * 1024]; \
424 char buf[8 * 1024]; \
426 if (fsync(fd) || lseek(fd, (off_t)0, SEEK_SET)) \
429 memset(pattern, byte, sizeof(pattern)); \
430 for(len = sbp->st_size; len > 0; len -= rlen) { \
431 rlen = len < (off_t)sizeof(buf) ? (size_t)len : sizeof(buf); \
432 if((size_t)read(fd, buf, rlen) != rlen) \
434 if(memcmp(buf, pattern, rlen)) \
437 sync(); /* another poke at hidden caches */ \
438 } while (/* CONSTCOND */ 0)
441 * DSS sanitization matrix "clear" for magnetic disks:
442 * option 'c' "Overwrite all addressable locations with a single
445 randint
= arc4random();
446 randchar
= *(char *)&randint
;
447 WRITE_PASS(THIS_BYTE
, randchar
);
450 * DSS sanitization matrix "sanitize" for magnetic disks:
451 * option 'd', sub 2 "Overwrite all addressable locations with a
452 * character, then its complement. Verify "complement" character
453 * was written successfully to all addressable locations, then
454 * overwrite all addressable locations with random characters; or
455 * verify third overwrite of random characters." The rest of the
456 * text in d-sub-2 specifies requirements for overwriting spared
457 * sectors; we cannot conform to it when erasing only a file, thus
458 * we do not conform to the standard.
461 /* 1. "a character" */
462 WRITE_PASS(THIS_BYTE
, 0xff);
464 /* 2. "its complement" */
465 WRITE_PASS(THIS_BYTE
, 0x00);
467 /* 3. "Verify 'complement' character" */
470 /* 4. "overwrite all addressable locations with random characters" */
472 WRITE_PASS(RAND_BYTES
, 0x00);
475 * As the file might be huge, and we note that this revision of
476 * the matrix says "random characters", not "a random character"
477 * as the original did, we do not verify the random-character
478 * write; the "or" in the standard allows this.
481 if (close(fd
) == -1) {
496 check(char *path
, char *name
, struct stat
*sp
)
501 /* Check -i first. */
503 (void)fprintf(stderr
, "remove '%s'? ", path
);
506 * If it's not a symbolic link and it's unwritable and we're
507 * talking to a terminal, ask. Symbolic links are excluded
508 * because their permissions are meaningless. Check stdin_ok
509 * first because we may not have stat'ed the file.
511 if (!stdin_ok
|| S_ISLNK(sp
->st_mode
) ||
512 !(access(name
, W_OK
) && (errno
!= ETXTBSY
)))
514 strmode(sp
->st_mode
, modep
);
517 "%s: -P was specified but file could not"
518 " be overwritten", path
);
521 (void)fprintf(stderr
, "override %s%s%s:%s for '%s'? ",
522 modep
+ 1, modep
[9] == ' ' ? "" : " ",
523 user_from_uid(sp
->st_uid
, 0),
524 group_from_gid(sp
->st_gid
, 0), path
);
526 (void)fflush(stderr
);
528 first
= ch
= getchar();
529 while (ch
!= '\n' && ch
!= EOF
)
531 return (first
== 'y' || first
== 'Y');
535 * POSIX.2 requires that if "." or ".." are specified as the basename
536 * portion of an operand, a diagnostic message be written to standard
537 * error and nothing more be done with such operands.
539 * Since POSIX.2 defines basename as the final portion of a path after
540 * trailing slashes have been removed, we'll remove them here.
542 #define ISDOT(a) ((a)[0] == '.' && (!(a)[1] || ((a)[1] == '.' && !(a)[2])))
544 checkdot(char **argv
)
546 char *p
, **save
, **t
;
550 for (t
= argv
; *t
;) {
551 /* strip trailing slashes */
552 p
= strrchr(*t
, '\0');
553 while (--p
> *t
&& *p
== '/')
556 /* extract basename */
557 if ((p
= strrchr(*t
, '/')) != NULL
)
564 warnx("\".\" and \"..\" may not be removed");
566 for (save
= t
; (t
[0] = t
[1]) != NULL
; ++t
)
578 (void)fprintf(stderr
, "usage: %s [-f|-i] [-dPRrvW] file ...\n",