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