Debian Codegraph @

copy/copy.go

raw symbols SCIP
1 package fs
2
3 import (
4 "context"
5 "os"
6 "path"
7 "path/filepath"
8 "runtime"
9 "slices"
10 "strings"
11 "sync"
12 "time"
13
14 "github.com/containerd/continuity/fs"
15 "github.com/moby/patternmatcher"
16 "github.com/pkg/errors"
17 mode "github.com/tonistiigi/dchapes-mode"
18 "github.com/tonistiigi/fsutil"
19 )
20
21 const defaultDirectoryMode = 0755
22
23 var bufferPool = &sync.Pool{
24 New: func() interface{} {
25 buffer := make([]byte, 32*1024)
26 return &buffer
27 },
28 }
29
30 func rootPath(root, p string, followLinks bool) (string, error) {
31 p = filepath.Join("/", p)
32 if p == "/" {
33 return root, nil
34 }
35 if followLinks {
36 return fs.RootPath(root, p)
37 }
38 d, f := filepath.Split(p)
39 ppath, err := fs.RootPath(root, d)
40 if err != nil {
41 return "", err
42 }
43 return filepath.Join(ppath, f), nil
44 }
45
46 func ResolveWildcards(root, src string, followLinks bool) ([]string, error) {
47 d1, d2 := splitWildcards(src)
48 if d2 != "" {
49 p, err := rootPath(root, d1, followLinks)
50 if err != nil {
51 return nil, err
52 }
53 matches, err := resolveWildcards(p, d2)
54 if err != nil {
55 return nil, err
56 }
57 for i, m := range matches {
58 p, err := rel(root, m)
59 if err != nil {
60 return nil, err
61 }
62 matches[i] = p
63 }
64 return matches, nil
65 }
66 return []string{d1}, nil
67 }
68
69 // Copy copies files using `cp -a` semantics.
70 // Copy is likely unsafe to be used in non-containerized environments.
71 func Copy(ctx context.Context, srcRoot, src, dstRoot, dst string, opts ...Opt) error {
72 var ci CopyInfo
73 for _, o := range opts {
74 o(&ci)
75 }
76 ensureDstPath := dst
77 if d, f := filepath.Split(dst); f != "" && f != "." {
78 ensureDstPath = d
79 }
80 if ensureDstPath != "" {
81 ensureDstPath, err := fs.RootPath(dstRoot, ensureDstPath)
82 if err != nil {
83 return err
84 }
85 perm := defaultDirectoryMode
86 if ci.Mode != nil {
87 perm = *ci.Mode
88 }
89 if createdDirs, err := MkdirAll(ensureDstPath, os.FileMode(perm), ci.Chown, ci.Utime); err != nil {
90 return err
91 } else {
92 defer fixCreatedParentDirs(createdDirs, ci.Utime)
93 }
94 }
95
96 var modeSet *mode.Set
97 if ci.ModeStr != "" {
98 ms, err := mode.ParseWithUmask(ci.ModeStr, 0)
99 if err != nil {
100 return err
101 }
102 modeSet = &ms
103 }
104
105 dst, err := fs.RootPath(dstRoot, filepath.Clean(dst))
106 if err != nil {
107 return err
108 }
109
110 c, err := newCopier(dstRoot, ci.Chown, ci.Utime, ci.Mode, modeSet, ci.XAttrErrorHandler, ci.IncludePatterns, ci.ExcludePatterns, ci.AlwaysReplaceExistingDestPaths, ci.ChangeFunc)
111 if err != nil {
112 return err
113 }
114 c.testHookLstat = ci.testHookLstat
115 srcs := []string{src}
116
117 if ci.AllowWildcards {
118 matches, err := ResolveWildcards(srcRoot, src, ci.FollowLinks)
119 if err != nil {
120 return err
121 }
122 if len(matches) == 0 {
123 return errors.Errorf("no matches found: %s", src)
124 }
125 srcs = matches
126 }
127
128 for _, src := range srcs {
129 srcFollowed, err := rootPath(srcRoot, src, ci.FollowLinks)
130 if err != nil {
131 return err
132 }
133 dst, createdDirs, err := c.prepareTargetDir(srcFollowed, src, dst, ci.CopyDirContents)
134 if err != nil {
135 return err
136 }
137 defer fixCreatedParentDirs(createdDirs, ci.Utime)
138 if err := c.copy(ctx, srcFollowed, "", dst, false, patternmatcher.MatchInfo{}, patternmatcher.MatchInfo{}); err != nil {
139 return err
140 }
141 }
142
143 return nil
144 }
145
146 func (c *copier) prepareTargetDir(srcFollowed, src, destPath string, copyDirContents bool) (string, []string, error) {
147 fiSrc, err := os.Lstat(srcFollowed)
148 if err != nil {
149 return "", nil, err
150 }
151
152 fiDest, err := os.Stat(destPath)
153 if err != nil {
154 if !os.IsNotExist(err) {
155 return "", nil, errors.Wrap(err, "failed to lstat destination path")
156 }
157 }
158
159 if (!copyDirContents && fiSrc.IsDir() && fiDest != nil) || (!fiSrc.IsDir() && fiDest != nil && fiDest.IsDir()) {
160 destPath = filepath.Join(destPath, filepath.Base(src))
161 }
162
163 target := filepath.Dir(destPath)
164
165 if copyDirContents && fiSrc.IsDir() && fiDest == nil {
166 target = destPath
167 }
168 var createdDirs []string
169 mode := defaultDirectoryMode
170 if c.mode != nil {
171 mode = *c.mode
172 }
173 if dirs, err := MkdirAll(target, os.FileMode(mode), c.chown, c.utime); err != nil {
174 return "", nil, err
175 } else {
176 createdDirs = dirs
177 }
178
179 return destPath, createdDirs, nil
180 }
181
182 type User struct {
183 UID, GID int
184 SID string
185 }
186
187 type Chowner func(*User) (*User, error)
188
189 type XAttrErrorHandler func(dst, src, xattrKey string, err error) error
190
191 type CopyInfo struct {
192 Chown Chowner
193 Utime *time.Time
194 AllowWildcards bool
195 Mode *int
196 // ModeStr is mode in non-octal format. Overrides Mode if non-empty.
197 ModeStr string
198 XAttrErrorHandler XAttrErrorHandler
199 CopyDirContents bool
200 FollowLinks bool
201 // Include only files/dirs matching at least one of these patterns
202 IncludePatterns []string
203 // Exclude files/dir matching any of these patterns (even if they match an include pattern)
204 ExcludePatterns []string
205 // If true, any source path that overwrite existing destination paths will always replace
206 // the existing destination path, even if they are of different types (e.g. a directory will
207 // replace any existing symlink or file)
208 AlwaysReplaceExistingDestPaths bool
209 ChangeFunc fsutil.ChangeFunc
210
211 // testHookLstat is called before each os.Lstat if non-nil (for testing only)
212 testHookLstat func(path string)
213 }
214
215 type Opt func(*CopyInfo)
216
217 func WithCopyInfo(ci CopyInfo) func(*CopyInfo) {
218 return func(c *CopyInfo) {
219 *c = ci
220 }
221 }
222
223 func WithChown(uid, gid int) Opt {
224 return func(ci *CopyInfo) {
225 ci.Chown = func(*User) (*User, error) {
226 return &User{UID: uid, GID: gid}, nil
227 }
228 }
229 }
230
231 func AllowWildcards(ci *CopyInfo) {
232 ci.AllowWildcards = true
233 }
234
235 func WithXAttrErrorHandler(h XAttrErrorHandler) Opt {
236 return func(ci *CopyInfo) {
237 ci.XAttrErrorHandler = h
238 }
239 }
240
241 func AllowXAttrErrors(ci *CopyInfo) {
242 h := func(string, string, string, error) error {
243 return nil
244 }
245 WithXAttrErrorHandler(h)(ci)
246 }
247
248 func WithIncludePattern(includePattern string) Opt {
249 return func(ci *CopyInfo) {
250 ci.IncludePatterns = append(ci.IncludePatterns, includePattern)
251 }
252 }
253
254 func WithExcludePattern(excludePattern string) Opt {
255 return func(ci *CopyInfo) {
256 ci.ExcludePatterns = append(ci.ExcludePatterns, excludePattern)
257 }
258 }
259
260 func WithChangeNotifier(fn fsutil.ChangeFunc) Opt {
261 return func(ci *CopyInfo) {
262 ci.ChangeFunc = fn
263 }
264 }
265
266 type copier struct {
267 chown Chowner
268 utime *time.Time
269 mode *int
270 modeSet *mode.Set
271 inodes map[uint64]string
272 xattrErrorHandler XAttrErrorHandler
273 includePatternMatcher *patternmatcher.PatternMatcher
274 excludePatternMatcher *patternmatcher.PatternMatcher
275 parentDirs []parentDir
276 changefn fsutil.ChangeFunc
277 root string
278 alwaysReplaceExistingDestPaths bool
279 testHookLstat func(string)
280 }
281
282 type parentDir struct {
283 srcPath string
284 dstPath string
285 copied bool
286 }
287
288 func newCopier(root string, chown Chowner, tm *time.Time, mode *int, modeSet *mode.Set, xeh XAttrErrorHandler, includePatterns, excludePatterns []string, alwaysReplaceExistingDestPaths bool, changeFunc fsutil.ChangeFunc) (*copier, error) {
289 if xeh == nil {
290 xeh = func(dst, src, key string, err error) error {
291 return err
292 }
293 }
294
295 var includePatternMatcher *patternmatcher.PatternMatcher
296 if len(includePatterns) != 0 {
297 var err error
298 includePatternMatcher, err = patternmatcher.New(includePatterns)
299 if err != nil {
300 return nil, errors.Wrapf(err, "invalid includepatterns: %s", includePatterns)
301 }
302 }
303
304 var excludePatternMatcher *patternmatcher.PatternMatcher
305 if len(excludePatterns) != 0 {
306 var err error
307 excludePatternMatcher, err = patternmatcher.New(excludePatterns)
308 if err != nil {
309 return nil, errors.Wrapf(err, "invalid excludepatterns: %s", excludePatterns)
310 }
311 }
312
313 return &copier{
314 root: root,
315 inodes: map[uint64]string{},
316 chown: chown,
317 utime: tm,
318 xattrErrorHandler: xeh,
319 mode: mode,
320 modeSet: modeSet,
321 includePatternMatcher: includePatternMatcher,
322 excludePatternMatcher: excludePatternMatcher,
323 changefn: changeFunc,
324 alwaysReplaceExistingDestPaths: alwaysReplaceExistingDestPaths,
325 testHookLstat: nil,
326 }, nil
327 }
328
329 // dest is always clean
330 func (c *copier) copy(ctx context.Context, src, srcComponents, target string, overwriteTargetMetadata bool, parentIncludeMatchInfo, parentExcludeMatchInfo patternmatcher.MatchInfo) error {
331 select {
332 case <-ctx.Done():
333 return ctx.Err()
334 default:
335 }
336
337 // Check exclude patterns BEFORE calling os.Lstat to avoid permission errors
338 // on inaccessible files/directories (e.g., protected Windows system folders)
339 include := true
340 excluded := false
341 var (
342 includeMatchInfo patternmatcher.MatchInfo
343 excludeMatchInfo patternmatcher.MatchInfo
344 )
345 if srcComponents != "" {
346 matchesIncludePattern := false
347 matchesExcludePattern := false
348 var err error
349 matchesIncludePattern, includeMatchInfo, err = c.include(srcComponents, parentIncludeMatchInfo)
350 if err != nil {
351 return err
352 }
353 include = matchesIncludePattern
354
355 matchesExcludePattern, excludeMatchInfo, err = c.exclude(srcComponents, parentExcludeMatchInfo)
356 if err != nil {
357 return err
358 }
359 if matchesExcludePattern {
360 include = false
361 excluded = true
362 }
363
364 // Optimization: Skip os.Lstat() for excluded paths when safe to do so.
365 // We can skip Lstat if:
366 // 1. The path is explicitly excluded
367 // 2. There are no include patterns (no need to check children)
368 // 3. There are no negation patterns in excludes (no exceptions to exclusions)
369 //
370 // This prevents "Access is denied" errors on Windows protected folders
371 // like "System Volume Information" and "WcSandboxState".
372 canSkip := !include && c.includePatternMatcher == nil &&
373 (c.excludePatternMatcher == nil || !c.excludePatternMatcher.Exclusions())
374 if canSkip {
375 return nil
376 }
377 }
378
379 if c.testHookLstat != nil {
380 c.testHookLstat(src)
381 }
382 fi, err := os.Lstat(src)
383 if err != nil {
384 return errors.Wrapf(err, "failed to stat %s", src)
385 }
386
387 // After Lstat, if this item is excluded and is NOT a directory, skip it
388 if !include && !fi.IsDir() {
389 return nil
390 }
391
392 targetFi, err := os.Lstat(target)
393 if err != nil && !os.IsNotExist(err) {
394 return errors.Wrapf(err, "failed to stat %s", target)
395 }
396
397 if include {
398 if err := c.removeTargetIfNeeded(target, fi, targetFi); err != nil {
399 return err
400 }
401
402 if err := c.createParentDirs(src, overwriteTargetMetadata); err != nil {
403 return err
404 }
405 }
406
407 if !fi.IsDir() {
408 if !include {
409 return nil
410 }
411
412 if err := ensureEmptyFileTarget(target); err != nil {
413 return err
414 }
415 }
416
417 copyFileInfo := include
418 restoreFileTimestamp := false
419 notify := true
420
421 switch {
422 case fi.IsDir():
423 if created, err := c.copyDirectory(
424 ctx, src, srcComponents, target, fi, overwriteTargetMetadata,
425 include, excluded, includeMatchInfo, excludeMatchInfo,
426 ); err != nil {
427 return err
428 } else if !overwriteTargetMetadata {
429 // if we aren't supposed to overwrite existing target metadata,
430 // then we only need to copy the new file info if we newly created
431 // it, or restore the previous file timestamp if not
432 copyFileInfo = created
433 restoreFileTimestamp = !created
434 }
435 notify = false
436 case (fi.Mode() & os.ModeType) == 0:
437 link, err := getLinkSource(target, fi, c.inodes)
438 if err != nil {
439 return errors.Wrap(err, "failed to get hardlink")
440 }
441 if link != "" {
442 if err := os.Link(link, target); err != nil {
443 return errors.Wrap(err, "failed to create hard link")
444 }
445 } else if err := copyFile(src, target); err != nil {
446 return errors.Wrap(err, "failed to copy files")
447 }
448 case (fi.Mode() & os.ModeSymlink) == os.ModeSymlink:
449 link, err := os.Readlink(src)
450 if err != nil {
451 return errors.Wrapf(err, "failed to read link: %s", src)
452 }
453 if err := os.Symlink(link, target); err != nil {
454 return errors.Wrapf(err, "failed to create symlink: %s", target)
455 }
456 case (fi.Mode() & os.ModeDevice) == os.ModeDevice,
457 (fi.Mode() & os.ModeNamedPipe) == os.ModeNamedPipe,
458 (fi.Mode() & os.ModeSocket) == os.ModeSocket:
459 if err := copyDevice(target, fi); err != nil {
460 return errors.Wrapf(err, "failed to create device")
461 }
462 }
463
464 if copyFileInfo {
465 if err := c.copyFileInfo(fi, src, target); err != nil {
466 return errors.Wrap(err, "failed to copy file info")
467 }
468
469 if err := copyXAttrs(target, src, c.xattrErrorHandler); err != nil {
470 return errors.Wrap(err, "failed to copy xattrs")
471 }
472 } else if restoreFileTimestamp && targetFi != nil {
473 if err := c.copyFileTimestamp(fi, target); err != nil {
474 return errors.Wrap(err, "failed to restore file timestamp")
475 }
476 }
477 if notify {
478 if err := c.notifyChange(target, fi); err != nil {
479 return err
480 }
481 }
482 return nil
483 }
484
485 func (c *copier) notifyChange(target string, fi os.FileInfo) error {
486 if c.changefn != nil {
487 if err := c.changefn(fsutil.ChangeKindAdd, path.Clean(strings.TrimPrefix(target, c.root)), fi, nil); err != nil {
488 return errors.Wrap(err, "failed to notify file change")
489 }
490 }
491 return nil
492 }
493
494 func (c *copier) include(path string, parentIncludeMatchInfo patternmatcher.MatchInfo) (bool, patternmatcher.MatchInfo, error) {
495 if c.includePatternMatcher == nil {
496 return true, patternmatcher.MatchInfo{}, nil
497 }
498
499 m, matchInfo, err := c.includePatternMatcher.MatchesUsingParentResults(path, parentIncludeMatchInfo)
500 if err != nil {
501 return false, matchInfo, errors.Wrap(err, "failed to match includepatterns")
502 }
503 return m, matchInfo, nil
504 }
505
506 func (c *copier) exclude(path string, parentExcludeMatchInfo patternmatcher.MatchInfo) (bool, patternmatcher.MatchInfo, error) {
507 if c.excludePatternMatcher == nil {
508 return false, patternmatcher.MatchInfo{}, nil
509 }
510
511 m, matchInfo, err := c.excludePatternMatcher.MatchesUsingParentResults(path, parentExcludeMatchInfo)
512 if err != nil {
513 return false, matchInfo, errors.Wrap(err, "failed to match excludepatterns")
514 }
515 return m, matchInfo, nil
516 }
517
518 func (c *copier) removeTargetIfNeeded(target string, srcFi, targetFi os.FileInfo) error {
519 if !c.alwaysReplaceExistingDestPaths {
520 return nil
521 }
522 if targetFi == nil {
523 // already doesn't exist
524 return nil
525 }
526 if srcFi.IsDir() && targetFi.IsDir() {
527 // directories are merged, not replaced
528 return nil
529 }
530 return os.RemoveAll(target)
531 }
532
533 // Delayed creation of parent directories when a file or dir matches an include
534 // pattern.
535 func (c *copier) createParentDirs(src string, overwriteTargetMetadata bool) error {
536 for i, parentDir := range c.parentDirs {
537 if parentDir.copied {
538 continue
539 }
540
541 fi, err := os.Stat(parentDir.srcPath)
542 if err != nil {
543 return errors.Wrapf(err, "failed to stat %s", src)
544 }
545 if !fi.IsDir() {
546 return errors.Errorf("%s is not a directory", parentDir.srcPath)
547 }
548
549 created, err := copyDirectoryOnly(parentDir.dstPath, fi, overwriteTargetMetadata)
550 if err != nil {
551 return err
552 }
553 if created {
554 if err := c.copyFileInfo(fi, parentDir.srcPath, parentDir.dstPath); err != nil {
555 return errors.Wrap(err, "failed to copy file info")
556 }
557
558 if err := copyXAttrs(parentDir.dstPath, parentDir.srcPath, c.xattrErrorHandler); err != nil {
559 return errors.Wrap(err, "failed to copy xattrs")
560 }
561 }
562
563 c.parentDirs[i].copied = true
564 }
565 return nil
566 }
567
568 func (c *copier) copyDirectory(
569 ctx context.Context,
570 src string,
571 srcComponents string,
572 dst string,
573 stat os.FileInfo,
574 overwriteTargetMetadata bool,
575 include bool,
576 excluded bool,
577 includeMatchInfo patternmatcher.MatchInfo,
578 excludeMatchInfo patternmatcher.MatchInfo,
579 ) (bool, error) {
580 if !stat.IsDir() {
581 return false, errors.Errorf("source is not directory")
582 }
583
584 created := false
585
586 parentDir := parentDir{
587 srcPath: src,
588 dstPath: dst,
589 }
590
591 // If this directory passed include/exclude matching directly, go ahead
592 // and create the directory. Otherwise, delay to handle include
593 // patterns like a/*/c where we do not want to create a/b until we
594 // encounter a/b/c.
595 if include {
596 var err error
597 created, err = copyDirectoryOnly(dst, stat, overwriteTargetMetadata)
598 if err != nil {
599 return created, err
600 }
601 if created || overwriteTargetMetadata {
602 if err := c.notifyChange(dst, stat); err != nil {
603 return created, err
604 }
605 }
606 parentDir.copied = true
607 }
608
609 c.parentDirs = append(c.parentDirs, parentDir)
610
611 defer func() {
612 c.parentDirs = c.parentDirs[:len(c.parentDirs)-1]
613 }()
614
615 // Skip reading directory contents if explicitly excluded AND no negation patterns exist.
616 // If negation patterns exist (e.g., "!bar/baz"), we must traverse excluded directories
617 // to find children that might be un-excluded by the negation.
618 if excluded && (c.excludePatternMatcher == nil || !c.excludePatternMatcher.Exclusions()) {
619 return false, nil
620 }
621
622 fis, err := os.ReadDir(src)
623 if err != nil {
624 return false, errors.Wrapf(err, "failed to read %s", src)
625 }
626
627 for _, fi := range fis {
628 if err := c.copy(
629 ctx,
630 filepath.Join(src, fi.Name()), filepath.Join(srcComponents, fi.Name()),
631 filepath.Join(dst, fi.Name()),
632 true, includeMatchInfo, excludeMatchInfo,
633 ); err != nil {
634 return false, err
635 }
636 }
637
638 return created, nil
639 }
640
641 func copyDirectoryOnly(dst string, stat os.FileInfo, overwriteTargetMetadata bool) (bool, error) {
642 if st, err := os.Lstat(dst); err != nil {
643 if !os.IsNotExist(err) {
644 return false, err
645 }
646 if err := os.Mkdir(dst, stat.Mode()); err != nil {
647 return false, errors.Wrapf(err, "failed to mkdir %s", dst)
648 }
649 return true, nil
650 } else if !st.IsDir() {
651 return false, errors.Errorf("cannot copy to non-directory: %s", dst)
652 } else if overwriteTargetMetadata {
653 if err := os.Chmod(dst, stat.Mode()); err != nil {
654 return false, errors.Wrapf(err, "failed to chmod on %s", dst)
655 }
656 }
657 return false, nil
658 }
659
660 func ensureEmptyFileTarget(dst string) error {
661 fi, err := os.Lstat(dst)
662 if err != nil {
663 if os.IsNotExist(err) {
664 return nil
665 }
666 return errors.Wrap(err, "failed to lstat file target")
667 }
668 if fi.IsDir() {
669 return errors.Errorf("cannot replace to directory %s with file", dst)
670 }
671 return os.Remove(dst)
672 }
673
674 func containsWildcards(name string) bool {
675 isWindows := runtime.GOOS == "windows"
676 for i := 0; i < len(name); i++ {
677 ch := name[i]
678 if ch == '\\' && !isWindows {
679 i++
680 } else if ch == '*' || ch == '?' || ch == '[' {
681 return true
682 }
683 }
684 return false
685 }
686
687 func splitWildcards(p string) (d1, d2 string) {
688 parts := strings.Split(filepath.Join(p), string(filepath.Separator))
689 var p1, p2 []string
690 var found bool
691 for _, p := range parts {
692 if !found && containsWildcards(p) {
693 found = true
694 }
695 if p == "" {
696 p = "/"
697 }
698 if !found {
699 p1 = append(p1, p)
700 } else {
701 p2 = append(p2, p)
702 }
703 }
704 return filepath.Join(p1...), filepath.Join(p2...)
705 }
706
707 func resolveWildcards(basePath, comp string) ([]string, error) {
708 var out []string
709 err := filepath.Walk(basePath, func(path string, info os.FileInfo, err error) error {
710 if err != nil {
711 return err
712 }
713 rel, err := rel(basePath, path)
714 if err != nil {
715 return err
716 }
717 if rel == "." {
718 return nil
719 }
720 if match, _ := filepath.Match(comp, rel); !match {
721 return nil
722 }
723 out = append(out, path)
724 if info.IsDir() {
725 return filepath.SkipDir
726 }
727 return nil
728 })
729 if err != nil {
730 return nil, err
731 }
732 return out, nil
733 }
734
735 // rel makes a path relative to base path. Same as `filepath.Rel` but can also
736 // handle UUID paths in windows.
737 func rel(basepath, targpath string) (string, error) {
738 // filepath.Rel can't handle UUID paths in windows
739 if runtime.GOOS == "windows" {
740 pfx := basepath + `\`
741 if strings.HasPrefix(targpath, pfx) {
742 p := strings.TrimPrefix(targpath, pfx)
743 if p == "" {
744 p = "."
745 }
746 return p, nil
747 }
748 }
749 return filepath.Rel(basepath, targpath)
750 }
751
752 func fixCreatedParentDirs(dirs []string, tm *time.Time) error {
753 slices.Reverse(dirs)
754 for _, d := range dirs {
755 if tm != nil {
756 if err := Utimes(d, tm); err != nil {
757 return err
758 }
759 }
760 }
761 return nil
762 }