1 /* shred.c - Overwrite a file to securely delete
3 * Copyright 2014 Rob Landley <rob@landley.net>
7 USE_SHRED(NEWTOY(shred, "<1zxus#<1n#<1o#<0f", TOYFLAG_USR|TOYFLAG_BIN))
13 usage: shred [-fuz] [-n COUNT] [-s SIZE] FILE...
15 Securely delete a file by overwriting its contents with random data.
17 -f Force (chmod if necessary)
18 -n COUNT Random overwrite iterations (default 1)
19 -o OFFSET Start at OFFSET
20 -s SIZE Use SIZE instead of detecting file size
21 -u unlink (actually delete file when done)
22 -x Use exact size (default without -s rounds up to next 4k)
25 Note: data journaling filesystems render this command useless, you must
26 overwrite all free space (fill up disk) to erase old data on those.
44 if (!(toys.optflags & FLAG_n)) TT.iterations++;
45 TT.ufd = xopen("/dev/urandom", O_RDONLY);
47 // We don't use loopfiles() here because "-" isn't stdin, and want to
48 // respond to files we can't open via chmod.
50 for (try = toys.optargs; *try; try++) {
51 off_t pos = 0, len = TT.size;
52 int fd = open(*try, O_RDWR), iter = 0, throw;
54 // do -f chmod if necessary
55 if (fd == -1 && (toys.optflags & FLAG_f)) {
57 fd = open(*try, O_RDWR);
60 perror_msg("%s", *try);
65 if (!len) len = fdlength(fd);
67 error_msg("%s: needs -s", *try);
72 // Loop through, writing to this file
74 // Advance to next -n or -z?
78 if (++iter == TT.iterations && (toys.optargs && FLAG_z)) {
79 memset(toybuf, 0, sizeof(toybuf));
82 if (iter >= TT.iterations) break;
85 if (pos < TT.offset) {
86 if (TT.offset != lseek(fd, TT.offset, SEEK_SET)) {
87 perror_msg("%s", *try);
93 // Determine length, read random data if not zeroing, write.
95 throw = sizeof(toybuf);
96 if (toys.optflags & FLAG_x)
97 if (len-pos < throw) throw = len-pos;
99 if (iter != TT.iterations) xread(TT.ufd, toybuf, throw);
100 if (throw != writeall(fd, toybuf, throw)) perror_msg("%s");