(usage): Note that ``Mandatory arguments to long options are mandatory
[platform/upstream/coreutils.git] / src / shred.c
1 /* TODO:
2    - use consistent non-capitalization in error messages
3    - add standard GNU copyleft comment
4
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.
13  */
14
15 /*
16  * shred.c - by Colin Plumb.
17  *
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.
20  *
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.
24  *
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
28  *
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.
37  *
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.
43  *
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.
46  *
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.
51  *
52  * The ISAAC code still bears some resemblance to the code written
53  * by Bob Jenkins, but he permits pretty unlimited use.
54  *
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.
59  *
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.
68  *
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?
73  */
74
75 /* The official name of this program (e.g., no `g' prefix).  */
76 #define PROGRAM_NAME "shred"
77
78 #define AUTHORS "Colin Plumb"
79
80 #if HAVE_CONFIG_H
81 # include <config.h>
82 #endif
83
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>
90
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 # include "gtod.h"
102 char *xstrdup PARAMS ((char const *));
103
104 #else /* !HAVE_CONFIG_H */
105 /*
106  * Standalone build - this file compiles by itself without autoconf and
107  * the like.  No i18n, and I still have to write a stub for getopt_long,
108  * but it's a lot less intertwingled than the usual GNU utilities.
109  */
110
111 # include <ctype.h>     /* For isprint */
112 # include <string.h>    /* For memcpy, strerror */
113 # include <limits.h>    /* For ULONG_MAX etc. */
114 # include <stdlib.h>    /* For strtoul, EXIT_FAILURE */
115 # include <errno.h>
116 # include <fcntl.h>     /* For O_RDONLY etc. */
117 # include <unistd.h>    /* For getpid, etc. */
118 # include <sys/time.h>  /* For struct timeval */
119 # include <sys/stat.h>  /* For struct stat */
120
121 # define PACKAGE "standalone"
122 # define VERSION "2.0" /* Kind of arbitrary... */
123
124 # if __GNUC__ < 2 || __GNUC__ == 2 && __GNUC_MINOR__ < 5 || __STRICT_ANSI__
125 #  define attribute(x)
126 # else
127 #  define attribute __attribute__
128 #  if __GNUC__ == 2 && __GNUC_MINOR__ < 7
129    /* The __-protected forms were introduced in GCC 2.6.4 */
130 #   define __format__ format
131 #   define __printf__ printf
132 #  endif
133 # endif
134
135 /* Reasonable default assumptions for time-getting */
136 # ifndef HAVE_GETTIMEOFDAY
137 #  define HAVE_GETTIMEOFDAY 1 /* Most systems have it these days */
138 # endif
139
140 # ifdef CLOCK_REALTIME
141 #  ifndef HAVE_CLOCK_GETTIME
142 #   define HAVE_CLOCK_GETTIME 1
143 #  endif
144 # endif
145
146 # ifndef STDOUT_FILENO
147 #  define STDOUT_FILENO 1
148 # endif
149
150 # define RETSIGTYPE int
151
152 # ifndef S_IWUSR
153 #  ifdef S_IWRITE
154 #   define S_IWUSR S_IWRITE
155 #  else
156 #   define S_IWUSR 0200
157 #  endif
158 # endif
159
160 /* POSIX doesn't require st_blksize, and 65536 is a reasonable
161    upper bound for existing filesystem practice.  */
162 # define ST_BLKSIZE(Stat) 65536
163
164 # define uintmax_t unsigned long
165
166 /* Variant human-readable function that ignores last two args */
167 # define human_readable(v, b, f, t) (sprintf (b, "%lu", (unsigned long) v), b)
168 # define LONGEST_HUMAN_READABLE (sizeof (uintmax_t) * CHAR_BIT / 3)
169
170 /* Variant convert-to-uintmax_t function that accepts metric suffixes */
171 enum strtol_error
172   {
173     LONGINT_OK, LONGINT_INVALID, LONGINT_INVALID_SUFFIX_CHAR, LONGINT_OVERFLOW
174   };
175 static uintmax_t
176 xstrtoumax (char const *ptr, char const **end, int base, uintmax_t *res,
177             char const *valid_suffixes)
178 {
179   char *end_ptr;
180   char const *p;
181   static char const metric_suffixes[] = "kMGTPEZY";
182   int decimal_flag;
183   uintmax_t n;
184   char c;
185
186   errno = 0;
187   *res = n = strtoul (ptr, &end_ptr, base);
188   if (end)
189     *end = end_ptr;
190   if (errno)
191     return LONGINT_OVERFLOW;
192   if (ptr == end_ptr)
193     return LONGINT_INVALID;
194   c = *end_ptr;
195   if (!c)
196     return LONGINT_OK;
197   /* Now deal with metric-style suffixes */
198   if (valid_suffixes && !strchr (valid_suffixes, c))
199     return LONGINT_INVALID_SUFFIX_CHAR;
200
201   decimal_flag = 0;
202   switch (c)
203     {
204     case 'b':
205       if (n > ULONG_MAX/512)
206         return LONGINT_OVERFLOW;
207       n *= 512;
208       break;
209
210     case 'B':
211       if (n > ULONG_MAX/102412)
212         return LONGINT_OVERFLOW;
213       n *= 1024;
214       break;
215
216     case 'c':
217       break;
218
219     case 'K':
220       c = 'k';
221       goto def;
222
223     case 'm':
224       c = 'M';
225       /*FALLTHROUGH*/
226 def:default:
227       p = strchr (metric_suffixes, c);
228       if (!p)
229         return LONGINT_INVALID_SUFFIX_CHAR;
230       /*
231        * If valid_suffixes contains '0', then xD (decimal) and xB (binary)
232        * are allowed as "supersuffixes".  Binary is the default.
233        */
234       if (strchr (valid_suffixes, '0'))
235         {
236           if (end_ptr[1] == 'B')
237             end_ptr++;
238           else if (end_ptr[1] == 'D')
239             {
240               decimal_flag = 1;
241               end_ptr++;
242             }
243         }
244       /* Now do the scaling */
245       p++;
246       if (decimal_flag)
247         do {
248           if (n > ULONG_MAX/1000)
249             return LONGINT_OVERFLOW;
250           n *= 1000;
251         } while (--p > metric_suffixes);
252       else
253         do {
254           if (n > ULONG_MAX/1024)
255             return LONGINT_OVERFLOW;
256           n *= 1024;
257         } while (--p > metric_suffixes);
258     }
259
260   /* Final wrapup */
261   if (end)
262     *end = end_ptr+1;   /* Extra suffix is allowed if it's expected */
263   else if (end_ptr[1])
264     return LONGINT_INVALID_SUFFIX_CHAR;
265   *res = n;
266   return LONGINT_OK;
267 }
268
269 /* Dummy i18n stubs */
270 # define _(x) x
271 # define N_(x) x
272 # define setlocale(x,y) (void) 0
273 # define bindtextdomain(x,y) (void) 0
274 # define textdomain(x) (void) 0
275
276 /*
277  * Print a message with `fprintf (stderr, FORMAT, ...)';
278  *    if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
279  *       If STATUS is nonzero, terminate the program with `exit (STATUS)'.
280  */
281 static void error (int status, int errnum, const char *format, ...)
282         attribute ((__format__ (__printf__, 3, 4)));
283
284 extern char const *program_name;
285 static void
286 error (int status, int errnum, const char *format, ...)
287 {
288   va_list ap;
289
290   if (program_name)
291     {
292       fputs (program_name, stderr);
293       fputs (": ", stderr);
294     }
295   va_start (ap, format);
296   vfprintf (stderr, format, ap);
297   va_end (ap);
298   if (errnum)
299     {
300       fputs (": ", stderr);
301       fputs (strerror (errnum), stderr);
302     }
303   putc ('\n', stderr);
304
305   if (status)
306     exit (status);
307 }
308
309 /*
310  * GNU programs actually check for failure closing standard output.
311  * This seems unnecessary, until your shell script starts hitting
312  * ENOSPC and doing bizarre things with zero-length files.
313  */
314 static void
315 close_stdout (void)
316 {
317   if (ferror (stdout))
318     error (EXIT_FAILURE, 0, _("write error"));
319   if (fclose (stdout) != 0)
320     error (EXIT_FAILURE, errno, _("write error"));
321 }
322
323 /*
324  * Quote the argument (including colon characters) into the buffer.
325  * Return the buffer size used (including trailing null byte.)
326  * If this is larger than the bufsize, it is an estimate of the space
327  * needed.
328  */
329 static size_t
330 quotearg_colon_buf (char const *arg, char *buf, size_t bufsize)
331 {
332   /* Some systems don't have \a or \e, so this is ASCII-dependent */
333   static char const escaped[] = "\7\b\33\f\n\r\t\v";
334   static char const escapes[] = "abefnrtv";
335   int c;
336   size_t pos = 0;
337   char const *p;
338
339   while ((c = (unsigned char) *arg++) != 0)
340     {
341       if (isprint (c))
342         {
343           if (strchr ("\\:", c))        /* Anything else we should quote? */
344             if (pos++ < bufsize) *buf++ = '\\';
345         }
346       else
347         {
348           if (pos++ < bufsize) *buf++ = '\\';
349           p = strchr (escaped, c); /* c is never 0, so this is okay */
350           if (p)
351             {
352               c = escapes[p-escaped];
353             }
354           else
355             {
356               if ('0' <= *arg && *arg <= '9')
357                 c += 256; /* Force 3-digit form if followed by a digit */
358               if (c > 077)
359                 if (pos++ < bufsize) *buf++ = "0123"[c>>6 & 3];
360               if (c > 07)
361                 if (pos++ < bufsize) *buf++ = "01234567"[c>>3 & 7];
362               c = "01234567"[c & 7];
363             }
364         }
365         if (pos++ < bufsize) *buf++ = c;
366     }
367     if (pos++ < bufsize) *buf++ = 0;
368     return pos;
369 }
370
371 /* Quote metacharacters in a filename */
372 char const *
373 quotearg_colon (char const *arg)
374 {
375   static char *buf = 0;
376   size_t bufsize = 0;
377   size_t newsize;
378
379   while ((newsize = quotearg_colon_buf (arg, buf, bufsize)) > bufsize)
380     {
381       buf = realloc (buf, newsize);
382       if (!buf)
383         error (EXIT_FAILURE, 0, _("memory exhausted"));
384       bufsize = newsize;
385     }
386   return buf;
387 }
388
389 void *
390 xmalloc (size_t n)
391 {
392   void *p = malloc (n);
393   if (!p)
394     error (EXIT_FAILURE, 0, _("memory exhausted"));
395   return p;
396 }
397
398 char *
399 xstrdup (char const *string)
400 {
401   return strcpy (xmalloc (strlen (string) + 1), string);
402 }
403
404 #endif /* ! HAVE_CONFIG_H */
405
406 #ifndef O_NOCTTY
407 # define O_NOCTTY 0  /* This is a very optional frill */
408 #endif
409
410 /* Some systems don't support some file types.  */
411 #ifndef S_ISFIFO
412 # define S_ISFIFO(mode) 0
413 #endif
414 #ifndef S_ISLNK
415 # define S_ISLNK(mode) 0
416 #endif
417 #ifndef S_ISSOCK
418 # define S_ISSOCK(mode) 0
419 #endif
420
421 #define DEFAULT_PASSES 25       /* Default */
422
423 /* How often to update wiping display */
424 #define VERBOSE_UPDATE  150*1024
425
426 /* If positive, the units to use when printing sizes;
427    if negative, the human-readable base.  */
428 #define OUTPUT_BLOCK_SIZE (-1024)
429
430 struct Options
431 {
432   int force;            /* -f flag: chmod files if necessary */
433   size_t n_iterations;  /* -n flag: Number of iterations */
434   off_t size;           /* -s flag: size of file */
435   int remove_file;      /* -u flag: remove file after shredding */
436   int verbose;          /* -v flag: Print progress */
437   int exact;            /* -x flag: Do not round up file size */
438   int zero_fill;        /* -z flag: Add a final zero pass */
439 };
440
441 static struct option const long_opts[] =
442 {
443   {"exact", no_argument, NULL, 'x'},
444   {"force", no_argument, NULL, 'f'},
445   {"iterations", required_argument, NULL, 'n'},
446   {"size", required_argument, NULL, 's'},
447   {"remove", no_argument, NULL, 'u'},
448   {"verbose", no_argument, NULL, 'v'},
449   {"zero", required_argument, NULL, 'z'},
450   {GETOPT_HELP_OPTION_DECL},
451   {GETOPT_VERSION_OPTION_DECL},
452   {NULL, 0, NULL, 0}
453 };
454
455 /* Global variable for error printing purposes */
456 char const *program_name; /* Initialized before any possible use */
457
458 void
459 usage (int status)
460 {
461   if (status != 0)
462     fprintf (stderr, _("Try `%s --help' for more information.\n"),
463              program_name);
464   else
465     {
466       printf (_("Usage: %s [OPTIONS] FILE [...]\n"), program_name);
467       fputs (_("\
468 Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\
469 for even very expensive hardware probing to recover the data.\n\
470 \n\
471 "), stdout);
472       fputs (_("\
473 Mandatory arguments to long options are mandatory for short options too.\n\
474 "), stdout);
475       printf (_("\
476   -f, --force    change permissions to allow writing if necessary\n\
477   -n, --iterations=N  Overwrite N times instead of the default (%d)\n\
478   -s, --size=N   shred this many bytes (suffixes like k, M, G accepted)\n\
479 "), DEFAULT_PASSES);
480       fputs (_("\
481   -u, --remove   truncate and remove file after overwriting\n\
482   -v, --verbose  show progress\n\
483   -x, --exact    do not round file sizes up to the next full block\n\
484   -z, --zero     add a final overwrite with zeros to hide shredding\n\
485   -              shred standard output\n\
486 "), stdout);
487       fputs (_("\
488       --help     display this help and exit\n\
489       --version  output version information and exit\n\
490 "), stdout);
491       fputs (_("\
492 \n\
493 Delete FILE(s) if --remove (-u) is specified.  The default is not to remove\n\
494 the files because it is common to operate on device files like /dev/hda,\n\
495 and those files usually should not be removed.  When operating on regular\n\
496 files, most people use the --remove option.\n\
497 \n\
498 "), stdout);
499       fputs (_("\
500 CAUTION: Note that shred relies on a very important assumption:\n\
501 that the filesystem overwrites data in place.  This is the traditional\n\
502 way to do things, but many modern filesystem designs do not satisfy this\n\
503 assumption.  The following are examples of filesystems on which shred is\n\
504 not effective:\n\
505 \n\
506 "), stdout);
507       fputs (_("\
508 * log-structured or journaled filesystems, such as those supplied with\n\
509   AIX and Solaris (and JFS, ReiserFS, XFS, etc.)\n\
510 \n\
511 * filesystems that write redundant data and carry on even if some writes\n\
512   fail, such as RAID-based filesystems\n\
513 \n\
514 * filesystems that make snapshots, such as Network Appliance's NFS server\n\
515 \n\
516 "), stdout);
517       fputs (_("\
518 * filesystems that cache in temporary locations, such as NFS\n\
519   version 3 clients\n\
520 \n\
521 * compressed filesystems\n\
522 \n\
523 In addition, file system backups and remote mirrors may contain copies\n\
524 of the file that cannot be removed, and that will allow a shredded file\n\
525 to be recovered later.\n\
526 "), stdout);
527       puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
528     }
529   exit (status);
530 }
531
532 #if ! HAVE_FDATASYNC
533 # define fdatasync(fd) -1
534 #endif
535
536 /*
537  * --------------------------------------------------------------------
538  *     Bob Jenkins' cryptographic random number generator, ISAAC.
539  *     Hacked by Colin Plumb.
540  *
541  * We need a source of random numbers for some of the overwrite data.
542  * Cryptographically secure is desirable, but it's not life-or-death
543  * so I can be a little bit experimental in the choice of RNGs here.
544  *
545  * This generator is based somewhat on RC4, but has analysis
546  * (http://ourworld.compuserve.com/homepages/bob_jenkins/randomnu.htm)
547  * pointing to it actually being better.  I like it because it's nice
548  * and fast, and because the author did good work analyzing it.
549  * --------------------------------------------------------------------
550  */
551
552 #if defined __STDC__ && __STDC__
553 # define UINT_MAX_32_BITS 4294967295U
554 #else
555 # define UINT_MAX_32_BITS 0xFFFFFFFF
556 #endif
557
558 #if ULONG_MAX == UINT_MAX_32_BITS
559 typedef unsigned long word32;
560 #else
561 # if UINT_MAX == UINT_MAX_32_BITS
562 typedef unsigned word32;
563 # else
564 #  if USHRT_MAX == UINT_MAX_32_BITS
565 typedef unsigned short word32;
566 #  else
567 #   if UCHAR_MAX == UINT_MAX_32_BITS
568 typedef unsigned char word32;
569 #   else
570      "No 32-bit type available!"
571 #   endif
572 #  endif
573 # endif
574 #endif
575
576 /* Size of the state tables to use.  (You may change ISAAC_LOG) */
577 #define ISAAC_LOG 8
578 #define ISAAC_WORDS (1 << ISAAC_LOG)
579 #define ISAAC_BYTES (ISAAC_WORDS * sizeof (word32))
580
581 /* RNG state variables */
582 struct isaac_state
583   {
584     word32 mm[ISAAC_WORDS];     /* Main state array */
585     word32 iv[8];               /* Seeding initial vector */
586     word32 a, b, c;             /* Extra index variables */
587   };
588
589 /* This index operation is more efficient on many processors */
590 #define ind(mm, x) \
591   (* (word32 *) ((char *) (mm) + ((x) & (ISAAC_WORDS - 1) * sizeof (word32))))
592
593 /*
594  * The central step.  This uses two temporaries, x and y.  mm is the
595  * whole state array, while m is a pointer to the current word.  off is
596  * the offset from m to the word ISAAC_WORDS/2 words away in the mm array,
597  * i.e. +/- ISAAC_WORDS/2.
598  */
599 #define isaac_step(mix, a, b, mm, m, off, r) \
600 ( \
601   a = ((a) ^ (mix)) + (m)[off], \
602   x = *(m), \
603   *(m) = y = ind (mm, x) + (a) + (b), \
604   *(r) = b = ind (mm, (y) >> ISAAC_LOG) + x \
605 )
606
607 /*
608  * Refill the entire R array, and update S.
609  */
610 static void
611 isaac_refill (struct isaac_state *s, word32 r[/* ISAAC_WORDS */])
612 {
613   register word32 a, b;         /* Caches of a and b */
614   register word32 x, y;         /* Temps needed by isaac_step macro */
615   register word32 *m = s->mm;   /* Pointer into state array */
616
617   a = s->a;
618   b = s->b + (++s->c);
619
620   do
621     {
622       isaac_step (a << 13, a, b, s->mm, m, ISAAC_WORDS / 2, r);
623       isaac_step (a >> 6, a, b, s->mm, m + 1, ISAAC_WORDS / 2, r + 1);
624       isaac_step (a << 2, a, b, s->mm, m + 2, ISAAC_WORDS / 2, r + 2);
625       isaac_step (a >> 16, a, b, s->mm, m + 3, ISAAC_WORDS / 2, r + 3);
626       r += 4;
627     }
628   while ((m += 4) < s->mm + ISAAC_WORDS / 2);
629   do
630     {
631       isaac_step (a << 13, a, b, s->mm, m, -ISAAC_WORDS / 2, r);
632       isaac_step (a >> 6, a, b, s->mm, m + 1, -ISAAC_WORDS / 2, r + 1);
633       isaac_step (a << 2, a, b, s->mm, m + 2, -ISAAC_WORDS / 2, r + 2);
634       isaac_step (a >> 16, a, b, s->mm, m + 3, -ISAAC_WORDS / 2, r + 3);
635       r += 4;
636     }
637   while ((m += 4) < s->mm + ISAAC_WORDS);
638   s->a = a;
639   s->b = b;
640 }
641
642 /*
643  * The basic seed-scrambling step for initialization, based on Bob
644  * Jenkins' 256-bit hash.
645  */
646 #define mix(a,b,c,d,e,f,g,h) \
647    (       a ^= b << 11, d += a, \
648    b += c, b ^= c >>  2, e += b, \
649    c += d, c ^= d <<  8, f += c, \
650    d += e, d ^= e >> 16, g += d, \
651    e += f, e ^= f << 10, h += e, \
652    f += g, f ^= g >>  4, a += f, \
653    g += h, g ^= h <<  8, b += g, \
654    h += a, h ^= a >>  9, c += h, \
655    a += b                        )
656
657 /* The basic ISAAC initialization pass.  */
658 static void
659 isaac_mix (struct isaac_state *s, word32 const seed[/* ISAAC_WORDS */])
660 {
661   int i;
662   word32 a = s->iv[0];
663   word32 b = s->iv[1];
664   word32 c = s->iv[2];
665   word32 d = s->iv[3];
666   word32 e = s->iv[4];
667   word32 f = s->iv[5];
668   word32 g = s->iv[6];
669   word32 h = s->iv[7];
670
671   for (i = 0; i < ISAAC_WORDS; i += 8)
672     {
673       a += seed[i];
674       b += seed[i + 1];
675       c += seed[i + 2];
676       d += seed[i + 3];
677       e += seed[i + 4];
678       f += seed[i + 5];
679       g += seed[i + 6];
680       h += seed[i + 7];
681
682       mix (a, b, c, d, e, f, g, h);
683
684       s->mm[i] = a;
685       s->mm[i + 1] = b;
686       s->mm[i + 2] = c;
687       s->mm[i + 3] = d;
688       s->mm[i + 4] = e;
689       s->mm[i + 5] = f;
690       s->mm[i + 6] = g;
691       s->mm[i + 7] = h;
692     }
693
694   s->iv[0] = a;
695   s->iv[1] = b;
696   s->iv[2] = c;
697   s->iv[3] = d;
698   s->iv[4] = e;
699   s->iv[5] = f;
700   s->iv[6] = g;
701   s->iv[7] = h;
702 }
703
704 #if 0 /* Provided for reference only; not used in this code */
705 /*
706  * Initialize the ISAAC RNG with the given seed material.
707  * Its size MUST be a multiple of ISAAC_BYTES, and may be
708  * stored in the s->mm array.
709  *
710  * This is a generalization of the original ISAAC initialization code
711  * to support larger seed sizes.  For seed sizes of 0 and ISAAC_BYTES,
712  * it is identical.
713  */
714 static void
715 isaac_init (struct isaac_state *s, word32 const *seed, size_t seedsize)
716 {
717   static word32 const iv[8] =
718   {
719     0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
720     0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119};
721   int i;
722
723 # if 0
724   /* The initialization of iv is a precomputed form of: */
725   for (i = 0; i < 7; i++)
726     iv[i] = 0x9e3779b9;         /* the golden ratio */
727   for (i = 0; i < 4; ++i)       /* scramble it */
728     mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
729 # endif
730   s->a = s->b = s->c = 0;
731
732   for (i = 0; i < 8; i++)
733     s->iv[i] = iv[i];
734
735   if (seedsize)
736     {
737       /* First pass (as in reference ISAAC code) */
738       isaac_mix (s, seed);
739       /* Second and subsequent passes (extension to ISAAC) */
740       while (seedsize -= ISAAC_BYTES)
741         {
742           seed += ISAAC_WORDS;
743           for (i = 0; i < ISAAC_WORDS; i++)
744             s->mm[i] += seed[i];
745           isaac_mix (s, s->mm);
746         }
747     }
748   else
749     {
750       /* The no seed case (as in reference ISAAC code) */
751       for (i = 0; i < ISAAC_WORDS; i++)
752         s->mm[i] = 0;
753     }
754
755   /* Final pass */
756   isaac_mix (s, s->mm);
757 }
758 #endif
759
760 /* Start seeding an ISAAC structire */
761 static void
762 isaac_seed_start (struct isaac_state *s)
763 {
764   static word32 const iv[8] =
765     {
766       0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
767       0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119
768     };
769   int i;
770
771 #if 0
772   /* The initialization of iv is a precomputed form of: */
773   for (i = 0; i < 7; i++)
774     iv[i] = 0x9e3779b9;         /* the golden ratio */
775   for (i = 0; i < 4; ++i)       /* scramble it */
776     mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
777 #endif
778   for (i = 0; i < 8; i++)
779     s->iv[i] = iv[i];
780   /* We could initialize s->mm to zero, but why bother? */
781
782   /* s->c gets used for a data pointer during the seeding phase */
783   s->a = s->b = s->c = 0;
784 }
785
786 /* Add a buffer of seed material */
787 static void
788 isaac_seed_data (struct isaac_state *s, void const *buf, size_t size)
789 {
790   unsigned char *p;
791   size_t avail;
792   size_t i;
793
794   avail = sizeof s->mm - (size_t) s->c; /* s->c is used as a write pointer */
795
796   /* Do any full buffers that are necessary */
797   while (size > avail)
798     {
799       p = (unsigned char *) s->mm + s->c;
800       for (i = 0; i < avail; i++)
801         p[i] ^= ((unsigned char const *) buf)[i];
802       buf = (char const *) buf + avail;
803       size -= avail;
804       isaac_mix (s, s->mm);
805       s->c = 0;
806       avail = sizeof s->mm;
807     }
808
809   /* And the final partial block */
810   p = (unsigned char *) s->mm + s->c;
811   for (i = 0; i < size; i++)
812     p[i] ^= ((unsigned char const *) buf)[i];
813   s->c = (word32) size;
814 }
815
816
817 /* End of seeding phase; get everything ready to produce output. */
818 static void
819 isaac_seed_finish (struct isaac_state *s)
820 {
821   isaac_mix (s, s->mm);
822   isaac_mix (s, s->mm);
823   /* Now reinitialize c to start things off right */
824   s->c = 0;
825 }
826 #define ISAAC_SEED(s,x) isaac_seed_data (s, &(x), sizeof (x))
827
828
829 #if __GNUC__ >= 2 && (__i386__ || __alpha__)
830 /*
831  * Many processors have very-high-resolution timer registers,
832  * The timer registers can be made inaccessible, so we have to deal with the
833  * possibility of SIGILL while we're working.
834  */
835 static jmp_buf env;
836 static RETSIGTYPE
837 sigill_handler (int signum)
838 {
839   (void) signum;
840   longjmp (env, 1);  /* Trivial, just return an indication that it happened */
841 }
842
843 /* FIXME: find a better way.
844    This signal-handling code may well end up being ripped out eventually.
845    An example of how fragile it is, on an i586-sco-sysv5uw7.0.1 system, with
846    gcc-2.95.3pl1, the "rdtsc" instruction causes a segmentation violation.
847    So now, the code catches SIGSEGV.  It'd probably be better to remove all
848    of that mess and find a better source of random data.  Patches welcome.  */
849
850 static void
851 isaac_seed_machdep (struct isaac_state *s)
852 {
853   RETSIGTYPE (*old_handler[2]) (int);
854
855   /* This is how one does try/except in C */
856   old_handler[0] = signal (SIGILL, sigill_handler);
857   old_handler[1] = signal (SIGSEGV, sigill_handler);
858   if (setjmp (env))  /* ANSI: Must be entire controlling expression */
859     {
860       signal (SIGILL, old_handler[0]);
861       signal (SIGSEGV, old_handler[1]);
862     }
863   else
864     {
865 # if __i386__
866       word32 t[2];
867       __asm__ __volatile__ ("rdtsc" : "=a" (t[0]), "=d" (t[1]));
868 # endif
869 # if __alpha__
870       unsigned long t;
871       __asm__ __volatile__ ("rpcc %0" : "=r" (t));
872 # endif
873 # if _ARCH_PPC
874       /* Code not used because this instruction is available only on first-
875          generation PPCs and evokes a SIGBUS on some Linux 2.4 kernels.  */
876       word32 t;
877       __asm__ __volatile__ ("mfspr %0,22" : "=r" (t));
878 # endif
879 # if __mips
880       /* Code not used because this is not accessible from userland */
881       word32 t;
882       __asm__ __volatile__ ("mfc0\t%0,$9" : "=r" (t));
883 # endif
884 # if __sparc__
885       /* This doesn't compile on all platforms yet.  How to fix? */
886       unsigned long t;
887       __asm__ __volatile__ ("rd %%tick, %0" : "=r" (t));
888 # endif
889      signal (SIGILL, old_handler[0]);
890      signal (SIGSEGV, old_handler[1]);
891      isaac_seed_data (s, &t, sizeof t);
892   }
893 }
894
895 #else /* !(__i386__ || __alpha__) */
896
897 /* Do-nothing stub */
898 # define isaac_seed_machdep(s) (void) 0
899
900 #endif /* !(__i386__ || __alpha__) */
901
902
903 /*
904  * Get seed material.  16 bytes (128 bits) is plenty, but if we have
905  * /dev/urandom, we get 32 bytes = 256 bits for complete overkill.
906  */
907 static void
908 isaac_seed (struct isaac_state *s)
909 {
910   isaac_seed_start (s);
911
912   { pid_t t = getpid ();   ISAAC_SEED (s, t); }
913   { pid_t t = getppid ();  ISAAC_SEED (s, t); }
914   { uid_t t = getuid ();   ISAAC_SEED (s, t); }
915   { gid_t t = getgid ();   ISAAC_SEED (s, t); }
916
917   {
918 #if HAVE_GETHRTIME
919     hrtime_t t = gethrtime ();
920     ISAAC_SEED (s, t);
921 #else
922 # if HAVE_CLOCK_GETTIME         /* POSIX ns-resolution */
923     struct timespec t;
924     clock_gettime (CLOCK_REALTIME, &t);
925 # else
926 #  if HAVE_GETTIMEOFDAY
927     struct timeval t;
928     gettimeofday (&t, (struct timezone *) 0);
929 #  else
930     time_t t;
931     t = time ((time_t *) 0);
932 #  endif
933 # endif
934 #endif
935     ISAAC_SEED (s, t);
936   }
937
938   isaac_seed_machdep (s);
939
940   {
941     char buf[32];
942     int fd = open ("/dev/urandom", O_RDONLY | O_NOCTTY);
943     if (fd >= 0)
944       {
945         read (fd, buf, 32);
946         close (fd);
947         isaac_seed_data (s, buf, 32);
948       }
949     else
950       {
951         fd = open ("/dev/random", O_RDONLY | O_NONBLOCK | O_NOCTTY);
952         if (fd >= 0)
953           {
954             /* /dev/random is more precious, so use less */
955             read (fd, buf, 16);
956             close (fd);
957             isaac_seed_data (s, buf, 16);
958           }
959       }
960   }
961
962   isaac_seed_finish (s);
963 }
964
965 /* Single-word RNG built on top of ISAAC */
966 struct irand_state
967 {
968   word32 r[ISAAC_WORDS];
969   unsigned numleft;
970   struct isaac_state *s;
971 };
972
973 static void
974 irand_init (struct irand_state *r, struct isaac_state *s)
975 {
976   r->numleft = 0;
977   r->s = s;
978 }
979
980 /*
981  * We take from the end of the block deliberately, so if we need
982  * only a small number of values, we choose the final ones which are
983  * marginally better mixed than the initial ones.
984  */
985 static word32
986 irand32 (struct irand_state *r)
987 {
988   if (!r->numleft)
989     {
990       isaac_refill (r->s, r->r);
991       r->numleft = ISAAC_WORDS;
992     }
993   return r->r[--r->numleft];
994 }
995
996 /*
997  * Return a uniformly distributed random number between 0 and n,
998  * inclusive.  Thus, the result is modulo n+1.
999  *
1000  * Theory of operation: as x steps through every possible 32-bit number,
1001  * x % n takes each value at least 2^32 / n times (rounded down), but
1002  * the values less than 2^32 % n are taken one additional time.  Thus,
1003  * x % n is not perfectly uniform.  To fix this, the values of x less
1004  * than 2^32 % n are disallowed, and if the RNG produces one, we ask
1005  * for a new value.
1006  */
1007 static word32
1008 irand_mod (struct irand_state *r, word32 n)
1009 {
1010   word32 x;
1011   word32 lim;
1012
1013   if (!++n)
1014     return irand32 (r);
1015
1016   lim = -n % n;                 /* == (2**32-n) % n == 2**32 % n */
1017   do
1018     {
1019       x = irand32 (r);
1020     }
1021   while (x < lim);
1022   return x % n;
1023 }
1024
1025 /*
1026  * Fill a buffer with a fixed pattern.
1027  *
1028  * The buffer must be at least 3 bytes long, even if
1029  * size is less.  Larger sizes are filled exactly.
1030  */
1031 static void
1032 fillpattern (int type, unsigned char *r, size_t size)
1033 {
1034   size_t i;
1035   unsigned bits = type & 0xfff;
1036
1037   bits |= bits << 12;
1038   ((unsigned char *) r)[0] = (bits >> 4) & 255;
1039   ((unsigned char *) r)[1] = (bits >> 8) & 255;
1040   ((unsigned char *) r)[2] = bits & 255;
1041   for (i = 3; i < size / 2; i *= 2)
1042     memcpy ((char *) r + i, (char *) r, i);
1043   if (i < size)
1044     memcpy ((char *) r + i, (char *) r, size - i);
1045
1046   /* Invert the first bit of every 512-byte sector. */
1047   if (type & 0x1000)
1048     for (i = 0; i < size; i += 512)
1049       r[i] ^= 0x80;
1050 }
1051
1052 /*
1053  * Fill a buffer, R (of size SIZE_MAX), with random data.
1054  * SIZE is rounded UP to a multiple of ISAAC_BYTES.
1055  */
1056 static void
1057 fillrand (struct isaac_state *s, word32 *r, size_t size_max, size_t size)
1058 {
1059   size = (size + ISAAC_BYTES - 1) / ISAAC_BYTES;
1060   assert (size <= size_max);
1061
1062   while (size--)
1063     {
1064       isaac_refill (s, r);
1065       r += ISAAC_WORDS;
1066     }
1067 }
1068
1069 /*
1070  * Generate a 6-character (+ nul) pass name string
1071  * FIXME: allow translation of "random".
1072  */
1073 #define PASS_NAME_SIZE 7
1074 static void
1075 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
1076 {
1077   if (data)
1078     sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
1079   else
1080     memcpy (name, "random", PASS_NAME_SIZE);
1081 }
1082
1083 /*
1084  * Do pass number k of n, writing "size" bytes of the given pattern "type"
1085  * to the file descriptor fd.   Qname, k and n are passed in only for verbose
1086  * progress message purposes.  If n == 0, no progress messages are printed.
1087  *
1088  * If *sizep == -1, the size is unknown, and it will be filled in as soon
1089  * as writing fails.
1090  */
1091 static int
1092 dopass (int fd, char const *qname, off_t *sizep, int type,
1093         struct isaac_state *s, unsigned long k, unsigned long n)
1094 {
1095   off_t size = *sizep;
1096   off_t offset;                 /* Current file posiiton */
1097   off_t thresh;                 /* Offset to print next status update */
1098   size_t lim;                   /* Amount of data to try writing */
1099   size_t soff;                  /* Offset into buffer for next write */
1100   ssize_t ssize;                /* Return value from write */
1101 #if ISAAC_WORDS > 1024
1102   word32 r[ISAAC_WORDS * 3];    /* Multiple of 4K and of pattern size */
1103 #else
1104   word32 r[1024 * 3];           /* Multiple of 4K and of pattern size */
1105 #endif
1106   char pass_string[PASS_NAME_SIZE];     /* Name of current pass */
1107
1108   if (lseek (fd, (off_t) 0, SEEK_SET) == -1)
1109     {
1110       error (0, errno, _("%s: cannot rewind"), qname);
1111       return -1;
1112     }
1113
1114   /* Constant fill patterns need only be set up once. */
1115   if (type >= 0)
1116     {
1117       lim = sizeof r;
1118       if ((off_t) lim > size && size != -1)
1119         {
1120           lim = (size_t) size;
1121         }
1122       fillpattern (type, (unsigned char *) r, lim);
1123       passname ((unsigned char *) r, pass_string);
1124     }
1125   else
1126     {
1127       passname (0, pass_string);
1128     }
1129
1130   /* Set position if first status update */
1131   thresh = 0;
1132   if (n)
1133     {
1134       error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
1135       thresh = VERBOSE_UPDATE;
1136       if (thresh > size && size != -1)
1137         thresh = size;
1138     }
1139
1140   offset = 0;
1141   for (;;)
1142     {
1143       /* How much to write this time? */
1144       lim = sizeof r;
1145       if ((off_t) lim > size - offset && size != -1)
1146         {
1147           if (size < offset)
1148             break;
1149           lim = (size_t) (size - offset);
1150           if (!lim)
1151             break;
1152         }
1153       if (type < 0)
1154         fillrand (s, r, sizeof r, lim);
1155       /* Loop to retry partial writes. */
1156       for (soff = 0; soff < lim; soff += ssize)
1157         {
1158           ssize = write (fd, (char *) r + soff, lim - soff);
1159           if (ssize <= 0)
1160             {
1161               if ((ssize == 0 || errno == ENOSPC)
1162                   && size == -1)
1163                 {
1164                   /* Ah, we have found the end of the file */
1165                   *sizep = thresh = size = offset + soff;
1166                   break;
1167                 }
1168               else
1169                 {
1170                   int errnum = errno;
1171                   char buf[LONGEST_HUMAN_READABLE + 1];
1172                   error (0, errnum, _("%s: error writing at offset %s"),
1173                          qname,
1174                          human_readable ((uintmax_t) (offset + soff),
1175                                          buf, 1, 1));
1176                   /*
1177                    * I sometimes use shred on bad media, before throwing it
1178                    * out.  Thus, I don't want it to give up on bad blocks.
1179                    * This code assumes 512-byte blocks and tries to skip
1180                    * over them.  It works because lim is always a multiple
1181                    * of 512, except at the end.
1182                    */
1183                   if (errnum == EIO && soff % 512 == 0 && lim >= soff + 512
1184                       && size != -1)
1185                     {
1186                       if (lseek (fd, (off_t) (offset + soff + 512), SEEK_SET)
1187                           != -1)
1188                         {
1189                           soff += 512;
1190                           continue;
1191                         }
1192                       error (0, errno, "%s: lseek", qname);
1193                     }
1194                   return -1;
1195                 }
1196             }
1197         }
1198
1199       /* Okay, we have written "lim" bytes. */
1200
1201       if (offset + lim < offset)
1202         {
1203           error (0, 0, _("%s: file too large"), qname);
1204           return -1;
1205         }
1206
1207       offset += lim;
1208
1209       /* Time to print progress? */
1210       if (offset >= thresh && n)
1211         {
1212           char offset_buf[LONGEST_HUMAN_READABLE + 1];
1213           char size_buf[LONGEST_HUMAN_READABLE + 1];
1214           char const *human_offset
1215             = human_readable ((uintmax_t) offset, offset_buf, 1,
1216                               OUTPUT_BLOCK_SIZE);
1217           if (size != -1)
1218             error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s"), qname, k, n,
1219                    pass_string, human_offset,
1220                    human_readable ((uintmax_t) size, size_buf, 1,
1221                                    OUTPUT_BLOCK_SIZE));
1222           else
1223             error (0, 0, _("%s: pass %lu/%lu (%s)...%s"), qname, k, n,
1224                    pass_string, human_offset);
1225
1226           thresh += VERBOSE_UPDATE;
1227           if (thresh > size && size != -1)
1228             thresh = size;
1229           /*
1230            * Force periodic syncs to keep displayed progress accurate
1231            * FIXME: Should these be present even if -v is not enabled,
1232            * to keep the buffer cache from filling with dirty pages?
1233            * It's a common problem with programs that do lots of writes,
1234            * like mkfs.
1235            */
1236           if (fdatasync (fd) < 0 && fsync (fd) < 0)
1237             {
1238               error (0, errno, "%s: fsync", qname);
1239               return -1;
1240             }
1241         }
1242     }
1243
1244   /* Force what we just wrote to hit the media. */
1245   if (fdatasync (fd) < 0 && fsync (fd) < 0)
1246     {
1247       error (0, errno, "%s: fsync", qname);
1248       return -1;
1249     }
1250   return 0;
1251 }
1252
1253 /*
1254  * The passes start and end with a random pass, and the passes in between
1255  * are done in random order.  The idea is to deprive someone trying to
1256  * reverse the process of knowledge of the overwrite patterns, so they
1257  * have the additional step of figuring out what was done to the disk
1258  * before they can try to reverse or cancel it.
1259  *
1260  * First, all possible 1-bit patterns.  There are two of them.
1261  * Then, all possible 2-bit patterns.  There are four, but the two
1262  * which are also 1-bit patterns can be omitted.
1263  * Then, all possible 3-bit patterns.  Likewise, 8-2 = 6.
1264  * Then, all possible 4-bit patterns.  16-4 = 12.
1265  *
1266  * The basic passes are:
1267  * 1-bit: 0x000, 0xFFF
1268  * 2-bit: 0x555, 0xAAA
1269  * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
1270  *        100100100100         110110110110
1271  *           9   2   4            D   B   6
1272  * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
1273  *        0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
1274  * Adding three random passes at the beginning, middle and end
1275  * produces the default 25-pass structure.
1276  *
1277  * The next extension would be to 5-bit and 6-bit patterns.
1278  * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
1279  * 6-bit patterns, so they would increase the time required
1280  * significantly.  4-bit patterns are enough for most purposes.
1281  *
1282  * The main gotcha is that this would require a trickier encoding,
1283  * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
1284  * lcm(2,3,4,5) = 60 bits is not.
1285  *
1286  * One extension that is included is to complement the first bit in each
1287  * 512-byte block, to alter the phase of the encoded data in the more
1288  * complex encodings.  This doesn't apply to MFM, so the 1-bit patterns
1289  * are considered part of the 3-bit ones and the 2-bit patterns are
1290  * considered part of the 4-bit patterns.
1291  *
1292  *
1293  * How does the generalization to variable numbers of passes work?
1294  *
1295  * Here's how...
1296  * Have an ordered list of groups of passes.  Each group is a set.
1297  * Take as many groups as will fit, plus a random subset of the
1298  * last partial group, and place them into the passes list.
1299  * Then shuffle the passes list into random order and use that.
1300  *
1301  * One extra detail: if we can't include a large enough fraction of the
1302  * last group to be interesting, then just substitute random passes.
1303  *
1304  * If you want more passes than the entire list of groups can
1305  * provide, just start repeating from the beginning of the list.
1306  */
1307 static int const
1308   patterns[] =
1309 {
1310   -2,                           /* 2 random passes */
1311   2, 0x000, 0xFFF,              /* 1-bit */
1312   2, 0x555, 0xAAA,              /* 2-bit */
1313   -1,                           /* 1 random pass */
1314   6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6,  /* 3-bit */
1315   12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
1316   0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE,     /* 4-bit */
1317   -1,                           /* 1 random pass */
1318         /* The following patterns have the frst bit per block flipped */
1319   8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
1320   14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
1321   0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
1322   -1,                           /* 1 random pass */
1323   0                             /* End */
1324 };
1325
1326 /*
1327  * Generate a random wiping pass pattern with num passes.
1328  * This is a two-stage process.  First, the passes to include
1329  * are chosen, and then they are shuffled into the desired
1330  * order.
1331  */
1332 static void
1333 genpattern (int *dest, size_t num, struct isaac_state *s)
1334 {
1335   struct irand_state r;
1336   size_t randpasses;
1337   int const *p;
1338   int *d;
1339   size_t n;
1340   size_t accum, top, swap;
1341   int k;
1342
1343   if (!num)
1344     return;
1345
1346   irand_init (&r, s);
1347
1348   /* Stage 1: choose the passes to use */
1349   p = patterns;
1350   randpasses = 0;
1351   d = dest;                     /* Destination for generated pass list */
1352   n = num;                      /* Passes remaining to fill */
1353
1354   for (;;)
1355     {
1356       k = *p++;                 /* Block descriptor word */
1357       if (!k)
1358         {                       /* Loop back to the beginning */
1359           p = patterns;
1360         }
1361       else if (k < 0)
1362         {                       /* -k random passes */
1363           k = -k;
1364           if ((size_t) k >= n)
1365             {
1366               randpasses += n;
1367               n = 0;
1368               break;
1369             }
1370           randpasses += k;
1371           n -= k;
1372         }
1373       else if ((size_t) k <= n)
1374         {                       /* Full block of patterns */
1375           memcpy (d, p, k * sizeof (int));
1376           p += k;
1377           d += k;
1378           n -= k;
1379         }
1380       else if (n < 2 || 3 * n < (size_t) k)
1381         {                       /* Finish with random */
1382           randpasses += n;
1383           break;
1384         }
1385       else
1386         {                       /* Pad out with k of the n available */
1387           do
1388             {
1389               if (n == (size_t) k-- || irand_mod (&r, k) < n)
1390                 {
1391                   *d++ = *p;
1392                   n--;
1393                 }
1394               p++;
1395             }
1396           while (n);
1397           break;
1398         }
1399     }
1400   top = num - randpasses;       /* Top of initialized data */
1401   /* assert (d == dest+top); */
1402
1403   /*
1404    * We now have fixed patterns in the dest buffer up to
1405    * "top", and we need to scramble them, with "randpasses"
1406    * random passes evenly spaced among them.
1407    *
1408    * We want one at the beginning, one at the end, and
1409    * evenly spaced in between.  To do this, we basically
1410    * use Bresenham's line draw (a.k.a DDA) algorithm
1411    * to draw a line with slope (randpasses-1)/(num-1).
1412    * (We use a positive accumulator and count down to
1413    * do this.)
1414    *
1415    * So for each desired output value, we do the following:
1416    * - If it should be a random pass, copy the pass type
1417    *   to top++, out of the way of the other passes, and
1418    *   set the current pass to -1 (random).
1419    * - If it should be a normal pattern pass, choose an
1420    *   entry at random between here and top-1 (inclusive)
1421    *   and swap the current entry with that one.
1422    */
1423   randpasses--;                 /* To speed up later math */
1424   accum = randpasses;           /* Bresenham DDA accumulator */
1425   for (n = 0; n < num; n++)
1426     {
1427       if (accum <= randpasses)
1428         {
1429           accum += num - 1;
1430           dest[top++] = dest[n];
1431           dest[n] = -1;
1432         }
1433       else
1434         {
1435           swap = n + irand_mod (&r, top - n - 1);
1436           k = dest[n];
1437           dest[n] = dest[swap];
1438           dest[swap] = k;
1439         }
1440       accum -= randpasses;
1441     }
1442   /* assert (top == num); */
1443
1444   memset (&r, 0, sizeof r);     /* Wipe this on general principles */
1445 }
1446
1447 /*
1448  * The core routine to actually do the work.  This overwrites the first
1449  * size bytes of the given fd.  Returns -1 on error, 0 on success.
1450  */
1451 static int
1452 do_wipefd (int fd, char const *qname, struct isaac_state *s,
1453            struct Options const *flags)
1454 {
1455   size_t i;
1456   struct stat st;
1457   off_t size;                   /* Size to write, size to read */
1458   unsigned long n;              /* Number of passes for printing purposes */
1459   int *passarray;
1460
1461   n = 0;                /* dopass takes n -- 0 to mean "don't print progress" */
1462   if (flags->verbose)
1463     n = flags->n_iterations + ((flags->zero_fill) != 0);
1464
1465   if (fstat (fd, &st))
1466     {
1467       error (0, errno, "%s: fstat", qname);
1468       return -1;
1469     }
1470
1471   /* If we know that we can't possibly shred the file, give up now.
1472      Otherwise, we may go into a infinite loop writing data before we
1473      find that we can't rewind the device.  */
1474   if ((S_ISCHR (st.st_mode) && isatty (fd))
1475       || S_ISFIFO (st.st_mode)
1476       || S_ISSOCK (st.st_mode))
1477     {
1478       error (0, 0, _("%s: invalid file type"), qname);
1479       return -1;
1480     }
1481
1482   /* Allocate pass array */
1483   passarray = xmalloc (flags->n_iterations * sizeof (int));
1484
1485   size = flags->size;
1486   if (size == -1)
1487     {
1488       /* Accept a length of zero only if it's a regular file.
1489          For any other type of file, try to get the size another way.  */
1490       if (S_ISREG (st.st_mode))
1491         {
1492           size = st.st_size;
1493           if (size < 0)
1494             {
1495               error (0, 0, _("%s: file has negative size"), qname);
1496               return -1;
1497             }
1498         }
1499       else
1500         {
1501           size = lseek (fd, (off_t) 0, SEEK_END);
1502           if (size <= 0)
1503             {
1504               /* We are unable to determine the length, up front.
1505                  Let dopass do that as part of its first iteration.  */
1506               size = -1;
1507             }
1508         }
1509
1510       if (0 <= size && !(flags->exact))
1511         {
1512           size += ST_BLKSIZE (st) - 1 - (size - 1) % ST_BLKSIZE (st);
1513
1514           /* If in rounding up, we've just overflowed, use the maximum.  */
1515           if (size < 0)
1516             size = TYPE_MAXIMUM (off_t);
1517         }
1518     }
1519
1520   /* Schedule the passes in random order. */
1521   genpattern (passarray, flags->n_iterations, s);
1522
1523   /* Do the work */
1524   for (i = 0; i < flags->n_iterations; i++)
1525     {
1526       if (dopass (fd, qname, &size, passarray[i], s, i + 1, n) < 0)
1527         {
1528           memset (passarray, 0, flags->n_iterations * sizeof (int));
1529           free (passarray);
1530           return -1;
1531         }
1532     }
1533
1534   memset (passarray, 0, flags->n_iterations * sizeof (int));
1535   free (passarray);
1536
1537   if (flags->zero_fill)
1538     if (dopass (fd, qname, &size, 0, s, flags->n_iterations + 1, n) < 0)
1539       return -1;
1540
1541   /* Okay, now deallocate the data.  The effect of ftruncate on
1542      non-regular files is unspecified, so don't worry about any
1543      errors reported for them.  */
1544   if (flags->remove_file && ftruncate (fd, (off_t) 0) != 0
1545       && S_ISREG (st.st_mode))
1546     {
1547       error (0, errno, _("%s: error truncating"), qname);
1548       return -1;
1549     }
1550
1551   return 0;
1552 }
1553
1554 /* A wrapper with a little more checking for fds on the command line */
1555 static int
1556 wipefd (int fd, char const *qname, struct isaac_state *s,
1557         struct Options const *flags)
1558 {
1559   int fd_flags = fcntl (fd, F_GETFL);
1560
1561   if (fd_flags < 0)
1562     {
1563       error (0, errno, "%s: fcntl", qname);
1564       return -1;
1565     }
1566   if (fd_flags & O_APPEND)
1567     {
1568       error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
1569       return -1;
1570     }
1571   return do_wipefd (fd, qname, s, flags);
1572 }
1573
1574 /* --- Name-wiping code --- */
1575
1576 /* Characters allowed in a file name - a safe universal set. */
1577 static char const nameset[] =
1578 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_+=%@#.";
1579
1580 /*
1581  * This increments the name, considering it as a big-endian base-N number
1582  * with the digits taken from nameset.  Characters not in the nameset
1583  * are considered to come before nameset[0].
1584  *
1585  * It's not obvious, but this will explode if name[0..len-1] contains
1586  * any 0 bytes.
1587  *
1588  * This returns the carry (1 on overflow).
1589  */
1590 static int
1591 incname (char *name, unsigned len)
1592 {
1593   char const *p;
1594
1595   if (!len)
1596     return 1;
1597
1598   p = strchr (nameset, name[--len]);
1599   /* If the character is not found, replace it with a 0 digit */
1600   if (!p)
1601     {
1602       name[len] = nameset[0];
1603       return 0;
1604     }
1605   /* If this character has a successor, use it */
1606   if (p[1])
1607     {
1608       name[len] = p[1];
1609       return 0;
1610     }
1611   /* Otherwise, set this digit to 0 and increment the prefix */
1612   name[len] = nameset[0];
1613   return incname (name, len);
1614 }
1615
1616 /*
1617  * Repeatedly rename a file with shorter and shorter names,
1618  * to obliterate all traces of the file name on any system that
1619  * adds a trailing delimiter to on-disk file names and reuses
1620  * the same directory slot.  Finally, unlink it.
1621  * The passed-in filename is modified in place to the new filename.
1622  * (Which is unlinked if this function succeeds, but is still present if
1623  * it fails for some reason.)
1624  *
1625  * The main loop is written carefully to not get stuck if all possible
1626  * names of a given length are occupied.  It counts down the length from
1627  * the original to 0.  While the length is non-zero, it tries to find an
1628  * unused file name of the given length.  It continues until either the
1629  * name is available and the rename succeeds, or it runs out of names
1630  * to try (incname wraps and returns 1).  Finally, it unlinks the file.
1631  *
1632  * The unlink is Unix-specific, as ANSI-standard remove has more
1633  * portability problems with C libraries making it "safe".  rename
1634  * is ANSI-standard.
1635  *
1636  * To force the directory data out, we try to open the directory and
1637  * invoke fdatasync on it.  This is rather non-standard, so we don't
1638  * insist that it works, just fall back to a global sync in that case.
1639  * This is fairly significantly Unix-specific.  Of course, on any
1640  * filesystem with synchronous metadata updates, this is unnecessary.
1641  */
1642 static int
1643 wipename (char *oldname, char const *qoldname, struct Options const *flags)
1644 {
1645   char *newname, *base;   /* Base points to filename part of newname */
1646   unsigned len;
1647   int err;
1648   int dir_fd;                   /* Try to open directory to sync *it* */
1649
1650   newname = xstrdup (oldname);
1651   if (flags->verbose)
1652     error (0, 0, _("%s: removing"), qoldname);
1653
1654   /* Find the file name portion */
1655   base = strrchr (newname, '/');
1656   /* Temporary hackery to get a directory fd */
1657   if (base)
1658     {
1659       *base = '\0';
1660       dir_fd = open (newname, O_RDONLY | O_NOCTTY);
1661       *base = '/';
1662     }
1663   else
1664     {
1665       dir_fd = open (".", O_RDONLY | O_NOCTTY);
1666     }
1667   base = base ? base + 1 : newname;
1668   len = strlen (base);
1669
1670   while (len)
1671     {
1672       memset (base, nameset[0], len);
1673       base[len] = 0;
1674       do
1675         {
1676           struct stat st;
1677           if (lstat (newname, &st) < 0)
1678             {
1679               if (rename (oldname, newname) == 0)
1680                 {
1681                   if (dir_fd < 0
1682                       || (fdatasync (dir_fd) < 0 && fsync (dir_fd) < 0))
1683                     sync ();    /* Force directory out */
1684                   if (flags->verbose)
1685                     {
1686                       /*
1687                        * People seem to understand this better than talking
1688                        * about renaming oldname.  newname doesn't need
1689                        * quoting because we picked it.
1690                        */
1691                       error (0, 0, _("%s: renamed to %s"), qoldname,
1692                              quote (newname));
1693                     }
1694                   memcpy (oldname + (base - newname), base, len + 1);
1695                   break;
1696                 }
1697               else
1698                 {
1699                   /* The rename failed: give up on this length.  */
1700                   break;
1701                 }
1702             }
1703           else
1704             {
1705               /* newname exists, so increment BASE so we use another */
1706             }
1707         }
1708       while (!incname (base, len));
1709       len--;
1710     }
1711   free (newname);
1712   err = unlink (oldname);
1713   if (dir_fd < 0 || (fdatasync (dir_fd) < 0 && fsync (dir_fd) < 0))
1714     sync ();
1715   close (dir_fd);
1716   if (!err && flags->verbose)
1717     error (0, 0, _("%s: removed"), qoldname);
1718   return err;
1719 }
1720
1721 /*
1722  * Finally, the function that actually takes a filename and grinds
1723  * it into hamburger.
1724  *
1725  * FIXME
1726  * Detail to note: since we do not restore errno to EACCES after
1727  * a failed chmod, we end up printing the error code from the chmod.
1728  * This is actually the error that stopped us from proceeding, so
1729  * it's arguably the right one, and in practice it'll be either EACCES
1730  * again or EPERM, which both give similar error messages.
1731  * Does anyone disagree?
1732  */
1733 static int
1734 wipefile (char *name, char const *qname,
1735           struct isaac_state *s, struct Options const *flags)
1736 {
1737   int err, fd;
1738
1739   fd = open (name, O_WRONLY | O_NOCTTY);
1740   if (fd < 0)
1741     {
1742       if (errno == EACCES && flags->force)
1743         {
1744           if (chmod (name, S_IWUSR) >= 0) /* 0200, user-write-only */
1745             fd = open (name, O_WRONLY | O_NOCTTY);
1746         }
1747       else if ((errno == ENOENT || errno == ENOTDIR)
1748                && strncmp (name, "/dev/fd/", 8) == 0)
1749         {
1750           /* We accept /dev/fd/# even if the OS doesn't support it */
1751           int errnum = errno;
1752           unsigned long num;
1753           char *p;
1754           errno = 0;
1755           num = strtoul (name + 8, &p, 10);
1756           /* If it's completely decimal with no leading zeros... */
1757           if (errno == 0 && !*p && num <= INT_MAX &&
1758               (('1' <= name[8] && name[8] <= '9')
1759                || (name[8] == '0' && !name[9])))
1760             {
1761               return wipefd ((int) num, qname, s, flags);
1762             }
1763           errno = errnum;
1764         }
1765     }
1766   if (fd < 0)
1767     {
1768       error (0, errno, "%s", qname);
1769       return -1;
1770     }
1771
1772   err = do_wipefd (fd, qname, s, flags);
1773   if (close (fd) != 0)
1774     {
1775       error (0, 0, "%s: close", qname);
1776       err = -1;
1777     }
1778   if (err == 0 && flags->remove_file)
1779     {
1780       err = wipename (name, qname, flags);
1781       if (err < 0)
1782         error (0, 0, _("%s: cannot remove"), qname);
1783     }
1784   return err;
1785 }
1786
1787 int
1788 main (int argc, char **argv)
1789 {
1790   struct isaac_state s;
1791   int err = 0;
1792   struct Options flags;
1793   char **file;
1794   int n_files;
1795   int c;
1796   int i;
1797
1798   program_name = argv[0];
1799   setlocale (LC_ALL, "");
1800   bindtextdomain (PACKAGE, LOCALEDIR);
1801   textdomain (PACKAGE);
1802
1803   atexit (close_stdout);
1804
1805   GETTIMEOFDAY_INIT ();
1806
1807   isaac_seed (&s);
1808
1809   memset (&flags, 0, sizeof flags);
1810
1811   flags.n_iterations = DEFAULT_PASSES;
1812   flags.size = -1;
1813
1814   while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1815     {
1816       switch (c)
1817         {
1818         case 0:
1819           break;
1820
1821         case 'f':
1822           flags.force = 1;
1823           break;
1824
1825         case 'n':
1826           {
1827             uintmax_t tmp;
1828             if (xstrtoumax (optarg, NULL, 10, &tmp, NULL) != LONGINT_OK
1829                 || (word32) tmp != tmp
1830                 || ((size_t) (tmp * sizeof (int)) / sizeof (int) != tmp))
1831               {
1832                 error (1, 0, _("%s: invalid number of passes"),
1833                        quotearg_colon (optarg));
1834               }
1835             flags.n_iterations = (size_t) tmp;
1836           }
1837           break;
1838
1839         case 'u':
1840           flags.remove_file = 1;
1841           break;
1842
1843         case 's':
1844           {
1845             uintmax_t tmp;
1846             if (xstrtoumax (optarg, NULL, 0, &tmp, "cbBkMGTPEZY0")
1847                 != LONGINT_OK)
1848               {
1849                 error (1, 0, _("%s: invalid file size"),
1850                        quotearg_colon (optarg));
1851               }
1852             flags.size = tmp;
1853           }
1854           break;
1855
1856         case 'v':
1857           flags.verbose = 1;
1858           break;
1859
1860         case 'x':
1861           flags.exact = 1;
1862           break;
1863
1864         case 'z':
1865           flags.zero_fill = 1;
1866           break;
1867
1868         case_GETOPT_HELP_CHAR;
1869
1870         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1871
1872         default:
1873           usage (1);
1874         }
1875     }
1876
1877   file = argv + optind;
1878   n_files = argc - optind;
1879
1880   if (n_files == 0)
1881     {
1882       error (0, 0, _("missing file argument"));
1883       usage (1);
1884     }
1885
1886   for (i = 0; i < n_files; i++)
1887     {
1888       char const *qname = quotearg_colon (file[i]);
1889       if (strcmp (file[i], "-") == 0)
1890         {
1891           if (wipefd (STDOUT_FILENO, qname, &s, &flags) < 0)
1892             err = 1;
1893         }
1894       else
1895         {
1896           /* Plain filename - Note that this overwrites *argv! */
1897           if (wipefile (file[i], qname, &s, &flags) < 0)
1898             err = 1;
1899         }
1900     }
1901
1902   /* Just on general principles, wipe s. */
1903   memset (&s, 0, sizeof s);
1904
1905   exit (err);
1906 }
1907 /*
1908  * vim:sw=2:sts=2:
1909  */