clash/proxy/socks/udp.go

75 lines
1.5 KiB
Go
Raw Normal View History

package socks
import (
"net"
adapters "github.com/Dreamacro/clash/adapters/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"
"github.com/Dreamacro/clash/tunnel"
)
type SockUDPListener struct {
net.PacketConn
address string
closed bool
}
func NewSocksUDPProxy(addr string) (*SockUDPListener, error) {
l, err := net.ListenPacket("udp", addr)
if err != nil {
return nil, err
}
err = sockopt.UDPReuseaddr(l.(*net.UDPConn))
if err != nil {
log.Warnln("Failed to Reuse UDP Address: %s", err)
}
sl := &SockUDPListener{l, addr, false}
go func() {
for {
2020-04-24 16:30:40 +00:00
buf := pool.Get(pool.RelayBufferSize)
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
}
2019-10-11 12:11:18 +00:00
handleSocksUDP(l, buf[:n], remoteAddr)
}
}()
return sl, nil
}
func (l *SockUDPListener) Close() error {
l.closed = true
return l.PacketConn.Close()
}
func (l *SockUDPListener) Address() string {
return l.address
}
2019-10-11 12:11:18 +00:00
func handleSocksUDP(pc net.PacketConn, buf []byte, addr net.Addr) {
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
}
tunnel.AddPacket(adapters.NewPacket(target, packet, C.SOCKS))
}