2019-07-25 17:47:39 +08:00
|
|
|
package socks
|
|
|
|
|
|
|
|
import (
|
|
|
|
"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"
|
2020-02-15 21:42:46 +08:00
|
|
|
"github.com/Dreamacro/clash/tunnel"
|
2019-07-25 17:47:39 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
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)
|
2019-07-25 17:47:39 +08:00
|
|
|
n, remoteAddr, err := l.ReadFrom(buf)
|
|
|
|
if err != nil {
|
2019-10-11 20:11:18 +08:00
|
|
|
pool.BufPool.Put(buf[:cap(buf)])
|
2019-07-25 17:47:39 +08:00
|
|
|
if sl.closed {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2019-10-11 20:11:18 +08:00
|
|
|
handleSocksUDP(l, buf[:n], remoteAddr)
|
2019-07-25 17:47:39 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
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)
|
2019-07-25 17:47:39 +08:00
|
|
|
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)])
|
2019-07-25 17:47:39 +08:00
|
|
|
return
|
|
|
|
}
|
2019-12-28 18:44:01 +08:00
|
|
|
packet := &fakeConn{
|
2019-10-11 20:11:18 +08:00
|
|
|
PacketConn: pc,
|
2020-01-31 14:43:54 +08:00
|
|
|
rAddr: addr,
|
2019-12-28 18:44:01 +08:00
|
|
|
payload: payload,
|
2019-10-11 20:11:18 +08:00
|
|
|
bufRef: buf,
|
|
|
|
}
|
2020-02-15 21:42:46 +08:00
|
|
|
tunnel.AddPacket(adapters.NewPacket(target, packet, C.SOCKS))
|
2019-07-25 17:47:39 +08:00
|
|
|
}
|