2019-07-25 09:47:39 +00:00
|
|
|
package socks
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
|
|
|
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
|
|
|
"github.com/Dreamacro/clash/common/pool"
|
2020-04-11 13:45:56 +00:00
|
|
|
"github.com/Dreamacro/clash/common/sockopt"
|
2019-07-25 09:47:39 +00:00
|
|
|
"github.com/Dreamacro/clash/component/socks5"
|
|
|
|
C "github.com/Dreamacro/clash/constant"
|
2020-06-15 02:34:15 +00:00
|
|
|
"github.com/Dreamacro/clash/log"
|
2020-02-15 13:42:46 +00:00
|
|
|
"github.com/Dreamacro/clash/tunnel"
|
2019-07-25 09:47:39 +00: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
|
|
|
|
}
|
|
|
|
|
2020-04-11 13:45:56 +00:00
|
|
|
err = sockopt.UDPReuseaddr(l.(*net.UDPConn))
|
|
|
|
if err != nil {
|
2020-06-15 02:34:15 +00:00
|
|
|
log.Warnln("Failed to Reuse UDP Address: %s", err)
|
2020-04-11 13:45:56 +00:00
|
|
|
}
|
|
|
|
|
2019-07-25 09:47:39 +00:00
|
|
|
sl := &SockUDPListener{l, addr, false}
|
|
|
|
go func() {
|
|
|
|
for {
|
2020-04-24 16:30:40 +00:00
|
|
|
buf := pool.Get(pool.RelayBufferSize)
|
2019-07-25 09:47:39 +00:00
|
|
|
n, remoteAddr, err := l.ReadFrom(buf)
|
|
|
|
if err != nil {
|
2020-04-24 16:30:40 +00:00
|
|
|
pool.Put(buf)
|
2019-07-25 09:47:39 +00:00
|
|
|
if sl.closed {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
2019-10-11 12:11:18 +00:00
|
|
|
handleSocksUDP(l, buf[:n], remoteAddr)
|
2019-07-25 09:47:39 +00: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 12:11:18 +00:00
|
|
|
func handleSocksUDP(pc net.PacketConn, buf []byte, addr net.Addr) {
|
|
|
|
target, payload, err := socks5.DecodeUDPPacket(buf)
|
2019-07-25 09:47:39 +00:00
|
|
|
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)
|
2019-07-25 09:47:39 +00:00
|
|
|
return
|
|
|
|
}
|
2020-04-16 10:19:36 +00:00
|
|
|
packet := &packet{
|
|
|
|
pc: pc,
|
|
|
|
rAddr: addr,
|
|
|
|
payload: payload,
|
|
|
|
bufRef: buf,
|
2019-10-11 12:11:18 +00:00
|
|
|
}
|
2020-02-15 13:42:46 +00:00
|
|
|
tunnel.AddPacket(adapters.NewPacket(target, packet, C.SOCKS))
|
2019-07-25 09:47:39 +00:00
|
|
|
}
|