-
Notifications
You must be signed in to change notification settings - Fork 2
/
extract.go
103 lines (96 loc) · 1.94 KB
/
extract.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
package main
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path"
"strings"
)
func isSafePath(name string) bool {
for _, part := range strings.Split(name, "/") {
if part == "" || part == "." || part == ".." {
return false
}
}
return true
}
func extractFile(e entry, src *os.File, dest string) error {
if _, err := src.Seek(int64(e.offset), io.SeekStart); err != nil {
return err
}
buf := make([]byte, len(e.path)+2)
if _, err := src.Read(buf); err != nil {
return nil
}
expect := make([]byte, len(e.path)+2)
copy(expect, buf)
if !bytes.Equal(buf, expect) {
return errors.New("out of sync with file")
}
if dest == "" {
return nil
}
fp, err := os.Create(dest)
if err != nil {
return err
}
if e.cmpsize > 0 {
exe := exec.Command("uncompress")
exe.Stdin = &io.LimitedReader{R: src, N: int64(e.cmpsize)}
exe.Stdout = fp
exe.Stderr = os.Stderr
return exe.Run()
}
_, err = io.CopyN(fp, src, int64(e.size))
return err
}
func extractDirectory(e entry, dest string) error {
if dest == "" {
return nil
}
return os.Mkdir(dest, 0777)
}
func extractLink(e entry, dest string) error {
if dest == "" {
return nil
}
return os.Symlink(e.symval, dest)
}
func extractEntry(e entry, src *os.File, dest string) error {
name := path.Clean(e.path)
if !isSafePath(name) {
return errors.New("invalid path")
}
if dest != "" {
dest = path.Join(dest, name)
if err := os.MkdirAll(path.Dir(dest), 0777); err != nil {
return err
}
}
switch e.ty {
case 'f':
return extractFile(e, src, dest)
case 'd':
return extractDirectory(e, dest)
case 'l':
return extractLink(e, dest)
default:
return fmt.Errorf("unknown type: %q", e.ty)
}
}
func extract(entries []entry, src, dest string) error {
fp, err := os.Open(src)
if err != nil {
return err
}
defer fp.Close()
for _, e := range entries {
if err := extractEntry(e, fp, dest); err != nil {
return fmt.Errorf("%s: %v", e.path, err)
}
}
return nil
}