-
Notifications
You must be signed in to change notification settings - Fork 1
/
udp.go
85 lines (74 loc) · 1.7 KB
/
udp.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
package socks
import (
"net"
"github.com/chwjbn/xclash/adapter/inbound"
"github.com/chwjbn/xclash/common/pool"
"github.com/chwjbn/xclash/common/sockopt"
C "github.com/chwjbn/xclash/constant"
"github.com/chwjbn/xclash/log"
"github.com/chwjbn/xclash/transport/socks5"
)
type UDPListener struct {
packetConn net.PacketConn
addr string
closed bool
}
// RawAddress implements C.Listener
func (l *UDPListener) RawAddress() string {
return l.addr
}
// Address implements C.Listener
func (l *UDPListener) Address() string {
return l.packetConn.LocalAddr().String()
}
// Close implements C.Listener
func (l *UDPListener) Close() error {
l.closed = true
return l.packetConn.Close()
}
func NewUDP(addr string, in chan<- *inbound.PacketAdapter) (*UDPListener, error) {
l, err := net.ListenPacket("udp", addr)
if err != nil {
return nil, err
}
if err := sockopt.UDPReuseaddr(l.(*net.UDPConn)); err != nil {
log.Warnln("Failed to Reuse UDP Address: %s", err)
}
sl := &UDPListener{
packetConn: l,
addr: addr,
}
go func() {
for {
buf := pool.Get(pool.UDPBufferSize)
n, remoteAddr, err := l.ReadFrom(buf)
if err != nil {
pool.Put(buf)
if sl.closed {
break
}
continue
}
handleSocksUDP(l, in, buf[:n], remoteAddr)
}
}()
return sl, nil
}
func handleSocksUDP(pc net.PacketConn, in chan<- *inbound.PacketAdapter, buf []byte, addr net.Addr) {
target, payload, err := socks5.DecodeUDPPacket(buf)
if err != nil {
// Unresolved UDP packet, return buffer to the pool
pool.Put(buf)
return
}
packet := &packet{
pc: pc,
rAddr: addr,
payload: payload,
bufRef: buf,
}
select {
case in <- inbound.NewPacket(target, packet, C.SOCKS5):
default:
}
}