Add func to Delete a chain (#35)

This commit is contained in:
Serguei Bezverkhi 2019-07-11 08:30:38 -04:00 committed by Michael Stapelberg
parent b62e86457d
commit d6b2000800
2 changed files with 91 additions and 0 deletions

View File

@ -114,6 +114,23 @@ func (cc *Conn) AddChain(c *Chain) *Chain {
return c
}
// DelChain deletes the specified Chain. See also
// https://wiki.nftables.org/wiki-nftables/index.php/Configuring_chains#Deleting_chains
func (cc *Conn) DelChain(c *Chain) {
data := cc.marshalAttr([]netlink.Attribute{
{Type: unix.NFTA_CHAIN_TABLE, Data: []byte(c.Table.Name + "\x00")},
{Type: unix.NFTA_CHAIN_NAME, Data: []byte(c.Name + "\x00")},
})
cc.messages = append(cc.messages, netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType((unix.NFNL_SUBSYS_NFTABLES << 8) | unix.NFT_MSG_DELCHAIN),
Flags: netlink.Request | netlink.Acknowledge,
},
Data: append(extraHeader(uint8(c.Table.Family), 0), data...),
})
}
// ListChains returns currently configured chains in the kernel
func (cc *Conn) ListChains() ([]*Chain, error) {
conn, err := cc.dialNetlink()

View File

@ -853,6 +853,80 @@ func TestAddChain(t *testing.T) {
}
}
func TestDelChain(t *testing.T) {
tests := []struct {
name string
chain *nftables.Chain
want [][]byte
}{
{
name: "Base chain",
chain: &nftables.Chain{
Name: "base-chain",
Hooknum: nftables.ChainHookPrerouting,
Priority: 0,
Type: nftables.ChainTypeFilter,
},
want: [][]byte{
// batch begin
[]byte("\x00\x00\x00\x0a"),
// nft delete chain ip filter base-chain
[]byte("\x02\x00\x00\x00\x0b\x00\x01\x00\x66\x69\x6c\x74\x65\x72\x00\x00\x0f\x00\x03\x00\x62\x61\x73\x65\x2d\x63\x68\x61\x69\x6e\x00\x00"),
// batch end
[]byte("\x00\x00\x00\x0a"),
},
},
{
name: "Regular chain",
chain: &nftables.Chain{
Name: "regular-chain",
},
want: [][]byte{
// batch begin
[]byte("\x00\x00\x00\x0a"),
// nft delete chain ip filter regular-chain
[]byte("\x02\x00\x00\x00\x0b\x00\x01\x00\x66\x69\x6c\x74\x65\x72\x00\x00\x12\x00\x03\x00\x72\x65\x67\x75\x6c\x61\x72\x2d\x63\x68\x61\x69\x6e\x00\x00\x00"),
// batch end
[]byte("\x00\x00\x00\x0a"),
},
},
}
for _, tt := range tests {
c := &nftables.Conn{
TestDial: func(req []netlink.Message) ([]netlink.Message, error) {
for idx, msg := range req {
b, err := msg.MarshalBinary()
if err != nil {
t.Fatal(err)
}
if len(b) < 16 {
continue
}
b = b[16:]
if len(tt.want[idx]) == 0 {
t.Errorf("no want entry for message %d: %x", idx, b)
continue
}
got := b
if !bytes.Equal(got, tt.want[idx]) {
t.Errorf("message %d: %s", idx, linediff(nfdump(got), nfdump(tt.want[idx])))
}
}
return req, nil
},
}
tt.chain.Table = &nftables.Table{
Family: nftables.TableFamilyIPv4,
Name: "filter",
}
c.DelChain(tt.chain)
if err := c.Flush(); err != nil {
t.Fatal(err)
}
}
}
func TestGetObjReset(t *testing.T) {
// The want byte sequences come from stracing nft(8), e.g.:
// strace -f -v -x -s 2048 -eraw=sendto nft list chain ip filter forward