/
portspec.go
118 lines (98 loc) · 2.61 KB
/
portspec.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
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
package portspec
// This package manages all port spec functions and validations and can
// be reused by all other packages.
import (
"errors"
"strconv"
"strings"
)
// PortSpec is the specification of a port or port range
type PortSpec struct {
Min uint16 `json:"Min,omitempty"`
Max uint16 `json:"Max,omitempty"`
value interface{}
}
// NewPortSpec creates a new port spec
func NewPortSpec(min, max uint16, value interface{}) (*PortSpec, error) {
if min > max {
return nil, errors.New("Min port greater than max")
}
return &PortSpec{
Min: min,
Max: max,
value: value,
}, nil
}
// NewPortSpecFromString creates a new port spec
func NewPortSpecFromString(ports string, value interface{}) (*PortSpec, error) {
var min, max int
var err error
if strings.Contains(ports, ":") {
portMinMax := strings.SplitN(ports, ":", 2)
if len(portMinMax) != 2 {
return nil, errors.New("Invalid port specification")
}
min, err = strconv.Atoi(portMinMax[0])
if err != nil || min < 0 {
return nil, errors.New("Min is not a valid port")
}
max, err = strconv.Atoi(portMinMax[1])
if err != nil || max >= 65536 {
return nil, errors.New("Max is not a valid port")
}
} else {
min, err = strconv.Atoi(ports)
if err != nil || min >= 65536 || min < 0 {
return nil, errors.New("Port is larger than 2^16 or invalid port")
}
max = min
}
return NewPortSpec(uint16(min), uint16(max), value)
}
// IsMultiPort returns true if the spec is for multiple ports.
func (s *PortSpec) IsMultiPort() bool {
return s.Min != s.Max
}
// SinglePort returns the port of a non multi-port spec
func (s *PortSpec) SinglePort() (uint16, error) {
if s.IsMultiPort() {
return 0, errors.New("Not a single port specification")
}
return s.Min, nil
}
// Range returns the range of a spec.
func (s *PortSpec) Range() (uint16, uint16) {
return s.Min, s.Max
}
// MultiPort returns the multi-port range as a string.
func (s *PortSpec) String() string {
if s.IsMultiPort() {
return strconv.Itoa(int(s.Min)) + ":" + strconv.Itoa(int(s.Max))
}
return strconv.Itoa(int(s.Min))
}
// Value returns the value of the portspec if one is there
func (s *PortSpec) Value() interface{} {
return s.value
}
// Overlaps returns true if the provided port spect overlaps with the given one.
func (s *PortSpec) Overlaps(p *PortSpec) bool {
a := p
b := s
if a.Min > b.Min {
a = s
b = p
}
if a.Max >= b.Min {
return true
}
return false
}
// IsIncluded returns trues if a port is within the range of the portspec
func (s *PortSpec) IsIncluded(port int) bool {
p := uint16(port)
if s.Min <= p && p <= s.Max {
return true
}
return false
}