-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
119 lines (98 loc) · 2.52 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
package main
import (
"flag"
"fmt"
"image/jpeg"
"io"
"os"
"strconv"
)
type counterReader struct {
r io.Reader
Counter int64
}
func newCounterReader(r io.Reader) *counterReader {
return &counterReader{
r: r,
Counter: 0,
}
}
func (cr *counterReader) Read(b []byte) (n int, err error) {
n, err = cr.r.Read(b)
cr.Counter += int64(n)
return
}
func main() {
inputFileName := flag.String("f", "", "Input file name")
blockSize := flag.Int64("b", 512, "Size of disc block (cluster)")
verbose := flag.Bool("v", false, "Verbose output")
aprox := flag.Bool("a", false, "Extract clusters that starts with jpeg header even when we can't decode without errors")
flag.Parse()
if *inputFileName == "" {
fmt.Printf("Usage:\n%s -f inputfile [-v -b blockSize]\n", os.Args[0])
return
}
inputFile, err := os.Open(*inputFileName)
if err != nil {
fmt.Printf("Can't open input file: %s\n", err)
os.Exit(1)
}
defer func() {
err := inputFile.Close()
if err != nil {
fmt.Printf("Can't close input file: %s\n", err)
os.Exit(1)
}
}()
address := int64(0)
for {
counterReader := newCounterReader(inputFile)
_, err = jpeg.Decode(counterReader)
if err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
break
}
address += *blockSize
_, err := inputFile.Seek(address, io.SeekStart)
if err != nil {
fmt.Printf("Can't seek to next cluster: %s\n", err)
os.Exit(1)
}
continue
}
numWholeClusters := counterReader.Counter / (*blockSize)
partOfCluster := counterReader.Counter - numWholeClusters*(*blockSize)
if partOfCluster > 0 {
numWholeClusters++
}
outFile, err := os.Create(strconv.FormatInt(address, 10) + ".jpg")
if err != nil {
fmt.Printf("Can't create JPEG file: %s\n", err)
os.Exit(1)
}
_, err = inputFile.Seek(address, io.SeekStart)
if err != nil {
fmt.Printf("Can't seek back to file start cluster: %s\n", err)
os.Exit(1)
}
_, err = io.CopyN(outFile, inputFile, int64(counterReader.Counter))
if err != nil {
fmt.Printf("Can't save JPEG data to file: %s\n", err)
os.Exit(1)
}
err = outFile.Close()
if err != nil {
fmt.Printf("Can't close JPEG file: %s\n", err)
os.Exit(1)
}
if *verbose {
fmt.Printf("JPEG file found at address 0x%x. Size: %d bytes; Num clusters: %d\n", address, counterReader.Counter, numWholeClusters)
}
address += numWholeClusters * (*blockSize)
_, err = inputFile.Seek(address, io.SeekStart)
if err != nil {
fmt.Printf("Can't seek to next cluster: %s\n", err)
os.Exit(1)
}
}
}