Skip to content

Commit

Permalink
Chore: move find connection process to tunnel (#2016)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kr328 committed Mar 12, 2022
1 parent 9683c29 commit b866f06
Show file tree
Hide file tree
Showing 16 changed files with 84 additions and 64 deletions.
3 changes: 1 addition & 2 deletions component/process/process_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package process
import (
"encoding/binary"
"net"
"path/filepath"
"syscall"
"unsafe"

Expand Down Expand Up @@ -96,7 +95,7 @@ func getExecPathFromPID(pid uint32) (string, error) {
return "", errno
}

return filepath.Base(unix.ByteSliceToString(buf)), nil
return unix.ByteSliceToString(buf), nil
}

func readNativeUint32(b []byte) uint32 {
Expand Down
3 changes: 1 addition & 2 deletions component/process/process_freebsd_amd64.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"encoding/binary"
"fmt"
"net"
"path/filepath"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -77,7 +76,7 @@ func getExecPathFromPID(pid uint32) (string, error) {
return "", errno
}

return filepath.Base(string(buf[:size-1])), nil
return string(buf[:size-1]), nil
}

func readNativeUint32(b []byte) uint32 {
Expand Down
21 changes: 3 additions & 18 deletions component/process/process_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"net"
"os"
"path"
"path/filepath"
"strings"
"syscall"
"unicode"
Expand Down Expand Up @@ -68,9 +67,8 @@ func resolveSocketByNetlink(network string, ip net.IP, srcPort int) (int32, int3
}
defer syscall.Close(socket)

syscall.SetNonblock(socket, true)
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &syscall.Timeval{Usec: 50})
syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &syscall.Timeval{Usec: 50})
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,
Expand Down Expand Up @@ -198,27 +196,14 @@ func resolveProcessNameByProcSearch(inode, uid int32) (string, error) {
}

if bytes.Equal(buffer[:n], socket) {
cmdline, err := os.ReadFile(path.Join(processPath, "cmdline"))
if err != nil {
return "", err
}

return splitCmdline(cmdline), nil
return os.Readlink(path.Join(processPath, "exe"))
}
}
}

return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode)
}

func splitCmdline(cmdline []byte) string {
idx := bytes.IndexFunc(cmdline, func(r rune) bool {
return unicode.IsControl(r) || unicode.IsSpace(r)
})

return filepath.Base(string(cmdline[:idx]))
}

