Skip to content

Commit

Permalink
Merge pull request #87 from machooo-x/master
Browse files Browse the repository at this point in the history
Added Replace method to replace rulespec (in specified pos)
  • Loading branch information
squeed authored Jul 31, 2023
2 parents b20e55f + c1c4017 commit b9dff5a
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 @@ -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...)
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 b9dff5a

Please sign in to comment.