From 9272d02149adf82d35428713750cc82778972f35 Mon Sep 17 00:00:00 2001 From: adlyq Date: Sat, 28 May 2022 19:26:42 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E5=90=88=E5=B9=B6=E9=83=A8?= =?UTF-8?q?=E5=88=86android=E4=BB=A3=E7=A0=81=E5=85=A5linux=20&&=20ip=20?= =?UTF-8?q?=E4=BD=BF=E7=94=A8netlink=E9=85=8D=E7=BD=AE=E8=B7=AF=E7=94=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- component/process/process_android.go | 228 ------------------ component/process/process_linux.go | 32 ++- .../tun/ipstack/commons/router_android.go | 44 +++- listener/tun/ipstack/commons/router_linux.go | 68 +++++- 4 files changed, 119 insertions(+), 253 deletions(-) delete mode 100644 component/process/process_android.go diff --git a/component/process/process_android.go b/component/process/process_android.go deleted file mode 100644 index 6013ecd3..00000000 --- a/component/process/process_android.go +++ /dev/null @@ -1,228 +0,0 @@ -package process - -import ( - "bytes" - "encoding/binary" - "fmt" - "net" - "net/netip" - "os" - "path" - "path/filepath" - "strings" - "syscall" - "unicode" - "unsafe" - - "github.com/Dreamacro/clash/common/pool" -) - -// from https://github.com/vishvananda/netlink/blob/bca67dfc8220b44ef582c9da4e9172bf1c9ec973/nl/nl_linux.go#L52-L62 -var nativeEndian = func() binary.ByteOrder { - var x uint32 = 0x01020304 - if *(*byte)(unsafe.Pointer(&x)) == 0x01 { - return binary.BigEndian - } - - return binary.LittleEndian -}() - -const ( - sizeOfSocketDiagRequest = syscall.SizeofNlMsghdr + 8 + 48 - socketDiagByFamily = 20 - pathProc = "/proc" -) - -func findProcessName(network string, ip netip.Addr, srcPort int) (int32, string, error) { - inode, uid, err := resolveSocketByNetlink(network, ip, srcPort) - if err != nil { - return -1, "", err - } - - pp, err := resolveProcessNameByProcSearch(inode, uid) - return uid, pp, err -} - -func resolveSocketByNetlink(network string, ip netip.Addr, srcPort int) (int32, int32, error) { - var family byte - var protocol byte - - switch network { - case TCP: - protocol = syscall.IPPROTO_TCP - case UDP: - protocol = syscall.IPPROTO_UDP - default: - return 0, 0, ErrInvalidNetwork - } - - if ip.Is4() { - family = syscall.AF_INET - } else { - family = syscall.AF_INET6 - } - - req := packSocketDiagRequest(family, protocol, ip, uint16(srcPort)) - - socket, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_DGRAM, syscall.NETLINK_INET_DIAG) - if err != nil { - return 0, 0, fmt.Errorf("dial netlink: %w", err) - } - defer syscall.Close(socket) - - _ = syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &syscall.Timeval{Usec: 100}) - _ = syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &syscall.Timeval{Usec: 100}) - - if err := syscall.Connect(socket, &syscall.SockaddrNetlink{ - Family: syscall.AF_NETLINK, - Pad: 0, - Pid: 0, - Groups: 0, - }); err != nil { - return 0, 0, err - } - - if _, err := syscall.Write(socket, req); err != nil { - return 0, 0, fmt.Errorf("write request: %w", err) - } - - rb := pool.Get(pool.RelayBufferSize) - defer pool.Put(rb) - - n, err := syscall.Read(socket, rb) - if err != nil { - return 0, 0, fmt.Errorf("read response: %w", err) - } - - messages, err := syscall.ParseNetlinkMessage(rb[:n]) - if err != nil { - return 0, 0, fmt.Errorf("parse netlink message: %w", err) - } else if len(messages) == 0 { - return 0, 0, fmt.Errorf("unexcepted netlink response") - } - - message := messages[0] - if message.Header.Type&syscall.NLMSG_ERROR != 0 { - return 0, 0, fmt.Errorf("netlink message: NLMSG_ERROR") - } - - uid, inode := unpackSocketDiagResponse(&messages[0]) - if uid < 0 || inode < 0 { - return 0, 0, fmt.Errorf("invalid uid(%d) or inode(%d)", uid, inode) - } - - return uid, inode, nil -} - -func packSocketDiagRequest(family, protocol byte, source netip.Addr, sourcePort uint16) []byte { - s := make([]byte, 16) - - copy(s, source.AsSlice()) - - buf := make([]byte, sizeOfSocketDiagRequest) - - nativeEndian.PutUint32(buf[0:4], sizeOfSocketDiagRequest) - nativeEndian.PutUint16(buf[4:6], socketDiagByFamily) - nativeEndian.PutUint16(buf[6:8], syscall.NLM_F_REQUEST|syscall.NLM_F_DUMP) - nativeEndian.PutUint32(buf[8:12], 0) - nativeEndian.PutUint32(buf[12:16], 0) - - buf[16] = family - buf[17] = protocol - buf[18] = 0 - buf[19] = 0 - nativeEndian.PutUint32(buf[20:24], 0xFFFFFFFF) - - binary.BigEndian.PutUint16(buf[24:26], sourcePort) - binary.BigEndian.PutUint16(buf[26:28], 0) - - copy(buf[28:44], s) - copy(buf[44:60], net.IPv6zero) - - nativeEndian.PutUint32(buf[60:64], 0) - nativeEndian.PutUint64(buf[64:72], 0xFFFFFFFFFFFFFFFF) - - return buf -} - -func unpackSocketDiagResponse(msg *syscall.NetlinkMessage) (inode, uid int32) { - if len(msg.Data) < 72 { - return 0, 0 - } - - data := msg.Data - - uid = int32(nativeEndian.Uint32(data[64:68])) - inode = int32(nativeEndian.Uint32(data[68:72])) - - return -} - -func resolveProcessNameByProcSearch(inode, uid int32) (string, error) { - files, err := os.ReadDir(pathProc) - if err != nil { - return "", err - } - - buffer := make([]byte, syscall.PathMax) - socket := []byte(fmt.Sprintf("socket:[%d]", inode)) - - for _, f := range files { - if !f.IsDir() || !isPid(f.Name()) { - continue - } - - info, err := f.Info() - if err != nil { - return "", err - } - if info.Sys().(*syscall.Stat_t).Uid != uint32(uid) { - continue - } - - processPath := path.Join(pathProc, f.Name()) - fdPath := path.Join(processPath, "fd") - - fds, err := os.ReadDir(fdPath) - if err != nil { - continue - } - - for _, fd := range fds { - n, err := syscall.Readlink(path.Join(fdPath, fd.Name()), buffer) - if err != nil { - continue - } - - if bytes.Equal(buffer[:n], socket) { - cmdline, err := os.ReadFile(path.Join(processPath, "cmdline")) - if err != nil { - return "", err - } - - return splitCmdline(cmdline), nil - } - } - } - - return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode) -} - -func splitCmdline(cmdline []byte) string { - cmdline = bytes.Trim(cmdline, " ") - - idx := bytes.IndexFunc(cmdline, func(r rune) bool { - return unicode.IsControl(r) || unicode.IsSpace(r) - }) - - if idx == -1 { - return filepath.Base(string(cmdline)) - } - return filepath.Base(string(cmdline[:idx])) -} - -func isPid(s string) bool { - return strings.IndexFunc(s, func(r rune) bool { - return !unicode.IsDigit(r) - }) == -1 -} diff --git a/component/process/process_linux.go b/component/process/process_linux.go index 4f937ba0..c2809da1 100644 --- a/component/process/process_linux.go +++ b/component/process/process_linux.go @@ -1,5 +1,3 @@ -//go:build !android - package process import ( @@ -10,6 +8,8 @@ import ( "net/netip" "os" "path" + "path/filepath" + "runtime" "strings" "syscall" "unicode" @@ -198,8 +198,19 @@ func resolveProcessNameByProcSearch(inode, uid int32) (string, error) { continue } - if bytes.Equal(buffer[:n], socket) { - return os.Readlink(path.Join(processPath, "exe")) + if runtime.GOOS == "android" { + if bytes.Equal(buffer[:n], socket) { + cmdline, err := os.ReadFile(path.Join(processPath, "cmdline")) + if err != nil { + return "", err + } + + return splitCmdline(cmdline), nil + } + } else { + if bytes.Equal(buffer[:n], socket) { + return os.Readlink(path.Join(processPath, "exe")) + } } } } @@ -207,6 +218,19 @@ func resolveProcessNameByProcSearch(inode, uid int32) (string, error) { return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode) } +func splitCmdline(cmdline []byte) string { + cmdline = bytes.Trim(cmdline, " ") + + idx := bytes.IndexFunc(cmdline, func(r rune) bool { + return unicode.IsControl(r) || unicode.IsSpace(r) + }) + + if idx == -1 { + return filepath.Base(string(cmdline)) + } + return filepath.Base(string(cmdline[:idx])) +} + func isPid(s string) bool { return strings.IndexFunc(s, func(r rune) bool { return !unicode.IsDigit(r) diff --git a/listener/tun/ipstack/commons/router_android.go b/listener/tun/ipstack/commons/router_android.go index 4dc351fc..812af547 100644 --- a/listener/tun/ipstack/commons/router_android.go +++ b/listener/tun/ipstack/commons/router_android.go @@ -5,8 +5,9 @@ import ( "github.com/Dreamacro/clash/common/cmd" "github.com/Dreamacro/clash/listener/tun/device" "github.com/Dreamacro/clash/log" + "github.com/vishvananda/netlink" + "net" "net/netip" - "strconv" "strings" ) @@ -30,38 +31,63 @@ func ConfigInterfaceAddress(dev device.Device, addr netip.Prefix, forceMTU int, ip = addr.Masked().Addr().Next() ) - _, err := cmd.ExecCmd(fmt.Sprintf("ip addr add %s dev %s", ip.String(), interfaceName)) + metaLink, err := netlink.LinkByName(interfaceName) if err != nil { return err } - _, err = cmd.ExecCmd(fmt.Sprintf("ip link set %s up", interfaceName)) + naddr, err := netlink.ParseAddr(addr.String()) if err != nil { return err } - if err = execRouterCmd("add", addr.Masked().String(), interfaceName, ip.String(), "main"); err != nil { + if err = netlink.AddrAdd(metaLink, naddr); err != nil { + return err + } + + if err = netlink.LinkSetUp(metaLink); err != nil { + return err + } + + if err = netlink.RouteAdd(&netlink.Route{ + LinkIndex: metaLink.Attrs().Index, + Scope: netlink.SCOPE_LINK, + Protocol: 2, + Src: ip.AsSlice(), + Table: 254, + }); err != nil { return err } if autoRoute { - err = configInterfaceRouting(interfaceName, addr) + err = configInterfaceRouting(metaLink.Attrs().Index, interfaceName, ip) } return err } -func configInterfaceRouting(interfaceName string, addr netip.Prefix) error { - linkIP := addr.Masked().Addr().Next() +func configInterfaceRouting(index int, interfaceName string, ip netip.Addr) error { const tableId = 1981801 for _, route := range defaultRoutes { - if err := execRouterCmd("add", route, interfaceName, linkIP.String(), strconv.Itoa(tableId)); err != nil { + _, ipn, err := net.ParseCIDR(route) + if err != nil { + return err + } + + if err := netlink.RouteAdd(&netlink.Route{ + LinkIndex: index, + Scope: netlink.SCOPE_LINK, + Protocol: 2, + Src: ip.AsSlice(), + Dst: ipn, + Table: 254, + }); err != nil { return err } } execAddRuleCmd(fmt.Sprintf("lookup main pref 9000")) execAddRuleCmd(fmt.Sprintf("from 0.0.0.0 iif lo uidrange 0-4294967294 lookup %d pref 9001", tableId)) - execAddRuleCmd(fmt.Sprintf("from %s iif lo uidrange 0-4294967294 lookup %d pref 9002", linkIP, tableId)) + execAddRuleCmd(fmt.Sprintf("from %s iif lo uidrange 0-4294967294 lookup %d pref 9002", ip, tableId)) execAddRuleCmd(fmt.Sprintf("from all iif %s lookup main suppress_prefixlength 0 pref 9003", interfaceName)) execAddRuleCmd(fmt.Sprintf("not from all iif lo lookup %d pref 9004", tableId)) diff --git a/listener/tun/ipstack/commons/router_linux.go b/listener/tun/ipstack/commons/router_linux.go index b34dd5a4..9428accb 100644 --- a/listener/tun/ipstack/commons/router_linux.go +++ b/listener/tun/ipstack/commons/router_linux.go @@ -6,15 +6,33 @@ import ( "fmt" "github.com/Dreamacro/clash/common/cmd" "github.com/Dreamacro/clash/listener/tun/device" + "github.com/vishvananda/netlink" + "net" "net/netip" ) func GetAutoDetectInterface() (string, error) { - execCmd, err := cmd.ExecCmd("bash -c ip route show | grep 'default via' | awk -F ' ' 'NR==1{print $5}' | xargs echo -n") - if execCmd == "" { - return "", fmt.Errorf("interface not found") + routes, err := netlink.RouteList(nil, netlink.FAMILY_V4) + if err != nil { + return "", err } - return execCmd, err + + for _, route := range routes { + if route.Dst == nil { + lk, err := netlink.LinkByIndex(route.LinkIndex) + if err != nil { + return "", err + } + + if lk.Type() == "tuntap" { + continue + } + + return lk.Attrs().Name, nil + } + } + + return "", fmt.Errorf("interface not found") } func ConfigInterfaceAddress(dev device.Device, addr netip.Prefix, forceMTU int, autoRoute bool) error { @@ -23,29 +41,55 @@ func ConfigInterfaceAddress(dev device.Device, addr netip.Prefix, forceMTU int, ip = addr.Masked().Addr().Next() ) - if _, err := cmd.ExecCmd(fmt.Sprintf("ip addr add %s dev %s", ip.String(), interfaceName)); err != nil { + metaLink, err := netlink.LinkByName(interfaceName) + if err != nil { return err } - if _, err := cmd.ExecCmd(fmt.Sprintf("ip link set %s up", interfaceName)); err != nil { + naddr, err := netlink.ParseAddr(addr.String()) + if err != nil { return err } - if err := execRouterCmd("add", addr.Masked().String(), interfaceName, ip.String(), "main"); err != nil { + if err = netlink.AddrAdd(metaLink, naddr); err != nil { + return err + } + + if err = netlink.LinkSetUp(metaLink); err != nil { + return err + } + + if err = netlink.RouteAdd(&netlink.Route{ + LinkIndex: metaLink.Attrs().Index, + Scope: netlink.SCOPE_LINK, + Protocol: 2, + Src: ip.AsSlice(), + Table: 254, + }); err != nil { return err } if autoRoute { - _ = configInterfaceRouting(interfaceName, addr) + _ = configInterfaceRouting(metaLink.Attrs().Index, interfaceName, ip) } return nil } -func configInterfaceRouting(interfaceName string, addr netip.Prefix) error { - linkIP := addr.Masked().Addr().Next() - +func configInterfaceRouting(index int, interfaceName string, ip netip.Addr) error { for _, route := range defaultRoutes { - if err := execRouterCmd("add", route, interfaceName, linkIP.String(), "main"); err != nil { + _, ipn, err := net.ParseCIDR(route) + if err != nil { + return err + } + + if err := netlink.RouteAdd(&netlink.Route{ + LinkIndex: index, + Scope: netlink.SCOPE_LINK, + Protocol: 2, + Src: ip.AsSlice(), + Dst: ipn, + Table: 254, + }); err != nil { return err } }