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