-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
365 lines (327 loc) · 9.24 KB
/
listener.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package listener
import (
"fmt"
"net"
"strconv"
"strings"
"sync"
"github.com/eyslce/clash/adapter/inbound"
"github.com/eyslce/clash/config"
C "github.com/eyslce/clash/constant"
"github.com/eyslce/clash/listener/http"
"github.com/eyslce/clash/listener/mixed"
"github.com/eyslce/clash/listener/redir"
"github.com/eyslce/clash/listener/socks"
"github.com/eyslce/clash/listener/tproxy"
"github.com/eyslce/clash/listener/tunnel"
"github.com/eyslce/clash/log"
"github.com/samber/lo"
)
var (
allowLan = false
bindAddress = "*"
tcpListeners = map[C.Inbound]C.Listener{}
udpListeners = map[C.Inbound]C.Listener{}
tunnelTCPListeners = map[string]*tunnel.Listener{}
tunnelUDPListeners = map[string]*tunnel.PacketConn{}
// lock for recreate function
recreateMux sync.Mutex
tunnelMux sync.Mutex
)
type Ports struct {
Port int `json:"port"`
SocksPort int `json:"socks-port"`
RedirPort int `json:"redir-port"`
TProxyPort int `json:"tproxy-port"`
MixedPort int `json:"mixed-port"`
}
var tcpListenerCreators = map[C.InboundType]tcpListenerCreator{
C.InboundTypeHTTP: http.New,
C.InboundTypeSocks: socks.New,
C.InboundTypeRedir: redir.New,
C.InboundTypeTproxy: tproxy.New,
C.InboundTypeMixed: mixed.New,
}
var udpListenerCreators = map[C.InboundType]udpListenerCreator{
C.InboundTypeSocks: socks.NewUDP,
C.InboundTypeRedir: tproxy.NewUDP,
C.InboundTypeTproxy: tproxy.NewUDP,
C.InboundTypeMixed: socks.NewUDP,
}
type (
tcpListenerCreator func(addr string, tcpIn chan<- C.ConnContext) (C.Listener, error)
udpListenerCreator func(addr string, udpIn chan<- *inbound.PacketAdapter) (C.Listener, error)
)
func AllowLan() bool {
return allowLan
}
func BindAddress() string {
return bindAddress
}
func SetAllowLan(al bool) {
allowLan = al
}
func SetBindAddress(host string) {
bindAddress = host
}
func createListener(inbound C.Inbound, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.PacketAdapter) {
addr := inbound.BindAddress
if portIsZero(addr) {
return
}
tcpCreator := tcpListenerCreators[inbound.Type]
udpCreator := udpListenerCreators[inbound.Type]
if tcpCreator == nil && udpCreator == nil {
log.Errorln("inbound type %s not support.", inbound.Type)
return
}
if tcpCreator != nil {
tcpListener, err := tcpCreator(addr, tcpIn)
if err != nil {
log.Errorln("create addr %s tcp listener error. err:%v", addr, err)
return
}
tcpListeners[inbound] = tcpListener
}
if udpCreator != nil {
udpListener, err := udpCreator(addr, udpIn)
if err != nil {
log.Errorln("create addr %s udp listener error. err:%v", addr, err)
return
}
udpListeners[inbound] = udpListener
}
log.Infoln("inbound %s create success.", inbound.ToAlias())
}
func closeListener(inbound C.Inbound) {
listener := tcpListeners[inbound]
if listener != nil {
if err := listener.Close(); err != nil {
log.Errorln("close tcp address `%s` error. err:%s", inbound.ToAlias(), err.Error())
}
delete(tcpListeners, inbound)
}
listener = udpListeners[inbound]
if listener != nil {
if err := listener.Close(); err != nil {
log.Errorln("close udp address `%s` error. err:%s", inbound.ToAlias(), err.Error())
}
delete(udpListeners, inbound)
}
}
func getNeedCloseAndCreateInbound(originInbounds []C.Inbound, newInbounds []C.Inbound) ([]C.Inbound, []C.Inbound) {
needCloseMap := map[C.Inbound]bool{}
needClose := []C.Inbound{}
needCreate := []C.Inbound{}
for _, inbound := range originInbounds {
needCloseMap[inbound] = true
}
for _, inbound := range newInbounds {
if needCloseMap[inbound] {
delete(needCloseMap, inbound)
} else {
needCreate = append(needCreate, inbound)
}
}
for inbound := range needCloseMap {
needClose = append(needClose, inbound)
}
return needClose, needCreate
}
// only recreate inbound config listener
func ReCreateListeners(inbounds []C.Inbound, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.PacketAdapter) {
newInbounds := []C.Inbound{}
newInbounds = append(newInbounds, inbounds...)
for _, inbound := range getInbounds() {
if inbound.IsFromPortCfg {
newInbounds = append(newInbounds, inbound)
}
}
reCreateListeners(newInbounds, tcpIn, udpIn)
}
// only recreate ports config listener
func ReCreatePortsListeners(ports Ports, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.PacketAdapter) {
newInbounds := []C.Inbound{}
newInbounds = append(newInbounds, GetInbounds()...)
newInbounds = addPortInbound(newInbounds, C.InboundTypeHTTP, ports.Port)
newInbounds = addPortInbound(newInbounds, C.InboundTypeSocks, ports.SocksPort)
newInbounds = addPortInbound(newInbounds, C.InboundTypeRedir, ports.RedirPort)
newInbounds = addPortInbound(newInbounds, C.InboundTypeTproxy, ports.TProxyPort)
newInbounds = addPortInbound(newInbounds, C.InboundTypeMixed, ports.MixedPort)
reCreateListeners(newInbounds, tcpIn, udpIn)
}
func addPortInbound(inbounds []C.Inbound, inboundType C.InboundType, port int) []C.Inbound {
if port != 0 {
inbounds = append(inbounds, C.Inbound{
Type: inboundType,
BindAddress: genAddr(bindAddress, port, allowLan),
IsFromPortCfg: true,
})
}
return inbounds
}
func reCreateListeners(inbounds []C.Inbound, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.PacketAdapter) {
recreateMux.Lock()
defer recreateMux.Unlock()
needClose, needCreate := getNeedCloseAndCreateInbound(getInbounds(), inbounds)
for _, inbound := range needClose {
closeListener(inbound)
}
for _, inbound := range needCreate {
createListener(inbound, tcpIn, udpIn)
}
}
func PatchTunnel(tunnels []config.Tunnel, tcpIn chan<- C.ConnContext, udpIn chan<- *inbound.PacketAdapter) {
tunnelMux.Lock()
defer tunnelMux.Unlock()
type addrProxy struct {
network string
addr string
target string
proxy string
}
tcpOld := lo.Map(
lo.Keys(tunnelTCPListeners),
func(key string, _ int) addrProxy {
parts := strings.Split(key, "/")
return addrProxy{
network: "tcp",
addr: parts[0],
target: parts[1],
proxy: parts[2],
}
},
)
udpOld := lo.Map(
lo.Keys(tunnelUDPListeners),
func(key string, _ int) addrProxy {
parts := strings.Split(key, "/")
return addrProxy{
network: "udp",
addr: parts[0],
target: parts[1],
proxy: parts[2],
}
},
)
oldElm := lo.Union(tcpOld, udpOld)
newElm := lo.FlatMap(
tunnels,
func(tunnel config.Tunnel, _ int) []addrProxy {
return lo.Map(
tunnel.Network,
func(network string, _ int) addrProxy {
return addrProxy{
network: network,
addr: tunnel.Address,
target: tunnel.Target,
proxy: tunnel.Proxy,
}
},
)
},
)
needClose, needCreate := lo.Difference(oldElm, newElm)
for _, elm := range needClose {
key := fmt.Sprintf("%s/%s/%s", elm.addr, elm.target, elm.proxy)
if elm.network == "tcp" {
tunnelTCPListeners[key].Close()
delete(tunnelTCPListeners, key)
} else {
tunnelUDPListeners[key].Close()
delete(tunnelUDPListeners, key)
}
}
for _, elm := range needCreate {
key := fmt.Sprintf("%s/%s/%s", elm.addr, elm.target, elm.proxy)
if elm.network == "tcp" {
l, err := tunnel.New(elm.addr, elm.target, elm.proxy, tcpIn)
if err != nil {
log.Errorln("Start tunnel %s error: %s", elm.target, err.Error())
continue
}
tunnelTCPListeners[key] = l
log.Infoln("Tunnel(tcp/%s) proxy %s listening at: %s", elm.target, elm.proxy, tunnelTCPListeners[key].Address())
} else {
l, err := tunnel.NewUDP(elm.addr, elm.target, elm.proxy, udpIn)
if err != nil {
log.Errorln("Start tunnel %s error: %s", elm.target, err.Error())
continue
}
tunnelUDPListeners[key] = l
log.Infoln("Tunnel(udp/%s) proxy %s listening at: %s", elm.target, elm.proxy, tunnelUDPListeners[key].Address())
}
}
}
func GetInbounds() []C.Inbound {
return lo.Filter(getInbounds(), func(inbound C.Inbound, idx int) bool {
return !inbound.IsFromPortCfg
})
}
// GetInbounds return the inbounds of proxy servers
func getInbounds() []C.Inbound {
var inbounds []C.Inbound
for inbound := range tcpListeners {
inbounds = append(inbounds, inbound)
}
for inbound := range udpListeners {
if _, ok := tcpListeners[inbound]; !ok {
inbounds = append(inbounds, inbound)
}
}
return inbounds
}
// GetPorts return the ports of proxy servers
func GetPorts() *Ports {
ports := &Ports{}
for _, inbound := range getInbounds() {
fillPort(inbound, ports)
}
return ports
}
func fillPort(inbound C.Inbound, ports *Ports) {
if inbound.IsFromPortCfg {
port := getPort(inbound.BindAddress)
switch inbound.Type {
case C.InboundTypeHTTP:
ports.Port = port
case C.InboundTypeSocks:
ports.SocksPort = port
case C.InboundTypeTproxy:
ports.TProxyPort = port
case C.InboundTypeRedir:
ports.RedirPort = port
case C.InboundTypeMixed:
ports.MixedPort = port
default:
// do nothing
}
}
}
func portIsZero(addr string) bool {
_, port, err := net.SplitHostPort(addr)
if port == "0" || port == "" || err != nil {
return true
}
return false
}
func genAddr(host string, port int, allowLan bool) string {
if allowLan {
if host == "*" {
return fmt.Sprintf(":%d", port)
}
return fmt.Sprintf("%s:%d", host, port)
}
return fmt.Sprintf("127.0.0.1:%d", port)
}
func getPort(addr string) int {
_, portStr, err := net.SplitHostPort(addr)
if err != nil {
return 0
}
port, err := strconv.Atoi(portStr)
if err != nil {
return 0
}
return port
}