| 1 |
/* |
| 2 |
Copyright The ORAS Authors. |
| 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 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
Unless required by applicable law or agreed to in writing, software |
| 8 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 9 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 |
See the License for the specific language governing permissions and |
| 11 |
limitations under the License. |
| 12 |
*/ |
| 13 |
|
| 14 |
// Package file provides implementation of a content store based on file system. |
| 15 |
package file |
| 16 |
|
| 17 |
import ( |
| 18 |
"compress/gzip" |
| 19 |
"context" |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"io" |
| 23 |
"os" |
| 24 |
"path/filepath" |
| 25 |
"strings" |
| 26 |
"sync" |
| 27 |
"sync/atomic" |
| 28 |
|
| 29 |
"github.com/opencontainers/go-digest" |
| 30 |
ocispec "github.com/opencontainers/image-spec/specs-go/v1" |
| 31 |
"oras.land/oras-go/v2/content" |
| 32 |
"oras.land/oras-go/v2/errdef" |
| 33 |
"oras.land/oras-go/v2/internal/cas" |
| 34 |
"oras.land/oras-go/v2/internal/graph" |
| 35 |
"oras.land/oras-go/v2/internal/ioutil" |
| 36 |
"oras.land/oras-go/v2/internal/resolver" |
| 37 |
) |
| 38 |
|
| 39 |
// bufPool is a pool of byte buffers that can be reused for copying content |
| 40 |
// between files. |
| 41 |
var bufPool = sync.Pool{ |
| 42 |
New: func() any { |
| 43 |
// the buffer size should be larger than or equal to 128 KiB |
| 44 |
// for performance considerations. |
| 45 |
// we choose 1 MiB here so there will be less disk I/O. |
| 46 |
buffer := make([]byte, 1<<20) // buffer size = 1 MiB |
| 47 |
return &buffer |
| 48 |
}, |
| 49 |
} |
| 50 |
|
| 51 |
const ( |
| 52 |
// AnnotationDigest is the annotation key for the digest of the uncompressed content. |
| 53 |
AnnotationDigest = "io.deis.oras.content.digest" |
| 54 |
// AnnotationUnpack is the annotation key for indication of unpacking. |
| 55 |
AnnotationUnpack = "io.deis.oras.content.unpack" |
| 56 |
// defaultBlobMediaType specifies the default blob media type. |
| 57 |
defaultBlobMediaType = ocispec.MediaTypeImageLayer |
| 58 |
// defaultBlobDirMediaType specifies the default blob directory media type. |
| 59 |
defaultBlobDirMediaType = ocispec.MediaTypeImageLayerGzip |
| 60 |
// defaultFallbackPushSizeLimit specifies the default size limit for pushing no-name contents. |
| 61 |
defaultFallbackPushSizeLimit = 1 << 22 // 4 MiB |
| 62 |
) |
| 63 |
|
| 64 |
// Store represents a file system based store, which implements `oras.Target`. |
| 65 |
// |
| 66 |
// In the file store, the contents described by names are location-addressed |
| 67 |
// by file paths. Meanwhile, the file paths are mapped to a virtual CAS |
| 68 |
// where all metadata are stored in the memory. |
| 69 |
// |
| 70 |
// The contents that are not described by names are stored in a fallback storage, |
| 71 |
// which is a limited memory CAS by default. |
| 72 |
// As all the metadata are stored in the memory, the file store |
| 73 |
// cannot be restored from the file system. |
| 74 |
// |
| 75 |
// After use, the file store needs to be closed by calling the [Store.Close] function. |
| 76 |
// The file store cannot be used after being closed. |
| 77 |
type Store struct { |
| 78 |
// TarReproducible controls if the tarballs generated |
| 79 |
// for the added directories are reproducible. |
| 80 |
// When specified, some metadata such as change time |
| 81 |
// will be removed from the files in the tarballs. Default value: false. |
| 82 |
TarReproducible bool |
| 83 |
// AllowPathTraversalOnWrite controls if path traversal is allowed |
| 84 |
// when writing files. When specified, writing files |
| 85 |
// outside the working directory will be allowed. Default value: false. |
| 86 |
AllowPathTraversalOnWrite bool |
| 87 |
// DisableOverwrite controls if push operations can overwrite existing files. |
| 88 |
// When specified, saving files to existing paths will be disabled. |
| 89 |
// Default value: false. |
| 90 |
DisableOverwrite bool |
| 91 |
// ForceCAS controls if files with same content but different names are |
| 92 |
// deduped after push operations. When a DAG is copied between CAS |
| 93 |
// targets, nodes are deduped by content. By default, file store restores |
| 94 |
// deduped successor files after a node is copied. This may result in two |
| 95 |
// files with identical content. If this is not the desired behavior, |
| 96 |
// ForceCAS can be specified to enforce CAS style dedup. |
| 97 |
// Default value: false. |
| 98 |
ForceCAS bool |
| 99 |
// IgnoreNoName controls if push operations should ignore descriptors |
| 100 |
// without a name. When specified, corresponding content will be discarded. |
| 101 |
// Otherwise, content will be saved to a fallback storage. |
| 102 |
// A typical scenario is pulling an arbitrary artifact masqueraded as OCI |
| 103 |
// image to file store. This option can be specified to discard unnamed |
| 104 |
// manifest and config file, while leaving only named layer files. |
| 105 |
// Default value: false. |
| 106 |
IgnoreNoName bool |
| 107 |
// SkipUnpack controls if push operations should skip unpacking files. This |
| 108 |
// value overrides the [AnnotationUnpack]. |
| 109 |
// Default value: false. |
| 110 |
SkipUnpack bool |
| 111 |
// PreservePermissions controls whether to preserve file permissions when unpacking, |
| 112 |
// disregarding the active umask, similar to tar's `--preserve-permissions` |
| 113 |
PreservePermissions bool |
| 114 |
|
| 115 |
workingDir string // the working directory of the file store |
| 116 |
closed int32 // if the store is closed - 0: false, 1: true. |
| 117 |
digestToPath sync.Map // map[digest.Digest]string |
| 118 |
nameToStatus sync.Map // map[string]*nameStatus |
| 119 |
tmpFiles sync.Map // map[string]bool |
| 120 |
|
| 121 |
fallbackStorage content.Storage |
| 122 |
resolver content.TagResolver |
| 123 |
graph *graph.Memory |
| 124 |
} |
| 125 |
|
| 126 |
// nameStatus contains a flag indicating if a name exists, |
| 127 |
// and a RWMutex protecting it. |
| 128 |
type nameStatus struct { |
| 129 |
sync.RWMutex |
| 130 |
exists bool |
| 131 |
} |
| 132 |
|
| 133 |
// New creates a file store, using a default limited memory CAS |
| 134 |
// as the fallback storage for contents without names. |
| 135 |
// When pushing content without names, the size of content being pushed |
| 136 |
// cannot exceed the default size limit: 4 MiB. |
| 137 |
func New(workingDir string) (*Store, error) { |
| 138 |
return NewWithFallbackLimit(workingDir, defaultFallbackPushSizeLimit) |
| 139 |
} |
| 140 |
|
| 141 |
// NewWithFallbackLimit creates a file store, using a default |
| 142 |
// limited memory CAS as the fallback storage for contents without names. |
| 143 |
// When pushing content without names, the size of content being pushed |
| 144 |
// cannot exceed the size limit specified by the `limit` parameter. |
| 145 |
func NewWithFallbackLimit(workingDir string, limit int64) (*Store, error) { |
| 146 |
m := cas.NewMemory() |
| 147 |
ls := content.LimitStorage(m, limit) |
| 148 |
return NewWithFallbackStorage(workingDir, ls) |
| 149 |
} |
| 150 |
|
| 151 |
// NewWithFallbackStorage creates a file store, |
| 152 |
// using the provided fallback storage for contents without names. |
| 153 |
func NewWithFallbackStorage(workingDir string, fallbackStorage content.Storage) (*Store, error) { |
| 154 |
workingDirAbs, err := filepath.Abs(workingDir) |
| 155 |
if err != nil { |
| 156 |
return nil, fmt.Errorf("failed to resolve absolute path for %s: %w", workingDir, err) |
| 157 |
} |
| 158 |
|
| 159 |
return &Store{ |
| 160 |
workingDir: workingDirAbs, |
| 161 |
fallbackStorage: fallbackStorage, |
| 162 |
resolver: resolver.NewMemory(), |
| 163 |
graph: graph.NewMemory(), |
| 164 |
}, nil |
| 165 |
} |
| 166 |
|
| 167 |
// Close closes the file store and cleans up all the temporary files used by it. |
| 168 |
// The store cannot be used after being closed. |
| 169 |
// This function is not go-routine safe. |
| 170 |
func (s *Store) Close() error { |
| 171 |
if s.isClosedSet() { |
| 172 |
return nil |
| 173 |
} |
| 174 |
s.setClosed() |
| 175 |
|
| 176 |
var errs []string |
| 177 |
s.tmpFiles.Range(func(name, _ any) bool { |
| 178 |
if err := os.Remove(name.(string)); err != nil { |
| 179 |
errs = append(errs, err.Error()) |
| 180 |
} |
| 181 |
return true |
| 182 |
}) |
| 183 |
|
| 184 |
if len(errs) > 0 { |
| 185 |
return errors.New(strings.Join(errs, "; ")) |
| 186 |
} |
| 187 |
return nil |
| 188 |
} |
| 189 |
|
| 190 |
// Fetch fetches the content identified by the descriptor. |
| 191 |
func (s *Store) Fetch(ctx context.Context, target ocispec.Descriptor) (io.ReadCloser, error) { |
| 192 |
if s.isClosedSet() { |
| 193 |
return nil, ErrStoreClosed |
| 194 |
} |
| 195 |
|
| 196 |
// if the target has name, check if the name exists. |
| 197 |
name := target.Annotations[ocispec.AnnotationTitle] |
| 198 |
if name != "" && !s.nameExists(name) { |
| 199 |
return nil, fmt.Errorf("%s: %s: %w", name, target.MediaType, errdef.ErrNotFound) |
| 200 |
} |
| 201 |
|
| 202 |
// check if the content exists in the store |
| 203 |
val, exists := s.digestToPath.Load(target.Digest) |
| 204 |
if exists { |
| 205 |
path := val.(string) |
| 206 |
|
| 207 |
fp, err := os.Open(path) |
| 208 |
if err != nil { |
| 209 |
if os.IsNotExist(err) { |
| 210 |
return nil, fmt.Errorf("%s: %s: %w", target.Digest, target.MediaType, errdef.ErrNotFound) |
| 211 |
} |
| 212 |
return nil, err |
| 213 |
} |
| 214 |
|
| 215 |
return fp, nil |
| 216 |
} |
| 217 |
|
| 218 |
// if the content does not exist in the store, |
| 219 |
// then fall back to the fallback storage. |
| 220 |
return s.fallbackStorage.Fetch(ctx, target) |
| 221 |
} |
| 222 |
|
| 223 |
// Push pushes the content, matching the expected descriptor. |
| 224 |
// If name is not specified in the descriptor, the content will be pushed to |
| 225 |
// the fallback storage by default, or will be discarded when |
| 226 |
// Store.IgnoreNoName is true. |
| 227 |
func (s *Store) Push(ctx context.Context, expected ocispec.Descriptor, content io.Reader) error { |
| 228 |
if s.isClosedSet() { |
| 229 |
return ErrStoreClosed |
| 230 |
} |
| 231 |
|
| 232 |
if err := s.push(ctx, expected, content); err != nil { |
| 233 |
if errors.Is(err, errSkipUnnamed) { |
| 234 |
return nil |
| 235 |
} |
| 236 |
return err |
| 237 |
} |
| 238 |
|
| 239 |
if !s.ForceCAS { |
| 240 |
if err := s.restoreDuplicates(ctx, expected); err != nil { |
| 241 |
return fmt.Errorf("failed to restore duplicated file: %w", err) |
| 242 |
} |
| 243 |
} |
| 244 |
|
| 245 |
return s.graph.Index(ctx, s, expected) |
| 246 |
} |
| 247 |
|
| 248 |
// push pushes the content, matching the expected descriptor. |
| 249 |
// If name is not specified in the descriptor, the content will be pushed to |
| 250 |
// the fallback storage by default, or will be discarded when |
| 251 |
// Store.IgnoreNoName is true. |
| 252 |
func (s *Store) push(ctx context.Context, expected ocispec.Descriptor, content io.Reader) error { |
| 253 |
name := expected.Annotations[ocispec.AnnotationTitle] |
| 254 |
if name == "" { |
| 255 |
if s.IgnoreNoName { |
| 256 |
return errSkipUnnamed |
| 257 |
} |
| 258 |
return s.fallbackStorage.Push(ctx, expected, content) |
| 259 |
} |
| 260 |
|
| 261 |
// check the status of the name |
| 262 |
status := s.status(name) |
| 263 |
status.Lock() |
| 264 |
defer status.Unlock() |
| 265 |
|
| 266 |
if status.exists { |
| 267 |
return fmt.Errorf("%s: %w", name, ErrDuplicateName) |
| 268 |
} |
| 269 |
|
| 270 |
target, err := s.resolveWritePath(name) |
| 271 |
if err != nil { |
| 272 |
return fmt.Errorf("failed to resolve path for writing: %w", err) |
| 273 |
} |
| 274 |
|
| 275 |
if needUnpack := expected.Annotations[AnnotationUnpack]; needUnpack == "true" && !s.SkipUnpack { |
| 276 |
err = s.pushDir(name, target, expected, content) |
| 277 |
} else { |
| 278 |
err = s.pushFile(target, expected, content) |
| 279 |
} |
| 280 |
if err != nil { |
| 281 |
return err |
| 282 |
} |
| 283 |
|
| 284 |
// update the name status as existed |
| 285 |
status.exists = true |
| 286 |
return nil |
| 287 |
} |
| 288 |
|
| 289 |
// restoreDuplicates restores successor files with same content but different |
| 290 |
// names. |
| 291 |
// See Store.ForceCAS for more info. |
| 292 |
func (s *Store) restoreDuplicates(ctx context.Context, desc ocispec.Descriptor) error { |
| 293 |
successors, err := content.Successors(ctx, s, desc) |
| 294 |
if err != nil { |
| 295 |
return err |
| 296 |
} |
| 297 |
for _, successor := range successors { |
| 298 |
name := successor.Annotations[ocispec.AnnotationTitle] |
| 299 |
if name == "" || s.nameExists(name) { |
| 300 |
continue |
| 301 |
} |
| 302 |
if err := func() error { |
| 303 |
desc := ocispec.Descriptor{ |
| 304 |
MediaType: successor.MediaType, |
| 305 |
Digest: successor.Digest, |
| 306 |
Size: successor.Size, |
| 307 |
} |
| 308 |
rc, err := s.Fetch(ctx, desc) |
| 309 |
if err != nil { |
| 310 |
return fmt.Errorf("%q: %s: %w", name, desc.MediaType, err) |
| 311 |
} |
| 312 |
defer rc.Close() |
| 313 |
if err := s.push(ctx, successor, rc); err != nil { |
| 314 |
return fmt.Errorf("%q: %s: %w", name, desc.MediaType, err) |
| 315 |
} |
| 316 |
return nil |
| 317 |
}(); err != nil { |
| 318 |
switch { |
| 319 |
case errors.Is(err, errdef.ErrNotFound): |
| 320 |
// allow pushing manifests before blobs |
| 321 |
case errors.Is(err, ErrDuplicateName): |
| 322 |
// in case multiple goroutines are pushing or restoring the same |
| 323 |
// named content, the error is ignored |
| 324 |
default: |
| 325 |
return err |
| 326 |
} |
| 327 |
} |
| 328 |
} |
| 329 |
return nil |
| 330 |
} |
| 331 |
|
| 332 |
// Exists returns true if the described content exists. |
| 333 |
func (s *Store) Exists(ctx context.Context, target ocispec.Descriptor) (bool, error) { |
| 334 |
if s.isClosedSet() { |
| 335 |
return false, ErrStoreClosed |
| 336 |
} |
| 337 |
|
| 338 |
// if the target has name, check if the name exists. |
| 339 |
name := target.Annotations[ocispec.AnnotationTitle] |
| 340 |
if name != "" && !s.nameExists(name) { |
| 341 |
return false, nil |
| 342 |
} |
| 343 |
|
| 344 |
// check if the content exists in the store |
| 345 |
_, exists := s.digestToPath.Load(target.Digest) |
| 346 |
if exists { |
| 347 |
return true, nil |
| 348 |
} |
| 349 |
|
| 350 |
// if the content does not exist in the store, |
| 351 |
// then fall back to the fallback storage. |
| 352 |
return s.fallbackStorage.Exists(ctx, target) |
| 353 |
} |
| 354 |
|
| 355 |
// Resolve resolves a reference to a descriptor. |
| 356 |
func (s *Store) Resolve(ctx context.Context, ref string) (ocispec.Descriptor, error) { |
| 357 |
if s.isClosedSet() { |
| 358 |
return ocispec.Descriptor{}, ErrStoreClosed |
| 359 |
} |
| 360 |
|
| 361 |
if ref == "" { |
| 362 |
return ocispec.Descriptor{}, errdef.ErrMissingReference |
| 363 |
} |
| 364 |
|
| 365 |
return s.resolver.Resolve(ctx, ref) |
| 366 |
} |
| 367 |
|
| 368 |
// Tag tags a descriptor with a reference string. |
| 369 |
func (s *Store) Tag(ctx context.Context, desc ocispec.Descriptor, ref string) error { |
| 370 |
if s.isClosedSet() { |
| 371 |
return ErrStoreClosed |
| 372 |
} |
| 373 |
|
| 374 |
if ref == "" { |
| 375 |
return errdef.ErrMissingReference |
| 376 |
} |
| 377 |
|
| 378 |
exists, err := s.Exists(ctx, desc) |
| 379 |
if err != nil { |
| 380 |
return err |
| 381 |
} |
| 382 |
if !exists { |
| 383 |
return fmt.Errorf("%s: %s: %w", desc.Digest, desc.MediaType, errdef.ErrNotFound) |
| 384 |
} |
| 385 |
|
| 386 |
return s.resolver.Tag(ctx, desc, ref) |
| 387 |
} |
| 388 |
|
| 389 |
// Predecessors returns the nodes directly pointing to the current node. |
| 390 |
// Predecessors returns nil without error if the node does not exists in the |
| 391 |
// store. |
| 392 |
func (s *Store) Predecessors(ctx context.Context, node ocispec.Descriptor) ([]ocispec.Descriptor, error) { |
| 393 |
if s.isClosedSet() { |
| 394 |
return nil, ErrStoreClosed |
| 395 |
} |
| 396 |
|
| 397 |
return s.graph.Predecessors(ctx, node) |
| 398 |
} |
| 399 |
|
| 400 |
// Add adds a file or a directory into the file store. |
| 401 |
// Hard links within the directory are treated as regular files. |
| 402 |
func (s *Store) Add(ctx context.Context, name, mediaType, path string) (ocispec.Descriptor, error) { |
| 403 |
if s.isClosedSet() { |
| 404 |
return ocispec.Descriptor{}, ErrStoreClosed |
| 405 |
} |
| 406 |
|
| 407 |
if name == "" { |
| 408 |
return ocispec.Descriptor{}, ErrMissingName |
| 409 |
} |
| 410 |
|
| 411 |
// check the status of the name |
| 412 |
status := s.status(name) |
| 413 |
status.Lock() |
| 414 |
defer status.Unlock() |
| 415 |
|
| 416 |
if status.exists { |
| 417 |
return ocispec.Descriptor{}, fmt.Errorf("%s: %w", name, ErrDuplicateName) |
| 418 |
} |
| 419 |
|
| 420 |
if path == "" { |
| 421 |
path = name |
| 422 |
} |
| 423 |
path = s.absPath(path) |
| 424 |
|
| 425 |
fi, err := os.Stat(path) |
| 426 |
if err != nil { |
| 427 |
return ocispec.Descriptor{}, fmt.Errorf("failed to stat %s: %w", path, err) |
| 428 |
} |
| 429 |
|
| 430 |
// generate descriptor |
| 431 |
var desc ocispec.Descriptor |
| 432 |
if fi.IsDir() { |
| 433 |
desc, err = s.descriptorFromDir(ctx, name, mediaType, path) |
| 434 |
} else { |
| 435 |
desc, err = s.descriptorFromFile(fi, mediaType, path) |
| 436 |
} |
| 437 |
if err != nil { |
| 438 |
return ocispec.Descriptor{}, fmt.Errorf("failed to generate descriptor from %s: %w", path, err) |
| 439 |
} |
| 440 |
|
| 441 |
if desc.Annotations == nil { |
| 442 |
desc.Annotations = make(map[string]string) |
| 443 |
} |
| 444 |
desc.Annotations[ocispec.AnnotationTitle] = name |
| 445 |
|
| 446 |
// update the name status as existed |
| 447 |
status.exists = true |
| 448 |
return desc, nil |
| 449 |
} |
| 450 |
|
| 451 |
// saveFile saves content matching the descriptor to the given file. |
| 452 |
func (s *Store) saveFile(fp *os.File, expected ocispec.Descriptor, content io.Reader) (err error) { |
| 453 |
defer func() { |
| 454 |
closeErr := fp.Close() |
| 455 |
if err == nil { |
| 456 |
err = closeErr |
| 457 |
} |
| 458 |
}() |
| 459 |
path := fp.Name() |
| 460 |
|
| 461 |
buf := bufPool.Get().(*[]byte) |
| 462 |
defer bufPool.Put(buf) |
| 463 |
if err := ioutil.CopyBuffer(fp, content, *buf, expected); err != nil { |
| 464 |
return fmt.Errorf("failed to copy content to %s: %w", path, err) |
| 465 |
} |
| 466 |
|
| 467 |
s.digestToPath.Store(expected.Digest, path) |
| 468 |
return nil |
| 469 |
} |
| 470 |
|
| 471 |
// pushFile saves content matching the descriptor to the target path. |
| 472 |
func (s *Store) pushFile(target string, expected ocispec.Descriptor, content io.Reader) error { |
| 473 |
if err := ensureDir(filepath.Dir(target)); err != nil { |
| 474 |
return fmt.Errorf("failed to ensure directories of the target path: %w", err) |
| 475 |
} |
| 476 |
|
| 477 |
fp, err := os.Create(target) |
| 478 |
if err != nil { |
| 479 |
return fmt.Errorf("failed to create file %s: %w", target, err) |
| 480 |
} |
| 481 |
|
| 482 |
return s.saveFile(fp, expected, content) |
| 483 |
} |
| 484 |
|
| 485 |
// pushDir saves content matching the descriptor to the target directory. |
| 486 |
func (s *Store) pushDir(name, target string, expected ocispec.Descriptor, content io.Reader) (err error) { |
| 487 |
if err := ensureDir(target); err != nil { |
| 488 |
return fmt.Errorf("failed to ensure directories of the target path: %w", err) |
| 489 |
} |
| 490 |
|
| 491 |
gz, err := s.tempFile() |
| 492 |
if err != nil { |
| 493 |
return err |
| 494 |
} |
| 495 |
|
| 496 |
gzPath := gz.Name() |
| 497 |
// the digest of the gz is verified while saving |
| 498 |
if err := s.saveFile(gz, expected, content); err != nil { |
| 499 |
return fmt.Errorf("failed to save gzip to %s: %w", gzPath, err) |
| 500 |
} |
| 501 |
|
| 502 |
checksum := expected.Annotations[AnnotationDigest] |
| 503 |
buf := bufPool.Get().(*[]byte) |
| 504 |
defer bufPool.Put(buf) |
| 505 |
if err := extractTarGzip(target, name, gzPath, checksum, *buf, s.PreservePermissions); err != nil { |
| 506 |
return fmt.Errorf("failed to extract tar to %s: %w", target, err) |
| 507 |
} |
| 508 |
return nil |
| 509 |
} |
| 510 |
|
| 511 |
// descriptorFromDir generates descriptor from the given directory. |
| 512 |
func (s *Store) descriptorFromDir(ctx context.Context, name, mediaType, dir string) (desc ocispec.Descriptor, err error) { |
| 513 |
// make a temp file to store the gzip |
| 514 |
gz, err := s.tempFile() |
| 515 |
if err != nil { |
| 516 |
return ocispec.Descriptor{}, err |
| 517 |
} |
| 518 |
defer func() { |
| 519 |
closeErr := gz.Close() |
| 520 |
if err == nil { |
| 521 |
err = closeErr |
| 522 |
} |
| 523 |
}() |
| 524 |
|
| 525 |
// compress the directory |
| 526 |
gzDigester := digest.Canonical.Digester() |
| 527 |
gzw := gzip.NewWriter(io.MultiWriter(gz, gzDigester.Hash())) |
| 528 |
defer func() { |
| 529 |
closeErr := gzw.Close() |
| 530 |
if err == nil { |
| 531 |
err = closeErr |
| 532 |
} |
| 533 |
}() |
| 534 |
|
| 535 |
tarDigester := digest.Canonical.Digester() |
| 536 |
tw := io.MultiWriter(gzw, tarDigester.Hash()) |
| 537 |
buf := bufPool.Get().(*[]byte) |
| 538 |
defer bufPool.Put(buf) |
| 539 |
if err := tarDirectory(ctx, dir, name, tw, s.TarReproducible, *buf); err != nil { |
| 540 |
return ocispec.Descriptor{}, fmt.Errorf("failed to tar %s: %w", dir, err) |
| 541 |
} |
| 542 |
|
| 543 |
// flush all |
| 544 |
if err := gzw.Close(); err != nil { |
| 545 |
return ocispec.Descriptor{}, err |
| 546 |
} |
| 547 |
if err := gz.Sync(); err != nil { |
| 548 |
return ocispec.Descriptor{}, err |
| 549 |
} |
| 550 |
|
| 551 |
fi, err := gz.Stat() |
| 552 |
if err != nil { |
| 553 |
return ocispec.Descriptor{}, err |
| 554 |
} |
| 555 |
|
| 556 |
// map gzip digest to gzip path |
| 557 |
gzDigest := gzDigester.Digest() |
| 558 |
s.digestToPath.Store(gzDigest, gz.Name()) |
| 559 |
|
| 560 |
// generate descriptor |
| 561 |
if mediaType == "" { |
| 562 |
mediaType = defaultBlobDirMediaType |
| 563 |
} |
| 564 |
|
| 565 |
return ocispec.Descriptor{ |
| 566 |
MediaType: mediaType, |
| 567 |
Digest: gzDigest, // digest for the compressed content |
| 568 |
Size: fi.Size(), |
| 569 |
Annotations: map[string]string{ |
| 570 |
AnnotationDigest: tarDigester.Digest().String(), // digest fot the uncompressed content |
| 571 |
AnnotationUnpack: "true", // the content needs to be unpacked |
| 572 |
}, |
| 573 |
}, nil |
| 574 |
} |
| 575 |
|
| 576 |
// descriptorFromFile generates descriptor from the given file. |
| 577 |
func (s *Store) descriptorFromFile(fi os.FileInfo, mediaType, path string) (desc ocispec.Descriptor, err error) { |
| 578 |
fp, err := os.Open(path) |
| 579 |
if err != nil { |
| 580 |
return ocispec.Descriptor{}, err |
| 581 |
} |
| 582 |
defer func() { |
| 583 |
closeErr := fp.Close() |
| 584 |
if err == nil { |
| 585 |
err = closeErr |
| 586 |
} |
| 587 |
}() |
| 588 |
|
| 589 |
dgst, err := digest.FromReader(fp) |
| 590 |
if err != nil { |
| 591 |
return ocispec.Descriptor{}, err |
| 592 |
} |
| 593 |
// map digest to file path |
| 594 |
s.digestToPath.Store(dgst, path) |
| 595 |
|
| 596 |
// generate descriptor |
| 597 |
if mediaType == "" { |
| 598 |
mediaType = defaultBlobMediaType |
| 599 |
} |
| 600 |
|
| 601 |
return ocispec.Descriptor{ |
| 602 |
MediaType: mediaType, |
| 603 |
Digest: dgst, |
| 604 |
Size: fi.Size(), |
| 605 |
}, nil |
| 606 |
} |
| 607 |
|
| 608 |
// resolveWritePath resolves the path to write for the given name. |
| 609 |
func (s *Store) resolveWritePath(name string) (string, error) { |
| 610 |
path := s.absPath(name) |
| 611 |
if !s.AllowPathTraversalOnWrite { |
| 612 |
base, err := filepath.Abs(s.workingDir) |
| 613 |
if err != nil { |
| 614 |
return "", err |
| 615 |
} |
| 616 |
target, err := filepath.Abs(path) |
| 617 |
if err != nil { |
| 618 |
return "", err |
| 619 |
} |
| 620 |
rel, err := filepath.Rel(base, target) |
| 621 |
if err != nil { |
| 622 |
return "", ErrPathTraversalDisallowed |
| 623 |
} |
| 624 |
rel = filepath.ToSlash(rel) |
| 625 |
if strings.HasPrefix(rel, "../") || rel == ".." { |
| 626 |
return "", ErrPathTraversalDisallowed |
| 627 |
} |
| 628 |
// The lexical check above prevents "../" escapes but does not resolve |
| 629 |
// symlinks. A symlink component under workingDir (e.g. "out" -> "/outside") |
| 630 |
// passes the lexical check yet directs writes outside workingDir. |
| 631 |
// Re-check after resolving symlinks in the parent path to close that gap. |
| 632 |
if err := checkSymlinkEscape(base, target); err != nil { |
| 633 |
return "", err |
| 634 |
} |
| 635 |
} |
| 636 |
if s.DisableOverwrite { |
| 637 |
if _, err := os.Stat(path); err == nil { |
| 638 |
return "", ErrOverwriteDisallowed |
| 639 |
} else if !os.IsNotExist(err) { |
| 640 |
return "", err |
| 641 |
} |
| 642 |
} |
| 643 |
return path, nil |
| 644 |
} |
| 645 |
|
| 646 |
// status returns the nameStatus for the given name. |
| 647 |
func (s *Store) status(name string) *nameStatus { |
| 648 |
v, _ := s.nameToStatus.LoadOrStore(name, &nameStatus{sync.RWMutex{}, false}) |
| 649 |
status := v.(*nameStatus) |
| 650 |
return status |
| 651 |
} |
| 652 |
|
| 653 |
// nameExists returns if the given name exists in the file store. |
| 654 |
func (s *Store) nameExists(name string) bool { |
| 655 |
status := s.status(name) |
| 656 |
status.RLock() |
| 657 |
defer status.RUnlock() |
| 658 |
|
| 659 |
return status.exists |
| 660 |
} |
| 661 |
|
| 662 |
// tempFile creates a temp file with the file name format "oras_file_randomString", |
| 663 |
// and returns the pointer to the temp file. |
| 664 |
func (s *Store) tempFile() (*os.File, error) { |
| 665 |
tmp, err := os.CreateTemp("", "oras_file_*") |
| 666 |
if err != nil { |
| 667 |
return nil, err |
| 668 |
} |
| 669 |
|
| 670 |
s.tmpFiles.Store(tmp.Name(), true) |
| 671 |
return tmp, nil |
| 672 |
} |
| 673 |
|
| 674 |
// absPath returns the absolute path of the path. |
| 675 |
func (s *Store) absPath(path string) string { |
| 676 |
if filepath.IsAbs(path) { |
| 677 |
return path |
| 678 |
} |
| 679 |
return filepath.Join(s.workingDir, path) |
| 680 |
} |
| 681 |
|
| 682 |
// isClosedSet returns true if the `closed` flag is set, otherwise returns false. |
| 683 |
func (s *Store) isClosedSet() bool { |
| 684 |
return atomic.LoadInt32(&s.closed) == 1 |
| 685 |
} |
| 686 |
|
| 687 |
// setClosed sets the `closed` flag. |
| 688 |
func (s *Store) setClosed() { |
| 689 |
atomic.StoreInt32(&s.closed, 1) |
| 690 |
} |
| 691 |
|
| 692 |
// ensureDir ensures the directories of the path exists. |
| 693 |
func ensureDir(path string) error { |
| 694 |
return os.MkdirAll(path, 0777) |
| 695 |
} |
| 696 |
|
| 697 |
// checkSymlinkEscape returns ErrPathTraversalDisallowed if resolving symlinks |
| 698 |
// in target's ancestor directories causes it to escape base. target may not |
| 699 |
// yet exist, so symlinks are resolved on its deepest existing ancestor. |
| 700 |
func checkSymlinkEscape(base, target string) error { |
| 701 |
realBase, err := filepath.EvalSymlinks(base) |
| 702 |
if err != nil { |
| 703 |
if os.IsNotExist(err) { |
| 704 |
return nil // base doesn't exist yet; no symlinks to follow |
| 705 |
} |
| 706 |
return err |
| 707 |
} |
| 708 |
realTarget, err := realPathForWrite(target) |
| 709 |
if err != nil { |
| 710 |
return err |
| 711 |
} |
| 712 |
rel, err := filepath.Rel(realBase, realTarget) |
| 713 |
if err != nil { |
| 714 |
return ErrPathTraversalDisallowed |
| 715 |
} |
| 716 |
rel = filepath.ToSlash(rel) |
| 717 |
if strings.HasPrefix(rel, "../") || rel == ".." { |
| 718 |
return ErrPathTraversalDisallowed |
| 719 |
} |
| 720 |
return nil |
| 721 |
} |
| 722 |
|
| 723 |
// realPathForWrite resolves symlinks in the deepest existing ancestor of path |
| 724 |
// and returns the resulting absolute path. Non-existent path components are |
| 725 |
// appended verbatim, matching the semantics of a file about to be created. |
| 726 |
func realPathForWrite(path string) (string, error) { |
| 727 |
dir := filepath.Dir(path) |
| 728 |
suffix := filepath.Base(path) |
| 729 |
for { |
| 730 |
real, err := filepath.EvalSymlinks(dir) |
| 731 |
if err == nil { |
| 732 |
return filepath.Join(real, suffix), nil |
| 733 |
} |
| 734 |
if !os.IsNotExist(err) { |
| 735 |
return "", err |
| 736 |
} |
| 737 |
parent := filepath.Dir(dir) |
| 738 |
if parent == dir { |
| 739 |
return path, nil // reached filesystem root |
| 740 |
} |
| 741 |
suffix = filepath.Join(filepath.Base(dir), suffix) |
| 742 |
dir = parent |
| 743 |
} |
| 744 |
} |