Chore: move find process name to a single part
This commit is contained in:
21
component/process/process.go
Normal file
21
component/process/process.go
Normal file
@ -0,0 +1,21 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
func FindProcessName(network string, srcIP net.IP, srcPort int) (string, error) {
|
||||
return findProcessName(network, srcIP, srcPort)
|
||||
}
|
107
component/process/process_darwin.go
Normal file
107
component/process/process_darwin.go
Normal file
@ -0,0 +1,107 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
procpidpathinfo = 0xb
|
||||
procpidpathinfosize = 1024
|
||||
proccallnumpidinfo = 0x2
|
||||
)
|
||||
|
||||
func findProcessName(network string, ip net.IP, port int) (string, error) {
|
||||
var spath string
|
||||
switch network {
|
||||
case TCP:
|
||||
spath = "net.inet.tcp.pcblist_n"
|
||||
case UDP:
|
||||
spath = "net.inet.udp.pcblist_n"
|
||||
default:
|
||||
return "", ErrInvalidNetwork
|
||||
}
|
||||
|
||||
isIPv4 := ip.To4() != nil
|
||||
|
||||
value, err := syscall.Sysctl(spath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
buf := []byte(value)
|
||||
|
||||
// from darwin-xnu/bsd/netinet/in_pcblist.c:get_pcblist_n
|
||||
// size/offset are round up (aligned) to 8 bytes in darwin
|
||||
// rup8(sizeof(xinpcb_n)) + rup8(sizeof(xsocket_n)) +
|
||||
// 2 * rup8(sizeof(xsockbuf_n)) + rup8(sizeof(xsockstat_n))
|
||||
itemSize := 384
|
||||
if network == TCP {
|
||||
// rup8(sizeof(xtcpcb_n))
|
||||
itemSize += 208
|
||||
}
|
||||
// skip the first xinpgen(24 bytes) block
|
||||
for i := 24; i+itemSize <= len(buf); i += itemSize {
|
||||
// offset of xinpcb_n and xsocket_n
|
||||
inp, so := i, i+104
|
||||
|
||||
srcPort := binary.BigEndian.Uint16(buf[inp+18 : inp+20])
|
||||
if uint16(port) != srcPort {
|
||||
continue
|
||||
}
|
||||
|
||||
// xinpcb_n.inp_vflag
|
||||
flag := buf[inp+44]
|
||||
|
||||
var srcIP net.IP
|
||||
switch {
|
||||
case flag&0x1 > 0 && isIPv4:
|
||||
// ipv4
|
||||
srcIP = net.IP(buf[inp+76 : inp+80])
|
||||
case flag&0x2 > 0 && !isIPv4:
|
||||
// ipv6
|
||||
srcIP = net.IP(buf[inp+64 : inp+80])
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
if !ip.Equal(srcIP) {
|
||||
continue
|
||||
}
|
||||
|
||||
// xsocket_n.so_last_pid
|
||||
pid := readNativeUint32(buf[so+68 : so+72])
|
||||
return getExecPathFromPID(pid)
|
||||
}
|
||||
|
||||
return "", ErrNotFound
|
||||
}
|
||||
|
||||
func getExecPathFromPID(pid uint32) (string, error) {
|
||||
buf := make([]byte, procpidpathinfosize)
|
||||
_, _, errno := syscall.Syscall6(
|
||||
syscall.SYS_PROC_INFO,
|
||||
proccallnumpidinfo,
|
||||
uintptr(pid),
|
||||
procpidpathinfo,
|
||||
0,
|
||||
uintptr(unsafe.Pointer(&buf[0])),
|
||||
procpidpathinfosize)
|
||||
if errno != 0 {
|
||||
return "", errno
|
||||
}
|
||||
firstZero := bytes.IndexByte(buf, 0)
|
||||
if firstZero <= 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
return filepath.Base(string(buf[:firstZero])), nil
|
||||
}
|
||||
|
||||
func readNativeUint32(b []byte) uint32 {
|
||||
return *(*uint32)(unsafe.Pointer(&b[0]))
|
||||
}
|
228
component/process/process_freebsd_amd64.go
Normal file
228
component/process/process_freebsd_amd64.go
Normal file
@ -0,0 +1,228 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Dreamacro/clash/log"
|
||||
)
|
||||
|
||||
// store process name for when dealing with multiple PROCESS-NAME rules
|
||||
var (
|
||||
defaultSearcher *searcher
|
||||
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
||||
once.Do(func() {
|
||||
if err := initSearcher(); err != nil {
|
||||
log.Errorln("Initialize PROCESS-NAME failed: %s", err.Error())
|
||||
log.Warnln("All PROCESS-NAME rules will be skipped")
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
var spath string
|
||||
isTCP := network == TCP
|
||||
switch network {
|
||||
case TCP:
|
||||
spath = "net.inet.tcp.pcblist"
|
||||
case UDP:
|
||||
spath = "net.inet.udp.pcblist"
|
||||
default:
|
||||
return "", ErrInvalidNetwork
|
||||
}
|
||||
|
||||
value, err := syscall.Sysctl(spath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
buf := []byte(value)
|
||||
pid, err := defaultSearcher.Search(buf, ip, uint16(srcPort), isTCP)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return getExecPathFromPID(pid)
|
||||
}
|
||||
|
||||
func getExecPathFromPID(pid uint32) (string, error) {
|
||||
buf := make([]byte, 2048)
|
||||
size := uint64(len(buf))
|
||||
// CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, pid
|
||||
mib := [4]uint32{1, 14, 12, pid}
|
||||
|
||||
_, _, errno := syscall.Syscall6(
|
||||
syscall.SYS___SYSCTL,
|
||||
uintptr(unsafe.Pointer(&mib[0])),
|
||||
uintptr(len(mib)),
|
||||
uintptr(unsafe.Pointer(&buf[0])),
|
||||
uintptr(unsafe.Pointer(&size)),
|
||||
0,
|
||||
0)
|
||||
if errno != 0 || size == 0 {
|
||||
return "", errno
|
||||
}
|
||||
|
||||
return filepath.Base(string(buf[:size-1])), nil
|
||||
}
|
||||
|
||||
func readNativeUint32(b []byte) uint32 {
|
||||
return *(*uint32)(unsafe.Pointer(&b[0]))
|
||||
}
|
||||
|
||||
type searcher struct {
|
||||
// sizeof(struct xinpgen)
|
||||
headSize int
|
||||
// sizeof(struct xtcpcb)
|
||||
tcpItemSize int
|
||||
// sizeof(struct xinpcb)
|
||||
udpItemSize int
|
||||
udpInpOffset int
|
||||
port int
|
||||
ip int
|
||||
vflag int
|
||||
socket int
|
||||
|
||||
// sizeof(struct xfile)
|
||||
fileItemSize int
|
||||
data int
|
||||
pid int
|
||||
}
|
||||
|
||||
func (s *searcher) Search(buf []byte, ip net.IP, port uint16, isTCP bool) (uint32, error) {
|
||||
var itemSize int
|
||||
var inpOffset int
|
||||
|
||||
if isTCP {
|
||||
// struct xtcpcb
|
||||
itemSize = s.tcpItemSize
|
||||
inpOffset = 8
|
||||
} else {
|
||||
// struct xinpcb
|
||||
itemSize = s.udpItemSize
|
||||
inpOffset = s.udpInpOffset
|
||||
}
|
||||
|
||||
isIPv4 := ip.To4() != nil
|
||||
// skip the first xinpgen block
|
||||
for i := s.headSize; i+itemSize <= len(buf); i += itemSize {
|
||||
inp := i + inpOffset
|
||||
|
||||
srcPort := binary.BigEndian.Uint16(buf[inp+s.port : inp+s.port+2])
|
||||
|
||||
if port != srcPort {
|
||||
continue
|
||||
}
|
||||
|
||||
// xinpcb.inp_vflag
|
||||
flag := buf[inp+s.vflag]
|
||||
|
||||
var srcIP net.IP
|
||||
switch {
|
||||
case flag&0x1 > 0 && isIPv4:
|
||||
// ipv4
|
||||
srcIP = net.IP(buf[inp+s.ip : inp+s.ip+4])
|
||||
case flag&0x2 > 0 && !isIPv4:
|
||||
// ipv6
|
||||
srcIP = net.IP(buf[inp+s.ip-12 : inp+s.ip+4])
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
if !ip.Equal(srcIP) {
|
||||
continue
|
||||
}
|
||||
|
||||
// xsocket.xso_so, interpreted as big endian anyway since it's only used for comparison
|
||||
socket := binary.BigEndian.Uint64(buf[inp+s.socket : inp+s.socket+8])
|
||||
return s.searchSocketPid(socket)
|
||||
}
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
|
||||
func (s *searcher) searchSocketPid(socket uint64) (uint32, error) {
|
||||
value, err := syscall.Sysctl("kern.file")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
buf := []byte(value)
|
||||
|
||||
// struct xfile
|
||||
itemSize := s.fileItemSize
|
||||
for i := 0; i+itemSize <= len(buf); i += itemSize {
|
||||
// xfile.xf_data
|
||||
data := binary.BigEndian.Uint64(buf[i+s.data : i+s.data+8])
|
||||
if data == socket {
|
||||
// xfile.xf_pid
|
||||
pid := readNativeUint32(buf[i+s.pid : i+s.pid+4])
|
||||
return pid, nil
|
||||
}
|
||||
}
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
|
||||
func newSearcher(major int) *searcher {
|
||||
var s *searcher = nil
|
||||
switch major {
|
||||
case 11:
|
||||
s = &searcher{
|
||||
headSize: 32,
|
||||
tcpItemSize: 1304,
|
||||
udpItemSize: 632,
|
||||
port: 198,
|
||||
ip: 228,
|
||||
vflag: 116,
|
||||
socket: 88,
|
||||
fileItemSize: 80,
|
||||
data: 56,
|
||||
pid: 8,
|
||||
udpInpOffset: 8,
|
||||
}
|
||||
case 12:
|
||||
s = &searcher{
|
||||
headSize: 64,
|
||||
tcpItemSize: 744,
|
||||
udpItemSize: 400,
|
||||
port: 254,
|
||||
ip: 284,
|
||||
vflag: 392,
|
||||
socket: 16,
|
||||
fileItemSize: 128,
|
||||
data: 56,
|
||||
pid: 8,
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func initSearcher() error {
|
||||
osRelease, err := syscall.Sysctl("kern.osrelease")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dot := strings.Index(osRelease, ".")
|
||||
if dot != -1 {
|
||||
osRelease = osRelease[:dot]
|
||||
}
|
||||
major, err := strconv.Atoi(osRelease)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defaultSearcher = newSearcher(major)
|
||||
if defaultSearcher == nil {
|
||||
return fmt.Errorf("unsupported freebsd version %d", major)
|
||||
}
|
||||
return nil
|
||||
}
|
238
component/process/process_linux.go
Normal file
238
component/process/process_linux.go
Normal file
@ -0,0 +1,238 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Dreamacro/clash/common/pool"
|
||||
)
|
||||
|
||||
// from https://github.com/vishvananda/netlink/blob/bca67dfc8220b44ef582c9da4e9172bf1c9ec973/nl/nl_linux.go#L52-L62
|
||||
func init() {
|
||||
var x uint32 = 0x01020304
|
||||
if *(*byte)(unsafe.Pointer(&x)) == 0x01 {
|
||||
nativeEndian = binary.BigEndian
|
||||
} else {
|
||||
nativeEndian = binary.LittleEndian
|
||||
}
|
||||
}
|
||||
|
||||
type SocketResolver func(network string, ip net.IP, srcPort int) (inode, uid int, err error)
|
||||
type ProcessNameResolver func(inode, uid int) (name string, err error)
|
||||
|
||||
// export for android
|
||||
var (
|
||||
DefaultSocketResolver SocketResolver = resolveSocketByNetlink
|
||||
DefaultProcessNameResolver ProcessNameResolver = resolveProcessNameByProcSearch
|
||||
)
|
||||
|
||||
const (
|
||||
sizeOfSocketDiagRequest = syscall.SizeofNlMsghdr + 8 + 48
|
||||
socketDiagByFamily = 20
|
||||
pathProc = "/proc"
|
||||
)
|
||||
|
||||
var nativeEndian binary.ByteOrder = binary.LittleEndian
|
||||
|
||||
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
||||
inode, uid, err := DefaultSocketResolver(network, ip, srcPort)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return DefaultProcessNameResolver(inode, uid)
|
||||
}
|
||||
|
||||
func resolveSocketByNetlink(network string, ip net.IP, srcPort int) (int, int, 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.To4() != nil {
|
||||
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, err
|
||||
}
|
||||
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})
|
||||
|
||||
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, err
|
||||
}
|
||||
|
||||
rb := pool.Get(pool.RelayBufferSize)
|
||||
defer pool.Put(rb)
|
||||
|
||||
n, err := syscall.Read(socket, rb)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
messages, err := syscall.ParseNetlinkMessage(rb[:n])
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
} else if len(messages) == 0 {
|
||||
return 0, 0, io.ErrUnexpectedEOF
|
||||
}
|
||||
|
||||
message := messages[0]
|
||||
if message.Header.Type&syscall.NLMSG_ERROR != 0 {
|
||||
return 0, 0, syscall.ESRCH
|
||||
}
|
||||
|
||||
uid, inode := unpackSocketDiagResponse(&messages[0])
|
||||
|
||||
return int(uid), int(inode), nil
|
||||
}
|
||||
|
||||
func packSocketDiagRequest(family, protocol byte, source net.IP, sourcePort uint16) []byte {
|
||||
s := make([]byte, 16)
|
||||
|
||||
if v4 := source.To4(); v4 != nil {
|
||||
copy(s, v4)
|
||||
} else {
|
||||
copy(s, source)
|
||||
}
|
||||
|
||||
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 uint32) {
|
||||
if len(msg.Data) < 72 {
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
data := msg.Data
|
||||
|
||||
uid = nativeEndian.Uint32(data[64:68])
|
||||
inode = nativeEndian.Uint32(data[68:72])
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func resolveProcessNameByProcSearch(inode, uid int) (string, error) {
|
||||
files, err := ioutil.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
|
||||
}
|
||||
|
||||
if f.Sys().(*syscall.Stat_t).Uid != uint32(uid) {
|
||||
continue
|
||||
}
|
||||
|
||||
processPath := path.Join(pathProc, f.Name())
|
||||
fdPath := path.Join(processPath, "fd")
|
||||
|
||||
fds, err := ioutil.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 := ioutil.ReadFile(path.Join(processPath, "cmdline"))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return splitCmdline(cmdline), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "", syscall.ESRCH
|
||||
}
|
||||
|
||||
func splitCmdline(cmdline []byte) string {
|
||||
indexOfEndOfString := len(cmdline)
|
||||
|
||||
for i, c := range cmdline {
|
||||
if c == 0 {
|
||||
indexOfEndOfString = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return filepath.Base(string(cmdline[:indexOfEndOfString]))
|
||||
}
|
||||
|
||||
func isPid(s string) bool {
|
||||
for _, s := range s {
|
||||
if s < '0' || s > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
10
component/process/process_other.go
Normal file
10
component/process/process_other.go
Normal file
@ -0,0 +1,10 @@
|
||||
// +build !darwin,!linux,!windows
|
||||
// +build !freebsd !amd64
|
||||
|
||||
package process
|
||||
|
||||
import "net"
|
||||
|
||||
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
||||
return "", ErrPlatformNotSupport
|
||||
}
|
223
component/process/process_windows.go
Normal file
223
component/process/process_windows.go
Normal file
@ -0,0 +1,223 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Dreamacro/clash/log"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
const (
|
||||
tcpTableFunc = "GetExtendedTcpTable"
|
||||
tcpTablePidConn = 4
|
||||
udpTableFunc = "GetExtendedUdpTable"
|
||||
udpTablePid = 1
|
||||
queryProcNameFunc = "QueryFullProcessImageNameW"
|
||||
)
|
||||
|
||||
var (
|
||||
getExTcpTable uintptr
|
||||
getExUdpTable uintptr
|
||||
queryProcName uintptr
|
||||
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func initWin32API() error {
|
||||
h, err := windows.LoadLibrary("iphlpapi.dll")
|
||||
if err != nil {
|
||||
return fmt.Errorf("LoadLibrary iphlpapi.dll failed: %s", err.Error())
|
||||
}
|
||||
|
||||
getExTcpTable, err = windows.GetProcAddress(h, tcpTableFunc)
|
||||
if err != nil {
|
||||
return fmt.Errorf("GetProcAddress of %s failed: %s", tcpTableFunc, err.Error())
|
||||
}
|
||||
|
||||
getExUdpTable, err = windows.GetProcAddress(h, udpTableFunc)
|
||||
if err != nil {
|
||||
return fmt.Errorf("GetProcAddress of %s failed: %s", udpTableFunc, err.Error())
|
||||
}
|
||||
|
||||
h, err = windows.LoadLibrary("kernel32.dll")
|
||||
if err != nil {
|
||||
return fmt.Errorf("LoadLibrary kernel32.dll failed: %s", err.Error())
|
||||
}
|
||||
|
||||
queryProcName, err = windows.GetProcAddress(h, queryProcNameFunc)
|
||||
if err != nil {
|
||||
return fmt.Errorf("GetProcAddress of %s failed: %s", queryProcNameFunc, err.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func findProcessName(network string, ip net.IP, srcPort int) (string, error) {
|
||||
once.Do(func() {
|
||||
err := initWin32API()
|
||||
if err != nil {
|
||||
log.Errorln("Initialize PROCESS-NAME failed: %s", err.Error())
|
||||
log.Warnln("All PROCESS-NAMES rules will be skiped")
|
||||
return
|
||||
}
|
||||
})
|
||||
family := windows.AF_INET
|
||||
if ip.To4() == nil {
|
||||
family = windows.AF_INET6
|
||||
}
|
||||
|
||||
var class int
|
||||
var fn uintptr
|
||||
switch network {
|
||||
case TCP:
|
||||
fn = getExTcpTable
|
||||
class = tcpTablePidConn
|
||||
case UDP:
|
||||
fn = getExUdpTable
|
||||
class = udpTablePid
|
||||
default:
|
||||
return "", ErrInvalidNetwork
|
||||
}
|
||||
|
||||
buf, err := getTransportTable(fn, family, class)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
s := newSearcher(family == windows.AF_INET, network == TCP)
|
||||
|
||||
pid, err := s.Search(buf, ip, uint16(srcPort))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return getExecPathFromPID(pid)
|
||||
}
|
||||
|
||||
type searcher struct {
|
||||
itemSize int
|
||||
port int
|
||||
ip int
|
||||
ipSize int
|
||||
pid int
|
||||
tcpState int
|
||||
}
|
||||
|
||||
func (s *searcher) Search(b []byte, ip net.IP, port uint16) (uint32, error) {
|
||||
n := int(readNativeUint32(b[:4]))
|
||||
itemSize := s.itemSize
|
||||
for i := 0; i < n; i++ {
|
||||
row := b[4+itemSize*i : 4+itemSize*(i+1)]
|
||||
|
||||
if s.tcpState >= 0 {
|
||||
tcpState := readNativeUint32(row[s.tcpState : s.tcpState+4])
|
||||
// MIB_TCP_STATE_ESTAB, only check established connections for TCP
|
||||
if tcpState != 5 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// according to MSDN, only the lower 16 bits of dwLocalPort are used and the port number is in network endian.
|
||||
// this field can be illustrated as follows depends on different machine endianess:
|
||||
// little endian: [ MSB LSB 0 0 ] interpret as native uint32 is ((LSB<<8)|MSB)
|
||||
// big endian: [ 0 0 MSB LSB ] interpret as native uint32 is ((MSB<<8)|LSB)
|
||||
// so we need an syscall.Ntohs on the lower 16 bits after read the port as native uint32
|
||||
srcPort := syscall.Ntohs(uint16(readNativeUint32(row[s.port : s.port+4])))
|
||||
if srcPort != port {
|
||||
continue
|
||||
}
|
||||
|
||||
srcIP := net.IP(row[s.ip : s.ip+s.ipSize])
|
||||
if !ip.Equal(srcIP) {
|
||||
continue
|
||||
}
|
||||
|
||||
pid := readNativeUint32(row[s.pid : s.pid+4])
|
||||
return pid, nil
|
||||
}
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
|
||||
func newSearcher(isV4, isTCP bool) *searcher {
|
||||
var itemSize, port, ip, ipSize, pid int
|
||||
tcpState := -1
|
||||
switch {
|
||||
case isV4 && isTCP:
|
||||
// struct MIB_TCPROW_OWNER_PID
|
||||
itemSize, port, ip, ipSize, pid, tcpState = 24, 8, 4, 4, 20, 0
|
||||
case isV4 && !isTCP:
|
||||
// struct MIB_UDPROW_OWNER_PID
|
||||
itemSize, port, ip, ipSize, pid = 12, 4, 0, 4, 8
|
||||
case !isV4 && isTCP:
|
||||
// struct MIB_TCP6ROW_OWNER_PID
|
||||
itemSize, port, ip, ipSize, pid, tcpState = 56, 20, 0, 16, 52, 48
|
||||
case !isV4 && !isTCP:
|
||||
// struct MIB_UDP6ROW_OWNER_PID
|
||||
itemSize, port, ip, ipSize, pid = 28, 20, 0, 16, 24
|
||||
}
|
||||
|
||||
return &searcher{
|
||||
itemSize: itemSize,
|
||||
port: port,
|
||||
ip: ip,
|
||||
ipSize: ipSize,
|
||||
pid: pid,
|
||||
tcpState: tcpState,
|
||||
}
|
||||
}
|
||||
|
||||
func getTransportTable(fn uintptr, family int, class int) ([]byte, error) {
|
||||
for size, buf := uint32(8), make([]byte, 8); ; {
|
||||
ptr := unsafe.Pointer(&buf[0])
|
||||
err, _, _ := syscall.Syscall6(fn, 6, uintptr(ptr), uintptr(unsafe.Pointer(&size)), 0, uintptr(family), uintptr(class), 0)
|
||||
|
||||
switch err {
|
||||
case 0:
|
||||
return buf, nil
|
||||
case uintptr(syscall.ERROR_INSUFFICIENT_BUFFER):
|
||||
buf = make([]byte, size)
|
||||
default:
|
||||
return nil, fmt.Errorf("syscall error: %d", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readNativeUint32(b []byte) uint32 {
|
||||
return *(*uint32)(unsafe.Pointer(&b[0]))
|
||||
}
|
||||
|
||||
func getExecPathFromPID(pid uint32) (string, error) {
|
||||
// kernel process starts with a colon in order to distinguish with normal processes
|
||||
switch pid {
|
||||
case 0:
|
||||
// reserved pid for system idle process
|
||||
return ":System Idle Process", nil
|
||||
case 4:
|
||||
// reserved pid for windows kernel image
|
||||
return ":System", nil
|
||||
}
|
||||
h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer windows.CloseHandle(h)
|
||||
|
||||
buf := make([]uint16, syscall.MAX_LONG_PATH)
|
||||
size := uint32(len(buf))
|
||||
r1, _, err := syscall.Syscall6(
|
||||
queryProcName, 4,
|
||||
uintptr(h),
|
||||
uintptr(1),
|
||||
uintptr(unsafe.Pointer(&buf[0])),
|
||||
uintptr(unsafe.Pointer(&size)),
|
||||
0, 0)
|
||||
if r1 == 0 {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Base(syscall.UTF16ToString(buf[:size])), nil
|
||||
}
|
Reference in New Issue
Block a user