mihomo/listener/tproxy/udp.go

82 lines
1.5 KiB
Go
Raw Normal View History

2021-06-13 17:23:10 +08:00
package tproxy
import (
"net"
2021-06-10 14:05:56 +08:00
"github.com/Dreamacro/clash/adapter/inbound"
"github.com/Dreamacro/clash/common/pool"
C "github.com/Dreamacro/clash/constant"
2021-05-13 22:18:49 +08:00
"github.com/Dreamacro/clash/transport/socks5"
)
2021-06-13 17:23:10 +08:00
type UDPListener struct {
packetConn net.PacketConn
address string
closed bool
}
2021-06-13 17:23:10 +08:00
func NewUDP(addr string, in chan<- *inbound.PacketAdapter) (*UDPListener, error) {
l, err := net.ListenPacket("udp", addr)
if err != nil {
return nil, err
}
2021-06-13 17:23:10 +08:00
rl := &UDPListener{l, addr, false}
c := l.(*net.UDPConn)
rc, err := c.SyscallConn()
if err != nil {
return nil, err
}
err = setsockopt(rc, addr)
if err != nil {
return nil, err
}
go func() {
oob := make([]byte, 1024)
for {
2020-04-25 00:30:40 +08:00
buf := pool.Get(pool.RelayBufferSize)
2020-03-10 20:36:24 +08:00
n, oobn, _, lAddr, err := c.ReadMsgUDP(buf, oob)
if err != nil {
2020-04-25 00:30:40 +08:00
pool.Put(buf)
if rl.closed {
break
}
continue
}
2020-03-10 20:36:24 +08:00
rAddr, err := getOrigDst(oob, oobn)
if err != nil {
continue
}
2021-06-13 17:23:10 +08:00
handlePacketConn(l, in, buf[:n], lAddr, rAddr)
}
}()
return rl, nil
}
2021-06-13 17:23:10 +08:00
func (l *UDPListener) Close() error {
l.closed = true
return l.packetConn.Close()
}
2021-06-13 17:23:10 +08:00
func (l *UDPListener) Address() string {
return l.address
}
2021-06-13 17:23:10 +08:00
func handlePacketConn(pc net.PacketConn, in chan<- *inbound.PacketAdapter, buf []byte, lAddr *net.UDPAddr, rAddr *net.UDPAddr) {
2020-03-10 20:36:24 +08:00
target := socks5.ParseAddrToSocksAddr(rAddr)
pkt := &packet{
lAddr: lAddr,
buf: buf,
}
2021-06-13 17:23:10 +08:00
select {
case in <- inbound.NewPacket(target, pkt, C.TPROXY):
default:
}
}