-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathreader.go
377 lines (310 loc) · 8.42 KB
/
reader.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
package go7z
import (
"bufio"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
"sync"
"github.com/saracen/go7z/headers"
"github.com/saracen/solidblock"
)
var (
// ErrNotSupported is returned when an unrecognized archive format is
// encountered.
ErrNotSupported = errors.New("not supported")
// ErrDecompressorNotFound is returned when a requested decompressor has not
// been registered.
ErrDecompressorNotFound = errors.New("decompressor not found")
)
// Reader is a 7z archive reader.
type Reader struct {
r *io.SectionReader
err error
header *headers.Header
folderIndex int
fileIndex int
emptyStream bool
folders []*folderReader
Options ReaderOptions
}
// ReaderOptions are optional options to configure a 7z archive reader.
type ReaderOptions struct {
password string
cb func() string
}
// SetPassword sets the password used for extraction.
func (o *ReaderOptions) SetPassword(password string) {
o.password = password
}
// SetPasswordCallback sets the callback thats used if a password is required,
// but wasn't supplied with SetPassword()
func (o *ReaderOptions) SetPasswordCallback(cb func() string) {
o.cb = cb
}
// Password returns the set password. This will call the password callback
// supplied to SetPasswordCallback() if no password is set.
func (o *ReaderOptions) Password() string {
if o.password != "" {
return o.password
}
if o.cb != nil {
o.password = o.cb()
}
return o.password
}
// ReadCloser provides an io.ReadCloser for the archive when opened with
// OpenReader.
type ReadCloser struct {
f *os.File
Reader
}
// Close closes the 7z file, rendering it unusable for I/O.
func (rc *ReadCloser) Close() error {
return rc.f.Close()
}
// OpenReader will open the 7z file specified by name and return a ReadCloser.
func OpenReader(name string) (*ReadCloser, error) {
f, err := os.Open(name)
if err != nil {
return nil, err
}
fi, err := f.Stat()
if err != nil {
f.Close()
return nil, err
}
r := new(ReadCloser)
if err := r.init(f, fi.Size(), false); err != nil {
f.Close()
return nil, err
}
r.f = f
return r, nil
}
// NewReader returns a new Reader reading from r, which is assumed to
// have the given size in bytes.
func NewReader(r io.ReaderAt, size int64) (*Reader, error) {
szr := new(Reader)
if err := szr.init(r, size, false); err != nil {
return nil, err
}
return szr, nil
}
func (sz *Reader) init(r io.ReaderAt, size int64, ignoreChecksumError bool) error {
sz.r = io.NewSectionReader(r, 0, size)
signatureHeader, err := headers.ReadSignatureHeader(sz.r)
if err != nil {
if !(ignoreChecksumError && err == headers.ErrChecksumMismatch) {
return err
}
}
if _, err := sz.r.Seek(signatureHeader.StartHeader.NextHeaderOffset, io.SeekCurrent); err != nil {
return err
}
if signatureHeader.StartHeader.NextHeaderSize > size-headers.SignatureHeaderSize {
return io.ErrUnexpectedEOF
}
crc := crc32.NewIEEE()
tee := io.TeeReader(bufio.NewReader(io.LimitReader(sz.r, signatureHeader.StartHeader.NextHeaderSize)), crc)
header, encoded, err := headers.ReadPackedStreamsForHeaders(&io.LimitedReader{tee, signatureHeader.StartHeader.NextHeaderSize})
if err != nil {
return err
}
if crc.Sum32() != signatureHeader.StartHeader.NextHeaderCRC {
if !ignoreChecksumError {
return headers.ErrChecksumMismatch
}
}
if encoded != nil {
folders, err := sz.extract(encoded)
if err != nil {
return err
}
if len(folders) != 1 {
return ErrNotSupported
}
if err = folders[0].Next(); err != nil {
return err
}
header, _, err = headers.ReadPackedStreamsForHeaders(&io.LimitedReader{folders[0].sb, folders[0].sb.Size()})
if err != nil {
return err
}
if err = folders[0].Next(); err != io.EOF {
return ErrNotSupported
}
}
if header == nil {
return ErrNotSupported
}
sz.header = header
sz.folders, err = sz.extract(sz.header.MainStreamsInfo)
return err
}
// Next advances to the next entry in the 7z archive.
//
// io.EOF is returned at the end of the input.
func (sz *Reader) Next() (*headers.FileInfo, error) {
if sz.err != nil {
return nil, sz.err
}
hdr, err := sz.next()
sz.err = err
return hdr, err
}
func (sz *Reader) nextFileInfo() *headers.FileInfo {
var fileInfo *headers.FileInfo
if sz.fileIndex < len(sz.header.FilesInfo) {
fileInfo = sz.header.FilesInfo[sz.fileIndex]
sz.fileIndex++
return fileInfo
}
return nil
}
func (sz *Reader) extract(streamsInfo *headers.StreamsInfo) ([]*folderReader, error) {
var sizes []uint64
var crcs []uint32
if streamsInfo.SubStreamsInfo != nil {
sizes = streamsInfo.SubStreamsInfo.UnpackSizes
crcs = streamsInfo.SubStreamsInfo.Digests
}
offset := int64(headers.SignatureHeaderSize)
offset += int64(streamsInfo.PackInfo.PackPos)
packedIndicesOffset := 0
var folders []*folderReader
for i, folder := range streamsInfo.UnpackInfo.Folders {
if len(folder.PackedIndices) == 0 {
folder.PackedIndices = []int{0}
}
fr := &folderReader{}
fr.inputs = make(map[int]io.Reader)
fr.binder = solidblock.Binder{}
// setup codecs
for j := range folder.CoderInfo {
coderInfo := folder.CoderInfo[j]
size := folder.UnpackSizes[j]
d := decompressor(coderInfo.CodecID)
if d == nil {
return folders, ErrDecompressorNotFound
}
fn := func(in []io.Reader) ([]io.Reader, error) {
r, err := d(in, coderInfo.Properties, size, &sz.Options)
return []io.Reader{r}, err
}
fr.binder.AddCodec(fn, coderInfo.NumInStreams, coderInfo.NumOutStreams)
}
// setup initial inputs
for index, input := range folder.PackedIndices {
if packedIndicesOffset+index >= len(streamsInfo.PackInfo.PackSizes) {
return nil, fmt.Errorf("folder references invalid packinfo")
}
size := int64(streamsInfo.PackInfo.PackSizes[packedIndicesOffset+index])
fr.inputs[input] = io.NewSectionReader(sz.r, offset, size)
offset += size
}
packedIndicesOffset += len(folder.PackedIndices)
// setup pairs
for _, bindPairsInfo := range folder.BindPairsInfo {
fr.binder.Pair(bindPairsInfo.InIndex, bindPairsInfo.OutIndex)
}
if streamsInfo.SubStreamsInfo != nil {
numUnpackStreamsInFolders := streamsInfo.SubStreamsInfo.NumUnpackStreamsInFolders
if i >= len(numUnpackStreamsInFolders) {
return nil, fmt.Errorf("folder references invalid unpack stream")
}
off := numUnpackStreamsInFolders[i]
if off > len(sizes) || off > len(crcs) {
return nil, fmt.Errorf("folder references invalid unpack size or digest")
}
fr.sizes = sizes[:off]
fr.crcs = crcs[:off]
sizes = sizes[len(fr.sizes):]
crcs = crcs[len(fr.crcs):]
} else {
fr.sizes = []uint64{folder.UnpackSize()}
fr.crcs = []uint32{folder.UnpackCRC}
}
folders = append(folders, fr)
}
return folders, nil
}
type folderReader struct {
binder solidblock.Binder
sizes []uint64
crcs []uint32
inputs map[int]io.Reader
bufs []*bufio.Reader
sb *solidblock.Solidblock
}
var bufioReaderPool = sync.Pool{
New: func() interface{} {
return bufio.NewReaderSize(nil, 32*1024)
},
}
func (fr *folderReader) Next() error {
if fr.sb == nil {
fr.bufs = make([]*bufio.Reader, 0, len(fr.inputs))
for in, r := range fr.inputs {
br := bufioReaderPool.Get().(*bufio.Reader)
br.Reset(r)
fr.bufs = append(fr.bufs, br)
fr.binder.Reader(br, in)
}
outputs, err := fr.binder.Outputs()
if err != nil {
return err
}
if len(outputs) != 1 {
return ErrNotSupported
}
if outputs[0] == nil {
return ErrNotSupported
}
fr.sb = solidblock.New(outputs[0], fr.sizes, fr.crcs)
}
return fr.sb.Next()
}
func (fr *folderReader) Close() error {
for _, buf := range fr.bufs {
bufioReaderPool.Put(buf)
}
fr.bufs = nil
return nil
}
func (sz *Reader) next() (*headers.FileInfo, error) {
fileInfo := sz.nextFileInfo()
if fileInfo == nil {
return nil, io.EOF
}
sz.emptyStream = fileInfo.IsEmptyStream
if sz.emptyStream {
return fileInfo, nil
}
if sz.folders[sz.folderIndex].Next() == io.EOF {
sz.folders[sz.folderIndex].Close()
sz.folderIndex++
if sz.folderIndex >= len(sz.folders) {
return nil, io.EOF
}
sz.folders[sz.folderIndex].Next()
}
return fileInfo, nil
}
// Read reads from the current file in the 7z archive.
// It returns (0, io.EOF) when it reaches the end of that file,
// until Next is called to advance to the next file.
func (sz *Reader) Read(p []byte) (int, error) {
if sz.err != nil {
return 0, sz.err
}
if sz.emptyStream {
return 0, io.EOF
}
n, err := sz.folders[sz.folderIndex].sb.Read(p)
if err != nil && err != io.EOF {
sz.err = err
}
return n, err
}