github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/net/netlink/route.go (about)

     1  package netlink
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"net/netip"
     7  	"strconv"
     8  
     9  	"github.com/Asutorufa/yuhaiin/pkg/utils/net"
    10  	wun "github.com/tailscale/wireguard-go/tun"
    11  	"gvisor.dev/gvisor/pkg/tcpip/stack"
    12  )
    13  
    14  type Options struct {
    15  	Endpoint     stack.LinkEndpoint
    16  	Writer       Tun
    17  	Interface    TunScheme
    18  	Inet6Address []netip.Prefix
    19  	Inet4Address []netip.Prefix
    20  	Routes       []netip.Prefix
    21  	MTU          int
    22  }
    23  
    24  type Tun interface {
    25  	Tun() wun.Device
    26  	Write(bufs [][]byte) (int, error)
    27  	Read(bufs [][]byte, sizes []int) (n int, err error)
    28  	io.Closer
    29  }
    30  
    31  func (o *Options) V4Address() netip.Prefix {
    32  	if len(o.Inet4Address) > 0 {
    33  		return o.Inet4Address[0]
    34  	}
    35  	return netip.Prefix{}
    36  }
    37  
    38  func (o *Options) V6Address() netip.Prefix {
    39  	if len(o.Inet6Address) > 0 {
    40  		return o.Inet6Address[0]
    41  	}
    42  	return netip.Prefix{}
    43  }
    44  
    45  type TunScheme struct {
    46  	Fd     int
    47  	Scheme string
    48  	Name   string
    49  }
    50  
    51  func ParseTunScheme(str string) (TunScheme, error) {
    52  	scheme, name, err := net.GetScheme(str)
    53  	if err != nil {
    54  		return TunScheme{}, err
    55  	}
    56  
    57  	if len(name) < 3 {
    58  		return TunScheme{}, fmt.Errorf("invalid tun name: %s", name)
    59  	}
    60  
    61  	name = name[2:]
    62  
    63  	var fd int
    64  	switch scheme {
    65  	case "tun":
    66  	case "fd":
    67  		fd, err = strconv.Atoi(name)
    68  		if err != nil {
    69  			return TunScheme{}, fmt.Errorf("invalid fd: %s", name)
    70  		}
    71  	default:
    72  		return TunScheme{}, fmt.Errorf("invalid tun name: %s", str)
    73  	}
    74  
    75  	return TunScheme{
    76  		Scheme: scheme,
    77  		Name:   name,
    78  		Fd:     fd,
    79  	}, nil
    80  }