mihomo/component/process/process.go

85 lines
1.7 KiB
Go
Raw Normal View History

package process
import (
"errors"
"github.com/Dreamacro/clash/common/nnip"
C "github.com/Dreamacro/clash/constant"
"net"
2022-04-20 01:52:51 +08:00
"net/netip"
)
var (
ErrInvalidNetwork = errors.New("invalid network")
ErrPlatformNotSupport = errors.New("not support on this platform")
ErrNotFound = errors.New("process not found")
enableFindProcess = true
)
const (
TCP = "tcp"
UDP = "udp"
)
func EnableFindProcess(e bool) {
enableFindProcess = e
}
func FindProcessName(network string, srcIP netip.Addr, srcPort int) (int32, string, error) {
return findProcessName(network, srcIP, srcPort)
}
2022-03-13 01:21:23 +08:00
func FindUid(network string, srcIP netip.Addr, srcPort int) (int32, error) {
_, uid, err := resolveSocketByNetlink(network, srcIP, srcPort)
if err != nil {
return -1, err
}
return uid, nil
}
2022-03-13 01:21:23 +08:00
func ShouldFindProcess(metadata *C.Metadata) bool {
if !enableFindProcess || 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()
}