Skip to content

Commit

Permalink
Using netipx.IPSet safely
Browse files Browse the repository at this point in the history
  • Loading branch information
wwqgtxx committed Jun 19, 2024
1 parent ef83d16 commit b925011
Showing 1 changed file with 24 additions and 42 deletions.
66 changes: 24 additions & 42 deletions redirect_nftables_exprs.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ package tun

import (
"net/netip"
"unsafe"

"github.com/sagernet/nftables"
"github.com/sagernet/nftables/expr"
Expand Down Expand Up @@ -77,42 +76,34 @@ func nftablesCreateIPSet(
id uint32, name string, family nftables.TableFamily,
setList []*netipx.IPSet, prefixList []netip.Prefix, appendDefault bool, update bool,
) (*nftables.Set, error) {
if len(prefixList) > 0 {
var builder netipx.IPSetBuilder
for _, prefix := range prefixList {
builder.AddPrefix(prefix)
}
ipSet, err := builder.IPSet()
if err != nil {
return nil, err
}
setList = append(setList, ipSet)
var builder netipx.IPSetBuilder
for _, prefix := range prefixList {
builder.AddPrefix(prefix)
}
ipSets := make([]*myIPSet, 0, len(setList))
var rangeLen int
for _, set := range setList {
mySet := (*myIPSet)(unsafe.Pointer(set))
ipSets = append(ipSets, mySet)
rangeLen += len(mySet.rr)
builder.AddSet(set)
}
setElements := make([]nftables.SetElement, 0, rangeLen)
for _, mySet := range ipSets {
for _, rr := range mySet.rr {
if (family == nftables.TableFamilyIPv4) != rr.from.Is4() {
continue
}
endAddr := rr.to.Next()
if !endAddr.IsValid() {
endAddr = rr.from
}
setElements = append(setElements, nftables.SetElement{
Key: rr.from.AsSlice(),
})
setElements = append(setElements, nftables.SetElement{
Key: endAddr.AsSlice(),
IntervalEnd: true,
})
ipSet, err := builder.IPSet()
if err != nil {
return nil, err
}
ipRanges := ipSet.Ranges()
setElements := make([]nftables.SetElement, 0, len(ipRanges))
for _, rr := range ipRanges {
if (family == nftables.TableFamilyIPv4) != rr.From().Is4() {
continue
}
endAddr := rr.To().Next()
if !endAddr.IsValid() {
endAddr = rr.From()
}
setElements = append(setElements, nftables.SetElement{
Key: rr.To().AsSlice(),
})
setElements = append(setElements, nftables.SetElement{
Key: endAddr.AsSlice(),
IntervalEnd: true,
})
}
if len(prefixList) == 0 && appendDefault {
if family == nftables.TableFamilyIPv4 {
Expand Down Expand Up @@ -179,12 +170,3 @@ func nftablesCreateIPSet(
}
return mySet, nil
}

type myIPSet struct {
rr []myIPRange
}

type myIPRange struct {
from netip.Addr
to netip.Addr
}

0 comments on commit b925011

Please sign in to comment.