-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathip.y
125 lines (104 loc) · 2.91 KB
/
ip.y
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
%{
package iprange
import (
"encoding/binary"
"net"
"github.com/pkg/errors"
)
type AddressRangeList []AddressRange
type AddressRange struct {
Min net.IP
Max net.IP
}
type octetRange struct {
min byte
max byte
}
const (
ipV4MaskLength = 32
maxMaskValue = ipV4MaskLength
)
%}
%union {
byteValue byte
octRange octetRange
addrRange AddressRange
result AddressRangeList
ipMask net.IPMask
}
%token <byteValue> NUM
%type <ipMask> mask
%type <addrRange> address target
%type <octRange> term octet_range
%type <result> result
%%
result: target
{
$$ = append($$, $1)
iplex.(*ipLex).output = $$
}
| result comma target
{
$$ = append($1, $3)
iplex.(*ipLex).output = $$
}
comma: ',' | ',' ' '
target: address '/' mask
{
mask := $3
min := $1.Min.Mask(mask)
maxInt := binary.BigEndian.Uint32([]byte(min)) +
0xffffffff -
binary.BigEndian.Uint32([]byte(mask))
maxBytes := make([]byte, 4)
binary.BigEndian.PutUint32(maxBytes, maxInt)
maxBytes = maxBytes[len(maxBytes)-4:]
max := net.IP(maxBytes)
$$ = AddressRange {
Min: min.To4(),
Max: max.To4(),
}
}
| address
{
$$ = $1
}
address: term '.' term '.' term '.' term
{
$$ = AddressRange {
Min: net.IPv4($1.min, $3.min, $5.min, $7.min).To4(),
Max: net.IPv4($1.max, $3.max, $5.max, $7.max).To4(),
}
}
term: NUM { $$ = octetRange { $1, $1 } }
| '*' { $$ = octetRange { 0, 255 } }
| octet_range { $$ = $1 }
octet_range: NUM '-' NUM { $$ = octetRange { $1, $3 } }
mask: NUM
{
if $1 > maxMaskValue {
$$ = net.CIDRMask(maxMaskValue, ipV4MaskLength)
break
}
$$ = net.CIDRMask(int($1), ipV4MaskLength)
}
%%
// ParseList takes a list of target specifications and returns a list of ranges,
// even if the list contains a single element.
func ParseList(in string) (AddressRangeList, error) {
lex := &ipLex{line: []byte(in)}
errCode := ipParse(lex)
if errCode != 0 || lex.err != nil {
return nil, errors.Wrap(lex.err, "could not parse target")
}
return lex.output, nil
}
// Parse takes a single target specification and returns a range. It effectively calls ParseList
// and returns the first result
func Parse(in string) (*AddressRange, error) {
l, err := ParseList(in)
if err != nil {
return nil, err
}
return &l[0], nil
}