func isPid(s string) bool {
return strings.IndexFunc(s, func(r rune) bool {
return !unicode.IsDigit(r)
Expand Down
3 changes: 1 addition & 2 deletions component/process/process_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package process
import (
"fmt"
"net"
"path/filepath"
"sync"
"syscall"
"unsafe"
Expand Down Expand Up @@ -220,5 +219,5 @@ func getExecPathFromPID(pid uint32) (string, error) {
if r1 == 0 {
return "", err
}
return filepath.Base(syscall.UTF16ToString(buf[:size])), nil
return syscall.UTF16ToString(buf[:size]), nil
}
19 changes: 10 additions & 9 deletions constant/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,16 @@ func (t Type) MarshalJSON() ([]byte, error) {

// Metadata is used to store connection address
type Metadata struct {
NetWork NetWork `json:"network"`
Type Type `json:"type"`
SrcIP net.IP `json:"sourceIP"`
DstIP net.IP `json:"destinationIP"`
SrcPort string `json:"sourcePort"`
DstPort string `json:"destinationPort"`
AddrType int `json:"-"`
Host string `json:"host"`
DNSMode DNSMode `json:"dnsMode"`
NetWork NetWork `json:"network"`
Type Type `json:"type"`
SrcIP net.IP `json:"sourceIP"`
DstIP net.IP `json:"destinationIP"`
SrcPort string `json:"sourcePort"`
DstPort string `json:"destinationPort"`
AddrType int `json:"-"`
Host string `json:"host"`
DNSMode DNSMode `json:"dnsMode"`
ProcessPath string `json:"processPath"`
}

func (m *Metadata) RemoteAddress() string {
Expand Down
4 changes: 4 additions & 0 deletions constant/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const (
SrcPort
DstPort
Process
ProcessPath
MATCH
)

Expand All @@ -36,6 +37,8 @@ func (rt RuleType) String() string {
return "DstPort"
case Process:
return "Process"
case ProcessPath:
return "ProcessPath"
case MATCH:
return "Match"
default:
Expand All @@ -49,4 +52,5 @@ type Rule interface {
Adapter() string
Payload() string
ShouldResolveIP() bool
ShouldFindProcess() bool
}
4 changes: 4 additions & 0 deletions rule/domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ func (d *Domain) ShouldResolveIP() bool {
return false
}

func (d *Domain) ShouldFindProcess() bool {
return false
}

func NewDomain(domain string, adapter string) *Domain {
return &Domain{
domain: strings.ToLower(domain),
Expand Down
4 changes: 4 additions & 0 deletions rule/domain_keyword.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ func (dk *DomainKeyword) ShouldResolveIP() bool {
return false
}

func (dk *DomainKeyword) ShouldFindProcess() bool {
return false
}

func NewDomainKeyword(keyword string, adapter string) *DomainKeyword {
return &DomainKeyword{
keyword: strings.ToLower(keyword),
Expand Down
4 changes: 4 additions & 0 deletions rule/domain_suffix.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ func (ds *DomainSuffix) ShouldResolveIP() bool {
return false
}

func (ds *DomainSuffix) ShouldFindProcess() bool {
return false
}

func NewDomainSuffix(suffix string, adapter string) *DomainSuffix {
return &DomainSuffix{
suffix: strings.ToLower(suffix),
Expand Down
4 changes: 4 additions & 0 deletions rule/final.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ func (f *Match) ShouldResolveIP() bool {
return false
}

func (f *Match) ShouldFindProcess() bool {
return false
}

func NewMatch(adapter string) *Match {
return &Match{
adapter: adapter,
Expand Down
4 changes: 4 additions & 0 deletions rule/geoip.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ func (g *GEOIP) ShouldResolveIP() bool {
return !g.noResolveIP
}

func (g *GEOIP) ShouldFindProcess() bool {
return false
}

func NewGEOIP(country string, adapter string, noResolveIP bool) *GEOIP {
geoip := &GEOIP{
country: country,
Expand Down
4 changes: 4 additions & 0 deletions rule/ipcidr.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ func (i *IPCIDR) ShouldResolveIP() bool {
return !i.noResolveIP
}

func (i *IPCIDR) ShouldFindProcess() bool {
return false
}

func NewIPCIDR(s string, adapter string, opts ...IPCIDROption) (*IPCIDR, error) {
_, ipnet, err := net.ParseCIDR(s)
if err != nil {
Expand Down
4 changes: 3 additions & 1 deletion rule/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ func ParseRule(tp, payload, target string, params []string) (C.Rule, error) {
case "DST-PORT":
parsed, parseErr = NewPort(payload, target, false)
case "PROCESS-NAME":
parsed, parseErr = NewProcess(payload, target)
parsed, parseErr = NewProcess(payload, target, true)
case "PROCESS-PATH":
parsed, parseErr = NewProcess(payload, target, false)
case "MATCH":
parsed = NewMatch(target)
default:
Expand Down
4 changes: 4 additions & 0 deletions rule/port.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ func (p *Port) ShouldResolveIP() bool {
return false
}

func (p *Port) ShouldFindProcess() bool {
return false
}

func NewPort(port string, adapter string, isSource bool) (*Port, error) {
_, err := strconv.ParseUint(port, 10, 16)
if err != nil {
Expand Down
45 changes: 15 additions & 30 deletions rule/process.go
Original file line number Diff line number Diff line change
@@ -1,48 +1,28 @@
package rules

import (
"fmt"
"strconv"
"path/filepath"
"strings"

"github.com/Dreamacro/clash/common/cache"
"github.com/Dreamacro/clash/component/process"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/log"
)

var processCache = cache.NewLRUCache(cache.WithAge(2), cache.WithSize(64))

type Process struct {
adapter string
process string
adapter string
process string
nameOnly bool
}

func (ps *Process) RuleType() C.RuleType {
return C.Process
}

func (ps *Process) Match(metadata *C.Metadata) bool {
key := fmt.Sprintf("%s:%s:%s", metadata.NetWork.String(), metadata.SrcIP.String(), metadata.SrcPort)
cached, hit := processCache.Get(key)
if !hit {
srcPort, err := strconv.Atoi(metadata.SrcPort)
if err != nil {
processCache.Set(key, "")
return false
}

name, err := process.FindProcessName(metadata.NetWork.String(), metadata.SrcIP, srcPort)
if err != nil {
log.Debugln("[Rule] find process name %s error: %s", C.Process.String(), err.Error())
}

processCache.Set(key, name)

cached = name
if ps.nameOnly {
return strings.EqualFold(filepath.Base(metadata.ProcessPath), ps.process)
}

return strings.EqualFold(cached.(string), ps.process)
return strings.EqualFold(metadata.ProcessPath, ps.process)
}

func (ps *Process) Adapter() string {
Expand All @@ -57,9 +37,14 @@ func (ps *Process) ShouldResolveIP() bool {
return false
}

func NewProcess(process string, adapter string) (*Process, error) {
func (ps *Process) ShouldFindProcess() bool {
return true
}

func NewProcess(process string, adapter string, nameOnly bool) (*Process, error) {
return &Process{
adapter: adapter,
process: process,
adapter: adapter,
process: process,
nameOnly: nameOnly,
}, nil
}
18 changes: 18 additions & 0 deletions tunnel/tunnel.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import (
"fmt"
"net"
"runtime"
"strconv"
"sync"
"time"

"github.com/Dreamacro/clash/adapter/inbound"
"github.com/Dreamacro/clash/component/nat"
P "github.com/Dreamacro/clash/component/process"
"github.com/Dreamacro/clash/component/resolver"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/constant/provider"
Expand Down Expand Up @@ -308,6 +310,7 @@ func match(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
defer configMux.RUnlock()

var resolved bool
var processFound bool

if node := resolver.DefaultHosts.Search(metadata.Host); node != nil {
ip := node.Data.(net.IP)
Expand All @@ -327,6 +330,21 @@ func match(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
resolved = true
}

if !processFound && rule.ShouldFindProcess() {
processFound = true

srcPort, err := strconv.Atoi(metadata.SrcPort)
if err == nil {
path, err := P.FindProcessName(metadata.NetWork.String(), metadata.SrcIP, srcPort)
if err != nil {
log.Debugln("[Process] find process %s: %v", metadata.String(), err)
} else {
log.Debugln("[Process] %s from process %s", metadata.String(), path)
metadata.ProcessPath = path
}
}
}

if rule.Match(metadata) {
adapter, ok := proxies[rule.Adapter()]
if !ok {
Expand Down

0 comments on commit b866f06

Please sign in to comment.