Port parts of the code to C89 to minimize the need for c99-to-c89.diff,
[coreutils.git] / src / shred.c
blob4c1819ccb189ff077a4fb45c7faf9f69e5e52d47
1 /* shred.c - overwrite files and devices to make it harder to recover data
3 Copyright (C) 1999-2006 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 2, or (at your option)
9 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, write to the Free Software Foundation,
18 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 Written by Colin Plumb. */
22 /* TODO:
23 - use consistent non-capitalization in error messages
24 - add standard GNU copyleft comment
26 - Add -r/-R/--recursive
27 - Add -i/--interactive
28 - Reserve -d
29 - Add -L
30 - Add an unlink-all option to emulate rm.
34 * Do a more secure overwrite of given files or devices, to make it harder
35 * for even very expensive hardware probing to recover the data.
37 * Although this process is also known as "wiping", I prefer the longer
38 * name both because I think it is more evocative of what is happening and
39 * because a longer name conveys a more appropriate sense of deliberateness.
41 * For the theory behind this, see "Secure Deletion of Data from Magnetic
42 * and Solid-State Memory", on line at
43 * http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html
45 * Just for the record, reversing one or two passes of disk overwrite
46 * is not terribly difficult with hardware help. Hook up a good-quality
47 * digitizing oscilloscope to the output of the head preamplifier and copy
48 * the high-res digitized data to a computer for some off-line analysis.
49 * Read the "current" data and average all the pulses together to get an
50 * "average" pulse on the disk. Subtract this average pulse from all of
51 * the actual pulses and you can clearly see the "echo" of the previous
52 * data on the disk.
54 * Real hard drives have to balance the cost of the media, the head,
55 * and the read circuitry. They use better-quality media than absolutely
56 * necessary to limit the cost of the read circuitry. By throwing that
57 * assumption out, and the assumption that you want the data processed
58 * as fast as the hard drive can spin, you can do better.
60 * If asked to wipe a file, this also unlinks it, renaming it to in a
61 * clever way to try to leave no trace of the original filename.
63 * This was inspired by a desire to improve on some code titled:
64 * Wipe V1.0-- Overwrite and delete files. S. 2/3/96
65 * but I've rewritten everything here so completely that no trace of
66 * the original remains.
68 * Thanks to:
69 * Bob Jenkins, for his good RNG work and patience with the FSF copyright
70 * paperwork.
71 * Jim Meyering, for his work merging this into the GNU fileutils while
72 * still letting me feel a sense of ownership and pride. Getting me to
73 * tolerate the GNU brace style was quite a feat of diplomacy.
74 * Paul Eggert, for lots of useful discussion and code. I disagree with
75 * an awful lot of his suggestions, but they're disagreements worth having.
77 * Things to think about:
78 * - Security: Is there any risk to the race
79 * between overwriting and unlinking a file? Will it do anything
80 * drastically bad if told to attack a named pipe or socket?
83 /* The official name of this program (e.g., no `g' prefix). */
84 #define PROGRAM_NAME "shred"
86 #define AUTHORS "Colin Plumb"
88 #include <config.h>
90 #include <getopt.h>
91 #include <stdio.h>
92 #include <assert.h>
93 #include <setjmp.h>
94 #include <sys/types.h>
96 #include "system.h"
97 #include "xstrtol.h"
98 #include "error.h"
99 #include "fcntl--.h"
100 #include "getpagesize.h"
101 #include "human.h"
102 #include "inttostr.h"
103 #include "quotearg.h" /* For quotearg_colon */
104 #include "quote.h" /* For quotearg_colon */
105 #include "randint.h"
106 #include "randread.h"
108 /* Default number of times to overwrite. */
109 enum { DEFAULT_PASSES = 25 };
111 /* How many seconds to wait before checking whether to output another
112 verbose output line. */
113 enum { VERBOSE_UPDATE = 5 };
115 /* Sector size and corresponding mask, for recovering after write failures.
116 The size must be a power of 2. */
117 enum { SECTOR_SIZE = 512 };
118 enum { SECTOR_MASK = SECTOR_SIZE - 1 };
119 verify (0 < SECTOR_SIZE && (SECTOR_SIZE & SECTOR_MASK) == 0);
121 struct Options
123 bool force; /* -f flag: chmod files if necessary */
124 size_t n_iterations; /* -n flag: Number of iterations */
125 off_t size; /* -s flag: size of file */
126 bool remove_file; /* -u flag: remove file after shredding */
127 bool verbose; /* -v flag: Print progress */
128 bool exact; /* -x flag: Do not round up file size */
129 bool zero_fill; /* -z flag: Add a final zero pass */
132 /* For long options that have no equivalent short option, use a
133 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
134 enum
136 RANDOM_SOURCE_OPTION = CHAR_MAX + 1
139 static struct option const long_opts[] =
141 {"exact", no_argument, NULL, 'x'},
142 {"force", no_argument, NULL, 'f'},
143 {"iterations", required_argument, NULL, 'n'},
144 {"size", required_argument, NULL, 's'},
145 {"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION},
146 {"remove", no_argument, NULL, 'u'},
147 {"verbose", no_argument, NULL, 'v'},
148 {"zero", no_argument, NULL, 'z'},
149 {GETOPT_HELP_OPTION_DECL},
150 {GETOPT_VERSION_OPTION_DECL},
151 {NULL, 0, NULL, 0}
154 /* Global variable for error printing purposes */
155 char const *program_name; /* Initialized before any possible use */
157 void
158 usage (int status)
160 if (status != EXIT_SUCCESS)
161 fprintf (stderr, _("Try `%s --help' for more information.\n"),
162 program_name);
163 else
165 printf (_("Usage: %s [OPTIONS] FILE [...]\n"), program_name);
166 fputs (_("\
167 Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\
168 for even very expensive hardware probing to recover the data.\n\
170 "), stdout);
171 fputs (_("\
172 Mandatory arguments to long options are mandatory for short options too.\n\
173 "), stdout);
174 printf (_("\
175 -f, --force change permissions to allow writing if necessary\n\
176 -n, --iterations=N Overwrite N times instead of the default (%d)\n\
177 --random-source=FILE get random bytes from FILE (default /dev/urandom)\n\
178 -s, --size=N shred this many bytes (suffixes like K, M, G accepted)\n\
179 "), DEFAULT_PASSES);
180 fputs (_("\
181 -u, --remove truncate and remove file after overwriting\n\
182 -v, --verbose show progress\n\
183 -x, --exact do not round file sizes up to the next full block;\n\
184 this is the default for non-regular files\n\
185 -z, --zero add a final overwrite with zeros to hide shredding\n\
186 "), stdout);
187 fputs (HELP_OPTION_DESCRIPTION, stdout);
188 fputs (VERSION_OPTION_DESCRIPTION, stdout);
189 fputs (_("\
191 If FILE is -, shred standard output.\n\
193 Delete FILE(s) if --remove (-u) is specified. The default is not to remove\n\
194 the files because it is common to operate on device files like /dev/hda,\n\
195 and those files usually should not be removed. When operating on regular\n\
196 files, most people use the --remove option.\n\
198 "), stdout);
199 fputs (_("\
200 CAUTION: Note that shred relies on a very important assumption:\n\
201 that the file system overwrites data in place. This is the traditional\n\
202 way to do things, but many modern file system designs do not satisfy this\n\
203 assumption. The following are examples of file systems on which shred is\n\
204 not effective, or is not guaranteed to be effective in all file system modes:\n\
206 "), stdout);
207 fputs (_("\
208 * log-structured or journaled file systems, such as those supplied with\n\
209 AIX and Solaris (and JFS, ReiserFS, XFS, Ext3, etc.)\n\
211 * file systems that write redundant data and carry on even if some writes\n\
212 fail, such as RAID-based file systems\n\
214 * file systems that make snapshots, such as Network Appliance's NFS server\n\
216 "), stdout);
217 fputs (_("\
218 * file systems that cache in temporary locations, such as NFS\n\
219 version 3 clients\n\
221 * compressed file systems\n\
223 In the case of ext3 file systems, the above disclaimer applies\n\
224 (and shred is thus of limited effectiveness) only in data=journal mode,\n\
225 which journals file data in addition to just metadata. In both the\n\
226 data=ordered (default) and data=writeback modes, shred works as usual.\n\
227 Ext3 journaling modes can be changed by adding the data=something option\n\
228 to the mount options for a particular file system in the /etc/fstab file,\n\
229 as documented in the mount man page (man mount).\n\
231 In addition, file system backups and remote mirrors may contain copies\n\
232 of the file that cannot be removed, and that will allow a shredded file\n\
233 to be recovered later.\n\
234 "), stdout);
235 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
237 exit (status);
242 * Fill a buffer with a fixed pattern.
244 * The buffer must be at least 3 bytes long, even if
245 * size is less. Larger sizes are filled exactly.
247 static void
248 fillpattern (int type, unsigned char *r, size_t size)
250 size_t i;
251 unsigned int bits = type & 0xfff;
253 bits |= bits << 12;
254 r[0] = (bits >> 4) & 255;
255 r[1] = (bits >> 8) & 255;
256 r[2] = bits & 255;
257 for (i = 3; i < size / 2; i *= 2)
258 memcpy (r + i, r, i);
259 if (i < size)
260 memcpy (r + i, r, size - i);
262 /* Invert the first bit of every sector. */
263 if (type & 0x1000)
264 for (i = 0; i < size; i += SECTOR_SIZE)
265 r[i] ^= 0x80;
269 * Generate a 6-character (+ nul) pass name string
270 * FIXME: allow translation of "random".
272 #define PASS_NAME_SIZE 7
273 static void
274 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
276 if (data)
277 sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
278 else
279 memcpy (name, "random", PASS_NAME_SIZE);
282 /* Request that all data for FD be transferred to the corresponding
283 storage device. QNAME is the file name (quoted for colons).
284 Report any errors found. Return 0 on success, -1
285 (setting errno) on failure. It is not an error if fdatasync and/or
286 fsync is not supported for this file, or if the file is not a
287 writable file descriptor. */
288 static int
289 dosync (int fd, char const *qname)
291 int err;
293 #if HAVE_FDATASYNC
294 if (fdatasync (fd) == 0)
295 return 0;
296 err = errno;
297 if (err != EINVAL && err != EBADF)
299 error (0, err, _("%s: fdatasync failed"), qname);
300 errno = err;
301 return -1;
303 #endif
305 if (fsync (fd) == 0)
306 return 0;
307 err = errno;
308 if (err != EINVAL && err != EBADF)
310 error (0, err, _("%s: fsync failed"), qname);
311 errno = err;
312 return -1;
315 sync ();
316 return 0;
319 /* Turn on or off direct I/O mode for file descriptor FD, if possible.
320 Try to turn it on if ENABLE is true. Otherwise, try to turn it off. */
321 static void
322 direct_mode (int fd, bool enable)
324 if (O_DIRECT)
326 int fd_flags = fcntl (fd, F_GETFL);
327 if (0 < fd_flags)
329 int new_flags = (enable
330 ? (fd_flags | O_DIRECT)
331 : (fd_flags & ~O_DIRECT));
332 if (new_flags != fd_flags)
333 fcntl (fd, F_SETFL, new_flags);
337 #if HAVE_DIRECTIO && defined DIRECTIO_ON && defined DIRECTIO_OFF
338 /* This is Solaris-specific. See the following for details:
339 http://docs.sun.com/db/doc/816-0213/6m6ne37so?q=directio&a=view */
340 directio (fd, enable ? DIRECTIO_ON : DIRECTIO_OFF);
341 #endif
345 * Do pass number k of n, writing "size" bytes of the given pattern "type"
346 * to the file descriptor fd. Qname, k and n are passed in only for verbose
347 * progress message purposes. If n == 0, no progress messages are printed.
349 * If *sizep == -1, the size is unknown, and it will be filled in as soon
350 * as writing fails.
352 * Return 1 on write error, -1 on other error, 0 on success.
354 static int
355 dopass (int fd, char const *qname, off_t *sizep, int type,
356 struct randread_source *s, unsigned long int k, unsigned long int n)
358 off_t size = *sizep;
359 off_t offset; /* Current file posiiton */
360 time_t thresh IF_LINT (= 0); /* Time to maybe print next status update */
361 time_t now = 0; /* Current time */
362 size_t lim; /* Amount of data to try writing */
363 size_t soff; /* Offset into buffer for next write */
364 ssize_t ssize; /* Return value from write */
366 /* Fill pattern buffer. Aligning it to a 32-bit boundary speeds up randread
367 in some cases. */
368 typedef uint32_t fill_pattern_buffer[3 * 1024];
369 union
371 fill_pattern_buffer buffer;
372 char c[sizeof (fill_pattern_buffer)];
373 unsigned char u[sizeof (fill_pattern_buffer)];
374 } r;
376 off_t sizeof_r = sizeof r;
377 char pass_string[PASS_NAME_SIZE]; /* Name of current pass */
378 bool write_error = false;
379 bool first_write = true;
381 /* Printable previous offset into the file */
382 char previous_offset_buf[LONGEST_HUMAN_READABLE + 1];
383 char const *previous_human_offset IF_LINT (= 0);
385 if (lseek (fd, 0, SEEK_SET) == -1)
387 error (0, errno, _("%s: cannot rewind"), qname);
388 return -1;
391 /* Constant fill patterns need only be set up once. */
392 if (type >= 0)
394 lim = (0 <= size && size < sizeof_r ? size : sizeof r);
395 fillpattern (type, r.u, lim);
396 passname (r.u, pass_string);
398 else
400 passname (0, pass_string);
403 /* Set position if first status update */
404 if (n)
406 error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
407 thresh = time (NULL) + VERBOSE_UPDATE;
408 previous_human_offset = "";
411 offset = 0;
412 for (;;)
414 /* How much to write this time? */
415 lim = sizeof r;
416 if (0 <= size && size - offset < sizeof_r)
418 if (size < offset)
419 break;
420 lim = size - offset;
421 if (!lim)
422 break;
424 if (type < 0)
425 randread (s, &r, lim);
426 /* Loop to retry partial writes. */
427 for (soff = 0; soff < lim; soff += ssize, first_write = false)
429 ssize = write (fd, r.c + soff, lim - soff);
430 if (ssize <= 0)
432 if (size < 0 && (ssize == 0 || errno == ENOSPC))
434 /* Ah, we have found the end of the file */
435 *sizep = size = offset + soff;
436 break;
438 else
440 int errnum = errno;
441 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
443 /* If the first write of the first pass for a given file
444 has just failed with EINVAL, turn off direct mode I/O
445 and try again. This works around a bug in linux-2.4
446 whereby opening with O_DIRECT would succeed for some
447 file system types (e.g., ext3), but any attempt to
448 access a file through the resulting descriptor would
449 fail with EINVAL. */
450 if (k == 1 && first_write && errno == EINVAL)
452 direct_mode (fd, false);
453 ssize = 0;
454 continue;
456 error (0, errnum, _("%s: error writing at offset %s"),
457 qname, umaxtostr (offset + soff, buf));
459 /* 'shred' is often used on bad media, before throwing it
460 out. Thus, it shouldn't give up on bad blocks. This
461 code works because lim is always a multiple of
462 SECTOR_SIZE, except at the end. */
463 verify (sizeof r % SECTOR_SIZE == 0);
464 if (errnum == EIO && 0 <= size && (soff | SECTOR_MASK) < lim)
466 size_t soff1 = (soff | SECTOR_MASK) + 1;
467 if (lseek (fd, offset + soff1, SEEK_SET) != -1)
469 /* Arrange to skip this block. */
470 ssize = soff1 - soff;
471 write_error = true;
472 continue;
474 error (0, errno, _("%s: lseek failed"), qname);
476 return -1;
481 /* Okay, we have written "soff" bytes. */
483 if (offset + soff < offset)
485 error (0, 0, _("%s: file too large"), qname);
486 return -1;
489 offset += soff;
491 /* Time to print progress? */
492 if (n
493 && ((offset == size && *previous_human_offset)
494 || thresh <= (now = time (NULL))))
496 char offset_buf[LONGEST_HUMAN_READABLE + 1];
497 char size_buf[LONGEST_HUMAN_READABLE + 1];
498 int human_progress_opts = (human_autoscale | human_SI
499 | human_base_1024 | human_B);
500 char const *human_offset
501 = human_readable (offset, offset_buf,
502 human_floor | human_progress_opts, 1, 1);
504 if (offset == size
505 || !STREQ (previous_human_offset, human_offset))
507 if (size < 0)
508 error (0, 0, _("%s: pass %lu/%lu (%s)...%s"),
509 qname, k, n, pass_string, human_offset);
510 else
512 uintmax_t off = offset;
513 int percent = (size == 0
514 ? 100
515 : (off <= TYPE_MAXIMUM (uintmax_t) / 100
516 ? off * 100 / size
517 : off / (size / 100)));
518 char const *human_size
519 = human_readable (size, size_buf,
520 human_ceiling | human_progress_opts,
521 1, 1);
522 if (offset == size)
523 human_offset = human_size;
524 error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s %d%%"),
525 qname, k, n, pass_string, human_offset, human_size,
526 percent);
529 strcpy (previous_offset_buf, human_offset);
530 previous_human_offset = previous_offset_buf;
531 thresh = now + VERBOSE_UPDATE;
534 * Force periodic syncs to keep displayed progress accurate
535 * FIXME: Should these be present even if -v is not enabled,
536 * to keep the buffer cache from filling with dirty pages?
537 * It's a common problem with programs that do lots of writes,
538 * like mkfs.
540 if (dosync (fd, qname) != 0)
542 if (errno != EIO)
543 return -1;
544 write_error = true;
550 /* Force what we just wrote to hit the media. */
551 if (dosync (fd, qname) != 0)
553 if (errno != EIO)
554 return -1;
555 write_error = true;
558 return write_error;
562 * The passes start and end with a random pass, and the passes in between
563 * are done in random order. The idea is to deprive someone trying to
564 * reverse the process of knowledge of the overwrite patterns, so they
565 * have the additional step of figuring out what was done to the disk
566 * before they can try to reverse or cancel it.
568 * First, all possible 1-bit patterns. There are two of them.
569 * Then, all possible 2-bit patterns. There are four, but the two
570 * which are also 1-bit patterns can be omitted.
571 * Then, all possible 3-bit patterns. Likewise, 8-2 = 6.
572 * Then, all possible 4-bit patterns. 16-4 = 12.
574 * The basic passes are:
575 * 1-bit: 0x000, 0xFFF
576 * 2-bit: 0x555, 0xAAA
577 * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
578 * 100100100100 110110110110
579 * 9 2 4 D B 6
580 * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
581 * 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
582 * Adding three random passes at the beginning, middle and end
583 * produces the default 25-pass structure.
585 * The next extension would be to 5-bit and 6-bit patterns.
586 * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
587 * 6-bit patterns, so they would increase the time required
588 * significantly. 4-bit patterns are enough for most purposes.
590 * The main gotcha is that this would require a trickier encoding,
591 * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
592 * lcm(2,3,4,5) = 60 bits is not.
594 * One extension that is included is to complement the first bit in each
595 * 512-byte block, to alter the phase of the encoded data in the more
596 * complex encodings. This doesn't apply to MFM, so the 1-bit patterns
597 * are considered part of the 3-bit ones and the 2-bit patterns are
598 * considered part of the 4-bit patterns.
601 * How does the generalization to variable numbers of passes work?
603 * Here's how...
604 * Have an ordered list of groups of passes. Each group is a set.
605 * Take as many groups as will fit, plus a random subset of the
606 * last partial group, and place them into the passes list.
607 * Then shuffle the passes list into random order and use that.
609 * One extra detail: if we can't include a large enough fraction of the
610 * last group to be interesting, then just substitute random passes.
612 * If you want more passes than the entire list of groups can
613 * provide, just start repeating from the beginning of the list.
615 static int const
616 patterns[] =
618 -2, /* 2 random passes */
619 2, 0x000, 0xFFF, /* 1-bit */
620 2, 0x555, 0xAAA, /* 2-bit */
621 -1, /* 1 random pass */
622 6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6, /* 3-bit */
623 12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
624 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */
625 -1, /* 1 random pass */
626 /* The following patterns have the frst bit per block flipped */
627 8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
628 14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
629 0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
630 -1, /* 1 random pass */
631 0 /* End */
635 * Generate a random wiping pass pattern with num passes.
636 * This is a two-stage process. First, the passes to include
637 * are chosen, and then they are shuffled into the desired
638 * order.
640 static void
641 genpattern (int *dest, size_t num, struct randint_source *s)
643 size_t randpasses;
644 int const *p;
645 int *d;
646 size_t n;
647 size_t accum, top, swap;
648 int k;
650 if (!num)
651 return;
653 /* Stage 1: choose the passes to use */
654 p = patterns;
655 randpasses = 0;
656 d = dest; /* Destination for generated pass list */
657 n = num; /* Passes remaining to fill */
659 for (;;)
661 k = *p++; /* Block descriptor word */
662 if (!k)
663 { /* Loop back to the beginning */
664 p = patterns;
666 else if (k < 0)
667 { /* -k random passes */
668 k = -k;
669 if ((size_t) k >= n)
671 randpasses += n;
672 n = 0;
673 break;
675 randpasses += k;
676 n -= k;
678 else if ((size_t) k <= n)
679 { /* Full block of patterns */
680 memcpy (d, p, k * sizeof (int));
681 p += k;
682 d += k;
683 n -= k;
685 else if (n < 2 || 3 * n < (size_t) k)
686 { /* Finish with random */
687 randpasses += n;
688 break;
690 else
691 { /* Pad out with k of the n available */
694 if (n == (size_t) k || randint_choose (s, k) < n)
696 *d++ = *p;
697 n--;
699 p++;
701 while (n);
702 break;
705 top = num - randpasses; /* Top of initialized data */
706 /* assert (d == dest+top); */
709 * We now have fixed patterns in the dest buffer up to
710 * "top", and we need to scramble them, with "randpasses"
711 * random passes evenly spaced among them.
713 * We want one at the beginning, one at the end, and
714 * evenly spaced in between. To do this, we basically
715 * use Bresenham's line draw (a.k.a DDA) algorithm
716 * to draw a line with slope (randpasses-1)/(num-1).
717 * (We use a positive accumulator and count down to
718 * do this.)
720 * So for each desired output value, we do the following:
721 * - If it should be a random pass, copy the pass type
722 * to top++, out of the way of the other passes, and
723 * set the current pass to -1 (random).
724 * - If it should be a normal pattern pass, choose an
725 * entry at random between here and top-1 (inclusive)
726 * and swap the current entry with that one.
728 randpasses--; /* To speed up later math */
729 accum = randpasses; /* Bresenham DDA accumulator */
730 for (n = 0; n < num; n++)
732 if (accum <= randpasses)
734 accum += num - 1;
735 dest[top++] = dest[n];
736 dest[n] = -1;
738 else
740 swap = n + randint_choose (s, top - n);
741 k = dest[n];
742 dest[n] = dest[swap];
743 dest[swap] = k;
745 accum -= randpasses;
747 /* assert (top == num); */
751 * The core routine to actually do the work. This overwrites the first
752 * size bytes of the given fd. Return true if successful.
754 static bool
755 do_wipefd (int fd, char const *qname, struct randint_source *s,
756 struct Options const *flags)
758 size_t i;
759 struct stat st;
760 off_t size; /* Size to write, size to read */
761 unsigned long int n; /* Number of passes for printing purposes */
762 int *passarray;
763 bool ok = true;
764 struct randread_source *rs;
766 n = 0; /* dopass takes n -- 0 to mean "don't print progress" */
767 if (flags->verbose)
768 n = flags->n_iterations + flags->zero_fill;
770 if (fstat (fd, &st))
772 error (0, errno, _("%s: fstat failed"), qname);
773 return false;
776 /* If we know that we can't possibly shred the file, give up now.
777 Otherwise, we may go into a infinite loop writing data before we
778 find that we can't rewind the device. */
779 if ((S_ISCHR (st.st_mode) && isatty (fd))
780 || S_ISFIFO (st.st_mode)
781 || S_ISSOCK (st.st_mode))
783 error (0, 0, _("%s: invalid file type"), qname);
784 return false;
787 direct_mode (fd, true);
789 /* Allocate pass array */
790 passarray = xnmalloc (flags->n_iterations, sizeof *passarray);
792 size = flags->size;
793 if (size == -1)
795 /* Accept a length of zero only if it's a regular file.
796 For any other type of file, try to get the size another way. */
797 if (S_ISREG (st.st_mode))
799 size = st.st_size;
800 if (size < 0)
802 error (0, 0, _("%s: file has negative size"), qname);
803 return false;
806 else
808 size = lseek (fd, 0, SEEK_END);
809 if (size <= 0)
811 /* We are unable to determine the length, up front.
812 Let dopass do that as part of its first iteration. */
813 size = -1;
817 /* Allow `rounding up' only for regular files. */
818 if (0 <= size && !(flags->exact) && S_ISREG (st.st_mode))
820 size += ST_BLKSIZE (st) - 1 - (size - 1) % ST_BLKSIZE (st);
822 /* If in rounding up, we've just overflowed, use the maximum. */
823 if (size < 0)
824 size = TYPE_MAXIMUM (off_t);
828 /* Schedule the passes in random order. */
829 genpattern (passarray, flags->n_iterations, s);
831 rs = randint_get_source (s);
833 /* Do the work */
834 for (i = 0; i < flags->n_iterations; i++)
836 int err = dopass (fd, qname, &size, passarray[i], rs, i + 1, n);
837 if (err)
839 if (err < 0)
841 memset (passarray, 0, flags->n_iterations * sizeof (int));
842 free (passarray);
843 return false;
845 ok = false;
849 memset (passarray, 0, flags->n_iterations * sizeof (int));
850 free (passarray);
852 if (flags->zero_fill)
854 int err = dopass (fd, qname, &size, 0, rs, flags->n_iterations + 1, n);
855 if (err)
857 if (err < 0)
858 return false;
859 ok = false;
863 /* Okay, now deallocate the data. The effect of ftruncate on
864 non-regular files is unspecified, so don't worry about any
865 errors reported for them. */
866 if (flags->remove_file && ftruncate (fd, 0) != 0
867 && S_ISREG (st.st_mode))
869 error (0, errno, _("%s: error truncating"), qname);
870 return false;
873 return ok;
876 /* A wrapper with a little more checking for fds on the command line */
877 static bool
878 wipefd (int fd, char const *qname, struct randint_source *s,
879 struct Options const *flags)
881 int fd_flags = fcntl (fd, F_GETFL);
883 if (fd_flags < 0)
885 error (0, errno, _("%s: fcntl failed"), qname);
886 return false;
888 if (fd_flags & O_APPEND)
890 error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
891 return false;
893 return do_wipefd (fd, qname, s, flags);
896 /* --- Name-wiping code --- */
898 /* Characters allowed in a file name - a safe universal set. */
899 static char const nameset[] =
900 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
902 /* Increment NAME (with LEN bytes). NAME must be a big-endian base N
903 number with the digits taken from nameset. Return true if
904 successful if not (because NAME already has the greatest possible
905 value. */
907 static bool
908 incname (char *name, size_t len)
910 while (len--)
912 char const *p = strchr (nameset, name[len]);
914 /* If this character has a successor, use it. */
915 if (p[1])
917 name[len] = p[1];
918 return true;
921 /* Otherwise, set this digit to 0 and increment the prefix. */
922 name[len] = nameset[0];
925 return false;
929 * Repeatedly rename a file with shorter and shorter names,
930 * to obliterate all traces of the file name on any system that
931 * adds a trailing delimiter to on-disk file names and reuses
932 * the same directory slot. Finally, unlink it.
933 * The passed-in filename is modified in place to the new filename.
934 * (Which is unlinked if this function succeeds, but is still present if
935 * it fails for some reason.)
937 * The main loop is written carefully to not get stuck if all possible
938 * names of a given length are occupied. It counts down the length from
939 * the original to 0. While the length is non-zero, it tries to find an
940 * unused file name of the given length. It continues until either the
941 * name is available and the rename succeeds, or it runs out of names
942 * to try (incname wraps and returns 1). Finally, it unlinks the file.
944 * The unlink is Unix-specific, as ANSI-standard remove has more
945 * portability problems with C libraries making it "safe". rename
946 * is ANSI-standard.
948 * To force the directory data out, we try to open the directory and
949 * invoke fdatasync and/or fsync on it. This is non-standard, so don't
950 * insist that it works: just fall back to a global sync in that case.
951 * This is fairly significantly Unix-specific. Of course, on any
952 * file system with synchronous metadata updates, this is unnecessary.
954 static bool
955 wipename (char *oldname, char const *qoldname, struct Options const *flags)
957 char *newname = xstrdup (oldname);
958 char *base = last_component (newname);
959 size_t len = base_len (base);
960 char *dir = dir_name (newname);
961 char *qdir = xstrdup (quotearg_colon (dir));
962 bool first = true;
963 bool ok = true;
965 int dir_fd = open (dir, O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK);
967 if (flags->verbose)
968 error (0, 0, _("%s: removing"), qoldname);
970 while (len)
972 memset (base, nameset[0], len);
973 base[len] = 0;
976 struct stat st;
977 if (lstat (newname, &st) < 0)
979 if (rename (oldname, newname) == 0)
981 if (0 <= dir_fd && dosync (dir_fd, qdir) != 0)
982 ok = false;
983 if (flags->verbose)
986 * People seem to understand this better than talking
987 * about renaming oldname. newname doesn't need
988 * quoting because we picked it. oldname needs to
989 * be quoted only the first time.
991 char const *old = (first ? qoldname : oldname);
992 error (0, 0, _("%s: renamed to %s"), old, newname);
993 first = false;
995 memcpy (oldname + (base - newname), base, len + 1);
996 break;
998 else
1000 /* The rename failed: give up on this length. */
1001 break;
1004 else
1006 /* newname exists, so increment BASE so we use another */
1009 while (incname (base, len));
1010 len--;
1012 if (unlink (oldname) != 0)
1014 error (0, errno, _("%s: failed to remove"), qoldname);
1015 ok = false;
1017 else if (flags->verbose)
1018 error (0, 0, _("%s: removed"), qoldname);
1019 if (0 <= dir_fd)
1021 if (dosync (dir_fd, qdir) != 0)
1022 ok = false;
1023 if (close (dir_fd) != 0)
1025 error (0, errno, _("%s: failed to close"), qdir);
1026 ok = false;
1029 free (newname);
1030 free (dir);
1031 free (qdir);
1032 return ok;
1036 * Finally, the function that actually takes a filename and grinds
1037 * it into hamburger.
1039 * FIXME
1040 * Detail to note: since we do not restore errno to EACCES after
1041 * a failed chmod, we end up printing the error code from the chmod.
1042 * This is actually the error that stopped us from proceeding, so
1043 * it's arguably the right one, and in practice it'll be either EACCES
1044 * again or EPERM, which both give similar error messages.
1045 * Does anyone disagree?
1047 static bool
1048 wipefile (char *name, char const *qname,
1049 struct randint_source *s, struct Options const *flags)
1051 bool ok;
1052 int fd;
1054 fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1055 if (fd < 0
1056 && (errno == EACCES && flags->force)
1057 && chmod (name, S_IWUSR) == 0)
1058 fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1059 if (fd < 0)
1061 error (0, errno, _("%s: failed to open for writing"), qname);
1062 return false;
1065 ok = do_wipefd (fd, qname, s, flags);
1066 if (close (fd) != 0)
1068 error (0, errno, _("%s: failed to close"), qname);
1069 ok = false;
1071 if (ok && flags->remove_file)
1072 ok = wipename (name, qname, flags);
1073 return ok;
1077 /* Buffers for random data. */
1078 static struct randint_source *randint_source;
1080 /* Just on general principles, wipe buffers containing information
1081 that may be related to the possibly-pseudorandom values used during
1082 shredding. */
1083 static void
1084 clear_random_data (void)
1086 randint_all_free (randint_source);
1091 main (int argc, char **argv)
1093 bool ok = true;
1094 struct Options flags = { 0, };
1095 char **file;
1096 int n_files;
1097 int c;
1098 int i;
1099 char const *random_source = NULL;
1101 initialize_main (&argc, &argv);
1102 program_name = argv[0];
1103 setlocale (LC_ALL, "");
1104 bindtextdomain (PACKAGE, LOCALEDIR);
1105 textdomain (PACKAGE);
1107 atexit (close_stdout);
1109 flags.n_iterations = DEFAULT_PASSES;
1110 flags.size = -1;
1112 while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1114 switch (c)
1116 case 'f':
1117 flags.force = true;
1118 break;
1120 case 'n':
1122 uintmax_t tmp;
1123 if (xstrtoumax (optarg, NULL, 10, &tmp, NULL) != LONGINT_OK
1124 || MIN (UINT32_MAX, SIZE_MAX / sizeof (int)) < tmp)
1126 error (EXIT_FAILURE, 0, _("%s: invalid number of passes"),
1127 quotearg_colon (optarg));
1129 flags.n_iterations = tmp;
1131 break;
1133 case RANDOM_SOURCE_OPTION:
1134 if (random_source && !STREQ (random_source, optarg))
1135 error (EXIT_FAILURE, 0, _("multiple random sources specified"));
1136 random_source = optarg;
1137 break;
1139 case 'u':
1140 flags.remove_file = true;
1141 break;
1143 case 's':
1145 uintmax_t tmp;
1146 if (xstrtoumax (optarg, NULL, 0, &tmp, "cbBkKMGTPEZY0")
1147 != LONGINT_OK)
1149 error (EXIT_FAILURE, 0, _("%s: invalid file size"),
1150 quotearg_colon (optarg));
1152 flags.size = tmp;
1154 break;
1156 case 'v':
1157 flags.verbose = true;
1158 break;
1160 case 'x':
1161 flags.exact = true;
1162 break;
1164 case 'z':
1165 flags.zero_fill = true;
1166 break;
1168 case_GETOPT_HELP_CHAR;
1170 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1172 default:
1173 usage (EXIT_FAILURE);
1177 file = argv + optind;
1178 n_files = argc - optind;
1180 if (n_files == 0)
1182 error (0, 0, _("missing file operand"));
1183 usage (EXIT_FAILURE);
1186 randint_source = randint_all_new (random_source, SIZE_MAX);
1187 if (! randint_source)
1188 error (EXIT_FAILURE, errno, "%s", quotearg_colon (random_source));
1189 atexit (clear_random_data);
1191 for (i = 0; i < n_files; i++)
1193 char *qname = xstrdup (quotearg_colon (file[i]));
1194 if (STREQ (file[i], "-"))
1196 ok &= wipefd (STDOUT_FILENO, qname, randint_source, &flags);
1198 else
1200 /* Plain filename - Note that this overwrites *argv! */
1201 ok &= wipefile (file[i], qname, randint_source, &flags);
1203 free (qname);
1206 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
1209 * vim:sw=2:sts=2: