/
zip.go
209 lines (191 loc) · 5.55 KB
/
zip.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
// Copyright 2011-2014 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package zip
import (
"archive/zip"
"bytes"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
)
// FindAll returns the cleaned path of every file in the supplied zip reader.
func FindAll(reader *zip.Reader) ([]string, error) {
return Find(reader, "*")
}
// Find returns the cleaned path of every file in the supplied zip reader whose
// base name matches the supplied pattern, which is interpreted as in path.Match.
func Find(reader *zip.Reader, pattern string) ([]string, error) {
// path.Match will only return an error if the pattern is not
// valid (*and* the supplied name is not empty, hence "check").
if _, err := path.Match(pattern, "check"); err != nil {
return nil, err
}
var matches []string
for _, zipFile := range reader.File {
cleanPath := path.Clean(zipFile.Name)
baseName := path.Base(cleanPath)
if match, _ := path.Match(pattern, baseName); match {
matches = append(matches, cleanPath)
}
}
return matches, nil
}
// ExtractAll extracts the supplied zip reader to the target path, overwriting
// existing files and directories only where necessary.
func ExtractAll(reader *zip.Reader, targetRoot string) error {
return Extract(reader, targetRoot, "")
}
// Extract extracts files from the supplied zip reader, from the (internal, slash-
// separated) source path into the (external, OS-specific) target path. If the
// source path does not reference a directory, the referenced file will be written
// directly to the target path.
func Extract(reader *zip.Reader, targetRoot, sourceRoot string) error {
sourceRoot = path.Clean(sourceRoot)
if sourceRoot == "." {
sourceRoot = ""
}
if !isSanePath(sourceRoot) {
return fmt.Errorf("cannot extract files rooted at %q", sourceRoot)
}
extractor := extractor{targetRoot, sourceRoot}
for _, zipFile := range reader.File {
if err := extractor.extract(zipFile); err != nil {
cleanName := path.Clean(zipFile.Name)
return fmt.Errorf("cannot extract %q: %v", cleanName, err)
}
}
return nil
}
type extractor struct {
targetRoot string
sourceRoot string
}
// targetPath returns the target path for a given zip file and whether
// it should be extracted.
func (x extractor) targetPath(zipFile *zip.File) (string, bool) {
cleanPath := path.Clean(zipFile.Name)
if cleanPath == x.sourceRoot {
return x.targetRoot, true
}
if x.sourceRoot != "" {
mustPrefix := x.sourceRoot + "/"
if !strings.HasPrefix(cleanPath, mustPrefix) {
return "", false
}
cleanPath = cleanPath[len(mustPrefix):]
}
return filepath.Join(x.targetRoot, filepath.FromSlash(cleanPath)), true
}
func (x extractor) extract(zipFile *zip.File) error {
targetPath, ok := x.targetPath(zipFile)
if !ok {
return nil
}
parentPath := filepath.Dir(targetPath)
if err := os.MkdirAll(parentPath, 0777); err != nil {
return err
}
mode := zipFile.Mode()
modePerm := mode & os.ModePerm
modeType := mode & os.ModeType
switch modeType {
case os.ModeDir:
return x.writeDir(targetPath, modePerm)
case os.ModeSymlink:
return x.writeSymlink(targetPath, zipFile)
case 0:
return x.writeFile(targetPath, zipFile, modePerm)
}
return fmt.Errorf("unknown file type %d", modeType)
}
func (x extractor) writeDir(targetPath string, modePerm os.FileMode) error {
fileInfo, err := os.Lstat(targetPath)
switch {
case err == nil:
mode := fileInfo.Mode()
if mode.IsDir() {
if mode&os.ModePerm != modePerm {
return os.Chmod(targetPath, modePerm)
}
return nil
}
fallthrough
case !os.IsNotExist(err):
if err := os.RemoveAll(targetPath); err != nil {
return err
}
}
return os.MkdirAll(targetPath, modePerm)
}
func (x extractor) writeFile(targetPath string, zipFile *zip.File, modePerm os.FileMode) error {
if _, err := os.Lstat(targetPath); !os.IsNotExist(err) {
if err := os.RemoveAll(targetPath); err != nil {
return err
}
}
writer, err := os.OpenFile(targetPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, modePerm)
if err != nil {
return err
}
defer writer.Close()
if err := copyTo(writer, zipFile); err != nil {
return err
}
if err := writer.Sync(); err != nil {
return err
}
if err := writer.Close(); err != nil {
return err
}
return nil
}
func (x extractor) writeSymlink(targetPath string, zipFile *zip.File) error {
symlinkTarget, err := x.checkSymlink(targetPath, zipFile)
if err != nil {
return err
}
if _, err := os.Lstat(targetPath); !os.IsNotExist(err) {
if err := os.RemoveAll(targetPath); err != nil {
return err
}
}
return os.Symlink(symlinkTarget, targetPath)
}
func (x extractor) checkSymlink(targetPath string, zipFile *zip.File) (string, error) {
var buffer bytes.Buffer
if err := copyTo(&buffer, zipFile); err != nil {
return "", err
}
symlinkTarget := buffer.String()
if filepath.IsAbs(symlinkTarget) {
return "", fmt.Errorf("symlink %q is absolute", symlinkTarget)
}
finalPath := filepath.Join(filepath.Dir(targetPath), symlinkTarget)
relativePath, err := filepath.Rel(x.targetRoot, finalPath)
if err != nil {
// Not tested, because I don't know how to trigger this condition.
return "", fmt.Errorf("symlink %q not comprehensible", symlinkTarget)
}
if !isSanePath(relativePath) {
return "", fmt.Errorf("symlink %q leads out of scope", symlinkTarget)
}
return symlinkTarget, nil
}
func copyTo(writer io.Writer, zipFile *zip.File) error {
reader, err := zipFile.Open()
if err != nil {
return err
}
_, err = io.Copy(writer, reader)
reader.Close()
return err
}
func isSanePath(path string) bool {
if path == ".." || strings.HasPrefix(path, "../") {
return false
}
return true
}