...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package name
16
17 import (
18 "net"
19 "net/url"
20 "path"
21 "regexp"
22 "strings"
23 )
24
25
26 var reLocal = regexp.MustCompile(`.*\.local(?:host)?(?::\d{1,5})?$`)
27
28
29 var reLoopback = regexp.MustCompile(regexp.QuoteMeta("127.0.0.1"))
30
31
32 var reipv6Loopback = regexp.MustCompile(regexp.QuoteMeta("::1"))
33
34
35 type Registry struct {
36 insecure bool
37 registry string
38 }
39
40
41 func (r Registry) RegistryStr() string {
42 return r.registry
43 }
44
45
46 func (r Registry) Name() string {
47 return r.RegistryStr()
48 }
49
50 func (r Registry) String() string {
51 return r.Name()
52 }
53
54
55 func (r Registry) Repo(repo ...string) Repository {
56 return Repository{Registry: r, repository: path.Join(repo...)}
57 }
58
59
60 func (r Registry) Scope(string) string {
61
62 return "registry:catalog:*"
63 }
64
65 func (r Registry) isRFC1918() bool {
66 ipStr := strings.Split(r.Name(), ":")[0]
67 ip := net.ParseIP(ipStr)
68 if ip == nil {
69 return false
70 }
71 for _, cidr := range []string{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"} {
72 _, block, _ := net.ParseCIDR(cidr)
73 if block.Contains(ip) {
74 return true
75 }
76 }
77 return false
78 }
79
80
81 func (r Registry) Scheme() string {
82 if r.insecure {
83 return "http"
84 }
85 if r.isRFC1918() {
86 return "http"
87 }
88 if strings.HasPrefix(r.Name(), "localhost:") {
89 return "http"
90 }
91 if reLocal.MatchString(r.Name()) {
92 return "http"
93 }
94 if reLoopback.MatchString(r.Name()) {
95 return "http"
96 }
97 if reipv6Loopback.MatchString(r.Name()) {
98 return "http"
99 }
100 return "https"
101 }
102
103 func checkRegistry(name string) error {
104
105
106 if url, err := url.Parse("//" + name); err != nil || url.Host != name {
107 return newErrBadName("registries must be valid RFC 3986 URI authorities: %s", name)
108 }
109 return nil
110 }
111
112
113
114 func NewRegistry(name string, opts ...Option) (Registry, error) {
115 opt := makeOptions(opts...)
116 if opt.strict && len(name) == 0 {
117 return Registry{}, newErrBadName("strict validation requires the registry to be explicitly defined")
118 }
119
120 if err := checkRegistry(name); err != nil {
121 return Registry{}, err
122 }
123
124 if name == "" {
125 name = opt.defaultRegistry
126 }
127
128
129 if name == defaultRegistryAlias {
130 name = DefaultRegistry
131 }
132
133 return Registry{registry: name, insecure: opt.insecure}, nil
134 }
135
136
137
138
139 func NewInsecureRegistry(name string, opts ...Option) (Registry, error) {
140 opts = append(opts, Insecure)
141 return NewRegistry(name, opts...)
142 }
143
View as plain text