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