From 3f27ef39f8c96bbfbc8b0b9bb10f5c9ef60149d8 Mon Sep 17 00:00:00 2001 From: saba-futai <120904569+saba-futai@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:51:58 +0800 Subject: [PATCH] chore: refactored and fixed issues for sudoku while also improving performance (#3333) --- listener/sudoku/server.go | 14 +- transport/sudoku/address.go | 118 +- transport/sudoku/crypto/aead.go | 150 --- transport/sudoku/crypto/record_conn.go | 82 +- transport/sudoku/crypto/record_conn_test.go | 38 + transport/sudoku/handshake.go | 2 +- transport/sudoku/handshake_test.go | 131 ++- transport/sudoku/httpmask_tunnel_test.go | 4 +- transport/sudoku/kip.go | 21 +- transport/sudoku/kip_test.go | 15 + transport/sudoku/multiplex.go | 3 +- transport/sudoku/multiplex/session.go | 202 +++- transport/sudoku/multiplex/session_test.go | 116 +- transport/sudoku/multiplex/write_chunks.go | 12 - transport/sudoku/obfs/httpmask/halfpipe.go | 29 +- transport/sudoku/obfs/httpmask/tunnel_api.go | 52 +- .../sudoku/obfs/httpmask/tunnel_conn_poll.go | 363 ------ .../sudoku/obfs/httpmask/tunnel_conn_queue.go | 41 +- .../sudoku/obfs/httpmask/tunnel_conn_split.go | 493 ++++++++ .../obfs/httpmask/tunnel_conn_stream.go | 375 ------ transport/sudoku/obfs/httpmask/tunnel_dial.go | 20 +- .../sudoku/obfs/httpmask/tunnel_server.go | 1021 +++++++++-------- transport/sudoku/obfs/httpmask/tunnel_test.go | 171 ++- .../sudoku/obfs/httpmask/tunnel_ws_server.go | 40 +- transport/sudoku/obfs/sudoku/conn.go | 188 +-- transport/sudoku/obfs/sudoku/downlink.go | 73 +- transport/sudoku/obfs/sudoku/encode.go | 162 ++- transport/sudoku/obfs/sudoku/layout.go | 59 +- transport/sudoku/obfs/sudoku/packed.go | 314 +++-- .../sudoku/obfs/sudoku/packed_prefix_test.go | 103 ++ transport/sudoku/obfs/sudoku/pending.go | 69 -- transport/sudoku/obfs/sudoku/rand.go | 46 +- transport/sudoku/obfs/sudoku/read_buffer.go | 80 ++ transport/sudoku/obfs/sudoku/table.go | 106 +- transport/sudoku/obfs/sudoku/write_buffer.go | 88 ++ transport/sudoku/table_probe.go | 13 +- transport/sudoku/uot.go | 161 ++- transport/sudoku/write_chunks.go | 12 - 38 files changed, 2685 insertions(+), 2302 deletions(-) delete mode 100644 transport/sudoku/crypto/aead.go delete mode 100644 transport/sudoku/multiplex/write_chunks.go delete mode 100644 transport/sudoku/obfs/httpmask/tunnel_conn_poll.go create mode 100644 transport/sudoku/obfs/httpmask/tunnel_conn_split.go delete mode 100644 transport/sudoku/obfs/httpmask/tunnel_conn_stream.go delete mode 100644 transport/sudoku/obfs/sudoku/pending.go create mode 100644 transport/sudoku/obfs/sudoku/read_buffer.go create mode 100644 transport/sudoku/obfs/sudoku/write_buffer.go delete mode 100644 transport/sudoku/write_chunks.go diff --git a/listener/sudoku/server.go b/listener/sudoku/server.go index e648b656e..0e9371a83 100644 --- a/listener/sudoku/server.go +++ b/listener/sudoku/server.go @@ -11,6 +11,7 @@ import ( "github.com/metacubex/mihomo/adapter/inbound" N "github.com/metacubex/mihomo/common/net" + "github.com/metacubex/mihomo/common/pool" "github.com/metacubex/mihomo/common/utils" C "github.com/metacubex/mihomo/constant" LC "github.com/metacubex/mihomo/listener/config" @@ -145,7 +146,8 @@ func (l *Listener) handleConn(conn net.Conn, tunnel C.Tunnel, additions ...inbou _ = stream.Close() continue } - go l.handler.HandleSocket(targetAddr, stream, additions...) + // mux streams ignore deadlines, so the 200ms sniff peek of a server-speaks-first target would never end + go l.handler.HandleSocket(targetAddr, N.NewDeadlineConn(stream), additions...) } default: targetAddr := socks5.ParseAddr(session.Target) @@ -167,11 +169,12 @@ func wrapSessionConn(conn net.Conn) net.Conn { func (l *Listener) handleUoTSession(conn net.Conn, tunnel C.Tunnel, additions ...inbound.Addition) { writer := sudoku.NewUoTPacketConn(conn) + reader := sudoku.NewUoTReader(conn) remoteAddr := conn.RemoteAddr() connID := utils.NewUUIDV4().String() // make a new SNAT key for { - addrStr, payload, err := sudoku.ReadDatagram(conn) + target, payload, err := reader.ReadDatagram() if err != nil { if !errors.Is(err, io.EOF) { log.Debugln("[Sudoku][UoT] session closed: %v", err) @@ -180,12 +183,6 @@ func (l *Listener) handleUoTSession(conn net.Conn, tunnel C.Tunnel, additions .. return } - target := socks5.ParseAddr(addrStr) - if target == nil { - log.Debugln("[Sudoku][UoT] drop invalid target: %s", addrStr) - continue - } - cPacket := &uotPacket{ payload: payload, writer: writer, @@ -211,6 +208,7 @@ func (p *uotPacket) WriteBack(b []byte, addr net.Addr) (int, error) { } func (p *uotPacket) Drop() { + _ = pool.Put(p.payload) p.payload = nil } diff --git a/transport/sudoku/address.go b/transport/sudoku/address.go index d68205add..7e28b9e46 100644 --- a/transport/sudoku/address.go +++ b/transport/sudoku/address.go @@ -1,100 +1,74 @@ package sudoku import ( - "encoding/binary" + "errors" "fmt" "io" "net" + "net/netip" "strconv" "strings" + + "github.com/metacubex/mihomo/transport/socks5" ) +// EncodeAddress returns the SOCKS5 encoding of rawAddr ("host:port"). func EncodeAddress(rawAddr string) ([]byte, error) { + return AppendAddress(nil, rawAddr) +} + +// AppendAddress appends the SOCKS5 encoding of rawAddr ("host:port") to dst; dst is returned +// unchanged on error. IPv4-mapped IPv6 literals are encoded as IPv4 and IPv6 zones are dropped. +func AppendAddress(dst []byte, rawAddr string) ([]byte, error) { host, portStr, err := net.SplitHostPort(rawAddr) if err != nil { - return nil, err + return dst, err } - portInt, err := strconv.ParseUint(portStr, 10, 16) + port, err := strconv.ParseUint(portStr, 10, 16) if err != nil { - return nil, err + return dst, err } - var buf []byte if i := strings.IndexByte(host, '%'); i >= 0 { // Zone identifiers are not representable in SOCKS5 IPv6 address encoding. host = host[:i] } - if ip := net.ParseIP(host); ip != nil { - if ip4 := ip.To4(); ip4 != nil { - buf = append(buf, 0x01) // IPv4 - buf = append(buf, ip4...) - } else { - buf = append(buf, 0x04) // IPv6 - ip16 := ip.To16() - if ip16 == nil { - return nil, fmt.Errorf("invalid ipv6: %q", host) - } - buf = append(buf, ip16...) - } + if ip, err := netip.ParseAddr(host); err == nil { + return AppendAddrPort(dst, netip.AddrPortFrom(ip, uint16(port))), nil + } + if len(host) > 255 { + return dst, errors.New("domain too long") + } + dst = append(dst, socks5.AtypDomainName, byte(len(host))) + dst = append(dst, host...) + return append(dst, byte(port>>8), byte(port)), nil +} + +// AppendAddrPort appends the SOCKS5 encoding of an IP destination to dst. IPv4-mapped IPv6 +// addresses are encoded as IPv4 and zones are dropped. +func AppendAddrPort(dst []byte, ap netip.AddrPort) []byte { + if ip := ap.Addr().Unmap(); ip.Is4() { + v := ip.As4() + dst = append(dst, socks5.AtypIPv4) + dst = append(dst, v[:]...) } else { - if len(host) > 255 { - return nil, fmt.Errorf("domain too long") - } - buf = append(buf, 0x03) // domain - buf = append(buf, byte(len(host))) - buf = append(buf, host...) + v := ip.As16() + dst = append(dst, socks5.AtypIPv6) + dst = append(dst, v[:]...) } - - var portBytes [2]byte - binary.BigEndian.PutUint16(portBytes[:], uint16(portInt)) - buf = append(buf, portBytes[:]...) - return buf, nil + return append(dst, byte(ap.Port()>>8), byte(ap.Port())) } -func DecodeAddress(r io.Reader) (string, error) { - var atyp [1]byte - if _, err := io.ReadFull(r, atyp[:]); err != nil { - return "", err - } - - switch atyp[0] { - case 0x01: // IPv4 - var ipBuf [net.IPv4len]byte - if _, err := io.ReadFull(r, ipBuf[:]); err != nil { - return "", err - } - var portBuf [2]byte - if _, err := io.ReadFull(r, portBuf[:]); err != nil { - return "", err - } - return net.JoinHostPort(net.IP(ipBuf[:]).String(), fmt.Sprint(binary.BigEndian.Uint16(portBuf[:]))), nil - case 0x04: // IPv6 - var ipBuf [net.IPv6len]byte - if _, err := io.ReadFull(r, ipBuf[:]); err != nil { - return "", err - } - var portBuf [2]byte - if _, err := io.ReadFull(r, portBuf[:]); err != nil { - return "", err - } - return net.JoinHostPort(net.IP(ipBuf[:]).String(), fmt.Sprint(binary.BigEndian.Uint16(portBuf[:]))), nil - case 0x03: // domain - var lengthBuf [1]byte - if _, err := io.ReadFull(r, lengthBuf[:]); err != nil { - return "", err - } - l := int(lengthBuf[0]) - hostBuf := make([]byte, l) - if _, err := io.ReadFull(r, hostBuf); err != nil { - return "", err - } - var portBuf [2]byte - if _, err := io.ReadFull(r, portBuf[:]); err != nil { - return "", err - } - return net.JoinHostPort(string(hostBuf), fmt.Sprint(binary.BigEndian.Uint16(portBuf[:]))), nil - default: - return "", fmt.Errorf("unknown address type: %d", atyp[0]) +// DecodeAddress parses the SOCKS5 address at the start of b and returns it as "host:port"; +// bytes after the address are ignored. +func DecodeAddress(b []byte) (string, error) { + addr := socks5.SplitAddr(b) + if addr == nil { + if len(b) == 0 { + return "", io.EOF + } + return "", fmt.Errorf("invalid address: type %d, %d bytes", b[0], len(b)) } + return addr.String(), nil } diff --git a/transport/sudoku/crypto/aead.go b/transport/sudoku/crypto/aead.go deleted file mode 100644 index 368caea32..000000000 --- a/transport/sudoku/crypto/aead.go +++ /dev/null @@ -1,150 +0,0 @@ -package crypto - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "crypto/sha256" - "encoding/binary" - "errors" - "fmt" - "io" - "net" - - "golang.org/x/crypto/chacha20poly1305" -) - -type AEADConn struct { - net.Conn - aead cipher.AEAD - readBuf bytes.Buffer - nonceSize int -} - -func (cc *AEADConn) CloseWrite() error { - if cc == nil || cc.Conn == nil { - return nil - } - if cw, ok := cc.Conn.(interface{ CloseWrite() error }); ok { - return cw.CloseWrite() - } - return nil -} - -func (cc *AEADConn) CloseRead() error { - if cc == nil || cc.Conn == nil { - return nil - } - if cr, ok := cc.Conn.(interface{ CloseRead() error }); ok { - return cr.CloseRead() - } - return nil -} - -func NewAEADConn(c net.Conn, key string, method string) (*AEADConn, error) { - if method == "none" { - return &AEADConn{Conn: c, aead: nil}, nil - } - - h := sha256.New() - h.Write([]byte(key)) - keyBytes := h.Sum(nil) - - var aead cipher.AEAD - var err error - - switch method { - case "aes-128-gcm": - block, _ := aes.NewCipher(keyBytes[:16]) - aead, err = cipher.NewGCM(block) - case "chacha20-poly1305": - aead, err = chacha20poly1305.New(keyBytes) - default: - return nil, fmt.Errorf("unsupported cipher: %s", method) - } - if err != nil { - return nil, err - } - - return &AEADConn{ - Conn: c, - aead: aead, - nonceSize: aead.NonceSize(), - }, nil -} - -func (cc *AEADConn) Write(p []byte) (int, error) { - if cc.aead == nil { - return cc.Conn.Write(p) - } - - maxPayload := 65535 - cc.nonceSize - cc.aead.Overhead() - totalWritten := 0 - var frameBuf bytes.Buffer - header := make([]byte, 2) - nonce := make([]byte, cc.nonceSize) - - for len(p) > 0 { - chunkSize := len(p) - if chunkSize > maxPayload { - chunkSize = maxPayload - } - chunk := p[:chunkSize] - p = p[chunkSize:] - - if _, err := io.ReadFull(rand.Reader, nonce); err != nil { - return totalWritten, err - } - - ciphertext := cc.aead.Seal(nil, nonce, chunk, nil) - frameLen := len(nonce) + len(ciphertext) - binary.BigEndian.PutUint16(header, uint16(frameLen)) - - frameBuf.Reset() - frameBuf.Write(header) - frameBuf.Write(nonce) - frameBuf.Write(ciphertext) - - if _, err := cc.Conn.Write(frameBuf.Bytes()); err != nil { - return totalWritten, err - } - totalWritten += chunkSize - } - return totalWritten, nil -} - -func (cc *AEADConn) Read(p []byte) (int, error) { - if cc.aead == nil { - return cc.Conn.Read(p) - } - - if cc.readBuf.Len() > 0 { - return cc.readBuf.Read(p) - } - - header := make([]byte, 2) - if _, err := io.ReadFull(cc.Conn, header); err != nil { - return 0, err - } - frameLen := int(binary.BigEndian.Uint16(header)) - - body := make([]byte, frameLen) - if _, err := io.ReadFull(cc.Conn, body); err != nil { - return 0, err - } - - if len(body) < cc.nonceSize { - return 0, errors.New("frame too short") - } - nonce := body[:cc.nonceSize] - ciphertext := body[cc.nonceSize:] - - plaintext, err := cc.aead.Open(nil, nonce, ciphertext, nil) - if err != nil { - return 0, errors.New("decryption failed") - } - - cc.readBuf.Write(plaintext) - return cc.readBuf.Read(p) -} diff --git a/transport/sudoku/crypto/record_conn.go b/transport/sudoku/crypto/record_conn.go index e4e68d1e0..0a46eeb42 100644 --- a/transport/sudoku/crypto/record_conn.go +++ b/transport/sudoku/crypto/record_conn.go @@ -1,7 +1,6 @@ package crypto import ( - "bytes" "crypto/aes" "crypto/cipher" "crypto/hmac" @@ -15,6 +14,8 @@ import ( "sync" "sync/atomic" + "github.com/metacubex/mihomo/common/pool" + "golang.org/x/crypto/chacha20poly1305" ) @@ -67,11 +68,12 @@ type RecordConn struct { recvSeq uint64 recvInitialized bool - readBuf bytes.Buffer - - // writeFrame is a reusable buffer for [len||header||ciphertext] on the wire. - // Guarded by writeMu. - writeFrame []byte + // readFrame is the pooled record whose decrypted plaintext (readPlain) the + // caller has not fully read yet; it is nil whenever the connection is idle. + // Guarded by readMu. + readFrame []byte + readPlain []byte + readOff int } func (c *RecordConn) CloseWrite() error { @@ -137,7 +139,7 @@ func (c *RecordConn) Rekey(baseSend, baseRecv []byte) error { if err := c.resetTrafficState(); err != nil { return err } - c.readBuf.Reset() + c.releaseReadFrame() c.sendAEAD = nil c.recvAEAD = nil @@ -357,17 +359,16 @@ func (c *RecordConn) Write(p []byte) (int, error) { if bodyLen > maxFrameBodySize { return total, errors.New("frame too large") } - if cap(c.writeFrame) < frameLen { - c.writeFrame = make([]byte, frameLen) - } - frame := c.writeFrame[:frameLen] + frame := pool.Get(frameLen) binary.BigEndian.PutUint16(frame[:2], uint16(bodyLen)) copy(frame[2:2+recordHeaderSize], header[:]) dst := frame[2+recordHeaderSize : 2+recordHeaderSize : frameLen] _ = aead.Seal(dst[:0], header[:], chunk, header[:]) - if _, err := c.Conn.Write(frame); err != nil { + _, err := c.Conn.Write(frame) + _ = pool.Put(frame) + if err != nil { return total, err } @@ -390,8 +391,8 @@ func (c *RecordConn) Read(p []byte) (int, error) { c.readMu.Lock() defer c.readMu.Unlock() - if c.readBuf.Len() > 0 { - return c.readBuf.Read(p) + if c.readOff < len(c.readPlain) { + return c.drainPlain(p), nil } var lenBuf [2]byte @@ -406,10 +407,25 @@ func (c *RecordConn) Read(p []byte) (int, error) { return 0, errors.New("frame too large") } - body := make([]byte, bodyLen) + body := pool.Get(bodyLen) if _, err := io.ReadFull(c.Conn, body); err != nil { + _ = pool.Put(body) return 0, err } + n, plain, err := c.open(body, p) + if plain == nil { + _ = pool.Put(body) + return n, err + } + // p was too small for the record: keep the frame until it is drained. + c.readFrame, c.readPlain, c.readOff = body, plain, 0 + return c.drainPlain(p), nil +} + +// open authenticates one record body. The plaintext goes straight into p when it +// fits (n bytes, plain == nil); otherwise it is decrypted in place and returned as +// plain for drainPlain to hand out. +func (c *RecordConn) open(body, p []byte) (n int, plain []byte, err error) { header := body[:recordHeaderSize] ciphertext := body[recordHeaderSize:] @@ -417,25 +433,49 @@ func (c *RecordConn) Read(p []byte) (int, error) { seq := binary.BigEndian.Uint64(header[4:]) if err := c.validateRecvPosition(epoch, seq); err != nil { - return 0, err + return 0, nil, err } if c.recvAEAD == nil || c.recvAEADEpoch != epoch { a, err := c.newAEADFor(c.keys.baseRecv, epoch) if err != nil { - return 0, err + return 0, nil, err } c.recvAEAD = a c.recvAEADEpoch = epoch } aead := c.recvAEAD - plaintext, err := aead.Open(nil, header, ciphertext, header) + plainSize := len(ciphertext) - aead.Overhead() + direct := plainSize >= 0 && len(p) >= plainSize + dst := ciphertext[:0] + if direct { + dst = p[:0] + } + plaintext, err := aead.Open(dst, header, ciphertext, header) if err != nil { - return 0, fmt.Errorf("decryption failed: epoch=%d seq=%d: %w", epoch, seq, err) + return 0, nil, fmt.Errorf("decryption failed: epoch=%d seq=%d: %w", epoch, seq, err) } c.markRecvPosition(epoch, seq) - c.readBuf.Write(plaintext) - return c.readBuf.Read(p) + if direct { + return len(plaintext), nil, nil + } + return 0, plaintext, nil +} + +func (c *RecordConn) drainPlain(dst []byte) int { + n := copy(dst, c.readPlain[c.readOff:]) + c.readOff += n + if c.readOff >= len(c.readPlain) { + c.releaseReadFrame() + } + return n +} + +func (c *RecordConn) releaseReadFrame() { + if c.readFrame != nil { + _ = pool.Put(c.readFrame) + } + c.readFrame, c.readPlain, c.readOff = nil, nil, 0 } diff --git a/transport/sudoku/crypto/record_conn_test.go b/transport/sudoku/crypto/record_conn_test.go index 4ea0b9b88..31f555dc0 100644 --- a/transport/sudoku/crypto/record_conn_test.go +++ b/transport/sudoku/crypto/record_conn_test.go @@ -84,3 +84,41 @@ func TestRecordConn_FirstFrameUsesRandomizedCounters(t *testing.T) { t.Fatalf("plaintext mismatch: got %q want %q", got, want) } } + +func TestRecordConn_SmallReadsReleaseFrame(t *testing.T) { + pskSend := sha256.Sum256([]byte("record-send")) + pskRecv := sha256.Sum256([]byte("record-recv")) + + raw := &captureConn{} + writer, err := NewRecordConn(raw, "chacha20-poly1305", pskSend[:], pskRecv[:]) + if err != nil { + t.Fatalf("new writer: %v", err) + } + want := bytes.Repeat([]byte("0123456789abcdef"), 1024) + if _, err := writer.Write(want); err != nil { + t.Fatalf("write: %v", err) + } + + reader, err := NewRecordConn(&replayConn{reader: bytes.NewReader(raw.Bytes())}, "chacha20-poly1305", pskRecv[:], pskSend[:]) + if err != nil { + t.Fatalf("new reader: %v", err) + } + got := make([]byte, len(want)) + buf := make([]byte, 100) + for off := 0; off < len(got); { + n, err := reader.Read(buf) + if err != nil { + t.Fatalf("read: %v", err) + } + if reader.readFrame != nil && reader.readOff >= len(reader.readPlain) { + t.Fatal("drained record still holds its frame") + } + off += copy(got[off:], buf[:n]) + } + if !bytes.Equal(got, want) { + t.Fatal("plaintext mismatch") + } + if reader.readFrame != nil { + t.Fatal("idle reader holds a frame") + } +} diff --git a/transport/sudoku/handshake.go b/transport/sudoku/handshake.go index 8ed9e60c3..e49bf014e 100644 --- a/transport/sudoku/handshake.go +++ b/transport/sudoku/handshake.go @@ -526,7 +526,7 @@ func ReadServerSession(conn net.Conn, meta *HandshakeMeta) (*ServerSession, erro case KIPTypeStartMux: return &ServerSession{Conn: conn, Type: SessionTypeMultiplex, UserHash: userHash}, nil case KIPTypeOpenTCP: - target, err := DecodeAddress(bytes.NewReader(first.Payload)) + target, err := DecodeAddress(first.Payload) if err != nil { return nil, fmt.Errorf("decode target address failed: %w", err) } diff --git a/transport/sudoku/handshake_test.go b/transport/sudoku/handshake_test.go index c940c764a..39a512b49 100644 --- a/transport/sudoku/handshake_test.go +++ b/transport/sudoku/handshake_test.go @@ -2,6 +2,8 @@ package sudoku import ( "bytes" + "encoding/binary" + "errors" "fmt" "io" "net" @@ -66,6 +68,38 @@ func TestPackedConnRoundTrip_WithPadding(t *testing.T) { } } +// newSocketPair returns two connected loopback conns. The packed tests use it instead of net.Pipe: a pipe +// has no buffer, so a Write returns only once the peer has read every byte, including the padding byte that +// may close it. A decoder that already has the whole message never reads that byte, and a server that +// answers at that point leaves both ends blocked in Write. +func newSocketPair() (server, client net.Conn, err error) { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return nil, nil, err + } + defer ln.Close() + + accepted := make(chan net.Conn, 1) + go func() { + c, err := ln.Accept() + if err != nil { + c = nil + } + accepted <- c + }() + + client, err = net.Dial("tcp", ln.Addr().String()) + if err != nil { + return nil, nil, err + } + server = <-accepted + if server == nil { + _ = client.Close() + return nil, nil, errors.New("accept loopback conn failed") + } + return server, client, nil +} + func newPackedConfig(table *sudokuobfs.Table) *ProtocolConfig { cfg := DefaultConfig() cfg.Key = "sudoku-test-key" @@ -118,12 +152,17 @@ func TestPackedDownlinkSoak(t *testing.T) { } func runPackedTCPSession(id int, cfg *ProtocolConfig, errCh chan<- error) { - serverConn, clientConn := net.Pipe() + serverConn, clientConn, err := newSocketPair() + if err != nil { + errCh <- err + return + } target := fmt.Sprintf("1.1.1.%d:80", (id%200)+1) payload := []byte{0x42, byte(id)} serverErr := make(chan error, 1) go func() { + defer serverConn.Close() c, meta, err := ServerHandshake(serverConn, cfg) if err != nil { serverErr <- fmt.Errorf("server handshake tcp: %w", err) @@ -183,12 +222,17 @@ func runPackedTCPSession(id int, cfg *ProtocolConfig, errCh chan<- error) { } func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) { - serverConn, clientConn := net.Pipe() + serverConn, clientConn, err := newSocketPair() + if err != nil { + errCh <- err + return + } target := "8.8.8.8:53" payload := []byte{0xaa, byte(id)} serverErr := make(chan error, 1) go func() { + defer serverConn.Close() c, meta, err := ServerHandshake(serverConn, cfg) if err != nil { serverErr <- fmt.Errorf("server handshake uot: %w", err) @@ -226,7 +270,7 @@ func runPackedUoTSession(id int, cfg *ProtocolConfig, errCh chan<- error) { return } - addr, data, err := ReadDatagram(cConn) + addr, data, err := readTestDatagram(cConn) if err != nil { errCh <- fmt.Errorf("client read datagram: %w", err) return @@ -270,3 +314,84 @@ func TestCustomTableHandshake(t *testing.T) { } } } + +func readTestDatagram(r io.Reader) (string, []byte, error) { + addr, payload, err := NewUoTReader(r).ReadDatagram() + if err != nil { + return "", nil, err + } + return addr.String(), payload, nil +} + +type countingWriter struct { + writes int + bytes.Buffer +} + +func (w *countingWriter) Write(p []byte) (int, error) { + w.writes++ + return w.Buffer.Write(p) +} + +func TestUoTDatagramIsOneWrite(t *testing.T) { + for _, target := range []string{"8.8.8.8:53", "[2001:db8::1]:443", "example.com:80"} { + var w countingWriter + payload := bytes.Repeat([]byte{0x5a}, 1200) + if err := WriteDatagram(&w, target, payload); err != nil { + t.Fatalf("%s: write datagram: %v", target, err) + } + if w.writes != 1 { + t.Fatalf("%s: datagram took %d writes, want 1", target, w.writes) + } + addr, got, err := readTestDatagram(&w.Buffer) + if err != nil || addr != target || !bytes.Equal(got, payload) { + t.Fatalf("%s: round trip got %q %d bytes, %v", target, addr, len(got), err) + } + } + + var w countingWriter + if err := WriteDatagram(&w, "8.8.8.8:53", make([]byte, 65535)); err != nil { + t.Fatalf("largest payload: %v", err) + } + if err := WriteDatagram(&w, "8.8.8.8:53", make([]byte, 65536)); err == nil { + t.Fatal("payload over 65535 bytes must be rejected") + } +} + +func TestUoTPacketConnReadFrom(t *testing.T) { + frame := func(addr string, padding int, payload string) []byte { + enc, err := EncodeAddress(addr) + if err != nil { + t.Fatal(err) + } + b := binary.BigEndian.AppendUint16(nil, uint16(len(enc)+padding)) + b = binary.BigEndian.AppendUint16(b, uint16(len(payload))) + b = append(b, enc...) + b = append(b, make([]byte, padding)...) + return append(b, payload...) + } + + var stream []byte + stream = append(stream, frame("example.com:53", 0, "dns")...) // domain peers are dropped + stream = append(stream, frame("8.8.8.8:53", 0, "too long for p")...) // consumed, reported as short + stream = append(stream, frame("[::ffff:1.2.3.4]:5353", 300, "ok")...) // padded address, mapped IPv6 + client, server := net.Pipe() + defer client.Close() + go func() { + _, _ = server.Write(stream) + _ = server.Close() + }() + + pc := NewUoTPacketConn(client) + p := make([]byte, 8) + if _, _, err := pc.ReadFrom(p); !errors.Is(err, io.ErrShortBuffer) { + t.Fatalf("oversized datagram: err = %v, want io.ErrShortBuffer", err) + } + n, from, err := pc.ReadFrom(p) + if err != nil || string(p[:n]) != "ok" { + t.Fatalf("read after short buffer: %q, %v", p[:n], err) + } + if udp := from.(*net.UDPAddr); udp.String() != "1.2.3.4:5353" || len(udp.IP) != net.IPv4len { + t.Fatalf("peer = %v (%d-byte IP), want 1.2.3.4:5353 as IPv4", from, len(udp.IP)) + } +} diff --git a/transport/sudoku/httpmask_tunnel_test.go b/transport/sudoku/httpmask_tunnel_test.go index 9a877223e..eca790196 100644 --- a/transport/sudoku/httpmask_tunnel_test.go +++ b/transport/sudoku/httpmask_tunnel_test.go @@ -207,7 +207,7 @@ func TestHTTPMaskTunnel_Poll_UoTRoundTrip(t *testing.T) { if s.Type != SessionTypeUoT { return fmt.Errorf("unexpected session type: %v", s.Type) } - gotAddr, gotPayload, err := ReadDatagram(s.Conn) + gotAddr, gotPayload, err := readTestDatagram(s.Conn) if err != nil { return fmt.Errorf("server read datagram: %w", err) } @@ -250,7 +250,7 @@ func TestHTTPMaskTunnel_Poll_UoTRoundTrip(t *testing.T) { if err := WriteDatagram(cConn, target, payload); err != nil { t.Fatalf("write datagram: %v", err) } - gotAddr, gotPayload, err := ReadDatagram(cConn) + gotAddr, gotPayload, err := readTestDatagram(cConn) if err != nil { t.Fatalf("read datagram: %v", err) } diff --git a/transport/sudoku/kip.go b/transport/sudoku/kip.go index 5cd6eed9f..0123a33cd 100644 --- a/transport/sudoku/kip.go +++ b/transport/sudoku/kip.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/metacubex/mihomo/common/pool" sudokuobfs "github.com/metacubex/mihomo/transport/sudoku/obfs/sudoku" ) @@ -53,6 +54,11 @@ type KIPMessage struct { Payload []byte } +// kipHeaderSize is magic | type | u16 payload length. +const kipHeaderSize = len(kipMagic) + 1 + 2 + +// WriteKIPMessage sends header and payload with a single write, so the transport frames +// them as one record instead of two. func WriteKIPMessage(w io.Writer, typ byte, payload []byte) error { if w == nil { return fmt.Errorf("%w: nil writer", errKIP) @@ -61,19 +67,22 @@ func WriteKIPMessage(w io.Writer, typ byte, payload []byte) error { return fmt.Errorf("%w: payload too large: %d", errKIP, len(payload)) } - var hdr [3 + 1 + 2]byte - copy(hdr[:3], []byte(kipMagic)) - hdr[3] = typ - binary.BigEndian.PutUint16(hdr[4:], uint16(len(payload))) + buf := pool.Get(kipHeaderSize + len(payload)) + defer pool.Put(buf) + copy(buf, kipMagic) + buf[3] = typ + binary.BigEndian.PutUint16(buf[4:], uint16(len(payload))) + copy(buf[kipHeaderSize:], payload) - return writeAllChunks(w, hdr[:], payload) + _, err := w.Write(buf) + return err } func ReadKIPMessage(r io.Reader) (*KIPMessage, error) { if r == nil { return nil, fmt.Errorf("%w: nil reader", errKIP) } - var hdr [3 + 1 + 2]byte + var hdr [kipHeaderSize]byte if _, err := io.ReadFull(r, hdr[:]); err != nil { return nil, err } diff --git a/transport/sudoku/kip_test.go b/transport/sudoku/kip_test.go index a52b1413e..8f070ecf3 100644 --- a/transport/sudoku/kip_test.go +++ b/transport/sudoku/kip_test.go @@ -1,6 +1,7 @@ package sudoku import ( + "bytes" "testing" sudokuobfs "github.com/metacubex/mihomo/transport/sudoku/obfs/sudoku" @@ -62,3 +63,17 @@ func TestResolveClientHelloTableRejectsEntropyMismatch(t *testing.T) { t.Fatalf("expected entropy-table mismatch to fail") } } + +func TestWriteKIPMessageIsOneWrite(t *testing.T) { + var w countingWriter + if err := WriteKIPMessage(&w, KIPTypeOpenTCP, []byte{1, 2, 3}); err != nil { + t.Fatalf("write: %v", err) + } + if w.writes != 1 { + t.Fatalf("KIP message took %d writes, want 1", w.writes) + } + msg, err := ReadKIPMessage(bytes.NewReader(w.Bytes())) + if err != nil || msg.Type != KIPTypeOpenTCP || !bytes.Equal(msg.Payload, []byte{1, 2, 3}) { + t.Fatalf("round trip: %+v, %v", msg, err) + } +} diff --git a/transport/sudoku/multiplex.go b/transport/sudoku/multiplex.go index 6596cc207..21a57b347 100644 --- a/transport/sudoku/multiplex.go +++ b/transport/sudoku/multiplex.go @@ -1,7 +1,6 @@ package sudoku import ( - "bytes" "context" "fmt" "net" @@ -119,7 +118,7 @@ func (s *MultiplexServer) AcceptTCP() (net.Conn, string, error) { return nil, "", err } - target, err := DecodeAddress(bytes.NewReader(payload)) + target, err := DecodeAddress(payload) if err != nil { _ = stream.Close() return nil, "", err diff --git a/transport/sudoku/multiplex/session.go b/transport/sudoku/multiplex/session.go index f7d6ba958..3c66bd0f7 100644 --- a/transport/sudoku/multiplex/session.go +++ b/transport/sudoku/multiplex/session.go @@ -1,6 +1,7 @@ package multiplex import ( + "bytes" "encoding/binary" "errors" "fmt" @@ -9,6 +10,8 @@ import ( "sync" "sync/atomic" "time" + + "github.com/metacubex/mihomo/common/pool" ) const ( @@ -16,6 +19,8 @@ const ( frameData byte = 0x02 frameClose byte = 0x03 frameReset byte = 0x04 + framePing byte = 0x05 + framePong byte = 0x06 ) const ( @@ -26,6 +31,12 @@ const ( maxFrameSize = 256 * 1024 maxDataPayload = 128 * 1024 keepaliveInterval = 15 * time.Second + + // Frames of at most coalesceMaxPayload bytes are queued and written together with the + // frames of other streams; larger ones are written directly behind the queue. A sender + // that finds coalesceMaxPending bytes queued waits for its turn to write. + coalesceMaxPayload = 4 * 1024 + coalesceMaxPending = 64 * 1024 ) var errMuxReceiveQueueFull = errors.New("mux receive queue full") @@ -38,7 +49,11 @@ type acceptEvent struct { type Session struct { conn net.Conn + // writeMu is held by whichever goroutine is writing to conn. Small frames wait in + // pending (guarded by pendMu) so that one write can carry the frames of several streams. writeMu sync.Mutex + pendMu sync.Mutex + pending *bytes.Buffer streamsMu sync.Mutex streams map[uint32]*stream @@ -50,8 +65,10 @@ type Session struct { closeOnce sync.Once closeErr error - lastWrite atomic.Int64 - keepaliveOnce sync.Once + // wroteSinceTick is set by sendFrame and consumed by the idle keepalive tick. + wroteSinceTick atomic.Bool + keepaliveOnce sync.Once + pongPending atomic.Bool } func NewClientSession(conn net.Conn) (*Session, error) { @@ -63,7 +80,6 @@ func NewClientSession(conn net.Conn) (*Session, error) { streams: make(map[uint32]*stream), closed: make(chan struct{}), } - s.lastWrite.Store(time.Now().UnixNano()) go s.readLoop() s.startKeepalive(keepaliveInterval) return s, nil @@ -79,7 +95,6 @@ func NewServerSession(conn net.Conn) (*Session, error) { acceptCh: make(chan acceptEvent, 256), closed: make(chan struct{}), } - s.lastWrite.Store(time.Now().UnixNano()) go s.readLoop() s.startKeepalive(keepaliveInterval) return s, nil @@ -138,6 +153,13 @@ func (s *Session) closeWithError(err error) { close(s.closed) _ = s.conn.Close() + + s.pendMu.Lock() + if s.pending != nil { + pool.PutBuffer(s.pending) + s.pending = nil + } + s.pendMu.Unlock() }) } @@ -188,22 +210,132 @@ func (s *Session) sendFrame(frameType byte, streamID uint32, payload []byte) err return fmt.Errorf("mux payload too large: %d", len(payload)) } - var header [headerSize]byte - header[0] = frameType - binary.BigEndian.PutUint32(header[1:5], streamID) - binary.BigEndian.PutUint32(header[5:9], uint32(len(payload))) - - s.writeMu.Lock() - defer s.writeMu.Unlock() - - if err := writeAllChunks(s.conn, header[:], payload); err != nil { - s.closeWithError(err) + var err error + if len(payload) <= coalesceMaxPayload { + err = s.sendQueued(frameType, streamID, payload) + } else { + err = s.sendDirect(frameType, streamID, payload) + } + if err != nil { return err } - s.lastWrite.Store(time.Now().UnixNano()) + // Load first: the store only happens once per keepalive interval, so the hot path + // never writes the shared cache line. + if !s.wroteSinceTick.Load() { + s.wroteSinceTick.Store(true) + } return nil } +func putHeader(header []byte, frameType byte, streamID uint32, payloadLen int) { + header[0] = frameType + binary.BigEndian.PutUint32(header[1:5], streamID) + binary.BigEndian.PutUint32(header[5:9], uint32(payloadLen)) +} + +// sendQueued appends the frame to the pending batch, then writes the batch unless another +// goroutine is already writing, which picks the frame up when it finishes its current write. +func (s *Session) sendQueued(frameType byte, streamID uint32, payload []byte) error { + var header [headerSize]byte + putHeader(header[:], frameType, streamID, len(payload)) + + s.pendMu.Lock() + if s.pending == nil { + s.pending = pool.GetBuffer() + } + s.pending.Write(header[:]) + s.pending.Write(payload) + full := s.pending.Len() >= coalesceMaxPending + s.pendMu.Unlock() + return s.flushPending(full) +} + +// flushPending writes the pending batch. Unless wait is set it gives up when another +// goroutine holds the write role; that goroutine rechecks the batch after each write, so +// no frame is stranded. +func (s *Session) flushPending(wait bool) error { + for { + if wait { + s.writeMu.Lock() + } else if !s.writeMu.TryLock() { + return nil + } + err := s.writeBatch(nil) + s.writeMu.Unlock() + if err != nil { + return err + } + wait = false + + s.pendMu.Lock() + empty := s.pending == nil + s.pendMu.Unlock() + if empty { + return nil + } + } +} + +// writeBatch writes the pending batch, followed by header when it is not nil, with one +// write. writeMu must be held. +func (s *Session) writeBatch(header []byte) error { + s.pendMu.Lock() + batch := s.pending + s.pending = nil + s.pendMu.Unlock() + + var err error + switch { + case batch == nil && header == nil: + return nil + case batch == nil: + _, err = s.conn.Write(header) + default: + batch.Write(header) + _, err = s.conn.Write(batch.Bytes()) + pool.PutBuffer(batch) + } + if err != nil { + s.closeWithError(err) + } + return err +} + +// sendDirect writes a large frame behind any batch that is already pending, which keeps the +// frames of a stream in order. The header travels with the batch; nothing can be queued in +// front of the payload because writeMu is held until it is written. +func (s *Session) sendDirect(frameType byte, streamID uint32, payload []byte) error { + var header [headerSize]byte + putHeader(header[:], frameType, streamID, len(payload)) + + s.writeMu.Lock() + err := s.writeBatch(header[:]) + if err == nil { + if _, err = s.conn.Write(payload); err != nil { + s.closeWithError(err) + } + } + s.writeMu.Unlock() + if err != nil { + return err + } + // Frames queued while this one was being written still need a writer. + _ = s.flushPending(false) + return nil +} + +// requestPong answers a ping off the read loop, which must not block on a write. Pings that +// arrive while a pong is still waiting to be sent share it. +func (s *Session) requestPong() { + if s.pongPending.Swap(true) { + return + } + go func() { + s.pongPending.Store(false) + _ = s.sendFrame(framePong, 0, nil) + }() +} + func (s *Session) startKeepalive(interval time.Duration) { if s == nil || interval <= 0 { return @@ -215,8 +347,7 @@ func (s *Session) startKeepalive(interval time.Duration) { for { select { case <-ticker.C: - lastWrite := time.Unix(0, s.lastWrite.Load()) - if time.Since(lastWrite) < interval { + if s.wroteSinceTick.Swap(false) { continue } // Stream zero is never allocated. v0.4.7 peers ignore DATA @@ -224,6 +355,8 @@ func (s *Session) startKeepalive(interval time.Duration) { if err := s.sendFrame(frameData, 0, nil); err != nil { return } + // The keepalive itself is not traffic. + s.wroteSinceTick.Store(false) case <-s.closed: return } @@ -299,6 +432,19 @@ func (s *Session) readLoop() { } } switch frameType { + case framePing: + if streamID != 0 || len(payload) != 0 { + s.closeWithError(errors.New("invalid mux ping frame")) + return + } + s.requestPong() + + case framePong: + if streamID != 0 || len(payload) != 0 { + s.closeWithError(errors.New("invalid mux pong frame")) + return + } + case frameOpen: if s.acceptCh == nil { s.sendReset(streamID, "unexpected open") @@ -397,7 +543,7 @@ type stream struct { writeMu sync.Mutex mu sync.Mutex - cond *sync.Cond + cond sync.Cond // cond.L is &mu. closed bool localReadClosed bool localWriteClosed bool @@ -407,19 +553,15 @@ type stream struct { queue [][]byte // queuedBytes includes unread bytes in readBuf and queue. queuedBytes int - - localAddr net.Addr - remoteAddr net.Addr } +// streamAddr is the placeholder address every stream reports; streams have no network +// address of their own, and sharing one value saves two allocations per stream. +var streamAddr net.Addr = &net.TCPAddr{} + func newStream(session *Session, id uint32) *stream { - st := &stream{ - session: session, - id: id, - localAddr: &net.TCPAddr{}, - remoteAddr: &net.TCPAddr{}, - } - st.cond = sync.NewCond(&st.mu) + st := &stream{session: session, id: id} + st.cond.L = &st.mu return st } @@ -623,8 +765,8 @@ func (c *stream) CloseRead() error { return nil } -func (c *stream) LocalAddr() net.Addr { return c.localAddr } -func (c *stream) RemoteAddr() net.Addr { return c.remoteAddr } +func (c *stream) LocalAddr() net.Addr { return streamAddr } +func (c *stream) RemoteAddr() net.Addr { return streamAddr } func (c *stream) SetDeadline(t time.Time) error { _ = c.SetReadDeadline(t) diff --git a/transport/sudoku/multiplex/session_test.go b/transport/sudoku/multiplex/session_test.go index 14cde66d3..114d5cc5a 100644 --- a/transport/sudoku/multiplex/session_test.go +++ b/transport/sudoku/multiplex/session_test.go @@ -18,7 +18,6 @@ func TestSessionKeepaliveUsesV047CompatibleFrame(t *testing.T) { streams: make(map[uint32]*stream), closed: make(chan struct{}), } - session.lastWrite.Store(time.Now().UnixNano()) t.Cleanup(func() { session.closeWithError(net.ErrClosed) _ = peerConn.Close() @@ -266,3 +265,118 @@ func TestStreamConcurrentWritesRemainContiguous(t *testing.T) { } } } + +func TestSessionMixedFrameSizesKeepStreamOrder(t *testing.T) { + clientConn, serverConn := net.Pipe() + clientSession, err := NewClientSession(clientConn) + if err != nil { + t.Fatalf("new client session: %v", err) + } + serverSession, err := NewServerSession(serverConn) + if err != nil { + t.Fatalf("new server session: %v", err) + } + t.Cleanup(func() { + _ = clientSession.Close() + _ = serverSession.Close() + }) + + // Small writes are batched, large ones are written directly behind the batch; each + // stream must still see its own bytes in order. + const streams = 6 + sizes := []int{1, 700, coalesceMaxPayload + 1, 40, maxDataPayload + 5, 3, coalesceMaxPayload, 9000} + expected := func(marker byte) []byte { + var out []byte + for i := 0; i < 20; i++ { + out = append(out, bytes.Repeat([]byte{marker + byte(i)}, sizes[i%len(sizes)])...) + } + return out + } + + type result struct { + marker byte + data []byte + err error + } + results := make(chan result, streams) + go func() { + for i := 0; i < streams; i++ { + st, _, err := serverSession.AcceptStream() + if err != nil { + results <- result{err: err} + continue + } + go func() { + data, err := io.ReadAll(st) + r := result{data: data, err: err} + if len(data) > 0 { + r.marker = data[0] + } + results <- r + }() + } + }() + + var wg sync.WaitGroup + for i := 0; i < streams; i++ { + st, err := clientSession.OpenStream(nil) + if err != nil { + t.Fatalf("open stream: %v", err) + } + wg.Add(1) + go func(st net.Conn, marker byte) { + defer wg.Done() + offset := 0 + data := expected(marker) + for i := 0; offset < len(data); i++ { + n := sizes[i%len(sizes)] + if _, err := st.Write(data[offset : offset+n]); err != nil { + t.Errorf("write: %v", err) + return + } + offset += n + } + _ = st.(interface{ CloseWrite() error }).CloseWrite() + }(st, byte(i*40)) + } + wg.Wait() + + for i := 0; i < streams; i++ { + r := <-results + if r.err != nil { + t.Fatalf("read stream: %v", r.err) + } + if !bytes.Equal(r.data, expected(r.marker)) { + t.Fatalf("stream with marker %d received reordered or corrupted data", r.marker) + } + } +} + +func TestSessionAnswersPingWithPong(t *testing.T) { + sessionConn, peerConn := net.Pipe() + session, err := NewServerSession(sessionConn) + if err != nil { + t.Fatalf("new server session: %v", err) + } + t.Cleanup(func() { + _ = session.Close() + _ = peerConn.Close() + }) + _ = peerConn.SetDeadline(time.Now().Add(2 * time.Second)) + + var ping [headerSize]byte + ping[0] = framePing + if _, err := peerConn.Write(ping[:]); err != nil { + t.Fatalf("write ping: %v", err) + } + var pong [headerSize]byte + if _, err := io.ReadFull(peerConn, pong[:]); err != nil { + t.Fatalf("read pong: %v", err) + } + if pong[0] != framePong || binary.BigEndian.Uint32(pong[1:5]) != 0 || binary.BigEndian.Uint32(pong[5:9]) != 0 { + t.Fatalf("reply = %v, want an empty PONG on stream 0", pong) + } + if session.IsClosed() { + t.Fatal("session closed by ping") + } +} diff --git a/transport/sudoku/multiplex/write_chunks.go b/transport/sudoku/multiplex/write_chunks.go deleted file mode 100644 index a1808b2ca..000000000 --- a/transport/sudoku/multiplex/write_chunks.go +++ /dev/null @@ -1,12 +0,0 @@ -package multiplex - -import "io" - -func writeAllChunks(w io.Writer, chunks ...[]byte) error { - for _, chunk := range chunks { - if _, err := w.Write(chunk); err != nil { - return err - } - } - return nil -} diff --git a/transport/sudoku/obfs/httpmask/halfpipe.go b/transport/sudoku/obfs/httpmask/halfpipe.go index 18fc394d7..d77bb671b 100644 --- a/transport/sudoku/obfs/httpmask/halfpipe.go +++ b/transport/sudoku/obfs/httpmask/halfpipe.go @@ -9,8 +9,10 @@ import ( ) type pipeDeadline struct { - mu sync.Mutex + mu sync.Mutex + // timer is reused across set calls; armed says it may still fire. timer *time.Timer + armed bool cancel chan struct{} } @@ -22,10 +24,10 @@ func (d *pipeDeadline) set(t time.Time) { d.mu.Lock() defer d.mu.Unlock() - if d.timer != nil && !d.timer.Stop() { + if d.armed && !d.timer.Stop() { <-d.cancel } - d.timer = nil + d.armed = false closed := isClosedPipeChan(d.cancel) if t.IsZero() { @@ -39,9 +41,12 @@ func (d *pipeDeadline) set(t time.Time) { if closed { d.cancel = make(chan struct{}) } - d.timer = time.AfterFunc(dur, func() { - close(d.cancel) - }) + if d.timer == nil { + d.timer = time.AfterFunc(dur, d.expire) + } else { + d.timer.Reset(dur) + } + d.armed = true return } @@ -50,6 +55,8 @@ func (d *pipeDeadline) set(t time.Time) { } } +func (d *pipeDeadline) expire() { close(d.cancel) } + func (d *pipeDeadline) wait() <-chan struct{} { d.mu.Lock() ch := d.cancel @@ -93,7 +100,7 @@ type halfPipeConn struct { writeDeadline pipeDeadline } -func newHalfPipe() (net.Conn, net.Conn) { +func newHalfPipe() (*halfPipeConn, *halfPipeConn) { cb1 := make(chan []byte) cb2 := make(chan []byte) cn1 := make(chan int) @@ -162,6 +169,14 @@ func (c *halfPipeConn) Read(p []byte) (int, error) { } } +// awaitReadable blocks until the peer is writing (or the pipe ends or the read deadline fires) without taking any +// bytes: a zero-length Read consumes a writer turn with n=0 and the writer re-offers the rest. It lets an idle +// reader wait without holding a buffer. +func (c *halfPipeConn) awaitReadable() error { + _, err := c.Read(nil) + return err +} + func (c *halfPipeConn) Write(p []byte) (int, error) { switch { case isClosedPipeChan(c.localWriteDone): diff --git a/transport/sudoku/obfs/httpmask/tunnel_api.go b/transport/sudoku/obfs/httpmask/tunnel_api.go index d36e60259..d5d29dea5 100644 --- a/transport/sudoku/obfs/httpmask/tunnel_api.go +++ b/transport/sudoku/obfs/httpmask/tunnel_api.go @@ -3,12 +3,12 @@ package httpmask import ( "context" "fmt" - mrand "math/rand" "net" "strings" "time" "github.com/metacubex/http" + "github.com/metacubex/randv2" ) type TunnelMode string @@ -179,21 +179,39 @@ var ( dialPollFn = dialPoll ) -func applyTunnelHeaders(h http.Header, host string, mode TunnelMode) { - if h == nil { - return +// Header values are prebuilt and shared by every request: the transport only reads them, and a fresh []string per +// header would be most of what applying the profile costs. +var ( + userAgentValues = singleValues(userAgents) + acceptValues = singleValues(accepts) + acceptLanguageValues = singleValues(acceptLanguages) + noCacheValue = []string{"no-cache"} + keepAliveValue = []string{"keep-alive"} + tunnelModeValues = map[TunnelMode][]string{ + TunnelModeStream: {string(TunnelModeStream)}, + TunnelModePoll: {string(TunnelModePoll)}, } - r := rngPool.Get().(*mrand.Rand) - ua := userAgents[r.Intn(len(userAgents))] - accept := accepts[r.Intn(len(accepts))] - lang := acceptLanguages[r.Intn(len(acceptLanguages))] - rngPool.Put(r) - h.Set("User-Agent", ua) - h.Set("Accept", accept) - h.Set("Accept-Language", lang) - h.Set("Cache-Control", "no-cache") - h.Set("Pragma", "no-cache") - h.Set("Connection", "keep-alive") - h.Set("Host", host) - h.Set("X-Sudoku-Tunnel", string(mode)) +) + +func singleValues(vs []string) [][]string { + out := make([][]string, len(vs)) + for i, v := range vs { + out[i] = []string{v} + } + return out +} + +func applyTunnelHeaders(h http.Header, host string, mode TunnelMode) { + h["User-Agent"] = userAgentValues[randv2.IntN(len(userAgentValues))] + h["Accept"] = acceptValues[randv2.IntN(len(acceptValues))] + h["Accept-Language"] = acceptLanguageValues[randv2.IntN(len(acceptLanguageValues))] + h["Cache-Control"] = noCacheValue + h["Pragma"] = noCacheValue + h["Connection"] = keepAliveValue + h["Host"] = []string{host} + modeValue, ok := tunnelModeValues[mode] + if !ok { + modeValue = []string{string(mode)} + } + h["X-Sudoku-Tunnel"] = modeValue } diff --git a/transport/sudoku/obfs/httpmask/tunnel_conn_poll.go b/transport/sudoku/obfs/httpmask/tunnel_conn_poll.go deleted file mode 100644 index 2c2acd8ef..000000000 --- a/transport/sudoku/obfs/httpmask/tunnel_conn_poll.go +++ /dev/null @@ -1,363 +0,0 @@ -package httpmask - -import ( - "bufio" - "bytes" - "context" - "encoding/base64" - "fmt" - "github.com/metacubex/http" - "io" - "net" - "sync/atomic" - "time" -) - -type pollConn struct { - queuedConn - readiness *tunnelReadiness - - ctx context.Context - cancel context.CancelFunc - - client *http.Client - owner *tunnelHTTPTransport - pushURL string - pullURL string - finURL string - closeURL string - headerHost string - uploadSeq atomic.Uint64 -} - -func (c *pollConn) closeWithError(err error) error { - _ = c.queuedConn.closeWithError(err) - if c.cancel != nil { - c.cancel() - } - bestEffortCloseSession(c.client, c.closeURL, c.headerHost, TunnelModePoll) - if c.owner != nil { - c.owner.close() - } - return nil -} - -func (c *pollConn) Close() error { - return c.closeWithError(io.ErrClosedPipe) -} - -func dialPoll(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) { - info, err := dialSession(ctx, serverAddress, opts, TunnelModePoll) - if err != nil { - return nil, err - } - return newPollConn(info, opts) -} - -func dialPollWithClient(ctx context.Context, client *http.Client, dialer *preconnectDialer, target httpClientTarget, opts TunnelDialOptions) (net.Conn, error) { - info, err := dialSessionWithClient(ctx, client, dialer, target, TunnelModePoll, opts, sessionPreconnectCount()) - if err != nil { - return nil, err - } - return newPollConn(info, opts) -} - -func newPollConn(info *sessionDialInfo, opts TunnelDialOptions) (net.Conn, error) { - if info == nil { - return nil, fmt.Errorf("httpmask: nil session") - } - - connCtx, cancel := context.WithCancel(context.Background()) - c := &pollConn{ - ctx: connCtx, - cancel: cancel, - readiness: newTunnelReadiness(), - client: info.client, - owner: info.owner, - pushURL: info.pushURL, - pullURL: info.pullURL, - finURL: info.finURL, - closeURL: info.closeURL, - headerHost: info.headerHost, - queuedConn: newQueuedConn(), - } - - go c.pullLoop() - go c.pushLoop() - outConn := net.Conn(c) - if opts.EarlyHandshake != nil && opts.EarlyHandshake.WrapConn != nil && (opts.EarlyHandshake.Ready == nil || opts.EarlyHandshake.Ready()) { - upgraded, err := opts.EarlyHandshake.WrapConn(c) - if err != nil { - _ = c.Close() - return nil, err - } - if upgraded != nil { - outConn = upgraded - } - return wrapReadyTunnelConn(outConn, c.waitReady), nil - } - if opts.Upgrade != nil { - upgraded, err := opts.Upgrade(c) - if err != nil { - _ = c.Close() - return nil, err - } - if upgraded != nil { - outConn = upgraded - } - } - return wrapReadyTunnelConn(outConn, c.waitReady), nil -} - -func (c *pollConn) waitReady(ctx context.Context) error { - if err := c.readiness.wait(ctx, c.closed, c.closedErr); err != nil { - return err - } - return nil -} - -func (c *pollConn) pullLoop() { - const ( - minBackoff = 10 * time.Millisecond - maxBackoff = 250 * time.Millisecond - ) - - backoff := minBackoff - for { - select { - case <-c.closed: - return - default: - } - - req, err := http.NewRequestWithContext(c.ctx, http.MethodGet, c.pullURL, nil) - if err != nil { - _ = c.closeWithError(err) - return - } - req.Host = c.headerHost - applyTunnelHeaders(req.Header, c.headerHost, TunnelModePoll) - - resp, err := c.client.Do(req) - if err != nil { - if isDialError(err) || isRetryableHTTPTransportError(err) { - closeIdleConnections(c.client) - if err := waitRetry(c.closed, c.closedErr, backoff); err != nil { - return - } - backoff = nextBackoff(backoff, minBackoff, maxBackoff) - continue - } - _ = c.closeWithError(fmt.Errorf("poll pull request failed: %w", err)) - return - } - if resp.StatusCode != http.StatusOK { - if isRetryableStatusCode(resp.StatusCode) { - _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024)) - _ = resp.Body.Close() - closeIdleConnections(c.client) - if err := waitRetry(c.closed, c.closedErr, backoff); err != nil { - return - } - backoff = nextBackoff(backoff, minBackoff, maxBackoff) - continue - } - _ = resp.Body.Close() - _ = c.closeWithError(fmt.Errorf("poll pull bad status: %s", resp.Status)) - return - } - c.readiness.markPullReady() - - scanner := bufio.NewScanner(resp.Body) - for scanner.Scan() { - line := scanner.Bytes() - if len(line) == 0 { - continue - } - payload := make([]byte, base64.StdEncoding.DecodedLen(len(line))) - n, err := base64.StdEncoding.Decode(payload, line) - if err != nil { - _ = resp.Body.Close() - _ = c.closeWithError(fmt.Errorf("poll pull decode failed: %w", err)) - return - } - select { - case c.rxc <- payload[:n]: - case <-c.closed: - _ = resp.Body.Close() - return - } - } - _ = resp.Body.Close() - if err := scanner.Err(); err != nil { - if isRetryableHTTPTransportError(err) { - closeIdleConnections(c.client) - if err := waitRetry(c.closed, c.closedErr, backoff); err != nil { - return - } - backoff = nextBackoff(backoff, minBackoff, maxBackoff) - continue - } - _ = c.closeWithError(fmt.Errorf("poll pull scan failed: %w", err)) - return - } - if resp.Trailer.Get(tunnelStreamEOFHeader) == "1" { - c.markReadEOF() - return - } - backoff = minBackoff - } -} - -func (c *pollConn) pushLoop() { - const ( - maxBatchBytes = 64 * 1024 - flushInterval = 5 * time.Millisecond - maxLineRawBytes = 16 * 1024 - minBackoff = 10 * time.Millisecond - maxBackoff = 250 * time.Millisecond - ) - - var ( - buf bytes.Buffer - encoded = make([]byte, base64.StdEncoding.EncodedLen(maxLineRawBytes)+1) - pendingRaw int - timer = time.NewTimer(flushInterval) - writeErr error - ) - defer timer.Stop() - defer func() { c.completeWrite(writeErr) }() - - fail := func(err error) { - writeErr = err - _ = c.closeWithError(err) - } - - flush := func() error { - if buf.Len() == 0 { - return nil - } - sequence := c.uploadSeq.Add(1) - requestURL, err := uploadURL(c.pushURL, sequence) - if err != nil { - return err - } - payload := append([]byte(nil), buf.Bytes()...) - - if err := retryPersistent(c.closed, c.closedErr, minBackoff, maxBackoff, func() error { - reqCtx, cancel := context.WithTimeout(c.ctx, 20*time.Second) - defer cancel() - req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, requestURL, bytes.NewReader(payload)) - if err != nil { - return err - } - req.Host = c.headerHost - applyTunnelHeaders(req.Header, c.headerHost, TunnelModePoll) - req.Header.Set("Content-Type", "text/plain") - - resp, err := c.client.Do(req) - if err != nil { - closeIdleConnections(c.client) - return err - } - _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024)) - _ = resp.Body.Close() - if resp.StatusCode != http.StatusOK { - err = statusError(resp) - if isRetryableHTTPTransportError(err) { - closeIdleConnections(c.client) - } - return err - } - return nil - }); err != nil { - return err - } - - buf.Reset() - pendingRaw = 0 - c.readiness.markPushReady() - return nil - } - - resetTimer(timer, flushInterval) - - enqueue := func(b []byte) error { - for len(b) > 0 { - chunk := b - if len(chunk) > maxLineRawBytes { - chunk = b[:maxLineRawBytes] - } - b = b[len(chunk):] - - encLen := base64.StdEncoding.EncodedLen(len(chunk)) - if pendingRaw+len(chunk) > maxBatchBytes || buf.Len()+encLen+1 > maxBatchBytes*2 { - if err := flush(); err != nil { - return err - } - } - - tmp := encoded[:encLen] - base64.StdEncoding.Encode(tmp, chunk) - encoded[encLen] = '\n' - _, _ = buf.Write(encoded[:encLen+1]) - pendingRaw += len(chunk) - } - return nil - } - - for { - select { - case b := <-c.writeCh: - if len(b) == 0 { - continue - } - - if err := enqueue(b); err != nil { - fail(fmt.Errorf("poll push flush failed: %w", err)) - return - } - - if pendingRaw >= maxBatchBytes { - if err := flush(); err != nil { - fail(fmt.Errorf("poll push flush failed: %w", err)) - return - } - resetTimer(timer, flushInterval) - } - case <-timer.C: - if err := flush(); err != nil { - fail(fmt.Errorf("poll push flush failed: %w", err)) - return - } - resetTimer(timer, flushInterval) - case <-c.writeClosed: - // Drain any already-accepted writes so CloseWrite does not lose data. - for { - select { - case b := <-c.writeCh: - if len(b) == 0 { - continue - } - if err := enqueue(b); err != nil { - fail(fmt.Errorf("poll push flush failed: %w", err)) - return - } - default: - if err := flush(); err != nil { - fail(fmt.Errorf("poll push flush failed: %w", err)) - return - } - if err := sendSessionControl(c.client, c.finURL, c.headerHost, TunnelModePoll); err != nil { - fail(fmt.Errorf("poll FIN failed: %w", err)) - return - } - return - } - } - case <-c.closed: - writeErr = c.closedErr() - return - } - } -} diff --git a/transport/sudoku/obfs/httpmask/tunnel_conn_queue.go b/transport/sudoku/obfs/httpmask/tunnel_conn_queue.go index 9c2ca3fb8..e5821f11c 100644 --- a/transport/sudoku/obfs/httpmask/tunnel_conn_queue.go +++ b/transport/sudoku/obfs/httpmask/tunnel_conn_queue.go @@ -5,6 +5,8 @@ import ( "net" "sync" "time" + + "github.com/metacubex/mihomo/common/pool" ) // queuedConn provides a net.Conn-like interface backed by internal channels. @@ -27,11 +29,12 @@ type queuedConn struct { readEOFOnce sync.Once readMu sync.Mutex - mu sync.Mutex - readBuf []byte - closeErr error - localAddr net.Addr - remoteAddr net.Addr + mu sync.Mutex + readBuf []byte // unread tail of readPayload + readPayload []byte + closeErr error + localAddr net.Addr + remoteAddr net.Addr } const queuedConnPayloadQueueDepth = 64 @@ -138,16 +141,19 @@ func (c *queuedConn) Read(b []byte) (n int, err error) { if len(c.readBuf) == 0 { select { - case c.readBuf = <-c.rxc: + case p := <-c.rxc: + c.startPayload(p) default: } } if len(c.readBuf) == 0 { select { - case c.readBuf = <-c.rxc: + case p := <-c.rxc: + c.startPayload(p) case <-c.readEOF: select { - case c.readBuf = <-c.rxc: + case p := <-c.rxc: + c.startPayload(p) default: return 0, io.EOF } @@ -157,9 +163,28 @@ func (c *queuedConn) Read(b []byte) (n int, err error) { } n = copy(b, c.readBuf) c.readBuf = c.readBuf[n:] + if len(c.readBuf) == 0 { + recyclePayload(c.readPayload) + c.readPayload = nil + } return n, nil } +// startPayload makes p the payload being read, recycling the previous one. +func (c *queuedConn) startPayload(p []byte) { + recyclePayload(c.readPayload) + c.readPayload = p + c.readBuf = p +} + +// recyclePayload returns a fully read payload to the pool when it is a whole pull chunk; the receiving conn is the +// only reference to it by then. +func recyclePayload(p []byte) { + if cap(p) == streamPullChunkBytes { + _ = pool.Put(p) + } +} + func (c *queuedConn) Write(b []byte) (n int, err error) { if len(b) == 0 { return 0, nil diff --git a/transport/sudoku/obfs/httpmask/tunnel_conn_split.go b/transport/sudoku/obfs/httpmask/tunnel_conn_split.go new file mode 100644 index 000000000..d921f8b0b --- /dev/null +++ b/transport/sudoku/obfs/httpmask/tunnel_conn_split.go @@ -0,0 +1,493 @@ +package httpmask + +import ( + "bufio" + "bytes" + "context" + "encoding/base64" + "errors" + "fmt" + "io" + "math" + "net" + "sync/atomic" + "time" + + "github.com/metacubex/http" + "github.com/metacubex/mihomo/common/pool" +) + +const ( + splitRequestTimeout = 20 * time.Second + splitFlushInterval = 5 * time.Millisecond + splitMinBackoff = 10 * time.Millisecond + splitMaxBackoff = 250 * time.Millisecond + + streamMaxBatchBytes = 256 * 1024 + streamPullChunkBytes = 32 * 1024 + // A chunk at least this full is queued as the pooled buffer it was read into; smaller ones are copied out so a + // full queue of tiny payloads does not pin 32KiB each. + streamPullHandoverMinBytes = streamPullChunkBytes / 2 + streamPullIdleBackoff = 25 * time.Millisecond + + pollMaxBatchBytes = 64 * 1024 + pollMaxLineBytes = 16 * 1024 +) + +var errSplitClosed = errors.New("split tunnel closed") + +// splitCodec holds what differs between stream (raw octet bodies) and poll (base64 text lines). +type splitCodec struct { + mode TunnelMode + uploadContentType string + maxBatchBytes int // raw payload bytes per upload request + maxLineBytes int // raw payload bytes per encoded upload line + pullIdleBackoff time.Duration // pause before pulling again after a response without data + + encodedLen func(rawLen int) int + appendEncoded func(dst, raw []byte) []byte + // readPull hands every decoded downlink payload to deliver until the body ends; a false deliver aborts with errSplitClosed. + readPull func(body io.Reader, deliver func([]byte) bool) (readAny bool, err error) +} + +var splitStreamCodec = splitCodec{ + mode: TunnelModeStream, + uploadContentType: "application/octet-stream", + maxBatchBytes: streamMaxBatchBytes, + maxLineBytes: math.MaxInt, + pullIdleBackoff: streamPullIdleBackoff, + encodedLen: func(rawLen int) int { return rawLen }, + appendEncoded: func(dst, raw []byte) []byte { return append(dst, raw...) }, + readPull: readStreamPull, +} + +var splitPollCodec = splitCodec{ + mode: TunnelModePoll, + uploadContentType: "text/plain", + maxBatchBytes: pollMaxBatchBytes, + maxLineBytes: pollMaxLineBytes, + encodedLen: func(rawLen int) int { return base64.StdEncoding.EncodedLen(rawLen) + 1 }, + appendEncoded: appendBase64Line, + readPull: readPollPull, +} + +func appendBase64Line(dst, raw []byte) []byte { + start := len(dst) + dst = append(dst, make([]byte, base64.StdEncoding.EncodedLen(len(raw)))...) + base64.StdEncoding.Encode(dst[start:], raw) + return append(dst, '\n') +} + +func readStreamPull(body io.Reader, deliver func([]byte) bool) (readAny bool, err error) { + buf := pool.Get(streamPullChunkBytes) + defer func() { _ = pool.Put(buf) }() + for { + n, rerr := body.Read(buf) + if n > 0 { + readAny = true + var payload []byte + if n >= streamPullHandoverMinBytes { + // Mostly full: the reader takes the buffer itself, which saves a copy; queuedConn returns it to the pool. + payload = buf[:n] + buf = pool.Get(streamPullChunkBytes) + } else { + payload = append([]byte(nil), buf[:n]...) + } + if !deliver(payload) { + return readAny, errSplitClosed + } + } + if errors.Is(rerr, io.EOF) { + return readAny, nil + } + if rerr != nil { + return readAny, rerr + } + } +} + +func readPollPull(body io.Reader, deliver func([]byte) bool) (readAny bool, err error) { + scanner := bufio.NewScanner(body) + for scanner.Scan() { + line := scanner.Bytes() + if len(line) == 0 { + continue + } + payload := make([]byte, base64.StdEncoding.DecodedLen(len(line))) + n, derr := base64.StdEncoding.Decode(payload, line) + if derr != nil { + return readAny, fmt.Errorf("decode: %w", derr) + } + readAny = true + if !deliver(payload[:n]) { + return readAny, errSplitClosed + } + } + return readAny, scanner.Err() +} + +// splitConn is the client end of a stream or poll session: uploads leave as POST batches, the downlink +// arrives on a long-running GET, and queuedConn bridges both to a net.Conn. +type splitConn struct { + queuedConn + codec *splitCodec + readiness *tunnelReadiness + + ctx context.Context + cancel context.CancelFunc + + client *http.Client + owner *tunnelHTTPTransport + pushURL string + pullURL string + finURL string + closeURL string + headerHost string + uploadSeq atomic.Uint64 +} + +func dialStream(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) { + // "stream" mode uses split-stream to stay CDN-friendly by default. + return dialSplit(ctx, serverAddress, opts, &splitStreamCodec) +} + +func dialPoll(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) { + return dialSplit(ctx, serverAddress, opts, &splitPollCodec) +} + +func dialSplit(ctx context.Context, serverAddress string, opts TunnelDialOptions, codec *splitCodec) (net.Conn, error) { + info, err := dialSession(ctx, serverAddress, opts, codec.mode) + if err != nil { + return nil, err + } + return newSplitConn(info, opts, codec) +} + +func dialStreamWithClient(ctx context.Context, client *http.Client, dialer *preconnectDialer, target httpClientTarget, opts TunnelDialOptions) (net.Conn, error) { + return dialSplitWithClient(ctx, client, dialer, target, opts, &splitStreamCodec) +} + +func dialPollWithClient(ctx context.Context, client *http.Client, dialer *preconnectDialer, target httpClientTarget, opts TunnelDialOptions) (net.Conn, error) { + return dialSplitWithClient(ctx, client, dialer, target, opts, &splitPollCodec) +} + +func dialSplitWithClient(ctx context.Context, client *http.Client, dialer *preconnectDialer, target httpClientTarget, opts TunnelDialOptions, codec *splitCodec) (net.Conn, error) { + info, err := dialSessionWithClient(ctx, client, dialer, target, codec.mode, opts, sessionPreconnectCount()) + if err != nil { + return nil, err + } + return newSplitConn(info, opts, codec) +} + +func newSplitConn(info *sessionDialInfo, opts TunnelDialOptions, codec *splitCodec) (net.Conn, error) { + connCtx, cancel := context.WithCancel(context.Background()) + c := &splitConn{ + queuedConn: newQueuedConn(), + codec: codec, + readiness: newTunnelReadiness(), + ctx: connCtx, + cancel: cancel, + client: info.client, + owner: info.owner, + pushURL: info.pushURL, + pullURL: info.pullURL, + finURL: info.finURL, + closeURL: info.closeURL, + headerHost: info.headerHost, + } + + go c.pullLoop() + go c.pushLoop() + outConn := net.Conn(c) + if opts.EarlyHandshake != nil && opts.EarlyHandshake.WrapConn != nil && (opts.EarlyHandshake.Ready == nil || opts.EarlyHandshake.Ready()) { + upgraded, err := opts.EarlyHandshake.WrapConn(c) + if err != nil { + _ = c.Close() + return nil, err + } + if upgraded != nil { + outConn = upgraded + } + return wrapReadyTunnelConn(outConn, c.waitReady), nil + } + if opts.Upgrade != nil { + upgraded, err := opts.Upgrade(c) + if err != nil { + _ = c.Close() + return nil, err + } + if upgraded != nil { + outConn = upgraded + } + } + return wrapReadyTunnelConn(outConn, c.waitReady), nil +} + +func (c *splitConn) Close() error { + return c.closeWithError(io.ErrClosedPipe) +} + +func (c *splitConn) closeWithError(err error) error { + _ = c.queuedConn.closeWithError(err) + c.cancel() + bestEffortCloseSession(c.client, c.closeURL, c.headerHost, c.codec.mode) + c.owner.close() + return nil +} + +func (c *splitConn) waitReady(ctx context.Context) error { + return c.readiness.wait(ctx, c.closed, c.closedErr) +} + +func (c *splitConn) deliver(payload []byte) bool { + select { + case c.rxc <- payload: + return true + case <-c.closed: + return false + } +} + +type pullOutcome int + +const ( + pullAgain pullOutcome = iota // the long-poll ended healthily + pullRetry // transient failure: back off, then pull again + pullStop // conn closed or downlink finished +) + +func (c *splitConn) pullLoop() { + backoff := splitMinBackoff + for { + select { + case <-c.closed: + return + default: + } + + outcome, readAny := c.pullOnce() + switch outcome { + case pullStop: + return + case pullRetry: + if err := waitRetry(c.closed, c.closedErr, backoff); err != nil { + return + } + backoff = nextBackoff(backoff, splitMinBackoff, splitMaxBackoff) + case pullAgain: + backoff = splitMinBackoff + if !readAny && c.codec.pullIdleBackoff > 0 { + // Avoid a tight loop when the server answered immediately with an empty body. + select { + case <-time.After(c.codec.pullIdleBackoff): + case <-c.closed: + return + } + } + } + } +} + +// pullOnce runs one downlink GET. Fatal failures close the conn before returning pullStop. +func (c *splitConn) pullOnce() (outcome pullOutcome, readAny bool) { + mode := c.codec.mode + // The server ends an idle pull after PullReadTimeout. A fixed client + // lifetime would instead cancel healthy continuous downloads mid-stream. + reqCtx, cancel := context.WithCancel(c.ctx) + defer cancel() + + req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, c.pullURL, nil) + if err != nil { + _ = c.closeWithError(err) + return pullStop, false + } + req.Host = c.headerHost + applyTunnelHeaders(req.Header, c.headerHost, mode) + + resp, err := c.client.Do(req) + if err != nil { + if isDialError(err) || isRetryableHTTPTransportError(err) { + closeIdleConnections(c.client) + return pullRetry, false + } + _ = c.closeWithError(fmt.Errorf("%s pull request failed: %w", mode, err)) + return pullStop, false + } + + if resp.StatusCode != http.StatusOK { + if isRetryableStatusCode(resp.StatusCode) { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024)) + _ = resp.Body.Close() + closeIdleConnections(c.client) + return pullRetry, false + } + _ = resp.Body.Close() + _ = c.closeWithError(fmt.Errorf("%s pull bad status: %s", mode, resp.Status)) + return pullStop, false + } + c.readiness.markPullReady() + + readAny, err = c.codec.readPull(resp.Body, c.deliver) + _ = resp.Body.Close() + switch { + case errors.Is(err, errSplitClosed): + return pullStop, readAny + case err == nil: + if resp.Trailer.Get(tunnelStreamEOFHeader) == "1" { + c.markReadEOF() + return pullStop, readAny + } + return pullAgain, readAny + case isRetryableHTTPTransportError(err): + closeIdleConnections(c.client) + return pullRetry, readAny + default: + _ = c.closeWithError(fmt.Errorf("%s pull failed: %w", mode, err)) + return pullStop, readAny + } +} + +// postUpload sends one encoded batch; the caller retries it until it succeeds or the conn closes. +func (c *splitConn) postUpload(requestURL string, payload []byte) error { + reqCtx, cancel := context.WithTimeout(c.ctx, splitRequestTimeout) + defer cancel() + req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, requestURL, bytes.NewReader(payload)) + if err != nil { + return err + } + req.Host = c.headerHost + applyTunnelHeaders(req.Header, c.headerHost, c.codec.mode) + req.Header.Set("Content-Type", c.codec.uploadContentType) + + resp, err := c.client.Do(req) + if err != nil { + closeIdleConnections(c.client) + return err + } + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024)) + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK { + err = statusError(resp) + if isRetryableHTTPTransportError(err) { + closeIdleConnections(c.client) + } + return err + } + return nil +} + +func (c *splitConn) pushLoop() { + codec := c.codec + var ( + buf []byte + pendingRaw int + timer = time.NewTimer(splitFlushInterval) + timerArmed bool + writeErr error + ) + // The timer runs only while a batch is buffered, so idle sessions never wake up. + timer.Stop() + defer timer.Stop() + defer func() { c.completeWrite(writeErr) }() + + fail := func(err error) { + writeErr = err + _ = c.closeWithError(err) + } + failFlush := func(err error) { fail(fmt.Errorf("%s push flush failed: %w", codec.mode, err)) } + + flush := func() error { + if len(buf) == 0 { + return nil + } + requestURL := uploadURL(c.pushURL, c.uploadSeq.Add(1)) + attempts := 0 + if err := retryPersistent(c.closed, c.closedErr, splitMinBackoff, splitMaxBackoff, func() error { + attempts++ + return c.postUpload(requestURL, buf) + }); err != nil { + return err + } + if attempts == 1 { + buf = buf[:0] + } else { + // A failed attempt's transport goroutine may still be reading the old batch. + buf = nil + } + pendingRaw = 0 + timer.Stop() + timerArmed = false + c.readiness.markPushReady() + return nil + } + + enqueue := func(b []byte) error { + for len(b) > 0 { + line := b + if len(line) > codec.maxLineBytes { + line = b[:codec.maxLineBytes] + } + b = b[len(line):] + if pendingRaw+len(line) > codec.maxBatchBytes || len(buf)+codec.encodedLen(len(line)) > 2*codec.maxBatchBytes { + if err := flush(); err != nil { + return err + } + } + buf = codec.appendEncoded(buf, line) + pendingRaw += len(line) + } + return nil + } + + for { + select { + case b := <-c.writeCh: + if len(b) == 0 { + continue + } + if err := enqueue(b); err != nil { + failFlush(err) + return + } + if pendingRaw >= codec.maxBatchBytes { + if err := flush(); err != nil { + failFlush(err) + return + } + } else if !timerArmed { + resetTimer(timer, splitFlushInterval) + timerArmed = true + } + case <-timer.C: + timerArmed = false + if err := flush(); err != nil { + failFlush(err) + return + } + case <-c.writeClosed: + // Drain any already-accepted writes so CloseWrite does not lose data. + for drained := false; !drained; { + select { + case b := <-c.writeCh: + if err := enqueue(b); err != nil { + failFlush(err) + return + } + default: + drained = true + } + } + if err := flush(); err != nil { + failFlush(err) + return + } + if err := sendSessionControl(c.client, c.finURL, c.headerHost, codec.mode); err != nil { + fail(fmt.Errorf("%s FIN failed: %w", codec.mode, err)) + } + return + case <-c.closed: + writeErr = c.closedErr() + return + } + } +} diff --git a/transport/sudoku/obfs/httpmask/tunnel_conn_stream.go b/transport/sudoku/obfs/httpmask/tunnel_conn_stream.go deleted file mode 100644 index 0ae4d45ea..000000000 --- a/transport/sudoku/obfs/httpmask/tunnel_conn_stream.go +++ /dev/null @@ -1,375 +0,0 @@ -package httpmask - -import ( - "bytes" - "context" - "errors" - "fmt" - "github.com/metacubex/http" - "io" - "net" - "sync/atomic" - "time" -) - -func dialStream(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) { - // "stream" mode uses split-stream to stay CDN-friendly by default. - return dialStreamSplit(ctx, serverAddress, opts) -} - -type streamSplitConn struct { - queuedConn - readiness *tunnelReadiness - - ctx context.Context - cancel context.CancelFunc - - client *http.Client - owner *tunnelHTTPTransport - pushURL string - pullURL string - finURL string - closeURL string - headerHost string - uploadSeq atomic.Uint64 -} - -func (c *streamSplitConn) Close() error { - return c.closeWithError(io.ErrClosedPipe) -} - -func (c *streamSplitConn) closeWithError(err error) error { - _ = c.queuedConn.closeWithError(err) - - if c.cancel != nil { - c.cancel() - } - - bestEffortCloseSession(c.client, c.closeURL, c.headerHost, TunnelModeStream) - if c.owner != nil { - c.owner.close() - } - return nil -} - -func dialStreamSplit(ctx context.Context, serverAddress string, opts TunnelDialOptions) (net.Conn, error) { - info, err := dialSession(ctx, serverAddress, opts, TunnelModeStream) - if err != nil { - return nil, err - } - return newStreamSplitConn(info, opts) -} - -func dialStreamWithClient(ctx context.Context, client *http.Client, dialer *preconnectDialer, target httpClientTarget, opts TunnelDialOptions) (net.Conn, error) { - info, err := dialSessionWithClient(ctx, client, dialer, target, TunnelModeStream, opts, sessionPreconnectCount()) - if err != nil { - return nil, err - } - return newStreamSplitConn(info, opts) -} - -func newStreamSplitConn(info *sessionDialInfo, opts TunnelDialOptions) (net.Conn, error) { - if info == nil { - return nil, errors.New("httpmask: nil session") - } - - connCtx, cancel := context.WithCancel(context.Background()) - c := &streamSplitConn{ - ctx: connCtx, - cancel: cancel, - readiness: newTunnelReadiness(), - client: info.client, - owner: info.owner, - pushURL: info.pushURL, - pullURL: info.pullURL, - finURL: info.finURL, - closeURL: info.closeURL, - headerHost: info.headerHost, - queuedConn: newQueuedConn(), - } - - go c.pullLoop() - go c.pushLoop() - outConn := net.Conn(c) - if opts.EarlyHandshake != nil && opts.EarlyHandshake.WrapConn != nil && (opts.EarlyHandshake.Ready == nil || opts.EarlyHandshake.Ready()) { - upgraded, err := opts.EarlyHandshake.WrapConn(c) - if err != nil { - _ = c.Close() - return nil, err - } - if upgraded != nil { - outConn = upgraded - } - return wrapReadyTunnelConn(outConn, c.waitReady), nil - } - if opts.Upgrade != nil { - upgraded, err := opts.Upgrade(c) - if err != nil { - _ = c.Close() - return nil, err - } - if upgraded != nil { - outConn = upgraded - } - } - return wrapReadyTunnelConn(outConn, c.waitReady), nil -} - -func (c *streamSplitConn) waitReady(ctx context.Context) error { - if err := c.readiness.wait(ctx, c.closed, c.closedErr); err != nil { - return err - } - return nil -} - -func (c *streamSplitConn) pullLoop() { - const ( - readChunkSize = 32 * 1024 - idleBackoff = 25 * time.Millisecond - minBackoff = 10 * time.Millisecond - maxBackoff = 250 * time.Millisecond - ) - - var ( - backoff = minBackoff - ) - buf := make([]byte, readChunkSize) - for { - select { - case <-c.closed: - return - default: - } - - // The server ends an idle pull after PullReadTimeout. A fixed client - // lifetime would instead cancel healthy continuous downloads mid-stream. - reqCtx, cancel := context.WithCancel(c.ctx) - req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, c.pullURL, nil) - if err != nil { - cancel() - _ = c.Close() - return - } - req.Host = c.headerHost - applyTunnelHeaders(req.Header, c.headerHost, TunnelModeStream) - - resp, err := c.client.Do(req) - if err != nil { - cancel() - if isDialError(err) || isRetryableHTTPTransportError(err) { - closeIdleConnections(c.client) - if err := waitRetry(c.closed, c.closedErr, backoff); err != nil { - return - } - backoff = nextBackoff(backoff, minBackoff, maxBackoff) - continue - } - _ = c.Close() - return - } - backoff = minBackoff - - if resp.StatusCode != http.StatusOK { - if isRetryableStatusCode(resp.StatusCode) { - _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024)) - _ = resp.Body.Close() - cancel() - closeIdleConnections(c.client) - if err := waitRetry(c.closed, c.closedErr, backoff); err != nil { - return - } - backoff = nextBackoff(backoff, minBackoff, maxBackoff) - continue - } - _ = resp.Body.Close() - cancel() - _ = c.Close() - return - } - c.readiness.markPullReady() - - readAny := false - bodyRetry := false - for { - n, rerr := resp.Body.Read(buf) - if n > 0 { - readAny = true - payload := make([]byte, n) - copy(payload, buf[:n]) - select { - case c.rxc <- payload: - case <-c.closed: - _ = resp.Body.Close() - cancel() - return - } - } - if rerr != nil { - _ = resp.Body.Close() - cancel() - if errors.Is(rerr, io.EOF) { - if resp.Trailer.Get(tunnelStreamEOFHeader) == "1" { - c.markReadEOF() - return - } - // Long-poll ended; retry. - break - } - if isRetryableHTTPTransportError(rerr) { - closeIdleConnections(c.client) - bodyRetry = true - break - } - _ = c.Close() - return - } - } - cancel() - if bodyRetry { - if err := waitRetry(c.closed, c.closedErr, backoff); err != nil { - return - } - backoff = nextBackoff(backoff, minBackoff, maxBackoff) - continue - } - backoff = minBackoff - if !readAny { - // Avoid tight loop if the server replied quickly with an empty body. - select { - case <-time.After(idleBackoff): - case <-c.closed: - return - } - } - } -} - -func (c *streamSplitConn) pushLoop() { - const ( - maxBatchBytes = 256 * 1024 - flushInterval = 5 * time.Millisecond - requestTimeout = 20 * time.Second - minBackoff = 10 * time.Millisecond - maxBackoff = 250 * time.Millisecond - ) - - var ( - buf bytes.Buffer - timer = time.NewTimer(flushInterval) - writeErr error - ) - defer timer.Stop() - defer func() { c.completeWrite(writeErr) }() - - fail := func(err error) { - writeErr = err - _ = c.closeWithError(err) - } - - flush := func() error { - if buf.Len() == 0 { - return nil - } - sequence := c.uploadSeq.Add(1) - requestURL, err := uploadURL(c.pushURL, sequence) - if err != nil { - return err - } - payload := append([]byte(nil), buf.Bytes()...) - - if err := retryPersistent(c.closed, c.closedErr, minBackoff, maxBackoff, func() error { - reqCtx, cancel := context.WithTimeout(c.ctx, requestTimeout) - defer cancel() - req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, requestURL, bytes.NewReader(payload)) - if err != nil { - return err - } - req.Host = c.headerHost - applyTunnelHeaders(req.Header, c.headerHost, TunnelModeStream) - req.Header.Set("Content-Type", "application/octet-stream") - resp, err := c.client.Do(req) - if err != nil { - closeIdleConnections(c.client) - return err - } - _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4*1024)) - _ = resp.Body.Close() - if resp.StatusCode != http.StatusOK { - err = statusError(resp) - if isRetryableHTTPTransportError(err) { - closeIdleConnections(c.client) - } - return err - } - return nil - }); err != nil { - return err - } - - buf.Reset() - c.readiness.markPushReady() - return nil - } - - resetTimer(timer, flushInterval) - - for { - select { - case b := <-c.writeCh: - if len(b) == 0 { - continue - } - if buf.Len()+len(b) > maxBatchBytes { - if err := flush(); err != nil { - fail(fmt.Errorf("stream push flush failed: %w", err)) - return - } - resetTimer(timer, flushInterval) - } - _, _ = buf.Write(b) - if buf.Len() >= maxBatchBytes { - if err := flush(); err != nil { - fail(fmt.Errorf("stream push flush failed: %w", err)) - return - } - resetTimer(timer, flushInterval) - } - case <-timer.C: - if err := flush(); err != nil { - fail(fmt.Errorf("stream push flush failed: %w", err)) - return - } - resetTimer(timer, flushInterval) - case <-c.writeClosed: - // Drain any already-accepted writes so CloseWrite does not lose data. - for { - select { - case b := <-c.writeCh: - if len(b) == 0 { - continue - } - if buf.Len()+len(b) > maxBatchBytes { - if err := flush(); err != nil { - fail(fmt.Errorf("stream push flush failed: %w", err)) - return - } - } - _, _ = buf.Write(b) - default: - if err := flush(); err != nil { - fail(fmt.Errorf("stream push flush failed: %w", err)) - return - } - if err := sendSessionControl(c.client, c.finURL, c.headerHost, TunnelModeStream); err != nil { - fail(fmt.Errorf("stream FIN failed: %w", err)) - return - } - return - } - } - case <-c.closed: - writeErr = c.closedErr() - return - } - } -} diff --git a/transport/sudoku/obfs/httpmask/tunnel_dial.go b/transport/sudoku/obfs/httpmask/tunnel_dial.go index 8cae92d57..a12251bbf 100644 --- a/transport/sudoku/obfs/httpmask/tunnel_dial.go +++ b/transport/sudoku/obfs/httpmask/tunnel_dial.go @@ -124,11 +124,8 @@ func setEarlyDataQuery(rawURL string, payload []byte) (string, error) { return u.String(), nil } -func parseEarlyDataQuery(u *url.URL) ([]byte, error) { - if u == nil { - return nil, nil - } - val := strings.TrimSpace(u.Query().Get(tunnelEarlyDataQueryKey)) +func parseEarlyDataQuery(query url.Values) ([]byte, error) { + val := strings.TrimSpace(query.Get(tunnelEarlyDataQueryKey)) if val == "" { return nil, nil } @@ -145,15 +142,10 @@ type sessionDialInfo struct { headerHost string } -func uploadURL(rawURL string, sequence uint64) (string, error) { - u, err := url.Parse(rawURL) - if err != nil { - return "", err - } - q := u.Query() - q.Set(tunnelUploadSequenceQuery, strconv.FormatUint(sequence, 10)) - u.RawQuery = q.Encode() - return u.String(), nil +// uploadURL puts the sequence ahead of pushURL's query, where encoding the sorted keys has always placed it. +func uploadURL(pushURL string, sequence uint64) string { + base, query, _ := strings.Cut(pushURL, "?") + return base + "?" + tunnelUploadSequenceQuery + "=" + strconv.FormatUint(sequence, 10) + "&" + query } type tunnelHTTPTransport struct { diff --git a/transport/sudoku/obfs/httpmask/tunnel_server.go b/transport/sudoku/obfs/httpmask/tunnel_server.go index 6788ba36e..f2a8e06b7 100644 --- a/transport/sudoku/obfs/httpmask/tunnel_server.go +++ b/transport/sudoku/obfs/httpmask/tunnel_server.go @@ -9,6 +9,7 @@ import ( "fmt" "github.com/metacubex/http" "github.com/metacubex/http/httputil" + "github.com/metacubex/mihomo/common/pool" "io" "net" "net/url" @@ -56,22 +57,24 @@ type TunnelServer struct { sessions map[string]*tunnelSession } -const tunnelHeaderReadTimeout = 15 * time.Second +const ( + tunnelHeaderReadTimeout = 15 * time.Second + minReapInterval = 50 * time.Millisecond +) type tunnelSession struct { - conn net.Conn - lastActive time.Time - uplinkClosed bool - downlinkClosed bool - closed chan struct{} - closeOnce sync.Once + conn *halfPipeConn + lastActive time.Time // guarded by TunnelServer.mu + uplinkClosed bool // guarded by TunnelServer.mu + downlinkClosed bool // guarded by TunnelServer.mu + reaper *time.Timer // set under TunnelServer.mu before the session is visible - uploadMu sync.Mutex - nextUploadSeq uint64 + uploadMu sync.Mutex + nextUploadSeq uint64 + // Lock order: pullMu before TunnelServer.mu. pullMu sync.Mutex pull *sessionPullLease - downlinkMu sync.Mutex - pendingDownlink []byte + pendingDownlink []byte // owned by the current pull lease holder } type sessionPullLease struct { @@ -100,7 +103,10 @@ func (p *sessionPullLease) stop() { } } -var errUploadSequenceGap = errors.New("upload sequence gap") +var ( + errUploadSequenceGap = errors.New("upload sequence gap") + errUploadTooLarge = errors.New("upload too large") +) type sessionDirection uint8 @@ -153,9 +159,7 @@ func (s *TunnelServer) HandleConn(rawConn net.Conn) (HandleResult, net.Conn, err if s.passThroughOnReject { return passThroughRejected(prefix) } - _ = writeSimpleHTTPResponse(rawConn, http.StatusNotFound, "not found") - _ = rawConn.Close() - return HandleDone, nil, nil + return replyDone(rawConn, http.StatusNotFound, "not found") } // Preconnected HTTP sockets may wait for the client to assign their first @@ -181,57 +185,48 @@ func (s *TunnelServer) HandleConn(rawConn net.Conn) (HandleResult, net.Conn, err return HandlePassThrough, pc, nil } - req, headerBytes, buffered, err := readHTTPHeader(br) + req, unparsed, err := readHTTPRequest(rawConn, br, first[:]) _ = rawConn.SetReadDeadline(time.Time{}) if err != nil { // Not a valid HTTP request; hand it back to the legacy path with replay. - return passThrough(buildInvalidHTTPReplayPrefix(first[:], headerBytes, buffered)) + return passThrough(unparsed) } - replayPrefix := buildHTTPReplayPrefix(headerBytes, buffered) - - tunnelHeader := TunnelMode(strings.ToLower(strings.TrimSpace(req.headers["x-sudoku-tunnel"]))) - if looksLikeWebSocketUpgrade(req.headers) { + tunnelHeader := TunnelMode(strings.ToLower(strings.TrimSpace(req.tunnel))) + if req.isWebSocketUpgrade() { tunnelHeader = TunnelModeWS } if tunnelHeader == "" { // The explicit mode header is part of the stream/poll protocol. A request // without it belongs to the normal HTTP fallback path. - return passThrough(replayPrefix) + return passThrough(req.replayPrefix()) } if s.mode == TunnelModeLegacy { - return rejectOr404(replayPrefix) + return rejectOr404(req.replayPrefix()) } switch tunnelHeader { case TunnelModeStream: if s.mode != TunnelModeStream && s.mode != TunnelModeAuto { - return rejectOr404(replayPrefix) + return rejectOr404(req.replayPrefix()) } - return s.handleStream(rawConn, req, headerBytes, buffered) + return s.handleSession(req, streamCodec) case TunnelModePoll: if s.mode != TunnelModePoll && s.mode != TunnelModeAuto { - return rejectOr404(replayPrefix) + return rejectOr404(req.replayPrefix()) } - return s.handlePoll(rawConn, req, headerBytes, buffered) + return s.handleSession(req, pollCodec) case TunnelModeWS: if s.mode != TunnelModeWS && s.mode != TunnelModeAuto { - return rejectOr404(replayPrefix) + return rejectOr404(req.replayPrefix()) } - return s.handleWS(rawConn, req, headerBytes, buffered) + return s.handleWS(req) default: - return rejectOr404(replayPrefix) + return rejectOr404(req.replayPrefix()) } } -func buildHTTPReplayPrefix(headerBytes, buffered []byte) []byte { - out := make([]byte, 0, len(headerBytes)+len(buffered)) - out = append(out, headerBytes...) - out = append(out, buffered...) - return out -} - func buildInvalidHTTPReplayPrefix(first, headerBytes, buffered []byte) []byte { // readHTTPHeader may have consumed some bytes that don't include our initial 4-byte peek // (e.g. parse errors / short reads). Preserve a correct replay prefix for downstream handlers. @@ -244,71 +239,165 @@ func buildInvalidHTTPReplayPrefix(first, headerBytes, buffered []byte) []byte { return out } -type httpRequestHeader struct { - method string - target string // path + query - proto string - headers map[string]string // lower-case keys +const maxHTTPHeaderBytes = 32 * 1024 + +// headerBytesSizeHint covers a typical tunnel request header in one allocation. +const headerBytesSizeHint = 512 + +// tunnelRequest is a parsed HTTP request. br still holds the bytes read past the header, so the body is served +// from it directly and a rejected request can be replayed byte for byte. +type tunnelRequest struct { + conn net.Conn + br *bufio.Reader + headerBytes []byte + + method string + target string // path + query + proto string + // Header values are the first occurrence, space-trimmed; only the fields the tunnel routes on are kept. + tunnel string + upgrade string + connection string + authorization string + transferEncoding string + contentLength string + seenFields uint8 } -func readHTTPHeader(r *bufio.Reader) (*httpRequestHeader, []byte, []byte, error) { - const maxHeaderBytes = 32 * 1024 +// field returns the slot for a lower-case header name the tunnel cares about, plus its "seen" bit. +func (r *tunnelRequest) field(name []byte) (*string, uint8) { + switch string(name) { + case "x-sudoku-tunnel": + return &r.tunnel, 1 << 0 + case "upgrade": + return &r.upgrade, 1 << 1 + case "connection": + return &r.connection, 1 << 2 + case "authorization": + return &r.authorization, 1 << 3 + case "transfer-encoding": + return &r.transferEncoding, 1 << 4 + case "content-length": + return &r.contentLength, 1 << 5 + } + return nil, 0 +} - var consumed bytes.Buffer +func (r *tunnelRequest) setField(key, value []byte) { + // Tunnel header names are short ASCII, so lower-casing on the stack avoids an allocation per header line. + var stack [48]byte + lower := append(stack[:0], key...) + for i, c := range lower { + if c >= 0x80 { + lower = []byte(strings.ToLower(string(key))) + break + } + if 'A' <= c && c <= 'Z' { + lower[i] = c + 'a' - 'A' + } + } + slot, bit := r.field(lower) + if slot == nil || r.seenFields&bit != 0 { + return + } + r.seenFields |= bit + *slot = strings.TrimSpace(string(value)) +} + +func (r *tunnelRequest) isWebSocketUpgrade() bool { + if !strings.EqualFold(r.upgrade, "websocket") { + return false + } + for _, part := range strings.Split(r.connection, ",") { + if strings.EqualFold(strings.TrimSpace(part), "upgrade") { + return true + } + } + return false +} + +// buffered returns the bytes already read past the header. They are only valid until the body is read. +func (r *tunnelRequest) buffered() []byte { + b, _ := r.br.Peek(r.br.Buffered()) + return b +} + +// replayPrefix returns the request exactly as received so far. Call it only before the body is consumed. +func (r *tunnelRequest) replayPrefix() []byte { + buffered := r.buffered() + out := make([]byte, 0, len(r.headerBytes)+len(buffered)) + out = append(out, r.headerBytes...) + return append(out, buffered...) +} + +// body returns a reader over the request body, which follows the header in br, and its declared length (-1 when +// unknown). +func (r *tunnelRequest) body() (io.Reader, int64, error) { + if strings.Contains(strings.ToLower(r.transferEncoding), "chunked") { + return httputil.NewChunkedReader(r.br), -1, nil + } + if r.contentLength != "" { + n, err := strconv.ParseInt(r.contentLength, 10, 64) + if err != nil || n < 0 { + return nil, 0, fmt.Errorf("invalid content-length") + } + return io.LimitReader(r.br, n), n, nil + } + return r.br, -1, nil +} + +// readHTTPRequest parses a request header from br (which already holds first, the sniffed leading bytes). On +// failure the second result is everything read so far, ready to be replayed to the next protocol handler. +func readHTTPRequest(conn net.Conn, br *bufio.Reader, first []byte) (*tunnelRequest, []byte, error) { + consumed := make([]byte, 0, headerBytesSizeHint) + fail := func(err error) (*tunnelRequest, []byte, error) { + return nil, buildInvalidHTTPReplayPrefix(first, consumed, readAllBuffered(br)), err + } readLine := func() ([]byte, error) { - line, err := r.ReadSlice('\n') + line, err := br.ReadSlice('\n') if len(line) > 0 { - if consumed.Len()+len(line) > maxHeaderBytes { + if len(consumed)+len(line) > maxHTTPHeaderBytes { return line, fmt.Errorf("http header too large") } - consumed.Write(line) + consumed = append(consumed, line...) } return line, err } - // Request line line, err := readLine() if err != nil { - return nil, consumed.Bytes(), readAllBuffered(r), err + return fail(err) } - lineStr := strings.TrimRight(string(line), "\r\n") - parts := strings.SplitN(lineStr, " ", 3) - if len(parts) != 3 { - return nil, consumed.Bytes(), readAllBuffered(r), fmt.Errorf("invalid request line") + requestLine := strings.TrimRight(string(line), "\r\n") + method, rest, ok := strings.Cut(requestLine, " ") + if !ok { + return fail(fmt.Errorf("invalid request line")) } - req := &httpRequestHeader{ - method: parts[0], - target: parts[1], - proto: parts[2], - headers: make(map[string]string), + target, proto, ok := strings.Cut(rest, " ") + if !ok { + return fail(fmt.Errorf("invalid request line")) } + req := &tunnelRequest{conn: conn, br: br, method: method, target: target, proto: proto} - // Headers for { line, err = readLine() if err != nil { - return nil, consumed.Bytes(), readAllBuffered(r), err + return fail(err) } - trimmed := strings.TrimRight(string(line), "\r\n") - if trimmed == "" { + line = bytes.TrimRight(line, "\r\n") + if len(line) == 0 { break } - k, v, ok := strings.Cut(trimmed, ":") + key, value, ok := bytes.Cut(line, []byte{':'}) if !ok { continue } - k = strings.ToLower(strings.TrimSpace(k)) - v = strings.TrimSpace(v) - if k == "" { - continue - } - // Keep the first value; we only care about a small set. - if _, exists := req.headers[k]; !exists { - req.headers[k] = v + if key = bytes.TrimSpace(key); len(key) > 0 { + req.setField(key, value) } } - - return req, consumed.Bytes(), readAllBuffered(r), nil + req.headerBytes = consumed + return req, nil, nil } func readAllBuffered(r *bufio.Reader) []byte { @@ -459,111 +548,124 @@ func (c *bodyConn) Close() error { return firstErr } -func (s *TunnelServer) rejectOrReply(rawConn net.Conn, headerBytes, buffered []byte, code int, body string) (HandleResult, net.Conn, error) { +// rejectOrRespond answers a rejected request with the given status, or replays it for pass-through fallback. +// It must run before the request body is consumed. +func (s *TunnelServer) rejectOrRespond(req *tunnelRequest, code int, body string) (HandleResult, net.Conn, error) { if s.passThroughOnReject { - prefix := make([]byte, 0, len(headerBytes)+len(buffered)) - prefix = append(prefix, headerBytes...) - prefix = append(prefix, buffered...) - return HandlePassThrough, newRejectedPreBufferedConn(rawConn, prefix), nil + return HandlePassThrough, newRejectedPreBufferedConn(req.conn, req.replayPrefix()), nil } - _ = writeSimpleHTTPResponse(rawConn, code, body) - _ = rawConn.Close() - return HandleDone, nil, nil + return replyDone(req.conn, code, body) } -func (s *TunnelServer) handleStream(rawConn net.Conn, req *httpRequestHeader, headerBytes []byte, buffered []byte) (HandleResult, net.Conn, error) { - u, err := url.ParseRequestURI(req.target) - if err != nil { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") +// handleSession serves one stream or poll request. The two modes share their +// routing and differ only in payload encoding (codec) and in a few rejection +// details that older clients and probes can observe, so those are preserved. +func (s *TunnelServer) handleSession(req *tunnelRequest, codec sessionCodec) (HandleResult, net.Conn, error) { + reject := func(code int, body string) (HandleResult, net.Conn, error) { + return s.rejectOrRespond(req, code, body) } + u, err := url.ParseRequestURI(req.target) + if err != nil { + return reject(http.StatusBadRequest, "bad request") + } // Only accept plausible paths to reduce accidental exposure. path, ok := stripPathRoot(s.pathRoot, u.Path) if !ok || !s.isAllowedBasePath(path) { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusNotFound, "not found") + return reject(http.StatusNotFound, "not found") } - token := u.Query().Get("token") - closeFlag := u.Query().Get("close") == "1" - finFlag := u.Query().Get("fin") == "1" + query := u.Query() + token := query.Get("token") switch strings.ToUpper(req.method) { case http.MethodGet: - // Stream Split Session: GET /session (no token) => token + start tunnel on a server-side pipe. if token == "" && path == "/session" { - earlyPayload, err := parseEarlyDataQuery(u) + earlyPayload, err := parseEarlyDataQuery(query) if err != nil { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") + return reject(http.StatusBadRequest, "bad request") } - return s.sessionAuthorize(rawConn, headerBytes, buffered, earlyPayload) + return s.sessionAuthorize(req, earlyPayload) } - // Stream Split Session: GET /stream?token=... => downlink poll. - if token != "" && path == "/stream" { - if s.passThroughOnReject && !s.sessionHas(token) { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusNotFound, "not found") - } - return s.streamPull(rawConn, token) + // A tokenless pull is a bare 400 in stream mode but reaches the session + // lookup (403) in poll mode. + if path != "/stream" || (token == "" && !codec.poll) { + return reject(http.StatusBadRequest, "bad request") } - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") + if s.passThroughOnReject && !s.sessionHas(token) { + return reject(http.StatusNotFound, "not found") + } + return s.pull(req.conn, token, codec) case http.MethodPost: - // Stream Split Session: POST /api/v1/upload?token=... => uplink push. - if token != "" && path == "/api/v1/upload" { - if closeFlag { - s.sessionClose(token) - _ = writeSimpleHTTPResponse(rawConn, http.StatusOK, "") - _ = rawConn.Close() - return HandleDone, nil, nil - } - if finFlag { - s.sessionCloseWrite(token) - _ = writeSimpleHTTPResponse(rawConn, http.StatusOK, "") - _ = rawConn.Close() - return HandleDone, nil, nil - } - if s.passThroughOnReject && !s.sessionHas(token) { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusNotFound, "not found") - } - bodyReader, err := newRequestBodyReader(newPreBufferedConn(rawConn, buffered), req.headers) - if err != nil { - _ = writeSimpleHTTPResponse(rawConn, http.StatusBadRequest, "bad request") - _ = rawConn.Close() - return HandleDone, nil, nil - } - sequence, err := parseUploadSequence(u) - if err != nil { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") - } - return s.streamPush(rawConn, token, sequence, bodyReader) + if path == "/api/v1/upload" && token != "" { + return s.handleUpload(req, query, codec) } - - // Stream-One: single full-duplex POST. - if err := writeTunnelResponseHeader(rawConn); err != nil { - _ = rawConn.Close() - return HandleDone, nil, err + if codec.poll { + if path != "/api/v1/upload" { + return reject(http.StatusBadRequest, "bad request") + } + return reject(http.StatusBadRequest, "missing token") } - - bodyReader, err := newRequestBodyReader(newPreBufferedConn(rawConn, buffered), req.headers) - if err != nil { - _ = rawConn.Close() - return HandleDone, nil, err - } - - bw := bufio.NewWriterSize(rawConn, 32*1024) - chunked := httputil.NewChunkedWriter(bw) - stream := &bodyConn{ - Conn: rawConn, - reader: bodyReader, - writer: chunked, - tail: bw, - flush: bw.Flush, - } - return HandleStartTunnel, stream, nil + return s.startStreamOne(req) default: - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") + return reject(http.StatusBadRequest, "bad request") } } +// handleUpload serves POST /api/v1/upload?token=...: close, FIN or a payload push. +func (s *TunnelServer) handleUpload(req *tunnelRequest, query url.Values, codec sessionCodec) (HandleResult, net.Conn, error) { + rawConn := req.conn + token := query.Get("token") + + if query.Get("close") == "1" { + s.sessionClose(token) + return replyDone(rawConn, http.StatusOK, "") + } + if query.Get("fin") == "1" { + s.sessionCloseWrite(token) + return replyDone(rawConn, http.StatusOK, "") + } + if s.passThroughOnReject && !s.sessionHas(token) { + return s.rejectOrRespond(req, http.StatusNotFound, "not found") + } + body, length, err := req.body() + if err != nil { + if codec.poll { + return s.rejectOrRespond(req, http.StatusBadRequest, "bad request") + } + return replyDone(rawConn, http.StatusBadRequest, "bad request") + } + sequence, err := parseUploadSequence(query) + if err != nil { + return s.rejectOrRespond(req, http.StatusBadRequest, "bad request") + } + return s.push(rawConn, token, sequence, body, length, codec) +} + +// startStreamOne turns a tokenless POST into a single full-duplex tunnel. +func (s *TunnelServer) startStreamOne(req *tunnelRequest) (HandleResult, net.Conn, error) { + rawConn := req.conn + if err := writeTunnelResponseHeader(rawConn); err != nil { + _ = rawConn.Close() + return HandleDone, nil, err + } + bodyReader, _, err := req.body() + if err != nil { + _ = rawConn.Close() + return HandleDone, nil, err + } + + bw := bufio.NewWriterSize(rawConn, 32*1024) + return HandleStartTunnel, &bodyConn{ + Conn: rawConn, + reader: bodyReader, + writer: httputil.NewChunkedWriter(bw), + tail: bw, + flush: bw.Flush, + }, nil +} + func (s *TunnelServer) isAllowedBasePath(path string) bool { for _, p := range paths { if path == p { @@ -573,23 +675,6 @@ func (s *TunnelServer) isAllowedBasePath(path string) bool { return false } -func newRequestBodyReader(conn net.Conn, headers map[string]string) (io.Reader, error) { - br := bufio.NewReaderSize(conn, 32*1024) - - te := strings.ToLower(headers["transfer-encoding"]) - if strings.Contains(te, "chunked") { - return httputil.NewChunkedReader(br), nil - } - if clStr := headers["content-length"]; clStr != "" { - n, err := strconv.ParseInt(strings.TrimSpace(clStr), 10, 64) - if err != nil || n < 0 { - return nil, fmt.Errorf("invalid content-length") - } - return io.LimitReader(br, n), nil - } - return br, nil -} - func writeTunnelResponseHeader(w io.Writer) error { _, err := io.WriteString(w, "HTTP/1.1 200 OK\r\n"+ @@ -617,6 +702,13 @@ func writeSessionPullResponseHeader(w io.Writer) error { return err } +// replyDone answers a one-shot request and ends handling of the connection. +func replyDone(rawConn net.Conn, code int, body string) (HandleResult, net.Conn, error) { + _ = writeSimpleHTTPResponse(rawConn, code, body) + _ = rawConn.Close() + return HandleDone, nil, nil +} + func writeSimpleHTTPResponse(w io.Writer, code int, body string) error { if body == "" { body = http.StatusText(code) @@ -642,77 +734,11 @@ func writeTokenHTTPResponse(w io.Writer, token string, earlyPayload []byte) erro return err } -func (s *TunnelServer) handlePoll(rawConn net.Conn, req *httpRequestHeader, headerBytes []byte, buffered []byte) (HandleResult, net.Conn, error) { - u, err := url.ParseRequestURI(req.target) - if err != nil { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") - } - - path, ok := stripPathRoot(s.pathRoot, u.Path) - if !ok || !s.isAllowedBasePath(path) { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusNotFound, "not found") - } - token := u.Query().Get("token") - closeFlag := u.Query().Get("close") == "1" - finFlag := u.Query().Get("fin") == "1" - switch strings.ToUpper(req.method) { - case http.MethodGet: - if token == "" && path == "/session" { - earlyPayload, err := parseEarlyDataQuery(u) - if err != nil { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") - } - return s.sessionAuthorize(rawConn, headerBytes, buffered, earlyPayload) - } - if path == "/stream" { - if s.passThroughOnReject && !s.sessionHas(token) { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusNotFound, "not found") - } - return s.pollPull(rawConn, token) - } - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") - case http.MethodPost: - if path != "/api/v1/upload" { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") - } - if token == "" { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "missing token") - } - if closeFlag { - s.sessionClose(token) - _ = writeSimpleHTTPResponse(rawConn, http.StatusOK, "") - _ = rawConn.Close() - return HandleDone, nil, nil - } - if finFlag { - s.sessionCloseWrite(token) - _ = writeSimpleHTTPResponse(rawConn, http.StatusOK, "") - _ = rawConn.Close() - return HandleDone, nil, nil - } - if s.passThroughOnReject && !s.sessionHas(token) { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusNotFound, "not found") - } - bodyReader, err := newRequestBodyReader(newPreBufferedConn(rawConn, buffered), req.headers) - if err != nil { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") - } - sequence, err := parseUploadSequence(u) - if err != nil { - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") - } - return s.pollPush(rawConn, token, sequence, bodyReader) - default: - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusBadRequest, "bad request") - } -} - -func (s *TunnelServer) sessionAuthorize(rawConn net.Conn, headerBytes, buffered, earlyPayload []byte) (HandleResult, net.Conn, error) { +func (s *TunnelServer) sessionAuthorize(req *tunnelRequest, earlyPayload []byte) (HandleResult, net.Conn, error) { + rawConn := req.conn token, err := newSessionToken() if err != nil { - _ = writeSimpleHTTPResponse(rawConn, http.StatusInternalServerError, "internal error") - _ = rawConn.Close() - return HandleDone, nil, nil + return replyDone(rawConn, http.StatusInternalServerError, "internal error") } c1, c2 := newHalfPipe() @@ -724,7 +750,7 @@ func (s *TunnelServer) sessionAuthorize(rawConn net.Conn, headerBytes, buffered, if err != nil { _ = c1.Close() _ = c2.Close() - return s.rejectOrReply(rawConn, headerBytes, buffered, http.StatusNotFound, "not found") + return s.rejectOrRespond(req, http.StatusNotFound, "not found") } responsePayload = prepared.ResponsePayload userHash = prepared.UserHash @@ -733,9 +759,7 @@ func (s *TunnelServer) sessionAuthorize(rawConn net.Conn, headerBytes, buffered, if err != nil { _ = c1.Close() _ = c2.Close() - _ = writeSimpleHTTPResponse(rawConn, http.StatusInternalServerError, "internal error") - _ = rawConn.Close() - return HandleDone, nil, nil + return replyDone(rawConn, http.StatusInternalServerError, "internal error") } if wrapped != nil { outConn = wrapEarlyHandshakeConn(wrapped, userHash) @@ -743,11 +767,7 @@ func (s *TunnelServer) sessionAuthorize(rawConn net.Conn, headerBytes, buffered, } } - s.mu.Lock() - s.sessions[token] = &tunnelSession{conn: c2, closed: make(chan struct{}), lastActive: time.Now(), nextUploadSeq: 1} - s.mu.Unlock() - - go s.reapLater(token) + s.sessionAdd(token, c2) if err := writeTokenHTTPResponse(rawConn, token, responsePayload); err != nil { s.sessionClose(token) @@ -766,73 +786,79 @@ func newSessionToken() (string, error) { return base64.RawURLEncoding.EncodeToString(b[:]), nil } -func (s *TunnelServer) reapLater(token string) { - ttl := s.sessionTTL - if ttl <= 0 { +// sessionAdd registers a session for conn and arms its idle reaper. +func (s *TunnelServer) sessionAdd(token string, conn *halfPipeConn) *tunnelSession { + sess := &tunnelSession{conn: conn, lastActive: time.Now(), nextUploadSeq: 1} + s.mu.Lock() + s.sessions[token] = sess + sess.reaper = time.AfterFunc(s.sessionTTL, func() { s.reap(token, sess) }) + s.mu.Unlock() + return sess +} + +// shutdown disarms the reaper, stops the active pull and closes the tunnel pipe. +func (sess *tunnelSession) shutdown() { + sess.reaper.Stop() + sess.pullMu.Lock() + lease := sess.pull + sess.pullMu.Unlock() + lease.stop() + _ = sess.conn.Close() +} + +// reap runs when the reaper fires and re-arms it unless sess is gone. +func (s *TunnelServer) reap(token string, sess *tunnelSession) { + next, done := s.reapIfIdle(token, sess) + if done { return } - - timer := time.NewTimer(ttl) - defer timer.Stop() - - for { - s.mu.Lock() - sess, ok := s.sessions[token] - s.mu.Unlock() - if !ok { - return + s.mu.Lock() + defer s.mu.Unlock() + if s.sessions[token] == sess { + // Best-effort cleanup does not need a tight loop under constant activity. + if next < minReapInterval { + next = minReapInterval } - - select { - case <-timer.C: - case <-sess.closed: - return - } - - s.mu.Lock() - sess, ok = s.sessions[token] - if !ok { - s.mu.Unlock() - return - } - idle := time.Since(sess.lastActive) - s.mu.Unlock() - - // Pull ownership has its own lock. Do not take it while holding s.mu: - // pull takeover validates the session while holding pullMu. - sess.pullMu.Lock() - active := sess.pull != nil - sess.pullMu.Unlock() - - s.mu.Lock() - if s.sessions[token] != sess { - s.mu.Unlock() - return - } - if idle >= ttl && !active { - delete(s.sessions, token) - s.mu.Unlock() - sess.pullMu.Lock() - lease := sess.pull - sess.pullMu.Unlock() - lease.stop() - _ = sess.conn.Close() - return - } - next := ttl - idle - if active && next < ttl { - next = ttl - } - s.mu.Unlock() - - // Avoid a tight loop under high-frequency activity; we only need best-effort cleanup. - if next < 50*time.Millisecond { - next = 50 * time.Millisecond - } - timer.Reset(next) + sess.reaper.Reset(next) } } +// reapIfIdle closes sess once it has been idle for the TTL with no active pull, +// otherwise it returns how long to wait before checking again. +func (s *TunnelServer) reapIfIdle(token string, sess *tunnelSession) (next time.Duration, done bool) { + s.mu.Lock() + if s.sessions[token] != sess { + s.mu.Unlock() + return 0, true + } + idle := time.Since(sess.lastActive) + s.mu.Unlock() + + // Pull ownership has its own lock. Do not take it while holding s.mu: + // pull takeover validates the session while holding pullMu. + sess.pullMu.Lock() + pulling := sess.pull != nil + sess.pullMu.Unlock() + + s.mu.Lock() + if s.sessions[token] != sess { + s.mu.Unlock() + return 0, true + } + if idle >= s.sessionTTL && !pulling { + delete(s.sessions, token) + s.mu.Unlock() + sess.shutdown() + return 0, true + } + next = s.sessionTTL - idle + if pulling && next < s.sessionTTL { + next = s.sessionTTL + } + s.mu.Unlock() + return next, false +} + func (s *TunnelServer) sessionHas(token string) bool { s.mu.Lock() _, ok := s.sessions[token] @@ -870,14 +896,7 @@ func (s *TunnelServer) sessionClose(token string) { } s.mu.Unlock() if ok { - if sess.closed != nil { - sess.closeOnce.Do(func() { close(sess.closed) }) - } - sess.pullMu.Lock() - lease := sess.pull - sess.pullMu.Unlock() - lease.stop() - _ = sess.conn.Close() + sess.shutdown() } } @@ -886,10 +905,7 @@ func (s *TunnelServer) sessionCloseWrite(token string) { } func (s *TunnelServer) sessionHalfClose(token string, direction sessionDirection) { - var ( - conn net.Conn - closeWrite bool - ) + var closeWrite, removed bool s.mu.Lock() sess, ok := s.sessions[token] @@ -909,32 +925,24 @@ func (s *TunnelServer) sessionHalfClose(token string, direction sessionDirection } if sess.uplinkClosed && sess.downlinkClosed { delete(s.sessions, token) - if sess.closed != nil { - sess.closeOnce.Do(func() { close(sess.closed) }) - } + removed = true } - conn = sess.conn s.mu.Unlock() if closeWrite { - _ = tryCloseWrite(conn) + _ = tryCloseWrite(sess.conn) } // When both directions are complete the session has been removed. Closing // the backing connection is safe after the optional half-close above and // prevents a leaked pipe from surviving its token. - s.mu.Lock() - _, stillPresent := s.sessions[token] - s.mu.Unlock() - if !stillPresent { - _ = conn.Close() + if removed { + sess.reaper.Stop() + _ = sess.conn.Close() } } -func parseUploadSequence(u *url.URL) (uint64, error) { - if u == nil { - return 0, errors.New("missing upload sequence") - } - raw := strings.TrimSpace(u.Query().Get(tunnelUploadSequenceQuery)) +func parseUploadSequence(query url.Values) (uint64, error) { + raw := strings.TrimSpace(query.Get(tunnelUploadSequenceQuery)) if raw == "" { return 0, errors.New("missing upload sequence") } @@ -973,81 +981,108 @@ func (s *TunnelServer) writeSessionUpload(token string, sess *tunnelSession, seq return nil } +const ( + maxUploadBytes = 1 << 20 // per request + // presizedUploadBytes bounds how much of a declared Content-Length is allocated before any byte arrives; it + // matches the largest batch a stream client sends. + presizedUploadBytes = 256 << 10 +) + +// readUpload reads up to limit bytes of r into a pooled buffer. length is the declared body size, or -1 when +// unknown. The caller returns the buffer with pool.Put once the bytes are consumed, also when err is not nil. +func readUpload(r io.Reader, length int64, limit int) ([]byte, error) { + size := 4096 + if length >= 0 { + // One spare byte lets the final Read report EOF without growing the buffer. + size = presizedUploadBytes + if length < int64(size) { + size = int(length) + } + size++ + } + buf := pool.Get(size)[:0] + for len(buf) < limit { + if len(buf) == cap(buf) { + grown := pool.Get(2 * cap(buf)) + grown = grown[:copy(grown, buf)] + _ = pool.Put(buf) + buf = grown + } + end := cap(buf) + if end > limit { + end = limit + } + n, err := r.Read(buf[len(buf):end]) + buf = buf[:len(buf)+n] + if err != nil { + if err == io.EOF { + err = nil + } + return buf, err + } + } + return buf, nil +} + +// decodeUploadLines base64-decodes every non-blank line of encoded and concatenates the results in a pooled +// buffer that the caller returns with pool.Put. +func decodeUploadLines(encoded []byte) ([]byte, error) { + out := pool.Get(base64.StdEncoding.DecodedLen(len(encoded)))[:0] + for len(encoded) > 0 { + var line []byte + line, encoded, _ = bytes.Cut(encoded, []byte{'\n'}) + if line = bytes.TrimSpace(line); len(line) == 0 { + continue + } + n, err := base64.StdEncoding.Decode(out[len(out):cap(out)], line) + if err != nil { + return out, err + } + out = out[:len(out)+n] + } + return out, nil +} + func writeUploadResult(rawConn net.Conn, err error) (HandleResult, net.Conn, error) { if errors.Is(err, errUploadSequenceGap) { - _ = writeSimpleHTTPResponse(rawConn, http.StatusConflict, "sequence gap") - } else { - _ = writeSimpleHTTPResponse(rawConn, http.StatusGone, "gone") + return replyDone(rawConn, http.StatusConflict, "sequence gap") } - _ = rawConn.Close() - return HandleDone, nil, nil + return replyDone(rawConn, http.StatusGone, "gone") } -func (s *TunnelServer) pollPush(rawConn net.Conn, token string, sequence uint64, body io.Reader) (HandleResult, net.Conn, error) { - sess, ok := s.sessionGet(token) - if !ok { - _ = writeSimpleHTTPResponse(rawConn, http.StatusForbidden, "forbidden") - _ = rawConn.Close() - return HandleDone, nil, nil +// readUpload reads one upload body of the given declared length (-1 when unknown) and returns the tunnel bytes it +// carries in a pooled buffer. The caller returns the buffer with pool.Put also when err is not nil. +func (c sessionCodec) readUpload(body io.Reader, length int64) ([]byte, error) { + if !c.poll { + payload, err := readUpload(body, length, maxUploadBytes+1) + if err == nil && len(payload) > maxUploadBytes { + err = errUploadTooLarge + } + return payload, err } - payload, err := io.ReadAll(io.LimitReader(body, 1<<20)) // 1MiB per request cap + encoded, err := readUpload(body, length, maxUploadBytes) + defer func() { _ = pool.Put(encoded) }() if err != nil { - _ = writeSimpleHTTPResponse(rawConn, http.StatusBadRequest, "bad request") - _ = rawConn.Close() - return HandleDone, nil, nil + return nil, err } - - var decodedPayload bytes.Buffer - for _, line := range bytes.Split(payload, []byte{'\n'}) { - line = bytes.TrimSpace(line) - if len(line) == 0 { - continue - } - decoded := make([]byte, base64.StdEncoding.DecodedLen(len(line))) - n, decErr := base64.StdEncoding.Decode(decoded, line) - if decErr != nil { - _ = writeSimpleHTTPResponse(rawConn, http.StatusBadRequest, "bad request") - _ = rawConn.Close() - return HandleDone, nil, nil - } - if n == 0 { - continue - } - _, _ = decodedPayload.Write(decoded[:n]) - } - - if err := s.writeSessionUpload(token, sess, sequence, decodedPayload.Bytes()); err != nil { - if !errors.Is(err, errUploadSequenceGap) { - s.sessionClose(token) - } - return writeUploadResult(rawConn, err) - } - - _ = writeSimpleHTTPResponse(rawConn, http.StatusOK, "") - _ = rawConn.Close() - return HandleDone, nil, nil + return decodeUploadLines(encoded) } -func (s *TunnelServer) streamPush(rawConn net.Conn, token string, sequence uint64, body io.Reader) (HandleResult, net.Conn, error) { +// push applies one upload request to the session and answers it. +func (s *TunnelServer) push(rawConn net.Conn, token string, sequence uint64, body io.Reader, length int64, codec sessionCodec) (HandleResult, net.Conn, error) { sess, ok := s.sessionGet(token) if !ok { - _ = writeSimpleHTTPResponse(rawConn, http.StatusForbidden, "forbidden") - _ = rawConn.Close() - return HandleDone, nil, nil + return replyDone(rawConn, http.StatusForbidden, "forbidden") } - const maxUploadBytes = 1 << 20 - payload, err := io.ReadAll(io.LimitReader(body, maxUploadBytes+1)) - if err != nil { - _ = writeSimpleHTTPResponse(rawConn, http.StatusBadRequest, "bad request") - _ = rawConn.Close() - return HandleDone, nil, nil + payload, err := codec.readUpload(body, length) + defer func() { _ = pool.Put(payload) }() + if errors.Is(err, errUploadTooLarge) { + return replyDone(rawConn, http.StatusRequestEntityTooLarge, "too large") } - if len(payload) > maxUploadBytes { - _ = writeSimpleHTTPResponse(rawConn, http.StatusRequestEntityTooLarge, "too large") - _ = rawConn.Close() - return HandleDone, nil, nil + if err != nil { + return replyDone(rawConn, http.StatusBadRequest, "bad request") } if err := s.writeSessionUpload(token, sess, sequence, payload); err != nil { @@ -1056,40 +1091,16 @@ func (s *TunnelServer) streamPush(rawConn net.Conn, token string, sequence uint6 } return writeUploadResult(rawConn, err) } - - _ = writeSimpleHTTPResponse(rawConn, http.StatusOK, "") - _ = rawConn.Close() - return HandleDone, nil, nil -} - -func (s *TunnelServer) streamPull(rawConn net.Conn, token string) (HandleResult, net.Conn, error) { - return s.sessionPull(rawConn, token, false, func(w io.Writer, p []byte) error { - return writeFull(w, p) - }) -} - -func (s *TunnelServer) pollPull(rawConn net.Conn, token string) (HandleResult, net.Conn, error) { - enc := make([]byte, base64.StdEncoding.EncodedLen(32*1024)) - return s.sessionPull(rawConn, token, true, func(w io.Writer, p []byte) error { - if cap(enc) < base64.StdEncoding.EncodedLen(len(p)) { - enc = make([]byte, base64.StdEncoding.EncodedLen(len(p))) - } - line := enc[:base64.StdEncoding.EncodedLen(len(p))] - base64.StdEncoding.Encode(line, p) - if err := writeFull(w, line); err != nil { - return err - } - return writeFull(w, []byte{'\n'}) - }) + return replyDone(rawConn, http.StatusOK, "") } func (s *TunnelServer) beginSessionPull(token string, sess *tunnelSession, rawConn net.Conn) (*sessionPullLease, bool) { for { + sess.pullMu.Lock() if !s.sessionTouch(token, sess) { + sess.pullMu.Unlock() return nil, false } - - sess.pullMu.Lock() previous := sess.pull if previous == nil { lease := newSessionPullLease(rawConn) @@ -1119,48 +1130,17 @@ func (s *TunnelServer) endSessionPull(token string, sess *tunnelSession, lease * close(lease.done) } -func (s *TunnelServer) pendingDownlink(sess *tunnelSession) []byte { - sess.downlinkMu.Lock() - pending := sess.pendingDownlink - sess.downlinkMu.Unlock() - return pending -} - -func (s *TunnelServer) storeDownlink(sess *tunnelSession, payload []byte) { - sess.downlinkMu.Lock() - if len(sess.pendingDownlink) == 0 { - sess.pendingDownlink = append(sess.pendingDownlink[:0], payload...) - } - sess.downlinkMu.Unlock() -} - -func (s *TunnelServer) acknowledgeDownlink(sess *tunnelSession, n int) { - if n <= 0 { - return - } - sess.downlinkMu.Lock() - if n >= len(sess.pendingDownlink) { - sess.pendingDownlink = nil - } else { - copy(sess.pendingDownlink, sess.pendingDownlink[n:]) - sess.pendingDownlink = sess.pendingDownlink[:len(sess.pendingDownlink)-n] - } - sess.downlinkMu.Unlock() -} - -func (s *TunnelServer) sessionPull(rawConn net.Conn, token string, keepalive bool, writePayload func(io.Writer, []byte) error) (HandleResult, net.Conn, error) { +// pull answers GET /stream with a chunked downlink until the session has +// nothing more to say, the response breaks or another pull takes over. +func (s *TunnelServer) pull(rawConn net.Conn, token string, codec sessionCodec) (HandleResult, net.Conn, error) { sess, ok := s.sessionGet(token) if !ok { - _ = writeSimpleHTTPResponse(rawConn, http.StatusForbidden, "forbidden") - _ = rawConn.Close() - return HandleDone, nil, nil + return replyDone(rawConn, http.StatusForbidden, "forbidden") } lease, ok := s.beginSessionPull(token, sess, rawConn) if !ok { - _ = writeSimpleHTTPResponse(rawConn, http.StatusForbidden, "forbidden") - _ = rawConn.Close() - return HandleDone, nil, nil + return replyDone(rawConn, http.StatusForbidden, "forbidden") } defer s.endSessionPull(token, sess, lease) @@ -1169,20 +1149,15 @@ func (s *TunnelServer) sessionPull(rawConn net.Conn, token string, keepalive boo return HandleDone, nil, err } - bw := bufio.NewWriterSize(rawConn, 32*1024) - cw := httputil.NewChunkedWriter(bw) - streamEOF := false + // nil once a frame failed to go out whole: the body is already broken, so no terminator. + end := pullEnd defer func() { - _ = cw.Close() - if streamEOF { - _, _ = fmt.Fprintf(bw, "%s: 1\r\n", tunnelStreamEOFHeader) + if end != nil { + _, _ = rawConn.Write(end) } - _, _ = bw.WriteString("\r\n") - _ = bw.Flush() _ = rawConn.Close() }() - buf := make([]byte, 32*1024) for { select { case <-lease.cancel: @@ -1190,58 +1165,118 @@ func (s *TunnelServer) sessionPull(rawConn net.Conn, token string, keepalive boo default: } - payload := s.pendingDownlink(sess) - var n int - var err error + // An idle pull waits for the tunnel without holding a buffer; one is taken only once bytes arrive. + payload := sess.pendingDownlink + var read []byte + var readErr error if len(payload) == 0 { _ = sess.conn.SetReadDeadline(time.Now().Add(s.pullReadTimeout)) - n, err = sess.conn.Read(buf) - if n > 0 { - s.storeDownlink(sess, buf[:n]) - payload = s.pendingDownlink(sess) + if readErr = sess.conn.awaitReadable(); readErr == nil { + read = pool.Get(downlinkReadBytes) + var n int + n, readErr = sess.conn.Read(read) + payload = read[:n] } } if len(payload) > 0 { if !s.sessionTouch(token, sess) { + _ = pool.Put(read) return HandleDone, nil, nil } + frame := codec.appendPullFrame(pool.Get(codec.pullFrameSize(len(payload)))[:0], payload) _ = rawConn.SetWriteDeadline(time.Now().Add(s.pullReadTimeout)) - if writeErr := writePayload(cw, payload); writeErr != nil { + err := writeFull(rawConn, frame) + _ = pool.Put(frame) + if err != nil { // The HTTP response may be reset by a CDN while the backing // tunnel is still healthy. The client will establish a fresh // pull request, so never destroy the session for this request's - // downstream socket failure. - return HandleDone, nil, nil - } - if flushErr := bw.Flush(); flushErr != nil { + // downstream socket failure; its next pull resends the payload. + sess.pendingDownlink = append(sess.pendingDownlink[:0], payload...) + _ = pool.Put(read) + end = nil return HandleDone, nil, nil } _ = rawConn.SetWriteDeadline(time.Time{}) - s.acknowledgeDownlink(sess, len(payload)) + sess.pendingDownlink = nil } - if err == nil { + _ = pool.Put(read) + if readErr == nil { continue } - if errors.Is(err, os.ErrDeadlineExceeded) { + switch { + case errors.Is(readErr, os.ErrDeadlineExceeded): select { case <-lease.cancel: - return HandleDone, nil, nil default: + if codec.poll { + end = pollKeepaliveEnd + s.sessionTouch(token, sess) + } } - if keepalive { - _, _ = cw.Write([]byte("\n")) - _ = bw.Flush() - s.sessionTouch(token, sess) - } - return HandleDone, nil, nil - } - if errors.Is(err, io.EOF) { - streamEOF = true + case errors.Is(readErr, io.EOF): + end = pullEndAfterEOF s.sessionHalfClose(token, sessionDownlink) - return HandleDone, nil, nil + default: + s.sessionClose(token) } - s.sessionClose(token) return HandleDone, nil, nil } } + +// sessionCodec is how a mode carries tunnel bytes: raw octets for stream, one +// base64 line per payload for poll. +type sessionCodec struct { + poll bool +} + +var ( + streamCodec = sessionCodec{} + pollCodec = sessionCodec{poll: true} +) + +const ( + downlinkReadBytes = 32 * 1024 + + // pollNewlineChunk is the one-byte chunk that ends every poll line and doubles as the idle keepalive. + pollNewlineChunk = "1\r\n\n\r\n" +) + +// Bodies end with the zero chunk; EOF is reported as a trailer, which is why the response header announces one. +var ( + pullEnd = []byte("0\r\n\r\n") + pullEndAfterEOF = []byte("0\r\n" + tunnelStreamEOFHeader + ": 1\r\n\r\n") + pollKeepaliveEnd = []byte(pollNewlineChunk + "0\r\n\r\n") +) + +// pullFrameSize bounds the chunked-body bytes that carry an n-byte downlink payload. +func (c sessionCodec) pullFrameSize(n int) int { + if c.poll { + return 8 + base64.StdEncoding.EncodedLen(n) + len(pollNewlineChunk) + } + return 8 + n +} + +// appendPullFrame appends the chunked-body bytes that carry one downlink payload: a single chunk of raw octets for +// stream, a base64 line chunk followed by a newline chunk for poll. +func (c sessionCodec) appendPullFrame(dst, payload []byte) []byte { + if !c.poll { + return appendChunk(dst, payload) + } + encLen := base64.StdEncoding.EncodedLen(len(payload)) + dst = strconv.AppendInt(dst, int64(encLen), 16) + dst = append(dst, '\r', '\n') + start := len(dst) + dst = dst[:start+encLen] + base64.StdEncoding.Encode(dst[start:], payload) + dst = append(dst, '\r', '\n') + return append(dst, pollNewlineChunk...) +} + +func appendChunk(dst, data []byte) []byte { + dst = strconv.AppendInt(dst, int64(len(data)), 16) + dst = append(dst, '\r', '\n') + dst = append(dst, data...) + return append(dst, '\r', '\n') +} diff --git a/transport/sudoku/obfs/httpmask/tunnel_test.go b/transport/sudoku/obfs/httpmask/tunnel_test.go index 31a371179..d4d8a6061 100644 --- a/transport/sudoku/obfs/httpmask/tunnel_test.go +++ b/transport/sudoku/obfs/httpmask/tunnel_test.go @@ -10,12 +10,15 @@ import ( "io" "net" "net/http" + "net/url" "strings" "sync/atomic" "testing" "time" mhttp "github.com/metacubex/http" + "github.com/metacubex/http/httputil" + "github.com/metacubex/mihomo/common/pool" ) type roundTripFunc func(*mhttp.Request) (*mhttp.Response, error) @@ -138,6 +141,44 @@ func TestQueuedConnReadEOFDrainsBufferedPayload(t *testing.T) { } } +func TestUploadURLMatchesQueryEncoding(t *testing.T) { + for _, token := range []string{"T-k_9", "a+b/c=", "sp ace&x=y", "é"} { + pushURL := "https://h.test/root/api/v1/upload?token=" + url.QueryEscape(token) + u, err := url.Parse(pushURL) + if err != nil { + t.Fatal(err) + } + q := u.Query() + q.Set(tunnelUploadSequenceQuery, "7") + u.RawQuery = q.Encode() + if got := uploadURL(pushURL, 7); got != u.String() { + t.Fatalf("token %q: uploadURL = %q, want %q", token, got, u.String()) + } + } +} + +func TestQueuedConnRecyclesDrainedPooledPayload(t *testing.T) { + conn := &queuedConn{ + rxc: make(chan []byte, 1), + closed: make(chan struct{}), + } + conn.rxc <- pool.Get(streamPullChunkBytes)[:100] + + var buf [60]byte + if _, err := conn.Read(buf[:]); err != nil { + t.Fatal(err) + } + if conn.readPayload == nil { + t.Fatal("payload released with 40 bytes still unread") + } + if n, err := conn.Read(buf[:]); n != 40 || err != nil { + t.Fatalf("second read = (%d, %v), want 40 bytes", n, err) + } + if conn.readPayload != nil { + t.Fatal("drained payload still held by the conn") + } +} + func TestSendSessionControlRetriesTransportEOF(t *testing.T) { var calls atomic.Int32 client := &mhttp.Client{Transport: roundTripFunc(func(req *mhttp.Request) (*mhttp.Response, error) { @@ -229,8 +270,7 @@ func TestTunnelServerPullTakeoverSerializesReaders(t *testing.T) { defer sessionConn.Close() server := NewTunnelServer(TunnelServerOptions{}) - sess := &tunnelSession{conn: sessionConn, closed: make(chan struct{})} - server.sessions[token] = sess + sess := server.sessionAdd(token, sessionConn) firstClient, firstServer := net.Pipe() defer firstClient.Close() @@ -269,6 +309,116 @@ func TestTunnelServerPullTakeoverSerializesReaders(t *testing.T) { } } +func TestPullFrameMatchesChunkedWriter(t *testing.T) { + payload := bytes.Repeat([]byte("sudoku"), 1000) + for _, n := range []int{1, 2, 3, 255, 4096, len(payload)} { + p := payload[:n] + + var want bytes.Buffer + cw := httputil.NewChunkedWriter(&want) + _, _ = cw.Write(p) + if got := streamCodec.appendPullFrame(nil, p); !bytes.Equal(got, want.Bytes()) { + t.Fatalf("stream frame for %d bytes = %q, want %q", n, got, want.Bytes()) + } + + want.Reset() + _, _ = cw.Write([]byte(base64.StdEncoding.EncodeToString(p))) + _, _ = cw.Write([]byte("\n")) + got := pollCodec.appendPullFrame(make([]byte, 0, pollCodec.pullFrameSize(n)), p) + if !bytes.Equal(got, want.Bytes()) { + t.Fatalf("poll frame for %d bytes = %q, want %q", n, got, want.Bytes()) + } + if len(got) > pollCodec.pullFrameSize(n) { + t.Fatalf("poll frame for %d bytes is %d, over its size bound %d", n, len(got), pollCodec.pullFrameSize(n)) + } + } +} + +func TestReadUploadGrowsPastPresize(t *testing.T) { + want := bytes.Repeat([]byte("0123456789abcdef"), 20000) // 320 KB: more than the pooled classes and the presize + for _, length := range []int64{-1, 0, 100, int64(len(want))} { + got, err := readUpload(bytes.NewReader(want), length, maxUploadBytes+1) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("declared length %d: read %d bytes, err %v, want %d bytes", length, len(got), err, len(want)) + } + _ = pool.Put(got) + } + got, err := readUpload(bytes.NewReader(want), -1, 1000) + if err != nil || len(got) != 1000 { + t.Fatalf("limit: read %d bytes, err %v, want 1000", len(got), err) + } + _ = pool.Put(got) +} + +func TestDecodeUploadLines(t *testing.T) { + enc := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) } + got, err := decodeUploadLines([]byte(enc("hello") + "\n\n \r\n" + enc("w") + "\r\n" + enc("orld"))) + if err != nil || string(got) != "helloworld" { + t.Fatalf("decode = %q, %v", got, err) + } + _ = pool.Put(got) + if _, err := decodeUploadLines([]byte(enc("ok") + "\n!!!!\n")); err == nil { + t.Fatal("invalid base64 line was accepted") + } +} + +func TestReadHTTPRequestKeepsReplayAndBody(t *testing.T) { + raw := "POST /api/v1/upload?token=t HTTP/1.1\r\nHost: x\r\nX-SUDOKU-Tunnel: poll \r\n" + + "Content-Length: 5\r\ncontent-length: 9\r\nConnection: keep-alive, Upgrade\r\nUpgrade: WebSocket\r\n\r\nhello" + client, server := net.Pipe() + defer client.Close() + defer server.Close() + go func() { _, _ = client.Write([]byte(raw)) }() + + br := bufio.NewReader(server) + req, _, err := readHTTPRequest(server, br, []byte(raw[:4])) + if err != nil { + t.Fatalf("readHTTPRequest: %v", err) + } + if req.method != "POST" || req.target != "/api/v1/upload?token=t" || req.tunnel != "poll" || req.contentLength != "5" { + t.Fatalf("parsed request = %+v", req) + } + if !req.isWebSocketUpgrade() { + t.Fatal("upgrade headers were not recognised") + } + if got := req.replayPrefix(); !bytes.HasPrefix([]byte(raw), got) || !bytes.HasPrefix(got, []byte(raw[:len(raw)-5])) { + t.Fatalf("replay prefix = %q", got) + } + body, length, err := req.body() + if err != nil || length != 5 { + t.Fatalf("body: length %d, err %v", length, err) + } + if got, err := io.ReadAll(body); err != nil || string(got) != "hello" { + t.Fatalf("body = %q, %v", got, err) + } +} + +func TestTunnelServerReapsIdleSession(t *testing.T) { + const token = "idle-session" + + appConn, sessionConn := newHalfPipe() + defer appConn.Close() + defer sessionConn.Close() + + server := NewTunnelServer(TunnelServerOptions{SessionTTL: 20 * time.Millisecond}) + server.sessionAdd(token, sessionConn) + + // The tunnel read ends once the reaper closes the session pipe. + readDone := make(chan error, 1) + go func() { + _, err := appConn.Read(make([]byte, 1)) + readDone <- err + }() + select { + case <-readDone: + case <-time.After(5 * time.Second): + t.Fatal("idle session was not reaped") + } + if server.sessionHas(token) { + t.Fatal("reaped session is still registered") + } +} + func startTestTunnelServer(t testing.TB, server *TunnelServer) (string, func(), <-chan net.Conn) { t.Helper() @@ -308,20 +458,17 @@ func startTestTunnelServer(t testing.TB, server *TunnelServer) (string, func(), func TestTunnelServerDownlinkHalfCloseKeepsUplink(t *testing.T) { tests := []struct { name string - pull func(*TunnelServer, net.Conn, string) (HandleResult, net.Conn, error) - push func(*TunnelServer, net.Conn, string, uint64, io.Reader) (HandleResult, net.Conn, error) + codec sessionCodec pushBody string }{ { name: "stream", - pull: (*TunnelServer).streamPull, - push: (*TunnelServer).streamPush, + codec: streamCodec, pushBody: "tail", }, { name: "poll", - pull: (*TunnelServer).pollPull, - push: (*TunnelServer).pollPush, + codec: pollCodec, pushBody: base64.StdEncoding.EncodeToString([]byte("tail")) + "\n", }, } @@ -332,7 +479,7 @@ func TestTunnelServerDownlinkHalfCloseKeepsUplink(t *testing.T) { appConn, sessionConn := newHalfPipe() server := NewTunnelServer(TunnelServerOptions{PullReadTimeout: 20 * time.Millisecond}) - server.sessions[token] = &tunnelSession{conn: sessionConn, nextUploadSeq: 1} + server.sessionAdd(token, sessionConn) t.Cleanup(func() { _ = appConn.Close() server.sessionClose(token) @@ -344,7 +491,7 @@ func TestTunnelServerDownlinkHalfCloseKeepsUplink(t *testing.T) { appDone <- err return } - if err := appConn.(interface{ CloseWrite() error }).CloseWrite(); err != nil { + if err := appConn.CloseWrite(); err != nil { appDone <- err return } @@ -358,7 +505,7 @@ func TestTunnelServerDownlinkHalfCloseKeepsUplink(t *testing.T) { clientConn, serverConn := net.Pipe() done := make(chan error, 1) go func() { - _, _, err := tt.pull(server, serverConn, token) + _, _, err := server.pull(serverConn, token, tt.codec) done <- err }() @@ -385,7 +532,7 @@ func TestTunnelServerDownlinkHalfCloseKeepsUplink(t *testing.T) { clientConn, serverConn = net.Pipe() done = make(chan error, 1) go func() { - _, _, err := tt.push(server, serverConn, token, 1, strings.NewReader(tt.pushBody)) + _, _, err := server.push(serverConn, token, 1, strings.NewReader(tt.pushBody), -1, tt.codec) done <- err }() resp, err = http.ReadResponse(bufio.NewReader(clientConn), &http.Request{Method: http.MethodPost}) diff --git a/transport/sudoku/obfs/httpmask/tunnel_ws_server.go b/transport/sudoku/obfs/httpmask/tunnel_ws_server.go index b17b1ded3..916a0d1f8 100644 --- a/transport/sudoku/obfs/httpmask/tunnel_ws_server.go +++ b/transport/sudoku/obfs/httpmask/tunnel_ws_server.go @@ -11,33 +11,10 @@ import ( "github.com/gobwas/ws" ) -func looksLikeWebSocketUpgrade(headers map[string]string) bool { - if headers == nil { - return false - } - if !strings.EqualFold(strings.TrimSpace(headers["upgrade"]), "websocket") { - return false - } - conn := headers["connection"] - for _, part := range strings.Split(conn, ",") { - if strings.EqualFold(strings.TrimSpace(part), "upgrade") { - return true - } - } - return false -} - -func (s *TunnelServer) handleWS(rawConn net.Conn, req *httpRequestHeader, headerBytes []byte, buffered []byte) (HandleResult, net.Conn, error) { +func (s *TunnelServer) handleWS(req *tunnelRequest) (HandleResult, net.Conn, error) { + rawConn := req.conn rejectOrReply := func(code int, body string) (HandleResult, net.Conn, error) { - if s.passThroughOnReject { - prefix := make([]byte, 0, len(headerBytes)+len(buffered)) - prefix = append(prefix, headerBytes...) - prefix = append(prefix, buffered...) - return HandlePassThrough, newRejectedPreBufferedConn(rawConn, prefix), nil - } - _ = writeSimpleHTTPResponse(rawConn, code, body) - _ = rawConn.Close() - return HandleDone, nil, nil + return s.rejectOrRespond(req, code, body) } u, err := url.ParseRequestURI(req.target) @@ -52,11 +29,11 @@ func (s *TunnelServer) handleWS(rawConn net.Conn, req *httpRequestHeader, header if strings.ToUpper(strings.TrimSpace(req.method)) != http.MethodGet { return rejectOrReply(http.StatusBadRequest, "bad request") } - if !looksLikeWebSocketUpgrade(req.headers) { + if !req.isWebSocketUpgrade() { return rejectOrReply(http.StatusBadRequest, "bad request") } - authVal := req.headers["authorization"] + authVal := req.authorization if authVal == "" { authVal = u.Query().Get(tunnelAuthQueryKey) } @@ -64,7 +41,7 @@ func (s *TunnelServer) handleWS(rawConn net.Conn, req *httpRequestHeader, header return rejectOrReply(http.StatusNotFound, "not found") } - earlyPayload, err := parseEarlyDataQuery(u) + earlyPayload, err := parseEarlyDataQuery(u.Query()) if err != nil { return rejectOrReply(http.StatusBadRequest, "bad request") } @@ -76,10 +53,7 @@ func (s *TunnelServer) handleWS(rawConn net.Conn, req *httpRequestHeader, header } } - prefix := make([]byte, 0, len(headerBytes)+len(buffered)) - prefix = append(prefix, headerBytes...) - prefix = append(prefix, buffered...) - wsConnRaw := newPreBufferedConn(rawConn, prefix) + wsConnRaw := newPreBufferedConn(rawConn, req.replayPrefix()) upgrader := ws.Upgrader{} if prepared != nil && len(prepared.ResponsePayload) > 0 { diff --git a/transport/sudoku/obfs/sudoku/conn.go b/transport/sudoku/obfs/sudoku/conn.go index 08197b832..3fa73e5a3 100644 --- a/transport/sudoku/obfs/sudoku/conn.go +++ b/transport/sudoku/obfs/sudoku/conn.go @@ -1,7 +1,6 @@ package sudoku import ( - "bufio" "bytes" "io" "net" @@ -9,51 +8,21 @@ import ( "sync/atomic" ) -const IOBufferSize = 32 * 1024 - -const minDecodeReadSize = 64 - -var perm4 = [24][4]byte{ - {0, 1, 2, 3}, - {0, 1, 3, 2}, - {0, 2, 1, 3}, - {0, 2, 3, 1}, - {0, 3, 1, 2}, - {0, 3, 2, 1}, - {1, 0, 2, 3}, - {1, 0, 3, 2}, - {1, 2, 0, 3}, - {1, 2, 3, 0}, - {1, 3, 0, 2}, - {1, 3, 2, 0}, - {2, 0, 1, 3}, - {2, 0, 3, 1}, - {2, 1, 0, 3}, - {2, 1, 3, 0}, - {2, 3, 0, 1}, - {2, 3, 1, 0}, - {3, 0, 1, 2}, - {3, 0, 2, 1}, - {3, 1, 0, 2}, - {3, 1, 2, 0}, - {3, 2, 0, 1}, - {3, 2, 1, 0}, -} +// decodeWindow bounds how many wire bytes decode compacts at a time. +const decodeWindow = 256 type Conn struct { net.Conn table *Table - reader *bufio.Reader + reader *wireReader recorder *bytes.Buffer recording atomic.Bool recordLock sync.Mutex - rawBuf []byte - pendingData pendingBuffer - hintBuf [4]byte - hintCount int - writeMu sync.Mutex - writeBuf []byte + hintBuf [3]uint8 // hint indexes of a group still being read + hintCount int + writeMu sync.Mutex + writeBuf []byte rng *sudokuRand paddingThreshold uint64 @@ -85,10 +54,6 @@ func NewConn(c net.Conn, table *Table, pMin, pMax int, record bool) *Conn { sc := &Conn{ Conn: c, table: table, - reader: bufio.NewReaderSize(c, IOBufferSize), - rawBuf: make([]byte, IOBufferSize), - pendingData: newPendingBuffer(4096), - writeBuf: make([]byte, 0, 4096), rng: localRng, paddingThreshold: pickPaddingThreshold(localRng, pMin, pMax), } @@ -109,6 +74,8 @@ func (sc *Conn) StopRecording() { sc.recordLock.Unlock() } +// GetBufferedAndRecorded returns every wire byte read so far that has not been +// stopped from recording, plus bytes buffered but not yet decoded. func (sc *Conn) GetBufferedAndRecorded() []byte { if sc == nil { return nil @@ -121,19 +88,14 @@ func (sc *Conn) GetBufferedAndRecorded() []byte { if sc.recorder != nil { recorded = sc.recorder.Bytes() } - if sc.reader == nil { + pending := sc.reader.pending() + if len(pending) == 0 { return recorded } - - buffered := sc.reader.Buffered() - if buffered > 0 { - peeked, _ := sc.reader.Peek(buffered) - full := make([]byte, len(recorded)+len(peeked)) - copy(full, recorded) - copy(full[len(recorded):], peeked) - return full - } - return recorded + full := make([]byte, len(recorded)+len(pending)) + copy(full, recorded) + copy(full[len(recorded):], pending) + return full } func (sc *Conn) Write(p []byte) (n int, err error) { @@ -147,83 +109,38 @@ func (sc *Conn) Write(p []byte) (n int, err error) { sc.writeMu.Lock() defer sc.writeMu.Unlock() - sc.writeBuf = encodeSudokuPayload(sc.writeBuf[:0], sc.table, sc.rng, sc.paddingThreshold, p) - if _, err := sc.Conn.Write(sc.writeBuf); err != nil { - return len(p), err - } - return len(p), nil + sc.writeBuf, n, err = writeSudokuPayload(sc.Conn, sc.writeBuf, sc.table, sc.rng, sc.paddingThreshold, p) + return n, err } func (sc *Conn) Read(p []byte) (n int, err error) { if len(p) == 0 { return 0, nil } - if sc == nil || sc.Conn == nil || sc.reader == nil || len(sc.rawBuf) == 0 || sc.table == nil || sc.table.layout == nil { + if sc == nil || sc.Conn == nil || sc.table == nil || sc.table.layout == nil { return 0, io.ErrClosedPipe } - if n, ok := drainPending(p, &sc.pendingData); ok { - return n, nil + if sc.reader == nil { + // Write-only codecs never pay for a read buffer. + sc.reader = &wireReader{src: sc.Conn} } outN := 0 for { - nr, rErr := readRawLimited(sc.Conn, sc.reader, sc.rawBuf[:sudokuReadSize(len(p)-outN, len(sc.rawBuf))]) - if nr > 0 { - chunk := sc.rawBuf[:nr] + chunk, rErr := sc.reader.peek() + if len(chunk) > 0 { + var consumed int + outN, consumed, rErr = sc.decode(p, chunk) if sc.recording.Load() { sc.recordLock.Lock() if sc.recording.Load() && sc.recorder != nil { - sc.recorder.Write(chunk) + sc.recorder.Write(chunk[:consumed]) } sc.recordLock.Unlock() } - - table := sc.table - layout := table.layout - for i := 0; i < len(chunk); { - if sc.hintCount == 0 && outN < len(p) && i+3 < len(chunk) && - layout.hintTable[chunk[i]] && - layout.hintTable[chunk[i+1]] && - layout.hintTable[chunk[i+2]] && - layout.hintTable[chunk[i+3]] { - val, ok := table.DecodeMap[packHintBytes(chunk[i], chunk[i+1], chunk[i+2], chunk[i+3])] - if !ok { - return 0, ErrInvalidSudokuMapMiss - } - p[outN] = val - outN++ - i += 4 - continue - } - - b := chunk[i] - i++ - if !layout.hintTable[b] { - continue - } - - sc.hintBuf[sc.hintCount] = b - sc.hintCount++ - if sc.hintCount != len(sc.hintBuf) { - continue - } - - val, ok := table.DecodeMap[packHintBytes(sc.hintBuf[0], sc.hintBuf[1], sc.hintBuf[2], sc.hintBuf[3])] - if !ok { - return 0, ErrInvalidSudokuMapMiss - } - outN = appendDecodedByte(p, outN, &sc.pendingData, val) - sc.hintCount = 0 - } + sc.reader.discard(consumed) } - if rErr != nil { - if outN > 0 { - return outN, nil - } - if n, ok := drainPending(p, &sc.pendingData); ok { - return n, nil - } return 0, rErr } if outN > 0 { @@ -232,26 +149,39 @@ func (sc *Conn) Read(p []byte) (n int, err error) { } } -func sudokuReadSize(decodedRemaining, maxRaw int) int { - if maxRaw <= minDecodeReadSize || decodedRemaining <= 0 { - return maxRaw - } - if decodedRemaining > (maxRaw-minDecodeReadSize)/9 { - return maxRaw - } +// decode writes only as much plaintext as fits in p, so the wire bytes it +// consumed can be dropped and the rest stay in the reader. It consumes whole +// windows of wire bytes, keeping the hints of an unfinished group in hintBuf, +// but never more than can complete into the space left in p. Compacting a +// window through hintIdx with a branchless store skips padding without a +// per-byte branch. +func (sc *Conn) decode(p, chunk []byte) (outN, consumed int, err error) { + table := sc.table + hintIdx := &table.layout.hintIdx + var hints [512]uint8 - return decodedRemaining*9 + minDecodeReadSize -} + for consumed < len(chunk) && outN < len(p) { + window := minInt(minInt(len(chunk)-consumed, decodeWindow), 4*(len(p)-outN)+3-sc.hintCount) + k := copy(hints[:], sc.hintBuf[:sc.hintCount]) + for _, b := range chunk[consumed : consumed+window] { + idx := hintIdx[b] + hints[k&511] = idx + k += int(idx>>7) ^ 1 + } + consumed += window -func readRawLimited(conn net.Conn, reader *bufio.Reader, dst []byte) (int, error) { - if len(dst) == 0 { - return 0, nil + groups := k / 4 + for i := 0; i < groups; i++ { + h := (*[4]uint8)(hints[4*i:]) + val, ok := table.decodeHints(h[0], h[1], h[2], h[3]) + if !ok { + sc.hintCount = 0 + return outN, consumed, ErrInvalidSudokuMapMiss + } + p[outN] = val + outN++ + } + sc.hintCount = copy(sc.hintBuf[:], hints[4*groups:k]) } - if reader != nil && reader.Buffered() > 0 { - return reader.Read(dst) - } - if conn == nil { - return 0, io.ErrClosedPipe - } - return conn.Read(dst) + return outN, consumed, nil } diff --git a/transport/sudoku/obfs/sudoku/downlink.go b/transport/sudoku/obfs/sudoku/downlink.go index e76e3ec8b..7a6170b5b 100644 --- a/transport/sudoku/obfs/sudoku/downlink.go +++ b/transport/sudoku/obfs/sudoku/downlink.go @@ -6,50 +6,25 @@ import ( "sync" ) -// DownlinkWriter encodes payload bytes with the selected downlink codec. -type DownlinkWriter struct { - dataWriter io.Writer - writeMu sync.Mutex -} - -func NewDownlinkWriter(raw io.Writer, table *Table, pMin, pMax int) *DownlinkWriter { - localRng := newSeededRand() - return newDownlinkWriter(newSudokuDataWriter(raw, table, localRng, pMin, pMax)) -} - -func NewPackedDownlinkWriter(raw net.Conn, table *Table, pMin, pMax int) (*PackedConn, *DownlinkWriter) { - packed := NewPackedConn(raw, table, pMin, pMax) - return packed, newDownlinkWriter(packed) -} - +// NewServerDownlinkWriter returns the server-to-client writer for a connection +// whose uplink is already wrapped. The packed codec buffers residual bits, so +// its Flush is returned as a closer to run before the connection is closed. func NewServerDownlinkWriter(raw net.Conn, table *Table, pMin, pMax int, pure bool) (io.Writer, []func() error) { if pure { - return NewDownlinkWriter(raw, table, pMin, pMax), nil + return newPureWriter(raw, table, newSeededRand(), pMin, pMax), nil } - packed, writer := NewPackedDownlinkWriter(raw, table, pMin, pMax) - return writer, []func() error{packed.Flush} + packed := NewPackedConn(raw, table, pMin, pMax) + return writerOnly{packed}, []func() error{packed.Flush} } -func newDownlinkWriter(dataWriter io.Writer) *DownlinkWriter { - return &DownlinkWriter{dataWriter: dataWriter} -} +// writerOnly hides every method but Write, so wrapping it in a directional +// conn does not half-close the shared socket twice. +type writerOnly struct{ io.Writer } -func (w *DownlinkWriter) Write(p []byte) (int, error) { - if len(p) == 0 { - return 0, nil - } - if w == nil || w.dataWriter == nil { - return 0, io.ErrClosedPipe - } - - w.writeMu.Lock() - defer w.writeMu.Unlock() - - return w.dataWriter.Write(p) -} - -type sudokuDataWriter struct { +// pureWriter is the write half of Conn, safe for concurrent callers. +type pureWriter struct { + mu sync.Mutex writer io.Writer table *Table rng *sudokuRand @@ -57,30 +32,28 @@ type sudokuDataWriter struct { writeBuf []byte } -func newSudokuDataWriter(writer io.Writer, table *Table, rng *sudokuRand, pMin, pMax int) *sudokuDataWriter { - return &sudokuDataWriter{ +func newPureWriter(writer io.Writer, table *Table, rng *sudokuRand, pMin, pMax int) *pureWriter { + return &pureWriter{ writer: writer, table: table, rng: rng, paddingThreshold: pickPaddingThreshold(rng, pMin, pMax), - writeBuf: make([]byte, 0, 4096), } } -func (w *sudokuDataWriter) Write(p []byte) (int, error) { +func (w *pureWriter) Write(p []byte) (int, error) { if len(p) == 0 { return 0, nil } - if w == nil || w.writer == nil { - return 0, io.ErrClosedPipe - } - if w.table == nil || w.table.layout == nil || w.rng == nil { + if w == nil || w.writer == nil || w.table == nil || w.table.layout == nil || w.rng == nil { return 0, io.ErrClosedPipe } - w.writeBuf = encodeSudokuPayload(w.writeBuf[:0], w.table, w.rng, w.paddingThreshold, p) - if _, err := w.writer.Write(w.writeBuf); err != nil { - return len(p), err - } - return len(p), nil + w.mu.Lock() + defer w.mu.Unlock() + + var n int + var err error + w.writeBuf, n, err = writeSudokuPayload(w.writer, w.writeBuf, w.table, w.rng, w.paddingThreshold, p) + return n, err } diff --git a/transport/sudoku/obfs/sudoku/encode.go b/transport/sudoku/obfs/sudoku/encode.go index f93c8d99b..df8bc0c77 100644 --- a/transport/sudoku/obfs/sudoku/encode.go +++ b/transport/sudoku/obfs/sudoku/encode.go @@ -1,72 +1,118 @@ package sudoku -func encodeSudokuPayload(dst []byte, table *Table, rng *sudokuRand, paddingThreshold uint64, p []byte) []byte { +import ( + "encoding/binary" + "math" +) + +const ( + // maxPaddedExpansion is the worst case per plaintext byte: five padding + // slots and four hints. + maxPaddedExpansion = 9 + // encodeSlack is the headroom the encoder needs past the last byte it keeps, + // so each plaintext byte can be stored as one fixed-size array write. + encodeSlack = 16 +) + +// permShifts[i][j] is the bit offset, inside a packed puzzle, of the hint that +// the i-th hint order places in slot j. The orders are the 24 permutations of +// 0..3 in lexicographic order. +var permShifts = buildPermShifts() + +func buildPermShifts() (shifts [24][4]uint8) { + n := 0 + for a := uint8(0); a < 4; a++ { + for b := uint8(0); b < 4; b++ { + for c := uint8(0); c < 4; c++ { + for d := uint8(0); d < 4; d++ { + if a == b || a == c || a == d || b == c || b == d || c == d { + continue + } + shifts[n] = [4]uint8{8 * a, 8 * b, 8 * c, 8 * d} + n++ + } + } + } + } + return shifts +} + +// permute reorders the four hint bytes of a packed puzzle. +func permute(puzzle uint32, s *[4]uint8) uint32 { + return puzzle>>(s[0]&31)&0xff | + puzzle>>(s[1]&31)&0xff<<8 | + puzzle>>(s[2]&31)&0xff<<16 | + puzzle>>(s[3]&31)<<24 +} + +// pickPuzzle draws one puzzle of plaintext byte b and one hint order from a +// single 64-bit random value. +func (t *Table) pickPuzzle(b byte, draw uint64) uint32 { + puzzles := t.EncodeTable[b] + puzzle := puzzles[(draw>>32)*uint64(len(puzzles))>>32] + return permute(binary.LittleEndian.Uint32(puzzle[:]), &permShifts[(draw&math.MaxUint32)*uint64(len(permShifts))>>32]) +} + +// padSlot writes a candidate padding byte at w[k] and keeps it only when the +// slot's draw falls under threshold. A slot that draws no padding leaves k +// alone, so the next write overwrites the candidate. +func padSlot(state, threshold uint64, pool []byte, w *[16]byte, k int) (uint64, int) { + state, draw := wyNext(state) + w[k&15] = pool[(draw>>32)*uint64(len(pool))>>32] + return state, k + int((draw&math.MaxUint32-threshold)>>63) +} + +// appendSudokuPayload encodes p after dst. Each plaintext byte becomes one +// puzzle's four hints in a random order, with a padding byte possible before +// each hint and one more before the group. threshold is the per-slot padding +// probability scaled to 1<<32, so a value of 1<<32 pads every slot. +func appendSudokuPayload(dst []byte, table *Table, rng *sudokuRand, threshold uint64, p []byte) []byte { if len(p) == 0 { - return dst[:0] + return dst } - if paddingThreshold == 0 { - return encodeSudokuPayloadNoPadding(dst, table, rng, p) + n := len(dst) + expansion := maxPaddedExpansion + if threshold == 0 { + expansion = 4 } + out := dst + if need := n + len(p)*expansion + encodeSlack; cap(out) < need { + out = make([]byte, n, need) + copy(out, dst) + } + out = out[:cap(out)] + state := rng.state - outCapacity := len(p)*6 + 1 - if cap(dst) < outCapacity { - dst = make([]byte, 0, outCapacity) - } - out := dst[:0] - pads := table.PaddingPool - padLen := len(pads) - - if paddingThreshold >= probOne { + if threshold == 0 { for _, b := range p { - out = append(out, pads[rng.Intn(padLen)]) - - puzzles := table.EncodeTable[b] - puzzle := puzzles[rng.Intn(len(puzzles))] - - perm := perm4[rng.Intn(len(perm4))] - for _, idx := range perm { - out = append(out, pads[rng.Intn(padLen)], puzzle[idx]) - } + var draw uint64 + state, draw = wyNext(state) + binary.LittleEndian.PutUint32(out[n:], table.pickPuzzle(b, draw)) + n += 4 } - - out = append(out, pads[rng.Intn(padLen)]) - return out + rng.state = state + return out[:n] } + pool := table.PaddingPool for _, b := range p { - if uint64(rng.Uint32()) < paddingThreshold { - out = append(out, pads[rng.Intn(padLen)]) - } + var draw uint64 + state, draw = wyNext(state) + hints := table.pickPuzzle(b, draw) - puzzles := table.EncodeTable[b] - puzzle := puzzles[rng.Intn(len(puzzles))] - perm := perm4[rng.Intn(len(perm4))] - for _, idx := range perm { - if uint64(rng.Uint32()) < paddingThreshold { - out = append(out, pads[rng.Intn(padLen)]) - } - out = append(out, puzzle[idx]) - } + w := (*[16]byte)(out[n:]) + var k int + state, k = padSlot(state, threshold, pool, w, 0) + state, k = padSlot(state, threshold, pool, w, k) + w[k&15] = byte(hints) + state, k = padSlot(state, threshold, pool, w, k+1) + w[k&15] = byte(hints >> 8) + state, k = padSlot(state, threshold, pool, w, k+1) + w[k&15] = byte(hints >> 16) + state, k = padSlot(state, threshold, pool, w, k+1) + w[k&15] = byte(hints >> 24) + n += k + 1 } - - if uint64(rng.Uint32()) < paddingThreshold { - out = append(out, pads[rng.Intn(padLen)]) - } - return out -} - -func encodeSudokuPayloadNoPadding(dst []byte, table *Table, rng *sudokuRand, p []byte) []byte { - outCapacity := len(p) * 4 - if cap(dst) < outCapacity { - dst = make([]byte, 0, outCapacity) - } - out := dst[:0] - - for _, b := range p { - puzzles := table.EncodeTable[b] - puzzle := puzzles[rng.Intn(len(puzzles))] - perm := perm4[rng.Intn(len(perm4))] - out = append(out, puzzle[perm[0]], puzzle[perm[1]], puzzle[perm[2]], puzzle[perm[3]]) - } - return out + rng.state = state + return out[:n] } diff --git a/transport/sudoku/obfs/sudoku/layout.go b/transport/sudoku/obfs/sudoku/layout.go index 2e1ec236a..80c162179 100644 --- a/transport/sudoku/obfs/sudoku/layout.go +++ b/transport/sudoku/obfs/sudoku/layout.go @@ -14,32 +14,43 @@ type byteLayout struct { padMarker byte paddingPool []byte - hintTable [256]bool + hintIdx [256]uint8 // pos<<2|val for a hint byte, poisonHint for a hint-class byte no encoder emits, notHint otherwise encodeHint [4][16]byte encodeGroup [64]byte - decodeGroup [256]byte - groupValid [256]bool + decodeGroup [256]byte // 0..63 for hints, 0xff for padding/invalid bytes +} + +const ( + // poisonHint indexes an all-zero set: a hint-class byte no encoder emits, + // which keeps the stream from ever decoding. + poisonHint = 64 + notHint = 0x80 +) + +// indexHints derives hintIdx from encodeHint; aliases lists hint-class wire +// bytes that encodeHint never produces. +func (l *byteLayout) indexHints(aliases ...byte) { + for i := range l.hintIdx { + l.hintIdx[i] = notHint + } + for _, b := range aliases { + l.hintIdx[b] = poisonHint + } + for val := range l.encodeHint { + for pos, b := range l.encodeHint[val] { + l.hintIdx[b] = uint8(pos<<2 | val) + } + } } func (l *byteLayout) isHint(b byte) bool { - return l != nil && l.hintTable[b] + return l != nil && l.hintIdx[b] != notHint } func (l *byteLayout) hintByte(val, pos byte) byte { return l.encodeHint[val&0x03][pos&0x0F] } -func (l *byteLayout) groupByte(group byte) byte { - return l.encodeGroup[group&0x3F] -} - -func (l *byteLayout) decodePackedGroup(b byte) (byte, bool) { - if l == nil { - return 0, false - } - return l.decodeGroup[b], l.groupValid[b] -} - // resolveLayout picks the byte layout for a single traffic direction. // ASCII always wins if requested. Custom patterns are ignored when ASCII is preferred. func resolveLayout(mode string, customPattern string) (*byteLayout, error) { @@ -88,17 +99,19 @@ func newASCIILayout() *byteLayout { } layout.encodeGroup[group] = b } + // Every byte with bit 6 set is hint-class on the wire, though only the 63 + // below 0x7F and '\n' are ever emitted as hints. + var aliases []byte for b := 0; b < 256; b++ { + layout.decodeGroup[b] = 0xff wire := byte(b) if (wire & 0x40) == 0x40 { - layout.hintTable[wire] = true layout.decodeGroup[wire] = wire & 0x3F - layout.groupValid[wire] = true + aliases = append(aliases, wire) } } - layout.hintTable['\n'] = true layout.decodeGroup['\n'] = 0x3F - layout.groupValid['\n'] = true + layout.indexHints(aliases...) return layout } @@ -128,14 +141,14 @@ func newEntropyLayout() *byteLayout { layout.encodeGroup[group] = ((v & 0x30) << 1) | (v & 0x0F) } for b := 0; b < 256; b++ { + layout.decodeGroup[b] = 0xff wire := byte(b) if (wire & 0x90) != 0 { continue } - layout.hintTable[wire] = true layout.decodeGroup[wire] = ((wire >> 1) & 0x30) | (wire & 0x0F) - layout.groupValid[wire] = true } + layout.indexHints() return layout } @@ -229,11 +242,11 @@ func newCustomLayout(pattern string) (*byteLayout, error) { layout.encodeGroup[group] = encodeBits(val, pos, -1) } for b := 0; b < 256; b++ { + layout.decodeGroup[b] = 0xff wire := byte(b) if (wire & xMask) != xMask { continue } - layout.hintTable[wire] = true var val, pos byte if wire&(1<= 6 { + pc.bitCount -= 6 + group := byte(pc.bitBuf >> pc.bitCount) + pc.bitBuf &= 1<= 6 { - pc.bitCount -= 6 - group := byte(pc.bitBuf >> pc.bitCount) - if pc.bitCount == 0 { - pc.bitBuf = 0 - } else { - pc.bitBuf &= (1 << pc.bitCount) - 1 - } - out = appendPackedGroup(out, pc.table.layout, pc.rng, pc.paddingThreshold, pc.padPool, group) - } + out = pc.appendByte(out, p[i]) effective++ if effective >= gap { @@ -148,6 +138,32 @@ func appendPackedGroup(out []byte, layout *byteLayout, rng *sudokuRand, paddingT return append(out, layout.encodeGroup[group&0x3F]) } +// appendPackedBlocks encodes complete three-byte blocks. Keeping the no-padding +// loop separate removes the random draws and per-group append calls from it. +func appendPackedBlocks(out, p []byte, layout *byteLayout, rng *sudokuRand, threshold uint64, padPool []byte) []byte { + encode := &layout.encodeGroup + if threshold == 0 { + for ; len(p) >= 3; p = p[3:] { + b0, b1, b2 := p[0], p[1], p[2] + out = append(out, + encode[b0>>2], + encode[(b0&3)<<4|b1>>4], + encode[(b1&15)<<2|b2>>6], + encode[b2&63]) + } + return out + } + for ; len(p) >= 3; p = p[3:] { + b0, b1, b2 := p[0], p[1], p[2] + groups := [4]byte{b0 >> 2, (b0&3)<<4 | b1>>4, (b1&15)<<2 | b2>>6, b2 & 63} + for _, group := range groups { + out = maybeAppendPackedPadding(out, rng, threshold, padPool) + out = append(out, encode[group]) + } + } + return out +} + func maybeAppendPackedPadding(out []byte, rng *sudokuRand, paddingThreshold uint64, padPool []byte) []byte { if paddingThreshold != 0 { u := rng.Uint32() @@ -169,88 +185,47 @@ func (pc *PackedConn) Write(p []byte) (int, error) { pc.writeMu.Lock() defer pc.writeMu.Unlock() - needed := len(p)*3/2 + 32 - if pc.paddingThreshold == 0 { - needed = ((len(p)+2)/3)*4 + 32 - } - if cap(pc.writeBuf) < needed { - pc.writeBuf = make([]byte, 0, needed) - } - out := pc.writeBuf[:0] + // Bound storage independently of the caller's Write size, including padding. + out := growWriteBuf(pc.writeBuf, minInt(minInt(len(p), maxEncodedWriteSize)*3+64, maxEncodedWriteSize)) + defer func() { pc.writeBuf = releaseWriteBuf(out) }() layout := pc.table.layout rng := pc.rng paddingThreshold := pc.paddingThreshold padPool := pc.padPool - var prefixN int - out, prefixN = pc.writeProtectedPrefix(out, p) - - i := prefixN + out, i := pc.writeProtectedPrefix(out, p) n := len(p) + // Align to a complete group boundary. for pc.bitCount > 0 && i < n { - b := p[i] + out = pc.appendByte(out, p[i]) i++ - pc.bitBuf = (pc.bitBuf << 8) | uint64(b) - pc.bitCount += 8 - for pc.bitCount >= 6 { - pc.bitCount -= 6 - group := byte(pc.bitBuf >> pc.bitCount) - if pc.bitCount == 0 { - pc.bitBuf = 0 - } else { - pc.bitBuf &= (1 << pc.bitCount) - 1 + } + + end := i + (n-i)/3*3 + blockSize := 4 + if paddingThreshold != 0 { + blockSize = 8 + } + written := 0 + for i < end { + // Reserve room for the final two bytes, residual marker and trailing pad. + count := minInt((cap(out)-len(out)-8)/blockSize*3, end-i) + if count == 0 { + if _, err := pc.Conn.Write(out); err != nil { + return written, err } - out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, group) + written = i + out = out[:0] + continue } + out = appendPackedBlocks(out, p[i:i+count], layout, rng, paddingThreshold, padPool) + i += count } - for i+11 < n { - for batch := 0; batch < 4; batch++ { - b1, b2, b3 := p[i], p[i+1], p[i+2] - i += 3 - - g1 := (b1 >> 2) & 0x3F - g2 := ((b1 & 0x03) << 4) | ((b2 >> 4) & 0x0F) - g3 := ((b2 & 0x0F) << 2) | ((b3 >> 6) & 0x03) - g4 := b3 & 0x3F - - out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g1) - out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g2) - out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g3) - out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g4) - } - } - - for i+2 < n { - b1, b2, b3 := p[i], p[i+1], p[i+2] - i += 3 - - g1 := (b1 >> 2) & 0x3F - g2 := ((b1 & 0x03) << 4) | ((b2 >> 4) & 0x0F) - g3 := ((b2 & 0x0F) << 2) | ((b3 >> 6) & 0x03) - g4 := b3 & 0x3F - - out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g1) - out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g2) - out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g3) - out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, g4) - } - + // The remaining one or two bytes stay in the accumulator. for ; i < n; i++ { - b := p[i] - pc.bitBuf = (pc.bitBuf << 8) | uint64(b) - pc.bitCount += 8 - for pc.bitCount >= 6 { - pc.bitCount -= 6 - group := byte(pc.bitBuf >> pc.bitCount) - if pc.bitCount == 0 { - pc.bitBuf = 0 - } else { - pc.bitBuf &= (1 << pc.bitCount) - 1 - } - out = appendPackedGroup(out, layout, rng, paddingThreshold, padPool, group) - } + out = pc.appendByte(out, p[i]) } if pc.bitCount > 0 { @@ -263,14 +238,9 @@ func (pc *PackedConn) Write(p []byte) (int, error) { out = maybeAppendPackedPadding(out, rng, paddingThreshold, padPool) - if len(out) > 0 { - pc.writeBuf = out[:0] - if _, err := pc.Conn.Write(out); err != nil { - return len(p), err - } - return len(p), nil + if _, err := pc.Conn.Write(out); err != nil { + return written, err } - pc.writeBuf = out[:0] return len(p), nil } @@ -288,7 +258,7 @@ func (pc *PackedConn) Flush() error { pc.bitBuf = 0 pc.bitCount = 0 - out = append(out, pc.table.layout.groupByte(group&0x3F)) + out = append(out, pc.table.layout.encodeGroup[group&0x3F]) out = append(out, pc.padMarker) } @@ -306,71 +276,21 @@ func (pc *PackedConn) Read(p []byte) (int, error) { if len(p) == 0 { return 0, nil } - if pc == nil || pc.Conn == nil || pc.reader == nil || len(pc.rawBuf) == 0 || pc.table == nil || pc.table.layout == nil { + if pc == nil || pc.Conn == nil || pc.table == nil || pc.table.layout == nil { return 0, io.ErrClosedPipe } - if n, ok := drainPending(p, &pc.pendingData); ok { - return n, nil + if pc.reader == nil { + // Write-only codecs never pay for a read buffer. + pc.reader = &wireReader{src: pc.Conn} } outN := 0 for { - nr, rErr := readRawLimited(pc.Conn, pc.reader, pc.rawBuf[:packedReadSize(len(p)-outN, len(pc.rawBuf))]) - if nr > 0 { - rBuf := pc.readBitBuf - rBits := pc.readBits - padMarker := pc.padMarker - layout := pc.table.layout - - chunk := pc.rawBuf[:nr] - for i := 0; i < len(chunk); { - if rBits == 0 && outN+3 <= len(p) && i+3 < len(chunk) && - layout.hintTable[chunk[i]] && layout.hintTable[chunk[i+1]] && - layout.hintTable[chunk[i+2]] && layout.hintTable[chunk[i+3]] { - g1 := layout.decodeGroup[chunk[i]] - g2 := layout.decodeGroup[chunk[i+1]] - g3 := layout.decodeGroup[chunk[i+2]] - g4 := layout.decodeGroup[chunk[i+3]] - p[outN] = (g1 << 2) | (g2 >> 4) - p[outN+1] = (g2 << 4) | (g3 >> 2) - p[outN+2] = (g3 << 6) | g4 - outN += 3 - i += 4 - continue - } - - b := chunk[i] - i++ - if !layout.hintTable[b] { - if b == padMarker { - rBuf = 0 - rBits = 0 - } - continue - } - - group, ok := layout.decodePackedGroup(b) - if !ok { - return 0, ErrInvalidSudokuMapMiss - } - - rBuf = (rBuf << 6) | uint64(group) - rBits += 6 - - if rBits >= 8 { - rBits -= 8 - val := byte(rBuf >> rBits) - outN = appendDecodedByte(p, outN, &pc.pendingData, val) - if rBits == 0 { - rBuf = 0 - } else { - rBuf &= (uint64(1) << rBits) - 1 - } - } - } - - pc.readBitBuf = rBuf - pc.readBits = rBits + chunk, rErr := pc.reader.peek() + if len(chunk) > 0 { + var consumed int + outN, consumed, rErr = pc.decode(p, chunk) + pc.reader.discard(consumed) } if rErr != nil { @@ -378,12 +298,6 @@ func (pc *PackedConn) Read(p []byte) (int, error) { pc.readBitBuf = 0 pc.readBits = 0 } - if outN > 0 { - return outN, nil - } - if n, ok := drainPending(p, &pc.pendingData); ok { - return n, nil - } return 0, rErr } @@ -393,17 +307,59 @@ func (pc *PackedConn) Read(p []byte) (int, error) { } } +// decode writes only as much plaintext as fits in p; the wire bytes it +// consumed can then be dropped and the rest stay in the reader. +func (pc *PackedConn) decode(p, chunk []byte) (outN, consumed int, err error) { + rBuf := pc.readBitBuf + rBits := pc.readBits + padMarker := pc.padMarker + layout := pc.table.layout + + for consumed < len(chunk) && outN < len(p) { + i := consumed + if rBits == 0 && outN+3 <= len(p) && i+3 < len(chunk) { + g1 := layout.decodeGroup[chunk[i]] + g2 := layout.decodeGroup[chunk[i+1]] + g3 := layout.decodeGroup[chunk[i+2]] + g4 := layout.decodeGroup[chunk[i+3]] + // The invalid sentinel combines validation and decoding in one lookup. + if (g1 | g2 | g3 | g4) < 64 { + p[outN] = (g1 << 2) | (g2 >> 4) + p[outN+1] = (g2 << 4) | (g3 >> 2) + p[outN+2] = (g3 << 6) | g4 + outN += 3 + consumed += 4 + continue + } + } + + b := chunk[i] + consumed++ + group := layout.decodeGroup[b] + if group >= 64 { + if b == padMarker { + rBuf = 0 + rBits = 0 + } + continue + } + + rBuf = (rBuf << 6) | uint64(group) + rBits += 6 + + if rBits >= 8 { + rBits -= 8 + p[outN] = byte(rBuf >> rBits) + outN++ + rBuf &= (uint64(1) << rBits) - 1 + } + } + + pc.readBitBuf = rBuf + pc.readBits = rBits + return outN, consumed, nil +} + func (pc *PackedConn) getPaddingByte() byte { return pc.padPool[pc.rng.Intn(len(pc.padPool))] } - -func packedReadSize(decodedRemaining, maxRaw int) int { - if maxRaw <= minDecodeReadSize || decodedRemaining <= 0 { - return maxRaw - } - if decodedRemaining > (maxRaw-minDecodeReadSize)/2 { - return maxRaw - } - - return decodedRemaining*2 + minDecodeReadSize -} diff --git a/transport/sudoku/obfs/sudoku/packed_prefix_test.go b/transport/sudoku/obfs/sudoku/packed_prefix_test.go index f6f35fccb..abb1b2809 100644 --- a/transport/sudoku/obfs/sudoku/packed_prefix_test.go +++ b/transport/sudoku/obfs/sudoku/packed_prefix_test.go @@ -3,6 +3,7 @@ package sudoku import ( "bytes" "io" + "math/rand" "net" "testing" "time" @@ -88,3 +89,105 @@ func TestPackedConn_ProtectedPrefixPadding(t *testing.T) { t.Fatalf("roundtrip mismatch") } } + +func TestCodecRoundTrip(t *testing.T) { + tables := map[string]*Table{ + "entropy": NewTable("roundtrip-seed", "prefer_entropy"), + "ascii": NewTable("roundtrip-seed", "prefer_ascii"), + } + custom, err := NewTableWithCustom("roundtrip-seed", "up_ascii_down_entropy", "xpxvvpvv") + if err != nil { + t.Fatal(err) + } + tables["custom"] = custom.OppositeDirection() + + for name, table := range tables { + for _, packed := range []bool{false, true} { + for _, pad := range [][2]int{{0, 0}, {5, 15}, {100, 100}} { + for _, size := range []int{1, 2, 14, 15, 100, 70000} { + payload := make([]byte, size) + rand.New(rand.NewSource(int64(size))).Read(payload) + + mock := &mockConn{} + var w io.Writer = NewConn(mock, table, pad[0], pad[1], false) + if packed { + w = NewPackedConn(mock, table, pad[0], pad[1]) + } + // Split the payload so partial packed groups carry over between writes. + if _, err := w.Write(payload[:size/2]); err != nil { + t.Fatal(err) + } + if _, err := w.Write(payload[size/2:]); err != nil { + t.Fatal(err) + } + if f, ok := w.(*PackedConn); ok { + if err := f.Flush(); err != nil { + t.Fatal(err) + } + } + + for _, readSize := range []int{1, 7, 4096} { + src := &mockConn{readBuf: append([]byte(nil), mock.writeBuf...)} + var r io.Reader = NewConn(src, table, pad[0], pad[1], false) + if packed { + r = NewPackedConn(src, table, pad[0], pad[1]) + } + got := make([]byte, 0, size) + buf := make([]byte, readSize) + for { + n, err := r.Read(buf) + got = append(got, buf[:n]...) + if err == io.EOF { + break + } + if err != nil { + t.Fatal(err) + } + } + if !bytes.Equal(got, payload) { + t.Fatalf("%s packed=%v pad=%v size=%d read=%d: round trip mismatch", name, packed, pad, size, readSize) + } + } + } + } + } + } +} + +func TestConnRecordsEverythingRead(t *testing.T) { + table := NewTable("record-seed", "prefer_entropy") + writer := &mockConn{} + payload := bytes.Repeat([]byte("sudoku"), 3000) + if _, err := NewConn(writer, table, 5, 15, false).Write(payload); err != nil { + t.Fatal(err) + } + wire := writer.writeBuf + + src := &mockConn{readBuf: append([]byte(nil), wire...)} + sc := NewConn(src, table, 5, 15, true) + buf := make([]byte, 200) + for step := 0; step < 3; step++ { + if _, err := io.ReadFull(sc, buf); err != nil { + t.Fatal(err) + } + // Recorded plus buffered must be every byte taken from the socket, whatever + // the reader has or has not decoded yet. + if got, want := sc.GetBufferedAndRecorded(), wire[:len(wire)-len(src.readBuf)]; !bytes.Equal(got, want) { + t.Fatalf("step %d: recorded %d bytes, want %d", step, len(got), len(want)) + } + } + if !sc.reader.pooled { + t.Fatalf("a busy connection should have switched to a pooled read buffer") + } + + sc.StopRecording() + if _, err := io.Copy(io.Discard, sc); err != nil { + t.Fatal(err) + } + if sc.reader.pooled || len(sc.reader.pending()) != 0 { + t.Fatalf("a drained connection should hold no pooled buffer") + } + if got := sc.GetBufferedAndRecorded(); len(got) != 0 { + t.Fatalf("recording was stopped, got %d bytes", len(got)) + } +} diff --git a/transport/sudoku/obfs/sudoku/pending.go b/transport/sudoku/obfs/sudoku/pending.go deleted file mode 100644 index 6c6243740..000000000 --- a/transport/sudoku/obfs/sudoku/pending.go +++ /dev/null @@ -1,69 +0,0 @@ -package sudoku - -type pendingBuffer struct { - data []byte - off int -} - -func newPendingBuffer(capacity int) pendingBuffer { - return pendingBuffer{data: make([]byte, 0, capacity)} -} - -func (p *pendingBuffer) available() int { - if p == nil { - return 0 - } - return len(p.data) - p.off -} - -func (p *pendingBuffer) reset() { - if p == nil { - return - } - p.data = p.data[:0] - p.off = 0 -} - -func (p *pendingBuffer) ensureAppendCapacity(extra int) { - if p == nil || extra <= 0 { - return - } - if p.off == 0 { - return - } - if cap(p.data)-len(p.data) >= extra { - return - } - - unread := len(p.data) - p.off - copy(p.data[:unread], p.data[p.off:]) - p.data = p.data[:unread] - p.off = 0 -} - -func (p *pendingBuffer) appendByte(b byte) { - p.ensureAppendCapacity(1) - p.data = append(p.data, b) -} - -func appendDecodedByte(dst []byte, n int, pending *pendingBuffer, b byte) int { - if n < len(dst) { - dst[n] = b - return n + 1 - } - pending.appendByte(b) - return n -} - -func drainPending(dst []byte, pending *pendingBuffer) (int, bool) { - if pending == nil || pending.available() == 0 { - return 0, false - } - - n := copy(dst, pending.data[pending.off:]) - pending.off += n - if pending.off == len(pending.data) { - pending.reset() - } - return n, true -} diff --git a/transport/sudoku/obfs/sudoku/rand.go b/transport/sudoku/obfs/sudoku/rand.go index f40a08611..f35629096 100644 --- a/transport/sudoku/obfs/sudoku/rand.go +++ b/transport/sudoku/obfs/sudoku/rand.go @@ -3,13 +3,14 @@ package sudoku import ( crypto_rand "crypto/rand" "encoding/binary" + "math/bits" "time" ) +// sudokuRand is a wyrand generator. Its state advances by a constant, so draws +// do not depend on each other's results and the encoder can overlap them. type sudokuRand struct { - state uint64 - cached uint32 - haveCached bool + state uint64 } func newSeededRand() *sudokuRand { @@ -22,38 +23,25 @@ func newSeededRand() *sudokuRand { } func newSudokuRand(seed int64) *sudokuRand { - state := uint64(seed) - if state == 0 { - state = 0x9e3779b97f4a7c15 - } - return &sudokuRand{state: state} + return &sudokuRand{state: uint64(seed)} +} + +// wyNext is the generator step as a pure function so hot loops can keep the +// state in a register. +func wyNext(state uint64) (next, out uint64) { + state += 0xa0761d6478bd642f + hi, lo := bits.Mul64(state, state^0xe7037ed1a0b428db) + return state, hi ^ lo } func (r *sudokuRand) Uint64() uint64 { - if r == nil { - return 0 - } - r.haveCached = false - x := r.state - x ^= x >> 12 - x ^= x << 25 - x ^= x >> 27 - r.state = x - return x * 0x2545f4914f6cdd1d + var out uint64 + r.state, out = wyNext(r.state) + return out } func (r *sudokuRand) Uint32() uint32 { - if r == nil { - return 0 - } - if r.haveCached { - r.haveCached = false - return r.cached - } - v := r.Uint64() - r.cached = uint32(v) - r.haveCached = true - return uint32(v >> 32) + return uint32(r.Uint64() >> 32) } func (r *sudokuRand) Intn(n int) int { diff --git a/transport/sudoku/obfs/sudoku/read_buffer.go b/transport/sudoku/obfs/sudoku/read_buffer.go new file mode 100644 index 000000000..68d9819f4 --- /dev/null +++ b/transport/sudoku/obfs/sudoku/read_buffer.go @@ -0,0 +1,80 @@ +package sudoku + +import ( + "io" + + "github.com/metacubex/mihomo/common/pool" +) + +const ( + // smallReadSize is what a connection reads into while it may block for a + // long time. Idle connections hold at most this much. + smallReadSize = 512 + // readBufferSize is the wire read size of a busy connection, borrowed from + // the shared pool only while it has data. + readBufferSize = 32 * 1024 +) + +// wireReader hands the codecs the raw bytes already received, without a second +// copy. It reads small while a connection is quiet, switches to a pooled buffer +// once a read fills its buffer (more is queued, so the next read will not +// block), and returns that buffer when drained. +type wireReader struct { + src io.Reader + buf []byte + pooled bool + r, w int + wasFull bool + smallBuf [smallReadSize]byte +} + +// peek borrows every unread wire byte, reading first when there are none. It +// waits for at least one byte, never for a full buffer. The slice is valid +// until the next peek or discard. +func (wr *wireReader) peek() ([]byte, error) { + if wr.r == wr.w { + if err := wr.fill(); err != nil { + return nil, err + } + } + return wr.buf[wr.r:wr.w], nil +} + +func (wr *wireReader) fill() error { + switch { + case wr.wasFull && !wr.pooled: + wr.buf, wr.pooled = pool.Get(readBufferSize), true + case wr.buf == nil: + wr.buf = wr.smallBuf[:] + } + for { + n, err := wr.src.Read(wr.buf) + if n > 0 { + wr.r, wr.w = 0, n + wr.wasFull = n == len(wr.buf) + return nil + } + if err != nil { + return err + } + } +} + +// discard drops n bytes peek returned. A pooled buffer goes back once it is +// drained by a read that did not fill it, since the next read may block. +func (wr *wireReader) discard(n int) { + wr.r += n + if wr.r == wr.w && wr.pooled && !wr.wasFull { + pool.Put(wr.buf) + wr.buf, wr.pooled = wr.smallBuf[:], false + wr.r, wr.w = 0, 0 + } +} + +// pending returns the received but undecoded bytes. +func (wr *wireReader) pending() []byte { + if wr == nil { + return nil + } + return wr.buf[wr.r:wr.w] +} diff --git a/transport/sudoku/obfs/sudoku/table.go b/transport/sudoku/obfs/sudoku/table.go index d355ae0e1..33ff3bfb9 100644 --- a/transport/sudoku/obfs/sudoku/table.go +++ b/transport/sudoku/obfs/sudoku/table.go @@ -4,6 +4,7 @@ import ( "crypto/sha256" "encoding/binary" "errors" + "math/bits" "math/rand" "strings" ) @@ -14,12 +15,16 @@ var ( type Table struct { EncodeTable [256][][4]byte - DecodeMap map[uint32]byte PaddingPool []byte IsASCII bool // 标记当前模式 layout *byteLayout opposite *Table hint uint32 + + // hintSets[pos<<2|val] holds bit k when the k-th shuffled grid has val at + // pos. Four hints identify a plaintext byte exactly when their sets share a + // single grid, and that grid's rank is the byte. + hintSets [128][5]uint64 } // NewTable initializes the obfuscation tables with built-in layouts. @@ -73,9 +78,8 @@ func newSingleDirectionTable(key string, mode string, customPattern string) (*Ta } t := &Table{ - DecodeMap: make(map[uint32]byte), - IsASCII: layout.name == "ascii", - layout: layout, + IsASCII: layout.name == "ascii", + layout: layout, } t.PaddingPool = append(t.PaddingPool, layout.paddingPool...) @@ -110,50 +114,31 @@ func newSingleDirectionTable(key string, mode string, customPattern string) (*Ta } combine(0, 4, []int{}) + for k, g := range shuffledGrids { + for pos, val := range g { + t.hintSets[pos<<2|int(val-1)][k>>6] |= 1 << (k & 63) + } + } + // 构建映射表 for byteVal := 0; byteVal < 256; byteVal++ { targetGrid := shuffledGrids[byteVal] for _, positions := range combinations { - var currentHints [4]byte - - // 1. 计算抽象提示 (Abstract Hints) - // 我们先计算出 val 和 pos,后面再根据模式编码成 byte - var rawParts [4]struct{ val, pos byte } - + var hints [4]uint8 for i, pos := range positions { - val := targetGrid[pos] // 1..4 - rawParts[i] = struct{ val, pos byte }{val, uint8(pos)} + hints[i] = uint8(pos)<<2 | (targetGrid[pos] - 1) } - // 检查唯一性 (数独逻辑) - matchCount := 0 - for _, g := range allGrids { - match := true - for _, p := range rawParts { - if g[p.pos] != p.val { - match = false - break - } - } - if match { - matchCount++ - if matchCount > 1 { - break - } - } + // 唯一确定才可作为 puzzle + if _, ok := t.decodeHints(hints[0], hints[1], hints[2], hints[3]); !ok { + continue } - if matchCount == 1 { - // 唯一确定,生成最终编码字节 - for i, p := range rawParts { - currentHints[i] = t.layout.hintByte(p.val-1, p.pos) - } - - t.EncodeTable[byteVal] = append(t.EncodeTable[byteVal], currentHints) - // 生成解码键 (需要对 Hints 进行排序以忽略传输顺序) - key := packHintsToKey(currentHints) - t.DecodeMap[key] = byte(byteVal) + var currentHints [4]byte + for i, pos := range positions { + currentHints[i] = t.layout.hintByte(targetGrid[pos]-1, uint8(pos)) } + t.EncodeTable[byteVal] = append(t.EncodeTable[byteVal], currentHints) } } return t, nil @@ -191,28 +176,35 @@ func tableHintFingerprint(key string, mode string, uplinkPattern string, downlin return binary.BigEndian.Uint32(sum[:4]) } -func packHintsToKey(hints [4]byte) uint32 { - return packHintBytes(hints[0], hints[1], hints[2], hints[3]) -} +// decodeHints returns the plaintext byte whose puzzle is exactly these four +// hint indexes (pos<<2|val, or poisonHint). +func (t *Table) decodeHints(a, b, c, d uint8) (byte, bool) { + sa, sb, sc, sd := &t.hintSets[a&127], &t.hintSets[b&127], &t.hintSets[c&127], &t.hintSets[d&127] + r0 := sa[0] & sb[0] & sc[0] & sd[0] + r1 := sa[1] & sb[1] & sc[1] & sd[1] + r2 := sa[2] & sb[2] & sc[2] & sd[2] + r3 := sa[3] & sb[3] & sc[3] & sd[3] + r4 := sa[4] & sb[4] & sc[4] & sd[4] -func packHintBytes(h0, h1, h2, h3 byte) uint32 { - // Sorting network for 4 elements (Bubble sort unrolled) - // Swap if a > b - if h0 > h1 { - h0, h1 = h1, h0 + // Exactly one shared grid, and it must be one of the 256 that carry a byte. + multi := r0&(r0-1) | r1&(r1-1) | r2&(r2-1) | r3&(r3-1) | r4 + var nonEmpty uint64 + word := 0 + if r1 != 0 { + nonEmpty++ + word = 64 } - if h2 > h3 { - h2, h3 = h3, h2 + if r2 != 0 { + nonEmpty++ + word = 128 } - if h0 > h2 { - h0, h2 = h2, h0 + if r3 != 0 { + nonEmpty++ + word = 192 } - if h1 > h3 { - h1, h3 = h3, h1 + if r0 != 0 { + nonEmpty++ } - if h1 > h2 { - h1, h2 = h2, h1 - } - - return uint32(h0)<<24 | uint32(h1)<<16 | uint32(h2)<<8 | uint32(h3) + rank := word + bits.TrailingZeros64(r0|r1|r2|r3) + return byte(rank), multi|(nonEmpty^1) == 0 } diff --git a/transport/sudoku/obfs/sudoku/write_buffer.go b/transport/sudoku/obfs/sudoku/write_buffer.go new file mode 100644 index 000000000..b752bce76 --- /dev/null +++ b/transport/sudoku/obfs/sudoku/write_buffer.go @@ -0,0 +1,88 @@ +package sudoku + +import ( + "io" + "math" + + "github.com/metacubex/mihomo/common/pool" +) + +const ( + // maxEncodedWriteSize bounds one Write to the underlying connection and the + // encode buffer, matching readBufferSize. + maxEncodedWriteSize = 32 * 1024 + // retainedWriteBytes is the encode buffer a connection keeps between writes. + // Larger encodes borrow a pooled buffer for the duration of one Write. + retainedWriteBytes = 2048 +) + +// minInt exists because the module still targets Go 1.20, which has no min. +func minInt(a, b int) int { + if a < b { + return a + } + return b +} + +// writeSudokuPayload encodes p and writes it to w, keeping the encode buffer +// bounded however large p is. It fills the remaining space with complete +// payload bytes, then sends that buffer. The padding slot that closes a Write +// belongs to the whole Write, never to an internal batch. +func writeSudokuPayload(w io.Writer, buf []byte, table *Table, rng *sudokuRand, threshold uint64, p []byte) ([]byte, int, error) { + expansion := maxPaddedExpansion + if threshold == 0 { + expansion = 4 + } + buf = growWriteBuf(buf, minInt(minInt(len(p), maxEncodedWriteSize)*expansion+encodeSlack, maxEncodedWriteSize)) + out := buf[:0] + total, buffered := 0, 0 + for len(p) > 0 { + n := minInt(len(p), (cap(out)-len(out)-encodeSlack)/expansion) + if n == 0 { + if _, err := w.Write(out); err != nil { + return releaseWriteBuf(out), total, err + } + total += buffered + buffered = 0 + out = out[:0] + continue + } + out = appendSudokuPayload(out, table, rng, threshold, p[:n]) + buffered += n + p = p[n:] + } + + if threshold != 0 { + draw := rng.Uint64() + if draw&math.MaxUint32 < threshold { + pad := table.PaddingPool + out = append(out, pad[(draw>>32)*uint64(len(pad))>>32]) + } + } + if _, err := w.Write(out); err != nil { + return releaseWriteBuf(out), total, err + } + return releaseWriteBuf(out), total + buffered, nil +} + +// growWriteBuf returns an empty buffer with room for need bytes, borrowed from +// the pool when need exceeds what a connection may retain. +func growWriteBuf(buf []byte, need int) []byte { + if cap(buf) >= need { + return buf[:0] + } + if need <= retainedWriteBytes { + return make([]byte, 0, need) + } + return pool.Get(maxEncodedWriteSize)[:0] +} + +// releaseWriteBuf keeps a small buffer for the next Write and returns a pooled +// one. +func releaseWriteBuf(buf []byte) []byte { + if cap(buf) <= retainedWriteBytes { + return buf[:0] + } + pool.Put(buf) + return nil +} diff --git a/transport/sudoku/table_probe.go b/transport/sudoku/table_probe.go index 54320afe5..471fa2eee 100644 --- a/transport/sudoku/table_probe.go +++ b/transport/sudoku/table_probe.go @@ -10,6 +10,7 @@ import ( "net" "time" + "github.com/metacubex/mihomo/common/pool" "github.com/metacubex/mihomo/transport/sudoku/crypto" "github.com/metacubex/mihomo/transport/sudoku/obfs/sudoku" ) @@ -115,7 +116,10 @@ func selectTableByProbe(r *bufio.Reader, cfg *ProtocolConfig, tables []*sudoku.T return nil, nil, fmt.Errorf("drain buffered bytes failed: %w", err) } - tmp := make([]byte, readChunk) + // Most handshakes are decided by the bytes bufio already holds, so the read chunk is + // only taken once another read is needed. + var chunk []byte + defer func() { _ = pool.Put(chunk) }() for { if len(candidates) == 1 { tail, err := drainBuffered(r) @@ -153,9 +157,12 @@ func selectTableByProbe(r *bufio.Reader, cfg *ProtocolConfig, tables []*sudoku.T return nil, probe, fmt.Errorf("handshake probe exceeded %d bytes", maxProbeBytes) } - n, err := r.Read(tmp) + if chunk == nil { + chunk = pool.Get(readChunk) + } + n, err := r.Read(chunk) if n > 0 { - probe = append(probe, tmp[:n]...) + probe = append(probe, chunk[:n]...) } if err != nil { return nil, probe, fmt.Errorf("handshake probe read failed: %w", err) diff --git a/transport/sudoku/uot.go b/transport/sudoku/uot.go index 854b3b503..88812e7be 100644 --- a/transport/sudoku/uot.go +++ b/transport/sudoku/uot.go @@ -1,76 +1,121 @@ package sudoku import ( - "bytes" "encoding/binary" "errors" "fmt" "io" + "math" "net" "net/netip" "sync" "time" + "github.com/metacubex/mihomo/common/pool" "github.com/metacubex/mihomo/log" + "github.com/metacubex/mihomo/transport/socks5" ) -const ( - maxUoTPayload = 64 * 1024 -) +// uotHeaderSize is u16 address length | u16 payload length. +const uotHeaderSize = 4 // WriteDatagram sends a single UDP datagram frame over a reliable stream. func WriteDatagram(w io.Writer, addr string, payload []byte) error { - addrBuf, err := EncodeAddress(addr) + return writeDatagram(w, payload, func(b []byte) ([]byte, error) { return AppendAddress(b, addr) }) +} + +// writeDatagram sends the whole frame with one write, so it is sealed as one record. +func writeDatagram(w io.Writer, payload []byte, appendAddr func([]byte) ([]byte, error)) error { + if len(payload) > math.MaxUint16 { + return fmt.Errorf("payload too large: %d", len(payload)) + } + buf := pool.Get(uotHeaderSize + socks5.MaxAddrLen + len(payload)) + defer pool.Put(buf) + + frame, err := appendAddr(buf[:uotHeaderSize]) if err != nil { return fmt.Errorf("encode address: %w", err) } - - if addrLen := len(addrBuf); addrLen == 0 || addrLen > maxUoTPayload { - return fmt.Errorf("address too long: %d", len(addrBuf)) - } - if payloadLen := len(payload); payloadLen > maxUoTPayload { - return fmt.Errorf("payload too large: %d", payloadLen) - } - - var header [4]byte - binary.BigEndian.PutUint16(header[:2], uint16(len(addrBuf))) - binary.BigEndian.PutUint16(header[2:], uint16(len(payload))) - - return writeAllChunks(w, header[:], addrBuf, payload) + binary.BigEndian.PutUint16(frame, uint16(len(frame)-uotHeaderSize)) + binary.BigEndian.PutUint16(frame[2:], uint16(len(payload))) + _, err = w.Write(append(frame, payload...)) + return err } -// ReadDatagram parses a single UDP datagram frame from the reliable stream. -func ReadDatagram(r io.Reader) (string, []byte, error) { - addr, payloadLen, err := readDatagramHeaderAndAddress(r) - if err != nil { - return "", nil, err +// UoTReader reads datagram frames from a UoT stream. The header and address are read into +// scratch space owned by the reader, so a frame costs no allocation besides its payload. +type UoTReader struct { + r io.Reader + buf [uotHeaderSize + socks5.MaxAddrLen]byte +} + +func NewUoTReader(r io.Reader) *UoTReader { + return &UoTReader{r: r} +} + +// readHeader reads the next frame's header and address and leaves its payload (payloadLen bytes) +// unread. addr is only valid until the next call. +func (u *UoTReader) readHeader() (addr socks5.Addr, payloadLen int, err error) { + if _, err = io.ReadFull(u.r, u.buf[:uotHeaderSize]); err != nil { + return nil, 0, err } - payload := make([]byte, payloadLen) - if _, err := io.ReadFull(r, payload); err != nil { - return "", nil, err + addrLen := int(binary.BigEndian.Uint16(u.buf[:2])) + payloadLen = int(binary.BigEndian.Uint16(u.buf[2:])) + if addrLen == 0 { + return nil, 0, fmt.Errorf("invalid address length: %d", addrLen) } + // An encoded address is at most socks5.MaxAddrLen bytes; anything after it is padding. + n := addrLen + if n > socks5.MaxAddrLen { + n = socks5.MaxAddrLen + } + if _, err = io.ReadFull(u.r, u.buf[uotHeaderSize:uotHeaderSize+n]); err != nil { + return nil, 0, err + } + if err = discardBytes(u.r, addrLen-n); err != nil { + return nil, 0, err + } + if addr = socks5.SplitAddr(u.buf[uotHeaderSize : uotHeaderSize+n]); addr == nil { + return nil, 0, errors.New("decode address: invalid address") + } + return addr, payloadLen, nil +} + +// ReadDatagram reads the next frame. addr is only valid until the next call; payload comes from +// common/pool and must be released with pool.Put. +func (u *UoTReader) ReadDatagram() (socks5.Addr, []byte, error) { + addr, payloadLen, err := u.readHeader() + if err != nil { + return nil, nil, err + } + payload := pool.Get(payloadLen) + if _, err := io.ReadFull(u.r, payload); err != nil { + _ = pool.Put(payload) + return nil, nil, err + } return addr, payload, nil } // UoTPacketConn adapts a net.Conn with the Sudoku UoT framing to net.PacketConn. type UoTPacketConn struct { conn net.Conn + reader *UoTReader writeMu sync.Mutex } func NewUoTPacketConn(conn net.Conn) *UoTPacketConn { - return &UoTPacketConn{conn: conn} + return &UoTPacketConn{conn: conn, reader: NewUoTReader(conn)} } func (c *UoTPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { for { - addrStr, payloadLen, err := readDatagramHeaderAndAddress(c.conn) + addr, payloadLen, err := c.reader.readHeader() if err != nil { return 0, nil, err } - udpAddr, err := parseDatagramUDPAddr(addrStr) + udpAddr, err := uotUDPAddr(addr) if payloadLen > len(p) { if discardErr := discardBytes(c.conn, payloadLen); discardErr != nil { return 0, nil, discardErr @@ -81,7 +126,7 @@ func (c *UoTPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { if discardErr := discardBytes(c.conn, payloadLen); discardErr != nil { return 0, nil, discardErr } - log.Debugln("[Sudoku][UoT] discard datagram with invalid address %s: %v", addrStr, err) + log.Debugln("[Sudoku][UoT] discard datagram with invalid address %s: %v", addr, err) continue } if _, err := io.ReadFull(c.conn, p[:payloadLen]); err != nil { @@ -95,9 +140,16 @@ func (c *UoTPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) { if addr == nil { return 0, errors.New("address is nil") } + appendAddr := func(b []byte) ([]byte, error) { return AppendAddress(b, addr.String()) } + if udpAddr, ok := addr.(*net.UDPAddr); ok { + if ap := udpAddr.AddrPort(); ap.Addr().IsValid() { + appendAddr = func(b []byte) ([]byte, error) { return AppendAddrPort(b, ap), nil } + } + } + c.writeMu.Lock() defer c.writeMu.Unlock() - if err := WriteDatagram(c.conn, addr.String(), p); err != nil { + if err := writeDatagram(c.conn, p, appendAddr); err != nil { return 0, err } return len(p), nil @@ -123,39 +175,22 @@ func (c *UoTPacketConn) SetWriteDeadline(t time.Time) error { return c.conn.SetWriteDeadline(t) } -func readDatagramHeaderAndAddress(r io.Reader) (string, int, error) { - var header [4]byte - if _, err := io.ReadFull(r, header[:]); err != nil { - return "", 0, err +// uotUDPAddr converts a datagram's peer to a *net.UDPAddr. Domain names are not resolved: only +// the IP literals they may spell are accepted. +func uotUDPAddr(addr socks5.Addr) (*net.UDPAddr, error) { + var ap netip.AddrPort + switch addr[0] { + case socks5.AtypIPv4: + ap = netip.AddrPortFrom(netip.AddrFrom4([4]byte(addr[1:5])), binary.BigEndian.Uint16(addr[5:])) + case socks5.AtypIPv6: + ap = netip.AddrPortFrom(netip.AddrFrom16([16]byte(addr[1:17])), binary.BigEndian.Uint16(addr[17:])) + default: + var err error + if ap, err = netip.ParseAddrPort(addr.String()); err != nil { + return nil, err + } } - - addrLen := int(binary.BigEndian.Uint16(header[:2])) - payloadLen := int(binary.BigEndian.Uint16(header[2:])) - if addrLen <= 0 || addrLen > maxUoTPayload { - return "", 0, fmt.Errorf("invalid address length: %d", addrLen) - } - if payloadLen < 0 || payloadLen > maxUoTPayload { - return "", 0, fmt.Errorf("invalid payload length: %d", payloadLen) - } - - addrBuf := make([]byte, addrLen) - if _, err := io.ReadFull(r, addrBuf); err != nil { - return "", 0, err - } - - addr, err := DecodeAddress(bytes.NewReader(addrBuf)) - if err != nil { - return "", 0, fmt.Errorf("decode address: %w", err) - } - return addr, payloadLen, nil -} - -func parseDatagramUDPAddr(addr string) (*net.UDPAddr, error) { - addrPort, err := netip.ParseAddrPort(addr) - if err != nil { - return nil, err - } - return net.UDPAddrFromAddrPort(netip.AddrPortFrom(addrPort.Addr().Unmap(), addrPort.Port())), nil + return net.UDPAddrFromAddrPort(netip.AddrPortFrom(ap.Addr().Unmap(), ap.Port())), nil } func discardBytes(r io.Reader, n int) error { diff --git a/transport/sudoku/write_chunks.go b/transport/sudoku/write_chunks.go deleted file mode 100644 index 66927a40c..000000000 --- a/transport/sudoku/write_chunks.go +++ /dev/null @@ -1,12 +0,0 @@ -package sudoku - -import "io" - -func writeAllChunks(w io.Writer, chunks ...[]byte) error { - for _, chunk := range chunks { - if _, err := w.Write(chunk); err != nil { - return err - } - } - return nil -}