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
|
package zip
import (
"archive/zip"
"context"
"io"
"io/ioutil"
"os"
"strings"
"fmt"
"sync"
"gitlab.com/gitlab-org/gitlab-pages/internal/vfs"
)
const dirPrefix = "public/"
const maxSymlinkSize = 256
type zipArchive struct {
path string
once sync.Once
done chan struct{}
zip *zip.Reader
zipCloser io.Closer
files map[string]*zip.File
zipErr error
}
func (a *zipArchive) openArchive(ctx context.Context) error {
a.once.Do(func() {
a.zip, a.zipCloser, a.zipErr = openZIPArchive(a.path)
if a.zip != nil {
a.processZip()
}
close(a.done)
})
// wait for it to close
// or exit early
select {
case <-a.done:
case <-ctx.Done():
}
return a.zipErr
}
func (a *zipArchive) processZip() {
for _, file := range a.zip.File {
if !strings.HasPrefix(file.Name, dirPrefix) {
continue
}
a.files[file.Name] = file
}
// recycle memory
a.zip.File = nil
}
func (a *zipArchive) close() {
if a.zipCloser != nil {
a.zipCloser.Close()
}
a.zipCloser = nil
a.zip = nil
}
func (a *zipArchive) Lstat(ctx context.Context, name string) (os.FileInfo, error) {
file := a.files[name]
if file == nil {
return nil, os.ErrNotExist
}
return file.FileInfo(), nil
}
func (a *zipArchive) Readlink(ctx context.Context, name string) (string, error) {
file := a.files[name]
if file == nil {
return "", os.ErrNotExist
}
if file.FileInfo().Mode()&os.ModeSymlink != os.ModeSymlink {
return "", os.ErrInvalid
}
rc, err := file.Open()
if err != nil {
return "", err
}
data, err := ioutil.ReadAll(&io.LimitedReader{R: rc, N: maxSymlinkSize})
if err != nil {
return "", err
}
return string(data), nil
}
func (a *zipArchive) Open(ctx context.Context, name string) (vfs.File, error) {
file := a.files[name]
if file == nil {
return nil, os.ErrNotExist
}
dataOffset, err := file.DataOffset()
if err != nil {
return nil, err
}
// TODO: We can support `io.Seeker` if file would not be compressed
if !isHTTPArchive(a.path) {
return file.Open()
}
var reader io.ReadCloser
reader = &httpReader{
URL: a.path,
Off: dataOffset,
N: int64(file.UncompressedSize64),
}
switch file.Method {
case zip.Deflate:
reader = newDeflateReader(reader)
case zip.Store:
// no-op
default:
return nil, fmt.Errorf("unsupported compression: %x", file.Method)
}
return reader, nil
}
func newArchive(path string) *zipArchive {
return &zipArchive{
path: path,
done: make(chan struct{}),
}
}
|