-
Notifications
You must be signed in to change notification settings - Fork 786
/
copier.go
2086 lines (2016 loc) · 72.8 KB
/
copier.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package copier
import (
"archive/tar"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net"
"os"
"os/user"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unicode"
"github.com/containers/image/v5/pkg/compression"
"github.com/containers/storage/pkg/archive"
"github.com/containers/storage/pkg/fileutils"
"github.com/containers/storage/pkg/idtools"
"github.com/containers/storage/pkg/reexec"
"github.com/sirupsen/logrus"
)
const (
copierCommand = "buildah-copier"
maxLoopsFollowed = 64
// See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_06, from archive/tar
cISUID = 0o4000 // Set uid, from archive/tar
cISGID = 0o2000 // Set gid, from archive/tar
cISVTX = 0o1000 // Save text (sticky bit), from archive/tar
// xattrs in the PAXRecords map are namespaced with this prefix
xattrPAXRecordNamespace = "SCHILY.xattr."
)
func init() {
reexec.Register(copierCommand, copierMain)
}
// extendedGlob calls filepath.Glob() on the passed-in patterns. If there is a
// "**" component in the pattern, filepath.Glob() will be called with the "**"
// replaced with all of the subdirectories under that point, and the results
// will be concatenated.
func extendedGlob(pattern string) (matches []string, err error) {
subdirs := func(dir string) []string {
var subdirectories []string
if err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
if rel, err := filepath.Rel(dir, path); err == nil {
subdirectories = append(subdirectories, rel)
}
}
return nil
}); err != nil {
subdirectories = []string{"."}
}
return subdirectories
}
expandPatterns := func(pattern string) []string {
components := []string{}
dir := pattern
file := ""
for dir != "" && dir != string(os.PathSeparator) {
dir, file = filepath.Split(dir)
components = append([]string{file}, components...)
dir = strings.TrimSuffix(dir, string(os.PathSeparator))
}
patterns := []string{string(os.PathSeparator)}
for i := range components {
var nextPatterns []string
if components[i] == "**" {
for _, parent := range patterns {
nextSubdirs := subdirs(parent)
for _, nextSubdir := range nextSubdirs {
nextPatterns = append(nextPatterns, filepath.Join(parent, nextSubdir))
}
}
} else {
for _, parent := range patterns {
nextPattern := filepath.Join(parent, components[i])
nextPatterns = append(nextPatterns, nextPattern)
}
}
patterns = []string{}
seen := map[string]struct{}{}
for _, nextPattern := range nextPatterns {
if _, seen := seen[nextPattern]; seen {
continue
}
patterns = append(patterns, nextPattern)
seen[nextPattern] = struct{}{}
}
}
return patterns
}
patterns := expandPatterns(pattern)
for _, pattern := range patterns {
theseMatches, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
matches = append(matches, theseMatches...)
}
return matches, nil
}
// isArchivePath returns true if the specified path can be read like a (possibly
// compressed) tarball.
func isArchivePath(path string) bool {
f, err := os.Open(path)
if err != nil {
return false
}
defer f.Close()
rc, _, err := compression.AutoDecompress(f)
if err != nil {
return false
}
defer rc.Close()
tr := tar.NewReader(rc)
_, err = tr.Next()
return err == nil
}
// requestType encodes exactly what kind of request this is.
type requestType string
const (
requestEval requestType = "EVAL"
requestStat requestType = "STAT"
requestGet requestType = "GET"
requestPut requestType = "PUT"
requestMkdir requestType = "MKDIR"
requestRemove requestType = "REMOVE"
requestQuit requestType = "QUIT"
)
// Request encodes a single request.
type request struct {
Request requestType
Root string // used by all requests
preservedRoot string
rootPrefix string // used to reconstruct paths being handed back to the caller
Directory string // used by all requests
preservedDirectory string
Globs []string `json:",omitempty"` // used by stat, get
preservedGlobs []string
StatOptions StatOptions `json:",omitempty"`
GetOptions GetOptions `json:",omitempty"`
PutOptions PutOptions `json:",omitempty"`
MkdirOptions MkdirOptions `json:",omitempty"`
RemoveOptions RemoveOptions `json:",omitempty"`
}
func (req *request) Excludes() []string {
switch req.Request {
case requestEval:
return nil
case requestStat:
return req.StatOptions.Excludes
case requestGet:
return req.GetOptions.Excludes
case requestPut:
return nil
case requestMkdir:
return nil
case requestRemove:
return nil
case requestQuit:
return nil
default:
panic(fmt.Sprintf("not an implemented request type: %q", req.Request))
}
}
func (req *request) UIDMap() []idtools.IDMap {
switch req.Request {
case requestEval:
return nil
case requestStat:
return nil
case requestGet:
return req.GetOptions.UIDMap
case requestPut:
return req.PutOptions.UIDMap
case requestMkdir:
return req.MkdirOptions.UIDMap
case requestRemove:
return nil
case requestQuit:
return nil
default:
panic(fmt.Sprintf("not an implemented request type: %q", req.Request))
}
}
func (req *request) GIDMap() []idtools.IDMap {
switch req.Request {
case requestEval:
return nil
case requestStat:
return nil
case requestGet:
return req.GetOptions.GIDMap
case requestPut:
return req.PutOptions.GIDMap
case requestMkdir:
return req.MkdirOptions.GIDMap
case requestRemove:
return nil
case requestQuit:
return nil
default:
panic(fmt.Sprintf("not an implemented request type: %q", req.Request))
}
}
// Response encodes a single response.
type response struct {
Error string `json:",omitempty"`
Stat statResponse `json:",omitempty"`
Eval evalResponse `json:",omitempty"`
Get getResponse `json:",omitempty"`
Put putResponse `json:",omitempty"`
Mkdir mkdirResponse `json:",omitempty"`
Remove removeResponse `json:",omitempty"`
}
// statResponse encodes a response for a single Stat request.
type statResponse struct {
Globs []*StatsForGlob
}
// evalResponse encodes a response for a single Eval request.
type evalResponse struct {
Evaluated string
}
// StatsForGlob encode results for a single glob pattern passed to Stat().
type StatsForGlob struct {
Error string `json:",omitempty"` // error if the Glob pattern was malformed
Glob string // input pattern to which this result corresponds
Globbed []string // a slice of zero or more names that match the glob
Results map[string]*StatForItem // one for each Globbed value if there are any, or for Glob
}
// StatForItem encode results for a single filesystem item, as returned by Stat().
type StatForItem struct {
Error string `json:",omitempty"`
Name string
Size int64 // dereferenced value for symlinks
Mode os.FileMode // dereferenced value for symlinks
ModTime time.Time // dereferenced value for symlinks
IsSymlink bool
IsDir bool // dereferenced value for symlinks
IsRegular bool // dereferenced value for symlinks
IsArchive bool // dereferenced value for symlinks
ImmediateTarget string `json:",omitempty"` // raw link content
}
// getResponse encodes a response for a single Get request.
type getResponse struct{}
// putResponse encodes a response for a single Put request.
type putResponse struct{}
// mkdirResponse encodes a response for a single Mkdir request.
type mkdirResponse struct{}
// removeResponse encodes a response for a single Remove request.
type removeResponse struct{}
// EvalOptions controls parts of Eval()'s behavior.
type EvalOptions struct{}
// Eval evaluates the directory's path, including any intermediate symbolic
// links.
// If root is specified and the current OS supports it, and the calling process
// has the necessary privileges, evaluation is performed in a chrooted context.
// If the directory is specified as an absolute path, it should either be the
// root directory or a subdirectory of the root directory. Otherwise, the
// directory is treated as a path relative to the root directory.
func Eval(root string, directory string, _ EvalOptions) (string, error) {
req := request{
Request: requestEval,
Root: root,
Directory: directory,
}
resp, err := copier(nil, nil, req)
if err != nil {
return "", err
}
if resp.Error != "" {
return "", errors.New(resp.Error)
}
return resp.Eval.Evaluated, nil
}
// StatOptions controls parts of Stat()'s behavior.
type StatOptions struct {
CheckForArchives bool // check for and populate the IsArchive bit in returned values
Excludes []string // contents to pretend don't exist, using the OS-specific path separator
}
// Stat globs the specified pattern in the specified directory and returns its
// results.
// If root and directory are both not specified, the current root directory is
// used, and relative names in the globs list are treated as being relative to
// the current working directory.
// If root is specified and the current OS supports it, and the calling process
// has the necessary privileges, the stat() is performed in a chrooted context.
// If the directory is specified as an absolute path, it should either be the
// root directory or a subdirectory of the root directory. Otherwise, the
// directory is treated as a path relative to the root directory.
// Relative names in the glob list are treated as being relative to the
// directory.
func Stat(root string, directory string, options StatOptions, globs []string) ([]*StatsForGlob, error) {
req := request{
Request: requestStat,
Root: root,
Directory: directory,
Globs: append([]string{}, globs...),
StatOptions: options,
}
resp, err := copier(nil, nil, req)
if err != nil {
return nil, err
}
if resp.Error != "" {
return nil, errors.New(resp.Error)
}
return resp.Stat.Globs, nil
}
// GetOptions controls parts of Get()'s behavior.
type GetOptions struct {
UIDMap, GIDMap []idtools.IDMap // map from hostIDs to containerIDs in the output archive
Excludes []string // contents to pretend don't exist, using the OS-specific path separator
ExpandArchives bool // extract the contents of named items that are archives
ChownDirs *idtools.IDPair // set ownership on directories. no effect on archives being extracted
ChmodDirs *os.FileMode // set permissions on directories. no effect on archives being extracted
ChownFiles *idtools.IDPair // set ownership of files. no effect on archives being extracted
ChmodFiles *os.FileMode // set permissions on files. no effect on archives being extracted
StripSetuidBit bool // strip the setuid bit off of items being copied. no effect on archives being extracted
StripSetgidBit bool // strip the setgid bit off of items being copied. no effect on archives being extracted
StripStickyBit bool // strip the sticky bit off of items being copied. no effect on archives being extracted
StripXattrs bool // don't record extended attributes of items being copied. no effect on archives being extracted
KeepDirectoryNames bool // don't strip the top directory's basename from the paths of items in subdirectories
Rename map[string]string // rename items with the specified names, or under the specified names
NoDerefSymlinks bool // don't follow symlinks when globs match them
IgnoreUnreadable bool // ignore errors reading items, instead of returning an error
NoCrossDevice bool // if a subdirectory is a mountpoint with a different device number, include it but skip its contents
}
// Get produces an archive containing items that match the specified glob
// patterns and writes it to bulkWriter.
// If root and directory are both not specified, the current root directory is
// used, and relative names in the globs list are treated as being relative to
// the current working directory.
// If root is specified and the current OS supports it, and the calling process
// has the necessary privileges, the contents are read in a chrooted context.
// If the directory is specified as an absolute path, it should either be the
// root directory or a subdirectory of the root directory. Otherwise, the
// directory is treated as a path relative to the root directory.
// Relative names in the glob list are treated as being relative to the
// directory.
func Get(root string, directory string, options GetOptions, globs []string, bulkWriter io.Writer) error {
req := request{
Request: requestGet,
Root: root,
Directory: directory,
Globs: append([]string{}, globs...),
StatOptions: StatOptions{
CheckForArchives: options.ExpandArchives,
},
GetOptions: options,
}
resp, err := copier(nil, bulkWriter, req)
if err != nil {
return err
}
if resp.Error != "" {
return errors.New(resp.Error)
}
return nil
}
// PutOptions controls parts of Put()'s behavior.
type PutOptions struct {
UIDMap, GIDMap []idtools.IDMap // map from containerIDs to hostIDs when writing contents to disk
DefaultDirOwner *idtools.IDPair // set ownership of implicitly-created directories, default is ChownDirs, or 0:0 if ChownDirs not set
DefaultDirMode *os.FileMode // set permissions on implicitly-created directories, default is ChmodDirs, or 0755 if ChmodDirs not set
ChownDirs *idtools.IDPair // set ownership of newly-created directories
ChmodDirs *os.FileMode // set permissions on newly-created directories
ChownFiles *idtools.IDPair // set ownership of newly-created files
ChmodFiles *os.FileMode // set permissions on newly-created files
StripSetuidBit bool // strip the setuid bit off of items being written
StripSetgidBit bool // strip the setgid bit off of items being written
StripStickyBit bool // strip the sticky bit off of items being written
StripXattrs bool // don't bother trying to set extended attributes of items being copied
IgnoreXattrErrors bool // ignore any errors encountered when attempting to set extended attributes
IgnoreDevices bool // ignore items which are character or block devices
NoOverwriteDirNonDir bool // instead of quietly overwriting directories with non-directories, return an error
NoOverwriteNonDirDir bool // instead of quietly overwriting non-directories with directories, return an error
Rename map[string]string // rename items with the specified names, or under the specified names
}
// Put extracts an archive from the bulkReader at the specified directory.
// If root and directory are both not specified, the current root directory is
// used.
// If root is specified and the current OS supports it, and the calling process
// has the necessary privileges, the contents are written in a chrooted
// context. If the directory is specified as an absolute path, it should
// either be the root directory or a subdirectory of the root directory.
// Otherwise, the directory is treated as a path relative to the root
// directory.
func Put(root string, directory string, options PutOptions, bulkReader io.Reader) error {
req := request{
Request: requestPut,
Root: root,
Directory: directory,
PutOptions: options,
}
resp, err := copier(bulkReader, nil, req)
if err != nil {
return err
}
if resp.Error != "" {
return errors.New(resp.Error)
}
return nil
}
// MkdirOptions controls parts of Mkdir()'s behavior.
type MkdirOptions struct {
UIDMap, GIDMap []idtools.IDMap // map from containerIDs to hostIDs when creating directories
ChownNew *idtools.IDPair // set ownership of newly-created directories
ChmodNew *os.FileMode // set permissions on newly-created directories
}
// Mkdir ensures that the specified directory exists. Any directories which
// need to be created will be given the specified ownership and permissions.
// If root and directory are both not specified, the current root directory is
// used.
// If root is specified and the current OS supports it, and the calling process
// has the necessary privileges, the directory is created in a chrooted
// context. If the directory is specified as an absolute path, it should
// either be the root directory or a subdirectory of the root directory.
// Otherwise, the directory is treated as a path relative to the root
// directory.
func Mkdir(root string, directory string, options MkdirOptions) error {
req := request{
Request: requestMkdir,
Root: root,
Directory: directory,
MkdirOptions: options,
}
resp, err := copier(nil, nil, req)
if err != nil {
return err
}
if resp.Error != "" {
return errors.New(resp.Error)
}
return nil
}
// RemoveOptions controls parts of Remove()'s behavior.
type RemoveOptions struct {
All bool // if Directory is a directory, remove its contents as well
}
// Remove removes the specified directory or item, traversing any intermediate
// symbolic links.
// If the root directory is not specified, the current root directory is used.
// If root is specified and the current OS supports it, and the calling process
// has the necessary privileges, the remove() is performed in a chrooted context.
// If the item to remove is specified as an absolute path, it should either be
// in the root directory or in a subdirectory of the root directory. Otherwise,
// the directory is treated as a path relative to the root directory.
func Remove(root string, item string, options RemoveOptions) error {
req := request{
Request: requestRemove,
Root: root,
Directory: item,
RemoveOptions: options,
}
resp, err := copier(nil, nil, req)
if err != nil {
return err
}
if resp.Error != "" {
return errors.New(resp.Error)
}
return nil
}
// cleanerReldirectory resolves relative path candidate lexically, attempting
// to ensure that when joined as a subdirectory of another directory, it does
// not reference anything outside of that other directory.
func cleanerReldirectory(candidate string) string {
cleaned := strings.TrimPrefix(filepath.Clean(string(os.PathSeparator)+candidate), string(os.PathSeparator))
if cleaned == "" {
return "."
}
return cleaned
}
// convertToRelSubdirectory returns the path of directory, bound and relative to
// root, as a relative path, or an error if that path can't be computed or if
// the two directories are on different volumes
func convertToRelSubdirectory(root, directory string) (relative string, err error) {
if root == "" || !filepath.IsAbs(root) {
return "", fmt.Errorf("expected root directory to be an absolute path, got %q", root)
}
if directory == "" || !filepath.IsAbs(directory) {
return "", fmt.Errorf("expected directory to be an absolute path, got %q", root)
}
if filepath.VolumeName(root) != filepath.VolumeName(directory) {
return "", fmt.Errorf("%q and %q are on different volumes", root, directory)
}
rel, err := filepath.Rel(root, directory)
if err != nil {
return "", fmt.Errorf("computing path of %q relative to %q: %w", directory, root, err)
}
return cleanerReldirectory(rel), nil
}
func currentVolumeRoot() (string, error) {
cwd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("getting current working directory: %w", err)
}
return filepath.VolumeName(cwd) + string(os.PathSeparator), nil
}
func isVolumeRoot(candidate string) (bool, error) {
abs, err := filepath.Abs(candidate)
if err != nil {
return false, fmt.Errorf("converting %q to an absolute path: %w", candidate, err)
}
return abs == filepath.VolumeName(abs)+string(os.PathSeparator), nil
}
func looksLikeAbs(candidate string) bool {
return candidate[0] == os.PathSeparator && (len(candidate) == 1 || candidate[1] != os.PathSeparator)
}
func copier(bulkReader io.Reader, bulkWriter io.Writer, req request) (*response, error) {
if req.Directory == "" {
if req.Root == "" {
wd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("getting current working directory: %w", err)
}
req.Directory = wd
} else {
req.Directory = req.Root
}
}
if req.Root == "" {
root, err := currentVolumeRoot()
if err != nil {
return nil, fmt.Errorf("determining root of current volume: %w", err)
}
req.Root = root
}
if filepath.IsAbs(req.Directory) {
_, err := convertToRelSubdirectory(req.Root, req.Directory)
if err != nil {
return nil, fmt.Errorf("rewriting %q to be relative to %q: %w", req.Directory, req.Root, err)
}
}
isAlreadyRoot, err := isVolumeRoot(req.Root)
if err != nil {
return nil, fmt.Errorf("checking if %q is a root directory: %w", req.Root, err)
}
if !isAlreadyRoot && canChroot {
return copierWithSubprocess(bulkReader, bulkWriter, req)
}
return copierWithoutSubprocess(bulkReader, bulkWriter, req)
}
func copierWithoutSubprocess(bulkReader io.Reader, bulkWriter io.Writer, req request) (*response, error) {
req.preservedRoot = req.Root
req.rootPrefix = string(os.PathSeparator)
req.preservedDirectory = req.Directory
req.preservedGlobs = append([]string{}, req.Globs...)
if !filepath.IsAbs(req.Directory) {
req.Directory = filepath.Join(req.Root, cleanerReldirectory(req.Directory))
}
absoluteGlobs := make([]string, 0, len(req.Globs))
for _, glob := range req.preservedGlobs {
if filepath.IsAbs(glob) {
relativeGlob, err := convertToRelSubdirectory(req.preservedRoot, glob)
if err != nil {
fmt.Fprintf(os.Stderr, "error rewriting %q to be relative to %q: %v", glob, req.preservedRoot, err)
os.Exit(1)
}
absoluteGlobs = append(absoluteGlobs, filepath.Join(req.Root, string(os.PathSeparator)+relativeGlob))
} else {
absoluteGlobs = append(absoluteGlobs, filepath.Join(req.Directory, cleanerReldirectory(glob)))
}
}
req.Globs = absoluteGlobs
resp, cb, err := copierHandler(bulkReader, bulkWriter, req)
if err != nil {
return nil, err
}
if cb != nil {
if err = cb(); err != nil {
return nil, err
}
}
return resp, nil
}
func closeIfNotNilYet(f **os.File, what string) {
if f != nil && *f != nil {
err := (*f).Close()
*f = nil
if err != nil {
logrus.Debugf("error closing %s: %v", what, err)
}
}
}
func copierWithSubprocess(bulkReader io.Reader, bulkWriter io.Writer, req request) (resp *response, err error) {
if bulkReader == nil {
bulkReader = bytes.NewReader([]byte{})
}
if bulkWriter == nil {
bulkWriter = io.Discard
}
cmd := reexec.Command(copierCommand)
stdinRead, stdinWrite, err := os.Pipe()
if err != nil {
return nil, fmt.Errorf("pipe: %w", err)
}
defer closeIfNotNilYet(&stdinRead, "stdin pipe reader")
defer closeIfNotNilYet(&stdinWrite, "stdin pipe writer")
encoder := json.NewEncoder(stdinWrite)
stdoutRead, stdoutWrite, err := os.Pipe()
if err != nil {
return nil, fmt.Errorf("pipe: %w", err)
}
defer closeIfNotNilYet(&stdoutRead, "stdout pipe reader")
defer closeIfNotNilYet(&stdoutWrite, "stdout pipe writer")
decoder := json.NewDecoder(stdoutRead)
bulkReaderRead, bulkReaderWrite, err := os.Pipe()
if err != nil {
return nil, fmt.Errorf("pipe: %w", err)
}
defer closeIfNotNilYet(&bulkReaderRead, "child bulk content reader pipe, read end")
defer closeIfNotNilYet(&bulkReaderWrite, "child bulk content reader pipe, write end")
bulkWriterRead, bulkWriterWrite, err := os.Pipe()
if err != nil {
return nil, fmt.Errorf("pipe: %w", err)
}
defer closeIfNotNilYet(&bulkWriterRead, "child bulk content writer pipe, read end")
defer closeIfNotNilYet(&bulkWriterWrite, "child bulk content writer pipe, write end")
cmd.Dir = "/"
cmd.Env = append([]string{fmt.Sprintf("LOGLEVEL=%d", logrus.GetLevel())}, os.Environ()...)
errorBuffer := bytes.Buffer{}
cmd.Stdin = stdinRead
cmd.Stdout = stdoutWrite
cmd.Stderr = &errorBuffer
cmd.ExtraFiles = []*os.File{bulkReaderRead, bulkWriterWrite}
if err = cmd.Start(); err != nil {
return nil, fmt.Errorf("starting subprocess: %w", err)
}
cmdToWaitFor := cmd
defer func() {
if cmdToWaitFor != nil {
if err := cmdToWaitFor.Wait(); err != nil {
if errorBuffer.String() != "" {
logrus.Debug(errorBuffer.String())
}
}
}
}()
stdinRead.Close()
stdinRead = nil
stdoutWrite.Close()
stdoutWrite = nil
bulkReaderRead.Close()
bulkReaderRead = nil
bulkWriterWrite.Close()
bulkWriterWrite = nil
killAndReturn := func(err error, step string) (*response, error) { // nolint: unparam
if err2 := cmd.Process.Kill(); err2 != nil {
return nil, fmt.Errorf("killing subprocess: %v; %s: %w", err2, step, err)
}
if errors.Is(err, io.ErrClosedPipe) || errors.Is(err, syscall.EPIPE) {
err2 := cmd.Wait()
if errorText := strings.TrimFunc(errorBuffer.String(), unicode.IsSpace); errorText != "" {
err = fmt.Errorf("%s: %w", errorText, err)
}
if err2 != nil {
return nil, fmt.Errorf("waiting on subprocess: %v; %s: %w", err2, step, err)
}
}
return nil, fmt.Errorf("%v: %w", step, err)
}
if err = encoder.Encode(req); err != nil {
return killAndReturn(err, "error encoding work request for copier subprocess")
}
if err = decoder.Decode(&resp); err != nil {
if errors.Is(err, io.EOF) && errorBuffer.Len() > 0 {
return killAndReturn(errors.New(errorBuffer.String()), "error in copier subprocess")
}
return killAndReturn(err, "error decoding response from copier subprocess")
}
if err = encoder.Encode(&request{Request: requestQuit}); err != nil {
return killAndReturn(err, "error encoding quit request for copier subprocess")
}
stdinWrite.Close()
stdinWrite = nil
stdoutRead.Close()
stdoutRead = nil
var wg sync.WaitGroup
var readError, writeError error
wg.Add(1)
go func() {
_, writeError = io.Copy(bulkWriter, bulkWriterRead)
bulkWriterRead.Close()
bulkWriterRead = nil
wg.Done()
}()
wg.Add(1)
go func() {
_, readError = io.Copy(bulkReaderWrite, bulkReader)
bulkReaderWrite.Close()
bulkReaderWrite = nil
wg.Done()
}()
wg.Wait()
cmdToWaitFor = nil
if err = cmd.Wait(); err != nil {
if errorBuffer.String() != "" {
err = fmt.Errorf("%s", errorBuffer.String())
}
return nil, err
}
if cmd.ProcessState.Exited() && !cmd.ProcessState.Success() {
err = fmt.Errorf("subprocess exited with error")
if errorBuffer.String() != "" {
err = fmt.Errorf("%s", errorBuffer.String())
}
return nil, err
}
loggedOutput := strings.TrimSuffix(errorBuffer.String(), "\n")
if len(loggedOutput) > 0 {
for _, output := range strings.Split(loggedOutput, "\n") {
logrus.Debug(output)
}
}
if readError != nil {
return nil, fmt.Errorf("passing bulk input to subprocess: %w", readError)
}
if writeError != nil {
return nil, fmt.Errorf("passing bulk output from subprocess: %w", writeError)
}
return resp, nil
}
func copierMain() {
var chrooted bool
decoder := json.NewDecoder(os.Stdin)
encoder := json.NewEncoder(os.Stdout)
previousRequestRoot := ""
// Attempt a user and host lookup to force libc (glibc, and possibly others that use dynamic
// modules to handle looking up user and host information) to load modules that match the libc
// our binary is currently using. Hopefully they're loaded on first use, so that they won't
// need to be loaded after we've chrooted into the rootfs, which could include modules that
// don't match our libc and which can't be loaded, or modules which we don't want to execute
// because we don't trust their code.
_, _ = user.Lookup("buildah")
_, _ = net.LookupHost("localhost")
// Set logging.
if level := os.Getenv("LOGLEVEL"); level != "" {
if ll, err := strconv.Atoi(level); err == nil {
logrus.SetLevel(logrus.Level(ll))
}
}
// Set up descriptors for receiving and sending tarstreams.
bulkReader := os.NewFile(3, "bulk-reader")
bulkWriter := os.NewFile(4, "bulk-writer")
for {
// Read a request.
req := new(request)
if err := decoder.Decode(req); err != nil {
fmt.Fprintf(os.Stderr, "error decoding request from copier parent process: %v", err)
os.Exit(1)
}
if req.Request == requestQuit {
// Making Quit a specific request means that we could
// run Stat() at a caller's behest before using the
// same process for Get() or Put(). Maybe later.
break
}
// Multiple requests should list the same root, because we
// can't un-chroot to chroot to some other location.
if previousRequestRoot != "" {
// Check that we got the same input value for
// where-to-chroot-to.
if req.Root != previousRequestRoot {
fmt.Fprintf(os.Stderr, "error: can't change location of chroot from %q to %q", previousRequestRoot, req.Root)
os.Exit(1)
}
previousRequestRoot = req.Root
} else {
// Figure out where to chroot to, if we weren't told.
if req.Root == "" {
root, err := currentVolumeRoot()
if err != nil {
fmt.Fprintf(os.Stderr, "error determining root of current volume: %v", err)
os.Exit(1)
}
req.Root = root
}
// Change to the specified root directory.
var err error
chrooted, err = chroot(req.Root)
if err != nil {
fmt.Fprintf(os.Stderr, "%v", err)
os.Exit(1)
}
}
req.preservedRoot = req.Root
req.rootPrefix = string(os.PathSeparator)
req.preservedDirectory = req.Directory
req.preservedGlobs = append([]string{}, req.Globs...)
if chrooted {
// We'll need to adjust some things now that the root
// directory isn't what it was. Make the directory and
// globs absolute paths for simplicity's sake.
absoluteDirectory := req.Directory
if !filepath.IsAbs(req.Directory) {
absoluteDirectory = filepath.Join(req.Root, cleanerReldirectory(req.Directory))
}
relativeDirectory, err := convertToRelSubdirectory(req.preservedRoot, absoluteDirectory)
if err != nil {
fmt.Fprintf(os.Stderr, "error rewriting %q to be relative to %q: %v", absoluteDirectory, req.preservedRoot, err)
os.Exit(1)
}
req.Directory = filepath.Clean(string(os.PathSeparator) + relativeDirectory)
absoluteGlobs := make([]string, 0, len(req.Globs))
for i, glob := range req.preservedGlobs {
if filepath.IsAbs(glob) {
relativeGlob, err := convertToRelSubdirectory(req.preservedRoot, glob)
if err != nil {
fmt.Fprintf(os.Stderr, "error rewriting %q to be relative to %q: %v", glob, req.preservedRoot, err)
os.Exit(1)
}
absoluteGlobs = append(absoluteGlobs, filepath.Clean(string(os.PathSeparator)+relativeGlob))
} else {
absoluteGlobs = append(absoluteGlobs, filepath.Join(req.Directory, cleanerReldirectory(req.Globs[i])))
}
}
req.Globs = absoluteGlobs
req.rootPrefix = req.Root
req.Root = string(os.PathSeparator)
} else {
// Make the directory and globs absolute paths for
// simplicity's sake.
if !filepath.IsAbs(req.Directory) {
req.Directory = filepath.Join(req.Root, cleanerReldirectory(req.Directory))
}
absoluteGlobs := make([]string, 0, len(req.Globs))
for i, glob := range req.preservedGlobs {
if filepath.IsAbs(glob) {
absoluteGlobs = append(absoluteGlobs, req.Globs[i])
} else {
absoluteGlobs = append(absoluteGlobs, filepath.Join(req.Directory, cleanerReldirectory(req.Globs[i])))
}
}
req.Globs = absoluteGlobs
}
resp, cb, err := copierHandler(bulkReader, bulkWriter, *req)
if err != nil {
fmt.Fprintf(os.Stderr, "error handling request %#v from copier parent process: %v", *req, err)
os.Exit(1)
}
// Encode the response.
if err := encoder.Encode(resp); err != nil {
fmt.Fprintf(os.Stderr, "error encoding response %#v for copier parent process: %v", *req, err)
os.Exit(1)
}
// If there's bulk data to transfer, run the callback to either
// read or write it.
if cb != nil {
if err = cb(); err != nil {
fmt.Fprintf(os.Stderr, "error during bulk transfer for %#v: %v", *req, err)
os.Exit(1)
}
}
}
}
func copierHandler(bulkReader io.Reader, bulkWriter io.Writer, req request) (*response, func() error, error) {
// NewPatternMatcher splits patterns into components using
// os.PathSeparator, implying that it expects OS-specific naming
// conventions.
excludes := req.Excludes()
pm, err := fileutils.NewPatternMatcher(excludes)
if err != nil {
return nil, nil, fmt.Errorf("processing excludes list %v: %w", excludes, err)
}
var idMappings *idtools.IDMappings
uidMap, gidMap := req.UIDMap(), req.GIDMap()
if len(uidMap) > 0 && len(gidMap) > 0 {
idMappings = idtools.NewIDMappingsFromMaps(uidMap, gidMap)
}
switch req.Request {
default:
return nil, nil, fmt.Errorf("not an implemented request type: %q", req.Request)
case requestEval:
resp := copierHandlerEval(req)
return resp, nil, nil
case requestStat:
resp := copierHandlerStat(req, pm)
return resp, nil, nil
case requestGet:
return copierHandlerGet(bulkWriter, req, pm, idMappings)
case requestPut:
return copierHandlerPut(bulkReader, req, idMappings)
case requestMkdir:
return copierHandlerMkdir(req, idMappings)
case requestRemove:
resp := copierHandlerRemove(req)
return resp, nil, nil
case requestQuit:
return nil, nil, nil
}
}
// pathIsExcluded computes path relative to root, then asks the pattern matcher
// if the result is excluded. Returns the relative path and the matcher's
// results.
func pathIsExcluded(root, path string, pm *fileutils.PatternMatcher) (string, bool, error) {
rel, err := convertToRelSubdirectory(root, path)
if err != nil {
return "", false, fmt.Errorf("copier: error computing path of %q relative to root %q: %w", path, root, err)
}
if pm == nil {
return rel, false, nil
}
if rel == "." {
// special case
return rel, false, nil
}
// Matches uses filepath.FromSlash() to convert candidates before
// checking if they match the patterns it's been given, implying that
// it expects Unix-style paths.
matches, err := pm.Matches(filepath.ToSlash(rel)) // nolint:staticcheck
if err != nil {
return rel, false, fmt.Errorf("copier: error checking if %q is excluded: %w", rel, err)
}
if matches {
return rel, true, nil
}
return rel, false, nil
}
// resolvePath resolves symbolic links in paths, treating the specified
// directory as the root.
// Resolving the path this way, and using the result, is in no way secure
// against another process manipulating the content that we're looking at, and
// it is not expected to be.
// This helps us approximate chrooted behavior on systems and in test cases
// where chroot isn't available.
func resolvePath(root, path string, evaluateFinalComponent bool, pm *fileutils.PatternMatcher) (string, error) {
rel, err := convertToRelSubdirectory(root, path)
if err != nil {
return "", fmt.Errorf("making path %q relative to %q", path, root)
}
workingPath := root
followed := 0
components := strings.Split(rel, string(os.PathSeparator))
excluded := false
for len(components) > 0 {