From 984bf27d9b0bd1193acc1921652e18c9e1b10aea Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Sat, 20 May 2023 18:35:04 +0800 Subject: [PATCH] chore: using internal socks5.ReadAddr0 in trojan --- listener/shadowsocks/tcp.go | 2 +- transport/socks5/socks5.go | 44 +++++++++++++++++++++++++++++++++++++ transport/trojan/trojan.go | 3 +-- 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/listener/shadowsocks/tcp.go b/listener/shadowsocks/tcp.go index 6884b960..febf87c3 100644 --- a/listener/shadowsocks/tcp.go +++ b/listener/shadowsocks/tcp.go @@ -103,7 +103,7 @@ func (l *Listener) HandleConn(conn net.Conn, in chan<- C.ConnContext, additions conn = l.pickCipher.StreamConn(conn) conn = N.NewDeadlineConn(conn) // embed ss can't handle readDeadline correctly - target, err := socks5.ReadAddr(conn, make([]byte, socks5.MaxAddrLen)) + target, err := socks5.ReadAddr0(conn) if err != nil { _ = conn.Close() return diff --git a/transport/socks5/socks5.go b/transport/socks5/socks5.go index 7d4f11ae..6f95cce9 100644 --- a/transport/socks5/socks5.go +++ b/transport/socks5/socks5.go @@ -299,6 +299,50 @@ func ReadAddr(r io.Reader, b []byte) (Addr, error) { return nil, ErrAddressNotSupported } +func ReadAddr0(r io.Reader) (Addr, error) { + aType, err := ReadByte(r) // read 1st byte for address type + if err != nil { + return nil, err + } + + switch aType { + case AtypDomainName: + var domainLength byte + domainLength, err = ReadByte(r) // read 2nd byte for domain length + if err != nil { + return nil, err + } + b := make([]byte, 1+1+uint16(domainLength)+2) + _, err = io.ReadFull(r, b[2:]) + b[0] = aType + b[1] = domainLength + return b, err + case AtypIPv4: + var b [1 + net.IPv4len + 2]byte + _, err = io.ReadFull(r, b[1:]) + b[0] = aType + return b[:], err + case AtypIPv6: + var b [1 + net.IPv6len + 2]byte + _, err = io.ReadFull(r, b[1:]) + b[0] = aType + return b[:], err + } + + return nil, ErrAddressNotSupported +} + +func ReadByte(reader io.Reader) (byte, error) { + if br, isBr := reader.(io.ByteReader); isBr { + return br.ReadByte() + } + var b [1]byte + if _, err := io.ReadFull(reader, b[:]); err != nil { + return 0, err + } + return b[0], nil +} + // SplitAddr slices a SOCKS address from beginning of b. Returns nil if failed. func SplitAddr(b []byte) Addr { addrLen := 1 diff --git a/transport/trojan/trojan.go b/transport/trojan/trojan.go index 90700491..d37026c1 100644 --- a/transport/trojan/trojan.go +++ b/transport/trojan/trojan.go @@ -21,7 +21,6 @@ import ( "github.com/Dreamacro/clash/transport/vless" "github.com/Dreamacro/clash/transport/vmess" - M "github.com/sagernet/sing/common/metadata" xtls "github.com/xtls/go" ) @@ -358,7 +357,7 @@ func (pc *PacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, er pc.mux.Lock() defer pc.mux.Unlock() - destination, err := M.SocksaddrSerializer.ReadAddrPort(pc.Conn) + destination, err := socks5.ReadAddr0(pc.Conn) if err != nil { return nil, nil, nil, err }