forked from golift/xtractr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zip_new.go
68 lines (54 loc) · 1.67 KB
/
zip_new.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
package xtractr
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/alexmullins/zip"
)
/* How to extract a ZIP file. */
// ExtractZIP extracts a zip file.. to a destination. Simple enough.
func ExtractZIPNew(xFile *XFile) (int64, []string, error) {
zipReader, err := zip.OpenReader(xFile.FilePath)
if err != nil {
return 0, nil, fmt.Errorf("zip.OpenReader: %w", err)
}
defer zipReader.Close()
files := []string{}
size := int64(0)
for _, zipFile := range zipReader.File {
if zipFile.IsEncrypted() {
zipFile.SetPassword(xFile.Password)
}
fSize, err := xFile.unzipNew(zipFile)
if err != nil {
return size, files, fmt.Errorf("%s: %w", xFile.FilePath, err)
}
files = append(files, filepath.Join(xFile.OutputDir, zipFile.Name)) //nolint: gosec
size += fSize
}
return size, files, nil
}
func (x *XFile) unzipNew(zipFile *zip.File) (int64, error) { //nolint:dupl
wfile := x.clean(zipFile.Name)
if !strings.HasPrefix(wfile, x.OutputDir) {
// The file being written is trying to write outside of our base path. Malicious archive?
return 0, fmt.Errorf("%s: %w: %s (from: %s)", zipFile.FileInfo().Name(), ErrInvalidPath, wfile, zipFile.Name)
}
if strings.HasSuffix(wfile, "/") || zipFile.FileInfo().IsDir() {
if err := os.MkdirAll(wfile, x.DirMode); err != nil {
return 0, fmt.Errorf("making zipFile dir: %w", err)
}
return 0, nil
}
zFile, err := zipFile.Open()
if err != nil {
return 0, fmt.Errorf("zipFile.Open: %w", err)
}
defer zFile.Close()
s, err := writeFile(wfile, zFile, x.FileMode, x.DirMode)
if err != nil {
return s, fmt.Errorf("%s: %w: %s (from: %s)", zipFile.FileInfo().Name(), err, wfile, zipFile.Name)
}
return s, nil
}