-
Notifications
You must be signed in to change notification settings - Fork 785
/
unzip.go
120 lines (107 loc) · 2.42 KB
/
unzip.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
package util
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// Unzips the archvie into the specified directory
// returns an error if a general issue occurred unzipping the archive
func Unzip(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
err = extractFile(dest, f)
if err != nil {
return err
}
}
return nil
}
// Unzips the specified files from the archive
// returns an error if any of the specified files are not found or a general issue occurred unzipping the archive
func UnzipSpecificFiles(src, dest string, onlyFiles ...string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer r.Close()
m := make(map[string]bool)
for _, f := range onlyFiles {
m[f] = false
}
for _, f := range r.File {
name := f.Name
if _, matched := m[name]; matched {
err = extractFile(dest, f)
if err != nil {
return err
}
m[name] = true
}
}
// check we unzip all the specified files
failed := false
errString := ""
for f, b := range m {
if !b {
if failed {
errString += ", " + f
} else {
errString += ", " + f
failed = true
}
}
}
if failed {
return fmt.Errorf("the specified files where not found within the zip [%s]", errString)
}
return nil
}
// extract the specific file into the destination directory.
func extractFile(dest string, f *zip.File) error {
name := filepath.Join(dest, f.Name) // #nosec
// We need to be secure to prevent attacks like
// https://snyk.io/blog/zip-slip-vulnerability
// the result is already 'Clean'ed so we only need to check the string starts
if !strings.HasPrefix(name, dest) {
return fmt.Errorf("refusing to unzip %s due to escaping out of expected directory", f.Name)
}
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
if f.FileInfo().IsDir() {
err := os.MkdirAll(name, os.ModePerm)
if err != nil {
return err
}
} else {
var fdir string
if lastIndex := strings.LastIndex(name, string(os.PathSeparator)); lastIndex > -1 {
fdir = name[:lastIndex]
}
err = os.MkdirAll(fdir, os.ModePerm)
if err != nil {
return err
}
f, err := os.OpenFile(
name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer f.Close()
limited := io.LimitReader(rc, 100*1024*1024)
_, err = io.Copy(f, limited)
if err != nil {
return err
}
}
return nil
}