Skip to content

Commit

Permalink
Added Replace method to replace rulespec (in specified pos)
Browse files Browse the repository at this point in the history
  • Loading branch information
machooo-x committed Jun 6, 2023
1 parent fa6abe8 commit c1c4017
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
6 changes: 6 additions & 0 deletions iptables/iptables.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,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...)
Expand Down
15 changes: 15 additions & 0 deletions iptables/iptables_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit c1c4017

Please sign in to comment.