-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
extract_plugin_tar.go
82 lines (69 loc) · 2.09 KB
/
extract_plugin_tar.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
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"archive/tar"
"compress/gzip"
"io"
"os"
"path/filepath"
"strings"
"github.com/mattermost/mattermost-server/v5/mlog"
"github.com/pkg/errors"
)
// extractTarGz takes in an io.Reader containing the bytes for a .tar.gz file and
// a destination string to extract to.
func extractTarGz(gzipStream io.Reader, dst string) error {
if dst == "" {
return errors.New("no destination path provided")
}
uncompressedStream, err := gzip.NewReader(gzipStream)
if err != nil {
return errors.Wrap(err, "failed to initialize gzip reader")
}
defer uncompressedStream.Close()
tarReader := tar.NewReader(uncompressedStream)
for {
header, err := tarReader.Next()
if err == io.EOF {
break
} else if err != nil {
return errors.Wrap(err, "failed to read next file from archive")
}
// Pre-emptively check type flag to avoid reporting a misleading error in
// trying to sanitize the header name.
switch header.Typeflag {
case tar.TypeDir:
case tar.TypeReg:
default:
mlog.Warn("skipping unsupported header type on extracting tar file", mlog.String("header_type", string(header.Typeflag)), mlog.String("header_name", header.Name))
continue
}
// filepath.HasPrefix is deprecated, so we just use strings.HasPrefix to ensure
// the target path remains rooted at dst and has no `../` escaping outside.
path := filepath.Join(dst, header.Name)
if !strings.HasPrefix(path, dst) {
return errors.Errorf("failed to sanitize path %s", header.Name)
}
switch header.Typeflag {
case tar.TypeDir:
if err := os.Mkdir(path, 0744); err != nil && !os.IsExist(err) {
return err
}
case tar.TypeReg:
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0744); err != nil {
return err
}
outFile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, os.FileMode(header.Mode))
if err != nil {
return err
}
defer outFile.Close()
if _, err := io.Copy(outFile, tarReader); err != nil {
return err
}
}
}
return nil
}