Guest User

Untitled

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