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