github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/firewall/iptables/chain.go (about) 1 /* 2 * Copyright (C) 2019 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package iptables 19 20 import "strconv" 21 22 // Rule is a packet filter rule for IPTables. 23 type Rule struct { 24 chainName string 25 action []string 26 ruleSpec []string 27 } 28 29 // AppendTo creates a new rule to be appended to the specified chain. 30 func AppendTo(chainName string) Rule { 31 return Rule{ 32 chainName: chainName, 33 action: []string{"-A", chainName}, 34 } 35 } 36 37 // InsertAt creates a new rule to be inserted into the specified chain. 38 func InsertAt(chainName string, line int) Rule { 39 return Rule{ 40 chainName: chainName, 41 action: []string{"-I", chainName, strconv.Itoa(line)}, 42 } 43 } 44 45 // RuleSpec sets the rule specification (see `man iptables`). 46 func (r Rule) RuleSpec(spec ...string) Rule { 47 r.ruleSpec = spec 48 return r 49 } 50 51 // ApplyArgs returns an argument list to be passed to the iptables executable to APPLY the rule. 52 func (r Rule) ApplyArgs() []string { 53 return append(r.action, r.ruleSpec...) 54 } 55 56 // RemoveArgs returns an argument list to be passed to the iptables executable to REMOVE the rule. 57 func (r Rule) RemoveArgs() []string { 58 return append([]string{"-D", r.chainName}, r.ruleSpec...) 59 } 60 61 // Equals checks if two Rules are equal. 62 func (r Rule) Equals(another Rule) bool { 63 return r.chainName == another.chainName && 64 equalStringSlice(r.ruleSpec, another.ruleSpec) 65 } 66 67 func equalStringSlice(a, b []string) bool { 68 if len(a) != len(b) { 69 return false 70 } 71 for i := range a { 72 if a[i] != b[i] { 73 return false 74 } 75 } 76 return true 77 }