mihomo/listener/tunnel/udp.go

86 lines
1.7 KiB
Go
Raw Permalink 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()
}
2022-12-05 17:03:12 +08:00
func NewUDP(addr, target, proxy string, in chan<- C.PacketAdapter, additions ...inbound.Addition) (*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-12-05 17:03:12 +08:00
sl.handleUDP(l, in, buf[:n], remoteAddr, additions...)
2022-11-18 22:57:33 +08:00
}
}()
2022-11-18 22:57:33 +08:00
return sl, nil
}
2022-12-05 17:03:12 +08:00
func (l *PacketConn) handleUDP(pc net.PacketConn, in chan<- C.PacketAdapter, buf []byte, addr net.Addr, additions ...inbound.Addition) {
2022-11-18 22:57:33 +08:00
packet := &packet{
pc: pc,
rAddr: addr,
payload: buf,
}
2022-12-05 17:03:12 +08:00
ctx := inbound.NewPacket(l.target, packet, C.TUNNEL, additions...)
2022-11-18 22:57:33 +08:00
ctx.Metadata().SpecialProxy = l.proxy
select {
case in <- ctx:
default:
}
}