Browse Source

Merge pull request #87 from machooo-x/master

Added Replace method to replace rulespec (in specified pos)
Casey Callendrello 1 year ago
parent
commit
b9dff5a19d
2 changed files with 21 additions and 0 deletions
  1. 6 0
      iptables/iptables.go
  2. 15 0
      iptables/iptables_test.go

+ 6 - 0
iptables/iptables.go

@@ -187,6 +187,12 @@ func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) er
 	return ipt.run(cmd...)
 }
 
+// Replace replaces rulespec to specified table/chain (in specified pos)
+func (ipt *IPTables) Replace(table, chain string, pos int, rulespec ...string) error {
+	cmd := append([]string{"-t", table, "-R", chain, strconv.Itoa(pos)}, rulespec...)
+	return ipt.run(cmd...)
+}
+
 // InsertUnique acts like Insert except that it won't insert a duplicate (no matter the position in the chain)
 func (ipt *IPTables) InsertUnique(table, chain string, pos int, rulespec ...string) error {
 	exists, err := ipt.Exists(table, chain, rulespec...)

+ 15 - 0
iptables/iptables_test.go

@@ -309,6 +309,21 @@ func runRulesTests(t *testing.T, ipt *IPTables) {
 		t.Fatalf("Delete failed: %v", err)
 	}
 
+	err = ipt.Insert("filter", chain, 1, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
+	if err != nil {
+		t.Fatalf("Insert failed: %v", err)
+	}
+
+	err = ipt.Replace("filter", chain, 1, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
+	if err != nil {
+		t.Fatalf("Replace failed: %v", err)
+	}
+
+	err = ipt.Delete("filter", chain, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
+	if err != nil {
+		t.Fatalf("Delete failed: %v", err)
+	}
+
 	err = ipt.Append("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
 	if err != nil {
 		t.Fatalf("Append failed: %v", err)