-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
419 lines (349 loc) · 8.44 KB
/
main.go
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package main
import (
"crypto/sha256"
"encoding/json"
"flag"
"fmt"
"hash"
"io"
"io/ioutil"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
progressbar "github.com/schollz/progressbar/v3"
"github.com/sirupsen/logrus"
)
// Constants
const BLOCKSIZE = 128_000
// Configurations
var shuffleBytes bool
var continuous bool
var threads int
var guard chan struct{}
var wg sync.WaitGroup
var finished bool
// Runtime globals
var log *logrus.Logger
var done = make(chan os.Signal, 1)
// Completed files
type Completed struct {
CompletedFiles []string `json:"completed_files"`
CompletedInodes []uint64 `json:"completed_inodes"`
}
var completed = Completed{}
func saveCompleted() {
data, _ := json.MarshalIndent(completed, "", " ")
if err := os.WriteFile("progress.json", data, 0644); err != nil {
panic(err)
}
}
func readCompleted() {
if bytes, err := ioutil.ReadFile("progress.json"); err == nil {
if err := json.Unmarshal(bytes, &completed); err != nil {
panic(err)
}
}
}
func createBackupFile(path string, info os.FileInfo) (hash.Hash, error) {
// Prepare backup path
backupPath := fmt.Sprintf("%s.bak", path)
// Open backup file as readwrite
backupFile, err := os.Create(backupPath)
if err != nil {
return nil, err
}
defer backupFile.Close()
// Open file
file, err := os.OpenFile(path, os.O_RDWR, info.Mode().Perm())
if err != nil {
return nil, err
}
defer file.Close()
// Prepare progressbar
log.Infof("Backing up file '%s'", path)
bar := progressbar.DefaultBytes(info.Size(), "backing up")
defer func() {
if err := bar.Finish(); err != nil {
log.Error(err)
}
}()
// Copy to backup file while calculating hash
hash := sha256.New()
if _, err = io.Copy(io.MultiWriter(backupFile, bar, hash), file); err != nil {
return nil, err
}
// Return hash with no error
return hash, nil
}
func deleteBackupFile(path string) (err error) {
// Prepare backup path
backupPath := fmt.Sprintf("%s.bak", path)
// Remove backup path if exists
if _, err = os.Stat(backupPath); err == nil {
if err = os.Remove(backupPath); err != nil {
return err
}
}
// No error
return nil
}
func restoreBackupFile(path string, info os.FileInfo) error {
// Prepare backup path
backupPath := fmt.Sprintf("%s.bak", path)
// Open backup file as readwrite
backupFile, err := os.OpenFile(backupPath, os.O_RDWR, info.Mode().Perm())
if err != nil {
return err
}
defer backupFile.Close()
// Open file
file, err := os.OpenFile(path, os.O_RDWR, info.Mode().Perm())
if err != nil {
return err
}
defer file.Close()
// Prepare progressbar
log.Infof("Backing up file '%s'", path)
bar := progressbar.DefaultBytes(info.Size(), "backing up")
defer func() {
if err := bar.Finish(); err != nil {
log.Error(err)
}
}()
// Copy to original file
if _, err = io.Copy(io.MultiWriter(file, bar), backupFile); err != nil {
return err
}
// Return with no error
return nil
}
func RewriteFile(path string, info os.FileInfo, shuffle bool) (hash.Hash, error) {
// Open file
file, err := os.OpenFile(path, os.O_RDWR, info.Mode().Perm())
if err != nil {
return nil, err
}
defer file.Close()
// Prepare progress bar
bar := progressbar.DefaultBytes(info.Size(), "rewriting")
// Loop through whole file in BLOCKSIZE chunks
hash := sha256.New()
for i := int64(0); i < info.Size(); i += BLOCKSIZE {
// Prepare buffer
buf := make([]byte, BLOCKSIZE)
// Read BLOCKSIZE bytes at offset
n, err := file.ReadAt(buf, i)
if err != nil && err != io.EOF {
return nil, fmt.Errorf("failed to read to buf: %v", err)
}
buf = buf[:n]
// Swap bytes if specified and able
if shuffle && n > 2 {
buf[0], buf[1] = buf[1], buf[0]
}
// Write BLOCKSIZE bytes back at offset
if _, err := file.WriteAt(buf, i); err != nil {
return nil, err
}
// Add to hash
hash.Write(buf)
// Propagate progress bar
if err = bar.Add(BLOCKSIZE); err != nil {
if err = bar.Finish(); err != nil {
panic(err) // Really shouldn't ever reach this point
}
}
}
// Set modified time back
if err := os.Chtimes(path, info.ModTime(), info.ModTime()); err != nil {
log.Errorf("Failed to set modified time for file '%s'", path)
}
// Return hash with no error
return hash, nil
}
func ShuffleRewriteFile(path string, info os.FileInfo) (err error) {
// Backup file
var oldHash hash.Hash
if oldHash, err = createBackupFile(path, info); err != nil {
return err
}
// Loop twice
var newHash hash.Hash
for n := 0; n < 2; n++ {
if newHash, err = RewriteFile(path, info, true); err != nil {
return err
}
}
// If for some reason, hashes are not the same, restore backup
oldHashString := fmt.Sprintf("%x", oldHash.Sum(nil))
newHashString := fmt.Sprintf("%x", newHash.Sum(nil))
if oldHashString != newHashString {
if err := restoreBackupFile(path, info); err != nil {
log.Errorf("failed to restore backup: %v", err)
}
return fmt.Errorf("rewrite failed, hash mismatch '%s' != '%s'", oldHashString, newHashString)
}
// Delete backup file
if err := deleteBackupFile(path); err != nil {
log.Errorf("failed to delete backup file: %v", err)
}
// Return no error
return nil
}
func IsCompleted(path string, inode uint64) bool {
for _, b := range completed.CompletedFiles {
if b == path {
log.Infof("Skipping file '%s'\n", path)
// Check if inode exists
inodeExists := false
for _, i := range completed.CompletedInodes {
if i == inode {
inodeExists = true
break
}
}
// If not in CompletedInodes, add to it
if !inodeExists {
completed.CompletedInodes = append(completed.CompletedInodes, inode)
}
// Return early
return false
}
}
for _, b := range completed.CompletedInodes {
if b == inode {
log.Infof("Skipping inode '%d'\n", inode)
// Check if path exists
pathExists := false
for _, i := range completed.CompletedFiles {
if i == path {
pathExists = true
break
}
}
// If not in CompletedFiles, add to it
if !pathExists {
completed.CompletedFiles = append(completed.CompletedFiles, path)
}
// Return early
return false
}
}
return true
}
func Rewrite(path string, info os.FileInfo, err error) error {
// Call lstat() if info is nil, return if error
if info == nil {
info, err = os.Lstat(path)
if err != nil {
return err
}
}
// Return early if not file
if info.IsDir() {
return nil
}
// Get file inode
stat, _ := info.Sys().(*syscall.Stat_t)
inode := stat.Ino
// Return early if error
if err != nil {
return err
}
// Return early if already completed and not continuously rewriting
if !continuous && !IsCompleted(path, inode) {
return nil
}
// Rewrite file
if shuffleBytes {
if err := ShuffleRewriteFile(path, info); err != nil {
return err
}
} else {
if _, err := RewriteFile(path, info, false); err != nil {
return err
}
}
// Log
log.Infof("Rewritten file '%s'", path)
// Save progress
completed.CompletedFiles = append(completed.CompletedFiles, path)
if stat != nil {
completed.CompletedInodes = append(completed.CompletedInodes, stat.Ino)
}
saveCompleted()
// Return nil
return nil
}
func RewriteRouting(path string, info os.FileInfo, err error) error {
// Start goroutine
guard <- struct{}{}
wg.Add(1)
go func() {
err = Rewrite(path, info, err)
if err != nil {
log.Errorf("Rewrite failed: %+v", err)
}
wg.Done()
<-guard
}()
// Return error if finished
if finished {
return io.EOF
}
// Else continue
return nil
}
func init() {
// Prepare logger and load completed items
log = logrus.New()
readCompleted()
// Prepare signal handler
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
}
func main() {
// Get arguments
flag.BoolVar(&continuous, "c", false, "continuously rewrite")
flag.BoolVar(&shuffleBytes, "s", false, "shuffle bytes on rewrite")
flag.IntVar(&threads, "t", 1, "threads")
progname := filepath.Base(os.Args[0])
flag.Usage = func() {
fmt.Fprintf(os.Stderr, `
Usage of %s:
%s [flags] ./directory
Flags:
`, progname, progname)
flag.PrintDefaults()
}
flag.Parse()
// Check argument count
if flag.NArg() != 1 {
flag.Usage()
os.Exit(1)
}
// Ensure quit
go func() {
<-done
log.Infof("Finishing...")
finished = true
}()
// Get all files and folders
guard = make(chan struct{}, threads)
for {
err := filepath.Walk(flag.Arg(0), RewriteRouting)
if err == io.EOF || finished {
log.Infof("Program exited successfully")
break
} else if err != nil {
close(guard)
panic(err)
}
if !continuous {
break
}
}
// Cleanup
wg.Wait()
}