forked from v2ray/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
system_listener.go
70 lines (55 loc) · 2.04 KB
/
system_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
package internet
import (
"context"
"syscall"
"v2ray.com/core/common/net"
"v2ray.com/core/common/session"
)
var (
effectiveListener = DefaultListener{}
)
type controller func(network, address string, fd uintptr) error
type DefaultListener struct {
contollers []controller
}
func getControlFunc(ctx context.Context, sockopt *SocketConfig, contollers []controller) func(network, address string, c syscall.RawConn) error {
return func(network, address string, c syscall.RawConn) error {
return c.Control(func(fd uintptr) {
if sockopt != nil {
if err := applyInboundSocketOptions(network, fd, sockopt); err != nil {
newError("failed to apply socket options to incoming connection").Base(err).WriteToLog(session.ExportIDToError(ctx))
}
}
for _, controller := range contollers {
if err := controller(network, address, fd); err != nil {
newError("failed to apply external controller").Base(err).WriteToLog(session.ExportIDToError(ctx))
}
}
})
}
}
func (dl *DefaultListener) Listen(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.Listener, error) {
var lc net.ListenConfig
if sockopt != nil || len(dl.contollers) > 0 {
lc.Control = getControlFunc(ctx, sockopt, dl.contollers)
}
return lc.Listen(ctx, addr.Network(), addr.String())
}
func (dl *DefaultListener) ListenPacket(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.PacketConn, error) {
var lc net.ListenConfig
if sockopt != nil || len(dl.contollers) > 0 {
lc.Control = getControlFunc(ctx, sockopt, dl.contollers)
}
return lc.ListenPacket(ctx, addr.Network(), addr.String())
}
// RegisterListenerController adds a controller to the effective system listener.
// The controller can be used to operate on file descriptors before they are put into use.
//
// v2ray:api:beta
func RegisterListenerController(controller func(network, address string, fd uintptr) error) error {
if controller == nil {
return newError("nil listener controller")
}
effectiveListener.contollers = append(effectiveListener.contollers, controller)
return nil
}