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#define FOR_shred
30#include "toys.h"
31
32GLOBALS(
33 long o, n, s;
34)
35
36void shred_main(void)
37{
38 char **try;
39
40 if (!(toys.optflags & FLAG_n)) TT.n++;
41
42
43
44
45 for (try = toys.optargs; *try; try++) {
46 off_t pos = 0, len = TT.s;
47 int fd = open(*try, O_RDWR), iter = 0, throw;
48
49
50 if (fd == -1 && (toys.optflags & FLAG_f)) {
51 chmod(*try, 0600);
52 fd = open(*try, O_RDWR);
53 }
54 if (fd == -1) {
55 perror_msg_raw(*try);
56 continue;
57 }
58
59
60 if (!len) len = fdlength(fd);
61 if (len<1) {
62 error_msg("%s: needs -s", *try);
63 close(fd);
64 continue;
65 }
66
67
68 for (;;) {
69
70
71 if (pos >= len) {
72 pos = -1;
73 if (++iter == TT.n && (toys.optargs && FLAG_z)) {
74 memset(toybuf, 0, sizeof(toybuf));
75 continue;
76 }
77 if (iter >= TT.n) break;
78 }
79
80 if (pos < TT.o) {
81 if (TT.o != lseek(fd, TT.o, SEEK_SET)) {
82 perror_msg_raw(*try);
83 break;
84 }
85 pos = TT.o;
86 }
87
88
89
90 throw = sizeof(toybuf);
91 if (toys.optflags & FLAG_x)
92 if (len-pos < throw) throw = len-pos;
93
94 if (iter != TT.n) xgetrandom(toybuf, throw, 0);
95 if (throw != writeall(fd, toybuf, throw)) perror_msg_raw(*try);
96 pos += throw;
97 }
98 if (toys.optflags & FLAG_u)
99 if (unlink(*try)) perror_msg("unlink '%s'", *try);
100 }
101}
102