mihomo/listener/shadowsocks/udp.go

81 lines
1.7 KiB
Go
Raw Permalink Normal View History

package shadowsocks
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/shadowsocks/core"
"github.com/metacubex/mihomo/transport/socks5"
)
type UDPListener struct {
packetConn net.PacketConn
closed bool
}
func NewUDP(addr string, pickCipher core.Cipher, tunnel C.Tunnel) (*UDPListener, error) {
l, err := net.ListenPacket("udp", addr)
if err != nil {
return nil, err
}
err = sockopt.UDPReuseaddr(l.(*net.UDPConn))
if err != nil {
log.Warnln("Failed to Reuse UDP Address: %s", err)
}
sl := &UDPListener{l, false}
2023-05-28 22:51:26 +08:00
conn := pickCipher.PacketConn(N.NewEnhancePacketConn(l))
go func() {
for {
2023-05-28 22:51:26 +08:00
data, put, remoteAddr, err := conn.WaitReadFrom()
if err != nil {
2023-05-28 22:51:26 +08:00
if put != nil {
put()
}
if sl.closed {
break
}
continue
}
handleSocksUDP(conn, tunnel, data, put, remoteAddr)
}
}()
return sl, nil
}
func (l *UDPListener) Close() error {
l.closed = true
return l.packetConn.Close()
}
func (l *UDPListener) LocalAddr() net.Addr {
return l.packetConn.LocalAddr()
}
func handleSocksUDP(pc net.PacketConn, tunnel C.Tunnel, buf []byte, put func(), addr net.Addr, additions ...inbound.Addition) {
tgtAddr := socks5.SplitAddr(buf)
if tgtAddr == nil {
// Unresolved UDP packet, return buffer to the pool
2023-05-28 22:51:26 +08:00
if put != nil {
put()
}
return
}
2023-10-11 10:55:12 +08:00
target := tgtAddr
payload := buf[len(tgtAddr):]
packet := &packet{
pc: pc,
rAddr: addr,
payload: payload,
2023-05-28 22:51:26 +08:00
put: put,
}
tunnel.HandleUDPPacket(inbound.NewPacket(target, packet, C.SHADOWSOCKS, additions...))
}