Don't include "quote.h" when it is not used.
[platform/upstream/coreutils.git] / src / shred.c
1 /* shred.c - overwrite files and devices to make it harder to recover data
2
3    Copyright (C) 1999-2007 Free Software Foundation, Inc.
4    Copyright (C) 1997, 1998, 1999 Colin Plumb.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software Foundation,
18    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
20    Written by Colin Plumb.  */
21
22 /* TODO:
23    - use consistent non-capitalization in error messages
24    - add standard GNU copyleft comment
25
26   - Add -r/-R/--recursive
27   - Add -i/--interactive
28   - Reserve -d
29   - Add -L
30   - Add an unlink-all option to emulate rm.
31  */
32
33 /*
34  * Do a more secure overwrite of given files or devices, to make it harder
35  * for even very expensive hardware probing to recover the data.
36  *
37  * Although this process is also known as "wiping", I prefer the longer
38  * name both because I think it is more evocative of what is happening and
39  * because a longer name conveys a more appropriate sense of deliberateness.
40  *
41  * For the theory behind this, see "Secure Deletion of Data from Magnetic
42  * and Solid-State Memory", on line at
43  * http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html
44  *
45  * Just for the record, reversing one or two passes of disk overwrite
46  * is not terribly difficult with hardware help.  Hook up a good-quality
47  * digitizing oscilloscope to the output of the head preamplifier and copy
48  * the high-res digitized data to a computer for some off-line analysis.
49  * Read the "current" data and average all the pulses together to get an
50  * "average" pulse on the disk.  Subtract this average pulse from all of
51  * the actual pulses and you can clearly see the "echo" of the previous
52  * data on the disk.
53  *
54  * Real hard drives have to balance the cost of the media, the head,
55  * and the read circuitry.  They use better-quality media than absolutely
56  * necessary to limit the cost of the read circuitry.  By throwing that
57  * assumption out, and the assumption that you want the data processed
58  * as fast as the hard drive can spin, you can do better.
59  *
60  * If asked to wipe a file, this also unlinks it, renaming it to in a
61  * clever way to try to leave no trace of the original filename.
62  *
63  * This was inspired by a desire to improve on some code titled:
64  * Wipe V1.0-- Overwrite and delete files.  S. 2/3/96
65  * but I've rewritten everything here so completely that no trace of
66  * the original remains.
67  *
68  * Thanks to:
69  * Bob Jenkins, for his good RNG work and patience with the FSF copyright
70  * paperwork.
71  * Jim Meyering, for his work merging this into the GNU fileutils while
72  * still letting me feel a sense of ownership and pride.  Getting me to
73  * tolerate the GNU brace style was quite a feat of diplomacy.
74  * Paul Eggert, for lots of useful discussion and code.  I disagree with
75  * an awful lot of his suggestions, but they're disagreements worth having.
76  *
77  * Things to think about:
78  * - Security: Is there any risk to the race
79  *   between overwriting and unlinking a file?  Will it do anything
80  *   drastically bad if told to attack a named pipe or socket?
81  */
82
83 /* The official name of this program (e.g., no `g' prefix).  */
84 #define PROGRAM_NAME "shred"
85
86 #define AUTHORS "Colin Plumb"
87
88 #include <config.h>
89
90 #include <getopt.h>
91 #include <stdio.h>
92 #include <assert.h>
93 #include <setjmp.h>
94 #include <sys/types.h>
95
96 #include "system.h"
97 #include "xstrtol.h"
98 #include "error.h"
99 #include "fcntl--.h"
100 #include "getpagesize.h"
101 #include "human.h"
102 #include "inttostr.h"
103 #include "quotearg.h"           /* For quotearg_colon */
104 #include "randint.h"
105 #include "randread.h"
106
107 /* Default number of times to overwrite.  */
108 enum { DEFAULT_PASSES = 25 };
109
110 /* How many seconds to wait before checking whether to output another
111    verbose output line.  */
112 enum { VERBOSE_UPDATE = 5 };
113
114 /* Sector size and corresponding mask, for recovering after write failures.
115    The size must be a power of 2.  */
116 enum { SECTOR_SIZE = 512 };
117 enum { SECTOR_MASK = SECTOR_SIZE - 1 };
118 verify (0 < SECTOR_SIZE && (SECTOR_SIZE & SECTOR_MASK) == 0);
119
120 struct Options
121 {
122   bool force;           /* -f flag: chmod files if necessary */
123   size_t n_iterations;  /* -n flag: Number of iterations */
124   off_t size;           /* -s flag: size of file */
125   bool remove_file;     /* -u flag: remove file after shredding */
126   bool verbose;         /* -v flag: Print progress */
127   bool exact;           /* -x flag: Do not round up file size */
128   bool zero_fill;       /* -z flag: Add a final zero pass */
129 };
130
131 /* For long options that have no equivalent short option, use a
132    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
133 enum
134 {
135   RANDOM_SOURCE_OPTION = CHAR_MAX + 1
136 };
137
138 static struct option const long_opts[] =
139 {
140   {"exact", no_argument, NULL, 'x'},
141   {"force", no_argument, NULL, 'f'},
142   {"iterations", required_argument, NULL, 'n'},
143   {"size", required_argument, NULL, 's'},
144   {"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION},
145   {"remove", no_argument, NULL, 'u'},
146   {"verbose", no_argument, NULL, 'v'},
147   {"zero", no_argument, NULL, 'z'},
148   {GETOPT_HELP_OPTION_DECL},
149   {GETOPT_VERSION_OPTION_DECL},
150   {NULL, 0, NULL, 0}
151 };
152
153 /* Global variable for error printing purposes */
154 char const *program_name; /* Initialized before any possible use */
155
156 void
157 usage (int status)
158 {
159   if (status != EXIT_SUCCESS)
160     fprintf (stderr, _("Try `%s --help' for more information.\n"),
161              program_name);
162   else
163     {
164       printf (_("Usage: %s [OPTIONS] FILE [...]\n"), program_name);
165       fputs (_("\
166 Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\
167 for even very expensive hardware probing to recover the data.\n\
168 \n\
169 "), stdout);
170       fputs (_("\
171 Mandatory arguments to long options are mandatory for short options too.\n\
172 "), stdout);
173       printf (_("\
174   -f, --force    change permissions to allow writing if necessary\n\
175   -n, --iterations=N  Overwrite N times instead of the default (%d)\n\
176       --random-source=FILE  get random bytes from FILE (default /dev/urandom)\n\
177   -s, --size=N   shred this many bytes (suffixes like K, M, G accepted)\n\
178 "), DEFAULT_PASSES);
179       fputs (_("\
180   -u, --remove   truncate and remove file after overwriting\n\
181   -v, --verbose  show progress\n\
182   -x, --exact    do not round file sizes up to the next full block;\n\
183                    this is the default for non-regular files\n\
184   -z, --zero     add a final overwrite with zeros to hide shredding\n\
185 "), stdout);
186       fputs (HELP_OPTION_DESCRIPTION, stdout);
187       fputs (VERSION_OPTION_DESCRIPTION, stdout);
188       fputs (_("\
189 \n\
190 If FILE is -, shred standard output.\n\
191 \n\
192 Delete FILE(s) if --remove (-u) is specified.  The default is not to remove\n\
193 the files because it is common to operate on device files like /dev/hda,\n\
194 and those files usually should not be removed.  When operating on regular\n\
195 files, most people use the --remove option.\n\
196 \n\
197 "), stdout);
198       fputs (_("\
199 CAUTION: Note that shred relies on a very important assumption:\n\
200 that the file system overwrites data in place.  This is the traditional\n\
201 way to do things, but many modern file system designs do not satisfy this\n\
202 assumption.  The following are examples of file systems on which shred is\n\
203 not effective, or is not guaranteed to be effective in all file system modes:\n\
204 \n\
205 "), stdout);
206       fputs (_("\
207 * log-structured or journaled file systems, such as those supplied with\n\
208 AIX and Solaris (and JFS, ReiserFS, XFS, Ext3, etc.)\n\
209 \n\
210 * file systems that write redundant data and carry on even if some writes\n\
211 fail, such as RAID-based file systems\n\
212 \n\
213 * file systems that make snapshots, such as Network Appliance's NFS server\n\
214 \n\
215 "), stdout);
216       fputs (_("\
217 * file systems that cache in temporary locations, such as NFS\n\
218 version 3 clients\n\
219 \n\
220 * compressed file systems\n\
221 \n\
222 "), stdout);
223       fputs (_("\
224 In the case of ext3 file systems, the above disclaimer applies\n\
225 (and shred is thus of limited effectiveness) only in data=journal mode,\n\
226 which journals file data in addition to just metadata.  In both the\n\
227 data=ordered (default) and data=writeback modes, shred works as usual.\n\
228 Ext3 journaling modes can be changed by adding the data=something option\n\
229 to the mount options for a particular file system in the /etc/fstab file,\n\
230 as documented in the mount man page (man mount).\n\
231 \n\
232 "), stdout);
233       fputs (_("\
234 In addition, file system backups and remote mirrors may contain copies\n\
235 of the file that cannot be removed, and that will allow a shredded file\n\
236 to be recovered later.\n\
237 "), stdout);
238       emit_bug_reporting_address ();
239     }
240   exit (status);
241 }
242
243
244 /*
245  * Fill a buffer with a fixed pattern.
246  *
247  * The buffer must be at least 3 bytes long, even if
248  * size is less.  Larger sizes are filled exactly.
249  */
250 static void
251 fillpattern (int type, unsigned char *r, size_t size)
252 {
253   size_t i;
254   unsigned int bits = type & 0xfff;
255
256   bits |= bits << 12;
257   r[0] = (bits >> 4) & 255;
258   r[1] = (bits >> 8) & 255;
259   r[2] = bits & 255;
260   for (i = 3; i < size / 2; i *= 2)
261     memcpy (r + i, r, i);
262   if (i < size)
263     memcpy (r + i, r, size - i);
264
265   /* Invert the first bit of every sector. */
266   if (type & 0x1000)
267     for (i = 0; i < size; i += SECTOR_SIZE)
268       r[i] ^= 0x80;
269 }
270
271 /*
272  * Generate a 6-character (+ nul) pass name string
273  * FIXME: allow translation of "random".
274  */
275 #define PASS_NAME_SIZE 7
276 static void
277 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
278 {
279   if (data)
280     sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
281   else
282     memcpy (name, "random", PASS_NAME_SIZE);
283 }
284
285 /* Request that all data for FD be transferred to the corresponding
286    storage device.  QNAME is the file name (quoted for colons).
287    Report any errors found.  Return 0 on success, -1
288    (setting errno) on failure.  It is not an error if fdatasync and/or
289    fsync is not supported for this file, or if the file is not a
290    writable file descriptor.  */
291 static int
292 dosync (int fd, char const *qname)
293 {
294   int err;
295
296 #if HAVE_FDATASYNC
297   if (fdatasync (fd) == 0)
298     return 0;
299   err = errno;
300   if (err != EINVAL && err != EBADF)
301     {
302       error (0, err, _("%s: fdatasync failed"), qname);
303       errno = err;
304       return -1;
305     }
306 #endif
307
308   if (fsync (fd) == 0)
309     return 0;
310   err = errno;
311   if (err != EINVAL && err != EBADF)
312     {
313       error (0, err, _("%s: fsync failed"), qname);
314       errno = err;
315       return -1;
316     }
317
318   sync ();
319   return 0;
320 }
321
322 /* Turn on or off direct I/O mode for file descriptor FD, if possible.
323    Try to turn it on if ENABLE is true.  Otherwise, try to turn it off.  */
324 static void
325 direct_mode (int fd, bool enable)
326 {
327   if (O_DIRECT)
328     {
329       int fd_flags = fcntl (fd, F_GETFL);
330       if (0 < fd_flags)
331         {
332           int new_flags = (enable
333                            ? (fd_flags | O_DIRECT)
334                            : (fd_flags & ~O_DIRECT));
335           if (new_flags != fd_flags)
336             fcntl (fd, F_SETFL, new_flags);
337         }
338     }
339
340 #if HAVE_DIRECTIO && defined DIRECTIO_ON && defined DIRECTIO_OFF
341   /* This is Solaris-specific.  See the following for details:
342      http://docs.sun.com/db/doc/816-0213/6m6ne37so?q=directio&a=view  */
343   directio (fd, enable ? DIRECTIO_ON : DIRECTIO_OFF);
344 #endif
345 }
346
347 /*
348  * Do pass number k of n, writing "size" bytes of the given pattern "type"
349  * to the file descriptor fd.   Qname, k and n are passed in only for verbose
350  * progress message purposes.  If n == 0, no progress messages are printed.
351  *
352  * If *sizep == -1, the size is unknown, and it will be filled in as soon
353  * as writing fails.
354  *
355  * Return 1 on write error, -1 on other error, 0 on success.
356  */
357 static int
358 dopass (int fd, char const *qname, off_t *sizep, int type,
359         struct randread_source *s, unsigned long int k, unsigned long int n)
360 {
361   off_t size = *sizep;
362   off_t offset;                 /* Current file posiiton */
363   time_t thresh IF_LINT (= 0);  /* Time to maybe print next status update */
364   time_t now = 0;               /* Current time */
365   size_t lim;                   /* Amount of data to try writing */
366   size_t soff;                  /* Offset into buffer for next write */
367   ssize_t ssize;                /* Return value from write */
368
369   /* Fill pattern buffer.  Aligning it to a 32-bit boundary speeds up randread
370      in some cases.  */
371   typedef uint32_t fill_pattern_buffer[3 * 1024];
372   union
373   {
374     fill_pattern_buffer buffer;
375     char c[sizeof (fill_pattern_buffer)];
376     unsigned char u[sizeof (fill_pattern_buffer)];
377   } r;
378
379   off_t sizeof_r = sizeof r;
380   char pass_string[PASS_NAME_SIZE];     /* Name of current pass */
381   bool write_error = false;
382   bool first_write = true;
383
384   /* Printable previous offset into the file */
385   char previous_offset_buf[LONGEST_HUMAN_READABLE + 1];
386   char const *previous_human_offset IF_LINT (= 0);
387
388   if (lseek (fd, 0, SEEK_SET) == -1)
389     {
390       error (0, errno, _("%s: cannot rewind"), qname);
391       return -1;
392     }
393
394   /* Constant fill patterns need only be set up once. */
395   if (type >= 0)
396     {
397       lim = (0 <= size && size < sizeof_r ? size : sizeof r);
398       fillpattern (type, r.u, lim);
399       passname (r.u, pass_string);
400     }
401   else
402     {
403       passname (0, pass_string);
404     }
405
406   /* Set position if first status update */
407   if (n)
408     {
409       error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
410       thresh = time (NULL) + VERBOSE_UPDATE;
411       previous_human_offset = "";
412     }
413
414   offset = 0;
415   for (;;)
416     {
417       /* How much to write this time? */
418       lim = sizeof r;
419       if (0 <= size && size - offset < sizeof_r)
420         {
421           if (size < offset)
422             break;
423           lim = size - offset;
424           if (!lim)
425             break;
426         }
427       if (type < 0)
428         randread (s, &r, lim);
429       /* Loop to retry partial writes. */
430       for (soff = 0; soff < lim; soff += ssize, first_write = false)
431         {
432           ssize = write (fd, r.c + soff, lim - soff);
433           if (ssize <= 0)
434             {
435               if (size < 0 && (ssize == 0 || errno == ENOSPC))
436                 {
437                   /* Ah, we have found the end of the file */
438                   *sizep = size = offset + soff;
439                   break;
440                 }
441               else
442                 {
443                   int errnum = errno;
444                   char buf[INT_BUFSIZE_BOUND (uintmax_t)];
445
446                   /* If the first write of the first pass for a given file
447                      has just failed with EINVAL, turn off direct mode I/O
448                      and try again.  This works around a bug in linux-2.4
449                      whereby opening with O_DIRECT would succeed for some
450                      file system types (e.g., ext3), but any attempt to
451                      access a file through the resulting descriptor would
452                      fail with EINVAL.  */
453                   if (k == 1 && first_write && errno == EINVAL)
454                     {
455                       direct_mode (fd, false);
456                       ssize = 0;
457                       continue;
458                     }
459                   error (0, errnum, _("%s: error writing at offset %s"),
460                          qname, umaxtostr (offset + soff, buf));
461
462                   /* 'shred' is often used on bad media, before throwing it
463                      out.  Thus, it shouldn't give up on bad blocks.  This
464                      code works because lim is always a multiple of
465                      SECTOR_SIZE, except at the end.  */
466                   verify (sizeof r % SECTOR_SIZE == 0);
467                   if (errnum == EIO && 0 <= size && (soff | SECTOR_MASK) < lim)
468                     {
469                       size_t soff1 = (soff | SECTOR_MASK) + 1;
470                       if (lseek (fd, offset + soff1, SEEK_SET) != -1)
471                         {
472                           /* Arrange to skip this block. */
473                           ssize = soff1 - soff;
474                           write_error = true;
475                           continue;
476                         }
477                       error (0, errno, _("%s: lseek failed"), qname);
478                     }
479                   return -1;
480                 }
481             }
482         }
483
484       /* Okay, we have written "soff" bytes. */
485
486       if (offset + soff < offset)
487         {
488           error (0, 0, _("%s: file too large"), qname);
489           return -1;
490         }
491
492       offset += soff;
493
494       /* Time to print progress? */
495       if (n
496           && ((offset == size && *previous_human_offset)
497               || thresh <= (now = time (NULL))))
498         {
499           char offset_buf[LONGEST_HUMAN_READABLE + 1];
500           char size_buf[LONGEST_HUMAN_READABLE + 1];
501           int human_progress_opts = (human_autoscale | human_SI
502                                      | human_base_1024 | human_B);
503           char const *human_offset
504             = human_readable (offset, offset_buf,
505                               human_floor | human_progress_opts, 1, 1);
506
507           if (offset == size
508               || !STREQ (previous_human_offset, human_offset))
509             {
510               if (size < 0)
511                 error (0, 0, _("%s: pass %lu/%lu (%s)...%s"),
512                        qname, k, n, pass_string, human_offset);
513               else
514                 {
515                   uintmax_t off = offset;
516                   int percent = (size == 0
517                                  ? 100
518                                  : (off <= TYPE_MAXIMUM (uintmax_t) / 100
519                                     ? off * 100 / size
520                                     : off / (size / 100)));
521                   char const *human_size
522                     = human_readable (size, size_buf,
523                                       human_ceiling | human_progress_opts,
524                                       1, 1);
525                   if (offset == size)
526                     human_offset = human_size;
527                   error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s %d%%"),
528                          qname, k, n, pass_string, human_offset, human_size,
529                          percent);
530                 }
531
532               strcpy (previous_offset_buf, human_offset);
533               previous_human_offset = previous_offset_buf;
534               thresh = now + VERBOSE_UPDATE;
535
536               /*
537                * Force periodic syncs to keep displayed progress accurate
538                * FIXME: Should these be present even if -v is not enabled,
539                * to keep the buffer cache from filling with dirty pages?
540                * It's a common problem with programs that do lots of writes,
541                * like mkfs.
542                */
543               if (dosync (fd, qname) != 0)
544                 {
545                   if (errno != EIO)
546                     return -1;
547                   write_error = true;
548                 }
549             }
550         }
551     }
552
553   /* Force what we just wrote to hit the media. */
554   if (dosync (fd, qname) != 0)
555     {
556       if (errno != EIO)
557         return -1;
558       write_error = true;
559     }
560
561   return write_error;
562 }
563
564 /*
565  * The passes start and end with a random pass, and the passes in between
566  * are done in random order.  The idea is to deprive someone trying to
567  * reverse the process of knowledge of the overwrite patterns, so they
568  * have the additional step of figuring out what was done to the disk
569  * before they can try to reverse or cancel it.
570  *
571  * First, all possible 1-bit patterns.  There are two of them.
572  * Then, all possible 2-bit patterns.  There are four, but the two
573  * which are also 1-bit patterns can be omitted.
574  * Then, all possible 3-bit patterns.  Likewise, 8-2 = 6.
575  * Then, all possible 4-bit patterns.  16-4 = 12.
576  *
577  * The basic passes are:
578  * 1-bit: 0x000, 0xFFF
579  * 2-bit: 0x555, 0xAAA
580  * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
581  *        100100100100         110110110110
582  *           9   2   4            D   B   6
583  * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
584  *        0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
585  * Adding three random passes at the beginning, middle and end
586  * produces the default 25-pass structure.
587  *
588  * The next extension would be to 5-bit and 6-bit patterns.
589  * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
590  * 6-bit patterns, so they would increase the time required
591  * significantly.  4-bit patterns are enough for most purposes.
592  *
593  * The main gotcha is that this would require a trickier encoding,
594  * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
595  * lcm(2,3,4,5) = 60 bits is not.
596  *
597  * One extension that is included is to complement the first bit in each
598  * 512-byte block, to alter the phase of the encoded data in the more
599  * complex encodings.  This doesn't apply to MFM, so the 1-bit patterns
600  * are considered part of the 3-bit ones and the 2-bit patterns are
601  * considered part of the 4-bit patterns.
602  *
603  *
604  * How does the generalization to variable numbers of passes work?
605  *
606  * Here's how...
607  * Have an ordered list of groups of passes.  Each group is a set.
608  * Take as many groups as will fit, plus a random subset of the
609  * last partial group, and place them into the passes list.
610  * Then shuffle the passes list into random order and use that.
611  *
612  * One extra detail: if we can't include a large enough fraction of the
613  * last group to be interesting, then just substitute random passes.
614  *
615  * If you want more passes than the entire list of groups can
616  * provide, just start repeating from the beginning of the list.
617  */
618 static int const
619   patterns[] =
620 {
621   -2,                           /* 2 random passes */
622   2, 0x000, 0xFFF,              /* 1-bit */
623   2, 0x555, 0xAAA,              /* 2-bit */
624   -1,                           /* 1 random pass */
625   6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6,  /* 3-bit */
626   12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
627   0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE,     /* 4-bit */
628   -1,                           /* 1 random pass */
629         /* The following patterns have the frst bit per block flipped */
630   8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
631   14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
632   0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
633   -1,                           /* 1 random pass */
634   0                             /* End */
635 };
636
637 /*
638  * Generate a random wiping pass pattern with num passes.
639  * This is a two-stage process.  First, the passes to include
640  * are chosen, and then they are shuffled into the desired
641  * order.
642  */
643 static void
644 genpattern (int *dest, size_t num, struct randint_source *s)
645 {
646   size_t randpasses;
647   int const *p;
648   int *d;
649   size_t n;
650   size_t accum, top, swap;
651   int k;
652
653   if (!num)
654     return;
655
656   /* Stage 1: choose the passes to use */
657   p = patterns;
658   randpasses = 0;
659   d = dest;                     /* Destination for generated pass list */
660   n = num;                      /* Passes remaining to fill */
661
662   for (;;)
663     {
664       k = *p++;                 /* Block descriptor word */
665       if (!k)
666         {                       /* Loop back to the beginning */
667           p = patterns;
668         }
669       else if (k < 0)
670         {                       /* -k random passes */
671           k = -k;
672           if ((size_t) k >= n)
673             {
674               randpasses += n;
675               n = 0;
676               break;
677             }
678           randpasses += k;
679           n -= k;
680         }
681       else if ((size_t) k <= n)
682         {                       /* Full block of patterns */
683           memcpy (d, p, k * sizeof (int));
684           p += k;
685           d += k;
686           n -= k;
687         }
688       else if (n < 2 || 3 * n < (size_t) k)
689         {                       /* Finish with random */
690           randpasses += n;
691           break;
692         }
693       else
694         {                       /* Pad out with k of the n available */
695           do
696             {
697               if (n == (size_t) k || randint_choose (s, k) < n)
698                 {
699                   *d++ = *p;
700                   n--;
701                 }
702               p++;
703             }
704           while (n);
705           break;
706         }
707     }
708   top = num - randpasses;       /* Top of initialized data */
709   /* assert (d == dest+top); */
710
711   /*
712    * We now have fixed patterns in the dest buffer up to
713    * "top", and we need to scramble them, with "randpasses"
714    * random passes evenly spaced among them.
715    *
716    * We want one at the beginning, one at the end, and
717    * evenly spaced in between.  To do this, we basically
718    * use Bresenham's line draw (a.k.a DDA) algorithm
719    * to draw a line with slope (randpasses-1)/(num-1).
720    * (We use a positive accumulator and count down to
721    * do this.)
722    *
723    * So for each desired output value, we do the following:
724    * - If it should be a random pass, copy the pass type
725    *   to top++, out of the way of the other passes, and
726    *   set the current pass to -1 (random).
727    * - If it should be a normal pattern pass, choose an
728    *   entry at random between here and top-1 (inclusive)
729    *   and swap the current entry with that one.
730    */
731   randpasses--;                 /* To speed up later math */
732   accum = randpasses;           /* Bresenham DDA accumulator */
733   for (n = 0; n < num; n++)
734     {
735       if (accum <= randpasses)
736         {
737           accum += num - 1;
738           dest[top++] = dest[n];
739           dest[n] = -1;
740         }
741       else
742         {
743           swap = n + randint_choose (s, top - n);
744           k = dest[n];
745           dest[n] = dest[swap];
746           dest[swap] = k;
747         }
748       accum -= randpasses;
749     }
750   /* assert (top == num); */
751 }
752
753 /*
754  * The core routine to actually do the work.  This overwrites the first
755  * size bytes of the given fd.  Return true if successful.
756  */
757 static bool
758 do_wipefd (int fd, char const *qname, struct randint_source *s,
759            struct Options const *flags)
760 {
761   size_t i;
762   struct stat st;
763   off_t size;                   /* Size to write, size to read */
764   unsigned long int n;          /* Number of passes for printing purposes */
765   int *passarray;
766   bool ok = true;
767   struct randread_source *rs;
768
769   n = 0;                /* dopass takes n -- 0 to mean "don't print progress" */
770   if (flags->verbose)
771     n = flags->n_iterations + flags->zero_fill;
772
773   if (fstat (fd, &st))
774     {
775       error (0, errno, _("%s: fstat failed"), qname);
776       return false;
777     }
778
779   /* If we know that we can't possibly shred the file, give up now.
780      Otherwise, we may go into a infinite loop writing data before we
781      find that we can't rewind the device.  */
782   if ((S_ISCHR (st.st_mode) && isatty (fd))
783       || S_ISFIFO (st.st_mode)
784       || S_ISSOCK (st.st_mode))
785     {
786       error (0, 0, _("%s: invalid file type"), qname);
787       return false;
788     }
789
790   direct_mode (fd, true);
791
792   /* Allocate pass array */
793   passarray = xnmalloc (flags->n_iterations, sizeof *passarray);
794
795   size = flags->size;
796   if (size == -1)
797     {
798       /* Accept a length of zero only if it's a regular file.
799          For any other type of file, try to get the size another way.  */
800       if (S_ISREG (st.st_mode))
801         {
802           size = st.st_size;
803           if (size < 0)
804             {
805               error (0, 0, _("%s: file has negative size"), qname);
806               return false;
807             }
808         }
809       else
810         {
811           size = lseek (fd, 0, SEEK_END);
812           if (size <= 0)
813             {
814               /* We are unable to determine the length, up front.
815                  Let dopass do that as part of its first iteration.  */
816               size = -1;
817             }
818         }
819
820       /* Allow `rounding up' only for regular files.  */
821       if (0 <= size && !(flags->exact) && S_ISREG (st.st_mode))
822         {
823           size += ST_BLKSIZE (st) - 1 - (size - 1) % ST_BLKSIZE (st);
824
825           /* If in rounding up, we've just overflowed, use the maximum.  */
826           if (size < 0)
827             size = TYPE_MAXIMUM (off_t);
828         }
829     }
830
831   /* Schedule the passes in random order. */
832   genpattern (passarray, flags->n_iterations, s);
833
834   rs = randint_get_source (s);
835
836   /* Do the work */
837   for (i = 0; i < flags->n_iterations; i++)
838     {
839       int err = dopass (fd, qname, &size, passarray[i], rs, i + 1, n);
840       if (err)
841         {
842           if (err < 0)
843             {
844               memset (passarray, 0, flags->n_iterations * sizeof (int));
845               free (passarray);
846               return false;
847             }
848           ok = false;
849         }
850     }
851
852   memset (passarray, 0, flags->n_iterations * sizeof (int));
853   free (passarray);
854
855   if (flags->zero_fill)
856     {
857       int err = dopass (fd, qname, &size, 0, rs, flags->n_iterations + 1, n);
858       if (err)
859         {
860           if (err < 0)
861             return false;
862           ok = false;
863         }
864     }
865
866   /* Okay, now deallocate the data.  The effect of ftruncate on
867      non-regular files is unspecified, so don't worry about any
868      errors reported for them.  */
869   if (flags->remove_file && ftruncate (fd, 0) != 0
870       && S_ISREG (st.st_mode))
871     {
872       error (0, errno, _("%s: error truncating"), qname);
873       return false;
874     }
875
876   return ok;
877 }
878
879 /* A wrapper with a little more checking for fds on the command line */
880 static bool
881 wipefd (int fd, char const *qname, struct randint_source *s,
882         struct Options const *flags)
883 {
884   int fd_flags = fcntl (fd, F_GETFL);
885
886   if (fd_flags < 0)
887     {
888       error (0, errno, _("%s: fcntl failed"), qname);
889       return false;
890     }
891   if (fd_flags & O_APPEND)
892     {
893       error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
894       return false;
895     }
896   return do_wipefd (fd, qname, s, flags);
897 }
898
899 /* --- Name-wiping code --- */
900
901 /* Characters allowed in a file name - a safe universal set.  */
902 static char const nameset[] =
903 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
904
905 /* Increment NAME (with LEN bytes).  NAME must be a big-endian base N
906    number with the digits taken from nameset.  Return true if
907    successful if not (because NAME already has the greatest possible
908    value.  */
909
910 static bool
911 incname (char *name, size_t len)
912 {
913   while (len--)
914     {
915       char const *p = strchr (nameset, name[len]);
916
917       /* If this character has a successor, use it.  */
918       if (p[1])
919         {
920           name[len] = p[1];
921           return true;
922         }
923
924       /* Otherwise, set this digit to 0 and increment the prefix.  */
925       name[len] = nameset[0];
926     }
927
928   return false;
929 }
930
931 /*
932  * Repeatedly rename a file with shorter and shorter names,
933  * to obliterate all traces of the file name on any system that
934  * adds a trailing delimiter to on-disk file names and reuses
935  * the same directory slot.  Finally, unlink it.
936  * The passed-in filename is modified in place to the new filename.
937  * (Which is unlinked if this function succeeds, but is still present if
938  * it fails for some reason.)
939  *
940  * The main loop is written carefully to not get stuck if all possible
941  * names of a given length are occupied.  It counts down the length from
942  * the original to 0.  While the length is non-zero, it tries to find an
943  * unused file name of the given length.  It continues until either the
944  * name is available and the rename succeeds, or it runs out of names
945  * to try (incname wraps and returns 1).  Finally, it unlinks the file.
946  *
947  * The unlink is Unix-specific, as ANSI-standard remove has more
948  * portability problems with C libraries making it "safe".  rename
949  * is ANSI-standard.
950  *
951  * To force the directory data out, we try to open the directory and
952  * invoke fdatasync and/or fsync on it.  This is non-standard, so don't
953  * insist that it works: just fall back to a global sync in that case.
954  * This is fairly significantly Unix-specific.  Of course, on any
955  * file system with synchronous metadata updates, this is unnecessary.
956  */
957 static bool
958 wipename (char *oldname, char const *qoldname, struct Options const *flags)
959 {
960   char *newname = xstrdup (oldname);
961   char *base = last_component (newname);
962   size_t len = base_len (base);
963   char *dir = dir_name (newname);
964   char *qdir = xstrdup (quotearg_colon (dir));
965   bool first = true;
966   bool ok = true;
967
968   int dir_fd = open (dir, O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK);
969
970   if (flags->verbose)
971     error (0, 0, _("%s: removing"), qoldname);
972
973   while (len)
974     {
975       memset (base, nameset[0], len);
976       base[len] = 0;
977       do
978         {
979           struct stat st;
980           if (lstat (newname, &st) < 0)
981             {
982               if (rename (oldname, newname) == 0)
983                 {
984                   if (0 <= dir_fd && dosync (dir_fd, qdir) != 0)
985                     ok = false;
986                   if (flags->verbose)
987                     {
988                       /*
989                        * People seem to understand this better than talking
990                        * about renaming oldname.  newname doesn't need
991                        * quoting because we picked it.  oldname needs to
992                        * be quoted only the first time.
993                        */
994                       char const *old = (first ? qoldname : oldname);
995                       error (0, 0, _("%s: renamed to %s"), old, newname);
996                       first = false;
997                     }
998                   memcpy (oldname + (base - newname), base, len + 1);
999                   break;
1000                 }
1001               else
1002                 {
1003                   /* The rename failed: give up on this length.  */
1004                   break;
1005                 }
1006             }
1007           else
1008             {
1009               /* newname exists, so increment BASE so we use another */
1010             }
1011         }
1012       while (incname (base, len));
1013       len--;
1014     }
1015   if (unlink (oldname) != 0)
1016     {
1017       error (0, errno, _("%s: failed to remove"), qoldname);
1018       ok = false;
1019     }
1020   else if (flags->verbose)
1021     error (0, 0, _("%s: removed"), qoldname);
1022   if (0 <= dir_fd)
1023     {
1024       if (dosync (dir_fd, qdir) != 0)
1025         ok = false;
1026       if (close (dir_fd) != 0)
1027         {
1028           error (0, errno, _("%s: failed to close"), qdir);
1029           ok = false;
1030         }
1031     }
1032   free (newname);
1033   free (dir);
1034   free (qdir);
1035   return ok;
1036 }
1037
1038 /*
1039  * Finally, the function that actually takes a filename and grinds
1040  * it into hamburger.
1041  *
1042  * FIXME
1043  * Detail to note: since we do not restore errno to EACCES after
1044  * a failed chmod, we end up printing the error code from the chmod.
1045  * This is actually the error that stopped us from proceeding, so
1046  * it's arguably the right one, and in practice it'll be either EACCES
1047  * again or EPERM, which both give similar error messages.
1048  * Does anyone disagree?
1049  */
1050 static bool
1051 wipefile (char *name, char const *qname,
1052           struct randint_source *s, struct Options const *flags)
1053 {
1054   bool ok;
1055   int fd;
1056
1057   fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1058   if (fd < 0
1059       && (errno == EACCES && flags->force)
1060       && chmod (name, S_IWUSR) == 0)
1061     fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1062   if (fd < 0)
1063     {
1064       error (0, errno, _("%s: failed to open for writing"), qname);
1065       return false;
1066     }
1067
1068   ok = do_wipefd (fd, qname, s, flags);
1069   if (close (fd) != 0)
1070     {
1071       error (0, errno, _("%s: failed to close"), qname);
1072       ok = false;
1073     }
1074   if (ok && flags->remove_file)
1075     ok = wipename (name, qname, flags);
1076   return ok;
1077 }
1078
1079
1080 /* Buffers for random data.  */
1081 static struct randint_source *randint_source;
1082
1083 /* Just on general principles, wipe buffers containing information
1084    that may be related to the possibly-pseudorandom values used during
1085    shredding.  */
1086 static void
1087 clear_random_data (void)
1088 {
1089   randint_all_free (randint_source);
1090 }
1091
1092
1093 int
1094 main (int argc, char **argv)
1095 {
1096   bool ok = true;
1097   struct Options flags = { 0, };
1098   char **file;
1099   int n_files;
1100   int c;
1101   int i;
1102   char const *random_source = NULL;
1103
1104   initialize_main (&argc, &argv);
1105   program_name = argv[0];
1106   setlocale (LC_ALL, "");
1107   bindtextdomain (PACKAGE, LOCALEDIR);
1108   textdomain (PACKAGE);
1109
1110   atexit (close_stdout);
1111
1112   flags.n_iterations = DEFAULT_PASSES;
1113   flags.size = -1;
1114
1115   while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1116     {
1117       switch (c)
1118         {
1119         case 'f':
1120           flags.force = true;
1121           break;
1122
1123         case 'n':
1124           {
1125             uintmax_t tmp;
1126             if (xstrtoumax (optarg, NULL, 10, &tmp, NULL) != LONGINT_OK
1127                 || MIN (UINT32_MAX, SIZE_MAX / sizeof (int)) < tmp)
1128               {
1129                 error (EXIT_FAILURE, 0, _("%s: invalid number of passes"),
1130                        quotearg_colon (optarg));
1131               }
1132             flags.n_iterations = tmp;
1133           }
1134           break;
1135
1136         case RANDOM_SOURCE_OPTION:
1137           if (random_source && !STREQ (random_source, optarg))
1138             error (EXIT_FAILURE, 0, _("multiple random sources specified"));
1139           random_source = optarg;
1140           break;
1141
1142         case 'u':
1143           flags.remove_file = true;
1144           break;
1145
1146         case 's':
1147           {
1148             uintmax_t tmp;
1149             if (xstrtoumax (optarg, NULL, 0, &tmp, "cbBkKMGTPEZY0")
1150                 != LONGINT_OK)
1151               {
1152                 error (EXIT_FAILURE, 0, _("%s: invalid file size"),
1153                        quotearg_colon (optarg));
1154               }
1155             flags.size = tmp;
1156           }
1157           break;
1158
1159         case 'v':
1160           flags.verbose = true;
1161           break;
1162
1163         case 'x':
1164           flags.exact = true;
1165           break;
1166
1167         case 'z':
1168           flags.zero_fill = true;
1169           break;
1170
1171         case_GETOPT_HELP_CHAR;
1172
1173         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1174
1175         default:
1176           usage (EXIT_FAILURE);
1177         }
1178     }
1179
1180   file = argv + optind;
1181   n_files = argc - optind;
1182
1183   if (n_files == 0)
1184     {
1185       error (0, 0, _("missing file operand"));
1186       usage (EXIT_FAILURE);
1187     }
1188
1189   randint_source = randint_all_new (random_source, SIZE_MAX);
1190   if (! randint_source)
1191     error (EXIT_FAILURE, errno, "%s", quotearg_colon (random_source));
1192   atexit (clear_random_data);
1193
1194   for (i = 0; i < n_files; i++)
1195     {
1196       char *qname = xstrdup (quotearg_colon (file[i]));
1197       if (STREQ (file[i], "-"))
1198         {
1199           ok &= wipefd (STDOUT_FILENO, qname, randint_source, &flags);
1200         }
1201       else
1202         {
1203           /* Plain filename - Note that this overwrites *argv! */
1204           ok &= wipefile (file[i], qname, randint_source, &flags);
1205         }
1206       free (qname);
1207     }
1208
1209   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
1210 }
1211 /*
1212  * vim:sw=2:sts=2:
1213  */