Clash.Meta/listener/socks/udp.go

93 lines
2.0 KiB
Go
Raw Normal View History

package socks
import (
"net"
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/adapter/inbound"
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/sockopt"
C "github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/log"
"github.com/metacubex/mihomo/transport/socks5"
)
2021-06-13 17:23:10 +08:00
type UDPListener struct {
packetConn net.PacketConn
addr string
closed bool
}
2021-08-01 00:35:37 +08:00
// RawAddress implements C.Listener
func (l *UDPListener) RawAddress() string {
return l.addr
}
// Address implements C.Listener
func (l *UDPListener) Address() string {
return l.packetConn.LocalAddr().String()
}
// Close implements C.Listener
func (l *UDPListener) Close() error {
l.closed = true
return l.packetConn.Close()
}
func NewUDP(addr string, tunnel C.Tunnel, additions ...inbound.Addition) (*UDPListener, error) {
if len(additions) == 0 {
additions = []inbound.Addition{
inbound.WithInName("DEFAULT-SOCKS"),
inbound.WithSpecialRules(""),
}
}
l, err := net.ListenPacket("udp", addr)
if err != nil {
return nil, err
}
2021-06-13 17:23:10 +08:00
if err := sockopt.UDPReuseaddr(l.(*net.UDPConn)); err != nil {
log.Warnln("Failed to Reuse UDP Address: %s", err)
}
sl := &UDPListener{
packetConn: l,
addr: addr,
}
conn := N.NewEnhancePacketConn(l)
go func() {
for {
data, put, remoteAddr, err := conn.WaitReadFrom()
if err != nil {
if put != nil {
put()
}
if sl.closed {
break
}
continue
}
handleSocksUDP(l, tunnel, data, put, remoteAddr, additions...)
}
}()
return sl, nil
}
func handleSocksUDP(pc net.PacketConn, tunnel C.Tunnel, buf []byte, put func(), addr net.Addr, additions ...inbound.Addition) {
2019-10-11 20:11:18 +08:00
target, payload, err := socks5.DecodeUDPPacket(buf)
if err != nil {
2019-10-11 20:11:18 +08:00
// Unresolved UDP packet, return buffer to the pool
if put != nil {
put()
}
return
}
packet := &packet{
pc: pc,
rAddr: addr,
payload: payload,
put: put,
2019-10-11 20:11:18 +08:00
}
tunnel.HandleUDPPacket(inbound.NewPacket(target, packet, C.SOCKS5, additions...))
}