package socks import ( "net" "github.com/Dreamacro/clash/adapter/inbound" "github.com/Dreamacro/clash/common/pool" "github.com/Dreamacro/clash/common/sockopt" C "github.com/Dreamacro/clash/constant" "github.com/Dreamacro/clash/log" "github.com/Dreamacro/clash/transport/socks5" ) type UDPListener struct { packetConn net.PacketConn addr string closed bool name string preferRulesName string } // 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, in chan<- C.PacketAdapter) (*UDPListener, error) { return NewUDPWithInfos(addr, "DEFAULT-SOCKS", "", in) } func NewUDPWithInfos(addr, name, preferRulesName string, in chan<- C.PacketAdapter) (*UDPListener, error) { l, err := net.ListenPacket("udp", addr) if err != nil { return nil, err } if err := sockopt.UDPReuseaddr(l.(*net.UDPConn)); err != nil { log.Warnln("Failed to Reuse UDP Address: %s", err) } sl := &UDPListener{ packetConn: l, addr: addr, preferRulesName: preferRulesName, name: name, } go func() { for { buf := pool.Get(pool.UDPBufferSize) n, remoteAddr, err := l.ReadFrom(buf) if err != nil { pool.Put(buf) if sl.closed { break } continue } handleSocksUDP(sl.name, sl.preferRulesName, l, in, buf[:n], remoteAddr) } }() return sl, nil } func handleSocksUDP(name, preferRulesName string, pc net.PacketConn, in chan<- C.PacketAdapter, buf []byte, addr net.Addr) { target, payload, err := socks5.DecodeUDPPacket(buf) if err != nil { // Unresolved UDP packet, return buffer to the pool pool.Put(buf) return } packet := &packet{ pc: pc, rAddr: addr, payload: payload, bufRef: buf, } select { case in <- inbound.NewPacketWithInfos(target, packet, C.SOCKS5, name, preferRulesName): default: } }