*** empty log message ***
[coreutils.git] / src / shred.c
blob21469176ee4816f4c7570dc44f101610eac6dee4
1 /* TODO:
2 - use consistent non-capitalization in error messages
3 - add standard GNU copyleft comment
5 - Add -r/-R/--recursive
6 - Add -i/--interactive
7 - Reserve -d
8 - Add -L
9 - Deal with the amazing variety of gettimeofday() implementation bugs.
10 (Some systems use a one-arg form; still others insist that the timezone
11 either be NULL or be non-NULL. Whee.)
12 - Add an unlink-all option to emulate rm.
16 * shred.c - by Colin Plumb.
18 * Do a securer overwrite of given files or devices, to make it harder
19 * for even very expensive hardware probing to recover the data.
21 * Although this process is also known as "wiping", I prefer the longer
22 * name both because I think it is more evocative of what is happening and
23 * because a longer name conveys a more appropriate sense of deliberateness.
25 * For the theory behind this, see "Secure Deletion of Data from Magnetic
26 * and Solid-State Memory", on line at
27 * http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html
29 * Just for the record, reversing one or two passes of disk overwrite
30 * is not terribly difficult with hardware help. Hook up a good-quality
31 * digitizing oscilloscope to the output of the head preamplifier and copy
32 * the high-res digitized data to a computer for some off-line analysis.
33 * Read the "current" data and average all the pulses together to get an
34 * "average" pulse on the disk. Subtract this average pulse from all of
35 * the actual pulses and you can clearly see the "echo" of the previous
36 * data on the disk.
38 * Real hard drives have to balance the cost of the media, the head,
39 * and the read circuitry. They use better-quality media than absolutely
40 * necessary to limit the cost of the read circuitry. By throwing that
41 * assumption out, and the assumption that you want the data processed
42 * as fast as the hard drive can spin, you can do better.
44 * If asked to wipe a file, this also unlinks it, renaming it to in a
45 * clever way to try to leave no trace of the original filename.
47 * Copyright 1997, 1998, 1999 Colin Plumb <colin@nyx.net>. This program
48 * may be freely distributed under the terms of the GNU GPL, the BSD license,
49 * or Larry Wall's "Artistic License" Even if you use the BSD license,
50 * which does not require it, I'd really like to get improvements back.
52 * The ISAAC code still bears some resemblance to the code written
53 * by Bob Jenkins, but he permits pretty unlimited use.
55 * This was inspired by a desire to improve on some code titled:
56 * Wipe V1.0-- Overwrite and delete files. S. 2/3/96
57 * but I've rewritten everything here so completely that no trace of
58 * the original remains.
60 * Thanks to:
61 * Bob Jenkins, for his good RNG work and patience with the FSF copyright
62 * paperwork.
63 * Jim Meyering, for his work merging this into the GNU fileutils while
64 * still letting me feel a sense of ownership and pride. Getting me to
65 * tolerate the GNU brace style was quite a feat of diplomacy.
66 * Paul Eggert, for lots of useful discussion and code. I disagree with
67 * an awful lot of his suggestions, but they're disagreements worth having.
69 * Things to think about:
70 * - Security: Is there any risk to the race
71 * between overwriting and unlinking a file? Will it do anything
72 * drastically bad if told to attack a named pipe or socket?
75 /* The official name of this program (e.g., no `g' prefix). */
76 #define PROGRAM_NAME "shred"
78 #define AUTHORS "Colin Plumb"
80 #if HAVE_CONFIG_H
81 # include <config.h>
82 #endif
84 #include <getopt.h>
85 #include <stdio.h>
86 #include <assert.h>
87 #include <setjmp.h>
88 #include <signal.h>
89 #include <sys/types.h>
91 #if HAVE_CONFIG_H
92 /* Default fileutils build */
93 # include "system.h"
94 # include "xstrtol.h"
95 # include "closeout.h"
96 # include "error.h"
97 # include "human.h"
98 # include "quotearg.h" /* For quotearg_colon */
99 # include "quote.h" /* For quotearg_colon */
100 # include "xalloc.h"
101 char *xstrdup PARAMS ((char const *));
103 #else /* !HAVE_CONFIG_H */
105 * Standalone build - this file compiles by itself without autoconf and
106 * the like. No i18n, and I still have to write a stub for getopt_long,
107 * but it's a lot less intertwingled than the usual GNU utilities.
110 # include <ctype.h> /* For isprint */
111 # include <string.h> /* For memcpy, strerror */
112 # include <limits.h> /* For ULONG_MAX etc. */
113 # include <stdlib.h> /* For strtoul, EXIT_FAILURE */
114 # include <errno.h>
115 # include <fcntl.h> /* For O_RDONLY etc. */
116 # include <unistd.h> /* For getpid, etc. */
117 # include <sys/time.h> /* For struct timeval */
118 # include <sys/stat.h> /* For struct stat */
120 # define PACKAGE "standalone"
121 # define VERSION "2.0" /* Kind of arbitrary... */
123 # if __GNUC__ < 2 || __GNUC__ == 2 && __GNUC_MINOR__ < 5 || __STRICT_ANSI__
124 # define attribute(x)
125 # else
126 # define attribute __attribute__
127 # if __GNUC__ == 2 && __GNUC_MINOR__ < 7
128 /* The __-protected forms were introduced in GCC 2.6.4 */
129 # define __format__ format
130 # define __printf__ printf
131 # endif
132 # endif
134 /* Reasonable default assumptions for time-getting */
135 # ifndef HAVE_GETTIMEOFDAY
136 # define HAVE_GETTIMEOFDAY 1 /* Most systems have it these days */
137 # endif
139 # ifdef CLOCK_REALTIME
140 # ifndef HAVE_CLOCK_GETTIME
141 # define HAVE_CLOCK_GETTIME 1
142 # endif
143 # endif
145 # ifndef STDOUT_FILENO
146 # define STDOUT_FILENO 1
147 # endif
149 # define RETSIGTYPE int
151 # ifndef S_IWUSR
152 # ifdef S_IWRITE
153 # define S_IWUSR S_IWRITE
154 # else
155 # define S_IWUSR 0200
156 # endif
157 # endif
159 /* POSIX doesn't require st_blksize, and 65536 is a reasonable
160 upper bound for existing filesystem practice. */
161 # define ST_BLKSIZE(Stat) 65536
163 # define uintmax_t unsigned long
165 /* Variant human-readable function that ignores last two args */
166 # define human_readable(v, b, f, t) (sprintf (b, "%lu", (unsigned long) v), b)
167 # define LONGEST_HUMAN_READABLE (sizeof (uintmax_t) * CHAR_BIT / 3)
169 /* Variant convert-to-uintmax_t function that accepts metric suffixes */
170 enum strtol_error
172 LONGINT_OK, LONGINT_INVALID, LONGINT_INVALID_SUFFIX_CHAR, LONGINT_OVERFLOW
174 static uintmax_t
175 xstrtoumax (char const *ptr, char const **end, int base, uintmax_t *res,
176 char const *valid_suffixes)
178 char *end_ptr;
179 char const *p;
180 static char const metric_suffixes[] = "kMGTPEZY";
181 int decimal_flag;
182 uintmax_t n;
183 char c;
185 errno = 0;
186 *res = n = strtoul (ptr, &end_ptr, base);
187 if (end)
188 *end = end_ptr;
189 if (errno)
190 return LONGINT_OVERFLOW;
191 if (ptr == end_ptr)
192 return LONGINT_INVALID;
193 c = *end_ptr;
194 if (!c)
195 return LONGINT_OK;
196 /* Now deal with metric-style suffixes */
197 if (valid_suffixes && !strchr (valid_suffixes, c))
198 return LONGINT_INVALID_SUFFIX_CHAR;
200 decimal_flag = 0;
201 switch (c)
203 case 'b':
204 if (n > ULONG_MAX/512)
205 return LONGINT_OVERFLOW;
206 n *= 512;
207 break;
209 case 'B':
210 if (n > ULONG_MAX/102412)
211 return LONGINT_OVERFLOW;
212 n *= 1024;
213 break;
215 case 'c':
216 break;
218 case 'K':
219 c = 'k';
220 goto def;
222 case 'm':
223 c = 'M';
224 /*FALLTHROUGH*/
225 def:default:
226 p = strchr (metric_suffixes, c);
227 if (!p)
228 return LONGINT_INVALID_SUFFIX_CHAR;
230 * If valid_suffixes contains '0', then xD (decimal) and xB (binary)
231 * are allowed as "supersuffixes". Binary is the default.
233 if (strchr (valid_suffixes, '0'))
235 if (end_ptr[1] == 'B')
236 end_ptr++;
237 else if (end_ptr[1] == 'D')
239 decimal_flag = 1;
240 end_ptr++;
243 /* Now do the scaling */
244 p++;
245 if (decimal_flag)
246 do {
247 if (n > ULONG_MAX/1000)
248 return LONGINT_OVERFLOW;
249 n *= 1000;
250 } while (--p > metric_suffixes);
251 else
252 do {
253 if (n > ULONG_MAX/1024)
254 return LONGINT_OVERFLOW;
255 n *= 1024;
256 } while (--p > metric_suffixes);
259 /* Final wrapup */
260 if (end)
261 *end = end_ptr+1; /* Extra suffix is allowed if it's expected */
262 else if (end_ptr[1])
263 return LONGINT_INVALID_SUFFIX_CHAR;
264 *res = n;
265 return LONGINT_OK;
268 /* Dummy i18n stubs */
269 # define _(x) x
270 # define N_(x) x
271 # define setlocale(x,y) (void) 0
272 # define bindtextdomain(x,y) (void) 0
273 # define textdomain(x) (void) 0
276 * Print a message with `fprintf (stderr, FORMAT, ...)';
277 * if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
278 * If STATUS is nonzero, terminate the program with `exit (STATUS)'.
280 static void error (int status, int errnum, const char *format, ...)
281 attribute ((__format__ (__printf__, 3, 4)));
283 extern char const *program_name;
284 static void
285 error (int status, int errnum, const char *format, ...)
287 va_list ap;
289 if (program_name)
291 fputs (program_name, stderr);
292 fputs (": ", stderr);
294 va_start (ap, format);
295 vfprintf (stderr, format, ap);
296 va_end (ap);
297 if (errnum)
299 fputs (": ", stderr);
300 fputs (strerror (errnum), stderr);
302 putc ('\n', stderr);
304 if (status)
305 exit (status);
309 * GNU programs actually check for failure closing standard output.
310 * This seems unnecessary, until your shell script starts hitting
311 * ENOSPC and doing bizarre things with zero-length files.
313 static void
314 close_stdout (void)
316 if (ferror (stdout))
317 error (EXIT_FAILURE, 0, _("write error"));
318 if (fclose (stdout) != 0)
319 error (EXIT_FAILURE, errno, _("write error"));
323 * Quote the argument (including colon characters) into the buffer.
324 * Return the buffer size used (including trailing null byte.)
325 * If this is larger than the bufsize, it is an estimate of the space
326 * needed.
328 static size_t
329 quotearg_colon_buf (char const *arg, char *buf, size_t bufsize)
331 /* Some systems don't have \a or \e, so this is ASCII-dependent */
332 static char const escaped[] = "\7\b\33\f\n\r\t\v";
333 static char const escapes[] = "abefnrtv";
334 int c;
335 size_t pos = 0;
336 char const *p;
338 while ((c = (unsigned char) *arg++) != 0)
340 if (isprint (c))
342 if (strchr ("\\:", c)) /* Anything else we should quote? */
343 if (pos++ < bufsize) *buf++ = '\\';
345 else
347 if (pos++ < bufsize) *buf++ = '\\';
348 p = strchr (escaped, c); /* c is never 0, so this is okay */
349 if (p)
351 c = escapes[p-escaped];
353 else
355 if ('0' <= *arg && *arg <= '9')
356 c += 256; /* Force 3-digit form if followed by a digit */
357 if (c > 077)
358 if (pos++ < bufsize) *buf++ = "0123"[c>>6 & 3];
359 if (c > 07)
360 if (pos++ < bufsize) *buf++ = "01234567"[c>>3 & 7];
361 c = "01234567"[c & 7];
364 if (pos++ < bufsize) *buf++ = c;
366 if (pos++ < bufsize) *buf++ = 0;
367 return pos;
370 /* Quote metacharacters in a filename */
371 char const *
372 quotearg_colon (char const *arg)
374 static char *buf = 0;
375 size_t bufsize = 0;
376 size_t newsize;
378 while ((newsize = quotearg_colon_buf (arg, buf, bufsize)) > bufsize)
380 buf = realloc (buf, newsize);
381 if (!buf)
382 error (EXIT_FAILURE, 0, _("memory exhausted"));
383 bufsize = newsize;
385 return buf;
388 void *
389 xmalloc (size_t n)
391 void *p = malloc (n);
392 if (!p)
393 error (EXIT_FAILURE, 0, _("memory exhausted"));
394 return p;
397 char *
398 xstrdup (char const *string)
400 return strcpy (xmalloc (strlen (string) + 1), string);
403 #endif /* ! HAVE_CONFIG_H */
405 #ifndef O_NOCTTY
406 # define O_NOCTTY 0 /* This is a very optional frill */
407 #endif
409 /* Some systems don't support some file types. */
410 #ifndef S_ISFIFO
411 # define S_ISFIFO(mode) 0
412 #endif
413 #ifndef S_ISLNK
414 # define S_ISLNK(mode) 0
415 #endif
416 #ifndef S_ISSOCK
417 # define S_ISSOCK(mode) 0
418 #endif
420 #define DEFAULT_PASSES 25 /* Default */
422 /* How often to update wiping display */
423 #define VERBOSE_UPDATE 150*1024
425 /* If positive, the units to use when printing sizes;
426 if negative, the human-readable base. */
427 #define OUTPUT_BLOCK_SIZE (-1024)
429 struct Options
431 int force; /* -f flag: chmod files if necessary */
432 size_t n_iterations; /* -n flag: Number of iterations */
433 off_t size; /* -s flag: size of file */
434 int remove_file; /* -u flag: remove file after shredding */
435 int verbose; /* -v flag: Print progress */
436 int exact; /* -x flag: Do not round up file size */
437 int zero_fill; /* -z flag: Add a final zero pass */
440 static struct option const long_opts[] =
442 {"exact", no_argument, NULL, 'x'},
443 {"force", no_argument, NULL, 'f'},
444 {"iterations", required_argument, NULL, 'n'},
445 {"size", required_argument, NULL, 's'},
446 {"remove", no_argument, NULL, 'u'},
447 {"verbose", no_argument, NULL, 'v'},
448 {"zero", required_argument, NULL, 'z'},
449 {GETOPT_HELP_OPTION_DECL},
450 {GETOPT_VERSION_OPTION_DECL},
451 {NULL, 0, NULL, 0}
454 /* Global variable for error printing purposes */
455 char const *program_name; /* Initialized before any possible use */
457 void
458 usage (int status)
460 if (status != 0)
461 fprintf (stderr, _("Try `%s --help' for more information.\n"),
462 program_name);
463 else
465 printf (_("Usage: %s [OPTIONS] FILE [...]\n"), program_name);
466 printf (_("\
467 Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\
468 for even very expensive hardware probing to recover the data.\n\
470 -f, --force change permissions to allow writing if necessary\n\
471 -n, --iterations=N Overwrite N times instead of the default (%d)\n\
472 -s, --size=N shred this many bytes (suffixes like k, M, G accepted)\n\
473 -u, --remove truncate and remove file after overwriting\n\
474 -v, --verbose show progress\n\
475 -x, --exact do not round file sizes up to the next full block\n\
476 -z, --zero add a final overwrite with zeros to hide shredding\n\
477 - shred standard output\n\
478 --help display this help and exit\n\
479 --version print version information and exit\n\
481 Delete FILE(s) if --remove (-u) is specified. The default is not to remove\n\
482 the files because it is common to operate on device files like /dev/hda,\n\
483 and those files usually should not be removed. When operating on regular\n\
484 files, most people use the --remove option.\n\
485 "), DEFAULT_PASSES);
486 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
488 exit (status);
491 #if ! HAVE_FDATASYNC
492 # define fdatasync(fd) -1
493 #endif
496 * --------------------------------------------------------------------
497 * Bob Jenkins' cryptographic random number generator, ISAAC.
498 * Hacked by Colin Plumb.
500 * We need a source of random numbers for some of the overwrite data.
501 * Cryptographically secure is desirable, but it's not life-or-death
502 * so I can be a little bit experimental in the choice of RNGs here.
504 * This generator is based somewhat on RC4, but has analysis
505 * (http://ourworld.compuserve.com/homepages/bob_jenkins/randomnu.htm)
506 * pointing to it actually being better. I like it because it's nice
507 * and fast, and because the author did good work analyzing it.
508 * --------------------------------------------------------------------
511 #if defined __STDC__ && __STDC__
512 # define UINT_MAX_32_BITS 4294967295U
513 #else
514 # define UINT_MAX_32_BITS 0xFFFFFFFF
515 #endif
517 #if ULONG_MAX == UINT_MAX_32_BITS
518 typedef unsigned long word32;
519 #else
520 # if UINT_MAX == UINT_MAX_32_BITS
521 typedef unsigned word32;
522 # else
523 # if USHRT_MAX == UINT_MAX_32_BITS
524 typedef unsigned short word32;
525 # else
526 # if UCHAR_MAX == UINT_MAX_32_BITS
527 typedef unsigned char word32;
528 # else
529 "No 32-bit type available!"
530 # endif
531 # endif
532 # endif
533 #endif
535 /* Size of the state tables to use. (You may change ISAAC_LOG) */
536 #define ISAAC_LOG 8
537 #define ISAAC_WORDS (1 << ISAAC_LOG)
538 #define ISAAC_BYTES (ISAAC_WORDS * sizeof (word32))
540 /* RNG state variables */
541 struct isaac_state
543 word32 mm[ISAAC_WORDS]; /* Main state array */
544 word32 iv[8]; /* Seeding initial vector */
545 word32 a, b, c; /* Extra index variables */
548 /* This index operation is more efficient on many processors */
549 #define ind(mm, x) \
550 (* (word32 *) ((char *) (mm) + ((x) & (ISAAC_WORDS - 1) * sizeof (word32))))
553 * The central step. This uses two temporaries, x and y. mm is the
554 * whole state array, while m is a pointer to the current word. off is
555 * the offset from m to the word ISAAC_WORDS/2 words away in the mm array,
556 * i.e. +/- ISAAC_WORDS/2.
558 #define isaac_step(mix, a, b, mm, m, off, r) \
560 a = ((a) ^ (mix)) + (m)[off], \
561 x = *(m), \
562 *(m) = y = ind (mm, x) + (a) + (b), \
563 *(r) = b = ind (mm, (y) >> ISAAC_LOG) + x \
567 * Refill the entire R array, and update S.
569 static void
570 isaac_refill (struct isaac_state *s, word32 r[/* ISAAC_WORDS */])
572 register word32 a, b; /* Caches of a and b */
573 register word32 x, y; /* Temps needed by isaac_step macro */
574 register word32 *m = s->mm; /* Pointer into state array */
576 a = s->a;
577 b = s->b + (++s->c);
581 isaac_step (a << 13, a, b, s->mm, m, ISAAC_WORDS / 2, r);
582 isaac_step (a >> 6, a, b, s->mm, m + 1, ISAAC_WORDS / 2, r + 1);
583 isaac_step (a << 2, a, b, s->mm, m + 2, ISAAC_WORDS / 2, r + 2);
584 isaac_step (a >> 16, a, b, s->mm, m + 3, ISAAC_WORDS / 2, r + 3);
585 r += 4;
587 while ((m += 4) < s->mm + ISAAC_WORDS / 2);
590 isaac_step (a << 13, a, b, s->mm, m, -ISAAC_WORDS / 2, r);
591 isaac_step (a >> 6, a, b, s->mm, m + 1, -ISAAC_WORDS / 2, r + 1);
592 isaac_step (a << 2, a, b, s->mm, m + 2, -ISAAC_WORDS / 2, r + 2);
593 isaac_step (a >> 16, a, b, s->mm, m + 3, -ISAAC_WORDS / 2, r + 3);
594 r += 4;
596 while ((m += 4) < s->mm + ISAAC_WORDS);
597 s->a = a;
598 s->b = b;
602 * The basic seed-scrambling step for initialization, based on Bob
603 * Jenkins' 256-bit hash.
605 #define mix(a,b,c,d,e,f,g,h) \
606 ( a ^= b << 11, d += a, \
607 b += c, b ^= c >> 2, e += b, \
608 c += d, c ^= d << 8, f += c, \
609 d += e, d ^= e >> 16, g += d, \
610 e += f, e ^= f << 10, h += e, \
611 f += g, f ^= g >> 4, a += f, \
612 g += h, g ^= h << 8, b += g, \
613 h += a, h ^= a >> 9, c += h, \
614 a += b )
616 /* The basic ISAAC initialization pass. */
617 static void
618 isaac_mix (struct isaac_state *s, word32 const seed[/* ISAAC_WORDS */])
620 int i;
621 word32 a = s->iv[0];
622 word32 b = s->iv[1];
623 word32 c = s->iv[2];
624 word32 d = s->iv[3];
625 word32 e = s->iv[4];
626 word32 f = s->iv[5];
627 word32 g = s->iv[6];
628 word32 h = s->iv[7];
630 for (i = 0; i < ISAAC_WORDS; i += 8)
632 a += seed[i];
633 b += seed[i + 1];
634 c += seed[i + 2];
635 d += seed[i + 3];
636 e += seed[i + 4];
637 f += seed[i + 5];
638 g += seed[i + 6];
639 h += seed[i + 7];
641 mix (a, b, c, d, e, f, g, h);
643 s->mm[i] = a;
644 s->mm[i + 1] = b;
645 s->mm[i + 2] = c;
646 s->mm[i + 3] = d;
647 s->mm[i + 4] = e;
648 s->mm[i + 5] = f;
649 s->mm[i + 6] = g;
650 s->mm[i + 7] = h;
653 s->iv[0] = a;
654 s->iv[1] = b;
655 s->iv[2] = c;
656 s->iv[3] = d;
657 s->iv[4] = e;
658 s->iv[5] = f;
659 s->iv[6] = g;
660 s->iv[7] = h;
663 #if 0 /* Provided for reference only; not used in this code */
665 * Initialize the ISAAC RNG with the given seed material.
666 * Its size MUST be a multiple of ISAAC_BYTES, and may be
667 * stored in the s->mm array.
669 * This is a generalization of the original ISAAC initialization code
670 * to support larger seed sizes. For seed sizes of 0 and ISAAC_BYTES,
671 * it is identical.
673 static void
674 isaac_init (struct isaac_state *s, word32 const *seed, size_t seedsize)
676 static word32 const iv[8] =
678 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
679 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119};
680 int i;
682 # if 0
683 /* The initialization of iv is a precomputed form of: */
684 for (i = 0; i < 7; i++)
685 iv[i] = 0x9e3779b9; /* the golden ratio */
686 for (i = 0; i < 4; ++i) /* scramble it */
687 mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
688 # endif
689 s->a = s->b = s->c = 0;
691 for (i = 0; i < 8; i++)
692 s->iv[i] = iv[i];
694 if (seedsize)
696 /* First pass (as in reference ISAAC code) */
697 isaac_mix (s, seed);
698 /* Second and subsequent passes (extension to ISAAC) */
699 while (seedsize -= ISAAC_BYTES)
701 seed += ISAAC_WORDS;
702 for (i = 0; i < ISAAC_WORDS; i++)
703 s->mm[i] += seed[i];
704 isaac_mix (s, s->mm);
707 else
709 /* The no seed case (as in reference ISAAC code) */
710 for (i = 0; i < ISAAC_WORDS; i++)
711 s->mm[i] = 0;
714 /* Final pass */
715 isaac_mix (s, s->mm);
717 #endif
719 /* Start seeding an ISAAC structire */
720 static void
721 isaac_seed_start (struct isaac_state *s)
723 static word32 const iv[8] =
725 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
726 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119
728 int i;
730 #if 0
731 /* The initialization of iv is a precomputed form of: */
732 for (i = 0; i < 7; i++)
733 iv[i] = 0x9e3779b9; /* the golden ratio */
734 for (i = 0; i < 4; ++i) /* scramble it */
735 mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
736 #endif
737 for (i = 0; i < 8; i++)
738 s->iv[i] = iv[i];
739 /* We could initialize s->mm to zero, but why bother? */
741 /* s->c gets used for a data pointer during the seeding phase */
742 s->a = s->b = s->c = 0;
745 /* Add a buffer of seed material */
746 static void
747 isaac_seed_data (struct isaac_state *s, void const *buf, size_t size)
749 unsigned char *p;
750 size_t avail;
751 size_t i;
753 avail = sizeof s->mm - (size_t) s->c; /* s->c is used as a write pointer */
755 /* Do any full buffers that are necessary */
756 while (size > avail)
758 p = (unsigned char *) s->mm + s->c;
759 for (i = 0; i < avail; i++)
760 p[i] ^= ((unsigned char const *) buf)[i];
761 buf = (char const *) buf + avail;
762 size -= avail;
763 isaac_mix (s, s->mm);
764 s->c = 0;
765 avail = sizeof s->mm;
768 /* And the final partial block */
769 p = (unsigned char *) s->mm + s->c;
770 for (i = 0; i < size; i++)
771 p[i] ^= ((unsigned char const *) buf)[i];
772 s->c = (word32) size;
776 /* End of seeding phase; get everything ready to produce output. */
777 static void
778 isaac_seed_finish (struct isaac_state *s)
780 isaac_mix (s, s->mm);
781 isaac_mix (s, s->mm);
782 /* Now reinitialize c to start things off right */
783 s->c = 0;
785 #define ISAAC_SEED(s,x) isaac_seed_data (s, &(x), sizeof (x))
788 #if __GNUC__ >= 2 && (__i386__ || __alpha__)
790 * Many processors have very-high-resolution timer registers,
791 * The timer registers can be made inaccessible, so we have to deal with the
792 * possibility of SIGILL while we're working.
794 static jmp_buf env;
795 static RETSIGTYPE
796 sigill_handler (int signum)
798 (void) signum;
799 longjmp (env, 1); /* Trivial, just return an indication that it happened */
802 static void
803 isaac_seed_machdep (struct isaac_state *s)
805 RETSIGTYPE (*oldhandler) (int);
807 /* This is how one does try/except in C */
808 oldhandler = signal (SIGILL, sigill_handler);
809 if (setjmp (env)) /* ANSI: Must be entire controlling expression */
811 (void) signal (SIGILL, oldhandler);
813 else
815 # if __i386__
816 word32 t[2];
817 __asm__ __volatile__ ("rdtsc" : "=a" (t[0]), "=d" (t[1]));
818 # endif
819 # if __alpha__
820 unsigned long t;
821 __asm__ __volatile__ ("rpcc %0" : "=r" (t));
822 # endif
823 # if _ARCH_PPC
824 /* Code not used because this instruction is available only on first-
825 generation PPCs and evokes a SIGBUS on some Linux 2.4 kernels. */
826 word32 t;
827 __asm__ __volatile__ ("mfspr %0,22" : "=r" (t));
828 # endif
829 # if __mips
830 /* Code not used because this is not accessible from userland */
831 word32 t;
832 __asm__ __volatile__ ("mfc0\t%0,$9" : "=r" (t));
833 # endif
834 # if __sparc__
835 /* This doesn't compile on all platforms yet. How to fix? */
836 unsigned long t;
837 __asm__ __volatile__ ("rd %%tick, %0" : "=r" (t));
838 # endif
839 (void) signal (SIGILL, oldhandler);
840 isaac_seed_data (s, &t, sizeof t);
844 #else /* !(__i386__ || __alpha__) */
846 /* Do-nothing stub */
847 # define isaac_seed_machdep(s) (void) 0
849 #endif /* !(__i386__ || __alpha__) */
853 * Get seed material. 16 bytes (128 bits) is plenty, but if we have
854 * /dev/urandom, we get 32 bytes = 256 bits for complete overkill.
856 static void
857 isaac_seed (struct isaac_state *s)
859 isaac_seed_start (s);
861 { pid_t t = getpid (); ISAAC_SEED (s, t); }
862 { pid_t t = getppid (); ISAAC_SEED (s, t); }
863 { uid_t t = getuid (); ISAAC_SEED (s, t); }
864 { gid_t t = getgid (); ISAAC_SEED (s, t); }
867 #if HAVE_GETHRTIME
868 hrtime_t t = gethrtime ();
869 ISAAC_SEED (s, t);
870 #else
871 # if HAVE_CLOCK_GETTIME /* POSIX ns-resolution */
872 struct timespec t;
873 clock_gettime (CLOCK_REALTIME, &t);
874 # else
875 # if HAVE_GETTIMEOFDAY
876 struct timeval t;
877 gettimeofday (&t, (struct timezone *) 0);
878 # else
879 time_t t;
880 t = time ((time_t *) 0);
881 # endif
882 # endif
883 #endif
884 ISAAC_SEED (s, t);
887 isaac_seed_machdep (s);
890 char buf[32];
891 int fd = open ("/dev/urandom", O_RDONLY | O_NOCTTY);
892 if (fd >= 0)
894 read (fd, buf, 32);
895 close (fd);
896 isaac_seed_data (s, buf, 32);
898 else
900 fd = open ("/dev/random", O_RDONLY | O_NONBLOCK | O_NOCTTY);
901 if (fd >= 0)
903 /* /dev/random is more precious, so use less */
904 read (fd, buf, 16);
905 close (fd);
906 isaac_seed_data (s, buf, 16);
911 isaac_seed_finish (s);
914 /* Single-word RNG built on top of ISAAC */
915 struct irand_state
917 word32 r[ISAAC_WORDS];
918 unsigned numleft;
919 struct isaac_state *s;
922 static void
923 irand_init (struct irand_state *r, struct isaac_state *s)
925 r->numleft = 0;
926 r->s = s;
930 * We take from the end of the block deliberately, so if we need
931 * only a small number of values, we choose the final ones which are
932 * marginally better mixed than the initial ones.
934 static word32
935 irand32 (struct irand_state *r)
937 if (!r->numleft)
939 isaac_refill (r->s, r->r);
940 r->numleft = ISAAC_WORDS;
942 return r->r[--r->numleft];
946 * Return a uniformly distributed random number between 0 and n,
947 * inclusive. Thus, the result is modulo n+1.
949 * Theory of operation: as x steps through every possible 32-bit number,
950 * x % n takes each value at least 2^32 / n times (rounded down), but
951 * the values less than 2^32 % n are taken one additional time. Thus,
952 * x % n is not perfectly uniform. To fix this, the values of x less
953 * than 2^32 % n are disallowed, and if the RNG produces one, we ask
954 * for a new value.
956 static word32
957 irand_mod (struct irand_state *r, word32 n)
959 word32 x;
960 word32 lim;
962 if (!++n)
963 return irand32 (r);
965 lim = -n % n; /* == (2**32-n) % n == 2**32 % n */
968 x = irand32 (r);
970 while (x < lim);
971 return x % n;
975 * Fill a buffer with a fixed pattern.
977 * The buffer must be at least 3 bytes long, even if
978 * size is less. Larger sizes are filled exactly.
980 static void
981 fillpattern (int type, unsigned char *r, size_t size)
983 size_t i;
984 unsigned bits = type & 0xfff;
986 bits |= bits << 12;
987 ((unsigned char *) r)[0] = (bits >> 4) & 255;
988 ((unsigned char *) r)[1] = (bits >> 8) & 255;
989 ((unsigned char *) r)[2] = bits & 255;
990 for (i = 3; i < size / 2; i *= 2)
991 memcpy ((char *) r + i, (char *) r, i);
992 if (i < size)
993 memcpy ((char *) r + i, (char *) r, size - i);
995 /* Invert the first bit of every 512-byte sector. */
996 if (type & 0x1000)
997 for (i = 0; i < size; i += 512)
998 r[i] ^= 0x80;
1002 * Fill a buffer, R (of size SIZE_MAX), with random data.
1003 * SIZE is rounded UP to a multiple of ISAAC_BYTES.
1005 static void
1006 fillrand (struct isaac_state *s, word32 *r, size_t size_max, size_t size)
1008 size = (size + ISAAC_BYTES - 1) / ISAAC_BYTES;
1009 assert (size <= size_max);
1011 while (size--)
1013 isaac_refill (s, r);
1014 r += ISAAC_WORDS;
1019 * Generate a 6-character (+ nul) pass name string
1020 * FIXME: allow translation of "random".
1022 #define PASS_NAME_SIZE 7
1023 static void
1024 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
1026 if (data)
1027 sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
1028 else
1029 memcpy (name, "random", PASS_NAME_SIZE);
1033 * Do pass number k of n, writing "size" bytes of the given pattern "type"
1034 * to the file descriptor fd. Qname, k and n are passed in only for verbose
1035 * progress message purposes. If n == 0, no progress messages are printed.
1037 * If *sizep == -1, the size is unknown, and it will be filled in as soon
1038 * as writing fails.
1040 static int
1041 dopass (int fd, char const *qname, off_t *sizep, int type,
1042 struct isaac_state *s, unsigned long k, unsigned long n)
1044 off_t size = *sizep;
1045 off_t offset; /* Current file posiiton */
1046 off_t thresh; /* Offset to print next status update */
1047 size_t lim; /* Amount of data to try writing */
1048 size_t soff; /* Offset into buffer for next write */
1049 ssize_t ssize; /* Return value from write */
1050 #if ISAAC_WORDS > 1024
1051 word32 r[ISAAC_WORDS * 3]; /* Multiple of 4K and of pattern size */
1052 #else
1053 word32 r[1024 * 3]; /* Multiple of 4K and of pattern size */
1054 #endif
1055 char pass_string[PASS_NAME_SIZE]; /* Name of current pass */
1057 if (lseek (fd, (off_t) 0, SEEK_SET) == -1)
1059 error (0, errno, _("%s: cannot rewind"), qname);
1060 return -1;
1063 /* Constant fill patterns need only be set up once. */
1064 if (type >= 0)
1066 lim = sizeof r;
1067 if ((off_t) lim > size && size != -1)
1069 lim = (size_t) size;
1071 fillpattern (type, (unsigned char *) r, lim);
1072 passname ((unsigned char *) r, pass_string);
1074 else
1076 passname (0, pass_string);
1079 /* Set position if first status update */
1080 thresh = 0;
1081 if (n)
1083 error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
1084 thresh = VERBOSE_UPDATE;
1085 if (thresh > size && size != -1)
1086 thresh = size;
1089 offset = 0;
1090 for (;;)
1092 /* How much to write this time? */
1093 lim = sizeof r;
1094 if ((off_t) lim > size - offset && size != -1)
1096 if (size < offset)
1097 break;
1098 lim = (size_t) (size - offset);
1099 if (!lim)
1100 break;
1102 if (type < 0)
1103 fillrand (s, r, sizeof r, lim);
1104 /* Loop to retry partial writes. */
1105 for (soff = 0; soff < lim; soff += ssize)
1107 ssize = write (fd, (char *) r + soff, lim - soff);
1108 if (ssize <= 0)
1110 if ((ssize == 0 || errno == ENOSPC)
1111 && size == -1)
1113 /* Ah, we have found the end of the file */
1114 *sizep = thresh = size = offset + soff;
1115 break;
1117 else
1119 int errnum = errno;
1120 char buf[LONGEST_HUMAN_READABLE + 1];
1121 error (0, errnum, _("%s: error writing at offset %s"),
1122 qname,
1123 human_readable ((uintmax_t) (offset + soff),
1124 buf, 1, 1));
1126 * I sometimes use shred on bad media, before throwing it
1127 * out. Thus, I don't want it to give up on bad blocks.
1128 * This code assumes 512-byte blocks and tries to skip
1129 * over them. It works because lim is always a multiple
1130 * of 512, except at the end.
1132 if (errnum == EIO && soff % 512 == 0 && lim >= soff + 512
1133 && size != -1)
1135 if (lseek (fd, (off_t) (offset + soff + 512), SEEK_SET)
1136 != -1)
1138 soff += 512;
1139 continue;
1141 error (0, errno, "%s: lseek", qname);
1143 return -1;
1148 /* Okay, we have written "lim" bytes. */
1150 if (offset + lim < offset)
1152 error (0, 0, _("%s: file too large"), qname);
1153 return -1;
1156 offset += lim;
1158 /* Time to print progress? */
1159 if (offset >= thresh && n)
1161 char offset_buf[LONGEST_HUMAN_READABLE + 1];
1162 char size_buf[LONGEST_HUMAN_READABLE + 1];
1163 char const *human_offset
1164 = human_readable ((uintmax_t) offset, offset_buf, 1,
1165 OUTPUT_BLOCK_SIZE);
1166 if (size != -1)
1167 error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s"), qname, k, n,
1168 pass_string, human_offset,
1169 human_readable ((uintmax_t) size, size_buf, 1,
1170 OUTPUT_BLOCK_SIZE));
1171 else
1172 error (0, 0, _("%s: pass %lu/%lu (%s)...%s"), qname, k, n,
1173 pass_string, human_offset);
1175 thresh += VERBOSE_UPDATE;
1176 if (thresh > size && size != -1)
1177 thresh = size;
1179 * Force periodic syncs to keep displayed progress accurate
1180 * FIXME: Should these be present even if -v is not enabled,
1181 * to keep the buffer cache from filling with dirty pages?
1182 * It's a common problem with programs that do lots of writes,
1183 * like mkfs.
1185 if (fdatasync (fd) < 0 && fsync (fd) < 0)
1187 error (0, errno, "%s: fsync", qname);
1188 return -1;
1193 /* Force what we just wrote to hit the media. */
1194 if (fdatasync (fd) < 0 && fsync (fd) < 0)
1196 error (0, errno, "%s: fsync", qname);
1197 return -1;
1199 return 0;
1203 * The passes start and end with a random pass, and the passes in between
1204 * are done in random order. The idea is to deprive someone trying to
1205 * reverse the process of knowledge of the overwrite patterns, so they
1206 * have the additional step of figuring out what was done to the disk
1207 * before they can try to reverse or cancel it.
1209 * First, all possible 1-bit patterns. There are two of them.
1210 * Then, all possible 2-bit patterns. There are four, but the two
1211 * which are also 1-bit patterns can be omitted.
1212 * Then, all possible 3-bit patterns. Likewise, 8-2 = 6.
1213 * Then, all possible 4-bit patterns. 16-4 = 12.
1215 * The basic passes are:
1216 * 1-bit: 0x000, 0xFFF
1217 * 2-bit: 0x555, 0xAAA
1218 * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
1219 * 100100100100 110110110110
1220 * 9 2 4 D B 6
1221 * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
1222 * 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
1223 * Adding three random passes at the beginning, middle and end
1224 * produces the default 25-pass structure.
1226 * The next extension would be to 5-bit and 6-bit patterns.
1227 * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
1228 * 6-bit patterns, so they would increase the time required
1229 * significantly. 4-bit patterns are enough for most purposes.
1231 * The main gotcha is that this would require a trickier encoding,
1232 * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
1233 * lcm(2,3,4,5) = 60 bits is not.
1235 * One extension that is included is to complement the first bit in each
1236 * 512-byte block, to alter the phase of the encoded data in the more
1237 * complex encodings. This doesn't apply to MFM, so the 1-bit patterns
1238 * are considered part of the 3-bit ones and the 2-bit patterns are
1239 * considered part of the 4-bit patterns.
1242 * How does the generalization to variable numbers of passes work?
1244 * Here's how...
1245 * Have an ordered list of groups of passes. Each group is a set.
1246 * Take as many groups as will fit, plus a random subset of the
1247 * last partial group, and place them into the passes list.
1248 * Then shuffle the passes list into random order and use that.
1250 * One extra detail: if we can't include a large enough fraction of the
1251 * last group to be interesting, then just substitute random passes.
1253 * If you want more passes than the entire list of groups can
1254 * provide, just start repeating from the beginning of the list.
1256 static int const
1257 patterns[] =
1259 -2, /* 2 random passes */
1260 2, 0x000, 0xFFF, /* 1-bit */
1261 2, 0x555, 0xAAA, /* 2-bit */
1262 -1, /* 1 random pass */
1263 6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6, /* 3-bit */
1264 12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
1265 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */
1266 -1, /* 1 random pass */
1267 /* The following patterns have the frst bit per block flipped */
1268 8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
1269 14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
1270 0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
1271 -1, /* 1 random pass */
1272 0 /* End */
1276 * Generate a random wiping pass pattern with num passes.
1277 * This is a two-stage process. First, the passes to include
1278 * are chosen, and then they are shuffled into the desired
1279 * order.
1281 static void
1282 genpattern (int *dest, size_t num, struct isaac_state *s)
1284 struct irand_state r;
1285 size_t randpasses;
1286 int const *p;
1287 int *d;
1288 size_t n;
1289 size_t accum, top, swap;
1290 int k;
1292 if (!num)
1293 return;
1295 irand_init (&r, s);
1297 /* Stage 1: choose the passes to use */
1298 p = patterns;
1299 randpasses = 0;
1300 d = dest; /* Destination for generated pass list */
1301 n = num; /* Passes remaining to fill */
1303 for (;;)
1305 k = *p++; /* Block descriptor word */
1306 if (!k)
1307 { /* Loop back to the beginning */
1308 p = patterns;
1310 else if (k < 0)
1311 { /* -k random passes */
1312 k = -k;
1313 if ((size_t) k >= n)
1315 randpasses += n;
1316 n = 0;
1317 break;
1319 randpasses += k;
1320 n -= k;
1322 else if ((size_t) k <= n)
1323 { /* Full block of patterns */
1324 memcpy (d, p, k * sizeof (int));
1325 p += k;
1326 d += k;
1327 n -= k;
1329 else if (n < 2 || 3 * n < (size_t) k)
1330 { /* Finish with random */
1331 randpasses += n;
1332 break;
1334 else
1335 { /* Pad out with k of the n available */
1338 if (n == (size_t) k-- || irand_mod (&r, k) < n)
1340 *d++ = *p;
1341 n--;
1343 p++;
1345 while (n);
1346 break;
1349 top = num - randpasses; /* Top of initialized data */
1350 /* assert (d == dest+top); */
1353 * We now have fixed patterns in the dest buffer up to
1354 * "top", and we need to scramble them, with "randpasses"
1355 * random passes evenly spaced among them.
1357 * We want one at the beginning, one at the end, and
1358 * evenly spaced in between. To do this, we basically
1359 * use Bresenham's line draw (a.k.a DDA) algorithm
1360 * to draw a line with slope (randpasses-1)/(num-1).
1361 * (We use a positive accumulator and count down to
1362 * do this.)
1364 * So for each desired output value, we do the following:
1365 * - If it should be a random pass, copy the pass type
1366 * to top++, out of the way of the other passes, and
1367 * set the current pass to -1 (random).
1368 * - If it should be a normal pattern pass, choose an
1369 * entry at random between here and top-1 (inclusive)
1370 * and swap the current entry with that one.
1372 randpasses--; /* To speed up later math */
1373 accum = randpasses; /* Bresenham DDA accumulator */
1374 for (n = 0; n < num; n++)
1376 if (accum <= randpasses)
1378 accum += num - 1;
1379 dest[top++] = dest[n];
1380 dest[n] = -1;
1382 else
1384 swap = n + irand_mod (&r, top - n - 1);
1385 k = dest[n];
1386 dest[n] = dest[swap];
1387 dest[swap] = k;
1389 accum -= randpasses;
1391 /* assert (top == num); */
1393 memset (&r, 0, sizeof r); /* Wipe this on general principles */
1397 * The core routine to actually do the work. This overwrites the first
1398 * size bytes of the given fd. Returns -1 on error, 0 on success.
1400 static int
1401 do_wipefd (int fd, char const *qname, struct isaac_state *s,
1402 struct Options const *flags)
1404 size_t i;
1405 struct stat st;
1406 off_t size; /* Size to write, size to read */
1407 unsigned long n; /* Number of passes for printing purposes */
1408 int *passarray;
1410 n = 0; /* dopass takes n -- 0 to mean "don't print progress" */
1411 if (flags->verbose)
1412 n = flags->n_iterations + ((flags->zero_fill) != 0);
1414 if (fstat (fd, &st))
1416 error (0, errno, "%s: fstat", qname);
1417 return -1;
1420 /* If we know that we can't possibly shred the file, give up now.
1421 Otherwise, we may go into a infinite loop writing data before we
1422 find that we can't rewind the device. */
1423 if ((S_ISCHR (st.st_mode) && isatty (fd))
1424 || S_ISFIFO (st.st_mode)
1425 || S_ISSOCK (st.st_mode))
1427 error (0, 0, _("%s: invalid file type"), qname);
1428 return -1;
1431 /* Allocate pass array */
1432 passarray = xmalloc (flags->n_iterations * sizeof (int));
1434 size = flags->size;
1435 if (size == -1)
1437 /* Accept a length of zero only if it's a regular file.
1438 For any other type of file, try to get the size another way. */
1439 if (S_ISREG (st.st_mode))
1441 size = st.st_size;
1442 if (size < 0)
1444 error (0, 0, _("%s: file has negative size"), qname);
1445 return -1;
1448 else
1450 size = lseek (fd, (off_t) 0, SEEK_END);
1451 if (size <= 0)
1453 /* We are unable to determine the length, up front.
1454 Let dopass do that as part of its first iteration. */
1455 size = -1;
1459 if (0 <= size && !(flags->exact))
1461 size += ST_BLKSIZE (st) - 1 - (size - 1) % ST_BLKSIZE (st);
1463 /* If in rounding up, we've just overflowed, use the maximum. */
1464 if (size < 0)
1465 size = TYPE_MAXIMUM (off_t);
1469 /* Schedule the passes in random order. */
1470 genpattern (passarray, flags->n_iterations, s);
1472 /* Do the work */
1473 for (i = 0; i < flags->n_iterations; i++)
1475 if (dopass (fd, qname, &size, passarray[i], s, i + 1, n) < 0)
1477 memset (passarray, 0, flags->n_iterations * sizeof (int));
1478 free (passarray);
1479 return -1;
1483 memset (passarray, 0, flags->n_iterations * sizeof (int));
1484 free (passarray);
1486 if (flags->zero_fill)
1487 if (dopass (fd, qname, &size, 0, s, flags->n_iterations + 1, n) < 0)
1488 return -1;
1490 /* Okay, now deallocate the data. The effect of ftruncate on
1491 non-regular files is unspecified, so don't worry about any
1492 errors reported for them. */
1493 if (flags->remove_file && ftruncate (fd, (off_t) 0) != 0
1494 && S_ISREG (st.st_mode))
1496 error (0, errno, _("%s: error truncating"), qname);
1497 return -1;
1500 return 0;
1503 /* A wrapper with a little more checking for fds on the command line */
1504 static int
1505 wipefd (int fd, char const *qname, struct isaac_state *s,
1506 struct Options const *flags)
1508 int fd_flags = fcntl (fd, F_GETFL);
1510 if (fd_flags < 0)
1512 error (0, errno, "%s: fcntl", qname);
1513 return -1;
1515 if (fd_flags & O_APPEND)
1517 error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
1518 return -1;
1520 return do_wipefd (fd, qname, s, flags);
1523 /* --- Name-wiping code --- */
1525 /* Characters allowed in a file name - a safe universal set. */
1526 static char const nameset[] =
1527 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_+=%@#.";
1530 * This increments the name, considering it as a big-endian base-N number
1531 * with the digits taken from nameset. Characters not in the nameset
1532 * are considered to come before nameset[0].
1534 * It's not obvious, but this will explode if name[0..len-1] contains
1535 * any 0 bytes.
1537 * This returns the carry (1 on overflow).
1539 static int
1540 incname (char *name, unsigned len)
1542 char const *p;
1544 if (!len)
1545 return 1;
1547 p = strchr (nameset, name[--len]);
1548 /* If the character is not found, replace it with a 0 digit */
1549 if (!p)
1551 name[len] = nameset[0];
1552 return 0;
1554 /* If this character has a successor, use it */
1555 if (p[1])
1557 name[len] = p[1];
1558 return 0;
1560 /* Otherwise, set this digit to 0 and increment the prefix */
1561 name[len] = nameset[0];
1562 return incname (name, len);
1566 * Repeatedly rename a file with shorter and shorter names,
1567 * to obliterate all traces of the file name on any system that
1568 * adds a trailing delimiter to on-disk file names and reuses
1569 * the same directory slot. Finally, unlink it.
1570 * The passed-in filename is modified in place to the new filename.
1571 * (Which is unlinked if this function succeeds, but is still present if
1572 * it fails for some reason.)
1574 * The main loop is written carefully to not get stuck if all possible
1575 * names of a given length are occupied. It counts down the length from
1576 * the original to 0. While the length is non-zero, it tries to find an
1577 * unused file name of the given length. It continues until either the
1578 * name is available and the rename succeeds, or it runs out of names
1579 * to try (incname wraps and returns 1). Finally, it unlinks the file.
1581 * The unlink is Unix-specific, as ANSI-standard remove has more
1582 * portability problems with C libraries making it "safe". rename
1583 * is ANSI-standard.
1585 * To force the directory data out, we try to open the directory and
1586 * invoke fdatasync on it. This is rather non-standard, so we don't
1587 * insist that it works, just fall back to a global sync in that case.
1588 * This is fairly significantly Unix-specific. Of course, on any
1589 * filesystem with synchronous metadata updates, this is unnecessary.
1591 static int
1592 wipename (char *oldname, char const *qoldname, struct Options const *flags)
1594 char *newname, *base; /* Base points to filename part of newname */
1595 unsigned len;
1596 int err;
1597 int dir_fd; /* Try to open directory to sync *it* */
1599 newname = xstrdup (oldname);
1600 if (flags->verbose)
1601 error (0, 0, _("%s: removing"), qoldname);
1603 /* Find the file name portion */
1604 base = strrchr (newname, '/');
1605 /* Temporary hackery to get a directory fd */
1606 if (base)
1608 *base = '\0';
1609 dir_fd = open (newname, O_RDONLY | O_NOCTTY);
1610 *base = '/';
1612 else
1614 dir_fd = open (".", O_RDONLY | O_NOCTTY);
1616 base = base ? base + 1 : newname;
1617 len = strlen (base);
1619 while (len)
1621 memset (base, nameset[0], len);
1622 base[len] = 0;
1625 struct stat st;
1626 if (lstat (newname, &st) < 0)
1628 if (rename (oldname, newname) == 0)
1630 if (dir_fd < 0
1631 || (fdatasync (dir_fd) < 0 && fsync (dir_fd) < 0))
1632 sync (); /* Force directory out */
1633 if (flags->verbose)
1636 * People seem to understand this better than talking
1637 * about renaming oldname. newname doesn't need
1638 * quoting because we picked it.
1640 error (0, 0, _("%s: renamed to %s"), qoldname,
1641 quote (newname));
1643 memcpy (oldname + (base - newname), base, len + 1);
1644 break;
1646 else
1648 /* The rename failed: give up on this length. */
1649 break;
1652 else
1654 /* newname exists, so increment BASE so we use another */
1657 while (!incname (base, len));
1658 len--;
1660 free (newname);
1661 err = unlink (oldname);
1662 if (dir_fd < 0 || (fdatasync (dir_fd) < 0 && fsync (dir_fd) < 0))
1663 sync ();
1664 close (dir_fd);
1665 if (!err && flags->verbose)
1666 error (0, 0, _("%s: removed"), qoldname);
1667 return err;
1671 * Finally, the function that actually takes a filename and grinds
1672 * it into hamburger.
1674 * FIXME
1675 * Detail to note: since we do not restore errno to EACCES after
1676 * a failed chmod, we end up printing the error code from the chmod.
1677 * This is actually the error that stopped us from proceeding, so
1678 * it's arguably the right one, and in practice it'll be either EACCES
1679 * again or EPERM, which both give similar error messages.
1680 * Does anyone disagree?
1682 static int
1683 wipefile (char *name, char const *qname,
1684 struct isaac_state *s, struct Options const *flags)
1686 int err, fd;
1688 fd = open (name, O_WRONLY | O_NOCTTY);
1689 if (fd < 0)
1691 if (errno == EACCES && flags->force)
1693 if (chmod (name, S_IWUSR) >= 0) /* 0200, user-write-only */
1694 fd = open (name, O_WRONLY | O_NOCTTY);
1696 else if ((errno == ENOENT || errno == ENOTDIR)
1697 && strncmp (name, "/dev/fd/", 8) == 0)
1699 /* We accept /dev/fd/# even if the OS doesn't support it */
1700 int errnum = errno;
1701 unsigned long num;
1702 char *p;
1703 errno = 0;
1704 num = strtoul (name + 8, &p, 10);
1705 /* If it's completely decimal with no leading zeros... */
1706 if (errno == 0 && !*p && num <= INT_MAX &&
1707 (('1' <= name[8] && name[8] <= '9')
1708 || (name[8] == '0' && !name[9])))
1710 return wipefd ((int) num, qname, s, flags);
1712 errno = errnum;
1715 if (fd < 0)
1717 error (0, errno, "%s", qname);
1718 return -1;
1721 err = do_wipefd (fd, qname, s, flags);
1722 if (close (fd) != 0)
1724 error (0, 0, "%s: close", qname);
1725 err = -1;
1727 if (err == 0 && flags->remove_file)
1729 err = wipename (name, qname, flags);
1730 if (err < 0)
1731 error (0, 0, _("%s: cannot remove"), qname);
1733 return err;
1737 main (int argc, char **argv)
1739 struct isaac_state s;
1740 int err = 0;
1741 struct Options flags;
1742 char **file;
1743 int n_files;
1744 int c;
1745 int i;
1747 program_name = argv[0];
1748 setlocale (LC_ALL, "");
1749 bindtextdomain (PACKAGE, LOCALEDIR);
1750 textdomain (PACKAGE);
1752 atexit (close_stdout);
1754 isaac_seed (&s);
1756 memset (&flags, 0, sizeof flags);
1758 flags.n_iterations = DEFAULT_PASSES;
1759 flags.size = -1;
1761 while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1763 switch (c)
1765 case 0:
1766 break;
1768 case 'f':
1769 flags.force = 1;
1770 break;
1772 case 'n':
1774 uintmax_t tmp;
1775 if (xstrtoumax (optarg, NULL, 10, &tmp, NULL) != LONGINT_OK
1776 || (word32) tmp != tmp
1777 || ((size_t) (tmp * sizeof (int)) / sizeof (int) != tmp))
1779 error (1, 0, _("%s: invalid number of passes"),
1780 quotearg_colon (optarg));
1782 flags.n_iterations = (size_t) tmp;
1784 break;
1786 case 'u':
1787 flags.remove_file = 1;
1788 break;
1790 case 's':
1792 uintmax_t tmp;
1793 if (xstrtoumax (optarg, NULL, 0, &tmp, "cbBkMGTPEZY0")
1794 != LONGINT_OK)
1796 error (1, 0, _("%s: invalid file size"),
1797 quotearg_colon (optarg));
1799 flags.size = tmp;
1801 break;
1803 case 'v':
1804 flags.verbose = 1;
1805 break;
1807 case 'x':
1808 flags.exact = 1;
1809 break;
1811 case 'z':
1812 flags.zero_fill = 1;
1813 break;
1815 case_GETOPT_HELP_CHAR;
1817 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1819 default:
1820 usage (1);
1824 file = argv + optind;
1825 n_files = argc - optind;
1827 if (n_files == 0)
1829 error (0, 0, _("missing file argument"));
1830 usage (1);
1833 for (i = 0; i < n_files; i++)
1835 char const *qname = quotearg_colon (file[i]);
1836 if (strcmp (file[i], "-") == 0)
1838 if (wipefd (STDOUT_FILENO, qname, &s, &flags) < 0)
1839 err = 1;
1841 else
1843 /* Plain filename - Note that this overwrites *argv! */
1844 if (wipefile (file[i], qname, &s, &flags) < 0)
1845 err = 1;
1849 /* Just on general principles, wipe s. */
1850 memset (&s, 0, sizeof s);
1852 exit (err);
1855 * vim:sw=2:sts=2: