clash/listener/socks/udp.go

94 lines
2 KiB
Go
Raw Normal View History

package socks
import (
"net"
2021-06-10 06:05:56 +00: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 14:18:49 +00:00
"github.com/Dreamacro/clash/transport/socks5"
)
2021-06-13 09:23:10 +00:00
type UDPListener struct {
2022-12-04 14:08:20 +00:00
packetConn net.PacketConn
addr string
closed bool
name string
specialRules string
}
2021-07-31 16:35:37 +00: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) (*UDPListener, error) {
return NewUDPWithInfos(addr, "DEFAULT-SOCKS", "", in)
2022-12-04 05:37:14 +00:00
}
2022-12-04 14:08:20 +00:00
func NewUDPWithInfos(addr, name, specialRules string, in chan<- C.PacketAdapter) (*UDPListener, error) {
l, err := net.ListenPacket("udp", addr)
if err != nil {
return nil, err
}
2021-06-13 09:23:10 +00:00
if err := sockopt.UDPReuseaddr(l.(*net.UDPConn)); err != nil {
log.Warnln("Failed to Reuse UDP Address: %s", err)
}
sl := &UDPListener{
2022-12-04 14:08:20 +00:00
packetConn: l,
addr: addr,
specialRules: specialRules,
name: name,
}
go func() {
for {
2021-11-03 14:26:51 +00:00
buf := pool.Get(pool.UDPBufferSize)
n, remoteAddr, err := l.ReadFrom(buf)
if err != nil {
2020-04-24 16:30:40 +00:00
pool.Put(buf)
if sl.closed {
break
}
continue
}
2022-12-04 14:08:20 +00:00
handleSocksUDP(sl.name, sl.specialRules, l, in, buf[:n], remoteAddr)
}
}()
return sl, nil
}
2022-12-04 14:08:20 +00:00
func handleSocksUDP(name, specialRules string, pc net.PacketConn, in chan<- C.PacketAdapter, buf []byte, addr net.Addr) {
2019-10-11 12:11:18 +00:00
target, payload, err := socks5.DecodeUDPPacket(buf)
if err != nil {
2019-10-11 12:11:18 +00:00
// Unresolved UDP packet, return buffer to the pool
2020-04-24 16:30:40 +00:00
pool.Put(buf)
return
}
packet := &packet{
pc: pc,
rAddr: addr,
payload: payload,
bufRef: buf,
2019-10-11 12:11:18 +00:00
}
2021-06-13 09:23:10 +00:00
select {
2022-12-04 14:08:20 +00:00
case in <- inbound.NewPacketWithInfos(target, packet, C.SOCKS5, name, specialRules):
2021-06-13 09:23:10 +00:00
default:
}
}