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