github.com/TeaOSLab/EdgeNode@v1.3.8/internal/firewalls/nftables/conn.go (about)

     1  // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
     2  //go:build linux
     3  
     4  package nftables
     5  
     6  import (
     7  	"errors"
     8  	nft "github.com/google/nftables"
     9  	"github.com/iwind/TeaGo/types"
    10  )
    11  
    12  const MaxTableNameLength = 27
    13  
    14  type Conn struct {
    15  	rawConn *nft.Conn
    16  }
    17  
    18  func NewConn() (*Conn, error) {
    19  	conn, err := nft.New()
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	return &Conn{
    24  		rawConn: conn,
    25  	}, nil
    26  }
    27  
    28  func (this *Conn) Raw() *nft.Conn {
    29  	return this.rawConn
    30  }
    31  
    32  func (this *Conn) GetTable(name string, family TableFamily) (*Table, error) {
    33  	rawTables, err := this.rawConn.ListTables()
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  
    38  	for _, rawTable := range rawTables {
    39  		if rawTable.Name == name && rawTable.Family == family {
    40  			return NewTable(this, rawTable), nil
    41  		}
    42  	}
    43  
    44  	return nil, ErrTableNotFound
    45  }
    46  
    47  func (this *Conn) AddTable(name string, family TableFamily) (*Table, error) {
    48  	if len(name) > MaxTableNameLength {
    49  		return nil, errors.New("table name too long (max " + types.String(MaxTableNameLength) + ")")
    50  	}
    51  
    52  	var rawTable = this.rawConn.AddTable(&nft.Table{
    53  		Family: family,
    54  		Name:   name,
    55  	})
    56  
    57  	err := this.Commit()
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  
    62  	return NewTable(this, rawTable), nil
    63  }
    64  
    65  func (this *Conn) AddIPv4Table(name string) (*Table, error) {
    66  	return this.AddTable(name, TableFamilyIPv4)
    67  }
    68  
    69  func (this *Conn) AddIPv6Table(name string) (*Table, error) {
    70  	return this.AddTable(name, TableFamilyIPv6)
    71  }
    72  
    73  func (this *Conn) DeleteTable(name string, family TableFamily) error {
    74  	table, err := this.GetTable(name, family)
    75  	if err != nil {
    76  		if err == ErrTableNotFound {
    77  			return nil
    78  		}
    79  		return err
    80  	}
    81  	this.rawConn.DelTable(table.Raw())
    82  	return this.Commit()
    83  }
    84  
    85  func (this *Conn) Commit() error {
    86  	return this.rawConn.Flush()
    87  }