@@ -2,27 +2,51 @@ package hosts
2
2
3
3
import (
4
4
"fmt"
5
+ "regexp"
5
6
"sort"
6
7
"strings"
7
8
8
9
"github.com/goodhosts/hostsfile"
9
10
)
10
11
12
+ const (
13
+ // source https://github.com/kubernetes/apimachinery/blob/603e04655e9f537eb01238cdbce4891f832a4f27/pkg/util/validation/validation.go#L208
14
+ dns1123SubdomainRegexp = `[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*`
15
+ clusterDomain = ".crc.testing"
16
+ appsDomain = ".apps-crc.testing"
17
+ )
18
+
19
+ var (
20
+ clusterRegexp = regexp .MustCompile ("^" + dns1123SubdomainRegexp + regexp .QuoteMeta (clusterDomain ) + "$" )
21
+ appRegexp = regexp .MustCompile ("^" + dns1123SubdomainRegexp + regexp .QuoteMeta (appsDomain ) + "$" )
22
+ )
23
+
11
24
type Hosts struct {
12
- File * hostsfile.Hosts
25
+ File * hostsfile.Hosts
26
+ HostFilter func (string ) bool
13
27
}
14
28
15
29
func New () (* Hosts , error ) {
16
30
file , err := hostsfile .NewHosts ()
17
31
if err != nil {
18
32
return nil , err
19
33
}
34
+
20
35
return & Hosts {
21
- File : & file ,
36
+ File : & file ,
37
+ HostFilter : defaultFilter ,
22
38
}, nil
23
39
}
24
40
41
+ func defaultFilter (s string ) bool {
42
+ return clusterRegexp .MatchString (s ) || appRegexp .MatchString (s )
43
+ }
44
+
25
45
func (h * Hosts ) Add (ip string , hosts []string ) error {
46
+ if err := h .verifyHosts (hosts ); err != nil {
47
+ return err
48
+ }
49
+
26
50
if err := h .checkIsWritable (); err != nil {
27
51
return err
28
52
}
@@ -46,6 +70,10 @@ func (h *Hosts) Add(ip string, hosts []string) error {
46
70
}
47
71
48
72
func (h * Hosts ) Remove (hosts []string ) error {
73
+ if err := h .verifyHosts (hosts ); err != nil {
74
+ return err
75
+ }
76
+
49
77
if err := h .checkIsWritable (); err != nil {
50
78
return err
51
79
}
@@ -69,6 +97,10 @@ func (h *Hosts) Remove(hosts []string) error {
69
97
}
70
98
71
99
func (h * Hosts ) Clean (rawSuffixes []string ) error {
100
+ if err := h .verifyHosts (rawSuffixes ); err != nil {
101
+ return err
102
+ }
103
+
72
104
if err := h .checkIsWritable (); err != nil {
73
105
return err
74
106
}
@@ -109,5 +141,18 @@ func (h *Hosts) checkIsWritable() error {
109
141
}
110
142
111
143
func (h * Hosts ) Contains (ip , host string ) bool {
144
+ if err := h .verifyHosts ([]string {host }); err != nil {
145
+ return false
146
+ }
147
+
112
148
return h .File .Has (ip , host )
113
149
}
150
+
151
+ func (h * Hosts ) verifyHosts (hosts []string ) error {
152
+ for _ , host := range hosts {
153
+ if ! h .HostFilter (host ) {
154
+ return fmt .Errorf ("input %s rejected" , host )
155
+ }
156
+ }
157
+ return nil
158
+ }
0 commit comments