File: validate.go

package info (click to toggle)
golang-github-opencontainers-runtime-tools 0.9.0.141.g5e63903-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 3,160 kB
  • sloc: sh: 559; makefile: 90
file content (45 lines) | stat: -rw-r--r-- 1,064 bytes parent folder | download
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
package capabilities

import (
	"fmt"
	"strings"
	"sync"

	"github.com/moby/sys/capability"
)

// CapValid checks whether a capability is valid. If hostSpecific is set,
// it also checks that the capability is supported on the current host.
func CapValid(c string, hostSpecific bool) error {
	if !strings.HasPrefix(c, "CAP_") {
		return fmt.Errorf("capability %s must start with CAP_", c)
	}

	if _, ok := knownCaps()[c]; !ok {
		return fmt.Errorf("invalid capability: %s", c)
	}
	if !hostSpecific {
		return nil
	}
	if _, ok := supportedCaps()[c]; !ok {
		return fmt.Errorf("%s is not supported on the current host", c)
	}
	return nil
}

func capSet(list []capability.Cap) map[string]struct{} {
	m := make(map[string]struct{}, len(list))
	for _, c := range list {
		m["CAP_"+strings.ToUpper(c.String())] = struct{}{}
	}
	return m
}

var knownCaps = sync.OnceValue(func() map[string]struct{} {
	return capSet(capability.ListKnown())
})

var supportedCaps = sync.OnceValue(func() map[string]struct{} {
	list, _ := capability.ListSupported()
	return capSet(list)
})