Style: code style

This commit is contained in:
yaling888 2022-03-15 02:55:06 +08:00
parent 5abd03e241
commit 20b66d9550
20 changed files with 110 additions and 109 deletions

View file

@ -78,7 +78,7 @@ tun:
stack: gvisor # System or gVisor stack: gvisor # System or gVisor
# device: tun://utun8 # or fd://xxx, it's optional # device: tun://utun8 # or fd://xxx, it's optional
dns-hijack: dns-hijack:
- 0.0.0.0:53 # hijack all - 0.0.0.0:53 # hijack all public
auto-route: true # auto set global route auto-route: true # auto set global route
``` ```
### Rules configuration ### Rules configuration
@ -88,7 +88,9 @@ tun:
- Support `process` condition for all rules. - Support `process` condition for all rules.
- Support source IPCIDR condition for all rules, just append to the end. - Support source IPCIDR condition for all rules, just append to the end.
The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat. The `GEOIP` databases via [https://github.com/Loyalsoldier/geoip](https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb).
The `GEOSITE` databases via [https://github.com/Loyalsoldier/v2ray-rules-dat](https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat).
```yaml ```yaml
rules: rules:
# network condition for all rules # network condition for all rules

View file

@ -42,7 +42,7 @@ type General struct {
RoutingMark int `json:"-"` RoutingMark int `json:"-"`
} }
// Inbound // Inbound config
type Inbound struct { type Inbound struct {
Port int `json:"port"` Port int `json:"port"`
SocksPort int `json:"socks-port"` SocksPort int `json:"socks-port"`
@ -54,7 +54,7 @@ type Inbound struct {
BindAddress string `json:"bind-address"` BindAddress string `json:"bind-address"`
} }
// Controller // Controller config
type Controller struct { type Controller struct {
ExternalController string `json:"-"` ExternalController string `json:"-"`
ExternalUI string `json:"-"` ExternalUI string `json:"-"`
@ -326,11 +326,12 @@ func parseGeneral(cfg *RawConfig) (*General, error) {
func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[string]providerTypes.ProxyProvider, err error) { func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[string]providerTypes.ProxyProvider, err error) {
proxies = make(map[string]C.Proxy) proxies = make(map[string]C.Proxy)
providersMap = make(map[string]providerTypes.ProxyProvider) providersMap = make(map[string]providerTypes.ProxyProvider)
proxyList := []string{}
proxiesConfig := cfg.Proxy proxiesConfig := cfg.Proxy
groupsConfig := cfg.ProxyGroup groupsConfig := cfg.ProxyGroup
providersConfig := cfg.ProxyProvider providersConfig := cfg.ProxyProvider
var proxyList []string
proxies["DIRECT"] = adapter.NewProxy(outbound.NewDirect()) proxies["DIRECT"] = adapter.NewProxy(outbound.NewDirect())
proxies["REJECT"] = adapter.NewProxy(outbound.NewReject()) proxies["REJECT"] = adapter.NewProxy(outbound.NewReject())
proxyList = append(proxyList, "DIRECT", "REJECT") proxyList = append(proxyList, "DIRECT", "REJECT")
@ -377,10 +378,10 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
providersMap[name] = pd providersMap[name] = pd
} }
for _, provider := range providersMap { for _, proxyProvider := range providersMap {
log.Infoln("Start initial provider %s", provider.Name()) log.Infoln("Start initial provider %s", proxyProvider.Name())
if err := provider.Initial(); err != nil { if err := proxyProvider.Initial(); err != nil {
return nil, nil, fmt.Errorf("initial proxy provider %s error: %w", provider.Name(), err) return nil, nil, fmt.Errorf("initial proxy provider %s error: %w", proxyProvider.Name(), err)
} }
} }
@ -411,7 +412,7 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
} }
} }
ps := []C.Proxy{} var ps []C.Proxy
for _, v := range proxyList { for _, v := range proxyList {
ps = append(ps, proxies[v]) ps = append(ps, proxies[v])
} }
@ -430,9 +431,10 @@ func parseProxies(cfg *RawConfig) (proxies map[string]C.Proxy, providersMap map[
} }
func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) { func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
rules := []C.Rule{}
rulesConfig := cfg.Rule rulesConfig := cfg.Rule
var rules []C.Rule
// parse rules // parse rules
for idx, line := range rulesConfig { for idx, line := range rulesConfig {
rule := trimArr(strings.Split(line, ",")) rule := trimArr(strings.Split(line, ","))
@ -443,32 +445,28 @@ func parseRules(cfg *RawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
ruleName = strings.ToUpper(rule[0]) ruleName = strings.ToUpper(rule[0])
) )
switch l := len(rule); { l := len(rule)
case l == 2:
target = rule[1] if l < 2 {
case l == 3:
if ruleName == "MATCH" {
payload = ""
target = rule[1]
params = rule[2:]
break
}
payload = rule[1]
target = rule[2]
case l >= 4:
if ruleName == "MATCH" {
payload = ""
target = rule[1]
params = rule[2:]
break
}
payload = rule[1]
target = rule[2]
params = rule[3:]
default:
return nil, fmt.Errorf("rules[%d] [%s] error: format invalid", idx, line) return nil, fmt.Errorf("rules[%d] [%s] error: format invalid", idx, line)
} }
if l < 4 {
rule = append(rule, make([]string, 4-l)...)
}
if ruleName == "MATCH" {
l = 2
}
if l >= 3 {
l = 3
payload = rule[1]
}
target = rule[l-1]
params = rule[l:]
if _, ok := proxies[target]; !ok { if _, ok := proxies[target]; !ok {
return nil, fmt.Errorf("rules[%d] [%s] error: proxy [%s] not found", idx, line, target) return nil, fmt.Errorf("rules[%d] [%s] error: proxy [%s] not found", idx, line, target)
} }
@ -502,7 +500,7 @@ func parseHosts(cfg *RawConfig) (*trie.DomainTrie, error) {
if ip == nil { if ip == nil {
return nil, fmt.Errorf("%s is not a valid IP", ipStr) return nil, fmt.Errorf("%s is not a valid IP", ipStr)
} }
tree.Insert(domain, ip) _ = tree.Insert(domain, ip)
} }
} }
@ -527,7 +525,7 @@ func hostWithDefaultPort(host string, defPort string) (string, error) {
} }
func parseNameServer(servers []string) ([]dns.NameServer, error) { func parseNameServer(servers []string) ([]dns.NameServer, error) {
nameservers := []dns.NameServer{} var nameservers []dns.NameServer
for idx, server := range servers { for idx, server := range servers {
// parse without scheme .e.g 8.8.8.8:53 // parse without scheme .e.g 8.8.8.8:53
@ -596,7 +594,7 @@ func parseNameServerPolicy(nsPolicy map[string]string) (map[string]dns.NameServe
} }
func parseFallbackIPCIDR(ips []string) ([]*net.IPNet, error) { func parseFallbackIPCIDR(ips []string) ([]*net.IPNet, error) {
ipNets := []*net.IPNet{} var ipNets []*net.IPNet
for idx, ip := range ips { for idx, ip := range ips {
_, ipnet, err := net.ParseCIDR(ip) _, ipnet, err := net.ParseCIDR(ip)
@ -610,7 +608,7 @@ func parseFallbackIPCIDR(ips []string) ([]*net.IPNet, error) {
} }
func parseFallbackGeoSite(countries []string, rules []C.Rule) ([]*router.DomainMatcher, error) { func parseFallbackGeoSite(countries []string, rules []C.Rule) ([]*router.DomainMatcher, error) {
sites := []*router.DomainMatcher{} var sites []*router.DomainMatcher
for _, country := range countries { for _, country := range countries {
found := false found := false
@ -693,7 +691,7 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie, rules []C.Rule) (*DNS,
if len(cfg.FakeIPFilter) != 0 { if len(cfg.FakeIPFilter) != 0 {
host = trie.New() host = trie.New()
for _, domain := range cfg.FakeIPFilter { for _, domain := range cfg.FakeIPFilter {
host.Insert(domain, true) _ = host.Insert(domain, true)
} }
} }
@ -705,7 +703,7 @@ func parseDNS(rawCfg *RawConfig, hosts *trie.DomainTrie, rules []C.Rule) (*DNS,
if net.ParseIP(fb.Addr) != nil { if net.ParseIP(fb.Addr) != nil {
continue continue
} }
host.Insert(fb.Addr, true) _ = host.Insert(fb.Addr, true)
} }
} }
@ -766,12 +764,12 @@ func parseTun(rawTun RawTun, general *General) (*Tun, error) {
var dnsHijack []netip.AddrPort var dnsHijack []netip.AddrPort
for _, dns := range rawTun.DNSHijack { for _, d := range rawTun.DNSHijack {
if _, after, ok := strings.Cut(dns, "://"); ok { if _, after, ok := strings.Cut(d, "://"); ok {
dns = after d = after
} }
addrPort, err := netip.ParseAddrPort(dns) addrPort, err := netip.ParseAddrPort(d)
if err != nil { if err != nil {
return nil, fmt.Errorf("parse dns-hijack url error: %w", err) return nil, fmt.Errorf("parse dns-hijack url error: %w", err)
} }

View file

@ -7,8 +7,6 @@ import (
"github.com/Dreamacro/clash/component/geodata/router" "github.com/Dreamacro/clash/component/geodata/router"
) )
var TunBroadcastAddr = net.IPv4(198, 18, 255, 255)
type RuleExtra struct { type RuleExtra struct {
Network NetWork Network NetWork
SourceIPs []*net.IPNet SourceIPs []*net.IPNet

View file

@ -31,15 +31,15 @@ func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (*D.Msg, error)
ip net.IP ip net.IP
err error err error
) )
if c.r == nil {
// a default ip dns
if ip = net.ParseIP(c.host); ip == nil { if ip = net.ParseIP(c.host); ip == nil {
if c.r == nil {
return nil, fmt.Errorf("dns %s not a valid ip", c.host) return nil, fmt.Errorf("dns %s not a valid ip", c.host)
}
} else { } else {
if ip, err = resolver.ResolveIPWithResolver(c.host, c.r); err != nil { if ip, err = resolver.ResolveIPWithResolver(c.host, c.r); err != nil {
return nil, fmt.Errorf("use default dns resolve failed: %w", err) return nil, fmt.Errorf("use default dns resolve failed: %w", err)
} }
c.host = ip.String()
}
} }
network := "udp" network := "udp"

View file

@ -7,7 +7,6 @@ import (
"github.com/Dreamacro/clash/component/geodata/router" "github.com/Dreamacro/clash/component/geodata/router"
"github.com/Dreamacro/clash/component/mmdb" "github.com/Dreamacro/clash/component/mmdb"
"github.com/Dreamacro/clash/component/trie" "github.com/Dreamacro/clash/component/trie"
C "github.com/Dreamacro/clash/constant"
) )
type fallbackIPFilter interface { type fallbackIPFilter interface {
@ -20,11 +19,7 @@ type geoipFilter struct {
func (gf *geoipFilter) Match(ip net.IP) bool { func (gf *geoipFilter) Match(ip net.IP) bool {
record, _ := mmdb.Instance().Country(ip) record, _ := mmdb.Instance().Country(ip)
return !strings.EqualFold(record.Country.IsoCode, gf.code) && return !strings.EqualFold(record.Country.IsoCode, gf.code) && !ip.IsPrivate()
!ip.IsPrivate() &&
!ip.IsLoopback() &&
!ip.IsUnspecified() &&
!ip.Equal(C.TunBroadcastAddr)
} }
type ipnetFilter struct { type ipnetFilter struct {

2
go.mod
View file

@ -23,7 +23,7 @@ require (
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 golang.org/x/time v0.0.0-20191024005414-555d28b269f0
golang.zx2c4.com/wireguard v0.0.0-20220202223031-3b95c81cc178 golang.zx2c4.com/wireguard v0.0.0-20220310012736-ae6bc4dd64e1
golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477 golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477
google.golang.org/protobuf v1.27.1 google.golang.org/protobuf v1.27.1
gopkg.in/yaml.v2 v2.4.0 gopkg.in/yaml.v2 v2.4.0

4
go.sum
View file

@ -147,8 +147,8 @@ golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1N
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224 h1:Ug9qvr1myri/zFN6xL17LSCBGFDnphBBhzmILHsM5TY= golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224 h1:Ug9qvr1myri/zFN6xL17LSCBGFDnphBBhzmILHsM5TY=
golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI= golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
golang.zx2c4.com/wireguard v0.0.0-20220202223031-3b95c81cc178 h1:Nrf94TOjrvW8nm6N3u2xtbnMZaZudNI9b8nIJH8p8qY= golang.zx2c4.com/wireguard v0.0.0-20220310012736-ae6bc4dd64e1 h1:iuQdvJn3LrXxz3Iony1qBGVS7kEy2uHYnnjHsVbzq/s=
golang.zx2c4.com/wireguard v0.0.0-20220202223031-3b95c81cc178/go.mod h1:TjUWrnD5ATh7bFvmm/ALEJZQ4ivKbETb6pmyj1vUoNI= golang.zx2c4.com/wireguard v0.0.0-20220310012736-ae6bc4dd64e1/go.mod h1:TjUWrnD5ATh7bFvmm/ALEJZQ4ivKbETb6pmyj1vUoNI=
golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477 h1:aGh/leWQnRuYYo3vxSbHKrgnnQogntsZKk//JWR/f44= golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477 h1:aGh/leWQnRuYYo3vxSbHKrgnnQogntsZKk//JWR/f44=
golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477/go.mod h1:4GomF9UyodS7dPzPnrQHtpgekcDiTJISzJ3kOk07Ozs= golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477/go.mod h1:4GomF9UyodS7dPzPnrQHtpgekcDiTJISzJ3kOk07Ozs=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=

View file

@ -329,9 +329,6 @@ func ReCreateTun(tunConf *config.Tun, tcpIn chan<- C.ConnContext, udpIn chan<- *
} }
tunStackListener, err = tun.New(tunConf, tcpIn, udpIn) tunStackListener, err = tun.New(tunConf, tcpIn, udpIn)
if err != nil {
log.Warnln("Failed to start TUN listening: %s", err.Error())
}
} }
// GetPorts return the ports of proxy servers // GetPorts return the ports of proxy servers

View file

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"runtime" "runtime"
"github.com/Dreamacro/clash/common/pool"
"github.com/Dreamacro/clash/listener/tun/device" "github.com/Dreamacro/clash/listener/tun/device"
"github.com/Dreamacro/clash/listener/tun/device/iobased" "github.com/Dreamacro/clash/listener/tun/device/iobased"
@ -19,6 +20,7 @@ type TUN struct {
mtu uint32 mtu uint32
name string name string
offset int offset int
buff []byte
} }
func Open(name string, mtu uint32) (_ device.Device, err error) { func Open(name string, mtu uint32) (_ device.Device, err error) {
@ -37,7 +39,12 @@ func Open(name string, mtu uint32) (_ device.Device, err error) {
defaultMTU = 0 /* auto */ defaultMTU = 0 /* auto */
} }
t := &TUN{name: name, mtu: mtu, offset: offset} t := &TUN{
name: name,
mtu: mtu,
offset: offset,
buff: make([]byte, offset+pool.RelayBufferSize),
}
forcedMTU := defaultMTU forcedMTU := defaultMTU
if t.mtu > 0 { if t.mtu > 0 {
@ -64,14 +71,14 @@ func (t *TUN) Read(packet []byte) (int, error) {
return t.nt.Read(packet, t.offset) return t.nt.Read(packet, t.offset)
} }
buff := make([]byte, t.offset+cap(packet)) n, err := t.nt.Read(t.buff, t.offset)
n, err := t.nt.Read(buff, t.offset)
if err != nil { if err != nil {
return 0, err return 0, err
} }
copy(packet, buff[t.offset:t.offset+n]) _ = t.buff[:t.offset]
copy(packet, t.buff[t.offset:t.offset+n])
return n, err return n, err
} }

View file

@ -5,7 +5,7 @@ import (
"net" "net"
) )
var ROUTES = []string{"1.0.0.0/8", "2.0.0.0/7", "4.0.0.0/6", "8.0.0.0/5", "16.0.0.0/4", "32.0.0.0/3", "64.0.0.0/2", "128.0.0.0/1"} var Routes = []string{"1.0.0.0/8", "2.0.0.0/7", "4.0.0.0/6", "8.0.0.0/5", "16.0.0.0/4", "32.0.0.0/3", "64.0.0.0/2", "128.0.0.0/1"}
func IPv4MaskString(bits int) string { func IPv4MaskString(bits int) string {
m := net.CIDRMask(bits, 32) m := net.CIDRMask(bits, 32)

View file

@ -43,7 +43,7 @@ func ConfigInterfaceAddress(dev device.Device, addr netip.Prefix, forceMTU int,
} }
func configInterfaceRouting(interfaceName string, addr netip.Prefix) error { func configInterfaceRouting(interfaceName string, addr netip.Prefix) error {
routes := append(ROUTES, addr.String()) routes := append(Routes, addr.String())
for _, route := range routes { for _, route := range routes {
if err := execRouterCmd("add", "-inet", route, interfaceName); err != nil { if err := execRouterCmd("add", "-inet", route, interfaceName); err != nil {

View file

@ -36,7 +36,7 @@ func ConfigInterfaceAddress(dev device.Device, addr netip.Prefix, forceMTU int,
func configInterfaceRouting(interfaceName string, addr netip.Prefix) error { func configInterfaceRouting(interfaceName string, addr netip.Prefix) error {
linkIP := addr.Masked().Addr().Next() linkIP := addr.Masked().Addr().Next()
for _, route := range ROUTES { for _, route := range Routes {
if err := execRouterCmd("add", route, interfaceName, linkIP.String()); err != nil { if err := execRouterCmd("add", route, interfaceName, linkIP.String()); err != nil {
return err return err
} }

View file

@ -26,8 +26,8 @@ func GetAutoDetectInterface() (string, error) {
func ConfigInterfaceAddress(dev device.Device, addr netip.Prefix, forceMTU int, autoRoute bool) error { func ConfigInterfaceAddress(dev device.Device, addr netip.Prefix, forceMTU int, autoRoute bool) error {
retryOnFailure := StartedAtBoot() retryOnFailure := StartedAtBoot()
tryTimes := 0 tryTimes := 0
startOver:
var err error var err error
startOver:
if tryTimes > 0 { if tryTimes > 0 {
log.Infoln("Retrying interface configuration after failure because system just booted (T+%v): %v", windows.DurationSinceBoot(), err) log.Infoln("Retrying interface configuration after failure because system just booted (T+%v): %v", windows.DurationSinceBoot(), err)
time.Sleep(time.Second) time.Sleep(time.Second)
@ -35,12 +35,8 @@ startOver:
} }
tryTimes++ tryTimes++
luid := winipcfg.LUID(dev.(*tun.TUN).LUID())
if guid, err1 := luid.GUID(); err1 == nil {
log.Infoln("[wintun]: tun adapter GUID: %s", guid.String())
}
var ( var (
luid = winipcfg.LUID(dev.(*tun.TUN).LUID())
ip = addr.Masked().Addr().Next() ip = addr.Masked().Addr().Next()
addresses = []netip.Prefix{netip.PrefixFrom(ip, addr.Bits())} addresses = []netip.Prefix{netip.PrefixFrom(ip, addr.Bits())}
@ -82,8 +78,12 @@ startOver:
foundDefault6 := false foundDefault6 := false
if autoRoute { if autoRoute {
var allowedIPs []netip.Prefix var (
routeArr := ROUTES allowedIPs []netip.Prefix
// add default
routeArr = []string{"0.0.0.0/0"}
)
for _, route := range routeArr { for _, route := range routeArr {
allowedIPs = append(allowedIPs, netip.MustParsePrefix(route)) allowedIPs = append(allowedIPs, netip.MustParsePrefix(route))
@ -117,7 +117,7 @@ startOver:
deduplicatedRoutes = append(deduplicatedRoutes, &r) deduplicatedRoutes = append(deduplicatedRoutes, &r)
} }
// append the gateway // add gateway
deduplicatedRoutes = append(deduplicatedRoutes, &winipcfg.RouteData{ deduplicatedRoutes = append(deduplicatedRoutes, &winipcfg.RouteData{
Destination: addr.Masked(), Destination: addr.Masked(),
NextHop: addr.Addr(), NextHop: addr.Addr(),
@ -221,7 +221,7 @@ func cleanupAddressesOnDisconnectedInterfaces(family winipcfg.AddressFamily, add
if ip, _ := netip.AddrFromSlice(address.Address.IP()); addrHash[ip] { if ip, _ := netip.AddrFromSlice(address.Address.IP()); addrHash[ip] {
prefix := netip.PrefixFrom(ip, int(address.OnLinkPrefixLength)) prefix := netip.PrefixFrom(ip, int(address.OnLinkPrefixLength))
log.Infoln("Cleaning up stale address %s from interface %s", prefix.String(), iface.FriendlyName()) log.Infoln("Cleaning up stale address %s from interface %s", prefix.String(), iface.FriendlyName())
iface.LUID.DeleteIPAddress(prefix) _ = iface.LUID.DeleteIPAddress(prefix)
} }
} }
} }

View file

@ -5,6 +5,7 @@ import (
"net" "net"
"net/netip" "net/netip"
"github.com/Dreamacro/clash/common/pool"
"github.com/Dreamacro/clash/listener/tun/ipstack/system/mars/tcpip" "github.com/Dreamacro/clash/listener/tun/ipstack/system/mars/tcpip"
) )
@ -26,7 +27,7 @@ func Start(
udp := &UDP{ udp := &UDP{
calls: map[*call]struct{}{}, calls: map[*call]struct{}{},
device: device, device: device,
buf: [65535]byte{}, buf: [pool.UDPBufferSize]byte{},
} }
tcp := &TCP{ tcp := &TCP{
listener: listener, listener: listener,
@ -40,7 +41,7 @@ func Start(
defer tcp.Close() defer tcp.Close()
defer udp.Close() defer udp.Close()
buf := make([]byte, 65535) buf := make([]byte, pool.RelayBufferSize)
for { for {
n, err := device.Read(buf) n, err := device.Read(buf)
@ -137,7 +138,6 @@ func Start(
t.SetSourcePort(port) t.SetSourcePort(port)
t.SetDestinationPort(gatewayPort) t.SetDestinationPort(gatewayPort)
ip.DecTimeToLive()
ip.ResetChecksum() ip.ResetChecksum()
t.ResetChecksum(ip.PseudoSum()) t.ResetChecksum(ip.PseudoSum())
@ -164,7 +164,6 @@ func Start(
ip.SetSourceIP(destination) ip.SetSourceIP(destination)
ip.SetDestinationIP(source) ip.SetDestinationIP(source)
ip.DecTimeToLive()
ip.ResetChecksum() ip.ResetChecksum()
i.ResetChecksum() i.ResetChecksum()
@ -183,7 +182,6 @@ func Start(
ip.SetSourceIP(destination) ip.SetSourceIP(destination)
ip.SetDestinationIP(source) ip.SetDestinationIP(source)
ip.DecTimeToLive()
ip.ResetChecksum() ip.ResetChecksum()
i.ResetChecksum(ip.PseudoSum()) i.ResetChecksum(ip.PseudoSum())

View file

@ -7,6 +7,7 @@ import (
"net/netip" "net/netip"
"sync" "sync"
"github.com/Dreamacro/clash/common/pool"
"github.com/Dreamacro/clash/listener/tun/ipstack/system/mars/tcpip" "github.com/Dreamacro/clash/listener/tun/ipstack/system/mars/tcpip"
) )
@ -24,7 +25,7 @@ type UDP struct {
calls map[*call]struct{} calls map[*call]struct{}
device io.Writer device io.Writer
bufLock sync.Mutex bufLock sync.Mutex
buf [65535]byte buf [pool.UDPBufferSize]byte
} }
func (u *UDP) ReadFrom(buf []byte) (int, net.Addr, net.Addr, error) { func (u *UDP) ReadFrom(buf []byte) (int, net.Addr, net.Addr, error) {

View file

@ -23,22 +23,24 @@ import (
// New TunAdapter // New TunAdapter
func New(tunConf *config.Tun, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.PacketAdapter) (ipstack.Stack, error) { func New(tunConf *config.Tun, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.PacketAdapter) (ipstack.Stack, error) {
devName := tunConf.Device var (
tunAddress = netip.MustParsePrefix("198.18.255.254/16")
devName = tunConf.Device
stackType = tunConf.Stack
autoRoute = tunConf.AutoRoute
mtu = 9000
tunDevice device.Device
tunStack ipstack.Stack
err error
)
if devName == "" { if devName == "" {
devName = generateDeviceName() devName = generateDeviceName()
} }
tunAddress := netip.MustParsePrefix("198.18.255.254/16") // open tun device
autoRoute := tunConf.AutoRoute
stackType := tunConf.Stack
mtu := 9000
var tunDevice device.Device
var tunStack ipstack.Stack
var err error
// new tun device
tunDevice, err = parseDevice(devName, uint32(mtu)) tunDevice, err = parseDevice(devName, uint32(mtu))
if err != nil { if err != nil {
return nil, fmt.Errorf("can't open tun: %w", err) return nil, fmt.Errorf("can't open tun: %w", err)
@ -58,7 +60,8 @@ func New(tunConf *config.Tun, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.
DNSAdds: tunConf.DNSHijack, DNSAdds: tunConf.DNSHijack,
TCPIn: tcpIn, UDPIn: udpIn, TCPIn: tcpIn, UDPIn: udpIn,
}, },
gvisor.WithDefault()) gvisor.WithDefault(),
)
if err != nil { if err != nil {
_ = tunDevice.Close() _ = tunDevice.Close()
@ -68,7 +71,7 @@ func New(tunConf *config.Tun, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.
err = tunDevice.UseIOBased() err = tunDevice.UseIOBased()
if err != nil { if err != nil {
_ = tunDevice.Close() _ = tunDevice.Close()
return nil, fmt.Errorf("can't attach endpoint to tun: %w", err) return nil, fmt.Errorf("can't New system stack: %w", err)
} }
tunStack, err = system.New(tunDevice, tunConf.DNSHijack, tunAddress, tcpIn, udpIn) tunStack, err = system.New(tunDevice, tunConf.DNSHijack, tunAddress, tcpIn, udpIn)
@ -77,7 +80,7 @@ func New(tunConf *config.Tun, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.
return nil, fmt.Errorf("can't New system stack: %w", err) return nil, fmt.Errorf("can't New system stack: %w", err)
} }
default: default:
// ignore it, should never happen // never happen
} }
// setting address and routing // setting address and routing

View file

@ -4,6 +4,7 @@ import (
"strings" "strings"
"github.com/Dreamacro/clash/component/mmdb" "github.com/Dreamacro/clash/component/mmdb"
"github.com/Dreamacro/clash/component/resolver"
C "github.com/Dreamacro/clash/constant" C "github.com/Dreamacro/clash/constant"
) )
@ -29,7 +30,8 @@ func (g *GEOIP) Match(metadata *C.Metadata) bool {
ip.IsUnspecified() || ip.IsUnspecified() ||
ip.IsLoopback() || ip.IsLoopback() ||
ip.IsMulticast() || ip.IsMulticast() ||
C.TunBroadcastAddr.Equal(ip) ip.IsLinkLocalUnicast() ||
resolver.IsFakeBroadcastIP(ip)
} }
record, _ := mmdb.Instance().Country(ip) record, _ := mmdb.Instance().Country(ip)

View file

@ -49,7 +49,7 @@ require (
golang.org/x/tools v0.1.9 // indirect golang.org/x/tools v0.1.9 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224 // indirect golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224 // indirect
golang.zx2c4.com/wireguard v0.0.0-20220202223031-3b95c81cc178 // indirect golang.zx2c4.com/wireguard v0.0.0-20220310012736-ae6bc4dd64e1 // indirect
golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477 // indirect golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477 // indirect
google.golang.org/genproto v0.0.0-20210722135532-667f2b7c528f // indirect google.golang.org/genproto v0.0.0-20210722135532-667f2b7c528f // indirect
google.golang.org/grpc v1.43.0 // indirect google.golang.org/grpc v1.43.0 // indirect

View file

@ -907,8 +907,8 @@ golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1N
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224 h1:Ug9qvr1myri/zFN6xL17LSCBGFDnphBBhzmILHsM5TY= golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224 h1:Ug9qvr1myri/zFN6xL17LSCBGFDnphBBhzmILHsM5TY=
golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI= golang.zx2c4.com/wintun v0.0.0-20211104114900-415007cec224/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
golang.zx2c4.com/wireguard v0.0.0-20220202223031-3b95c81cc178 h1:Nrf94TOjrvW8nm6N3u2xtbnMZaZudNI9b8nIJH8p8qY= golang.zx2c4.com/wireguard v0.0.0-20220310012736-ae6bc4dd64e1 h1:iuQdvJn3LrXxz3Iony1qBGVS7kEy2uHYnnjHsVbzq/s=
golang.zx2c4.com/wireguard v0.0.0-20220202223031-3b95c81cc178/go.mod h1:TjUWrnD5ATh7bFvmm/ALEJZQ4ivKbETb6pmyj1vUoNI= golang.zx2c4.com/wireguard v0.0.0-20220310012736-ae6bc4dd64e1/go.mod h1:TjUWrnD5ATh7bFvmm/ALEJZQ4ivKbETb6pmyj1vUoNI=
golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477 h1:aGh/leWQnRuYYo3vxSbHKrgnnQogntsZKk//JWR/f44= golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477 h1:aGh/leWQnRuYYo3vxSbHKrgnnQogntsZKk//JWR/f44=
golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477/go.mod h1:4GomF9UyodS7dPzPnrQHtpgekcDiTJISzJ3kOk07Ozs= golang.zx2c4.com/wireguard/windows v0.5.4-0.20220201002028-22d54a5eb477/go.mod h1:4GomF9UyodS7dPzPnrQHtpgekcDiTJISzJ3kOk07Ozs=
google.golang.org/api v0.0.0-20160322025152-9bf6e6e569ff/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= google.golang.org/api v0.0.0-20160322025152-9bf6e6e569ff/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0=

View file

@ -144,7 +144,7 @@ func preHandleMetadata(metadata *C.Metadata) error {
// redir-host should lookup the hosts // redir-host should lookup the hosts
metadata.DstIP = node.Data.(net.IP) metadata.DstIP = node.Data.(net.IP)
} }
} else if resolver.IsFakeIP(metadata.DstIP) && !C.TunBroadcastAddr.Equal(metadata.DstIP) { } else if resolver.IsFakeIP(metadata.DstIP) {
return fmt.Errorf("fake DNS record %s missing", metadata.DstIP) return fmt.Errorf("fake DNS record %s missing", metadata.DstIP)
} }
} }