df: add --output=file to directly output specified arguments
[coreutils.git] / src / shred.c
blob95a255a5b58f294fe10b46c699b3342a5a9b13d4
1 /* shred.c - overwrite files and devices to make it harder to recover data
3 Copyright (C) 1999-2013 Free Software Foundation, Inc.
4 Copyright (C) 1997, 1998, 1999 Colin Plumb.
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 Written by Colin Plumb. */
22 * Do a more secure overwrite of given files or devices, to make it harder
23 * for even very expensive hardware probing to recover the data.
25 * Although this process is also known as "wiping", I prefer the longer
26 * name both because I think it is more evocative of what is happening and
27 * because a longer name conveys a more appropriate sense of deliberateness.
29 * For the theory behind this, see "Secure Deletion of Data from Magnetic
30 * and Solid-State Memory", on line at
31 * http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html
33 * Just for the record, reversing one or two passes of disk overwrite
34 * is not terribly difficult with hardware help. Hook up a good-quality
35 * digitizing oscilloscope to the output of the head preamplifier and copy
36 * the high-res digitized data to a computer for some off-line analysis.
37 * Read the "current" data and average all the pulses together to get an
38 * "average" pulse on the disk. Subtract this average pulse from all of
39 * the actual pulses and you can clearly see the "echo" of the previous
40 * data on the disk.
42 * Real hard drives have to balance the cost of the media, the head,
43 * and the read circuitry. They use better-quality media than absolutely
44 * necessary to limit the cost of the read circuitry. By throwing that
45 * assumption out, and the assumption that you want the data processed
46 * as fast as the hard drive can spin, you can do better.
48 * If asked to wipe a file, this also unlinks it, renaming it to in a
49 * clever way to try to leave no trace of the original filename.
51 * This was inspired by a desire to improve on some code titled:
52 * Wipe V1.0-- Overwrite and delete files. S. 2/3/96
53 * but I've rewritten everything here so completely that no trace of
54 * the original remains.
56 * Thanks to:
57 * Bob Jenkins, for his good RNG work and patience with the FSF copyright
58 * paperwork.
59 * Jim Meyering, for his work merging this into the GNU fileutils while
60 * still letting me feel a sense of ownership and pride. Getting me to
61 * tolerate the GNU brace style was quite a feat of diplomacy.
62 * Paul Eggert, for lots of useful discussion and code. I disagree with
63 * an awful lot of his suggestions, but they're disagreements worth having.
65 * Things to think about:
66 * - Security: Is there any risk to the race
67 * between overwriting and unlinking a file? Will it do anything
68 * drastically bad if told to attack a named pipe or socket?
71 /* The official name of this program (e.g., no 'g' prefix). */
72 #define PROGRAM_NAME "shred"
74 #define AUTHORS proper_name ("Colin Plumb")
76 #include <config.h>
78 #include <getopt.h>
79 #include <stdio.h>
80 #include <assert.h>
81 #include <setjmp.h>
82 #include <sys/types.h>
84 #include "system.h"
85 #include "xstrtol.h"
86 #include "error.h"
87 #include "fcntl--.h"
88 #include "human.h"
89 #include "quotearg.h" /* For quotearg_colon */
90 #include "randint.h"
91 #include "randread.h"
92 #include "stat-size.h"
94 /* Default number of times to overwrite. */
95 enum { DEFAULT_PASSES = 3 };
97 /* How many seconds to wait before checking whether to output another
98 verbose output line. */
99 enum { VERBOSE_UPDATE = 5 };
101 /* Sector size and corresponding mask, for recovering after write failures.
102 The size must be a power of 2. */
103 enum { SECTOR_SIZE = 512 };
104 enum { SECTOR_MASK = SECTOR_SIZE - 1 };
105 verify (0 < SECTOR_SIZE && (SECTOR_SIZE & SECTOR_MASK) == 0);
107 struct Options
109 bool force; /* -f flag: chmod files if necessary */
110 size_t n_iterations; /* -n flag: Number of iterations */
111 off_t size; /* -s flag: size of file */
112 bool remove_file; /* -u flag: remove file after shredding */
113 bool verbose; /* -v flag: Print progress */
114 bool exact; /* -x flag: Do not round up file size */
115 bool zero_fill; /* -z flag: Add a final zero pass */
118 /* For long options that have no equivalent short option, use a
119 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
120 enum
122 RANDOM_SOURCE_OPTION = CHAR_MAX + 1
125 static struct option const long_opts[] =
127 {"exact", no_argument, NULL, 'x'},
128 {"force", no_argument, NULL, 'f'},
129 {"iterations", required_argument, NULL, 'n'},
130 {"size", required_argument, NULL, 's'},
131 {"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION},
132 {"remove", no_argument, NULL, 'u'},
133 {"verbose", no_argument, NULL, 'v'},
134 {"zero", no_argument, NULL, 'z'},
135 {GETOPT_HELP_OPTION_DECL},
136 {GETOPT_VERSION_OPTION_DECL},
137 {NULL, 0, NULL, 0}
140 void
141 usage (int status)
143 if (status != EXIT_SUCCESS)
144 emit_try_help ();
145 else
147 printf (_("Usage: %s [OPTION]... FILE...\n"), program_name);
148 fputs (_("\
149 Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\
150 for even very expensive hardware probing to recover the data.\n\
151 "), stdout);
153 emit_mandatory_arg_note ();
155 printf (_("\
156 -f, --force change permissions to allow writing if necessary\n\
157 -n, --iterations=N overwrite N times instead of the default (%d)\n\
158 --random-source=FILE get random bytes from FILE\n\
159 -s, --size=N shred this many bytes (suffixes like K, M, G accepted)\n\
160 "), DEFAULT_PASSES);
161 fputs (_("\
162 -u, --remove truncate and remove file after overwriting\n\
163 -v, --verbose show progress\n\
164 -x, --exact do not round file sizes up to the next full block;\n\
165 this is the default for non-regular files\n\
166 -z, --zero add a final overwrite with zeros to hide shredding\n\
167 "), stdout);
168 fputs (HELP_OPTION_DESCRIPTION, stdout);
169 fputs (VERSION_OPTION_DESCRIPTION, stdout);
170 fputs (_("\
172 If FILE is -, shred standard output.\n\
174 Delete FILE(s) if --remove (-u) is specified. The default is not to remove\n\
175 the files because it is common to operate on device files like /dev/hda,\n\
176 and those files usually should not be removed. When operating on regular\n\
177 files, most people use the --remove option.\n\
179 "), stdout);
180 fputs (_("\
181 CAUTION: Note that shred relies on a very important assumption:\n\
182 that the file system overwrites data in place. This is the traditional\n\
183 way to do things, but many modern file system designs do not satisfy this\n\
184 assumption. The following are examples of file systems on which shred is\n\
185 not effective, or is not guaranteed to be effective in all file system modes:\n\
187 "), stdout);
188 fputs (_("\
189 * log-structured or journaled file systems, such as those supplied with\n\
190 AIX and Solaris (and JFS, ReiserFS, XFS, Ext3, etc.)\n\
192 * file systems that write redundant data and carry on even if some writes\n\
193 fail, such as RAID-based file systems\n\
195 * file systems that make snapshots, such as Network Appliance's NFS server\n\
197 "), stdout);
198 fputs (_("\
199 * file systems that cache in temporary locations, such as NFS\n\
200 version 3 clients\n\
202 * compressed file systems\n\
204 "), stdout);
205 fputs (_("\
206 In the case of ext3 file systems, the above disclaimer applies\n\
207 (and shred is thus of limited effectiveness) only in data=journal mode,\n\
208 which journals file data in addition to just metadata. In both the\n\
209 data=ordered (default) and data=writeback modes, shred works as usual.\n\
210 Ext3 journaling modes can be changed by adding the data=something option\n\
211 to the mount options for a particular file system in the /etc/fstab file,\n\
212 as documented in the mount man page (man mount).\n\
214 "), stdout);
215 fputs (_("\
216 In addition, file system backups and remote mirrors may contain copies\n\
217 of the file that cannot be removed, and that will allow a shredded file\n\
218 to be recovered later.\n\
219 "), stdout);
220 emit_ancillary_info ();
222 exit (status);
226 * Determine if pattern type is periodic or not.
228 static bool
229 periodic_pattern (int type)
231 if (type <= 0)
232 return false;
234 unsigned char r[3];
235 unsigned int bits = type & 0xfff;
237 bits |= bits << 12;
238 r[0] = (bits >> 4) & 255;
239 r[1] = (bits >> 8) & 255;
240 r[2] = bits & 255;
242 return (r[0] != r[1]) || (r[0] != r[2]);
246 * Fill a buffer with a fixed pattern.
248 * The buffer must be at least 3 bytes long, even if
249 * size is less. Larger sizes are filled exactly.
251 static void
252 fillpattern (int type, unsigned char *r, size_t size)
254 size_t i;
255 unsigned int bits = type & 0xfff;
257 bits |= bits << 12;
258 r[0] = (bits >> 4) & 255;
259 r[1] = (bits >> 8) & 255;
260 r[2] = bits & 255;
261 for (i = 3; i < size / 2; i *= 2)
262 memcpy (r + i, r, i);
263 if (i < size)
264 memcpy (r + i, r, size - i);
266 /* Invert the first bit of every sector. */
267 if (type & 0x1000)
268 for (i = 0; i < size; i += SECTOR_SIZE)
269 r[i] ^= 0x80;
273 * Generate a 6-character (+ nul) pass name string
274 * FIXME: allow translation of "random".
276 #define PASS_NAME_SIZE 7
277 static void
278 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
280 if (data)
281 sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
282 else
283 memcpy (name, "random", PASS_NAME_SIZE);
286 /* Return true when it's ok to ignore an fsync or fdatasync
287 failure that set errno to ERRNO_VAL. */
288 static bool
289 ignorable_sync_errno (int errno_val)
291 return (errno_val == EINVAL
292 || errno_val == EBADF
293 /* HP-UX does this */
294 || errno_val == EISDIR);
297 /* Request that all data for FD be transferred to the corresponding
298 storage device. QNAME is the file name (quoted for colons).
299 Report any errors found. Return 0 on success, -1
300 (setting errno) on failure. It is not an error if fdatasync and/or
301 fsync is not supported for this file, or if the file is not a
302 writable file descriptor. */
303 static int
304 dosync (int fd, char const *qname)
306 int err;
308 #if HAVE_FDATASYNC
309 if (fdatasync (fd) == 0)
310 return 0;
311 err = errno;
312 if ( ! ignorable_sync_errno (err))
314 error (0, err, _("%s: fdatasync failed"), qname);
315 errno = err;
316 return -1;
318 #endif
320 if (fsync (fd) == 0)
321 return 0;
322 err = errno;
323 if ( ! ignorable_sync_errno (err))
325 error (0, err, _("%s: fsync failed"), qname);
326 errno = err;
327 return -1;
330 sync ();
331 return 0;
334 /* Turn on or off direct I/O mode for file descriptor FD, if possible.
335 Try to turn it on if ENABLE is true. Otherwise, try to turn it off. */
336 static void
337 direct_mode (int fd, bool enable)
339 if (O_DIRECT)
341 int fd_flags = fcntl (fd, F_GETFL);
342 if (0 < fd_flags)
344 int new_flags = (enable
345 ? (fd_flags | O_DIRECT)
346 : (fd_flags & ~O_DIRECT));
347 if (new_flags != fd_flags)
348 fcntl (fd, F_SETFL, new_flags);
352 #if HAVE_DIRECTIO && defined DIRECTIO_ON && defined DIRECTIO_OFF
353 /* This is Solaris-specific. See the following for details:
354 http://docs.sun.com/db/doc/816-0213/6m6ne37so?q=directio&a=view */
355 directio (fd, enable ? DIRECTIO_ON : DIRECTIO_OFF);
356 #endif
360 * Do pass number k of n, writing "size" bytes of the given pattern "type"
361 * to the file descriptor fd. Qname, k and n are passed in only for verbose
362 * progress message purposes. If n == 0, no progress messages are printed.
364 * If *sizep == -1, the size is unknown, and it will be filled in as soon
365 * as writing fails.
367 * Return 1 on write error, -1 on other error, 0 on success.
369 static int
370 dopass (int fd, char const *qname, off_t *sizep, int type,
371 struct randread_source *s, unsigned long int k, unsigned long int n)
373 off_t size = *sizep;
374 off_t offset; /* Current file posiiton */
375 time_t thresh IF_LINT ( = 0); /* Time to maybe print next status update */
376 time_t now = 0; /* Current time */
377 size_t lim; /* Amount of data to try writing */
378 size_t soff; /* Offset into buffer for next write */
379 ssize_t ssize; /* Return value from write */
381 /* Do nothing for --size=0 or regular empty files with --exact. */
382 if (size == 0)
383 return 0;
385 /* Fill pattern buffer. Aligning it to a page so we can do direct I/O. */
386 size_t page_size = getpagesize ();
387 #define PERIODIC_OUTPUT_SIZE (60 * 1024)
388 #define NONPERIODIC_OUTPUT_SIZE (64 * 1024)
389 verify (PERIODIC_OUTPUT_SIZE % 3 == 0);
390 size_t output_size = periodic_pattern (type)
391 ? PERIODIC_OUTPUT_SIZE : NONPERIODIC_OUTPUT_SIZE;
392 #define PAGE_ALIGN_SLOP (page_size - 1) /* So directio works */
393 #define FILLPATTERN_SIZE (((output_size + 2) / 3) * 3) /* Multiple of 3 */
394 #define PATTERNBUF_SIZE (PAGE_ALIGN_SLOP + FILLPATTERN_SIZE)
395 void *fill_pattern_mem = xmalloc (PATTERNBUF_SIZE);
396 unsigned char *pbuf = ptr_align (fill_pattern_mem, page_size);
398 char pass_string[PASS_NAME_SIZE]; /* Name of current pass */
399 bool write_error = false;
400 bool other_error = false;
401 bool tried_without_directio = false;
403 /* Printable previous offset into the file */
404 char previous_offset_buf[LONGEST_HUMAN_READABLE + 1];
405 char const *previous_human_offset IF_LINT ( = 0);
407 if (lseek (fd, 0, SEEK_SET) == -1)
409 error (0, errno, _("%s: cannot rewind"), qname);
410 other_error = true;
411 goto free_pattern_mem;
414 /* Constant fill patterns need only be set up once. */
415 if (type >= 0)
417 lim = (0 <= size && size < FILLPATTERN_SIZE ? size : FILLPATTERN_SIZE);
418 fillpattern (type, pbuf, lim);
419 passname (pbuf, pass_string);
421 else
423 passname (0, pass_string);
426 /* Set position if first status update */
427 if (n)
429 error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
430 thresh = time (NULL) + VERBOSE_UPDATE;
431 previous_human_offset = "";
434 offset = 0;
435 while (true)
437 /* How much to write this time? */
438 lim = output_size;
439 if (0 <= size && size - offset < output_size)
441 if (size < offset)
442 break;
443 lim = size - offset;
444 if (!lim)
445 break;
447 if (type < 0)
448 randread (s, pbuf, lim);
449 /* Loop to retry partial writes. */
450 for (soff = 0; soff < lim; soff += ssize)
452 ssize = write (fd, pbuf + soff, lim - soff);
453 if (ssize <= 0)
455 if (size < 0 && (ssize == 0 || errno == ENOSPC))
457 /* Ah, we have found the end of the file */
458 *sizep = size = offset + soff;
459 break;
461 else
463 int errnum = errno;
464 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
466 /* Retry without direct I/O since this may not be supported
467 at all on some (file) systems, or with the current size.
468 I.E. a specified --size that is not aligned, or when
469 dealing with slop at the end of a file with --exact. */
470 if (k == 1 && !tried_without_directio && errno == EINVAL)
472 direct_mode (fd, false);
473 ssize = 0;
474 tried_without_directio = true;
475 continue;
477 error (0, errnum, _("%s: error writing at offset %s"),
478 qname, umaxtostr (offset + soff, buf));
480 /* 'shred' is often used on bad media, before throwing it
481 out. Thus, it shouldn't give up on bad blocks. This
482 code works because lim is always a multiple of
483 SECTOR_SIZE, except at the end. This size constraint
484 also enables direct I/O on some (file) systems. */
485 verify (PERIODIC_OUTPUT_SIZE % SECTOR_SIZE == 0);
486 verify (NONPERIODIC_OUTPUT_SIZE % SECTOR_SIZE == 0);
487 if (errnum == EIO && 0 <= size && (soff | SECTOR_MASK) < lim)
489 size_t soff1 = (soff | SECTOR_MASK) + 1;
490 if (lseek (fd, offset + soff1, SEEK_SET) != -1)
492 /* Arrange to skip this block. */
493 ssize = soff1 - soff;
494 write_error = true;
495 continue;
497 error (0, errno, _("%s: lseek failed"), qname);
499 other_error = true;
500 goto free_pattern_mem;
505 /* Okay, we have written "soff" bytes. */
507 if (offset > OFF_T_MAX - (off_t) soff)
509 error (0, 0, _("%s: file too large"), qname);
510 other_error = true;
511 goto free_pattern_mem;
514 offset += soff;
516 bool done = offset == size;
518 /* Time to print progress? */
519 if (n && ((done && *previous_human_offset)
520 || thresh <= (now = time (NULL))))
522 char offset_buf[LONGEST_HUMAN_READABLE + 1];
523 char size_buf[LONGEST_HUMAN_READABLE + 1];
524 int human_progress_opts = (human_autoscale | human_SI
525 | human_base_1024 | human_B);
526 char const *human_offset
527 = human_readable (offset, offset_buf,
528 human_floor | human_progress_opts, 1, 1);
530 if (done || !STREQ (previous_human_offset, human_offset))
532 if (size < 0)
533 error (0, 0, _("%s: pass %lu/%lu (%s)...%s"),
534 qname, k, n, pass_string, human_offset);
535 else
537 uintmax_t off = offset;
538 int percent = (size == 0
539 ? 100
540 : (off <= TYPE_MAXIMUM (uintmax_t) / 100
541 ? off * 100 / size
542 : off / (size / 100)));
543 char const *human_size
544 = human_readable (size, size_buf,
545 human_ceiling | human_progress_opts,
546 1, 1);
547 if (done)
548 human_offset = human_size;
549 error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s %d%%"),
550 qname, k, n, pass_string, human_offset, human_size,
551 percent);
554 strcpy (previous_offset_buf, human_offset);
555 previous_human_offset = previous_offset_buf;
556 thresh = now + VERBOSE_UPDATE;
559 * Force periodic syncs to keep displayed progress accurate
560 * FIXME: Should these be present even if -v is not enabled,
561 * to keep the buffer cache from filling with dirty pages?
562 * It's a common problem with programs that do lots of writes,
563 * like mkfs.
565 if (dosync (fd, qname) != 0)
567 if (errno != EIO)
569 other_error = true;
570 goto free_pattern_mem;
572 write_error = true;
578 /* Force what we just wrote to hit the media. */
579 if (dosync (fd, qname) != 0)
581 if (errno != EIO)
583 other_error = true;
584 goto free_pattern_mem;
586 write_error = true;
589 free_pattern_mem:
590 memset (pbuf, 0, FILLPATTERN_SIZE);
591 free (fill_pattern_mem);
593 return other_error ? -1 : write_error;
597 * The passes start and end with a random pass, and the passes in between
598 * are done in random order. The idea is to deprive someone trying to
599 * reverse the process of knowledge of the overwrite patterns, so they
600 * have the additional step of figuring out what was done to the disk
601 * before they can try to reverse or cancel it.
603 * First, all possible 1-bit patterns. There are two of them.
604 * Then, all possible 2-bit patterns. There are four, but the two
605 * which are also 1-bit patterns can be omitted.
606 * Then, all possible 3-bit patterns. Likewise, 8-2 = 6.
607 * Then, all possible 4-bit patterns. 16-4 = 12.
609 * The basic passes are:
610 * 1-bit: 0x000, 0xFFF
611 * 2-bit: 0x555, 0xAAA
612 * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
613 * 100100100100 110110110110
614 * 9 2 4 D B 6
615 * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
616 * 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
617 * Adding three random passes at the beginning, middle and end
618 * produces the default 25-pass structure.
620 * The next extension would be to 5-bit and 6-bit patterns.
621 * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
622 * 6-bit patterns, so they would increase the time required
623 * significantly. 4-bit patterns are enough for most purposes.
625 * The main gotcha is that this would require a trickier encoding,
626 * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
627 * lcm(2,3,4,5) = 60 bits is not.
629 * One extension that is included is to complement the first bit in each
630 * 512-byte block, to alter the phase of the encoded data in the more
631 * complex encodings. This doesn't apply to MFM, so the 1-bit patterns
632 * are considered part of the 3-bit ones and the 2-bit patterns are
633 * considered part of the 4-bit patterns.
636 * How does the generalization to variable numbers of passes work?
638 * Here's how...
639 * Have an ordered list of groups of passes. Each group is a set.
640 * Take as many groups as will fit, plus a random subset of the
641 * last partial group, and place them into the passes list.
642 * Then shuffle the passes list into random order and use that.
644 * One extra detail: if we can't include a large enough fraction of the
645 * last group to be interesting, then just substitute random passes.
647 * If you want more passes than the entire list of groups can
648 * provide, just start repeating from the beginning of the list.
650 static int const
651 patterns[] =
653 -2, /* 2 random passes */
654 2, 0x000, 0xFFF, /* 1-bit */
655 2, 0x555, 0xAAA, /* 2-bit */
656 -1, /* 1 random pass */
657 6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6, /* 3-bit */
658 12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
659 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */
660 -1, /* 1 random pass */
661 /* The following patterns have the frst bit per block flipped */
662 8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
663 14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
664 0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
665 -1, /* 1 random pass */
666 0 /* End */
670 * Generate a random wiping pass pattern with num passes.
671 * This is a two-stage process. First, the passes to include
672 * are chosen, and then they are shuffled into the desired
673 * order.
675 static void
676 genpattern (int *dest, size_t num, struct randint_source *s)
678 size_t randpasses;
679 int const *p;
680 int *d;
681 size_t n;
682 size_t accum, top, swap;
683 int k;
685 if (!num)
686 return;
688 /* Stage 1: choose the passes to use */
689 p = patterns;
690 randpasses = 0;
691 d = dest; /* Destination for generated pass list */
692 n = num; /* Passes remaining to fill */
694 while (true)
696 k = *p++; /* Block descriptor word */
697 if (!k)
698 { /* Loop back to the beginning */
699 p = patterns;
701 else if (k < 0)
702 { /* -k random passes */
703 k = -k;
704 if ((size_t) k >= n)
706 randpasses += n;
707 break;
709 randpasses += k;
710 n -= k;
712 else if ((size_t) k <= n)
713 { /* Full block of patterns */
714 memcpy (d, p, k * sizeof (int));
715 p += k;
716 d += k;
717 n -= k;
719 else if (n < 2 || 3 * n < (size_t) k)
720 { /* Finish with random */
721 randpasses += n;
722 break;
724 else
725 { /* Pad out with k of the n available */
728 if (n == (size_t) k || randint_choose (s, k) < n)
730 *d++ = *p;
731 n--;
733 p++;
735 while (n);
736 break;
739 top = num - randpasses; /* Top of initialized data */
740 /* assert (d == dest+top); */
743 * We now have fixed patterns in the dest buffer up to
744 * "top", and we need to scramble them, with "randpasses"
745 * random passes evenly spaced among them.
747 * We want one at the beginning, one at the end, and
748 * evenly spaced in between. To do this, we basically
749 * use Bresenham's line draw (a.k.a DDA) algorithm
750 * to draw a line with slope (randpasses-1)/(num-1).
751 * (We use a positive accumulator and count down to
752 * do this.)
754 * So for each desired output value, we do the following:
755 * - If it should be a random pass, copy the pass type
756 * to top++, out of the way of the other passes, and
757 * set the current pass to -1 (random).
758 * - If it should be a normal pattern pass, choose an
759 * entry at random between here and top-1 (inclusive)
760 * and swap the current entry with that one.
762 randpasses--; /* To speed up later math */
763 accum = randpasses; /* Bresenham DDA accumulator */
764 for (n = 0; n < num; n++)
766 if (accum <= randpasses)
768 accum += num - 1;
769 dest[top++] = dest[n];
770 dest[n] = -1;
772 else
774 swap = n + randint_choose (s, top - n);
775 k = dest[n];
776 dest[n] = dest[swap];
777 dest[swap] = k;
779 accum -= randpasses;
781 /* assert (top == num); */
785 * The core routine to actually do the work. This overwrites the first
786 * size bytes of the given fd. Return true if successful.
788 static bool
789 do_wipefd (int fd, char const *qname, struct randint_source *s,
790 struct Options const *flags)
792 size_t i;
793 struct stat st;
794 off_t size; /* Size to write, size to read */
795 unsigned long int n; /* Number of passes for printing purposes */
796 int *passarray;
797 bool ok = true;
798 struct randread_source *rs;
800 n = 0; /* dopass takes n -- 0 to mean "don't print progress" */
801 if (flags->verbose)
802 n = flags->n_iterations + flags->zero_fill;
804 if (fstat (fd, &st))
806 error (0, errno, _("%s: fstat failed"), qname);
807 return false;
810 /* If we know that we can't possibly shred the file, give up now.
811 Otherwise, we may go into an infinite loop writing data before we
812 find that we can't rewind the device. */
813 if ((S_ISCHR (st.st_mode) && isatty (fd))
814 || S_ISFIFO (st.st_mode)
815 || S_ISSOCK (st.st_mode))
817 error (0, 0, _("%s: invalid file type"), qname);
818 return false;
821 direct_mode (fd, true);
823 /* Allocate pass array */
824 passarray = xnmalloc (flags->n_iterations, sizeof *passarray);
826 size = flags->size;
827 if (size == -1)
829 /* Accept a length of zero only if it's a regular file.
830 For any other type of file, try to get the size another way. */
831 if (S_ISREG (st.st_mode))
833 size = st.st_size;
834 if (size < 0)
836 error (0, 0, _("%s: file has negative size"), qname);
837 return false;
840 else
842 size = lseek (fd, 0, SEEK_END);
843 if (size <= 0)
845 /* We are unable to determine the length, up front.
846 Let dopass do that as part of its first iteration. */
847 size = -1;
851 /* Allow 'rounding up' only for regular files. */
852 if (0 <= size && !(flags->exact) && S_ISREG (st.st_mode))
854 size += ST_BLKSIZE (st) - 1 - (size - 1) % ST_BLKSIZE (st);
856 /* If in rounding up, we've just overflowed, use the maximum. */
857 if (size < 0)
858 size = TYPE_MAXIMUM (off_t);
862 /* Schedule the passes in random order. */
863 genpattern (passarray, flags->n_iterations, s);
865 rs = randint_get_source (s);
867 /* Do the work */
868 for (i = 0; i < flags->n_iterations; i++)
870 int err = dopass (fd, qname, &size, passarray[i], rs, i + 1, n);
871 if (err)
873 if (err < 0)
875 memset (passarray, 0, flags->n_iterations * sizeof (int));
876 free (passarray);
877 return false;
879 ok = false;
883 memset (passarray, 0, flags->n_iterations * sizeof (int));
884 free (passarray);
886 if (flags->zero_fill)
888 int err = dopass (fd, qname, &size, 0, rs, flags->n_iterations + 1, n);
889 if (err)
891 if (err < 0)
892 return false;
893 ok = false;
897 /* Okay, now deallocate the data. The effect of ftruncate on
898 non-regular files is unspecified, so don't worry about any
899 errors reported for them. */
900 if (flags->remove_file && ftruncate (fd, 0) != 0
901 && S_ISREG (st.st_mode))
903 error (0, errno, _("%s: error truncating"), qname);
904 return false;
907 return ok;
910 /* A wrapper with a little more checking for fds on the command line */
911 static bool
912 wipefd (int fd, char const *qname, struct randint_source *s,
913 struct Options const *flags)
915 int fd_flags = fcntl (fd, F_GETFL);
917 if (fd_flags < 0)
919 error (0, errno, _("%s: fcntl failed"), qname);
920 return false;
922 if (fd_flags & O_APPEND)
924 error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
925 return false;
927 return do_wipefd (fd, qname, s, flags);
930 /* --- Name-wiping code --- */
932 /* Characters allowed in a file name - a safe universal set. */
933 static char const nameset[] =
934 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
936 /* Increment NAME (with LEN bytes). NAME must be a big-endian base N
937 number with the digits taken from nameset. Return true if successful.
938 Otherwise, (because NAME already has the greatest possible value)
939 return false. */
941 static bool
942 incname (char *name, size_t len)
944 while (len--)
946 char const *p = strchr (nameset, name[len]);
948 /* Given that NAME is composed of bytes from NAMESET,
949 P will never be NULL here. */
950 assert (p);
952 /* If this character has a successor, use it. */
953 if (p[1])
955 name[len] = p[1];
956 return true;
959 /* Otherwise, set this digit to 0 and increment the prefix. */
960 name[len] = nameset[0];
963 return false;
967 * Repeatedly rename a file with shorter and shorter names,
968 * to obliterate all traces of the file name on any system that
969 * adds a trailing delimiter to on-disk file names and reuses
970 * the same directory slot. Finally, unlink it.
971 * The passed-in filename is modified in place to the new filename.
972 * (Which is unlinked if this function succeeds, but is still present if
973 * it fails for some reason.)
975 * The main loop is written carefully to not get stuck if all possible
976 * names of a given length are occupied. It counts down the length from
977 * the original to 0. While the length is non-zero, it tries to find an
978 * unused file name of the given length. It continues until either the
979 * name is available and the rename succeeds, or it runs out of names
980 * to try (incname wraps and returns 1). Finally, it unlinks the file.
982 * The unlink is Unix-specific, as ANSI-standard remove has more
983 * portability problems with C libraries making it "safe". rename
984 * is ANSI-standard.
986 * To force the directory data out, we try to open the directory and
987 * invoke fdatasync and/or fsync on it. This is non-standard, so don't
988 * insist that it works: just fall back to a global sync in that case.
989 * This is fairly significantly Unix-specific. Of course, on any
990 * file system with synchronous metadata updates, this is unnecessary.
992 static bool
993 wipename (char *oldname, char const *qoldname, struct Options const *flags)
995 char *newname = xstrdup (oldname);
996 char *base = last_component (newname);
997 size_t len = base_len (base);
998 char *dir = dir_name (newname);
999 char *qdir = xstrdup (quotearg_colon (dir));
1000 bool first = true;
1001 bool ok = true;
1003 int dir_fd = open (dir, O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK);
1005 if (flags->verbose)
1006 error (0, 0, _("%s: removing"), qoldname);
1008 while (len)
1010 memset (base, nameset[0], len);
1011 base[len] = 0;
1014 struct stat st;
1015 if (lstat (newname, &st) < 0)
1017 if (rename (oldname, newname) == 0)
1019 if (0 <= dir_fd && dosync (dir_fd, qdir) != 0)
1020 ok = false;
1021 if (flags->verbose)
1024 * People seem to understand this better than talking
1025 * about renaming oldname. newname doesn't need
1026 * quoting because we picked it. oldname needs to
1027 * be quoted only the first time.
1029 char const *old = (first ? qoldname : oldname);
1030 error (0, 0, _("%s: renamed to %s"), old, newname);
1031 first = false;
1033 memcpy (oldname + (base - newname), base, len + 1);
1034 break;
1036 else
1038 /* The rename failed: give up on this length. */
1039 break;
1042 else
1044 /* newname exists, so increment BASE so we use another */
1047 while (incname (base, len));
1048 len--;
1050 if (unlink (oldname) != 0)
1052 error (0, errno, _("%s: failed to remove"), qoldname);
1053 ok = false;
1055 else if (flags->verbose)
1056 error (0, 0, _("%s: removed"), qoldname);
1057 if (0 <= dir_fd)
1059 if (dosync (dir_fd, qdir) != 0)
1060 ok = false;
1061 if (close (dir_fd) != 0)
1063 error (0, errno, _("%s: failed to close"), qdir);
1064 ok = false;
1067 free (newname);
1068 free (dir);
1069 free (qdir);
1070 return ok;
1074 * Finally, the function that actually takes a filename and grinds
1075 * it into hamburger.
1077 * FIXME
1078 * Detail to note: since we do not restore errno to EACCES after
1079 * a failed chmod, we end up printing the error code from the chmod.
1080 * This is actually the error that stopped us from proceeding, so
1081 * it's arguably the right one, and in practice it'll be either EACCES
1082 * again or EPERM, which both give similar error messages.
1083 * Does anyone disagree?
1085 static bool
1086 wipefile (char *name, char const *qname,
1087 struct randint_source *s, struct Options const *flags)
1089 bool ok;
1090 int fd;
1092 fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1093 if (fd < 0
1094 && (errno == EACCES && flags->force)
1095 && chmod (name, S_IWUSR) == 0)
1096 fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1097 if (fd < 0)
1099 error (0, errno, _("%s: failed to open for writing"), qname);
1100 return false;
1103 ok = do_wipefd (fd, qname, s, flags);
1104 if (close (fd) != 0)
1106 error (0, errno, _("%s: failed to close"), qname);
1107 ok = false;
1109 if (ok && flags->remove_file)
1110 ok = wipename (name, qname, flags);
1111 return ok;
1115 /* Buffers for random data. */
1116 static struct randint_source *randint_source;
1118 /* Just on general principles, wipe buffers containing information
1119 that may be related to the possibly-pseudorandom values used during
1120 shredding. */
1121 static void
1122 clear_random_data (void)
1124 randint_all_free (randint_source);
1129 main (int argc, char **argv)
1131 bool ok = true;
1132 struct Options flags = { 0, };
1133 char **file;
1134 int n_files;
1135 int c;
1136 int i;
1137 char const *random_source = NULL;
1139 initialize_main (&argc, &argv);
1140 set_program_name (argv[0]);
1141 setlocale (LC_ALL, "");
1142 bindtextdomain (PACKAGE, LOCALEDIR);
1143 textdomain (PACKAGE);
1145 atexit (close_stdout);
1147 flags.n_iterations = DEFAULT_PASSES;
1148 flags.size = -1;
1150 while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1152 switch (c)
1154 case 'f':
1155 flags.force = true;
1156 break;
1158 case 'n':
1160 uintmax_t tmp;
1161 if (xstrtoumax (optarg, NULL, 10, &tmp, NULL) != LONGINT_OK
1162 || MIN (UINT32_MAX, SIZE_MAX / sizeof (int)) < tmp)
1164 error (EXIT_FAILURE, 0, _("%s: invalid number of passes"),
1165 quotearg_colon (optarg));
1167 flags.n_iterations = tmp;
1169 break;
1171 case RANDOM_SOURCE_OPTION:
1172 if (random_source && !STREQ (random_source, optarg))
1173 error (EXIT_FAILURE, 0, _("multiple random sources specified"));
1174 random_source = optarg;
1175 break;
1177 case 'u':
1178 flags.remove_file = true;
1179 break;
1181 case 's':
1183 uintmax_t tmp;
1184 if (xstrtoumax (optarg, NULL, 0, &tmp, "cbBkKMGTPEZY0")
1185 != LONGINT_OK)
1187 error (EXIT_FAILURE, 0, _("%s: invalid file size"),
1188 quotearg_colon (optarg));
1190 flags.size = tmp;
1192 break;
1194 case 'v':
1195 flags.verbose = true;
1196 break;
1198 case 'x':
1199 flags.exact = true;
1200 break;
1202 case 'z':
1203 flags.zero_fill = true;
1204 break;
1206 case_GETOPT_HELP_CHAR;
1208 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1210 default:
1211 usage (EXIT_FAILURE);
1215 file = argv + optind;
1216 n_files = argc - optind;
1218 if (n_files == 0)
1220 error (0, 0, _("missing file operand"));
1221 usage (EXIT_FAILURE);
1224 randint_source = randint_all_new (random_source, SIZE_MAX);
1225 if (! randint_source)
1226 error (EXIT_FAILURE, errno, "%s", quotearg_colon (random_source));
1227 atexit (clear_random_data);
1229 for (i = 0; i < n_files; i++)
1231 char *qname = xstrdup (quotearg_colon (file[i]));
1232 if (STREQ (file[i], "-"))
1234 ok &= wipefd (STDOUT_FILENO, qname, randint_source, &flags);
1236 else
1238 /* Plain filename - Note that this overwrites *argv! */
1239 ok &= wipefile (file[i], qname, randint_source, &flags);
1241 free (qname);
1244 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
1247 * vim:sw=2:sts=2: