mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-11-27 20:10:17 +00:00
Hysteria proxy: Port v2.14.0 UDP forwarding optimizations; Bump quic-go (#7487)
https://github.com/XTLS/Xray-core/issues/7419#issuecomment-7063773710 Closes https://github.com/XTLS/Xray-core/issues/7484#issuecomment-7188906214
This commit is contained in:
@@ -3,7 +3,7 @@ module github.com/xtls/xray-core
|
||||
go 1.27
|
||||
|
||||
require (
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c
|
||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a
|
||||
github.com/bufbuild/protocompile v0.14.1
|
||||
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
|
||||
github.com/golang/mock v1.7.0-rc.1
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c h1:cxK8qTA0YCsj68A7zLYDCfPgMTOyt3ePkHh+oXEmYU0=
|
||||
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
|
||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a h1:uCIlOCbXUtBkFk47HxIkQieCkV+zKv5VCDawLtj3Pkc=
|
||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
|
||||
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
|
||||
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
|
||||
+39
-14
@@ -5,6 +5,7 @@ import (
|
||||
go_errors "errors"
|
||||
"io"
|
||||
"math/rand"
|
||||
"slices"
|
||||
|
||||
"github.com/apernet/quic-go"
|
||||
"github.com/xtls/xray-core/common"
|
||||
@@ -174,10 +175,15 @@ func init() {
|
||||
}))
|
||||
}
|
||||
|
||||
// UDPWriter is not safe for concurrent writes.
|
||||
type UDPWriter struct {
|
||||
writer io.Writer
|
||||
addr string
|
||||
buf [buf.Size]byte
|
||||
|
||||
// Last b.UDP and its NetAddr, which allocates on every call.
|
||||
lastUDP net.Destination
|
||||
lastUDPAddr string
|
||||
}
|
||||
|
||||
func (w *UDPWriter) SendMessage(msg *UDPMessage) error {
|
||||
@@ -193,21 +199,21 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
for i, b := range mb {
|
||||
addr := w.addr
|
||||
if b.UDP != nil {
|
||||
addr = b.UDP.NetAddr()
|
||||
if *b.UDP != w.lastUDP {
|
||||
w.lastUDP = *b.UDP
|
||||
w.lastUDPAddr = b.UDP.NetAddr()
|
||||
}
|
||||
addr = w.lastUDPAddr
|
||||
}
|
||||
|
||||
msg := &UDPMessage{
|
||||
SessionID: 0,
|
||||
PacketID: 0,
|
||||
FragID: 0,
|
||||
FragCount: 1,
|
||||
Addr: addr,
|
||||
Data: b.Bytes(),
|
||||
}
|
||||
|
||||
err := w.SendMessage(msg)
|
||||
var errTooLarge *quic.DatagramTooLargeError
|
||||
if go_errors.As(err, &errTooLarge) {
|
||||
if errTooLarge, ok := go_errors.AsType[*quic.DatagramTooLargeError](err); ok {
|
||||
msg.PacketID = uint16(rand.Intn(0xFFFF)) + 1
|
||||
fMsgs := FragUDPMessage(msg, int(errTooLarge.MaxDatagramPayloadSize))
|
||||
for _, fMsg := range fMsgs {
|
||||
@@ -228,40 +234,59 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// UDPReader is not safe for concurrent reads.
|
||||
type UDPReader struct {
|
||||
reader io.Reader
|
||||
df *Defragger
|
||||
firstBuf *buf.Buffer
|
||||
|
||||
// Last message address and its parsed destination.
|
||||
lastAddr string
|
||||
lastDest net.Destination
|
||||
|
||||
packet [1500]byte
|
||||
msg UDPMessage
|
||||
}
|
||||
|
||||
func (r *UDPReader) ReadFrom(p []byte) (n int, addr *net.Destination, err error) {
|
||||
for {
|
||||
var packet [1500]byte
|
||||
|
||||
n, err := r.reader.Read(packet[:])
|
||||
n, err := r.reader.Read(r.packet[:])
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
msg, err := ParseUDPMessage(packet[:n])
|
||||
if err != nil {
|
||||
if err := parseUDPMessage(r.packet[:n], r.lastAddr, &r.msg); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
msg := &r.msg
|
||||
if msg.FragCount > 1 {
|
||||
// The defragger keeps fragments between calls, so they must not alias packet.
|
||||
frag := *msg
|
||||
frag.Data = slices.Clone(msg.Data)
|
||||
msg = &frag
|
||||
}
|
||||
|
||||
dfMsg := r.df.Feed(msg)
|
||||
if dfMsg == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
|
||||
if err != nil {
|
||||
continue
|
||||
if dfMsg.Addr != r.lastAddr {
|
||||
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
r.lastAddr = dfMsg.Addr
|
||||
r.lastDest = dest
|
||||
}
|
||||
|
||||
if len(p) < len(dfMsg.Data) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Callers can rewrite the packet destination in place.
|
||||
dest := r.lastDest
|
||||
return copy(p, dfMsg.Data), &dest, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/apernet/quic-go"
|
||||
"github.com/xtls/xray-core/common/buf"
|
||||
xnet "github.com/xtls/xray-core/common/net"
|
||||
)
|
||||
|
||||
// datagramReader returns one datagram per Read, like a QUIC datagram stream.
|
||||
type datagramReader struct {
|
||||
msgs [][]byte
|
||||
}
|
||||
|
||||
func (r *datagramReader) Read(p []byte) (int, error) {
|
||||
if len(r.msgs) == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(p, r.msgs[0])
|
||||
r.msgs = r.msgs[1:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func newTestReader(msgs []UDPMessage) *UDPReader {
|
||||
datagrams := make([][]byte, len(msgs))
|
||||
for i := range msgs {
|
||||
datagrams[i] = make([]byte, msgs[i].Size())
|
||||
msgs[i].Serialize(datagrams[i])
|
||||
}
|
||||
return &UDPReader{reader: &datagramReader{msgs: datagrams}, df: &Defragger{}}
|
||||
}
|
||||
|
||||
func TestUDPReaderFragments(t *testing.T) {
|
||||
want := &UDPMessage{PacketID: 1, Addr: "example.com:443", Data: bytes.Repeat([]byte("0123456789"), 20)}
|
||||
frags := FragUDPMessage(want, 100)
|
||||
if len(frags) < 2 {
|
||||
t.Fatalf("got %d fragments, want at least 2", len(frags))
|
||||
}
|
||||
|
||||
p := make([]byte, buf.Size)
|
||||
n, dest, err := newTestReader(frags).ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
|
||||
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, want.Data, want.Addr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUDPReaderDestinations(t *testing.T) {
|
||||
msgs := []UDPMessage{
|
||||
{Addr: "203.0.113.1:53", Data: []byte("first")},
|
||||
{Addr: "203.0.113.1:53", Data: []byte("second")},
|
||||
{Addr: "203.0.113.2:53", Data: []byte("third")},
|
||||
}
|
||||
r := newTestReader(msgs)
|
||||
p := make([]byte, buf.Size)
|
||||
for i, want := range msgs {
|
||||
n, dest, err := r.ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
|
||||
t.Errorf("packet %d: got %q to %v, want %q to %s", i, p[:n], dest, want.Data, want.Addr)
|
||||
}
|
||||
// Callers rewrite the destination in place, the next packet must not see it.
|
||||
dest.Port = 5353
|
||||
}
|
||||
}
|
||||
|
||||
type captureWriter struct {
|
||||
writes [][]byte
|
||||
}
|
||||
|
||||
func (w *captureWriter) Write(p []byte) (int, error) {
|
||||
w.writes = append(w.writes, bytes.Clone(p))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestUDPWriterAddress(t *testing.T) {
|
||||
ip := xnet.UDPDestination(xnet.ParseAddress("203.0.113.1"), 53)
|
||||
domain := xnet.UDPDestination(xnet.DomainAddress("example.com"), 53)
|
||||
|
||||
cw := &captureWriter{}
|
||||
w := &UDPWriter{writer: cw, addr: "198.51.100.1:1"}
|
||||
for _, tc := range []struct {
|
||||
udp *xnet.Destination
|
||||
want string
|
||||
}{
|
||||
{&ip, "203.0.113.1:53"},
|
||||
{&domain, "example.com:53"},
|
||||
{nil, "198.51.100.1:1"},
|
||||
{&ip, "203.0.113.1:53"},
|
||||
} {
|
||||
b := buf.FromBytes([]byte("data"))
|
||||
b.UDP = tc.udp
|
||||
if err := w.WriteMultiBuffer(buf.MultiBuffer{b}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msg, err := ParseUDPMessage(cw.writes[len(cw.writes)-1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if msg.Addr != tc.want {
|
||||
t.Errorf("address = %q, want %q", msg.Addr, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fragmentingWriter rejects datagrams larger than max, like a QUIC connection.
|
||||
type fragmentingWriter struct {
|
||||
max int
|
||||
writes [][]byte
|
||||
}
|
||||
|
||||
func (w *fragmentingWriter) Write(p []byte) (int, error) {
|
||||
if len(p) > w.max {
|
||||
return 0, &quic.DatagramTooLargeError{MaxDatagramPayloadSize: int64(w.max)}
|
||||
}
|
||||
w.writes = append(w.writes, bytes.Clone(p))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestUDPWriterFragmentation(t *testing.T) {
|
||||
data := bytes.Repeat([]byte("0123456789"), 20)
|
||||
fw := &fragmentingWriter{max: 100}
|
||||
w := &UDPWriter{writer: fw, addr: "example.com:443"}
|
||||
if err := w.WriteMultiBuffer(buf.MultiBuffer{buf.FromBytes(data)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fw.writes) < 2 {
|
||||
t.Fatalf("got %d datagrams, want at least 2", len(fw.writes))
|
||||
}
|
||||
|
||||
r := &UDPReader{reader: &datagramReader{msgs: fw.writes}, df: &Defragger{}}
|
||||
p := make([]byte, buf.Size)
|
||||
n, dest, err := r.ReadFrom(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dest.NetAddr() != w.addr || !bytes.Equal(p[:n], data) {
|
||||
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, data, w.addr)
|
||||
}
|
||||
}
|
||||
+28
-20
@@ -1,7 +1,6 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -183,35 +182,44 @@ func (m *UDPMessage) Serialize(buf []byte) int {
|
||||
}
|
||||
|
||||
func ParseUDPMessage(msg []byte) (*UDPMessage, error) {
|
||||
m := &UDPMessage{}
|
||||
buf := bytes.NewBuffer(msg)
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.SessionID); err != nil {
|
||||
m := new(UDPMessage)
|
||||
if err := parseUDPMessage(msg, "", m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.PacketID); err != nil {
|
||||
return nil, err
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// parseUDPMessage parses msg into m. m.Data aliases msg; m.Addr is lastAddr
|
||||
// when they are equal, so an unchanged address is not allocated again.
|
||||
func parseUDPMessage(msg []byte, lastAddr string, m *UDPMessage) error {
|
||||
if len(msg) < 8 {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.FragID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := binary.Read(buf, binary.BigEndian, &m.FragCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lAddr, err := quicvarint.Read(buf)
|
||||
lAddr, n, err := quicvarint.Parse(msg[8:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
if lAddr == 0 || lAddr > MaxMessageLength {
|
||||
return nil, errors.New("invalid address length")
|
||||
return errors.New("invalid address length")
|
||||
}
|
||||
bs := buf.Bytes()
|
||||
bs := msg[8+n:]
|
||||
if len(bs) <= int(lAddr) {
|
||||
// We use <= instead of < here as we expect at least one byte of data after the address
|
||||
return nil, errors.New("invalid message length")
|
||||
return errors.New("invalid message length")
|
||||
}
|
||||
m.Addr = string(bs[:lAddr])
|
||||
m.Data = bs[lAddr:]
|
||||
return m, nil
|
||||
*m = UDPMessage{
|
||||
SessionID: binary.BigEndian.Uint32(msg),
|
||||
PacketID: binary.BigEndian.Uint16(msg[4:]),
|
||||
FragID: msg[6],
|
||||
FragCount: msg[7],
|
||||
Data: bs[lAddr:],
|
||||
}
|
||||
if string(bs[:lAddr]) == lastAddr {
|
||||
m.Addr = lastAddr
|
||||
} else {
|
||||
m.Addr = string(bs[:lAddr])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// varintPut is like quicvarint.Append, but instead of appending to a slice,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package hysteria
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseUDPMessage(t *testing.T) {
|
||||
want := &UDPMessage{PacketID: 1, FragID: 2, FragCount: 3, Addr: "example.com:443", Data: []byte("hello")}
|
||||
msg := make([]byte, want.Size())
|
||||
want.Serialize(msg)
|
||||
|
||||
for _, lastAddr := range []string{"", want.Addr, "other:1"} {
|
||||
got := new(UDPMessage)
|
||||
if err := parseUDPMessage(msg, lastAddr, got); err != nil {
|
||||
t.Fatalf("lastAddr %q: %v", lastAddr, err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("lastAddr %q: got %+v, want %+v", lastAddr, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseUDPMessageInvalid(t *testing.T) {
|
||||
msg := &UDPMessage{Addr: "example.com:443", Data: []byte("hello")}
|
||||
buf := make([]byte, msg.Size())
|
||||
msg.Serialize(buf)
|
||||
|
||||
zeroAddrLen := bytes.Clone(buf)
|
||||
zeroAddrLen[8] = 0 // Address length varint follows the 8-byte header
|
||||
|
||||
noData := &UDPMessage{Addr: msg.Addr}
|
||||
noDataBuf := make([]byte, noData.Size())
|
||||
noData.Serialize(noDataBuf)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
msg []byte
|
||||
}{
|
||||
{"short header", buf[:7]},
|
||||
{"zero address length", zeroAddrLen},
|
||||
{"no data after address", noDataBuf},
|
||||
} {
|
||||
if _, err := ParseUDPMessage(tc.msg); err == nil {
|
||||
t.Errorf("%s: expected error", tc.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,11 @@ func (s *Proxy) Proxy(w http.ResponseWriter, r *ProxyRequest) (*Conn, error) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
if ok {
|
||||
return newProxiedConn(streamer.HTTPStream()), nil
|
||||
str, err := streamer.HTTPStream()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newProxiedConn(str), nil
|
||||
}
|
||||
controller := http.NewResponseController(w)
|
||||
if err := controller.Flush(); err != nil {
|
||||
|
||||
@@ -231,7 +231,11 @@ func TestDialWarpHTTP3(t *testing.T) {
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.(http.Flusher).Flush()
|
||||
str := w.(http3.HTTPStreamer).HTTPStream()
|
||||
str, err := w.(http3.HTTPStreamer).HTTPStream()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
go func() { capsules <- readCapsuleTypes(str, nil) }()
|
||||
b, err := str.ReceiveDatagram(r.Context())
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user