2020-03-08 21:58:49 +08:00
|
|
|
package redir
|
|
|
|
|
|
|
|
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"
|
|
|
|
"github.com/Dreamacro/clash/tunnel"
|
|
|
|
)
|
|
|
|
|
|
|
|
type RedirUDPListener struct {
|
|
|
|
net.PacketConn
|
|
|
|
address string
|
|
|
|
closed bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewRedirUDPProxy(addr string) (*RedirUDPListener, error) {
|
|
|
|
l, err := net.ListenPacket("udp", addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
rl := &RedirUDPListener{l, addr, false}
|
|
|
|
|
|
|
|
c := l.(*net.UDPConn)
|
|
|
|
|
|
|
|
err = setsockopt(c, addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
oob := make([]byte, 1024)
|
|
|
|
for {
|
|
|
|
buf := pool.BufPool.Get().([]byte)
|
2020-03-10 20:36:24 +08:00
|
|
|
n, oobn, _, lAddr, err := c.ReadMsgUDP(buf, oob)
|
2020-03-08 21:58:49 +08:00
|
|
|
if err != nil {
|
|
|
|
pool.BufPool.Put(buf[:cap(buf)])
|
|
|
|
if rl.closed {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2020-03-10 20:36:24 +08:00
|
|
|
rAddr, err := getOrigDst(oob, oobn)
|
2020-03-08 21:58:49 +08:00
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2020-03-10 20:36:24 +08:00
|
|
|
handleRedirUDP(l, buf[:n], lAddr, rAddr)
|
2020-03-08 21:58:49 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return rl, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *RedirUDPListener) Close() error {
|
|
|
|
l.closed = true
|
|
|
|
return l.PacketConn.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *RedirUDPListener) Address() string {
|
|
|
|
return l.address
|
|
|
|
}
|
|
|
|
|
2020-03-10 20:36:24 +08:00
|
|
|
func handleRedirUDP(pc net.PacketConn, buf []byte, lAddr *net.UDPAddr, rAddr *net.UDPAddr) {
|
|
|
|
target := socks5.ParseAddrToSocksAddr(rAddr)
|
2020-04-16 18:19:36 +08:00
|
|
|
pkt := &packet{
|
|
|
|
lAddr: lAddr,
|
|
|
|
buf: buf,
|
2020-03-08 21:58:49 +08:00
|
|
|
}
|
2020-04-16 18:19:36 +08:00
|
|
|
tunnel.AddPacket(adapters.NewPacket(target, pkt, C.REDIR))
|
2020-03-08 21:58:49 +08:00
|
|
|
}
|