Debian Codegraph @

blob/fileblob/fileblob.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package fileblob provides a blob implementation that uses the filesystem.
16 // Use OpenBucket to construct a *blob.Bucket.
17 //
18 // To avoid partial writes, fileblob writes to a temporary file and then renames
19 // the temporary file to the final path on Close. By default, it creates these
20 // temporary files in `os.TempDir`. If `os.TempDir` is on a different mount than
21 // your base bucket path, the `os.Rename` will fail with `invalid cross-device link`.
22 // To avoid this, either configure the temp dir to use by setting the environment
23 // variable `TMPDIR`, or set `Options.NoTempDir` to `true` (fileblob will create
24 // the temporary files next to the actual files instead of in a temporary directory).
25 //
26 // By default fileblob stores blob metadata in "sidecar" files under the original
27 // filename with an additional ".attrs" suffix.
28 // This behaviour can be changed via `Options.Metadata`;
29 // writing of those metadata files can be suppressed by setting it to
30 // `MetadataDontWrite` or its equivalent "metadata=skip" in the URL for the opener.
31 // In either case, absent any stored metadata many `blob.Attributes` fields
32 // will be set to default values.
33 //
34 // # URLs
35 //
36 // For blob.OpenBucket, fileblob registers for the scheme "file".
37 // To customize the URL opener, or for more details on the URL format,
38 // see URLOpener.
39 // See https://gocloud.dev/concepts/urls/ for background information.
40 //
41 // # Escaping
42 //
43 // Go CDK supports all UTF-8 strings; to make this work with services lacking
44 // full UTF-8 support, strings must be escaped (during writes) and unescaped
45 // (during reads). The following escapes are performed for fileblob:
46 // - Blob keys: ASCII characters 0-31 are escaped to "__0x<hex>__".
47 // If os.PathSeparator != "/", it is also escaped.
48 // Additionally, the "/" in "../", the trailing "/" in "//", and a trailing
49 // "/" is key names are escaped in the same way.
50 // On Windows, the characters "<>:"|?*" are also escaped.
51 //
52 // # As
53 //
54 // fileblob exposes the following types for As:
55 // - Bucket: os.FileInfo
56 // - Error: *os.PathError
57 // - ListObject: os.FileInfo
58 // - Reader: io.Reader
59 // - ReaderOptions.BeforeRead: *os.File
60 // - Attributes: os.FileInfo
61 // - CopyOptions.BeforeCopy: *os.File
62 // - WriterOptions.BeforeWrite: *os.File
63 package fileblob // import "gocloud.dev/blob/fileblob"
64
65 import (
66 "context"
67 "crypto/hmac"
68 "crypto/md5"
69 "crypto/sha256"
70 "encoding/base64"
71 "errors"
72 "fmt"
73 "hash"
74 "io"
75 "io/fs"
76 "net/url"
77 "os"
78 "path/filepath"
79 "strconv"
80 "strings"
81 "sync"
82 "time"
83
84 "gocloud.dev/blob"
85 "gocloud.dev/blob/driver"
86 "gocloud.dev/gcerrors"
87 "gocloud.dev/internal/escape"
88 "gocloud.dev/internal/gcerr"
89 )
90
91 const defaultPageSize = 1000
92
93 func init() {
94 blob.DefaultURLMux().RegisterBucket(Scheme, &URLOpener{})
95 }
96
97 // Scheme is the URL scheme fileblob registers its URLOpener under on
98 // blob.DefaultMux.
99 const Scheme = "file"
100
101 // URLOpener opens file bucket URLs like "file:///foo/bar/baz".
102 //
103 // The URL's host is ignored unless it is ".", which is used to signal a
104 // relative path. For example, "file://./../.." uses "../.." as the path.
105 //
106 // If os.PathSeparator != "/", any leading "/" from the path is dropped
107 // and remaining '/' characters are converted to os.PathSeparator.
108 //
109 // The following query parameters are supported:
110 //
111 // - create_dir: (any non-empty value) the directory is created (using os.MkDirAll)
112 // if it does not already exist.
113 // - dir_file_mode: any directories that are created (the base directory when create_dir
114 // is true, or subdirectories for keys) are created using this os.FileMode, parsed
115 // using os.Parseuint. Defaults to 0777.
116 // - no_tmp_dir: (any non-empty value) temporary files are created next to the final
117 // path instead of in os.TempDir.
118 // - base_url: the base URL to use to construct signed URLs; see URLSignerHMAC
119 // - secret_key_path: path to read for the secret key used to construct signed URLs;
120 // see URLSignerHMAC
121 // - metadata: if set to "skip", won't write metadata such as blob.Attributes
122 // as per the package docstring
123 //
124 // If either of base_url / secret_key_path are provided, both must be.
125 //
126 // - file:///a/directory
127 // -> Passes "/a/directory" to OpenBucket.
128 // - file://localhost/a/directory
129 // -> Also passes "/a/directory".
130 // - file://./../..
131 // -> The hostname is ".", signaling a relative path; passes "../..".
132 // - file:///c:/foo/bar on Windows.
133 // -> Passes "c:\foo\bar".
134 // - file://localhost/c:/foo/bar on Windows.
135 // -> Also passes "c:\foo\bar".
136 // - file:///a/directory?base_url=/show&secret_key_path=secret.key
137 // -> Passes "/a/directory" to OpenBucket, and sets Options.URLSigner
138 // to a URLSignerHMAC initialized with base URL "/show" and secret key
139 // bytes read from the file "secret.key".
140 type URLOpener struct {
141 // Options specifies the default options to pass to OpenBucket.
142 Options Options
143 }
144
145 // OpenBucketURL opens a blob.Bucket based on u.
146 func (o *URLOpener) OpenBucketURL(ctx context.Context, u *url.URL) (*blob.Bucket, error) {
147 path := u.Path
148 // Hostname == "." means a relative path, so drop the leading "/".
149 // Also drop the leading "/" on Windows.
150 if u.Host == "." || os.PathSeparator != '/' {
151 path = strings.TrimPrefix(path, "/")
152 }
153 opts, err := o.forParams(ctx, u.Query())
154 if err != nil {
155 return nil, fmt.Errorf("open bucket %v: %v", u, err)
156 }
157 return OpenBucket(filepath.FromSlash(path), opts)
158 }
159
160 var recognizedParams = map[string]bool{
161 "create_dir": true,
162 "base_url": true,
163 "secret_key_path": true,
164 "metadata": true,
165 "no_tmp_dir": true,
166 "dir_file_mode": true,
167 }
168
169 type metadataOption string // Not exported as subject to change.
170
171 // Settings for Options.Metadata.
172 const (
173 // Metadata gets written to a separate file.
174 MetadataInSidecar metadataOption = ""
175 // Writes won't carry metadata, as per the package docstring.
176 MetadataDontWrite metadataOption = "skip"
177 )
178
179 func (o *URLOpener) forParams(ctx context.Context, q url.Values) (*Options, error) {
180 for k := range q {
181 if _, ok := recognizedParams[k]; !ok {
182 return nil, fmt.Errorf("invalid query parameter %q", k)
183 }
184 }
185 opts := new(Options)
186 *opts = o.Options
187
188 // Note: can't just use q.Get, because then we can't distinguish between
189 // "not set" (we should leave opts alone) vs "set to empty string" (which is
190 // one of the legal values, we should override opts).
191 metadataVal := q["metadata"]
192 if len(metadataVal) > 0 {
193 switch metadataOption(metadataVal[0]) {
194 case MetadataDontWrite:
195 opts.Metadata = MetadataDontWrite
196 case MetadataInSidecar:
197 opts.Metadata = MetadataInSidecar
198 default:
199 return nil, errors.New("fileblob.OpenBucket: unsupported value for query parameter 'metadata'")
200 }
201 }
202 if q.Get("create_dir") != "" {
203 opts.CreateDir = true
204 }
205 if fms := q.Get("dir_file_mode"); fms != "" {
206 fm, err := strconv.ParseUint(fms, 10, 32)
207 if err != nil {
208 return nil, fmt.Errorf("fileblob.OpenBucket: invalid dir_file_mode %q: %v", fms, err)
209 }
210 opts.DirFileMode = os.FileMode(fm)
211 }
212 if q.Get("no_tmp_dir") != "" {
213 opts.NoTempDir = true
214 }
215 baseURL := q.Get("base_url")
216 keyPath := q.Get("secret_key_path")
217 if (baseURL == "") != (keyPath == "") {
218 return nil, errors.New("fileblob.OpenBucket: must supply both base_url and secret_key_path query parameters")
219 }
220 if baseURL != "" {
221 burl, err := url.Parse(baseURL)
222 if err != nil {
223 return nil, err
224 }
225 sk, err := os.ReadFile(keyPath)
226 if err != nil {
227 return nil, err
228 }
229 opts.URLSigner = NewURLSignerHMAC(burl, sk)
230 }
231 return opts, nil
232 }
233
234 // Options sets options for constructing a *blob.Bucket backed by fileblob.
235 type Options struct {
236 // URLSigner implements signing URLs (to allow access to a resource without
237 // further authorization) and verifying that a given URL is unexpired and
238 // contains a signature produced by the URLSigner.
239 // URLSigner is only required for utilizing the SignedURL API.
240 URLSigner URLSigner
241
242 // If true, create the directory backing the Bucket if it does not exist
243 // (using os.MkdirAll).
244 CreateDir bool
245
246 // The FileMode to use when creating directories for the top-level directory
247 // backing the bucket (when CreateDir is true), and for subdirectories for keys.
248 // Defaults to 0777.
249 DirFileMode os.FileMode
250
251 // If true, don't use os.TempDir for temporary files, but instead place them
252 // next to the actual files. This may result in "stranded" temporary files
253 // (e.g., if the application is killed before the file cleanup runs).
254 //
255 // If your bucket directory is on a different mount than os.TempDir, you will
256 // need to set this to true, as os.Rename will fail across mount points.
257 NoTempDir bool
258
259 // Refers to the strategy for how to deal with metadata (such as blob.Attributes).
260 // For supported values please see the Metadata* constants.
261 // If left unchanged, 'MetadataInSidecar' will be used.
262 Metadata metadataOption
263 }
264
265 type bucket struct {
266 dir string
267 opts *Options
268 }
269
270 // openBucket creates a driver.Bucket that reads and writes to dir.
271 // dir must exist.
272 func openBucket(dir string, opts *Options) (driver.Bucket, error) {
273 if opts == nil {
274 opts = &Options{}
275 }
276 if opts.DirFileMode == 0 {
277 opts.DirFileMode = os.FileMode(0o777)
278 }
279
280 absdir, err := filepath.Abs(dir)
281 if err != nil {
282 return nil, fmt.Errorf("failed to convert %s into an absolute path: %v", dir, err)
283 }
284 info, err := os.Stat(absdir)
285
286 // Optionally, create the directory if it does not already exist.
287 if err != nil && opts.CreateDir && os.IsNotExist(err) {
288 err = os.MkdirAll(absdir, opts.DirFileMode)
289 if err != nil {
290 return nil, fmt.Errorf("tried to create directory but failed: %v", err)
291 }
292 info, err = os.Stat(absdir)
293 }
294 if err != nil {
295 return nil, err
296 }
297 if !info.IsDir() {
298 return nil, fmt.Errorf("%s is not a directory", absdir)
299 }
300 return &bucket{dir: absdir, opts: opts}, nil
301 }
302
303 // OpenBucket creates a *blob.Bucket backed by the filesystem and rooted at
304 // dir, which must exist. See the package documentation for an example.
305 func OpenBucket(dir string, opts *Options) (*blob.Bucket, error) {
306 drv, err := openBucket(dir, opts)
307 if err != nil {
308 return nil, err
309 }
310 return blob.NewBucket(drv), nil
311 }
312
313 func (b *bucket) Close() error {
314 return nil
315 }
316
317 // escapeKey does all required escaping for UTF-8 strings to work the filesystem.
318 func escapeKey(s string) string {
319 s = escape.HexEscape(s, func(r []rune, i int) bool {
320 c := r[i]
321 switch {
322 case c < 32:
323 return true
324 // We're going to replace '/' with os.PathSeparator below. In order for this
325 // to be reversible, we need to escape raw os.PathSeparators.
326 case os.PathSeparator != '/' && c == os.PathSeparator:
327 return true
328 // For "../", escape the trailing slash.
329 case i > 1 && c == '/' && r[i-1] == '.' && r[i-2] == '.':
330 return true
331 // For "//", escape the trailing slash.
332 case i > 0 && c == '/' && r[i-1] == '/':
333 return true
334 // Escape the trailing slash in a key.
335 case c == '/' && i == len(r)-1:
336 return true
337 // https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file
338 case os.PathSeparator == '\\' && (c == '>' || c == '<' || c == ':' || c == '"' || c == '|' || c == '?' || c == '*'):
339 return true
340 }
341 return false
342 })
343 // Replace "/" with os.PathSeparator if needed, so that the local filesystem
344 // can use subdirectories.
345 if os.PathSeparator != '/' {
346 s = strings.Replace(s, "/", string(os.PathSeparator), -1)
347 }
348 return s
349 }
350
351 // unescapeKey reverses escapeKey.
352 func unescapeKey(s string) string {
353 if os.PathSeparator != '/' {
354 s = strings.Replace(s, string(os.PathSeparator), "/", -1)
355 }
356 s = escape.HexUnescape(s)
357 return s
358 }
359
360 func (b *bucket) ErrorCode(err error) gcerrors.ErrorCode {
361 switch {
362 case os.IsNotExist(err):
363 return gcerrors.NotFound
364 default:
365 return gcerrors.Unknown
366 }
367 }
368
369 // path returns the full path for a key
370 func (b *bucket) path(key string) (string, error) {
371 path := filepath.Join(b.dir, escapeKey(key))
372 if strings.HasSuffix(path, attrsExt) {
373 return "", errAttrsExt
374 }
375 return path, nil
376 }
377
378 // forKey returns the full path, os.FileInfo, and attributes for key.
379 func (b *bucket) forKey(key string) (string, os.FileInfo, *xattrs, error) {
380 path, err := b.path(key)
381 if err != nil {
382 return "", nil, nil, err
383 }
384 info, err := os.Stat(path)
385 if err != nil {
386 return "", nil, nil, err
387 }
388 if info.IsDir() {
389 return "", nil, nil, os.ErrNotExist
390 }
391 xa, err := getAttrs(path)
392 if err != nil {
393 return "", nil, nil, err
394 }
395 return path, info, &xa, nil
396 }
397
398 // ListPaged implements driver.ListPaged.
399 func (b *bucket) ListPaged(ctx context.Context, opts *driver.ListOptions) (*driver.ListPage, error) {
400 var pageToken string
401 if len(opts.PageToken) > 0 {
402 pageToken = string(opts.PageToken)
403 }
404 pageSize := opts.PageSize
405 if pageSize == 0 {
406 pageSize = defaultPageSize
407 }
408 // If opts.Delimiter != "", lastPrefix contains the last "directory" key we
409 // added. It is used to avoid adding it again; all files in this "directory"
410 // are collapsed to the single directory entry.
411 var lastPrefix string
412 var lastKeyAdded string
413
414 // If the Prefix contains a "/", we can set the root of the Walk
415 // to the path specified by the Prefix as any files below the path will not
416 // match the Prefix.
417 // Note that we use "/" explicitly and not os.PathSeparator, as the opts.Prefix
418 // is in the unescaped form.
419 root := b.dir
420 if i := strings.LastIndex(opts.Prefix, "/"); i > -1 {
421 root = filepath.Join(root, opts.Prefix[:i])
422 }
423
424 // Do a full recursive scan of the root directory.
425 var result driver.ListPage
426 err := filepath.WalkDir(root, func(path string, info fs.DirEntry, err error) error {
427 if err != nil {
428 // Couldn't read this file/directory for some reason; just skip it.
429 return nil
430 }
431 // Skip the self-generated attribute files.
432 if strings.HasSuffix(path, attrsExt) {
433 return nil
434 }
435 // os.Walk returns the root directory; skip it.
436 if path == b.dir {
437 return nil
438 }
439 // Strip the <b.dir> prefix from path.
440 prefixLen := len(b.dir)
441 // Include the separator for non-root.
442 if b.dir != "/" {
443 prefixLen++
444 }
445 path = path[prefixLen:]
446 // Unescape the path to get the key.
447 key := unescapeKey(path)
448 // Skip all directories. If opts.Delimiter is set, we'll create
449 // pseudo-directories later.
450 // Note that returning nil means that we'll still recurse into it;
451 // we're just not adding a result for the directory itself.
452 if info.IsDir() {
453 key += "/"
454 // Avoid recursing into subdirectories if the directory name already
455 // doesn't match the prefix; any files in it are guaranteed not to match.
456 if len(key) > len(opts.Prefix) && !strings.HasPrefix(key, opts.Prefix) {
457 return filepath.SkipDir
458 }
459 // Similarly, avoid recursing into subdirectories if we're making
460 // "directories" and all of the files in this subdirectory are guaranteed
461 // to collapse to a "directory" that we've already added.
462 if lastPrefix != "" && strings.HasPrefix(key, lastPrefix) {
463 return filepath.SkipDir
464 }
465 return nil
466 }
467 // Skip files/directories that don't match the Prefix.
468 if !strings.HasPrefix(key, opts.Prefix) {
469 return nil
470 }
471 var md5 []byte
472 if xa, err := getAttrs(path); err == nil {
473 // Note: we only have the MD5 hash for blobs that we wrote.
474 // For other blobs, md5 will remain nil.
475 md5 = xa.MD5
476 }
477 fi, err := info.Info()
478 if err != nil {
479 return err
480 }
481 asFunc := func(i any) bool {
482 p, ok := i.(*os.FileInfo)
483 if !ok {
484 return false
485 }
486 *p = fi
487 return true
488 }
489 obj := &driver.ListObject{
490 Key: key,
491 ModTime: fi.ModTime(),
492 Size: fi.Size(),
493 MD5: md5,
494 AsFunc: asFunc,
495 }
496 // If using Delimiter, collapse "directories".
497 if opts.Delimiter != "" {
498 // Strip the prefix, which may contain Delimiter.
499 keyWithoutPrefix := key[len(opts.Prefix):]
500 // See if the key still contains Delimiter.
501 // If no, it's a file and we just include it.
502 // If yes, it's a file in a "sub-directory" and we want to collapse
503 // all files in that "sub-directory" into a single "directory" result.
504 if idx := strings.Index(keyWithoutPrefix, opts.Delimiter); idx != -1 {
505 prefix := opts.Prefix + keyWithoutPrefix[0:idx+len(opts.Delimiter)]
506 // We've already included this "directory"; don't add it.
507 if prefix == lastPrefix {
508 return nil
509 }
510 // Update the object to be a "directory".
511 obj = &driver.ListObject{
512 Key: prefix,
513 IsDir: true,
514 AsFunc: asFunc,
515 }
516 lastPrefix = prefix
517 }
518 }
519 // If there's a pageToken, skip anything before it.
520 if pageToken != "" && obj.Key <= pageToken {
521 return nil
522 }
523 // If we've already got a full page of results, set NextPageToken and stop.
524 // Unless the current object is a directory, in which case there may
525 // still be objects coming that are alphabetically before it (since
526 // we appended the delimiter). In that case, keep going; we'll trim the
527 // extra entries (if any) before returning.
528 if len(result.Objects) == pageSize && !obj.IsDir {
529 result.NextPageToken = []byte(result.Objects[pageSize-1].Key)
530 return io.EOF
531 }
532 result.Objects = append(result.Objects, obj)
533 // Normally, objects are added in the correct order (by Key).
534 // However, sometimes adding the file delimiter messes that up (e.g.,
535 // if the file delimiter is later in the alphabet than the last character
536 // of a key).
537 // Detect if this happens and swap if needed.
538 if len(result.Objects) > 1 && obj.Key < lastKeyAdded {
539 i := len(result.Objects) - 1
540 result.Objects[i-1], result.Objects[i] = result.Objects[i], result.Objects[i-1]
541 lastKeyAdded = result.Objects[i].Key
542 } else {
543 lastKeyAdded = obj.Key
544 }
545 return nil
546 })
547 if err != nil && err != io.EOF {
548 return nil, err
549 }
550 if len(result.Objects) > pageSize {
551 result.Objects = result.Objects[0:pageSize]
552 result.NextPageToken = []byte(result.Objects[pageSize-1].Key)
553 }
554 return &result, nil
555 }
556
557 // As implements driver.As.
558 func (b *bucket) As(i any) bool {
559 p, ok := i.(*os.FileInfo)
560 if !ok {
561 return false
562 }
563 fi, err := os.Stat(b.dir)
564 if err != nil {
565 return false
566 }
567 *p = fi
568 return true
569 }
570
571 // As implements driver.ErrorAs.
572 func (b *bucket) ErrorAs(err error, i any) bool {
573 if perr, ok := err.(*os.PathError); ok {
574 if p, ok := i.(**os.PathError); ok {
575 *p = perr
576 return true
577 }
578 }
579 return false
580 }
581
582 // Attributes implements driver.Attributes.
583 func (b *bucket) Attributes(ctx context.Context, key string) (*driver.Attributes, error) {
584 _, info, xa, err := b.forKey(key)
585 if err != nil {
586 return nil, err
587 }
588 return &driver.Attributes{
589 CacheControl: xa.CacheControl,
590 ContentDisposition: xa.ContentDisposition,
591 ContentEncoding: xa.ContentEncoding,
592 ContentLanguage: xa.ContentLanguage,
593 ContentType: xa.ContentType,
594 Metadata: xa.Metadata,
595 // CreateTime left as the zero time.
596 ModTime: info.ModTime(),
597 Size: info.Size(),
598 MD5: xa.MD5,
599 ETag: fmt.Sprintf("\"%x-%x\"", info.ModTime().UnixNano(), info.Size()),
600 AsFunc: func(i any) bool {
601 p, ok := i.(*os.FileInfo)
602 if !ok {
603 return false
604 }
605 *p = info
606 return true
607 },
608 }, nil
609 }
610
611 // NewRangeReader implements driver.NewRangeReader.
612 func (b *bucket) NewRangeReader(ctx context.Context, key string, offset, length int64, opts *driver.ReaderOptions) (driver.Reader, error) {
613 path, info, xa, err := b.forKey(key)
614 if err != nil {
615 return nil, err
616 }
617 f, err := os.Open(path)
618 if err != nil {
619 return nil, err
620 }
621 if opts.BeforeRead != nil {
622 if err := opts.BeforeRead(func(i any) bool {
623 p, ok := i.(**os.File)
624 if !ok {
625 return false
626 }
627 *p = f
628 return true
629 }); err != nil {
630 return nil, err
631 }
632 }
633 if offset > 0 {
634 if _, err := f.Seek(offset, io.SeekStart); err != nil {
635 return nil, err
636 }
637 }
638 r := io.Reader(f)
639 if length >= 0 {
640 r = io.LimitReader(r, length)
641 }
642 return &reader{
643 r: r,
644 c: f,
645 attrs: driver.ReaderAttributes{
646 ContentType: xa.ContentType,
647 ModTime: info.ModTime(),
648 Size: info.Size(),
649 },
650 }, nil
651 }
652
653 type reader struct {
654 r io.Reader
655 c io.Closer
656 attrs driver.ReaderAttributes
657 }
658
659 func (r *reader) Read(p []byte) (int, error) {
660 if r.r == nil {
661 return 0, io.EOF
662 }
663 return r.r.Read(p)
664 }
665
666 func (r *reader) Close() error {
667 if r.c == nil {
668 return nil
669 }
670 return r.c.Close()
671 }
672
673 func (r *reader) Attributes() *driver.ReaderAttributes {
674 return &r.attrs
675 }
676
677 func (r *reader) As(i any) bool {
678 p, ok := i.(*io.Reader)
679 if !ok {
680 return false
681 }
682 *p = r.r
683 return true
684 }
685
686 func createTemp(path string, noTempDir bool) (*os.File, error) {
687 // Use a custom createTemp function rather than os.CreateTemp() as
688 // os.CreateTemp() sets the permissions of the tempfile to 0600, rather than
689 // 0666, making it inconsistent with the directories and attribute files.
690 try := 0
691 for {
692 // Append the current time with nanosecond precision and .tmp to the
693 // base path. If the file already exists try again. Nanosecond changes enough
694 // between each iteration to make a conflict unlikely. Using the full
695 // time lowers the chance of a collision with a file using a similar
696 // pattern, but has undefined behavior after the year 2262.
697 var name string
698 if noTempDir {
699 name = path
700 } else {
701 name = filepath.Join(os.TempDir(), filepath.Base(path))
702 }
703 name += "." + strconv.FormatInt(time.Now().UnixNano(), 16) + ".tmp"
704 f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o666)
705 if os.IsExist(err) {
706 if try++; try < 10000 {
707 continue
708 }
709 return nil, &os.PathError{Op: "createtemp", Path: path + ".*.tmp", Err: os.ErrExist}
710 }
711 return f, err
712 }
713 }
714
715 // NewTypedWriter implements driver.NewTypedWriter.
716 func (b *bucket) NewTypedWriter(ctx context.Context, key, contentType string, opts *driver.WriterOptions) (driver.Writer, error) {
717 path, err := b.path(key)
718 if err != nil {
719 return nil, err
720 }
721 if err := os.MkdirAll(filepath.Dir(path), b.opts.DirFileMode); err != nil {
722 return nil, err
723 }
724 f, err := createTemp(path, b.opts.NoTempDir)
725 if err != nil {
726 return nil, err
727 }
728 if opts.BeforeWrite != nil {
729 if err := opts.BeforeWrite(func(i any) bool {
730 p, ok := i.(**os.File)
731 if !ok {
732 return false
733 }
734 *p = f
735 return true
736 }); err != nil {
737 return nil, err
738 }
739 }
740
741 if b.opts.Metadata == MetadataDontWrite {
742 w := &writer{
743 ctx: ctx,
744 File: f,
745 path: path,
746 ifNotExist: opts.IfNotExist,
747 mu: &sync.Mutex{},
748 }
749 return w, nil
750 }
751
752 var metadata map[string]string
753 if len(opts.Metadata) > 0 {
754 metadata = opts.Metadata
755 }
756 attrs := xattrs{
757 CacheControl: opts.CacheControl,
758 ContentDisposition: opts.ContentDisposition,
759 ContentEncoding: opts.ContentEncoding,
760 ContentLanguage: opts.ContentLanguage,
761 ContentType: contentType,
762 Metadata: metadata,
763 }
764 w := &writerWithSidecar{
765 ctx: ctx,
766 f: f,
767 path: path,
768 attrs: attrs,
769 contentMD5: opts.ContentMD5,
770 md5hash: md5.New(),
771 ifNotExist: opts.IfNotExist,
772 mu: &sync.Mutex{},
773 }
774 return w, nil
775 }
776
777 // writerWithSidecar implements the strategy of storing metadata in a distinct file.
778 type writerWithSidecar struct {
779 ctx context.Context
780 f *os.File
781 path string
782 attrs xattrs
783 contentMD5 []byte
784 // We compute the MD5 hash so that we can store it with the file attributes,
785 // not for verification.
786 md5hash hash.Hash
787 ifNotExist bool
788 mu *sync.Mutex
789 }
790
791 func (w *writerWithSidecar) Write(p []byte) (n int, err error) {
792 n, err = w.f.Write(p)
793 if err != nil {
794 // Don't hash the unwritten tail twice when writing is resumed.
795 w.md5hash.Write(p[:n])
796 return n, err
797 }
798 if _, err := w.md5hash.Write(p); err != nil {
799 return n, err
800 }
801 return n, nil
802 }
803
804 func (w *writerWithSidecar) Close() error {
805 err := w.f.Close()
806 if err != nil {
807 return err
808 }
809 // Always delete the temp file. On success, it will have been renamed so
810 // the Remove will fail.
811 defer func() {
812 _ = os.Remove(w.f.Name())
813 }()
814
815 // Check if the write was cancelled.
816 if err := w.ctx.Err(); err != nil {
817 return err
818 }
819
820 md5sum := w.md5hash.Sum(nil)
821 w.attrs.MD5 = md5sum
822
823 // Write the attributes file.
824 if err := setAttrs(w.path, w.attrs); err != nil {
825 return err
826 }
827
828 if w.ifNotExist {
829 w.mu.Lock()
830 defer w.mu.Unlock()
831 _, err = os.Stat(w.path)
832 if err == nil {
833 return gcerr.New(gcerrors.FailedPrecondition, err, 1, "File already exist")
834 }
835 }
836 // Rename the temp file to path.
837 if err := os.Rename(w.f.Name(), w.path); err != nil {
838 _ = os.Remove(w.path + attrsExt)
839 return err
840 }
841 return nil
842 }
843
844 // writer is a file with a temporary name until closed.
845 //
846 // Embedding os.File allows the likes of io.Copy to use optimizations.,
847 // which is why it is not folded into writerWithSidecar.
848 type writer struct {
849 *os.File
850 ctx context.Context
851 path string
852 ifNotExist bool
853 mu *sync.Mutex
854 }
855
856 func (w *writer) Upload(r io.Reader) error {
857 _, err := w.ReadFrom(r)
858 return err
859 }
860
861 func (w *writer) Close() error {
862 err := w.File.Close()
863 if err != nil {
864 return err
865 }
866 // Always delete the temp file. On success, it will have been renamed so
867 // the Remove will fail.
868 tempname := w.File.Name()
869 defer os.Remove(tempname)
870
871 // Check if the write was cancelled.
872 if err := w.ctx.Err(); err != nil {
873 return err
874 }
875
876 if w.ifNotExist {
877 w.mu.Lock()
878 defer w.mu.Unlock()
879 _, err = os.Stat(w.path)
880 if err == nil {
881 return gcerr.New(gcerrors.FailedPrecondition, err, 1, "File already exist")
882 }
883 }
884
885 // Rename the temp file to path.
886 if err := os.Rename(tempname, w.path); err != nil {
887 return err
888 }
889 return nil
890 }
891
892 // Copy implements driver.Copy.
893 func (b *bucket) Copy(ctx context.Context, dstKey, srcKey string, opts *driver.CopyOptions) error {
894 // Note: we could use NewRangeReader here, but since we need to copy all of
895 // the metadata (from xa), it's more efficient to do it directly.
896 srcPath, _, xa, err := b.forKey(srcKey)
897 if err != nil {
898 return err
899 }
900 f, err := os.Open(srcPath)
901 if err != nil {
902 return err
903 }
904 defer f.Close()
905
906 // We'll write the copy using Writer, to avoid re-implementing making of a
907 // temp file, cleaning up after partial failures, etc.
908 wopts := driver.WriterOptions{
909 CacheControl: xa.CacheControl,
910 ContentDisposition: xa.ContentDisposition,
911 ContentEncoding: xa.ContentEncoding,
912 ContentLanguage: xa.ContentLanguage,
913 Metadata: xa.Metadata,
914 BeforeWrite: opts.BeforeCopy,
915 }
916 // Create a cancelable context so we can cancel the write if there are
917 // problems.
918 writeCtx, cancel := context.WithCancel(ctx)
919 defer cancel()
920 w, err := b.NewTypedWriter(writeCtx, dstKey, xa.ContentType, &wopts)
921 if err != nil {
922 return err
923 }
924 _, err = io.Copy(w, f)
925 if err != nil {
926 cancel() // cancel before Close cancels the write
927 w.Close()
928 return err
929 }
930 return w.Close()
931 }
932
933 // Delete implements driver.Delete.
934 func (b *bucket) Delete(ctx context.Context, key string) error {
935 path, err := b.path(key)
936 if err != nil {
937 return err
938 }
939 err = os.Remove(path)
940 if err != nil {
941 return err
942 }
943 if err = os.Remove(path + attrsExt); err != nil && !os.IsNotExist(err) {
944 return err
945 }
946 return nil
947 }
948
949 // SignedURL implements driver.SignedURL
950 func (b *bucket) SignedURL(ctx context.Context, key string, opts *driver.SignedURLOptions) (string, error) {
951 if b.opts.URLSigner == nil {
952 return "", gcerr.New(gcerr.Unimplemented, nil, 1, "fileblob.SignedURL: bucket does not have an Options.URLSigner")
953 }
954 if opts.BeforeSign != nil {
955 if err := opts.BeforeSign(func(any) bool { return false }); err != nil {
956 return "", err
957 }
958 }
959 surl, err := b.opts.URLSigner.URLFromKey(ctx, key, opts)
960 if err != nil {
961 return "", err
962 }
963 return surl.String(), nil
964 }
965
966 // URLSigner defines an interface for creating and verifying a signed URL for
967 // objects in a fileblob bucket. Signed URLs are typically used for granting
968 // access to an otherwise-protected resource without requiring further
969 // authentication, and callers should take care to restrict the creation of
970 // signed URLs as is appropriate for their application.
971 type URLSigner interface {
972 // URLFromKey defines how the bucket's object key will be turned
973 // into a signed URL. URLFromKey must be safe to call from multiple goroutines.
974 URLFromKey(ctx context.Context, key string, opts *driver.SignedURLOptions) (*url.URL, error)
975
976 // KeyFromURL must be able to validate a URL returned from URLFromKey.
977 // KeyFromURL must only return the object if if the URL is
978 // both unexpired and authentic. KeyFromURL must be safe to call from
979 // multiple goroutines. Implementations of KeyFromURL should not modify
980 // the URL argument.
981 KeyFromURL(ctx context.Context, surl *url.URL) (string, error)
982 }
983
984 // URLSignerHMAC signs URLs by adding the object key, expiration time, and a
985 // hash-based message authentication code (HMAC) into the query parameters.
986 // Values of URLSignerHMAC with the same secret key will accept URLs produced by
987 // others as valid.
988 type URLSignerHMAC struct {
989 baseURL *url.URL
990 secretKey []byte
991 }
992
993 // NewURLSignerHMAC creates a URLSignerHMAC. If the secret key is empty,
994 // then NewURLSignerHMAC panics.
995 func NewURLSignerHMAC(baseURL *url.URL, secretKey []byte) *URLSignerHMAC {
996 if len(secretKey) == 0 {
997 panic("creating URLSignerHMAC: secretKey is required")
998 }
999 uc := new(url.URL)
1000 *uc = *baseURL
1001 return &URLSignerHMAC{
1002 baseURL: uc,
1003 secretKey: secretKey,
1004 }
1005 }
1006
1007 // URLFromKey creates a signed URL by copying the baseURL and appending the
1008 // object key, expiry, and signature as a query params.
1009 func (h *URLSignerHMAC) URLFromKey(ctx context.Context, key string, opts *driver.SignedURLOptions) (*url.URL, error) {
1010 sURL := new(url.URL)
1011 *sURL = *h.baseURL
1012
1013 q := sURL.Query()
1014 q.Set("obj", key)
1015 q.Set("expiry", strconv.FormatInt(time.Now().Add(opts.Expiry).Unix(), 10))
1016 q.Set("method", opts.Method)
1017 if opts.ContentType != "" {
1018 q.Set("contentType", opts.ContentType)
1019 }
1020 q.Set("signature", h.getMAC(q))
1021 sURL.RawQuery = q.Encode()
1022
1023 return sURL, nil
1024 }
1025
1026 func (h *URLSignerHMAC) getMAC(q url.Values) string {
1027 signedVals := url.Values{}
1028 signedVals.Set("obj", q.Get("obj"))
1029 signedVals.Set("expiry", q.Get("expiry"))
1030 signedVals.Set("method", q.Get("method"))
1031 if contentType := q.Get("contentType"); contentType != "" {
1032 signedVals.Set("contentType", contentType)
1033 }
1034 msg := signedVals.Encode()
1035
1036 hsh := hmac.New(sha256.New, h.secretKey)
1037 hsh.Write([]byte(msg))
1038 return base64.RawURLEncoding.EncodeToString(hsh.Sum(nil))
1039 }
1040
1041 // KeyFromURL checks expiry and signature, and returns the object key
1042 // only if the signed URL is both authentic and unexpired.
1043 func (h *URLSignerHMAC) KeyFromURL(ctx context.Context, sURL *url.URL) (string, error) {
1044 q := sURL.Query()
1045
1046 exp, err := strconv.ParseInt(q.Get("expiry"), 10, 64)
1047 if err != nil || time.Now().Unix() > exp {
1048 return "", errors.New("retrieving blob key from URL: key cannot be retrieved")
1049 }
1050
1051 if !h.checkMAC(q) {
1052 return "", errors.New("retrieving blob key from URL: key cannot be retrieved")
1053 }
1054 return q.Get("obj"), nil
1055 }
1056
1057 func (h *URLSignerHMAC) checkMAC(q url.Values) bool {
1058 mac := q.Get("signature")
1059 expected := h.getMAC(q)
1060 // This compares the Base-64 encoded MACs
1061 return hmac.Equal([]byte(mac), []byte(expected))
1062 }