-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathfolder_sink.go
More file actions
384 lines (315 loc) · 7.81 KB
/
folder_sink.go
File metadata and controls
384 lines (315 loc) · 7.81 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package savior
import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"github.com/itchio/headway/state"
"github.com/itchio/ox"
"github.com/pkg/errors"
)
var EnableLegacyPreallocate = os.Getenv("SAVIOR_LEGACY_PREALLOCATE") == "1"
const (
// ModeMask is or'd with files walked by butler
ModeMask = 0666
// LuckyMode is used when wiping in last-chance mode
LuckyMode = 0777
// DirMode is the default mode for directories created by butler
DirMode = 0755
)
var onWindows = runtime.GOOS == "windows"
type FolderSink struct {
Directory string
Consumer *state.Consumer
writer *entryWriter
}
var _ Sink = (*FolderSink)(nil)
var ignoredNames = map[string]struct{}{
// the path for folder icons on macOS (yes, really).
// thanks to Jordan Rose for pointing it out, and
// no thanks to whoever thought of that.
"Icon\r": struct{}{},
}
func shouldIgnorePath(s string) bool {
_, ok := ignoredNames[path.Base(s)]
return ok
}
// ErrPathTraversal is returned when an archive entry attempts to escape the destination directory
var ErrPathTraversal = fmt.Errorf("path traversal detected")
// destPath returns the safe destination path for an entry, validating that it
// stays within the sink's Directory to prevent path traversal attacks (ZIP slip).
func (fs *FolderSink) destPath(entry *Entry) (string, error) {
absBase, err := filepath.Abs(fs.Directory)
if err != nil {
return "", errors.WithStack(err)
}
joined := filepath.Join(absBase, filepath.FromSlash(entry.CanonicalPath))
absJoined, err := filepath.Abs(joined)
if err != nil {
return "", errors.WithStack(err)
}
// Ensure the path is within the base directory
if !strings.HasPrefix(absJoined, absBase+string(filepath.Separator)) && absJoined != absBase {
return "", fmt.Errorf("%w: %s", ErrPathTraversal, entry.CanonicalPath)
}
return absJoined, nil
}
func (fs *FolderSink) Mkdir(entry *Entry) error {
if shouldIgnorePath(entry.CanonicalPath) {
return nil
}
dstpath, err := fs.destPath(entry)
if err != nil {
return err
}
dirstat, err := os.Lstat(dstpath)
if err != nil {
// main case - dir doesn't exist yet
err = os.MkdirAll(dstpath, DirMode)
if err != nil {
return errors.WithStack(err)
}
return nil
}
if dirstat.IsDir() {
// is already a dir, good!
} else {
// is a file or symlink for example, turn into a dir
err = os.Remove(dstpath)
if err != nil {
return errors.WithStack(err)
}
err = os.MkdirAll(dstpath, DirMode)
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
func (fs *FolderSink) createFile(entry *Entry) (*os.File, error) {
dstpath, err := fs.destPath(entry)
if err != nil {
return nil, err
}
dirname := filepath.Dir(dstpath)
err = os.MkdirAll(dirname, LuckyMode)
if err != nil {
return nil, errors.WithStack(err)
}
stats, err := os.Lstat(dstpath)
if err == nil {
if stats.Mode()&os.ModeSymlink > 0 {
// if it used to be a symlink, remove it
err = os.RemoveAll(dstpath)
if err != nil {
return nil, errors.WithStack(err)
}
}
}
flag := os.O_CREATE | os.O_WRONLY
f, err := os.OpenFile(dstpath, flag, entry.Mode|ModeMask)
if err != nil {
return nil, errors.WithStack(err)
}
if stats != nil && !onWindows {
// if file already existed, chmod it, just in case
err = f.Chmod(entry.Mode | ModeMask)
if err != nil {
return nil, errors.WithStack(err)
}
}
return f, nil
}
func (fs *FolderSink) GetWriter(entry *Entry) (EntryWriter, error) {
if shouldIgnorePath(entry.CanonicalPath) {
return &nopEntryWriter{}, nil
}
f, err := fs.createFile(entry)
if err != nil {
return nil, errors.WithStack(err)
}
if f == nil {
return nil, nil
}
if entry.WriteOffset > 0 {
_, err = f.Seek(entry.WriteOffset, io.SeekStart)
if err != nil {
return nil, errors.WithStack(err)
}
}
err = f.Truncate(entry.WriteOffset)
if err != nil {
return nil, errors.WithStack(err)
}
err = fs.Close()
if err != nil {
fs.Consumer.Warnf("folder_sink could not close last writer: %s", err.Error())
}
ew := &entryWriter{
fs: fs,
f: f,
entry: entry,
}
fs.writer = ew
return ew, nil
}
func (fs *FolderSink) Preallocate(entry *Entry) error {
if shouldIgnorePath(entry.CanonicalPath) {
return nil
}
f, err := fs.createFile(entry)
if err != nil {
return errors.WithStack(err)
}
defer f.Close()
if entry.UncompressedSize > 0 {
if EnableLegacyPreallocate {
err := legacyPreallocate(f, entry.UncompressedSize)
if err != nil {
return err
}
} else {
err := ox.Preallocate(f, entry.UncompressedSize)
if err != nil {
return err
}
}
}
return nil
}
func legacyPreallocate(f *os.File, size int64) error {
endOffset, err := f.Seek(0, io.SeekEnd)
if err != nil {
return errors.WithStack(err)
}
allocSize := size - endOffset
if allocSize > 0 {
_, err := io.CopyN(f, &zeroReader{}, allocSize)
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
func (fs *FolderSink) Symlink(entry *Entry, linkname string) error {
if shouldIgnorePath(entry.CanonicalPath) {
return nil
}
if onWindows {
// on windows, write symlinks as regular files
w, err := fs.GetWriter(entry)
if err != nil {
return errors.WithStack(err)
}
defer w.Close()
_, err = w.Write([]byte(linkname))
if err != nil {
return errors.WithStack(err)
}
return nil
}
// actual symlink code
dstpath, err := fs.destPath(entry)
if err != nil {
return err
}
// Validate symlink target doesn't escape the destination directory.
// Resolve the symlink target relative to the symlink's directory.
symlinkDir := filepath.Dir(dstpath)
absBase, err := filepath.Abs(fs.Directory)
if err != nil {
return errors.WithStack(err)
}
// If linkname is absolute, reject it
if filepath.IsAbs(linkname) {
return fmt.Errorf("%w: absolute symlink target %s", ErrPathTraversal, linkname)
}
// Resolve the symlink target relative to where the symlink will be created
resolvedTarget := filepath.Join(symlinkDir, linkname)
absTarget, err := filepath.Abs(resolvedTarget)
if err != nil {
return errors.WithStack(err)
}
if !strings.HasPrefix(absTarget, absBase+string(filepath.Separator)) && absTarget != absBase {
return fmt.Errorf("%w: symlink target escapes destination: %s", ErrPathTraversal, linkname)
}
err = os.RemoveAll(dstpath)
if err != nil {
return errors.WithStack(err)
}
dirname := filepath.Dir(dstpath)
err = os.MkdirAll(dirname, LuckyMode)
if err != nil {
return errors.WithStack(err)
}
err = os.Symlink(linkname, dstpath)
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (fs *FolderSink) Nuke() error {
err := fs.Close()
if err != nil {
return errors.WithStack(err)
}
// TODO: retry logic, a-la butler
return os.RemoveAll(fs.Directory)
}
func (fs *FolderSink) Close() error {
if fs.writer != nil {
err := fs.writer.Close()
fs.writer = nil
return err
}
return nil
}
type entryWriter struct {
fs *FolderSink
f *os.File
entry *Entry
}
var _ EntryWriter = (*entryWriter)(nil)
func (ew *entryWriter) Write(buf []byte) (int, error) {
if ew.f == nil {
return 0, os.ErrClosed
}
n, err := ew.f.Write(buf)
ew.entry.WriteOffset += int64(n)
return n, err
}
func (ew *entryWriter) Close() error {
if ew.f == nil {
// already closed
return nil
}
err := ew.f.Close()
ew.f = nil
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (ew *entryWriter) Sync() error {
if ew.f == nil {
return os.ErrClosed
}
return ew.f.Sync()
}
//
type zeroReader struct{}
var _ io.Reader = (*zeroReader)(nil)
func (zr *zeroReader) Read(p []byte) (int, error) {
// p can be *anything* - it can be preallocated and
// already used in previous I/O operations. So we
// really do need to clear it.
// that code seems slow, but luckily it's optimized:
// https://github.com/golang/go/wiki/CompilerOptimizations#optimized-memclr
for i := range p {
p[i] = 0
}
return len(p), nil
}