summaryrefslogtreecommitdiff
path: root/wipe-sectors.c
blob: cac0028f1befeb0cf9430f23d546fc93bd914af9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* Reads a block device and wipe a block if non-zero.
 * Author: Peter Wu <peter@lekensteyn.nl>
 * Date: 2014-06-26
 */
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <err.h>
#include <stdlib.h>

#define BUFSIZE (1024 * 1024 * 2)

static char zeroes[BUFSIZE];

static void wipe(int fd, size_t len) {
    off_t pos;
    ssize_t r;

    pos = lseek(fd, -len, SEEK_CUR);
    if (pos == (off_t) -1)
        err(1, "failed to seek before write");

    r = write(fd, zeroes, len);
    if (r < 0)
        err(1, "failed to write zeroes");
    if ((size_t) r != len)
        errx(1, "could only write %zu instead of %zu bytes", r, len);
}

static void read_and_wipe(int fd) {
    ssize_t r;
    off_t endpos, pos;
    char *buf = malloc(BUFSIZE);
    unsigned iteration = 0, rounds;
    if (buf == NULL)
        err(1, "malloc");

    endpos = lseek(fd, 0, SEEK_END);
    if (endpos == (off_t) -1)
        err(1, "failed to seek end");
    if (endpos == 0) {
        warnx("file is empty");
        return;
    }

    pos = lseek(fd, 0, SEEK_SET);
    if (pos == (off_t) -1)
        err(1, "failed to seek to begin");

    rounds = endpos / BUFSIZE;
    if (rounds * BUFSIZE < endpos)
        ++rounds;

    do {
        r = read(fd, buf, BUFSIZE);
        printf("\r%u/%u -- %u%% (%llu/%llu)",
            iteration, rounds,
            (unsigned) (100 * pos / endpos),
            (long long) pos, (long long) endpos);
        if (r < 0) {
            warn("read failed");
        } else if (r > 0) {
            char val = 0;
            int i;
            for (i = 0; i < r; i++) {
                val |= buf[i];
            }
            pos += r;
            /* if there are any non-zero bytes, act accordingly */
            if (val != 0) {
                printf(" WIPE ME!\n");
                wipe(fd, r);
            }
        }
        fflush(stdout);
        ++iteration;
    } while (r > 0);
    putchar('\n');

    free(buf);
}

int main(int argc, char **argv) {
    int fd;

    if (argc < 2)
        errx(1, "Missing device argument");

    fd = open(argv[1], O_RDWR);
    if (fd < 0)
        err(1, "failed to open file");

    read_and_wipe(fd);

    close(fd);

    return 0;
}