Clash.Meta/proxy/socks/udp.go

69 lines
1.3 KiB
Go
Raw Normal View History

package socks
import (
2019-10-11 20:11:18 +08:00
"bytes"
"net"
adapters "github.com/Dreamacro/clash/adapters/inbound"
"github.com/Dreamacro/clash/common/pool"
"github.com/Dreamacro/clash/component/socks5"
C "github.com/Dreamacro/clash/constant"
)
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
}
sl := &SockUDPListener{l, addr, false}
go func() {
for {
2019-10-11 20:11:18 +08:00
buf := pool.BufPool.Get().([]byte)
n, remoteAddr, err := l.ReadFrom(buf)
if err != nil {
2019-10-11 20:11:18 +08:00
pool.BufPool.Put(buf[:cap(buf)])
if sl.closed {
break
}
continue
}
2019-10-11 20:11:18 +08: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 20:11:18 +08:00
func handleSocksUDP(pc net.PacketConn, buf []byte, addr net.Addr) {
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
pool.BufPool.Put(buf[:cap(buf)])
return
}
2019-10-11 20:11:18 +08:00
conn := &fakeConn{
PacketConn: pc,
remoteAddr: addr,
targetAddr: target,
buffer: bytes.NewBuffer(payload),
bufRef: buf,
}
tun.Add(adapters.NewSocket(target, conn, C.SOCKS, C.UDP))
}