/
restore.go
71 lines (61 loc) · 1.77 KB
/
restore.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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020 Authors of Cilium
// The restore package provides data structures important to restoring
// DNS proxy rules. This package serves as a central source for these
// structures.
// Note that these are marshaled as JSON and any changes need to be compatible
// across an upgrade!
package restore
import (
"regexp"
"sort"
)
// DNSRules contains IP-based DNS rules for a set of ports (e.g., 53)
type DNSRules map[uint16]IPRules
// IPRules is an unsorted collection of IPrules
type IPRules []IPRule
// IPRule stores the allowed destination IPs for a DNS names matching a regex
type IPRule struct {
Re RuleRegex
IPs map[string]struct{} // IPs, nil set is wildcard and allows all IPs!
}
// RuleRegex is a wrapper for *regexp.Regexp so that we can define marshalers for it.
type RuleRegex struct {
*regexp.Regexp
}
// Sort is only used for testing
// Sorts in place, but returns IPRules for convenience
func (r IPRules) Sort() IPRules {
sort.SliceStable(r, func(i, j int) bool {
return r[i].Re.String() < r[j].Re.String()
})
return r
}
// Sort is only used for testing
// Sorts in place, but returns DNSRules for convenience
func (r DNSRules) Sort() DNSRules {
for port, ipRules := range r {
if len(ipRules) > 0 {
ipRules = ipRules.Sort()
r[port] = ipRules
}
}
return r
}
// UnmarshalText unmarshals json into a RuleRegex
// This must have a pointer receiver, otherwise the RuleRegex remains empty.
func (r *RuleRegex) UnmarshalText(b []byte) error {
regex, err := regexp.Compile(string(b))
if err != nil {
return err
}
r.Regexp = regex
return nil
}
// MarshalText marshals RuleRegex as string
func (r RuleRegex) MarshalText() ([]byte, error) {
if r.Regexp != nil {
return []byte(r.Regexp.String()), nil
}
return nil, nil
}