-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
utils.go
1358 lines (1250 loc) · 40.9 KB
/
utils.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 util
import (
"errors"
"fmt"
"io/fs"
"math"
"math/bits"
"os"
"os/user"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/BurntSushi/toml"
"github.com/containers/common/pkg/config"
"github.com/containers/image/v5/types"
"github.com/containers/podman/v5/libpod/define"
"github.com/containers/podman/v5/pkg/errorhandling"
"github.com/containers/podman/v5/pkg/namespaces"
"github.com/containers/podman/v5/pkg/rootless"
"github.com/containers/podman/v5/pkg/signal"
"github.com/containers/storage/pkg/directory"
"github.com/containers/storage/pkg/idtools"
stypes "github.com/containers/storage/types"
securejoin "github.com/cyphar/filepath-securejoin"
ruser "github.com/moby/sys/user"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"golang.org/x/term"
)
// The flags that an [ug]id mapping can have
type idMapFlags struct {
Extends bool // The "+" flag
UserMap bool // The "u" flag
GroupMap bool // The "g" flag
}
var containerConfig *config.Config
func init() {
var err error
containerConfig, err = config.Default()
if err != nil {
logrus.Error(err)
os.Exit(1)
}
}
// Helper function to determine the username/password passed
// in the creds string. It could be either or both.
func parseCreds(creds string) (string, string) {
username, password, _ := strings.Cut(creds, ":")
return username, password
}
// Takes build context and validates `.containerignore` or `.dockerignore`
// if they are symlink outside of buildcontext. Returns list of files to be
// excluded and resolved path to the ignore files inside build context or error
func ParseDockerignore(containerfiles []string, root string) ([]string, string, error) {
ignoreFile := ""
path, err := securejoin.SecureJoin(root, ".containerignore")
if err != nil {
return nil, ignoreFile, err
}
// set resolved ignore file so imagebuildah
// does not attempts to re-resolve it
ignoreFile = path
ignore, err := os.ReadFile(path)
if err != nil {
var dockerIgnoreErr error
path, symlinkErr := securejoin.SecureJoin(root, ".dockerignore")
if symlinkErr != nil {
return nil, ignoreFile, symlinkErr
}
// set resolved ignore file so imagebuildah
// does not attempts to re-resolve it
ignoreFile = path
ignore, dockerIgnoreErr = os.ReadFile(path)
if os.IsNotExist(dockerIgnoreErr) {
// In this case either ignorefile was not found
// or it is a symlink to unexpected file in such
// case manually set ignorefile to `/dev/null` so
// internally imagebuildah does not attempts to re-resolve
// this invalid symlink and instead reads a blank file.
ignoreFile = "/dev/null"
}
// after https://github.com/containers/buildah/pull/4239 build supports
// <Containerfile>.containerignore or <Containerfile>.dockerignore as ignore file
// so remote must support parsing that.
if dockerIgnoreErr != nil {
for _, containerfile := range containerfiles {
containerfile = strings.TrimPrefix(containerfile, root)
if _, err := os.Stat(filepath.Join(root, containerfile+".containerignore")); err == nil {
path, symlinkErr = securejoin.SecureJoin(root, containerfile+".containerignore")
if symlinkErr == nil {
ignoreFile = path
ignore, dockerIgnoreErr = os.ReadFile(path)
}
}
if _, err := os.Stat(filepath.Join(root, containerfile+".dockerignore")); err == nil {
path, symlinkErr = securejoin.SecureJoin(root, containerfile+".dockerignore")
if symlinkErr == nil {
ignoreFile = path
ignore, dockerIgnoreErr = os.ReadFile(path)
}
}
if dockerIgnoreErr == nil {
break
}
}
}
if dockerIgnoreErr != nil && !os.IsNotExist(dockerIgnoreErr) {
return nil, ignoreFile, err
}
}
rawexcludes := strings.Split(string(ignore), "\n")
excludes := make([]string, 0, len(rawexcludes))
for _, e := range rawexcludes {
if len(e) == 0 || e[0] == '#' {
continue
}
excludes = append(excludes, e)
}
return excludes, ignoreFile, nil
}
// ParseRegistryCreds takes a credentials string in the form USERNAME:PASSWORD
// and returns a DockerAuthConfig
func ParseRegistryCreds(creds string) (*types.DockerAuthConfig, error) {
username, password := parseCreds(creds)
if username == "" {
fmt.Print("Username: ")
fmt.Scanln(&username)
}
if password == "" {
fmt.Print("Password: ")
termPassword, err := term.ReadPassword(0)
if err != nil {
return nil, fmt.Errorf("could not read password from terminal: %w", err)
}
password = string(termPassword)
}
return &types.DockerAuthConfig{
Username: username,
Password: password,
}, nil
}
// StringMatchRegexSlice determines if a given string matches one of the given regexes, returns bool
func StringMatchRegexSlice(s string, re []string) bool {
for _, r := range re {
m, err := regexp.MatchString(r, s)
if err == nil && m {
return true
}
}
return false
}
// ParseSignal parses and validates a signal name or number.
func ParseSignal(rawSignal string) (syscall.Signal, error) {
// Strip off leading dash, to allow -1 or -HUP
basename := strings.TrimPrefix(rawSignal, "-")
sig, err := signal.ParseSignal(basename)
if err != nil {
return -1, err
}
// 64 is SIGRTMAX; wish we could get this from a standard Go library
if sig < 1 || sig > 64 {
return -1, errors.New("valid signals are 1 through 64")
}
return sig, nil
}
// GetKeepIDMapping returns the mappings and the user to use when keep-id is used
func GetKeepIDMapping(opts *namespaces.KeepIDUserNsOptions) (*stypes.IDMappingOptions, int, int, error) {
options := stypes.IDMappingOptions{
HostUIDMapping: false,
HostGIDMapping: false,
}
if !rootless.IsRootless() {
uids, err := rootless.ReadMappingsProc("/proc/self/uid_map")
if err != nil {
return nil, 0, 0, err
}
gids, err := rootless.ReadMappingsProc("/proc/self/gid_map")
if err != nil {
return nil, 0, 0, err
}
options.UIDMap = uids
options.GIDMap = gids
uid, gid := 0, 0
if opts.UID != nil {
uid = int(*opts.UID)
}
if opts.GID != nil {
gid = int(*opts.GID)
}
return &options, uid, gid, nil
}
uid := rootless.GetRootlessUID()
gid := rootless.GetRootlessGID()
if opts.UID != nil {
uid = int(*opts.UID)
}
if opts.GID != nil {
gid = int(*opts.GID)
}
uids, gids, err := rootless.GetConfiguredMappings(true)
if err != nil {
return nil, -1, -1, fmt.Errorf("cannot read mappings: %w", err)
}
maxUID, maxGID := 0, 0
for _, u := range uids {
maxUID += u.Size
}
for _, g := range gids {
maxGID += g.Size
}
options.UIDMap, options.GIDMap = nil, nil
if len(uids) > 0 {
options.UIDMap = append(options.UIDMap, idtools.IDMap{ContainerID: 0, HostID: 1, Size: min(uid, maxUID)})
}
options.UIDMap = append(options.UIDMap, idtools.IDMap{ContainerID: uid, HostID: 0, Size: 1})
if maxUID > uid {
options.UIDMap = append(options.UIDMap, idtools.IDMap{ContainerID: uid + 1, HostID: uid + 1, Size: maxUID - uid})
}
if len(gids) > 0 {
options.GIDMap = append(options.GIDMap, idtools.IDMap{ContainerID: 0, HostID: 1, Size: min(gid, maxGID)})
}
options.GIDMap = append(options.GIDMap, idtools.IDMap{ContainerID: gid, HostID: 0, Size: 1})
if maxGID > gid {
options.GIDMap = append(options.GIDMap, idtools.IDMap{ContainerID: gid + 1, HostID: gid + 1, Size: maxGID - gid})
}
return &options, uid, gid, nil
}
// GetNoMapMapping returns the mappings and the user to use when nomap is used
func GetNoMapMapping() (*stypes.IDMappingOptions, int, int, error) {
if !rootless.IsRootless() {
return nil, -1, -1, errors.New("nomap is only supported in rootless mode")
}
options := stypes.IDMappingOptions{
HostUIDMapping: false,
HostGIDMapping: false,
}
uids, gids, err := rootless.GetConfiguredMappings(false)
if err != nil {
return nil, -1, -1, fmt.Errorf("cannot read mappings: %w", err)
}
if len(uids) == 0 || len(gids) == 0 {
return nil, -1, -1, fmt.Errorf("nomap requires additional UIDs or GIDs defined in /etc/subuid and /etc/subgid to function correctly: %w", err)
}
options.UIDMap, options.GIDMap = nil, nil
uid, gid := 0, 0
for _, u := range uids {
options.UIDMap = append(options.UIDMap, idtools.IDMap{ContainerID: uid, HostID: uid + 1, Size: u.Size})
uid += u.Size
}
for _, g := range gids {
options.GIDMap = append(options.GIDMap, idtools.IDMap{ContainerID: gid, HostID: gid + 1, Size: g.Size})
gid += g.Size
}
return &options, 0, 0, nil
}
// Map a given ID to the Parent/Host ID of a given mapping, and return
// its corresponding ID/ContainerID.
// Returns an error if the given ID is not found on the mapping parents
func mapIDwithMapping(id uint64, mapping []ruser.IDMap, mapSetting string) (mappedid uint64, err error) {
for _, v := range mapping {
if v.Count == 0 {
continue
}
if id >= uint64(v.ParentID) && id < uint64(v.ParentID+v.Count) {
offset := id - uint64(v.ParentID)
return uint64(v.ID) + offset, nil
}
}
return uint64(0), fmt.Errorf("parent ID %s %d is not mapped/delegated", mapSetting, id)
}
// Parse flags from spec
// The `u` and `g` flags can be used to enforce that the mapping applies
// exclusively to UIDs or GIDs.
//
// The `+` flag is interpreted as if the mapping replaces previous mappings
// removing any conflicting mapping from those before adding this one.
func parseFlags(spec []string) (flags idMapFlags, read int, err error) {
flags.Extends = false
flags.UserMap = false
flags.GroupMap = false
for read, char := range spec[0] {
switch {
case '0' <= char && char <= '9':
return flags, read, nil
case char == '+':
flags.Extends = true
case char == 'u':
flags.UserMap = true
case char == 'g':
flags.GroupMap = true
case true:
return flags, 0, fmt.Errorf("invalid mapping: %v. Unknown flag %v", spec, char)
}
}
return flags, read, fmt.Errorf("invalid mapping: %v, parsing flags", spec)
}
// Extension of idTools.parseTriple that parses idmap triples.
// The triple should be a length 3 string array, containing:
// - Flags and ContainerID
// - HostID
// - Size
//
// parseTriple returns the parsed mapping, the mapping flags and
// any possible error. If the error is not-nil, the mapping and flags
// are not well-defined.
//
// idTools.parseTriple is extended here with the following enhancements:
//
// HostID @ syntax:
// =================
// HostID may use the "@" syntax: The "101001:@1001:1" mapping
// means "take the 1001 id from the parent namespace and map it to 101001"
//
// Flags:
// ======
// Flags can be used to tell the caller how should the mapping be interpreted
func parseTriple(spec []string, parentMapping []ruser.IDMap, mapSetting string) (mappings []idtools.IDMap, flags idMapFlags, err error) {
if len(spec[0]) == 0 {
return mappings, flags, fmt.Errorf("invalid empty container id at %s map: %v", mapSetting, spec)
}
var cids, hids, sizes []uint64
var cid, hid uint64
var hidIsParent bool
flags, i, err := parseFlags(spec)
if err != nil {
return mappings, flags, err
}
// If no "u" nor "g" flag is given, assume the mapping applies to both
if !flags.UserMap && !flags.GroupMap {
flags.UserMap = true
flags.GroupMap = true
}
// Parse the container ID, which must be an integer:
cid, err = strconv.ParseUint(spec[0][i:], 10, 32)
if err != nil {
return mappings, flags, fmt.Errorf("parsing id map value %q: %w", spec[0], err)
}
// Parse the host id, which may be integer or @<integer>
if len(spec[1]) == 0 {
return mappings, flags, fmt.Errorf("invalid empty host id at %s map: %v", mapSetting, spec)
}
if spec[1][0] != '@' {
hidIsParent = false
hid, err = strconv.ParseUint(spec[1], 10, 32)
} else {
// Parse @<id>, where <id> is an integer corresponding to the parent mapping
hidIsParent = true
hid, err = strconv.ParseUint(spec[1][1:], 10, 32)
}
if err != nil {
return mappings, flags, fmt.Errorf("parsing id map value %q: %w", spec[1], err)
}
// Parse the size of the mapping, which must be an integer
sz, err := strconv.ParseUint(spec[2], 10, 32)
if err != nil {
return mappings, flags, fmt.Errorf("parsing id map value %q: %w", spec[2], err)
}
if hidIsParent {
if (mapSetting == "UID" && flags.UserMap) || (mapSetting == "GID" && flags.GroupMap) {
for i := uint64(0); i < sz; i++ {
cids = append(cids, cid+i)
mappedID, err := mapIDwithMapping(hid+i, parentMapping, mapSetting)
if err != nil {
return mappings, flags, err
}
hids = append(hids, mappedID)
sizes = append(sizes, 1)
}
}
} else {
cids = []uint64{cid}
hids = []uint64{hid}
sizes = []uint64{sz}
}
// Avoid possible integer overflow on 32bit builds
if bits.UintSize == 32 {
for i := range cids {
if cids[i] > math.MaxInt32 || hids[i] > math.MaxInt32 || sizes[i] > math.MaxInt32 {
return mappings, flags, fmt.Errorf("initializing ID mappings: %s setting is malformed expected [\"[+ug]uint32:[@]uint32[:uint32]\"] : %q", mapSetting, spec)
}
}
}
for i := range cids {
mappings = append(mappings, idtools.IDMap{
ContainerID: int(cids[i]),
HostID: int(hids[i]),
Size: int(sizes[i]),
})
}
return mappings, flags, nil
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
// Remove any conflicting mapping from mapping present in extension, so
// extension can be appended to mapping without conflicts.
// Returns the resulting mapping, with extension appended to it.
func breakInsert(mapping []idtools.IDMap, extension idtools.IDMap) (result []idtools.IDMap) {
// Two steps:
// 1. Remove extension regions from mapping
// For each element in mapping, remove those parts of the mapping
// that overlap with the extension, both in the container range
// or in the host range.
// 2. Add extension to mapping
// Step 1: Remove extension regions from mapping
for _, mapPiece := range mapping {
// Make container and host ranges comparable, by computing their
// extension relative to the start of the mapPiece:
range1Start := extension.ContainerID - mapPiece.ContainerID
range2Start := extension.HostID - mapPiece.HostID
// Range end relative to mapPiece range
range1End := range1Start + extension.Size
range2End := range2Start + extension.Size
// mapPiece range:
mapPieceStart := 0
mapPieceEnd := mapPiece.Size
if range1End < mapPieceStart || range1Start >= mapPieceEnd {
// out of range, forget about it
range1End = -1
range1Start = -1
} else {
// clip limits removal to mapPiece
range1End = min(range1End, mapPieceEnd)
range1Start = max(range1Start, mapPieceStart)
}
if range2End < mapPieceStart || range2Start >= mapPieceEnd {
// out of range, forget about it
range2End = -1
range2Start = -1
} else {
// clip limits removal to mapPiece
range2End = min(range2End, mapPieceEnd)
range2Start = max(range2Start, mapPieceStart)
}
// If there is nothing to remove, append the original and continue:
if range1Start == -1 && range2Start == -1 {
result = append(result, mapPiece)
continue
}
// If there is one range to remove, save it at range1:
if range1Start == -1 && range2Start != -1 {
range1Start = range2Start
range1End = range2End
range2Start = -1
range2End = -1
}
// If we have two valid ranges, merge them into range1 if possible
if range2Start != -1 {
// Swap ranges so always range1Start is <= range2Start
if range2Start < range1Start {
range1Start, range2Start = range2Start, range1Start
range1End, range2End = range2End, range1End
}
// If there is overlap, merge them:
if range1End >= range2Start {
range1End = max(range1End, range2End)
range2Start = -1
range2End = -1
}
}
if range1Start > 0 {
// Append everything before range1Start
result = append(result, idtools.IDMap{
ContainerID: mapPiece.ContainerID,
HostID: mapPiece.HostID,
Size: range1Start,
})
}
if range2Start == -1 {
// Append everything after range1
if mapPiece.Size-range1End > 0 {
result = append(result, idtools.IDMap{
ContainerID: mapPiece.ContainerID + range1End,
HostID: mapPiece.HostID + range1End,
Size: mapPiece.Size - range1End,
})
}
} else {
// Append everything between range1 and range2
result = append(result, idtools.IDMap{
ContainerID: mapPiece.ContainerID + range1End,
HostID: mapPiece.HostID + range1End,
Size: range2Start - range1End,
})
// Append everything after range2
if mapPiece.Size-range2End > 0 {
result = append(result, idtools.IDMap{
ContainerID: mapPiece.ContainerID + range2End,
HostID: mapPiece.HostID + range2End,
Size: mapPiece.Size - range2End,
})
}
}
}
// Step 2. Add extension to mapping
result = append(result, extension)
return result
}
// A multirange is a list of [start,end) ranges and is expressed as
// an array of length-2 integers.
//
// This function computes availableRanges = fullRanges - usedRanges,
// where all variables are multiranges.
// The subtraction operation is defined as "return the multirange
// containing all integers found in fullRanges and not found in usedRanges.
func getAvailableIDRanges(fullRanges, usedRanges [][2]int) (availableRanges [][2]int) {
// Sort them
sort.Slice(fullRanges, func(i, j int) bool {
return fullRanges[i][0] < fullRanges[j][0]
})
if len(usedRanges) == 0 {
return fullRanges
}
sort.Slice(usedRanges, func(i, j int) bool {
return usedRanges[i][0] < usedRanges[j][0]
})
// To traverse usedRanges
i := 0
nextUsedID := usedRanges[i][0]
nextUsedIDEnd := usedRanges[i][1]
for _, fullRange := range fullRanges {
currentIDToProcess := fullRange[0]
for currentIDToProcess < fullRange[1] {
switch {
case nextUsedID == -1:
// No further used ids, append all the remaining ranges
availableRanges = append(availableRanges, [2]int{currentIDToProcess, fullRange[1]})
currentIDToProcess = fullRange[1]
case currentIDToProcess < nextUsedID:
// currentIDToProcess is not used, append:
if fullRange[1] <= nextUsedID {
availableRanges = append(availableRanges, [2]int{currentIDToProcess, fullRange[1]})
currentIDToProcess = fullRange[1]
} else {
availableRanges = append(availableRanges, [2]int{currentIDToProcess, nextUsedID})
currentIDToProcess = nextUsedID
}
case currentIDToProcess == nextUsedID:
// currentIDToProcess and all ids until nextUsedIDEnd are used
// Advance currentIDToProcess
currentIDToProcess = min(fullRange[1], nextUsedIDEnd)
default: // currentIDToProcess > nextUsedID
// Increment nextUsedID so it is >= currentIDToProcess
// Go to next used block if this one is all behind:
if currentIDToProcess >= nextUsedIDEnd {
i += 1
if i == len(usedRanges) {
// No more used ranges
nextUsedID = -1
} else {
nextUsedID = usedRanges[i][0]
nextUsedIDEnd = usedRanges[i][1]
}
continue
} else { // currentIDToProcess < nextUsedIDEnd
currentIDToProcess = min(fullRange[1], nextUsedIDEnd)
}
}
}
}
return availableRanges
}
// Gets the multirange of subordinated ids from parentMapping and the
// multirange of already assigned ids from idmap, and returns the
// multirange of unassigned subordinated ids.
func getAvailableIDRangesFromMappings(idmap []idtools.IDMap, parentMapping []ruser.IDMap) (availableRanges [][2]int) {
// Get all subordinated ids from parentMapping:
fullRanges := [][2]int{} // {Multirange: [start, end), [start, end), ...}
for _, mapPiece := range parentMapping {
fullRanges = append(fullRanges, [2]int{int(mapPiece.ID), int(mapPiece.ID + mapPiece.Count)})
}
// Get the ids already mapped:
usedRanges := [][2]int{}
for _, mapPiece := range idmap {
usedRanges = append(usedRanges, [2]int{mapPiece.HostID, mapPiece.HostID + mapPiece.Size})
}
// availableRanges = fullRanges - usedRanges
availableRanges = getAvailableIDRanges(fullRanges, usedRanges)
return availableRanges
}
// Fills unassigned idmap ContainerIDs, starting from zero with all
// the available ids given by availableRanges.
// Returns the filled idmap.
func fillIDMap(idmap []idtools.IDMap, availableRanges [][2]int) (output []idtools.IDMap) {
idmapByCid := append([]idtools.IDMap{}, idmap...)
sort.Slice(idmapByCid, func(i, j int) bool {
return idmapByCid[i].ContainerID < idmapByCid[j].ContainerID
})
if len(availableRanges) == 0 {
return idmapByCid
}
i := 0 // to iterate through availableRanges
nextCid := 0
nextAvailHid := availableRanges[i][0]
for _, mapPiece := range idmapByCid {
// While there are available IDs to map and unassigned
// container ids, map the available ids:
for nextCid < mapPiece.ContainerID && nextAvailHid != -1 {
size := min(mapPiece.ContainerID-nextCid, availableRanges[i][1]-nextAvailHid)
output = append(output, idtools.IDMap{
ContainerID: nextCid,
HostID: nextAvailHid,
Size: size,
})
nextCid += size
if nextAvailHid+size < availableRanges[i][1] {
nextAvailHid += size
} else {
i += 1
if i == len(availableRanges) {
nextAvailHid = -1
continue
}
nextAvailHid = availableRanges[i][0]
}
}
// The given mapping does not change
output = append(output, mapPiece)
nextCid += mapPiece.Size
}
// After the last given mapping is mapped, we use all the remaining
// ids to map the rest of the space
for nextAvailHid != -1 {
size := availableRanges[i][1] - nextAvailHid
output = append(output, idtools.IDMap{
ContainerID: nextCid,
HostID: nextAvailHid,
Size: size,
})
nextCid += size
i += 1
if i == len(availableRanges) {
nextAvailHid = -1
continue
}
nextAvailHid = availableRanges[i][0]
}
return output
}
func addOneMapping(idmap []idtools.IDMap, fillMap bool, mapping idtools.IDMap, flags idMapFlags, mapSetting string) ([]idtools.IDMap, bool) {
// If we are mapping uids and the spec doesn't have the usermap flag, ignore it
if mapSetting == "UID" && !flags.UserMap {
return idmap, fillMap
}
// If we are mapping gids and the spec doesn't have the groupmap flag, ignore it
if mapSetting == "GID" && !flags.GroupMap {
return idmap, fillMap
}
// Zero-size mapping is ignored
if mapping.Size == 0 {
return idmap, fillMap
}
// Not extending, just append:
if !flags.Extends {
idmap = append(idmap, mapping)
return idmap, fillMap
}
// Break and extend the last mapping:
// Extending without any mapping, if rootless, we will fill
// the space with the remaining IDs:
if len(idmap) == 0 && rootless.IsRootless() {
fillMap = true
}
idmap = breakInsert(idmap, mapping)
return idmap, fillMap
}
// Extension of idTools.ParseIDMap that parses idmap triples from string.
// This extension accepts additional flags that control how the mapping is done
func ParseIDMap(mapSpec []string, mapSetting string, parentMapping []ruser.IDMap) (idmap []idtools.IDMap, err error) {
stdErr := fmt.Errorf("initializing ID mappings: %s setting is malformed expected [\"[+ug]uint32:[@]uint32[:uint32]\"] : %q", mapSetting, mapSpec)
// When fillMap is true, the given mapping will be filled with the remaining subordinate available ids
fillMap := false
for _, idMapSpec := range mapSpec {
if idMapSpec == "" {
continue
}
idSpec := strings.Split(idMapSpec, ":")
// if it's a length-2 list assume the size is 1:
if len(idSpec) == 2 {
idSpec = append(idSpec, "1")
}
if len(idSpec)%3 != 0 {
return nil, stdErr
}
for i := range idSpec {
if i%3 != 0 {
continue
}
if len(idSpec[i]) == 0 {
return nil, stdErr
}
// Parse this mapping:
mappings, flags, err := parseTriple(idSpec[i:i+3], parentMapping, mapSetting)
if err != nil {
return nil, err
}
for _, mapping := range mappings {
idmap, fillMap = addOneMapping(idmap, fillMap, mapping, flags, mapSetting)
}
}
}
if fillMap {
availableRanges := getAvailableIDRangesFromMappings(idmap, parentMapping)
idmap = fillIDMap(idmap, availableRanges)
}
if len(idmap) == 0 {
return idmap, nil
}
idmap = sortAndMergeConsecutiveMappings(idmap)
return idmap, nil
}
// Given a mapping, sort all entries by their ContainerID then and merge
// entries that are consecutive.
func sortAndMergeConsecutiveMappings(idmap []idtools.IDMap) (finalIDMap []idtools.IDMap) {
idmapByCid := append([]idtools.IDMap{}, idmap...)
sort.Slice(idmapByCid, func(i, j int) bool {
return idmapByCid[i].ContainerID < idmapByCid[j].ContainerID
})
for i, mapPiece := range idmapByCid {
if i == 0 {
finalIDMap = append(finalIDMap, mapPiece)
continue
}
lastMap := finalIDMap[len(finalIDMap)-1]
containersMatch := lastMap.ContainerID+lastMap.Size == mapPiece.ContainerID
hostsMatch := lastMap.HostID+lastMap.Size == mapPiece.HostID
if containersMatch && hostsMatch {
finalIDMap[len(finalIDMap)-1].Size += mapPiece.Size
} else {
finalIDMap = append(finalIDMap, mapPiece)
}
}
return finalIDMap
}
// Extension of idTools.parseAutoTriple that parses idmap triples.
// The triple should be a length 3 string array, containing:
// - Flags and ContainerID
// - HostID
// - Size
//
// parseAutoTriple returns the parsed mapping and any possible error.
// If the error is not-nil, the mapping is not well-defined.
//
// idTools.parseAutoTriple is extended here with the following enhancements:
//
// HostID @ syntax:
// =================
// HostID may use the "@" syntax: The "101001:@1001:1" mapping
// means "take the 1001 id from the parent namespace and map it to 101001"
func parseAutoTriple(spec []string, parentMapping []ruser.IDMap, mapSetting string) (mappings []idtools.IDMap, err error) {
if len(spec[0]) == 0 {
return mappings, fmt.Errorf("invalid empty container id at %s map: %v", mapSetting, spec)
}
var cids, hids, sizes []uint64
var cid, hid uint64
var hidIsParent bool
// Parse the container ID, which must be an integer:
cid, err = strconv.ParseUint(spec[0][0:], 10, 32)
if err != nil {
return mappings, fmt.Errorf("parsing id map value %q: %w", spec[0], err)
}
// Parse the host id, which may be integer or @<integer>
if len(spec[1]) == 0 {
return mappings, fmt.Errorf("invalid empty host id at %s map: %v", mapSetting, spec)
}
if spec[1][0] != '@' {
hidIsParent = false
hid, err = strconv.ParseUint(spec[1], 10, 32)
} else {
// Parse @<id>, where <id> is an integer corresponding to the parent mapping
hidIsParent = true
hid, err = strconv.ParseUint(spec[1][1:], 10, 32)
}
if err != nil {
return mappings, fmt.Errorf("parsing id map value %q: %w", spec[1], err)
}
// Parse the size of the mapping, which must be an integer
sz, err := strconv.ParseUint(spec[2], 10, 32)
if err != nil {
return mappings, fmt.Errorf("parsing id map value %q: %w", spec[2], err)
}
if hidIsParent {
for i := uint64(0); i < sz; i++ {
cids = append(cids, cid+i)
mappedID, err := mapIDwithMapping(hid+i, parentMapping, mapSetting)
if err != nil {
return mappings, err
}
hids = append(hids, mappedID)
sizes = append(sizes, 1)
}
} else {
cids = []uint64{cid}
hids = []uint64{hid}
sizes = []uint64{sz}
}
// Avoid possible integer overflow on 32bit builds
if bits.UintSize == 32 {
for i := range cids {
if cids[i] > math.MaxInt32 || hids[i] > math.MaxInt32 || sizes[i] > math.MaxInt32 {
return mappings, fmt.Errorf("initializing ID mappings: %s setting is malformed expected [\"[+ug]uint32:[@]uint32[:uint32]\"] : %q", mapSetting, spec)
}
}
}
for i := range cids {
mappings = append(mappings, idtools.IDMap{
ContainerID: int(cids[i]),
HostID: int(hids[i]),
Size: int(sizes[i]),
})
}
return mappings, nil
}
// Extension of idTools.ParseIDMap that parses idmap triples from string.
// This extension accepts additional flags that control how the mapping is done
func parseAutoIDMap(mapSpec string, mapSetting string, parentMapping []ruser.IDMap) (idmap []idtools.IDMap, err error) {
stdErr := fmt.Errorf("initializing ID mappings: %s setting is malformed expected [\"uint32:[@]uint32[:uint32]\"] : %q", mapSetting, mapSpec)
idSpec := strings.Split(mapSpec, ":")
// if it's a length-2 list assume the size is 1:
if len(idSpec) == 2 {
idSpec = append(idSpec, "1")
}
if len(idSpec) != 3 {
return nil, stdErr
}
// Parse this mapping:
mappings, err := parseAutoTriple(idSpec, parentMapping, mapSetting)
if err != nil {
return nil, err
}
idmap = sortAndMergeConsecutiveMappings(mappings)
return idmap, nil
}
// GetAutoOptions returns an AutoUserNsOptions with the settings to automatically set up
// a user namespace.
func GetAutoOptions(n namespaces.UsernsMode) (*stypes.AutoUserNsOptions, error) {
mode, opts, hasOpts := strings.Cut(string(n), ":")
if mode != "auto" {
return nil, fmt.Errorf("wrong user namespace mode")
}
options := stypes.AutoUserNsOptions{}
if !hasOpts {
return &options, nil
}
parentUIDMap, parentGIDMap, err := rootless.GetAvailableIDMaps()
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
// The kernel-provided files only exist if user namespaces are supported
logrus.Debugf("User or group ID mappings not available: %s", err)
} else {
return nil, err
}
}
for _, o := range strings.Split(opts, ",") {
key, val, hasVal := strings.Cut(o, "=")
if !hasVal {
return nil, fmt.Errorf("invalid option specified: %q", o)
}
switch key {
case "size":
s, err := strconv.ParseUint(val, 10, 32)
if err != nil {
return nil, err
}
options.Size = uint32(s)
case "uidmapping":
mapping, err := parseAutoIDMap(val, "UID", parentUIDMap)
if err != nil {
return nil, err
}
options.AdditionalUIDMappings = append(options.AdditionalUIDMappings, mapping...)
case "gidmapping":
mapping, err := parseAutoIDMap(val, "GID", parentGIDMap)
if err != nil {
return nil, err
}
options.AdditionalGIDMappings = append(options.AdditionalGIDMappings, mapping...)
default:
return nil, fmt.Errorf("unknown option specified: %q", key)
}
}
return &options, nil
}
// ParseIDMapping takes idmappings and subuid and subgid maps and returns a storage mapping
func ParseIDMapping(mode namespaces.UsernsMode, uidMapSlice, gidMapSlice []string, subUIDMap, subGIDMap string) (*stypes.IDMappingOptions, error) {
options := stypes.IDMappingOptions{
HostUIDMapping: true,
HostGIDMapping: true,
}
if mode.IsAuto() {
var err error
options.HostUIDMapping = false
options.HostGIDMapping = false
options.AutoUserNs = true
opts, err := GetAutoOptions(mode)
if err != nil {
return nil, err
}
options.AutoUserNsOpts = *opts
return &options, nil
}
if mode.IsKeepID() || mode.IsNoMap() {
options.HostUIDMapping = false
options.HostGIDMapping = false
return &options, nil
}
if subGIDMap == "" && subUIDMap != "" {
subGIDMap = subUIDMap
}
if subUIDMap == "" && subGIDMap != "" {
subUIDMap = subGIDMap
}
if len(gidMapSlice) == 0 && len(uidMapSlice) != 0 {
gidMapSlice = uidMapSlice
}
if len(uidMapSlice) == 0 && len(gidMapSlice) != 0 {
uidMapSlice = gidMapSlice