/
bucket.go
402 lines (373 loc) · 10.1 KB
/
bucket.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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Copyright 2020-2022 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package storageos
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"github.com/bufbuild/buf/private/pkg/filepathextended"
"github.com/bufbuild/buf/private/pkg/normalpath"
"github.com/bufbuild/buf/private/pkg/storage"
"github.com/bufbuild/buf/private/pkg/storage/storageutil"
)
// errNotDir is the error returned if a path is not a directory.
var errNotDir = errors.New("not a directory")
type bucket struct {
rootPath string
absoluteRootPath string
symlinks bool
}
func newBucket(rootPath string, symlinks bool) (*bucket, error) {
rootPath = normalpath.Unnormalize(rootPath)
if err := validateDirPathExists(rootPath, symlinks); err != nil {
return nil, err
}
absoluteRootPath, err := filepath.Abs(rootPath)
if err != nil {
return nil, err
}
// do not validate - allow anything with OS buckets including
// absolute paths and jumping context
rootPath = normalpath.Normalize(rootPath)
return &bucket{
rootPath: rootPath,
absoluteRootPath: absoluteRootPath,
symlinks: symlinks,
}, nil
}
func (b *bucket) Get(ctx context.Context, path string) (storage.ReadObjectCloser, error) {
externalPath, err := b.getExternalPath(path)
if err != nil {
return nil, err
}
if err := b.validateExternalPath(path, externalPath); err != nil {
return nil, err
}
resolvedPath := externalPath
if b.symlinks {
resolvedPath, err = filepath.EvalSymlinks(externalPath)
if err != nil {
return nil, err
}
}
file, err := os.Open(resolvedPath)
if err != nil {
return nil, err
}
// we could use fileInfo.Name() however we might as well use the externalPath
return newReadObjectCloser(
path,
externalPath,
file,
), nil
}
func (b *bucket) Stat(ctx context.Context, path string) (storage.ObjectInfo, error) {
externalPath, err := b.getExternalPath(path)
if err != nil {
return nil, err
}
if err := b.validateExternalPath(path, externalPath); err != nil {
return nil, err
}
// we could use fileInfo.Name() however we might as well use the externalPath
return storageutil.NewObjectInfo(
path,
externalPath,
), nil
}
func (b *bucket) Walk(
ctx context.Context,
prefix string,
f func(storage.ObjectInfo) error,
) error {
externalPrefix, err := b.getExternalPrefix(prefix)
if err != nil {
return err
}
walkChecker := storageutil.NewWalkChecker()
var walkOptions []filepathextended.WalkOption
if b.symlinks {
walkOptions = append(walkOptions, filepathextended.WalkWithSymlinks())
}
if err := filepathextended.Walk(
externalPrefix,
func(externalPath string, fileInfo os.FileInfo, err error) error {
if err != nil {
// this can happen if a symlink is broken
// in this case, we just want to continue the walk
if b.symlinks && os.IsNotExist(err) {
return nil
}
return err
}
if err := walkChecker.Check(ctx); err != nil {
return err
}
absoluteExternalPath, err := filepath.Abs(externalPath)
if err != nil {
return err
}
if fileInfo.Mode().IsRegular() {
path, err := normalpath.Rel(b.absoluteRootPath, absoluteExternalPath)
if err != nil {
return err
}
// just in case
path, err = normalpath.NormalizeAndValidate(path)
if err != nil {
return err
}
if err := f(
storageutil.NewObjectInfo(
path,
externalPath,
),
); err != nil {
return err
}
}
return nil
},
walkOptions...,
); err != nil {
if os.IsNotExist(err) {
// Should be a no-op according to the spec.
return nil
}
return err
}
return nil
}
func (b *bucket) Put(ctx context.Context, path string) (storage.WriteObjectCloser, error) {
externalPath, err := b.getExternalPath(path)
if err != nil {
return nil, err
}
externalDir := filepath.Dir(externalPath)
var fileInfo os.FileInfo
if b.symlinks {
fileInfo, err = os.Stat(externalDir)
} else {
fileInfo, err = os.Lstat(externalDir)
}
if err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(externalDir, 0755); err != nil {
return nil, err
}
} else {
return nil, err
}
} else if !fileInfo.IsDir() {
return nil, newErrNotDir(externalDir)
}
file, err := os.Create(externalPath)
if err != nil {
return nil, err
}
return newWriteObjectCloser(
file,
), nil
}
func (b *bucket) Delete(ctx context.Context, path string) error {
externalPath, err := b.getExternalPath(path)
if err != nil {
return err
}
// Note: this deletes the file at the path, but it may
// leave orphan parent directories around that were
// created by the MkdirAll in Put.
if err := os.Remove(externalPath); err != nil {
if os.IsNotExist(err) {
return storage.NewErrNotExist(path)
}
return err
}
return nil
}
func (b *bucket) DeleteAll(ctx context.Context, prefix string) error {
externalPrefix, err := b.getExternalPrefix(prefix)
if err != nil {
return err
}
if err := os.RemoveAll(externalPrefix); err != nil {
// this is a no-nop per the documentation
if os.IsNotExist(err) {
return nil
}
return err
}
return nil
}
func (*bucket) SetExternalPathSupported() bool {
return false
}
func (b *bucket) getExternalPath(path string) (string, error) {
path, err := storageutil.ValidatePath(path)
if err != nil {
return "", err
}
realClean, err := filepathextended.RealClean(normalpath.Join(b.rootPath, path))
if err != nil {
return "", err
}
return normalpath.Unnormalize(realClean), nil
}
func (b *bucket) validateExternalPath(path string, externalPath string) error {
// this is potentially introducing two calls to a file
// instead of one, ie we do both Stat and Open as opposed to just Open
// we do this to make sure we are only reading regular files
var fileInfo os.FileInfo
var err error
if b.symlinks {
fileInfo, err = os.Stat(externalPath)
} else {
fileInfo, err = os.Lstat(externalPath)
}
if err != nil {
if os.IsNotExist(err) {
return storage.NewErrNotExist(path)
}
// The path might have a regular file in one of its
// elements (e.g. 'foo/bar/baz.proto' where 'bar' is a
// regular file).
//
// In this case, the standard library will return an
// os.PathError, but there isn't an exported error value
// to check against (i.e. os.Is*). But we can still discover
// whether or not this is the case by checking if any of the
// path components represents a regular file (e.g. 'foo/bar').
//
// It's important that we detect these cases so that
// multi buckets don't unnecessarily fail when one of
// its delegates actually defines the path.
elements := strings.Split(normalpath.Normalize(externalPath), "/")
if len(elements) == 1 {
// The path is a single element, so there aren't
// any other files to check.
return err
}
for i := len(elements) - 1; i >= 0; i-- {
parentFileInfo, err := os.Stat(filepath.Join(elements[:i]...))
if err != nil {
continue
}
if parentFileInfo.Mode().IsRegular() {
// This error primarily serves as a sentinel error,
// but we preserve the original path argument so that
// the error still makes sense to the user.
return storage.NewErrNotExist(path)
}
}
return err
}
if !fileInfo.Mode().IsRegular() {
// making this a user error as any access means this was generally requested
// by the user, since we only call the function for Walk on regular files
return storage.NewErrNotExist(path)
}
return nil
}
func (b *bucket) getExternalPrefix(prefix string) (string, error) {
prefix, err := storageutil.ValidatePrefix(prefix)
if err != nil {
return "", err
}
realClean, err := filepathextended.RealClean(normalpath.Join(b.rootPath, prefix))
if err != nil {
return "", err
}
return normalpath.Unnormalize(realClean), nil
}
type readObjectCloser struct {
// we use ObjectInfo for Path, ExternalPath, etc to make sure this is static
// we put ObjectInfos in maps in other places so we do not want this to change
// this could be a problem if the underlying file is concurrently moved or resized however
storageutil.ObjectInfo
file *os.File
}
func newReadObjectCloser(
path string,
externalPath string,
file *os.File,
) *readObjectCloser {
return &readObjectCloser{
ObjectInfo: storageutil.NewObjectInfo(
path,
externalPath,
),
file: file,
}
}
func (r *readObjectCloser) Read(p []byte) (int, error) {
n, err := r.file.Read(p)
return n, toStorageError(err)
}
func (r *readObjectCloser) Close() error {
return toStorageError(r.file.Close())
}
type writeObjectCloser struct {
file *os.File
}
func newWriteObjectCloser(
file *os.File,
) *writeObjectCloser {
return &writeObjectCloser{
file: file,
}
}
func (w *writeObjectCloser) Write(p []byte) (int, error) {
n, err := w.file.Write(p)
return n, toStorageError(err)
}
func (w *writeObjectCloser) SetExternalPath(string) error {
return storage.ErrSetExternalPathUnsupported
}
func (w *writeObjectCloser) Close() error {
err := toStorageError(w.file.Close())
return err
}
// newErrNotDir returns a new Error for a path not being a directory.
func newErrNotDir(path string) *normalpath.Error {
return normalpath.NewError(path, errNotDir)
}
func toStorageError(err error) error {
if err == os.ErrClosed {
return storage.ErrClosed
}
return err
}
// validateDirPathExists returns a non-nil error if the given dirPath
// is not a valid directory path.
func validateDirPathExists(dirPath string, symlinks bool) error {
var fileInfo os.FileInfo
var err error
if symlinks {
fileInfo, err = os.Stat(dirPath)
} else {
fileInfo, err = os.Lstat(dirPath)
}
if err != nil {
if os.IsNotExist(err) {
return storage.NewErrNotExist(dirPath)
}
return err
}
if !fileInfo.IsDir() {
return newErrNotDir(dirPath)
}
return nil
}