Skip to content

Commit

Permalink
feat: add Conn.CreateTable (#246)
Browse files Browse the repository at this point in the history
`Conn.AddTable` use netlink.Create which will not emit an error
if the table we want to create already existed,
just like the `nft add table ...` command works.

The caller should use netlink.Excl to
get an EEXIST error for that already existed,

So I add another method `Conn.CreateTable`
which works just like `nft create table ...` command.

Related: #245

Signed-off-by: black-desk <me@black-desk.cn>
  • Loading branch information
black-desk committed Oct 24, 2023
1 parent 6df7a82 commit 32bfbb6
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions table.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,7 @@ func (cc *Conn) DelTable(t *Table) {
})
}

// AddTable adds the specified Table. See also
// https://wiki.nftables.org/wiki-nftables/index.php/Configuring_tables
func (cc *Conn) AddTable(t *Table) *Table {
func (cc *Conn) addTable(t *Table, flag netlink.HeaderFlags) *Table {
cc.mu.Lock()
defer cc.mu.Unlock()
data := cc.marshalAttr([]netlink.Attribute{
Expand All @@ -75,13 +73,25 @@ func (cc *Conn) AddTable(t *Table) *Table {
cc.messages = append(cc.messages, netlink.Message{
Header: netlink.Header{
Type: netlink.HeaderType((unix.NFNL_SUBSYS_NFTABLES << 8) | unix.NFT_MSG_NEWTABLE),
Flags: netlink.Request | netlink.Acknowledge | netlink.Create,
Flags: netlink.Request | netlink.Acknowledge | flag,
},
Data: append(extraHeader(uint8(t.Family), 0), data...),
})
return t
}

// AddTable adds the specified Table, just like `nft add table ...`.
// See also https://wiki.nftables.org/wiki-nftables/index.php/Configuring_tables
func (cc *Conn) AddTable(t *Table) *Table {
return cc.addTable(t, netlink.Create)
}

// CreateTable create the specified Table if it do not existed.
// just like `nft create table ...`.
func (cc *Conn) CreateTable(t *Table) *Table {
return cc.addTable(t, netlink.Excl)
}

// FlushTable removes all rules in all chains within the specified Table. See also
// https://wiki.nftables.org/wiki-nftables/index.php/Configuring_tables#Flushing_tables
func (cc *Conn) FlushTable(t *Table) {
Expand Down

0 comments on commit 32bfbb6

Please sign in to comment.