-
Notifications
You must be signed in to change notification settings - Fork 20
/
unpackit.go
361 lines (300 loc) · 7.78 KB
/
unpackit.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Package unpackit allows you to easily unpack *.tar.gz, *.tar.bzip2, *.tar.xz, *.zip and *.tar files.
// There are not CGO involved nor hard dependencies of any type.
package unpackit
import (
"archive/tar"
"archive/zip"
"bufio"
"bytes"
"fmt"
"io"
"log"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/dsnet/compress/bzip2"
gzip "github.com/klauspost/pgzip"
"github.com/pkg/errors"
"github.com/ulikunitz/xz"
)
var (
magicZIP = []byte{0x50, 0x4b, 0x03, 0x04}
magicGZ = []byte{0x1f, 0x8b}
magicBZIP = []byte{0x42, 0x5a}
magicTAR = []byte{0x75, 0x73, 0x74, 0x61, 0x72} // at offset 257
magicXZ = []byte{0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00}
)
// Check whether a file has the magic number for tar, gzip, bzip2 or zip files
//
// Note that this function does not advance the Reader.
//
// 50 4b 03 04 for pkzip format
// 1f 8b for .gz format
// 42 5a for .bzip format
// 75 73 74 61 72 at offset 257 for tar files
// fd 37 7a 58 5a 00 for .xz format
func magicNumber(reader *bufio.Reader, offset int) (string, error) {
headerBytes, err := reader.Peek(offset + 6)
if err != nil {
return "", err
}
magic := headerBytes[offset : offset+6]
if bytes.Equal(magicTAR, magic[0:5]) {
return "tar", nil
}
if bytes.Equal(magicZIP, magic[0:4]) {
return "zip", nil
}
if bytes.Equal(magicGZ, magic[0:2]) {
return "gzip", nil
} else if bytes.Equal(magicBZIP, magic[0:2]) {
return "bzip", nil
}
if bytes.Equal(magicXZ, magic) {
return "xz", nil
}
return "", nil
}
// Unpack unpacks a compressed stream. Magic numbers are used to determine what
// decompressor and/or unarchiver to use.
func Unpack(reader io.Reader, destPath string) error {
var err error
// Makes sure destPath exists
if err := os.MkdirAll(destPath, 0o740); err != nil {
return err
}
r := bufio.NewReader(reader)
// Reads magic number from the stream so we can better determine how to proceed
ftype, err := magicNumber(r, 0)
if err != nil {
return err
}
var decompressingReader *bufio.Reader
switch ftype {
case "gzip":
gzr, err := gzip.NewReader(r)
if err != nil {
return err
}
defer func() {
if err := gzr.Close(); err != nil {
fmt.Printf("%+v", errors.Wrapf(err, "unpackit: failed closing gzip reader"))
}
}()
decompressingReader = bufio.NewReader(gzr)
case "xz":
xzr, err := xz.NewReader(r)
if err != nil {
return err
}
decompressingReader = bufio.NewReader(xzr)
case "bzip":
br, err := bzip2.NewReader(r, nil)
if err != nil {
return err
}
defer func() {
if err := br.Close(); err != nil {
fmt.Printf("%+v", errors.Wrapf(err, "unpackit: failed closing bzip2 reader"))
}
}()
decompressingReader = bufio.NewReader(br)
case "zip":
// Like TAR, ZIP is also an archiving format, therefore we can just return
// after it finishes
return Unzip(r, destPath)
default:
// maybe it is a tarball file
decompressingReader = r
}
// Check magic number in offset 257 too see if this is also a TAR file
ftype, err = magicNumber(decompressingReader, 257)
if err != nil {
return err
}
if ftype == "tar" {
return Untar(decompressingReader, destPath)
}
// If it's not a TAR archive then save it to disk as is.
destRawFile := filepath.Join(destPath, sanitize(path.Base("unknown-pack")))
// Creates destination file
destFile, err := os.Create(destRawFile)
if err != nil {
return err
}
defer func() {
if err := destFile.Close(); err != nil {
log.Println(err)
}
}()
// Copies data to destination file
if _, err := io.Copy(destFile, decompressingReader); err != nil {
return err
}
return nil
}
// Unzip unpacks a ZIP stream. When given a os.File reader it will get its size without
// reading the entire zip file in memory.
func Unzip(r io.Reader, destPath string) error {
var (
zr *zip.Reader
readerErr error
)
if f, ok := r.(*os.File); ok {
fstat, err := f.Stat()
if err != nil {
return err
}
zr, readerErr = zip.NewReader(f, fstat.Size())
} else {
data, err := io.ReadAll(r)
if err != nil {
return err
}
memReader := bytes.NewReader(data)
zr, readerErr = zip.NewReader(memReader, memReader.Size())
}
if readerErr != nil {
return readerErr
}
return unpackZip(zr, destPath)
}
func unpackZip(zr *zip.Reader, destPath string) error {
for _, f := range zr.File {
err := unzipFile(f, destPath)
if err != nil {
return err
}
}
return nil
}
func unzipFile(f *zip.File, destPath string) error {
if f.FileInfo().IsDir() {
if err := os.MkdirAll(filepath.Join(destPath, f.Name), f.Mode().Perm()); err != nil {
return err
}
return nil
}
rc, err := f.Open()
if err != nil {
return err
}
defer func() {
if err := rc.Close(); err != nil {
log.Println(err)
}
}()
filePath := sanitize(f.Name)
destPath = filepath.Join(destPath, filePath)
// If directories were not included in the archive but are part of the file name,
// we create them relative to the destination path.
fileDir := filepath.Dir(destPath)
_, err = os.Lstat(fileDir)
if err != nil {
if err := os.MkdirAll(fileDir, 0o700); err != nil {
return err
}
}
file, err := os.Create(destPath)
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil {
log.Println(err)
}
}()
if err := file.Chmod(f.Mode()); err != nil {
log.Printf("warn: failed setting file permissions for %q: %#v", file.Name(), err)
}
if err := os.Chtimes(file.Name(), time.Now(), f.ModTime()); err != nil {
log.Printf("warn: failed setting file atime and mtime for %q: %#v", file.Name(), err)
}
if _, err := io.CopyN(file, rc, int64(f.UncompressedSize64)); err != nil {
return err
}
return nil
}
// Untar unarchives a TAR archive and returns the final destination path or an error
func Untar(data io.Reader, destPath string) error {
// Makes sure destPath exists
if err := os.MkdirAll(destPath, 0o740); err != nil {
return err
}
tr := tar.NewReader(data)
// Iterate through the files in the archive.
rootdir := destPath
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
if err != nil {
return err
}
// Skip pax_global_header with the commit ID this archive was created from
if hdr.Name == "pax_global_header" {
continue
}
fp := filepath.Join(destPath, sanitize(hdr.Name))
if hdr.FileInfo().IsDir() {
if rootdir == destPath {
rootdir = fp
}
if err := os.MkdirAll(fp, os.FileMode(hdr.Mode)); err != nil {
return err
}
continue
}
untarErr := untarFile(hdr, tr, fp, rootdir)
if untarErr != nil {
return untarErr
}
}
return nil
}
func untarFile(hdr *tar.Header, tr *tar.Reader, fp, rootdir string) error {
parentDir, _ := filepath.Split(fp)
if err := os.MkdirAll(parentDir, 0o740); err != nil {
return err
}
file, err := os.Create(fp)
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil {
log.Println(err)
}
}()
if err := file.Chmod(os.FileMode(hdr.Mode)); err != nil {
log.Printf("warn: failed setting file permissions for %q: %#v", file.Name(), err)
}
if err := os.Chtimes(file.Name(), time.Now(), hdr.ModTime); err != nil {
log.Printf("warn: failed setting file atime and mtime for %q: %#v", file.Name(), err)
}
if _, err := io.Copy(file, tr); err != nil {
return err
}
return nil
}
// Sanitizes name to avoid overwriting sensitive system files when unarchiving
func sanitize(name string) string {
// Gets rid of volume drive label in Windows
if len(name) > 1 && name[1] == ':' && runtime.GOOS == "windows" {
name = name[2:]
}
name = filepath.Clean(name)
name = filepath.ToSlash(name)
for strings.HasPrefix(name, "../") {
name = name[3:]
}
return name
}