Clash.Meta/listener/socks/udp.go

92 lines
1.9 KiB
Go
Raw Normal View History

package socks
import (
"net"
2021-06-10 14:05:56 +08:00
"github.com/Dreamacro/clash/adapter/inbound"
"github.com/Dreamacro/clash/common/pool"
"github.com/Dreamacro/clash/common/sockopt"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/log"
2021-05-13 22:18:49 +08:00
"github.com/Dreamacro/clash/transport/socks5"
)
2021-06-13 17:23:10 +08:00
type UDPListener struct {
packetConn net.PacketConn
addr string
closed bool
}
2021-08-01 00:35:37 +08:00
// 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<- C.PacketAdapter, additions ...inbound.Addition) (*UDPListener, error) {
if len(additions) == 0 {
additions = []inbound.Addition{
inbound.WithInName("DEFAULT-SOCKS"),
inbound.WithSpecialRules(""),
}
}
l, err := net.ListenPacket("udp", addr)
if err != nil {
return nil, err
}
2021-06-13 17:23:10 +08:00
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 {
2021-11-03 22:26:51 +08:00
buf := pool.Get(pool.UDPBufferSize)
n, remoteAddr, err := l.ReadFrom(buf)
if err != nil {
2020-04-25 00:30:40 +08:00
pool.Put(buf)
if sl.closed {
break
}
continue
}
handleSocksUDP(l, in, buf[:n], remoteAddr, additions...)
}
}()
return sl, nil
}
func handleSocksUDP(pc net.PacketConn, in chan<- C.PacketAdapter, buf []byte, addr net.Addr, additions ...inbound.Addition) {
2019-10-11 20:11:18 +08:00
target, payload, err := socks5.DecodeUDPPacket(buf)
if err != nil {
2019-10-11 20:11:18 +08:00
// Unresolved UDP packet, return buffer to the pool
2020-04-25 00:30:40 +08:00
pool.Put(buf)
return
}
packet := &packet{
pc: pc,
rAddr: addr,
payload: payload,
bufRef: buf,
2019-10-11 20:11:18 +08:00
}
2021-06-13 17:23:10 +08:00
select {
case in <- inbound.NewPacket(target, packet, C.SOCKS5, additions...):
2021-06-13 17:23:10 +08:00
default:
}
}