/
process_linux.go
232 lines (187 loc) · 4.59 KB
/
process_linux.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package process
import (
"bytes"
"encoding/binary"
"fmt"
"net"
"net/netip"
"os"
"unsafe"
"github.com/lijinglin3/clash/common/pool"
"github.com/mdlayher/netlink"
"golang.org/x/sys/unix"
)
type inetDiagRequest struct {
Family byte
Protocol byte
Ext byte
Pad byte
States uint32
SrcPort [2]byte
DstPort [2]byte
Src [16]byte
Dst [16]byte
If uint32
Cookie [2]uint32
}
type inetDiagResponse struct {
Family byte
State byte
Timer byte
ReTrans byte
SrcPort [2]byte
DstPort [2]byte
Src [16]byte
Dst [16]byte
If uint32
Cookie [2]uint32
Expires uint32
RQueue uint32
WQueue uint32
UID uint32
INode uint32
}
func findProcessPath(network string, from netip.AddrPort, to netip.AddrPort) (string, error) {
inode, uid, err := resolveSocketByNetlink(network, from, to)
if err != nil {
return "", err
}
return resolveProcessPathByProcSearch(inode, uid)
}
func resolveSocketByNetlink(network string, from netip.AddrPort, to netip.AddrPort) (inode uint32, uid uint32, err error) {
var families []byte
if from.Addr().Unmap().Is4() {
families = []byte{unix.AF_INET, unix.AF_INET6}
} else {
families = []byte{unix.AF_INET6, unix.AF_INET}
}
var protocol byte
switch network {
case TCP:
protocol = unix.IPPROTO_TCP
case UDP:
protocol = unix.IPPROTO_UDP
default:
return 0, 0, ErrInvalidNetwork
}
if protocol == unix.IPPROTO_UDP {
// Swap from & to for udp
// See also https://www.mail-archive.com/netdev@vger.kernel.org/msg248638.html
from, to = to, from
}
for _, family := range families {
inode, uid, err = resolveSocketByNetlinkExact(family, protocol, from, to, netlink.Request)
if err == nil {
return inode, uid, err
}
}
return 0, 0, ErrNotFound
}
func resolveSocketByNetlinkExact(family byte, protocol byte, from netip.AddrPort, to netip.AddrPort, flags netlink.HeaderFlags) (inode uint32, uid uint32, err error) {
request := &inetDiagRequest{
Family: family,
Protocol: protocol,
States: 0xffffffff,
Cookie: [2]uint32{0xffffffff, 0xffffffff},
}
var (
fromAddr []byte
toAddr []byte
)
if family == unix.AF_INET {
fromAddr = net.IP(from.Addr().AsSlice()).To4()
toAddr = net.IP(to.Addr().AsSlice()).To4()
} else {
fromAddr = net.IP(from.Addr().AsSlice()).To16()
toAddr = net.IP(to.Addr().AsSlice()).To16()
}
copy(request.Src[:], fromAddr)
copy(request.Dst[:], toAddr)
binary.BigEndian.PutUint16(request.SrcPort[:], from.Port())
binary.BigEndian.PutUint16(request.DstPort[:], to.Port())
conn, err := netlink.Dial(unix.NETLINK_INET_DIAG, nil)
if err != nil {
return 0, 0, err
}
defer conn.Close()
message := netlink.Message{
Header: netlink.Header{
Type: 20, // SOCK_DIAG_BY_FAMILY
Flags: flags,
},
Data: (*(*[unsafe.Sizeof(*request)]byte)(unsafe.Pointer(request)))[:],
}
messages, err := conn.Execute(message)
if err != nil {
return 0, 0, err
}
for _, msg := range messages {
if len(msg.Data) < int(unsafe.Sizeof(inetDiagResponse{})) {
continue
}
response := (*inetDiagResponse)(unsafe.Pointer(&msg.Data[0]))
return response.INode, response.UID, nil
}
return 0, 0, ErrNotFound
}
func resolveProcessPathByProcSearch(inode, uid uint32) (string, error) {
procDir, err := os.Open("/proc")
if err != nil {
return "", err
}
defer procDir.Close()
pids, err := procDir.Readdirnames(-1)
if err != nil {
return "", err
}
expectedSocketName := fmt.Appendf(nil, "socket:[%d]", inode)
pathBuffer := pool.Get(64)
defer pool.Put(pathBuffer)
readlinkBuffer := pool.Get(32)
defer pool.Put(readlinkBuffer)
copy(pathBuffer, "/proc/")
for _, pid := range pids {
if !isPid(pid) {
continue
}
pathBuffer = append(pathBuffer[:len("/proc/")], pid...)
stat := &unix.Stat_t{}
err = unix.Stat(string(pathBuffer), stat)
if err != nil {
continue
} else if stat.Uid != uid {
continue
}
pathBuffer = append(pathBuffer, "/fd/"...)
fdsPrefixLength := len(pathBuffer)
fdDir, err := os.Open(string(pathBuffer))
if err != nil {
continue
}
fds, err := fdDir.Readdirnames(-1)
fdDir.Close()
if err != nil {
continue
}
for _, fd := range fds {
pathBuffer = pathBuffer[:fdsPrefixLength]
pathBuffer = append(pathBuffer, fd...)
n, err := unix.Readlink(string(pathBuffer), readlinkBuffer)
if err != nil {
continue
}
if bytes.Equal(readlinkBuffer[:n], expectedSocketName) {
return os.Readlink("/proc/" + pid + "/exe")
}
}
}
return "", fmt.Errorf("inode %d of uid %d not found", inode, uid)
}
func isPid(name string) bool {
for _, c := range name {
if c < '0' || c > '9' {
return false
}
}
return true
}