split: port ‘split -n N /dev/null’ better to macOS
[coreutils.git] / src / shred.c
blob3ec8fe1f08b522d0360c03f6e0d31ffb6160ee1e
1 /* shred.c - overwrite files and devices to make it harder to recover data
3 Copyright (C) 1999-2023 Free Software Foundation, Inc.
4 Copyright (C) 1997, 1998, 1999 Colin Plumb.
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.
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.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <https://www.gnu.org/licenses/>.
19 Written by Colin Plumb. */
22 * Do a more secure overwrite of given files or devices, to make it harder
23 * for even very expensive hardware probing to recover the data.
25 * Although this process is also known as "wiping", I prefer the longer
26 * name both because I think it is more evocative of what is happening and
27 * because a longer name conveys a more appropriate sense of deliberateness.
29 * For the theory behind this, see "Secure Deletion of Data from Magnetic
30 * and Solid-State Memory", on line at
31 * https://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html
33 * Just for the record, reversing one or two passes of disk overwrite
34 * is not terribly difficult with hardware help. Hook up a good-quality
35 * digitizing oscilloscope to the output of the head preamplifier and copy
36 * the high-res digitized data to a computer for some off-line analysis.
37 * Read the "current" data and average all the pulses together to get an
38 * "average" pulse on the disk. Subtract this average pulse from all of
39 * the actual pulses and you can clearly see the "echo" of the previous
40 * data on the disk.
42 * Real hard drives have to balance the cost of the media, the head,
43 * and the read circuitry. They use better-quality media than absolutely
44 * necessary to limit the cost of the read circuitry. By throwing that
45 * assumption out, and the assumption that you want the data processed
46 * as fast as the hard drive can spin, you can do better.
48 * If asked to wipe a file, this also unlinks it, renaming it in a
49 * clever way to try to leave no trace of the original filename.
51 * This was inspired by a desire to improve on some code titled:
52 * Wipe V1.0-- Overwrite and delete files. S. 2/3/96
53 * but I've rewritten everything here so completely that no trace of
54 * the original remains.
56 * Thanks to:
57 * Bob Jenkins, for his good RNG work and patience with the FSF copyright
58 * paperwork.
59 * Jim Meyering, for his work merging this into the GNU fileutils while
60 * still letting me feel a sense of ownership and pride. Getting me to
61 * tolerate the GNU brace style was quite a feat of diplomacy.
62 * Paul Eggert, for lots of useful discussion and code. I disagree with
63 * an awful lot of his suggestions, but they're disagreements worth having.
65 * Things to think about:
66 * - Security: Is there any risk to the race
67 * between overwriting and unlinking a file? Will it do anything
68 * drastically bad if told to attack a named pipe or socket?
71 /* The official name of this program (e.g., no 'g' prefix). */
72 #define PROGRAM_NAME "shred"
74 #define AUTHORS proper_name ("Colin Plumb")
76 #include <config.h>
78 #include <getopt.h>
79 #include <stdio.h>
80 #include <assert.h>
81 #include <setjmp.h>
82 #include <sys/types.h>
83 #if defined __linux__ && HAVE_SYS_MTIO_H
84 # include <sys/mtio.h>
85 #endif
87 #include "system.h"
88 #include "alignalloc.h"
89 #include "argmatch.h"
90 #include "xdectoint.h"
91 #include "die.h"
92 #include "error.h"
93 #include "fcntl--.h"
94 #include "human.h"
95 #include "randint.h"
96 #include "randread.h"
97 #include "renameatu.h"
98 #include "stat-size.h"
100 /* Default number of times to overwrite. */
101 enum { DEFAULT_PASSES = 3 };
103 /* How many seconds to wait before checking whether to output another
104 verbose output line. */
105 enum { VERBOSE_UPDATE = 5 };
107 /* Sector size and corresponding mask, for recovering after write failures.
108 The size must be a power of 2. */
109 enum { SECTOR_SIZE = 512 };
110 enum { SECTOR_MASK = SECTOR_SIZE - 1 };
111 static_assert (0 < SECTOR_SIZE && (SECTOR_SIZE & SECTOR_MASK) == 0);
113 enum remove_method
115 remove_none = 0, /* the default: only wipe data. */
116 remove_unlink, /* don't obfuscate name, just unlink. */
117 remove_wipe, /* obfuscate name before unlink. */
118 remove_wipesync /* obfuscate name, syncing each byte, before unlink. */
121 static char const *const remove_args[] =
123 "unlink", "wipe", "wipesync", NULL
126 static enum remove_method const remove_methods[] =
128 remove_unlink, remove_wipe, remove_wipesync
131 struct Options
133 bool force; /* -f flag: chmod files if necessary */
134 size_t n_iterations; /* -n flag: Number of iterations */
135 off_t size; /* -s flag: size of file */
136 enum remove_method remove_file; /* -u flag: remove file after shredding */
137 bool verbose; /* -v flag: Print progress */
138 bool exact; /* -x flag: Do not round up file size */
139 bool zero_fill; /* -z flag: Add a final zero pass */
142 /* For long options that have no equivalent short option, use a
143 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
144 enum
146 RANDOM_SOURCE_OPTION = CHAR_MAX + 1
149 static struct option const long_opts[] =
151 {"exact", no_argument, NULL, 'x'},
152 {"force", no_argument, NULL, 'f'},
153 {"iterations", required_argument, NULL, 'n'},
154 {"size", required_argument, NULL, 's'},
155 {"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION},
156 {"remove", optional_argument, NULL, 'u'},
157 {"verbose", no_argument, NULL, 'v'},
158 {"zero", no_argument, NULL, 'z'},
159 {GETOPT_HELP_OPTION_DECL},
160 {GETOPT_VERSION_OPTION_DECL},
161 {NULL, 0, NULL, 0}
164 void
165 usage (int status)
167 if (status != EXIT_SUCCESS)
168 emit_try_help ();
169 else
171 printf (_("Usage: %s [OPTION]... FILE...\n"), program_name);
172 fputs (_("\
173 Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\
174 for even very expensive hardware probing to recover the data.\n\
175 "), stdout);
176 fputs (_("\
178 If FILE is -, shred standard output.\n\
179 "), stdout);
181 emit_mandatory_arg_note ();
183 printf (_("\
184 -f, --force change permissions to allow writing if necessary\n\
185 -n, --iterations=N overwrite N times instead of the default (%d)\n\
186 --random-source=FILE get random bytes from FILE\n\
187 -s, --size=N shred this many bytes (suffixes like K, M, G accepted)\n\
188 "), DEFAULT_PASSES);
189 fputs (_("\
190 -u deallocate and remove file after overwriting\n\
191 --remove[=HOW] like -u but give control on HOW to delete; See below\n\
192 -v, --verbose show progress\n\
193 -x, --exact do not round file sizes up to the next full block;\n\
194 this is the default for non-regular files\n\
195 -z, --zero add a final overwrite with zeros to hide shredding\n\
196 "), stdout);
197 fputs (HELP_OPTION_DESCRIPTION, stdout);
198 fputs (VERSION_OPTION_DESCRIPTION, stdout);
199 fputs (_("\
201 Delete FILE(s) if --remove (-u) is specified. The default is not to remove\n\
202 the files because it is common to operate on device files like /dev/hda,\n\
203 and those files usually should not be removed.\n\
204 The optional HOW parameter indicates how to remove a directory entry:\n\
205 'unlink' => use a standard unlink call.\n\
206 'wipe' => also first obfuscate bytes in the name.\n\
207 'wipesync' => also sync each obfuscated byte to the device.\n\
208 The default mode is 'wipesync', but note it can be expensive.\n\
210 "), stdout);
211 fputs (_("\
212 CAUTION: shred assumes the file system and hardware overwrite data in place.\n\
213 Although this is common, many platforms operate otherwise. Also, backups\n\
214 and mirrors may contain unremovable copies that will let a shredded file\n\
215 be recovered later. See the GNU coreutils manual for details.\n\
216 "), stdout);
217 emit_ancillary_info (PROGRAM_NAME);
219 exit (status);
223 * Determine if pattern type is periodic or not.
225 static bool
226 periodic_pattern (int type)
228 if (type <= 0)
229 return false;
231 unsigned char r[3];
232 unsigned int bits = type & 0xfff;
234 bits |= bits << 12;
235 r[0] = (bits >> 4) & 255;
236 r[1] = (bits >> 8) & 255;
237 r[2] = bits & 255;
239 return (r[0] != r[1]) || (r[0] != r[2]);
243 * Fill a buffer with a fixed pattern.
245 * The buffer must be at least 3 bytes long, even if
246 * size is less. Larger sizes are filled exactly.
248 static void
249 fillpattern (int type, unsigned char *r, size_t size)
251 size_t i;
252 unsigned int bits = type & 0xfff;
254 bits |= bits << 12;
255 r[0] = (bits >> 4) & 255;
256 r[1] = (bits >> 8) & 255;
257 r[2] = bits & 255;
258 for (i = 3; i <= size / 2; i *= 2)
259 memcpy (r + i, r, i);
260 if (i < size)
261 memcpy (r + i, r, size - i);
263 /* Invert the first bit of every sector. */
264 if (type & 0x1000)
265 for (i = 0; i < size; i += SECTOR_SIZE)
266 r[i] ^= 0x80;
270 * Generate a 6-character (+ nul) pass name string
271 * FIXME: allow translation of "random".
273 #define PASS_NAME_SIZE 7
274 static void
275 passname (unsigned char const *data, char name[PASS_NAME_SIZE])
277 if (data)
278 sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);
279 else
280 memcpy (name, "random", PASS_NAME_SIZE);
283 /* Return true when it's ok to ignore an fsync or fdatasync
284 failure that set errno to ERRNO_VAL. */
285 static bool
286 ignorable_sync_errno (int errno_val)
288 return (errno_val == EINVAL
289 || errno_val == EBADF
290 /* HP-UX does this */
291 || errno_val == EISDIR);
294 /* Request that all data for FD be transferred to the corresponding
295 storage device. QNAME is the file name (quoted for colons).
296 Report any errors found. Return 0 on success, -1
297 (setting errno) on failure. It is not an error if fdatasync and/or
298 fsync is not supported for this file, or if the file is not a
299 writable file descriptor. */
300 static int
301 dosync (int fd, char const *qname)
303 int err;
305 #if HAVE_FDATASYNC
306 if (fdatasync (fd) == 0)
307 return 0;
308 err = errno;
309 if ( ! ignorable_sync_errno (err))
311 error (0, err, _("%s: fdatasync failed"), qname);
312 errno = err;
313 return -1;
315 #endif
317 if (fsync (fd) == 0)
318 return 0;
319 err = errno;
320 if ( ! ignorable_sync_errno (err))
322 error (0, err, _("%s: fsync failed"), qname);
323 errno = err;
324 return -1;
327 sync ();
328 return 0;
331 /* Turn on or off direct I/O mode for file descriptor FD, if possible.
332 Try to turn it on if ENABLE is true. Otherwise, try to turn it off. */
333 static void
334 direct_mode (int fd, bool enable)
336 if (O_DIRECT)
338 int fd_flags = fcntl (fd, F_GETFL);
339 if (0 < fd_flags)
341 int new_flags = (enable
342 ? (fd_flags | O_DIRECT)
343 : (fd_flags & ~O_DIRECT));
344 if (new_flags != fd_flags)
345 fcntl (fd, F_SETFL, new_flags);
349 #if HAVE_DIRECTIO && defined DIRECTIO_ON && defined DIRECTIO_OFF
350 /* This is Solaris-specific. */
351 directio (fd, enable ? DIRECTIO_ON : DIRECTIO_OFF);
352 #endif
355 /* Rewind FD; its status is ST. */
356 static bool
357 dorewind (int fd, struct stat const *st)
359 if (S_ISCHR (st->st_mode))
361 #if defined __linux__ && HAVE_SYS_MTIO_H
362 /* In the Linux kernel, lseek does not work on tape devices; it
363 returns a randomish value instead. Try the low-level tape
364 rewind operation first. */
365 struct mtop op;
366 op.mt_op = MTREW;
367 op.mt_count = 1;
368 if (ioctl (fd, MTIOCTOP, &op) == 0)
369 return true;
370 #endif
372 off_t offset = lseek (fd, 0, SEEK_SET);
373 if (0 < offset)
374 errno = EINVAL;
375 return offset == 0;
378 /* By convention, negative sizes represent unknown values. */
380 static bool
381 known (off_t size)
383 return 0 <= size;
387 * Do pass number K of N, writing *SIZEP bytes of the given pattern TYPE
388 * to the file descriptor FD. K and N are passed in only for verbose
389 * progress message purposes. If N == 0, no progress messages are printed.
391 * If *SIZEP == -1, the size is unknown, and it will be filled in as soon
392 * as writing fails with ENOSPC.
394 * Return 1 on write error, -1 on other error, 0 on success.
396 static int
397 dopass (int fd, struct stat const *st, char const *qname, off_t *sizep,
398 int type, struct randread_source *s,
399 unsigned long int k, unsigned long int n)
401 off_t size = *sizep;
402 off_t offset; /* Current file position */
403 time_t thresh IF_LINT ( = 0); /* Time to maybe print next status update */
404 time_t now = 0; /* Current time */
405 size_t lim; /* Amount of data to try writing */
406 size_t soff; /* Offset into buffer for next write */
407 ssize_t ssize; /* Return value from write */
409 /* Fill pattern buffer. Aligning it to a page so we can do direct I/O. */
410 size_t page_size = getpagesize ();
411 #define PERIODIC_OUTPUT_SIZE (60 * 1024)
412 #define NONPERIODIC_OUTPUT_SIZE (64 * 1024)
413 static_assert (PERIODIC_OUTPUT_SIZE % 3 == 0);
414 size_t output_size = periodic_pattern (type)
415 ? PERIODIC_OUTPUT_SIZE : NONPERIODIC_OUTPUT_SIZE;
416 #define FILLPATTERN_SIZE (((output_size + 2) / 3) * 3) /* Multiple of 3 */
417 unsigned char *pbuf = xalignalloc (page_size, FILLPATTERN_SIZE);
419 char pass_string[PASS_NAME_SIZE]; /* Name of current pass */
420 bool write_error = false;
421 bool other_error = false;
423 /* Printable previous offset into the file */
424 char previous_offset_buf[LONGEST_HUMAN_READABLE + 1];
425 char const *previous_human_offset;
427 /* As a performance tweak, avoid direct I/O for small sizes,
428 as it's just a performance rather then security consideration,
429 and direct I/O can often be unsupported for small non aligned sizes. */
430 bool try_without_directio = 0 < size && size < output_size;
431 if (! try_without_directio)
432 direct_mode (fd, true);
434 if (! dorewind (fd, st))
436 error (0, errno, _("%s: cannot rewind"), qname);
437 other_error = true;
438 goto free_pattern_mem;
441 /* Constant fill patterns need only be set up once. */
442 if (type >= 0)
444 lim = known (size) && size < FILLPATTERN_SIZE ? size : FILLPATTERN_SIZE;
445 fillpattern (type, pbuf, lim);
446 passname (pbuf, pass_string);
448 else
450 passname (0, pass_string);
453 /* Set position if first status update */
454 if (n)
456 error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);
457 thresh = time (NULL) + VERBOSE_UPDATE;
458 previous_human_offset = "";
461 offset = 0;
462 while (true)
464 /* How much to write this time? */
465 lim = output_size;
466 if (known (size) && size - offset < output_size)
468 if (size < offset)
469 break;
470 lim = size - offset;
471 if (!lim)
472 break;
474 if (type < 0)
475 randread (s, pbuf, lim);
476 /* Loop to retry partial writes. */
477 for (soff = 0; soff < lim; soff += ssize)
479 ssize = write (fd, pbuf + soff, lim - soff);
480 if (0 < ssize)
481 assume (ssize <= lim - soff);
482 else
484 if (! known (size) && (ssize == 0 || errno == ENOSPC))
486 /* We have found the end of the file. */
487 if (soff <= OFF_T_MAX - offset)
488 *sizep = size = offset + soff;
489 break;
491 else
493 int errnum = errno;
494 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
496 /* Retry without direct I/O since this may not be supported
497 at all on some (file) systems, or with the current size.
498 I.e., a specified --size that is not aligned, or when
499 dealing with slop at the end of a file with --exact. */
500 if (! try_without_directio && errno == EINVAL)
502 direct_mode (fd, false);
503 ssize = 0;
504 try_without_directio = true;
505 continue;
507 error (0, errnum, _("%s: error writing at offset %s"),
508 qname, umaxtostr (offset + soff, buf));
510 /* 'shred' is often used on bad media, before throwing it
511 out. Thus, it shouldn't give up on bad blocks. This
512 code works because lim is always a multiple of
513 SECTOR_SIZE, except at the end. This size constraint
514 also enables direct I/O on some (file) systems. */
515 static_assert (PERIODIC_OUTPUT_SIZE % SECTOR_SIZE == 0);
516 static_assert (NONPERIODIC_OUTPUT_SIZE % SECTOR_SIZE == 0);
517 if (errnum == EIO && known (size)
518 && (soff | SECTOR_MASK) < lim)
520 size_t soff1 = (soff | SECTOR_MASK) + 1;
521 if (lseek (fd, offset + soff1, SEEK_SET) != -1)
523 /* Arrange to skip this block. */
524 ssize = soff1 - soff;
525 write_error = true;
526 continue;
528 error (0, errno, _("%s: lseek failed"), qname);
530 other_error = true;
531 goto free_pattern_mem;
536 /* Okay, we have written "soff" bytes. */
538 if (OFF_T_MAX - offset < soff)
540 error (0, 0, _("%s: file too large"), qname);
541 other_error = true;
542 goto free_pattern_mem;
545 offset += soff;
547 bool done = offset == size;
549 /* Time to print progress? */
550 if (n && ((done && *previous_human_offset)
551 || thresh <= (now = time (NULL))))
553 char offset_buf[LONGEST_HUMAN_READABLE + 1];
554 char size_buf[LONGEST_HUMAN_READABLE + 1];
555 int human_progress_opts = (human_autoscale | human_SI
556 | human_base_1024 | human_B);
557 char const *human_offset
558 = human_readable (offset, offset_buf,
559 human_floor | human_progress_opts, 1, 1);
561 if (done || !STREQ (previous_human_offset, human_offset))
563 if (! known (size))
564 error (0, 0, _("%s: pass %lu/%lu (%s)...%s"),
565 qname, k, n, pass_string, human_offset);
566 else
568 uintmax_t off = offset;
569 int percent = (size == 0
570 ? 100
571 : (off <= TYPE_MAXIMUM (uintmax_t) / 100
572 ? off * 100 / size
573 : off / (size / 100)));
574 char const *human_size
575 = human_readable (size, size_buf,
576 human_ceiling | human_progress_opts,
577 1, 1);
578 if (done)
579 human_offset = human_size;
580 error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s %d%%"),
581 qname, k, n, pass_string, human_offset, human_size,
582 percent);
585 strcpy (previous_offset_buf, human_offset);
586 previous_human_offset = previous_offset_buf;
587 thresh = now + VERBOSE_UPDATE;
590 * Force periodic syncs to keep displayed progress accurate
591 * FIXME: Should these be present even if -v is not enabled,
592 * to keep the buffer cache from filling with dirty pages?
593 * It's a common problem with programs that do lots of writes,
594 * like mkfs.
596 if (dosync (fd, qname) != 0)
598 if (errno != EIO)
600 other_error = true;
601 goto free_pattern_mem;
603 write_error = true;
609 /* Force what we just wrote to hit the media. */
610 if (dosync (fd, qname) != 0)
612 if (errno != EIO)
614 other_error = true;
615 goto free_pattern_mem;
617 write_error = true;
620 free_pattern_mem:
621 alignfree (pbuf);
623 return other_error ? -1 : write_error;
627 * The passes start and end with a random pass, and the passes in between
628 * are done in random order. The idea is to deprive someone trying to
629 * reverse the process of knowledge of the overwrite patterns, so they
630 * have the additional step of figuring out what was done to the device
631 * before they can try to reverse or cancel it.
633 * First, all possible 1-bit patterns. There are two of them.
634 * Then, all possible 2-bit patterns. There are four, but the two
635 * which are also 1-bit patterns can be omitted.
636 * Then, all possible 3-bit patterns. Likewise, 8-2 = 6.
637 * Then, all possible 4-bit patterns. 16-4 = 12.
639 * The basic passes are:
640 * 1-bit: 0x000, 0xFFF
641 * 2-bit: 0x555, 0xAAA
642 * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)
643 * 100100100100 110110110110
644 * 9 2 4 D B 6
645 * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
646 * 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)
647 * Adding three random passes at the beginning, middle and end
648 * produces the default 25-pass structure.
650 * The next extension would be to 5-bit and 6-bit patterns.
651 * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered
652 * 6-bit patterns, so they would increase the time required
653 * significantly. 4-bit patterns are enough for most purposes.
655 * The main gotcha is that this would require a trickier encoding,
656 * since lcm(2,3,4) = 12 bits is easy to fit into an int, but
657 * lcm(2,3,4,5) = 60 bits is not.
659 * One extension that is included is to complement the first bit in each
660 * 512-byte block, to alter the phase of the encoded data in the more
661 * complex encodings. This doesn't apply to MFM, so the 1-bit patterns
662 * are considered part of the 3-bit ones and the 2-bit patterns are
663 * considered part of the 4-bit patterns.
666 * How does the generalization to variable numbers of passes work?
668 * Here's how...
669 * Have an ordered list of groups of passes. Each group is a set.
670 * Take as many groups as will fit, plus a random subset of the
671 * last partial group, and place them into the passes list.
672 * Then shuffle the passes list into random order and use that.
674 * One extra detail: if we can't include a large enough fraction of the
675 * last group to be interesting, then just substitute random passes.
677 * If you want more passes than the entire list of groups can
678 * provide, just start repeating from the beginning of the list.
680 static int const
681 patterns[] =
683 -2, /* 2 random passes */
684 2, 0x000, 0xFFF, /* 1-bit */
685 2, 0x555, 0xAAA, /* 2-bit */
686 -1, /* 1 random pass */
687 6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6, /* 3-bit */
688 12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,
689 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */
690 -1, /* 1 random pass */
691 /* The following patterns have the first bit per block flipped */
692 8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,
693 14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,
694 0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,
695 -1, /* 1 random pass */
696 0 /* End */
700 * Generate a random wiping pass pattern with num passes.
701 * This is a two-stage process. First, the passes to include
702 * are chosen, and then they are shuffled into the desired
703 * order.
705 static void
706 genpattern (int *dest, size_t num, struct randint_source *s)
708 size_t randpasses;
709 int const *p;
710 int *d;
711 size_t n;
712 size_t accum, top, swap;
713 int k;
715 if (!num)
716 return;
718 /* Stage 1: choose the passes to use */
719 p = patterns;
720 randpasses = 0;
721 d = dest; /* Destination for generated pass list */
722 n = num; /* Passes remaining to fill */
724 while (true)
726 k = *p++; /* Block descriptor word */
727 if (!k)
728 { /* Loop back to the beginning */
729 p = patterns;
731 else if (k < 0)
732 { /* -k random passes */
733 k = -k;
734 if ((size_t) k >= n)
736 randpasses += n;
737 break;
739 randpasses += k;
740 n -= k;
742 else if ((size_t) k <= n)
743 { /* Full block of patterns */
744 memcpy (d, p, k * sizeof (int));
745 p += k;
746 d += k;
747 n -= k;
749 else if (n < 2 || 3 * n < (size_t) k)
750 { /* Finish with random */
751 randpasses += n;
752 break;
754 else
755 { /* Pad out with n of the k available */
758 if (n == (size_t) k || randint_choose (s, k) < n)
760 *d++ = *p;
761 n--;
763 p++;
764 k--;
766 while (n);
767 break;
770 top = num - randpasses; /* Top of initialized data */
771 /* assert (d == dest + top); */
774 * We now have fixed patterns in the dest buffer up to
775 * "top", and we need to scramble them, with "randpasses"
776 * random passes evenly spaced among them.
778 * We want one at the beginning, one at the end, and
779 * evenly spaced in between. To do this, we basically
780 * use Bresenham's line draw (a.k.a DDA) algorithm
781 * to draw a line with slope (randpasses-1)/(num-1).
782 * (We use a positive accumulator and count down to
783 * do this.)
785 * So for each desired output value, we do the following:
786 * - If it should be a random pass, copy the pass type
787 * to top++, out of the way of the other passes, and
788 * set the current pass to -1 (random).
789 * - If it should be a normal pattern pass, choose an
790 * entry at random between here and top-1 (inclusive)
791 * and swap the current entry with that one.
793 randpasses--; /* To speed up later math */
794 accum = randpasses; /* Bresenham DDA accumulator */
795 for (n = 0; n < num; n++)
797 if (accum <= randpasses)
799 accum += num - 1;
800 dest[top++] = dest[n];
801 dest[n] = -1;
803 else
805 swap = n + randint_choose (s, top - n);
806 k = dest[n];
807 dest[n] = dest[swap];
808 dest[swap] = k;
810 accum -= randpasses;
812 /* assert (top == num); */
816 * The core routine to actually do the work. This overwrites the first
817 * size bytes of the given fd. Return true if successful.
819 static bool
820 do_wipefd (int fd, char const *qname, struct randint_source *s,
821 struct Options const *flags)
823 size_t i;
824 struct stat st;
825 off_t size; /* Size to write, size to read */
826 off_t i_size = 0; /* For small files, initial size to overwrite inode */
827 unsigned long int n; /* Number of passes for printing purposes */
828 int *passarray;
829 bool ok = true;
830 struct randread_source *rs;
832 n = 0; /* dopass takes n == 0 to mean "don't print progress" */
833 if (flags->verbose)
834 n = flags->n_iterations + flags->zero_fill;
836 if (fstat (fd, &st))
838 error (0, errno, _("%s: fstat failed"), qname);
839 return false;
842 /* If we know that we can't possibly shred the file, give up now.
843 Otherwise, we may go into an infinite loop writing data before we
844 find that we can't rewind the device. */
845 if ((S_ISCHR (st.st_mode) && isatty (fd))
846 || S_ISFIFO (st.st_mode)
847 || S_ISSOCK (st.st_mode))
849 error (0, 0, _("%s: invalid file type"), qname);
850 return false;
852 else if (S_ISREG (st.st_mode) && st.st_size < 0)
854 error (0, 0, _("%s: file has negative size"), qname);
855 return false;
858 /* Allocate pass array */
859 passarray = xnmalloc (flags->n_iterations, sizeof *passarray);
861 size = flags->size;
862 if (size == -1)
864 if (S_ISREG (st.st_mode))
866 size = st.st_size;
868 if (! flags->exact)
870 /* Round up to the nearest block size to clear slack space. */
871 off_t remainder = size % ST_BLKSIZE (st);
872 if (size && size < ST_BLKSIZE (st))
873 i_size = size;
874 if (remainder != 0)
876 off_t size_incr = ST_BLKSIZE (st) - remainder;
877 size += MIN (size_incr, OFF_T_MAX - size);
881 else
883 /* The behavior of lseek is unspecified, but in practice if
884 it returns a positive number that's the size of this
885 device. */
886 size = lseek (fd, 0, SEEK_END);
887 if (size <= 0)
889 /* We are unable to determine the length, up front.
890 Let dopass do that as part of its first iteration. */
891 size = -1;
895 else if (S_ISREG (st.st_mode)
896 && st.st_size < MIN (ST_BLKSIZE (st), size))
897 i_size = st.st_size;
899 /* Schedule the passes in random order. */
900 genpattern (passarray, flags->n_iterations, s);
902 rs = randint_get_source (s);
904 while (true)
906 off_t pass_size;
907 unsigned long int pn = n;
909 if (i_size)
911 pass_size = i_size;
912 i_size = 0;
913 pn = 0;
915 else if (size)
917 pass_size = size;
918 size = 0;
920 /* TODO: consider handling tail packing by
921 writing the tail padding as a separate pass,
922 (that would not rewind). */
923 else
924 break;
926 for (i = 0; i < flags->n_iterations + flags->zero_fill; i++)
928 int err = 0;
929 int type = i < flags->n_iterations ? passarray[i] : 0;
931 err = dopass (fd, &st, qname, &pass_size, type, rs, i + 1, pn);
933 if (err)
935 ok = false;
936 if (err < 0)
937 goto wipefd_out;
942 /* Now deallocate the data. The effect of ftruncate is specified
943 on regular files and shared memory objects (also directories, but
944 they are not possible here); don't worry about errors reported
945 for other file types. */
947 if (flags->remove_file && ftruncate (fd, 0) != 0
948 && (S_ISREG (st.st_mode) || S_TYPEISSHM (&st)))
950 error (0, errno, _("%s: error truncating"), qname);
951 ok = false;
952 goto wipefd_out;
955 wipefd_out:
956 free (passarray);
957 return ok;
960 /* A wrapper with a little more checking for fds on the command line */
961 static bool
962 wipefd (int fd, char const *qname, struct randint_source *s,
963 struct Options const *flags)
965 int fd_flags = fcntl (fd, F_GETFL);
967 if (fd_flags < 0)
969 error (0, errno, _("%s: fcntl failed"), qname);
970 return false;
972 if (fd_flags & O_APPEND)
974 error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);
975 return false;
977 return do_wipefd (fd, qname, s, flags);
980 /* --- Name-wiping code --- */
982 /* Characters allowed in a file name - a safe universal set. */
983 static char const nameset[] =
984 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
986 /* Increment NAME (with LEN bytes). NAME must be a big-endian base N
987 number with the digits taken from nameset. Return true if successful.
988 Otherwise, (because NAME already has the greatest possible value)
989 return false. */
991 static bool
992 incname (char *name, size_t len)
994 while (len--)
996 char const *p = strchr (nameset, name[len]);
998 /* Given that NAME is composed of bytes from NAMESET,
999 P will never be NULL here. */
1000 assert (p);
1002 /* If this character has a successor, use it. */
1003 if (p[1])
1005 name[len] = p[1];
1006 return true;
1009 /* Otherwise, set this digit to 0 and increment the prefix. */
1010 name[len] = nameset[0];
1013 return false;
1017 * Repeatedly rename a file with shorter and shorter names,
1018 * to obliterate all traces of the file name (and length) on any system
1019 * that adds a trailing delimiter to on-device file names and reuses
1020 * the same directory slot. Finally, unlink it.
1021 * The passed-in filename is modified in place to the new filename.
1022 * (Which is unlinked if this function succeeds, but is still present if
1023 * it fails for some reason.)
1025 * The main loop is written carefully to not get stuck if all possible
1026 * names of a given length are occupied. It counts down the length from
1027 * the original to 0. While the length is non-zero, it tries to find an
1028 * unused file name of the given length. It continues until either the
1029 * name is available and the rename succeeds, or it runs out of names
1030 * to try (incname wraps and returns 1). Finally, it unlinks the file.
1032 * The unlink is Unix-specific, as ANSI-standard remove has more
1033 * portability problems with C libraries making it "safe". rename
1034 * is ANSI-standard.
1036 * To force the directory data out, we try to open the directory and
1037 * invoke fdatasync and/or fsync on it. This is non-standard, so don't
1038 * insist that it works: just fall back to a global sync in that case.
1039 * This is fairly significantly Unix-specific. Of course, on any
1040 * file system with synchronous metadata updates, this is unnecessary.
1042 static bool
1043 wipename (char *oldname, char const *qoldname, struct Options const *flags)
1045 char *newname = xstrdup (oldname);
1046 char *base = last_component (newname);
1047 char *dir = dir_name (newname);
1048 char *qdir = xstrdup (quotef (dir));
1049 bool first = true;
1050 bool ok = true;
1051 int dir_fd = -1;
1053 if (flags->remove_file == remove_wipesync)
1054 dir_fd = open (dir, O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK);
1056 if (flags->verbose)
1057 error (0, 0, _("%s: removing"), qoldname);
1059 if (flags->remove_file != remove_unlink)
1060 for (size_t len = base_len (base); len != 0; len--)
1062 memset (base, nameset[0], len);
1063 base[len] = 0;
1064 bool rename_ok;
1065 while (! (rename_ok = (renameatu (AT_FDCWD, oldname, AT_FDCWD, newname,
1066 RENAME_NOREPLACE)
1067 == 0))
1068 && errno == EEXIST && incname (base, len))
1069 continue;
1070 if (rename_ok)
1072 if (0 <= dir_fd && dosync (dir_fd, qdir) != 0)
1073 ok = false;
1074 if (flags->verbose)
1076 /* People seem to understand this better than talking
1077 about renaming OLDNAME. NEWNAME doesn't need
1078 quoting because we picked it. OLDNAME needs to be
1079 quoted only the first time. */
1080 char const *old = first ? qoldname : oldname;
1081 error (0, 0,
1082 _("%s: renamed to %s"), old, newname);
1083 first = false;
1085 memcpy (oldname + (base - newname), base, len + 1);
1089 if (unlink (oldname) != 0)
1091 error (0, errno, _("%s: failed to remove"), qoldname);
1092 ok = false;
1094 else if (flags->verbose)
1095 error (0, 0, _("%s: removed"), qoldname);
1096 if (0 <= dir_fd)
1098 if (dosync (dir_fd, qdir) != 0)
1099 ok = false;
1100 if (close (dir_fd) != 0)
1102 error (0, errno, _("%s: failed to close"), qdir);
1103 ok = false;
1106 free (newname);
1107 free (dir);
1108 free (qdir);
1109 return ok;
1113 * Finally, the function that actually takes a filename and grinds
1114 * it into hamburger.
1116 * FIXME
1117 * Detail to note: since we do not restore errno to EACCES after
1118 * a failed chmod, we end up printing the error code from the chmod.
1119 * This is actually the error that stopped us from proceeding, so
1120 * it's arguably the right one, and in practice it'll be either EACCES
1121 * again or EPERM, which both give similar error messages.
1122 * Does anyone disagree?
1124 static bool
1125 wipefile (char *name, char const *qname,
1126 struct randint_source *s, struct Options const *flags)
1128 bool ok;
1129 int fd;
1131 fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1132 if (fd < 0
1133 && (errno == EACCES && flags->force)
1134 && chmod (name, S_IWUSR) == 0)
1135 fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);
1136 if (fd < 0)
1138 error (0, errno, _("%s: failed to open for writing"), qname);
1139 return false;
1142 ok = do_wipefd (fd, qname, s, flags);
1143 if (close (fd) != 0)
1145 error (0, errno, _("%s: failed to close"), qname);
1146 ok = false;
1148 if (ok && flags->remove_file)
1149 ok = wipename (name, qname, flags);
1150 return ok;
1154 /* Buffers for random data. */
1155 static struct randint_source *randint_source;
1157 /* Just on general principles, wipe buffers containing information
1158 that may be related to the possibly-pseudorandom values used during
1159 shredding. */
1160 static void
1161 clear_random_data (void)
1163 randint_all_free (randint_source);
1168 main (int argc, char **argv)
1170 bool ok = true;
1171 struct Options flags = { 0, };
1172 char **file;
1173 int n_files;
1174 int c;
1175 int i;
1176 char const *random_source = NULL;
1178 initialize_main (&argc, &argv);
1179 set_program_name (argv[0]);
1180 setlocale (LC_ALL, "");
1181 bindtextdomain (PACKAGE, LOCALEDIR);
1182 textdomain (PACKAGE);
1184 atexit (close_stdout);
1186 flags.n_iterations = DEFAULT_PASSES;
1187 flags.size = -1;
1189 while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)
1191 switch (c)
1193 case 'f':
1194 flags.force = true;
1195 break;
1197 case 'n':
1198 flags.n_iterations = xdectoumax (optarg, 0,
1199 MIN (ULONG_MAX,
1200 SIZE_MAX / sizeof (int)), "",
1201 _("invalid number of passes"), 0);
1202 break;
1204 case RANDOM_SOURCE_OPTION:
1205 if (random_source && !STREQ (random_source, optarg))
1206 die (EXIT_FAILURE, 0, _("multiple random sources specified"));
1207 random_source = optarg;
1208 break;
1210 case 'u':
1211 if (optarg == NULL)
1212 flags.remove_file = remove_wipesync;
1213 else
1214 flags.remove_file = XARGMATCH ("--remove", optarg,
1215 remove_args, remove_methods);
1216 break;
1218 case 's':
1219 flags.size = xnumtoumax (optarg, 0, 0, OFF_T_MAX, "cbBkKMGTPEZYRQ0",
1220 _("invalid file size"), 0);
1221 break;
1223 case 'v':
1224 flags.verbose = true;
1225 break;
1227 case 'x':
1228 flags.exact = true;
1229 break;
1231 case 'z':
1232 flags.zero_fill = true;
1233 break;
1235 case_GETOPT_HELP_CHAR;
1237 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1239 default:
1240 usage (EXIT_FAILURE);
1244 file = argv + optind;
1245 n_files = argc - optind;
1247 if (n_files == 0)
1249 error (0, 0, _("missing file operand"));
1250 usage (EXIT_FAILURE);
1253 randint_source = randint_all_new (random_source, SIZE_MAX);
1254 if (! randint_source)
1255 die (EXIT_FAILURE, errno, "%s",
1256 quotef (random_source ? random_source : "getrandom"));
1257 atexit (clear_random_data);
1259 for (i = 0; i < n_files; i++)
1261 char *qname = xstrdup (quotef (file[i]));
1262 if (STREQ (file[i], "-"))
1264 ok &= wipefd (STDOUT_FILENO, qname, randint_source, &flags);
1266 else
1268 /* Plain filename - Note that this overwrites *argv! */
1269 ok &= wipefile (file[i], qname, randint_source, &flags);
1271 free (qname);
1274 return ok ? EXIT_SUCCESS : EXIT_FAILURE;
1277 * vim:sw=2:sts=2: