1
0
mirror of https://github.com/fumiama/WireGold.git synced 2026-06-10 11:40:30 +08:00

add cidr hook in unix

This commit is contained in:
fumiama
2021-12-30 17:11:13 +08:00
parent bcfba4418f
commit cd060c7b92
4 changed files with 35 additions and 2 deletions

View File

@@ -18,12 +18,14 @@ type NIC struct {
ifce *water.Interface ifce *water.Interface
ip string ip string
subnet string subnet string
cidrs []string
hasstart bool hasstart bool
} }
// NewNIC 新建 TUN 网络接口卡 // NewNIC 新建 TUN 网络接口卡
// 网卡地址为 ip, 所属子网为 subnet // 网卡地址为 ip, 所属子网为 subnet
func NewNIC(ip, subnet string) (n *NIC) { // 所有路由为 cidrs
func NewNIC(ip, subnet string, cidrs ...string) (n *NIC) {
ifce, err := water.New(water.Config{DeviceType: water.TUN}) ifce, err := water.New(water.Config{DeviceType: water.TUN})
if err != nil { if err != nil {
panic(err) panic(err)
@@ -31,6 +33,7 @@ func NewNIC(ip, subnet string) (n *NIC) {
n = &NIC{ n = &NIC{
ifce: ifce, ifce: ifce,
ip: ip, ip: ip,
cidrs: cidrs,
subnet: subnet, subnet: subnet,
} }
n.prepare() n.prepare()

View File

@@ -6,6 +6,9 @@ package lower
func (n *NIC) prepare() { func (n *NIC) prepare() {
execute("ifconfig", n.ifce.Name(), "inet", n.ip, n.ip, "up") execute("ifconfig", n.ifce.Name(), "inet", n.ip, n.ip, "up")
execute("route", "add", n.subnet, "-interface", n.ifce.Name()) execute("route", "add", n.subnet, "-interface", n.ifce.Name())
for _, c := range n.cidrs {
execute("route", "add", c, "-interface", n.ifce.Name())
}
} }
func (n *NIC) Up() { func (n *NIC) Up() {

View File

@@ -8,6 +8,9 @@ func (n *NIC) prepare() {
execute("/sbin/ip", "addr", "add", n.ip, "dev", n.ifce.Name()) execute("/sbin/ip", "addr", "add", n.ip, "dev", n.ifce.Name())
execute("/sbin/ip", "link", "set", "dev", n.ifce.Name(), "up") execute("/sbin/ip", "link", "set", "dev", n.ifce.Name(), "up")
execute("/sbin/ip", "route", "add", n.subnet, "dev", n.ifce.Name()) execute("/sbin/ip", "route", "add", n.subnet, "dev", n.ifce.Name())
for _, c := range n.cidrs {
execute("/sbin/ip", "route", "add", c, "dev", n.ifce.Name())
}
} }
func (n *NIC) Up() { func (n *NIC) Up() {

26
main.go
View File

@@ -3,6 +3,7 @@ package main
import ( import (
"flag" "flag"
"fmt" "fmt"
"net"
"os" "os"
base14 "github.com/fumiama/go-base16384" base14 "github.com/fumiama/go-base16384"
@@ -127,7 +128,30 @@ func main() {
os.Exit(0) os.Exit(0)
} }
nic := lower.NewNIC(c.IP, c.SubNet) cidrsmap := make(map[string]bool, 32)
_, mysubnet, err := net.ParseCIDR(c.SubNet)
if err != nil {
panic(err)
}
for _, p := range c.Peers {
for _, ip := range p.AllowedIPs {
ipnet, _, err := net.ParseCIDR(ip)
if err != nil {
panic(err)
}
if !mysubnet.Contains(ipnet) {
cidrsmap[ip] = true
}
}
}
cidrs := make([]string, len(cidrsmap))
i := 0
for k := range cidrsmap {
cidrs[i] = k
i++
}
nic := lower.NewNIC(c.IP, c.SubNet, cidrs...)
me := link.NewMe(&key, c.IP+"/32", c.EndPoint, true) me := link.NewMe(&key, c.IP+"/32", c.EndPoint, true)
for _, peer := range c.Peers { for _, peer := range c.Peers {