*** empty log message ***
[coreutils.git] / src / shred.c
blobe8b7c8d0807cab12f50cda8ce71e6a2945f0ee3e
1 /* TODO:
2 - use consistent non-capitalization in error messages
3 - add standard GNU copyleft comment
5 - Add -r/-R/--recursive
6 - Add -i/--interactive
7 - Reserve -d
8 - Add -L
9 - Deal with the amazing variety of gettimeofday() implementation bugs.
10 (Some systems use a one-arg form; still others insist that the timezone
11 either be NULL or be non-NULL. Whee.)
12 - Add an unlink-all option to emulate rm.
16 * shred.c - by Colin Plumb.
18 * Do a securer overwrite of given files or devices, to make it harder
19 * for even very expensive hardware probing to recover the data.
21 * Although this process is also known as "wiping", I prefer the longer
22 * name both because I think it is more evocative of what is happening and
23 * because a longer name conveys a more appropriate sense of deliberateness.
25 * For the theory behind this, see "Secure Deletion of Data from Magnetic
26 * and Solid-State Memory", on line at
27 * http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html
29 * Just for the record, reversing one or two passes of disk overwrite
30 * is not terribly difficult with hardware help. Hook up a good-quality
31 * digitizing oscilloscope to the output of the head preamplifier and copy
32 * the high-res digitized data to a computer for some off-line analysis.
33 * Read the "current" data and average all the pulses together to get an
34 * "average" pulse on the disk. Subtract this average pulse from all of
35 * the actual pulses and you can clearly see the "echo" of the previous
36 * data on the disk.
38 * Real hard drives have to balance the cost of the media, the head,
39 * and the read circuitry. They use better-quality media than absolutely
40 * necessary to limit the cost of the read circuitry. By throwing that
41 * assumption out, and the assumption that you want the data processed
42 * as fast as the hard drive can spin, you can do better.
44 * If asked to wipe a file, this also unlinks it, renaming it to in a
45 * clever way to try to leave no trace of the original filename.
47 * Copyright 1997, 1998, 1999 Colin Plumb <colin@nyx.net>. This program
48 * may be freely distributed under the terms of the GNU GPL, the BSD license,
49 * or Larry Wall's "Artistic License" Even if you use the BSD license,
50 * which does not require it, I'd really like to get improvements back.
52 * The ISAAC code still bears some resemblance to the code written
53 * by Bob Jenkins, but he permits pretty unlimited use.
55 * This was inspired by a desire to improve on some code titled:
56 * Wipe V1.0-- Overwrite and delete files. S. 2/3/96
57 * but I've rewritten everything here so completely that no trace of
58 * the original remains.
60 * Thanks to:
61 * Bob Jenkins, for his good RNG work and patience with the FSF copyright
62 * paperwork.
63 * Jim Meyering, for his work merging this into the GNU fileutils while
64 * still letting me feel a sense of ownership and pride. Getting me to
65 * tolerate the GNU brace style was quite a feat of diplomacy.
66 * Paul Eggert, for lots of useful discussion and code. I disagree with
67 * an awful lot of his suggestions, but they're disagreements worth having.
69 * Things to think about:
70 * - Security: Is there any risk to the race
71 * between overwriting and unlinking a file? Will it do anything
72 * drastically bad if told to attack a named pipe or socket?
75 /* The official name of this program (e.g., no `g' prefix). */
76 #define PROGRAM_NAME "shred"
78 #define AUTHORS "Colin Plumb"
80 #if HAVE_CONFIG_H
81 # include <config.h>
82 #endif
84 #include <getopt.h>
85 #include <stdio.h>
86 #include <setjmp.h>
87 #include <signal.h>
89 #if HAVE_CONFIG_H
90 /* Default fileutils build */
91 # include "system.h"
92 # include "xstrtol.h"
93 # include "closeout.h"
94 # include "error.h"
95 # include "human.h"
96 # include "quotearg.h" /* For quotearg_colon */
97 # include "xalloc.h"
98 char *xstrdup PARAMS ((char const *));
100 #else /* !HAVE_CONFIG_H */
102 * Standalone build - this file compiles by itself without autoconf and
103 * the like. No i18n, and I still have to write a stub for getopt_long,
104 * but it's a lot less intertwingled than the usual GNU utilities.
107 # include <ctype.h> /* For isprint */
108 # include <string.h> /* For memcpy, strerror */
109 # include <limits.h> /* For ULONG_MAX etc. */
110 # include <stdlib.h> /* For strtoul, EXIT_FAILURE */
111 # include <errno.h>
112 # include <fcntl.h> /* For O_RDONLY etc. */
113 # include <unistd.h> /* For getpid, etc. */
114 # include <sys/time.h> /* For struct timeval */
115 # include <sys/stat.h> /* For struct stat */
117 # define GNU_PACKAGE "standalone"
118 # define VERSION "2.0" /* Kind of arbitrary... */
120 # if __GNUC__ < 2 || __GNUC__ == 2 && __GNUC_MINOR__ < 5 || __STRICT_ANSI__
121 # define attribute(x)
122 # else
123 # define attribute __attribute__
124 # if __GNUC__ == 2 && __GNUC_MINOR__ < 7
125 /* The __-protected forms were introduced in GCC 2.6.4 */
126 # define __format__ format
127 # define __printf__ printf
128 # endif
129 # endif
131 /* Reasonable default assumptions for time-getting */
132 # ifndef HAVE_GETTIMEOFDAY
133 # define HAVE_GETTIMEOFDAY 1 /* Most systems have it these days */
134 # endif
136 # ifdef CLOCK_REALTIME
137 # ifndef HAVE_CLOCK_GETTIME
138 # define HAVE_CLOCK_GETTIME 1
139 # endif
140 # endif
142 # ifndef STDOUT_FILENO
143 # define STDOUT_FILENO 1
144 # endif
146 # define RETSIGTYPE int
148 # ifndef S_IWUSR
149 # ifdef S_IWRITE
150 # define S_IWUSR S_IWRITE
151 # else
152 # define S_IWUSR 0200
153 # endif
154 # endif
156 /* POSIX doesn't require st_blksize, and 65536 is a reasonable
157 upper bound for existing filesystem practice. */
158 # define ST_BLKSIZE(Stat) 65536
160 # define uintmax_t unsigned long
162 /* Variant human-readable function that ignores last two args */
163 # define human_readable(v, b, f, t) (sprintf (b, "%lu", (unsigned long) v), b)
164 # define LONGEST_HUMAN_READABLE (sizeof (uintmax_t) * CHAR_BIT / 3)
166 /* Variant convert-to-uintmax_t function that accepts metric suffixes */
167 enum strtol_error
169 LONGINT_OK, LONGINT_INVALID, LONGINT_INVALID_SUFFIX_CHAR, LONGINT_OVERFLOW
171 static uintmax_t
172 xstrtoumax (char const *ptr, char const **end, int base, uintmax_t *res,
173 char const *valid_suffixes)
175 char *end_ptr;
176 char const *p;
177 static char const metric_suffixes[] = "kMGTPEZY";
178 int decimal_flag;
179 uintmax_t n;
180 char c;
182 errno = 0;
183 *res = n = strtoul (ptr, &end_ptr, base);
184 if (end)
185 *end = end_ptr;
186 if (errno)
187 return LONGINT_OVERFLOW;
188 if (ptr == end_ptr)
189 return LONGINT_INVALID;
190 c = *end_ptr;
191 if (!c)
192 return LONGINT_OK;
193 /* Now deal with metric-style suffixes */
194 if (valid_suffixes && !strchr (valid_suffixes, c))
195 return LONGINT_INVALID_SUFFIX_CHAR;
197 decimal_flag = 0;
198 switch (c)
200 case 'b':
201 if (n > ULONG_MAX/512)
202 return LONGINT_OVERFLOW;
203 n *= 512;
204 break;
206 case 'B':
207 if (n > ULONG_MAX/102412)
208 return LONGINT_OVERFLOW;
209 n *= 1024;
210 break;
212 case 'c':
213 break;
215 case 'K':
216 c = 'k';
217 goto def;
219 case 'm':
220 c = 'M';
221 /*FALLTHROUGH*/
222 def:default:
223 p = strchr (metric_suffixes, c);
224 if (!p)
225 return LONGINT_INVALID_SUFFIX_CHAR;
227 * If valid_suffixes contains '0', then xD (decimal) and xB (binary)
228 * are allowed as "supersuffixes". Binary is the default.
230 if (strchr (valid_suffixes, '0'))
232 if (end_ptr[1] == 'B')
233 end_ptr++;
234 else if (end_ptr[1] == 'D')
236 decimal_flag = 1;
237 end_ptr++;
240 /* Now do the scaling */
241 p++;
242 if (decimal_flag)
243 do {
244 if (n > ULONG_MAX/1000)
245 return LONGINT_OVERFLOW;
246 n *= 1000;
247 } while (--p > metric_suffixes);
248 else
249 do {
250 if (n > ULONG_MAX/1024)
251 return LONGINT_OVERFLOW;
252 n *= 1024;
253 } while (--p > metric_suffixes);
256 /* Final wrapup */
257 if (end)
258 *end = end_ptr+1; /* Extra suffix is allowed if it's expected */
259 else if (end_ptr[1])
260 return LONGINT_INVALID_SUFFIX_CHAR;
261 *res = n;
262 return LONGINT_OK;
265 /* Dummy i18n stubs */
266 # define _(x) x
267 # define N_(x) x
268 # define setlocale(x,y) (void) 0
269 # define bindtextdomain(x,y) (void) 0
270 # define textdomain(x) (void) 0
273 * Print a message with `fprintf (stderr, FORMAT, ...)';
274 * if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
275 * If STATUS is nonzero, terminate the program with `exit (STATUS)'.
277 static void error (int status, int errnum, const char *format, ...)
278 attribute ((__format__ (__printf__, 3, 4)));
280 extern char const *program_name;
281 static void
282 error (int status, int errnum, const char *format, ...)
284 va_list ap;
286 if (program_name)
288 fputs (program_name, stderr);
289 fputs (": ", stderr);
291 va_start (ap, format);
292 vfprintf (stderr, format, ap);
293 va_end (ap);
294 if (errnum)
296 fputs (": ", stderr);
297 fputs (strerror (errnum), stderr);
299 putc ('\n', stderr);
301 if (status)
302 exit (status);
306 * GNU programs actually check for failure closing standard output.
307 * This seems unnecessary, until your shell script starts hitting
308 * ENOSPC and doing bizarre things with zero-length files.
310 static void
311 close_stdout (void)
313 if (ferror (stdout))
314 error (EXIT_FAILURE, 0, _("write error"));
315 if (fclose (stdout) != 0)
316 error (EXIT_FAILURE, errno, _("write error"));
320 * Quote the argument (including colon characters) into the buffer.
321 * Return the buffer size used (including trailing null byte.)
322 * If this is larger than the bufsize, it is an estimate of the space
323 * needed.
325 static size_t
326 quotearg_colon_buf (char const *arg, char *buf, size_t bufsize)
328 /* Some systems don't have \a or \e, so this is ASCII-dependent */
329 static char const escaped[] = "\7\b\33\f\n\r\t\v";
330 static char const escapes[] = "abefnrtv";
331 int c;
332 size_t pos = 0;
333 char const *p;
335 while ((c = (unsigned char) *arg++) != 0)
337 if (isprint (c))
339 if (strchr ("\\:", c)) /* Anything else we should quote? */
340 if (pos++ < bufsize) *buf++ = '\\';
342 else
344 if (pos++ < bufsize) *buf++ = '\\';
345 p = strchr (escaped, c); /* c is never 0, so this is okay */
346 if (p)
348 c = escapes[p-escaped];
350 else
352 if ('0' <= *arg && *arg <= '9')
353 c += 256; /* Force 3-digit form if followed by a digit */
354 if (c > 077)
355 if (pos++ < bufsize) *buf++ = "0123"[c>>6 & 3];
356 if (c > 07)
357 if (pos++ < bufsize) *buf++ = "01234567"[c>>3 & 7];
358 c = "01234567"[c & 7];
361 if (pos++ < bufsize) *buf++ = c;
363 if (pos++ < bufsize) *buf++ = 0;
364 return pos;
367 /* Quote metacharacters in a filename */
368 char const *
369 quotearg_colon (char const *arg)
371 static char *buf = 0;
372 size_t bufsize = 0;
373 size_t newsize;
375 while ((newsize = quotearg_colon_buf (arg, buf, bufsize)) > bufsize)
377 buf = realloc (buf, newsize);
378 if (!buf)
379 error (EXIT_FAILURE, 0, _("Memory exhausted"));
380 bufsize = newsize;
382 return buf;
385 void *
386 xmalloc (size_t n)
388 void *p = malloc (n);
389 if (!p)
390 error (EXIT_FAILURE, 0, _("Memory exhausted"));
391 return p;
394 char *
395 xstrdup (char const *string)
397 return strcpy (xmalloc (strlen (string) + 1), string);
400 #endif /* ! HAVE_CONFIG_H */
402 #ifndef O_NOCTTY
403 # define O_NOCTTY 0 /* This is a very optional frill */
404 #endif
406 /* Some systems don't support some file types. */
407 #ifndef S_ISFIFO
408 # define S_ISFIFO(mode) 0
409 #endif
410 #ifndef S_ISLNK
411 # define S_ISLNK(mode) 0
412 #endif
413 #ifndef S_ISSOCK
414 # define S_ISSOCK(mode) 0
415 #endif
417 #define DEFAULT_PASSES 25 /* Default */
419 /* How often to update wiping display */
420 #define VERBOSE_UPDATE 150*1024
422 /* If positive, the units to use when printing sizes;
423 if negative, the human-readable base. */
424 #define OUTPUT_BLOCK_SIZE (-1024)
426 struct Options
428 int force; /* -f flag: chmod files if necessary */
429 size_t n_iterations; /* -n flag: Number of iterations */
430 off_t size; /* -s flag: size of file */
431 int remove_file; /* -u flag: remove file after shredding */
432 int verbose; /* -v flag: Print progress */
433 int exact; /* -x flag: Do not round up file size */
434 int zero_fill; /* -z flag: Add a final zero pass */
437 static struct option const long_opts[] =
439 {"exact", required_argument, NULL, 'x'},
440 {"force", no_argument, NULL, 'f'},
441 {"iterations", required_argument, NULL, 'n'},
442 {"size", required_argument, NULL, 's'},
443 {"remove", no_argument, NULL, 'u'},
444 {"verbose", no_argument, NULL, 'v'},
445 {"zero", required_argument, NULL, 'z'},
446 {GETOPT_HELP_OPTION_DECL},
447 {GETOPT_VERSION_OPTION_DECL},
448 {NULL, 0, NULL, 0}
451 /* Global variable for error printing purposes */
452 char const *program_name; /* Initialized before any possible use */
454 void
455 usage (int status)
457 if (status != 0)
458 fprintf (stderr, _("Try `%s --help' for more information.\n"),
459 program_name);
460 else
462 printf (_("Usage: %s [OPTIONS] FILE [...]\n"), program_name);
463 printf (_("\
464 Delete a file securely, first overwriting it to hide its contents.\n\
466 -f, --force change permissions to allow writing if necessary\n\
467 -n, --iterations=N Overwrite N times instead of the default (%d)\n\
468 -s, --size=N shred this many bytes (suffixes like k, M, G accepted)\n\
469 -u, --remove truncate and remove file after overwriting\n\
470 -v, --verbose show progress\n\
471 -x, --exact do not round file sizes up to the next full block\n\
472 -z, --zero add a final overwrite with zeros to hide shredding\n\
473 - shred standard output\n\
474 --help display this help and exit\n\
475 --version print version information and exit\n\
477 FIXME maybe add more discussion here?"), DEFAULT_PASSES);
478 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
479 close_stdout ();
481 exit (status);
484 #if ! HAVE_FDATASYNC
485 # define fdatasync(fd) -1
486 #endif
489 * --------------------------------------------------------------------
490 * Bob Jenkins' cryptographic random number generator, ISAAC.
491 * Hacked by Colin Plumb.
493 * We need a source of random numbers for some of the overwrite data.
494 * Cryptographically secure is desirable, but it's not life-or-death
495 * so I can be a little bit experimental in the choice of RNGs here.
497 * This generator is based somewhat on RC4, but has analysis
498 * (http://ourworld.compuserve.com/homepages/bob_jenkins/randomnu.htm)
499 * pointing to it actually being better. I like it because it's nice
500 * and fast, and because the author did good work analyzing it.
501 * --------------------------------------------------------------------
504 #if ULONG_MAX == 0xffffffff
505 typedef unsigned long word32;
506 #else
507 # if UINT_MAX == 0xffffffff
508 typedef unsigned word32;
509 # else
510 # if USHRT_MAX == 0xffffffff
511 typedef unsigned short word32;
512 # else
513 # if UCHAR_MAX == 0xffffffff
514 typedef unsigned char word32;
515 # else
516 "No 32-bit type available!"
517 # endif
518 # endif
519 # endif
520 #endif
522 /* Size of the state tables to use. (You may change ISAAC_LOG) */
523 #define ISAAC_LOG 8
524 #define ISAAC_WORDS (1 << ISAAC_LOG)
525 #define ISAAC_BYTES (ISAAC_WORDS * sizeof (word32))
527 /* RNG state variables */
528 struct isaac_state
530 word32 mm[ISAAC_WORDS]; /* Main state array */
531 word32 iv[8]; /* Seeding initial vector */
532 word32 a, b, c; /* Extra index variables */
535 /* This index operation is more efficient on many processors */
536 #define ind(mm, x) \
537 (* (word32 *) ((char *) (mm) + ((x) & (ISAAC_WORDS - 1) * sizeof (word32))))
540 * The central step. This uses two temporaries, x and y. mm is the
541 * whole state array, while m is a pointer to the current word. off is
542 * the offset from m to the word ISAAC_WORDS/2 words away in the mm array,
543 * i.e. +/- ISAAC_WORDS/2.
545 #define isaac_step(mix, a, b, mm, m, off, r) \
547 a = ((a) ^ (mix)) + (m)[off], \
548 x = *(m), \
549 *(m) = y = ind (mm, x) + (a) + (b), \
550 *(r) = b = ind (mm, (y) >> ISAAC_LOG) + x \
554 * Refill the entire R array, and update S.
556 static void
557 isaac_refill (struct isaac_state *s, word32 r[/* ISAAC_WORDS */])
559 register word32 a, b; /* Caches of a and b */
560 register word32 x, y; /* Temps needed by isaac_step macro */
561 register word32 *m = s->mm; /* Pointer into state array */
563 a = s->a;
564 b = s->b + (++s->c);
568 isaac_step (a << 13, a, b, s->mm, m, ISAAC_WORDS / 2, r);
569 isaac_step (a >> 6, a, b, s->mm, m + 1, ISAAC_WORDS / 2, r + 1);
570 isaac_step (a << 2, a, b, s->mm, m + 2, ISAAC_WORDS / 2, r + 2);
571 isaac_step (a >> 16, a, b, s->mm, m + 3, ISAAC_WORDS / 2, r + 3);
572 r += 4;
574 while ((m += 4) < s->mm + ISAAC_WORDS / 2);
577 isaac_step (a << 13, a, b, s->mm, m, -ISAAC_WORDS / 2, r);
578 isaac_step (a >> 6, a, b, s->mm, m + 1, -ISAAC_WORDS / 2, r + 1);
579 isaac_step (a << 2, a, b, s->mm, m + 2, -ISAAC_WORDS / 2, r + 2);
580 isaac_step (a >> 16, a, b, s->mm, m + 3, -ISAAC_WORDS / 2, r + 3);
581 r += 4;
583 while ((m += 4) < s->mm + ISAAC_WORDS);
584 s->a = a;
585 s->b = b;
589 * The basic seed-scrambling step for initialization, based on Bob
590 * Jenkins' 256-bit hash.
592 #define mix(a,b,c,d,e,f,g,h) \
593 ( a ^= b << 11, d += a, \
594 b += c, b ^= c >> 2, e += b, \
595 c += d, c ^= d << 8, f += c, \
596 d += e, d ^= e >> 16, g += d, \
597 e += f, e ^= f << 10, h += e, \
598 f += g, f ^= g >> 4, a += f, \
599 g += h, g ^= h << 8, b += g, \
600 h += a, h ^= a >> 9, c += h, \
601 a += b )
603 /* The basic ISAAC initialization pass. */
604 static void
605 isaac_mix (struct isaac_state *s, word32 const seed[/* ISAAC_WORDS */])
607 int i;
608 word32 a = s->iv[0];
609 word32 b = s->iv[1];
610 word32 c = s->iv[2];
611 word32 d = s->iv[3];
612 word32 e = s->iv[4];
613 word32 f = s->iv[5];
614 word32 g = s->iv[6];
615 word32 h = s->iv[7];
617 for (i = 0; i < ISAAC_WORDS; i += 8)
619 a += seed[i];
620 b += seed[i + 1];
621 c += seed[i + 2];
622 d += seed[i + 3];
623 e += seed[i + 4];
624 f += seed[i + 5];
625 g += seed[i + 6];
626 h += seed[i + 7];
628 mix (a, b, c, d, e, f, g, h);
630 s->mm[i] = a;
631 s->mm[i + 1] = b;
632 s->mm[i + 2] = c;
633 s->mm[i + 3] = d;
634 s->mm[i + 4] = e;
635 s->mm[i + 5] = f;
636 s->mm[i + 6] = g;
637 s->mm[i + 7] = h;
640 s->iv[0] = a;
641 s->iv[1] = b;
642 s->iv[2] = c;
643 s->iv[3] = d;
644 s->iv[4] = e;
645 s->iv[5] = f;
646 s->iv[6] = g;
647 s->iv[7] = h;
650 #if 0 /* Provided for reference only; not used in this code */
652 * Initialize the ISAAC RNG with the given seed material.
653 * Its size MUST be a multiple of ISAAC_BYTES, and may be
654 * stored in the s->mm array.
656 * This is a generalization of the original ISAAC initialization code
657 * to support larger seed sizes. For seed sizes of 0 and ISAAC_BYTES,
658 * it is identical.
660 static void
661 isaac_init (struct isaac_state *s, word32 const *seed, size_t seedsize)
663 static word32 const iv[8] =
665 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
666 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119};
667 int i;
669 # if 0
670 /* The initialization of iv is a precomputed form of: */
671 for (i = 0; i < 7; i++)
672 iv[i] = 0x9e3779b9; /* the golden ratio */
673 for (i = 0; i < 4; ++i) /* scramble it */
674 mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
675 # endif
676 s->a = s->b = s->c = 0;
678 for (i = 0; i < 8; i++)
679 s->iv[i] = iv[i];
681 if (seedsize)
683 /* First pass (as in reference ISAAC code) */
684 isaac_mix (s, seed);
685 /* Second and subsequent passes (extension to ISAAC) */
686 while (seedsize -= ISAAC_BYTES)
688 seed += ISAAC_WORDS;
689 for (i = 0; i < ISAAC_WORDS; i++)
690 s->mm[i] += seed[i];
691 isaac_mix (s, s->mm);
694 else
696 /* The no seed case (as in reference ISAAC code) */
697 for (i = 0; i < ISAAC_WORDS; i++)
698 s->mm[i] = 0;
701 /* Final pass */
702 isaac_mix (s, s->mm);
704 #endif
706 /* Start seeding an ISAAC structire */
707 static void
708 isaac_seed_start (struct isaac_state *s)
710 static word32 const iv[8] =
712 0x1367df5a, 0x95d90059, 0xc3163e4b, 0x0f421ad8,
713 0xd92a4a78, 0xa51a3c49, 0xc4efea1b, 0x30609119
715 int i;
717 #if 0
718 /* The initialization of iv is a precomputed form of: */
719 for (i = 0; i < 7; i++)
720 iv[i] = 0x9e3779b9; /* the golden ratio */
721 for (i = 0; i < 4; ++i) /* scramble it */
722 mix (iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7]);
723 #endif
724 for (i = 0; i < 8; i++)
725 s->iv[i] = iv[i];
726 /* We could initialize s->mm to zero, but why bother? */
728 /* s->c gets used for a data pointer during the seeding phase */
729 s->a = s->b = s->c = 0;
732 /* Add a buffer of seed material */
733 static void
734 isaac_seed_data (struct isaac_state *s, void const *buf, size_t size)
736 unsigned char *p;
737 size_t avail;
738 size_t i;
740 avail = sizeof s->mm - (size_t) s->c; /* s->c is used as a write pointer */
742 /* Do any full buffers that are necessary */
743 while (size > avail)
745 p = (unsigned char *) s->mm + s->c;
746 for (i = 0; i < avail; i++)
747 p[i] ^= ((unsigned char const *) buf)[i];
748 buf = (char const *) buf + avail;
749 size -= avail;
750 isaac_mix (s, s->mm);
751 s->c = 0;
752 avail = sizeof s->mm;
755 /* And the final partial block */
756 p = (unsigned char *) s->mm + s->c;
757 for (i = 0; i < size; i++)
758 p[i] ^= ((unsigned char const *) buf)[i];
759 s->c = (word32) size;
763 /* End of seeding phase; get everything ready to produce output. */
764 static void
765 isaac_seed_finish (struct isaac_state *s)
767 isaac_mix (s, s->mm);
768 isaac_mix (s, s->mm);
769 /* Now reinitialize c to start things off right */
770 s->c = 0;
772 #define ISAAC_SEED(s,x) isaac_seed_data (s, &(x), sizeof (x))
775 #if __GNUC__ >= 2 && (__i386__ || __alpha__ || _ARCH_PPC)
777 * Many processors have very-high-resolution timer registers,
778 * The timer registers can be made inaccessible, so we have to deal with the
779 * possibility of SIGILL while we're working.
781 static jmp_buf env;
782 static RETSIGTYPE
783 sigill_handler (int signum)
785 (void) signum;
786 longjmp (env, 1); /* Trivial, just return an indication that it happened */
789 static void
790 isaac_seed_machdep (struct isaac_state *s)
792 RETSIGTYPE (*oldhandler) (int);
794 /* This is how one does try/except in C */
795 oldhandler = signal (SIGILL, sigill_handler);
796 if (setjmp (env)) /* ANSI: Must be entire controlling expression */
798 (void) signal (SIGILL, oldhandler);
800 else
802 # if __i386__
803 word32 t[2];
804 __asm__ __volatile__ ("rdtsc" : "=a" (t[0]), "=d" (t[1]));
805 # endif
806 # if __alpha__
807 unsigned long t;
808 __asm__ __volatile__ ("rpcc %0" : "=r" (t));
809 # endif
810 # if _ARCH_PPC
811 word32 t;
812 __asm__ __volatile__ ("mfspr %0,22" : "=r" (t));
813 # endif
814 # if __mips
815 /* Code not used because this is not accessible from userland */
816 word32 t;
817 __asm__ __volatile__ ("mfc0\t%0,$9" : "=r" (t));
818 # endif
819 # if __sparc__
820 /* This doesn't compile on all platforms yet. How to fix? */
821 unsigned long t;
822 __asm__ __volatile__ ("rd %%tick, %0" : "=r" (t));
823 # endif
824 (void) signal (SIGILL, oldhandler);
825 isaac_seed_data (s, &t, sizeof t);
829 #else /* !(__i386__ || __alpha__ || _ARCH_PPC) */
831 /* Do-nothing stub */
832 # define isaac_seed_machdep(s) (void) 0
834 #endif /* !(__i386__ || __alpha__ || _ARCH_PPC) */
838 * Get seed material. 16 bytes (128 bits) is plenty, but if we have
839 * /dev/urandom, we get 32 bytes = 256 bits for complete overkill.
841 static void
842 isaac_seed (struct isaac_state *s)
844 isaac_seed_start (s);
846 { pid_t t = getpid (); ISAAC_SEED (s, t); }
847 { pid_t t = getppid (); ISAAC_SEED (s, t); }
848 { uid_t t = getuid (); ISAAC_SEED (s, t); }
849 { gid_t t = getgid (); ISAAC_SEED (s, t); }
852 #if HAVE_GETHRTIME
853 hrtime_t t = gethrtime ();
854 ISAAC_SEED (s, t);
855 #else
856 # if HAVE_CLOCK_GETTIME /* POSIX ns-resolution */
857 struct timespec t;
858 clock_gettime (CLOCK_REALTIME, &t);
859 # else
860 # if HAVE_GETTIMEOFDAY
861 struct timeval t;
862 gettimeofday (&t, (struct timezone *) 0);
863 # else
864 time_t t;
865 t = time ((time_t *) 0);
866 # endif
867 # endif
868 #endif
869 ISAAC_SEED (s, t);
872 isaac_seed_machdep (s);
875 char buf[32];
876 int fd = open ("/dev/urandom", O_RDONLY | O_NOCTTY);
877 if (fd >= 0)
879 read (fd, buf, 32);
880 close (fd);
881 isaac_seed_data (s, buf, 32);
883 else
885 fd = open ("/dev/random", O_RDONLY | O_NONBLOCK | O_NOCTTY);
886 if (fd >= 0)
888 /* /dev/random is more precious, so use less */
889 read (fd, buf, 16);
890 close (fd);
891 isaac_seed_data (s, buf, 16);
896 isaac_seed_finish (s);
899 /* Single-word RNG built on top of ISAAC */
900 struct irand_state
902 word32 r[ISAAC_WORDS];
903 unsigned numleft;
904 struct isaac_state *s;
907 static void
908 irand_init (struct irand_state *r, struct isaac_state *s)
910 r->numleft = 0;
911 r->s = s;
915 * We take from the end of the block deliberately, so if we need
916 * only a small number of values, we choose the final ones which are
917 * marginally better mixed than the initial ones.
919 static word32
920 irand32 (struct irand_state *r)
922 if (!r->numleft)
924 isaac_refill (r->s, r->r);
925 r->numleft = ISAAC_WORDS;
927 return r->r[--r->numleft];
931 * Return a uniformly distributed random number between 0 and n,
932 * inclusive. Thus, the result is modulo n+1.
934 * Theory of operation: as x steps through every possible 32-bit number,
935 * x % n takes each value at least 2^32 / n times (rounded down), but
936 * the values less than 2^32 % n are taken one additional time. Thus,
937 * x % n is not perfectly uniform. To fix this, the values of x less
938 * than 2^32 % n are disallowed, and if the RNG produces one, we ask
939 * for a new value.
941 static word32
942 irand_mod (struct irand_state *r, word32 n)
944 word32 x;
945 word32 lim;
947 if (!++n)
948 return irand32 (r);
950 lim = -n % n; /* == (2**32-n) % n == 2**32 % n */
953 x = irand32 (r);
955 while (x < lim);
956 return x % n;
960 * Fill a buffer with a fixed pattern.
962 * The buffer must be at least 3 bytes long, even if
963 * size is less. Larger sizes are filled exactly.
965 static void
966 fillpattern (int type, unsigned char *r, size_t size)
968 size_t i;
969 unsigned bits = type & 0xfff;
971 bits |= bits << 12;
972 ((unsigned char *) r)[0] = (bits >> 4) & 255;
973 ((unsigned char *) r)[1] = (bits >> 8) & 255;
974 ((unsigned char *) r)[2] = bits & 255;
975 for (i = 3; i < size / 2; i *= 2)
976 memcpy ((char *) r + i, (char *) r, i);
977 if (i < size)
978 memcpy ((char *) r + i, (char *) r, size - i);
980 /* Invert the first bit of every 512-byte sector. */
981 if (type & 0x1000)
982 for (i = 0; i < size; i += 512)
983 r[i] ^= 0x80;
987 * Fill a buffer with random data.
988 * size is rounded UP to a multiple of ISAAC_BYTES.
990 static void
991 fillrand (struct isaac_state *s, word32 *r, size_t size)
993 size = (size + ISAAC_BYTES - 1) / ISAAC_BYTES;
995 while (size--)
997 isaac_refill (s, r);
998 r += ISAAC_WORDS;
1003 * Generate a 6-character (+ nul) pass name string
1004 * FIXME: allow translation of "random".
1006 #define PASS_NAME_SIZE 7
1007 static void
1008 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
1010 if (data)
1011 sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
1012 else
1013 memcpy (name, "random", PASS_NAME_SIZE);
1017 * Do pass number k of n, writing "size" bytes of the given pattern "type"
1018 * to the file descriptor fd. Qname, k and n are passed in only for verbose
1019 * progress message purposes. If n == 0, no progress messages are printed.
1021 * If *sizep == -1, the size is unknown, and it will be filled in as soon
1022 * as writing fails.
1024 static int
1025 dopass (int fd, char const *qname, off_t *sizep, int type,
1026 struct isaac_state *s, unsigned long k, unsigned long n)
1028 off_t size = *sizep;
1029 off_t offset; /* Current file posiiton */
1030 off_t thresh; /* Offset to print next status update */
1031 size_t lim; /* Amount of data to try writing */
1032 size_t soff; /* Offset into buffer for next write */
1033 ssize_t ssize; /* Return value from write */
1034 #if ISAAC_WORDS > 1024
1035 word32 r[ISAAC_WORDS * 3]; /* Multiple of 4K and of pattern size */
1036 #else
1037 word32 r[1024 * 3]; /* Multiple of 4K and of pattern size */
1038 #endif
1039 char pass_string[PASS_NAME_SIZE]; /* Name of current pass */
1041 if (lseek (fd, (off_t) 0, SEEK_SET) == -1)
1043 error (0, errno, _("%s: cannot rewind"), qname);
1044 return -1;
1047 /* Constant fill patterns need only be set up once. */
1048 if (type >= 0)
1050 lim = sizeof r;
1051 if ((off_t) lim > size && size != -1)
1053 lim = (size_t) size;
1055 fillpattern (type, (unsigned char *) r, lim);
1056 passname ((unsigned char *) r, pass_string);
1058 else
1060 passname (0, pass_string);
1063 /* Set position if first status update */
1064 thresh = 0;
1065 if (n)
1067 error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
1068 thresh = VERBOSE_UPDATE;
1069 if (thresh > size && size != -1)
1070 thresh = size;
1073 offset = 0;
1074 for (;;)
1076 /* How much to write this time? */
1077 lim = sizeof r;
1078 if ((off_t) lim > size - offset && size != -1)
1080 lim = (size_t) (size - offset);
1081 if (!lim)
1082 break;
1084 if (type < 0)
1085 fillrand (s, r, lim);
1086 /* Loop to retry partial writes. */
1087 for (soff = 0; soff < lim; soff += ssize)
1089 ssize = write (fd, (char *) r + soff, lim - soff);
1090 if (ssize <= 0)
1092 if ((ssize == 0 || errno == ENOSPC)
1093 && size == -1)
1095 /* Ah, we have found the end of the file */
1096 *sizep = thresh = size = offset + soff;
1097 break;
1099 else
1101 int errnum = errno;
1102 char buf[LONGEST_HUMAN_READABLE + 1];
1103 error (0, errnum, _("%s: error writing at offset %s"),
1104 qname,
1105 human_readable ((uintmax_t) (offset + soff),
1106 buf, 1, 1));
1108 * I sometimes use shred on bad media, before throwing it
1109 * out. Thus, I don't want it to give up on bad blocks.
1110 * This code assumes 512-byte blocks and tries to skip
1111 * over them. It works because lim is always a multiple
1112 * of 512, except at the end.
1114 if (errnum == EIO && soff % 512 == 0 && lim >= soff + 512
1115 && size != -1)
1117 if (lseek (fd, (off_t) (offset + soff + 512), SEEK_SET)
1118 != -1)
1120 soff += 512;
1121 continue;
1123 error (0, errno, "%s: lseek", qname);
1125 return -1;
1130 /* Okay, we have written "lim" bytes. */
1132 if (offset + lim < offset)
1134 error (0, 0, _("%s: file too large"), qname);
1135 return -1;
1138 offset += lim;
1140 /* Time to print progress? */
1141 if (offset >= thresh && n)
1143 char offset_buf[LONGEST_HUMAN_READABLE + 1];
1144 char size_buf[LONGEST_HUMAN_READABLE + 1];
1145 char const *human_offset
1146 = human_readable ((uintmax_t) offset, offset_buf, 1,
1147 OUTPUT_BLOCK_SIZE);
1148 if (size != -1)
1149 error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s"), qname, k, n,
1150 pass_string, human_offset,
1151 human_readable ((uintmax_t) size, size_buf, 1,
1152 OUTPUT_BLOCK_SIZE));
1153 else
1154 error (0, 0, _("%s: pass %lu/%lu (%s)...%s"), qname, k, n,
1155 pass_string, human_offset);
1157 thresh += VERBOSE_UPDATE;
1158 if (thresh > size && size != -1)
1159 thresh = size;
1161 * Force periodic syncs to keep displayed progress accurate
1162 * FIXME: Should these be present even if -v is not enabled,
1163 * to keep the buffer cache from filling with dirty pages?
1164 * It's a common problem with programs that do lots of writes,
1165 * like mkfs.
1167 if (fdatasync (fd) < 0 && fsync (fd) < 0)
1169 error (0, errno, "%s: fsync", qname);
1170 return -1;
1175 /* Force what we just wrote to hit the media. */
1176 if (fdatasync (fd) < 0 && fsync (fd) < 0)
1178 error (0, errno, "%s: fsync", qname);
1179 return -1;
1181 return 0;
1185 * The passes start and end with a random pass, and the passes in between
1186 * are done in random order. The idea is to deprive someone trying to
1187 * reverse the process of knowledge of the overwrite patterns, so they
1188 * have the additional step of figuring out what was done to the disk
1189 * before they can try to reverse or cancel it.
1191 * First, all possible 1-bit patterns. There are two of them.
1192 * Then, all possible 2-bit patterns. There are four, but the two
1193 * which are also 1-bit patterns can be omitted.
1194 * Then, all possible 3-bit patterns. Likewise, 8-2 = 6.
1195 * Then, all possible 4-bit patterns. 16-4 = 12.
1197 * The basic passes are:
1198 * 1-bit: 0x000, 0xFFF
1199 * 2-bit: 0x555, 0xAAA
1200 * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
1201 * 100100100100 110110110110
1202 * 9 2 4 D B 6
1203 * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
1204 * 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
1205 * Adding three random passes at the beginning, middle and end
1206 * produces the default 25-pass structure.
1208 * The next extension would be to 5-bit and 6-bit patterns.
1209 * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
1210 * 6-bit patterns, so they would increase the time required
1211 * significantly. 4-bit patterns are enough for most purposes.
1213 * The main gotcha is that this would require a trickier encoding,
1214 * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
1215 * lcm(2,3,4,5) = 60 bits is not.
1217 * One extension that is included is to complement the first bit in each
1218 * 512-byte block, to alter the phase of the encoded data in the more
1219 * complex encodings. This doesn't apply to MFM, so the 1-bit patterns
1220 * are considered part of the 3-bit ones and the 2-bit patterns are
1221 * considered part of the 4-bit patterns.
1224 * How does the generalization to variable numbers of passes work?
1226 * Here's how...
1227 * Have an ordered list of groups of passes. Each group is a set.
1228 * Take as many groups as will fit, plus a random subset of the
1229 * last partial group, and place them into the passes list.
1230 * Then shuffle the passes list into random order and use that.
1232 * One extra detail: if we can't include a large enough fraction of the
1233 * last group to be interesting, then just substitute random passes.
1235 * If you want more passes than the entire list of groups can
1236 * provide, just start repeating from the beginning of the list.
1238 static int const
1239 patterns[] =
1241 -2, /* 2 random passes */
1242 2, 0x000, 0xFFF, /* 1-bit */
1243 2, 0x555, 0xAAA, /* 2-bit */
1244 -1, /* 1 random pass */
1245 6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6, /* 3-bit */
1246 12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
1247 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */
1248 -1, /* 1 random pass */
1249 /* The following patterns have the frst bit per block flipped */
1250 8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
1251 14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
1252 0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
1253 -1, /* 1 random pass */
1254 0 /* End */
1258 * Generate a random wiping pass pattern with num passes.
1259 * This is a two-stage process. First, the passes to include
1260 * are chosen, and then they are shuffled into the desired
1261 * order.
1263 static void
1264 genpattern (int *dest, size_t num, struct isaac_state *s)
1266 struct irand_state r;
1267 size_t randpasses;
1268 int const *p;
1269 int *d;
1270 size_t n;
1271 size_t accum, top, swap;
1272 int k;
1274 if (!num)
1275 return;
1277 irand_init (&r, s);
1279 /* Stage 1: choose the passes to use */
1280 p = patterns;
1281 randpasses = 0;
1282 d = dest; /* Destination for generated pass list */
1283 n = num; /* Passes remaining to fill */
1285 for (;;)
1287 k = *p++; /* Block descriptor word */
1288 if (!k)
1289 { /* Loop back to the beginning */
1290 p = patterns;
1292 else if (k < 0)
1293 { /* -k random passes */
1294 k = -k;
1295 if ((size_t) k >= n)
1297 randpasses += n;
1298 n = 0;
1299 break;
1301 randpasses += k;
1302 n -= k;
1304 else if ((size_t) k <= n)
1305 { /* Full block of patterns */
1306 memcpy (d, p, k * sizeof (int));
1307 p += k;
1308 d += k;
1309 n -= k;
1311 else if (n < 2 || 3 * n < (size_t) k)
1312 { /* Finish with random */
1313 randpasses += n;
1314 break;
1316 else
1317 { /* Pad out with k of the n available */
1320 if (n == (size_t) k-- || irand_mod (&r, k) < n)
1322 *d++ = *p;
1323 n--;
1325 p++;
1327 while (n);
1328 break;
1331 top = num - randpasses; /* Top of initialized data */
1332 /* assert (d == dest+top); */
1335 * We now have fixed patterns in the dest buffer up to
1336 * "top", and we need to scramble them, with "randpasses"
1337 * random passes evenly spaced among them.
1339 * We want one at the beginning, one at the end, and
1340 * evenly spaced in between. To do this, we basically
1341 * use Bresenham's line draw (a.k.a DDA) algorithm
1342 * to draw a line with slope (randpasses-1)/(num-1).
1343 * (We use a positive accumulator and count down to
1344 * do this.)
1346 * So for each desired output value, we do the following:
1347 * - If it should be a random pass, copy the pass type
1348 * to top++, out of the way of the other passes, and
1349 * set the current pass to -1 (random).
1350 * - If it should be a normal pattern pass, choose an
1351 * entry at random between here and top-1 (inclusive)
1352 * and swap the current entry with that one.
1354 randpasses--; /* To speed up later math */
1355 accum = randpasses; /* Bresenham DDA accumulator */
1356 for (n = 0; n < num; n++)
1358 if (accum <= randpasses)
1360 accum += num - 1;
1361 dest[top++] = dest[n];
1362 dest[n] = -1;
1364 else
1366 swap = n + irand_mod (&r, top - n - 1);
1367 k = dest[n];
1368 dest[n] = dest[swap];
1369 dest[swap] = k;
1371 accum -= randpasses;
1373 /* assert (top == num); */
1375 memset (&r, 0, sizeof r); /* Wipe this on general principles */
1379 * The core routine to actually do the work. This overwrites the first
1380 * size bytes of the given fd. Returns -1 on error, 0 on success.
1382 static int
1383 do_wipefd (int fd, char const *qname, struct isaac_state *s,
1384 struct Options const *flags)
1386 size_t i;
1387 struct stat st;
1388 off_t size; /* Size to write, size to read */
1389 unsigned long n; /* Number of passes for printing purposes */
1390 int *passarray;
1392 n = 0; /* dopass takes n -- 0 to mean "don't print progress" */
1393 if (flags->verbose)
1394 n = flags->n_iterations + ((flags->zero_fill) != 0);
1396 if (fstat (fd, &st))
1398 error (0, errno, "%s: fstat", qname);
1399 return -1;
1402 /* If we know that we can't possibly shred the file, give up now.
1403 Otherwise, we may go into a infinite loop writing data before we
1404 find that we can't rewind the device. */
1405 if ((S_ISCHR (st.st_mode) && isatty (fd))
1406 || S_ISFIFO (st.st_mode)
1407 || S_ISSOCK (st.st_mode))
1409 error (0, 0, _("%s: invalid file type"), qname);
1410 return -1;
1413 /* Allocate pass array */
1414 passarray = xmalloc (flags->n_iterations * sizeof (int));
1416 size = flags->size;
1417 if (size == -1)
1419 size = (S_ISREG (st.st_mode)
1420 ? st.st_size
1421 : lseek (fd, (off_t) 0, SEEK_END));
1422 if (size < (S_ISREG (st.st_mode) ? 0 : -1))
1424 error (0, 0, _("%s: file has negative size"), qname);
1425 return -1;
1427 if (0 <= size && !(flags->exact))
1429 size += ST_BLKSIZE (st) - 1 - (size - 1) % ST_BLKSIZE (st);
1430 if (size < 0)
1431 size = TYPE_MAXIMUM (off_t);
1435 /* Schedule the passes in random order. */
1436 genpattern (passarray, flags->n_iterations, s);
1438 /* Do the work */
1439 for (i = 0; i < flags->n_iterations; i++)
1441 if (dopass (fd, qname, &size, passarray[i], s, i + 1, n) < 0)
1443 memset (passarray, 0, flags->n_iterations * sizeof (int));
1444 free (passarray);
1445 return -1;
1449 memset (passarray, 0, flags->n_iterations * sizeof (int));
1450 free (passarray);
1452 if (flags->zero_fill)
1453 if (dopass (fd, qname, &size, 0, s, flags->n_iterations + 1, n) < 0)
1454 return -1;
1456 /* Okay, now deallocate the data. The effect of ftruncate on
1457 non-regular files is unspecified, so don't worry about any
1458 errors reported for them. */
1459 if (flags->remove_file && ftruncate (fd, (off_t) 0) != 0
1460 && S_ISREG (st.st_mode))
1462 error (0, errno, _("%s: error truncating"), qname);
1463 return -1;
1466 return 0;
1469 /* A wrapper with a little more checking for fds on the command line */
1470 static int
1471 wipefd (int fd, char const *qname, struct isaac_state *s,
1472 struct Options const *flags)
1474 int fd_flags = fcntl (fd, F_GETFL);
1476 if (fd_flags < 0)
1478 error (0, errno, "%s: fcntl", qname);
1479 return -1;
1481 if (fd_flags & O_APPEND)
1483 error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
1484 return -1;
1486 return do_wipefd (fd, qname, s, flags);
1489 /* --- Name-wiping code --- */
1491 /* Characters allowed in a file name - a safe universal set. */
1492 static char const nameset[] =
1493 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_+=%@#.";
1496 * This increments the name, considering it as a big-endian base-N number
1497 * with the digits taken from nameset. Characters not in the nameset
1498 * are considered to come before nameset[0].
1500 * It's not obvious, but this will explode if name[0..len-1] contains
1501 * any 0 bytes.
1503 * This returns the carry (1 on overflow).
1505 static int
1506 incname (char *name, unsigned len)
1508 char const *p;
1510 if (!len)
1511 return 1;
1513 p = strchr (nameset, name[--len]);
1514 /* If the character is not found, replace it with a 0 digit */
1515 if (!p)
1517 name[len] = nameset[0];
1518 return 0;
1520 /* If this character has a successor, use it */
1521 if (p[1])
1523 name[len] = p[1];
1524 return 0;
1526 /* Otherwise, set this digit to 0 and increment the prefix */
1527 name[len] = nameset[0];
1528 return incname (name, len);
1532 * Repeatedly rename a file with shorter and shorter names,
1533 * to obliterate all traces of the file name on any system that
1534 * adds a trailing delimiter to on-disk file names and reuses
1535 * the same directory slot. Finally, unlink it.
1536 * The passed-in filename is modified in place to the new filename.
1537 * (Which is unlinked if this function succeeds, but is still present if
1538 * it fails for some reason.)
1540 * The main loop is written carefully to not get stuck if all possible
1541 * names of a given length are occupied. It counts down the length from
1542 * the original to 0. While the length is non-zero, it tries to find an
1543 * unused file name of the given length. It continues until either the
1544 * name is available and the rename succeeds, or it runs out of names
1545 * to try (incname wraps and returns 1). Finally, it unlinks the file.
1547 * The unlink is Unix-specific, as ANSI-standard remove has more
1548 * portability problems with C libraries making it "safe". rename
1549 * is ANSI-standard.
1551 * To force the directory data out, we try to open the directory and
1552 * invoke fdatasync on it. This is rather non-standard, so we don't
1553 * insist that it works, just fall back to a global sync in that case.
1554 * This is fairly significantly Unix-specific. Of course, on any
1555 * filesystem with synchronous metadata updates, this is unnecessary.
1557 static int
1558 wipename (char *oldname, char const *qoldname, struct Options const *flags)
1560 char *newname, *base; /* Base points to filename part of newname */
1561 unsigned len;
1562 int err;
1563 int dir_fd; /* Try to open directory to sync *it* */
1565 newname = xstrdup (oldname);
1566 if (flags->verbose)
1567 error (0, 0, _("%s: removing"), qoldname);
1569 /* Find the file name portion */
1570 base = strrchr (newname, '/');
1571 /* Temporary hackery to get a directory fd */
1572 if (base)
1574 *base = '\0';
1575 dir_fd = open (newname, O_RDONLY | O_NOCTTY);
1576 *base = '/';
1578 else
1580 dir_fd = open (".", O_RDONLY | O_NOCTTY);
1582 base = base ? base + 1 : newname;
1583 len = strlen (base);
1585 while (len)
1587 memset (base, nameset[0], len);
1588 base[len] = 0;
1591 struct stat st;
1592 if (lstat (newname, &st) < 0 && rename (oldname, newname) == 0)
1594 if (dir_fd < 0
1595 || (fdatasync (dir_fd) < 0 && fsync (dir_fd) < 0))
1596 sync (); /* Force directory out */
1597 if (flags->verbose)
1600 * People seem to understand this better than talking
1601 * about renaming oldname. newname doesn't need
1602 * quoting because we picked it.
1604 error (0, 0, _("%s: renamed to `%s'"), qoldname, newname);
1606 memcpy (oldname + (base - newname), base, len + 1);
1607 break;
1610 while (!incname (base, len));
1611 len--;
1613 free (newname);
1614 err = unlink (oldname);
1615 if (dir_fd < 0 || (fdatasync (dir_fd) < 0 && fsync (dir_fd) < 0))
1616 sync ();
1617 close (dir_fd);
1618 if (!err && flags->verbose)
1619 error (0, 0, _("%s: removed"), qoldname);
1620 return err;
1624 * Finally, the function that actually takes a filename and grinds
1625 * it into hamburger.
1627 * FIXME
1628 * Detail to note: since we do not restore errno to EACCES after
1629 * a failed chmod, we end up printing the error code from the chmod.
1630 * This is actually the error that stopped us from proceeding, so
1631 * it's arguably the right one, and in practice it'll be either EACCES
1632 * again or EPERM, which both give similar error messages.
1633 * Does anyone disagree?
1635 static int
1636 wipefile (char *name, char const *qname,
1637 struct isaac_state *s, struct Options const *flags)
1639 int err, fd;
1641 fd = open (name, O_WRONLY | O_NOCTTY);
1642 if (fd < 0)
1644 if (errno == EACCES && flags->force)
1646 if (chmod (name, S_IWUSR) >= 0) /* 0200, user-write-only */
1647 fd = open (name, O_WRONLY | O_NOCTTY);
1649 else if ((errno == ENOENT || errno == ENOTDIR)
1650 && strncmp (name, "/dev/fd/", 8) == 0)
1652 /* We accept /dev/fd/# even if the OS doesn't support it */
1653 int errnum = errno;
1654 unsigned long num;
1655 char *p;
1656 errno = 0;
1657 num = strtoul (name + 8, &p, 10);
1658 /* If it's completely decimal with no leading zeros... */
1659 if (errno == 0 && !*p && num <= INT_MAX &&
1660 (('1' <= name[8] && name[8] <= '9')
1661 || (name[8] == '0' && !name[9])))
1663 return wipefd ((int) num, qname, s, flags);
1665 errno = errnum;
1668 if (fd < 0)
1670 error (0, errno, "%s", qname);
1671 return -1;
1674 err = do_wipefd (fd, qname, s, flags);
1675 if (close (fd) != 0)
1677 error (0, 0, "%s: close", qname);
1678 err = -1;
1680 if (err == 0 && flags->remove_file)
1682 err = wipename (name, qname, flags);
1683 if (err < 0)
1684 error (0, 0, _("%s: cannot remove"), qname);
1686 return err;
1690 main (int argc, char **argv)
1692 struct isaac_state s;
1693 int err = 0;
1694 struct Options flags;
1695 char **file;
1696 int n_files;
1697 int c;
1698 int i;
1700 program_name = argv[0];
1701 setlocale (LC_ALL, "");
1702 bindtextdomain (PACKAGE, LOCALEDIR);
1703 textdomain (PACKAGE);
1705 isaac_seed (&s);
1707 memset (&flags, 0, sizeof flags);
1709 flags.n_iterations = DEFAULT_PASSES;
1710 flags.size = -1;
1712 while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1714 switch (c)
1716 case 0:
1717 break;
1719 case 'f':
1720 flags.force = 1;
1721 break;
1723 case 'n':
1725 uintmax_t tmp;
1726 if (xstrtoumax (optarg, NULL, 10, &tmp, NULL) != LONGINT_OK
1727 || (word32) tmp != tmp
1728 || ((size_t) (tmp * sizeof (int)) / sizeof (int) != tmp))
1730 error (1, 0, _("%s: invalid number of passes"),
1731 quotearg_colon (optarg));
1733 flags.n_iterations = (size_t) tmp;
1735 break;
1737 case 'u':
1738 flags.remove_file = 1;
1739 break;
1741 case 's':
1743 uintmax_t tmp;
1744 if (xstrtoumax (optarg, NULL, 0, &tmp, "cbBkMGTPEZY0")
1745 != LONGINT_OK)
1747 error (1, 0, _("%s: invalid file size"),
1748 quotearg_colon (optarg));
1750 flags.size = tmp;
1752 break;
1754 case 'v':
1755 flags.verbose = 1;
1756 break;
1758 case 'x':
1759 flags.exact = 1;
1760 break;
1762 case 'z':
1763 flags.zero_fill = 1;
1764 break;
1766 case_GETOPT_HELP_CHAR;
1768 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1770 default:
1771 usage (1);
1775 file = argv + optind;
1776 n_files = argc - optind;
1778 if (n_files == 0)
1780 error (0, 0, _("missing file argument"));
1781 usage (1);
1784 for (i = 0; i < n_files; i++)
1786 char const *qname = quotearg_colon (file[i]);
1787 if (strcmp (file[i], "-") == 0)
1789 if (wipefd (STDOUT_FILENO, qname, &s, &flags) < 0)
1790 err = 1;
1792 else
1794 /* Plain filename - Note that this overwrites *argv! */
1795 if (wipefile (file[i], qname, &s, &flags) < 0)
1796 err = 1;
1800 /* Just on general principles, wipe s. */
1801 memset (&s, 0, sizeof s);
1803 close_stdout ();
1805 exit (err);
1808 * vim:sw=2:sts=2: