Fix socks5 UDP

This commit is contained in:
世界 2025-03-16 10:20:59 +08:00
parent 2238a05966
commit ce1b4851a4
No known key found for this signature in database
GPG key ID: CD109927C34A63C4

View file

@ -10,6 +10,7 @@ import (
"github.com/sagernet/sing/common" "github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/auth" "github.com/sagernet/sing/common/auth"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio" "github.com/sagernet/sing/common/bufio"
E "github.com/sagernet/sing/common/exceptions" E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata" M "github.com/sagernet/sing/common/metadata"
@ -216,9 +217,24 @@ func HandleConnectionEx(
var udpConn *net.UDPConn var udpConn *net.UDPConn
udpConn, err = net.ListenUDP(M.NetworkFromNetAddr("udp", M.AddrFromNet(conn.LocalAddr())), net.UDPAddrFromAddrPort(netip.AddrPortFrom(M.AddrFromNet(conn.LocalAddr()), 0))) udpConn, err = net.ListenUDP(M.NetworkFromNetAddr("udp", M.AddrFromNet(conn.LocalAddr())), net.UDPAddrFromAddrPort(netip.AddrPortFrom(M.AddrFromNet(conn.LocalAddr()), 0)))
if err != nil { if err != nil {
return err return E.Cause(err, "socks5: listen udp")
} }
handler.NewPacketConnectionEx(ctx, NewLazyAssociatePacketConn(bufio.NewServerPacketConn(udpConn), conn), source, M.Socksaddr{}, onClose) err = socks5.WriteResponse(conn, socks5.Response{
ReplyCode: socks5.ReplyCodeSuccess,
Bind: M.SocksaddrFromNet(udpConn.LocalAddr()),
})
if err != nil {
return E.Cause(err, "socks5: write response")
}
var socksPacketConn N.PacketConn = NewAssociatePacketConn(bufio.NewServerPacketConn(udpConn), M.Socksaddr{}, conn)
firstPacket := buf.NewPacket()
var destination M.Socksaddr
destination, err = socksPacketConn.ReadPacket(firstPacket)
if err != nil {
return E.Cause(err, "socks5: read first packet")
}
socksPacketConn = bufio.NewCachedPacketConn(socksPacketConn, firstPacket, destination)
handler.NewPacketConnectionEx(ctx, socksPacketConn, source, destination, onClose)
return nil return nil
default: default:
err = socks5.WriteResponse(conn, socks5.Response{ err = socks5.WriteResponse(conn, socks5.Response{