Clash.Meta/component/process/process.go

76 lines
1.5 KiB
Go
Raw Normal View History

package process
import (
"errors"
"net"
2022-04-20 01:52:51 +08:00
"net/netip"
2022-04-09 17:54:01 +08:00
"runtime"
2022-03-13 01:21:23 +08:00
2022-04-20 01:52:51 +08:00
"github.com/Dreamacro/clash/common/nnip"
2022-03-13 01:21:23 +08:00
C "github.com/Dreamacro/clash/constant"
)
var (
ErrInvalidNetwork = errors.New("invalid network")
ErrPlatformNotSupport = errors.New("not support on this platform")
ErrNotFound = errors.New("process not found")
)
const (
TCP = "tcp"
UDP = "udp"
)
2022-04-20 01:52:51 +08:00
func FindProcessName(network string, srcIP netip.Addr, srcPort int) (string, error) {
return findProcessName(network, srcIP, srcPort)
}
2022-03-13 01:21:23 +08:00
func ShouldFindProcess(metadata *C.Metadata) bool {
2022-04-09 17:54:01 +08:00
if runtime.GOOS == "android" {
return false
}
2022-04-20 01:31:33 +08:00
if metadata.Process != "" || metadata.ProcessPath != "" {
2022-03-13 01:21:23 +08:00
return false
}
for _, ip := range localIPs {
2022-04-20 01:52:51 +08:00
if ip == metadata.SrcIP {
2022-03-13 01:21:23 +08:00
return true
}
}
return false
}
2022-04-20 01:52:51 +08:00
func AppendLocalIPs(ip ...netip.Addr) {
localIPs = append(ip, localIPs...)
}
2022-04-20 01:52:51 +08:00
func getLocalIPs() []netip.Addr {
ips := []netip.Addr{netip.IPv4Unspecified(), netip.IPv6Unspecified()}
2022-03-13 01:21:23 +08:00
netInterfaces, err := net.Interfaces()
if err != nil {
2022-04-20 01:52:51 +08:00
ips = append(ips, netip.AddrFrom4([4]byte{127, 0, 0, 1}), nnip.IpToAddr(net.IPv6loopback))
2022-03-13 01:21:23 +08:00
return ips
}
for i := 0; i < len(netInterfaces); i++ {
if (netInterfaces[i].Flags & net.FlagUp) != 0 {
adds, _ := netInterfaces[i].Addrs()
for _, address := range adds {
if ipNet, ok := address.(*net.IPNet); ok {
2022-04-20 01:52:51 +08:00
ips = append(ips, nnip.IpToAddr(ipNet.IP))
2022-03-13 01:21:23 +08:00
}
}
}
}
return ips
}
2022-04-20 01:52:51 +08:00
var localIPs []netip.Addr
2022-03-13 01:21:23 +08:00
func init() {
localIPs = getLocalIPs()
}