Clash.Meta/listener/tunnel/udp.go

86 lines
1.6 KiB
Go
Raw Normal View History

package tunnel
import (
2022-11-18 22:57:33 +08:00
"fmt"
"net"
"github.com/Dreamacro/clash/adapter/inbound"
"github.com/Dreamacro/clash/common/pool"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/transport/socks5"
)
2022-11-18 22:57:33 +08:00
type PacketConn struct {
conn net.PacketConn
addr string
target socks5.Addr
proxy string
closed bool
}
2022-11-18 22:57:33 +08:00
// RawAddress implements C.Listener
func (l *PacketConn) RawAddress() string {
return l.addr
}
// Address implements C.Listener
func (l *PacketConn) Address() string {
return l.conn.LocalAddr().String()
}
// Close implements C.Listener
func (l *PacketConn) Close() error {
l.closed = true
return l.conn.Close()
}
func NewUDP(addr, target, proxy string, in chan<- C.PacketAdapter) (*PacketConn, error) {
2022-11-18 22:57:33 +08:00
l, err := net.ListenPacket("udp", addr)
if err != nil {
return nil, err
}
2022-11-18 22:57:33 +08:00
targetAddr := socks5.ParseAddr(target)
if targetAddr == nil {
return nil, fmt.Errorf("invalid target address %s", target)
}
sl := &PacketConn{
conn: l,
target: targetAddr,
proxy: proxy,
addr: addr,
}
go func() {
for {
buf := pool.Get(pool.UDPBufferSize)
n, remoteAddr, err := l.ReadFrom(buf)
if err != nil {
2022-11-18 22:57:33 +08:00
pool.Put(buf)
if sl.closed {
break
}
2022-11-18 22:57:33 +08:00
continue
}
2022-11-18 22:57:33 +08:00
sl.handleUDP(l, in, buf[:n], remoteAddr)
}
}()
2022-11-18 22:57:33 +08:00
return sl, nil
}
func (l *PacketConn) handleUDP(pc net.PacketConn, in chan<- C.PacketAdapter, buf []byte, addr net.Addr) {
2022-11-18 22:57:33 +08:00
packet := &packet{
pc: pc,
rAddr: addr,
payload: buf,
}
2022-11-18 22:57:33 +08:00
ctx := inbound.NewPacket(l.target, packet, C.TUNNEL)
ctx.Metadata().SpecialProxy = l.proxy
select {
case in <- ctx:
default:
}
}