/
rule_translator.go
63 lines (50 loc) · 1.58 KB
/
rule_translator.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
package iptables
import (
"fmt"
"strings"
"code.cloudfoundry.org/garden"
)
var protocols = map[garden.Protocol]string{
garden.ProtocolAll: "all",
garden.ProtocolTCP: "tcp",
garden.ProtocolICMP: "icmp",
garden.ProtocolUDP: "udp",
}
type ruleTranslator struct {
}
func NewRuleTranslator() RuleTranslator {
return &ruleTranslator{}
}
func (t *ruleTranslator) TranslateRule(handle string, gardenRule garden.NetOutRule) ([]Rule, error) {
if len(gardenRule.Ports) > 0 && !allowsPort(gardenRule.Protocol) {
return nil, fmt.Errorf("Ports cannot be specified for Protocol %s", strings.ToUpper(protocols[gardenRule.Protocol]))
}
if _, ok := protocols[gardenRule.Protocol]; !ok {
return nil, fmt.Errorf("invalid protocol: %d", gardenRule.Protocol)
}
iptablesRule := SingleFilterRule{
Protocol: gardenRule.Protocol,
ICMPs: gardenRule.ICMPs,
Log: gardenRule.Log,
Handle: handle,
}
iptablesRules := []Rule{}
// It should still loop once even if there are no networks or ports.
for i := 0; i < len(gardenRule.Ports) || i == 0; i++ {
for j := 0; j < len(gardenRule.Networks) || j == 0; j++ {
// Preserve nils unless there are ports specified
if len(gardenRule.Ports) > 0 {
iptablesRule.Ports = &gardenRule.Ports[i]
}
// Preserve nils unless there are networks specified
if len(gardenRule.Networks) > 0 {
iptablesRule.Networks = &gardenRule.Networks[j]
}
iptablesRules = append(iptablesRules, iptablesRule)
}
}
return iptablesRules, nil
}
func allowsPort(p garden.Protocol) bool {
return p == garden.ProtocolTCP || p == garden.ProtocolUDP
}