From 2cdbbab994a3047c0665b10b4ed760fc3e2cd62b Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:31:06 -0600 Subject: [PATCH 01/10] http: strip hop-by-hop and proxy headers before forwarding The plain-HTTP handler wrote the client's request to the origin as is, so Proxy-Authorization (the proxy password) and Proxy-Connection were forwarded to the origin. Delete Proxy-Authorization, Proxy-Connection and the RFC 7230 hop-by-hop headers, including any header named in Connection, before req.Write. Co-Authored-By: Claude Sonnet 5.5 --- http.go | 33 ++++++++++++++++++++++++ http_test.go | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+) diff --git a/http.go b/http.go index 110bf9ef..97d72c8e 100644 --- a/http.go +++ b/http.go @@ -50,6 +50,37 @@ func (s *HTTPServer) authenticate(req *http.Request) (int, error) { return http.StatusUnauthorized, fmt.Errorf("username and password not matching") } +// hopByHopHeaders are the headers that apply to a single transport-level +// connection (RFC 7230 section 6.1) plus the proxy-specific ones, and must not +// be forwarded to the origin. +var hopByHopHeaders = []string{ + "Connection", + "Proxy-Connection", + "Keep-Alive", + "Proxy-Authenticate", + proxyAuthHeaderKey, + "Te", + "Trailer", + "Transfer-Encoding", + "Upgrade", +} + +// removeHopByHopHeaders deletes the hop-by-hop headers, including any header +// named in a Connection header, so that proxy credentials and connection +// management do not leak to the origin. +func removeHopByHopHeaders(h http.Header) { + for _, v := range h.Values("Connection") { + for _, name := range strings.Split(v, ",") { + if name = strings.TrimSpace(name); name != "" { + h.Del(name) + } + } + } + for _, name := range hopByHopHeaders { + h.Del(name) + } +} + func (s *HTTPServer) handleConn(req *http.Request, conn net.Conn) (peer net.Conn, err error) { addr := req.Host if !strings.Contains(addr, ":") { @@ -83,6 +114,8 @@ func (s *HTTPServer) handle(req *http.Request) (peer net.Conn, err error) { return peer, fmt.Errorf("tun tcp dial failed: %w", err) } + removeHopByHopHeaders(req.Header) + err = req.Write(peer) if err != nil { _ = peer.Close() diff --git a/http_test.go b/http_test.go index 97ccc02d..d44f9daf 100644 --- a/http_test.go +++ b/http_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "testing" + "time" ) func TestHTTPServerServeGet(t *testing.T) { @@ -99,3 +100,73 @@ func TestHTTPServerServeFailureClosesConn(t *testing.T) { t.Fatalf("expected EOF when server closes connection, got %v", err) } } + +// startTestProxy serves server on a loopback listener and returns its address. +func startTestProxy(t *testing.T, server *HTTPServer) string { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = listener.Close() }) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + go server.serve(conn) + } + }() + return listener.Addr().String() +} + +func TestHTTPServerStripsHopByHopHeaders(t *testing.T) { + got := make(chan http.Header, 1) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got <- r.Header.Clone() + _, _ = w.Write([]byte("ok")) + })) + defer ts.Close() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ts.Listener.Addr().String()) + }, + auth: CredentialValidator{"u", "p"}, + authRequired: true, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + + raw := "GET http://" + ts.Listener.Addr().String() + "/ HTTP/1.1\r\n" + + "Host: " + ts.Listener.Addr().String() + "\r\n" + + "Proxy-Authorization: Basic dTpw\r\n" + + "Proxy-Connection: keep-alive\r\n" + + "Connection: keep-alive, X-Secret-Hop\r\n" + + "Keep-Alive: timeout=5\r\n" + + "X-Secret-Hop: 1\r\n" + + "X-Keep-Me: yes\r\n\r\n" + if _, err := clientConn.Write([]byte(raw)); err != nil { + t.Fatal(err) + } + + select { + case h := <-got: + for _, name := range []string{"Proxy-Authorization", "Proxy-Connection", "Keep-Alive", "X-Secret-Hop"} { + if v := h.Get(name); v != "" { + t.Errorf("origin saw %s=%q", name, v) + } + } + if h.Get("X-Keep-Me") != "yes" { + t.Errorf("end-to-end header dropped: %v", h) + } + case <-time.After(5 * time.Second): + t.Fatal("origin did not receive the request") + } +} From b507cdbf71d822f1ab9b57fc059e5f62a3ab6f92 Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:31:42 -0600 Subject: [PATCH 02/10] http: forward bytes the client sent right after CONNECT serve reads the request through a bufio.Reader but copied the client-to-peer direction straight from the connection, so any bytes already buffered in the reader (a client that pipelines its first payload with the CONNECT request) were dropped. Copy from the reader. Co-Authored-By: Claude Sonnet 5.5 --- http.go | 3 ++- http_test.go | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/http.go b/http.go index 97d72c8e..93f9d2fa 100644 --- a/http.go +++ b/http.go @@ -187,7 +187,8 @@ func (s *HTTPServer) serve(conn net.Conn) { defer func() { _ = conn.Close() }() defer func() { _ = peer.Close() }() - _, _ = io.Copy(peer, conn) + // rd may already hold bytes the client sent after the request. + _, _ = io.Copy(peer, rd) }() } diff --git a/http_test.go b/http_test.go index d44f9daf..cf9a3e41 100644 --- a/http_test.go +++ b/http_test.go @@ -170,3 +170,66 @@ func TestHTTPServerStripsHopByHopHeaders(t *testing.T) { t.Fatal("origin did not receive the request") } } + +// startEchoServer accepts connections and echoes everything back. +func startEchoServer(t *testing.T) string { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = listener.Close() }) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + go func() { + defer func() { _ = conn.Close() }() + _, _ = io.Copy(conn, conn) + }() + } + }() + return listener.Addr().String() +} + +func TestHTTPServerConnectForwardsEarlyBytes(t *testing.T) { + echo := startEchoServer(t) + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, echo) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + + // The payload arrives in the same segment as the CONNECT request, so it + // sits in the proxy's bufio.Reader. + if _, err := clientConn.Write([]byte("CONNECT example.test:443 HTTP/1.1\r\nHost: example.test:443\r\n\r\nEARLY")); err != nil { + t.Fatal(err) + } + + rd := bufio.NewReader(clientConn) + status, err := rd.ReadString('\n') + if err != nil || status != "HTTP/1.1 200 Connection established\r\n" { + t.Fatalf("unexpected status %q (err %v)", status, err) + } + if line, err := rd.ReadString('\n'); err != nil || line != "\r\n" { + t.Fatalf("unexpected header terminator %q (err %v)", line, err) + } + + _ = clientConn.SetReadDeadline(time.Now().Add(5 * time.Second)) + buf := make([]byte, len("EARLY")) + if _, err := io.ReadFull(rd, buf); err != nil { + t.Fatalf("early bytes were not forwarded: %v", err) + } + if string(buf) != "EARLY" { + t.Fatalf("unexpected echo %q", buf) + } +} From d086f198dd8af2c3b77733490a99546dded32354 Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:33:52 -0600 Subject: [PATCH 03/10] proxy: honour half-close and reuse copy buffers in all forwarders The HTTP CONNECT tunnel, the TCP client/server tunnels, STDIO and the SNI proxy closed both connections as soon as either direction hit EOF. A client that sends a request and shuts down its write side (SHUT_WR) therefore lost the reply. They also allocated a 32 KiB buffer per direction per connection, because gonet.TCPConn has no ReadFrom/WriteTo. Add proxyCopy, used by all of them: it copies each direction with a pooled buffer (sync.Pool, io.CopyBuffer), calls CloseWrite on the destination after that direction's EOF when the connection supports it, and closes both connections only after both directions have finished (or as soon as a copy fails or CloseWrite is unavailable). The SNI wrapper and the HTTP client side (which reads through a bufio.Reader) gain a CloseWrite that delegates to the real connection. connForward is replaced by proxyCopy; STDIO wraps stdin/stdout as one connection. Co-Authored-By: Claude Sonnet 5.5 --- http.go | 17 +----- http_test.go | 60 ++++++++++++++++++++ proxy.go | 100 +++++++++++++++++++++++++++++++++ proxy_test.go | 150 ++++++++++++++++++++++++++++++++++++++++++++++++++ routine.go | 22 +------- sni.go | 16 ++---- sni_test.go | 83 ++++++++++++++++++++++++++++ 7 files changed, 402 insertions(+), 46 deletions(-) create mode 100644 proxy.go create mode 100644 proxy_test.go create mode 100644 sni_test.go diff --git a/http.go b/http.go index 93f9d2fa..69c0550d 100644 --- a/http.go +++ b/http.go @@ -6,7 +6,6 @@ import ( "crypto/tls" "encoding/base64" "fmt" - "io" "log" "net" "net/http" @@ -176,20 +175,8 @@ func (s *HTTPServer) serve(conn net.Conn) { handled = true - go func() { - defer func() { _ = conn.Close() }() - defer func() { _ = peer.Close() }() - - _, _ = io.Copy(conn, peer) - }() - - go func() { - defer func() { _ = conn.Close() }() - defer func() { _ = peer.Close() }() - - // rd may already hold bytes the client sent after the request. - _, _ = io.Copy(peer, rd) - }() + // rd may already hold bytes the client sent after the request. + proxyCopy(readerConn{Conn: conn, r: rd}, peer) } func (s *HTTPServer) listen(network, addr string) (net.Listener, error) { diff --git a/http_test.go b/http_test.go index cf9a3e41..ef8fa51b 100644 --- a/http_test.go +++ b/http_test.go @@ -233,3 +233,63 @@ func TestHTTPServerConnectForwardsEarlyBytes(t *testing.T) { t.Fatalf("unexpected echo %q", buf) } } + +func TestHTTPServerConnectHalfClose(t *testing.T) { + // The origin replies only after the client has half-closed. + originLn, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = originLn.Close() }() + go func() { + conn, err := originLn.Accept() + if err != nil { + return + } + defer func() { _ = conn.Close() }() + req, _ := io.ReadAll(conn) + _, _ = conn.Write(append([]byte("reply to "), req...)) + }() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, originLn.Addr().String()) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := clientConn.Write([]byte("CONNECT example.test:443 HTTP/1.1\r\nHost: example.test:443\r\n\r\n")); err != nil { + t.Fatal(err) + } + rd := bufio.NewReader(clientConn) + for { + line, err := rd.ReadString('\n') + if err != nil { + t.Fatal(err) + } + if line == "\r\n" { + break + } + } + + if _, err := clientConn.Write([]byte("request")); err != nil { + t.Fatal(err) + } + if err := clientConn.(*net.TCPConn).CloseWrite(); err != nil { + t.Fatal(err) + } + got, err := io.ReadAll(rd) + if err != nil { + t.Fatal(err) + } + if string(got) != "reply to request" { + t.Fatalf("got %q after half-close", got) + } +} diff --git a/proxy.go b/proxy.go new file mode 100644 index 00000000..9422cc39 --- /dev/null +++ b/proxy.go @@ -0,0 +1,100 @@ +package wireproxy + +import ( + "errors" + "io" + "net" + "os" + "sync" +) + +const copyBufferSize = 32 * 1024 + +// copyBufferPool holds the buffers used by proxyCopy, so that each connection +// does not allocate a new buffer per direction. +var copyBufferPool = sync.Pool{ + New: func() any { + b := make([]byte, copyBufferSize) + return &b + }, +} + +// closeWriter is implemented by connections that can shut down only their +// write side (*net.TCPConn, *tls.Conn, gonet.TCPConn). +type closeWriter interface { + CloseWrite() error +} + +// readerOnly and writerOnly hide the WriterTo and ReaderFrom methods of the +// wrapped value so that io.CopyBuffer always uses the supplied buffer. +type readerOnly struct{ io.Reader } +type writerOnly struct{ io.Writer } + +func copyPooled(dst io.Writer, src io.Reader) (int64, error) { + bp := copyBufferPool.Get().(*[]byte) + defer copyBufferPool.Put(bp) + return io.CopyBuffer(writerOnly{dst}, readerOnly{src}, *bp) +} + +// copyHalf copies src to dst. When src reaches EOF it shuts down the write side +// of dst so the other end sees EOF while the reverse direction keeps going. +// If that is not possible, or the copy failed, both connections are closed. +func copyHalf(dst, src io.ReadWriteCloser) { + _, err := copyPooled(dst, src) + if err != nil && !errors.Is(err, net.ErrClosed) { + errorLogger.Printf("Cannot forward traffic: %s\n", err.Error()) + } + if err == nil { + if cw, ok := dst.(closeWriter); ok && cw.CloseWrite() == nil { + return + } + } + _ = dst.Close() + _ = src.Close() +} + +// proxyCopy copies data in both directions between a and b, honouring +// half-close, and closes both once both directions are finished (or one fails). +// It blocks until then. +func proxyCopy(a, b io.ReadWriteCloser) { + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + copyHalf(a, b) + }() + go func() { + defer wg.Done() + copyHalf(b, a) + }() + wg.Wait() + _ = a.Close() + _ = b.Close() +} + +// readerConn reads from r instead of the embedded connection, for a connection +// that was partly consumed through a buffer. Writes and closes go to the +// connection. +type readerConn struct { + net.Conn + r io.Reader +} + +func (c readerConn) Read(p []byte) (int, error) { return c.r.Read(p) } + +func (c readerConn) CloseWrite() error { + if cw, ok := c.Conn.(closeWriter); ok { + return cw.CloseWrite() + } + return errors.ErrUnsupported +} + +// stdioConn presents a stdin/stdout pair as a single connection. +type stdioConn struct { + in *os.File + out *os.File +} + +func (c stdioConn) Read(p []byte) (int, error) { return c.in.Read(p) } +func (c stdioConn) Write(p []byte) (int, error) { return c.out.Write(p) } +func (c stdioConn) Close() error { return errors.Join(c.in.Close(), c.out.Close()) } diff --git a/proxy_test.go b/proxy_test.go new file mode 100644 index 00000000..02614e7a --- /dev/null +++ b/proxy_test.go @@ -0,0 +1,150 @@ +package wireproxy + +import ( + "bytes" + "io" + "net" + "testing" + "time" +) + +// tcpPair returns the two ends of a loopback TCP connection. +func tcpPair(t *testing.T) (*net.TCPConn, *net.TCPConn) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = listener.Close() }() + + accepted := make(chan *net.TCPConn, 1) + go func() { + conn, err := listener.Accept() + if err != nil { + accepted <- nil + return + } + accepted <- conn.(*net.TCPConn) + }() + + client, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + server := <-accepted + if server == nil { + t.Fatal("accept failed") + } + t.Cleanup(func() { + _ = client.Close() + _ = server.Close() + }) + return client.(*net.TCPConn), server +} + +func TestProxyCopyHalfClose(t *testing.T) { + client, proxyA := tcpPair(t) + proxyB, origin := tcpPair(t) + + done := make(chan struct{}) + go func() { + proxyCopy(proxyA, proxyB) + close(done) + }() + + // The origin only answers after it has seen the end of the request. + go func() { + req, _ := io.ReadAll(origin) + _, _ = origin.Write(append([]byte("reply to "), req...)) + _ = origin.Close() + }() + + _ = client.SetDeadline(time.Now().Add(5 * time.Second)) + if _, err := client.Write([]byte("request")); err != nil { + t.Fatal(err) + } + if err := client.CloseWrite(); err != nil { + t.Fatal(err) + } + got, err := io.ReadAll(client) + if err != nil { + t.Fatal(err) + } + if string(got) != "reply to request" { + t.Fatalf("got %q after half-close", got) + } + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("proxyCopy did not return after both directions finished") + } +} + +func TestProxyCopyLargeBidirectional(t *testing.T) { + client, proxyA := tcpPair(t) + proxyB, origin := tcpPair(t) + + go proxyCopy(proxyA, proxyB) + + payload := bytes.Repeat([]byte("0123456789abcdef"), 1<<16) // 1 MiB + _ = client.SetDeadline(time.Now().Add(10 * time.Second)) + _ = origin.SetDeadline(time.Now().Add(10 * time.Second)) + + send := func(c *net.TCPConn) { + _, _ = c.Write(payload) + _ = c.CloseWrite() + } + go send(client) + go send(origin) + + for name, c := range map[string]*net.TCPConn{"client": client, "origin": origin} { + got, err := io.ReadAll(c) + if err != nil { + t.Fatalf("%s read: %v", name, err) + } + if !bytes.Equal(got, payload) { + t.Fatalf("%s received %d bytes, want %d", name, len(got), len(payload)) + } + } +} + +// A connection without CloseWrite cannot signal EOF, so both sides are closed. +func TestProxyCopyClosesBothWithoutCloseWrite(t *testing.T) { + pipeClient, pipeProxy := net.Pipe() + proxyB, origin := tcpPair(t) + + done := make(chan struct{}) + go func() { + proxyCopy(pipeProxy, proxyB) + close(done) + }() + + _ = origin.Close() + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("proxyCopy did not return") + } + _ = pipeClient.SetReadDeadline(time.Now().Add(5 * time.Second)) + if _, err := pipeClient.Read(make([]byte, 1)); err != io.EOF { + t.Fatalf("expected EOF on the other side, got %v", err) + } +} + +type failingWriterTo struct{ io.Reader } + +func (failingWriterTo) WriteTo(io.Writer) (int64, error) { panic("WriteTo used") } + +type failingReaderFrom struct{ bytes.Buffer } + +func (*failingReaderFrom) ReadFrom(io.Reader) (int64, error) { panic("ReadFrom used") } + +func TestCopyPooledUsesBuffer(t *testing.T) { + var dst failingReaderFrom + n, err := copyPooled(&dst, failingWriterTo{bytes.NewReader([]byte("data"))}) + if err != nil || n != 4 || dst.String() != "data" { + t.Fatalf("copyPooled = %d, %v, %q", n, err, dst.String()) + } +} diff --git a/routine.go b/routine.go index 731d0175..d158c159 100644 --- a/routine.go +++ b/routine.go @@ -8,7 +8,6 @@ import ( "encoding/binary" "encoding/json" "errors" - "io" "log" "math/rand" "net" @@ -262,17 +261,6 @@ func (c CredentialValidator) Valid(username, password string) bool { return u&p == 1 } -// connForward copy data from `from` to `to` -func connForward(from io.ReadWriteCloser, to io.ReadWriteCloser) { - defer func() { _ = from.Close() }() - defer func() { _ = to.Close() }() - - _, err := io.Copy(to, from) - if err != nil && !errors.Is(err, net.ErrClosed) { - errorLogger.Printf("Cannot forward traffic: %s\n", err.Error()) - } -} - // tcpClientForward starts a new connection via wireguard and forward traffic from `conn` func tcpClientForward(vt *VirtualTun, raddr *addressPort, conn net.Conn) { target, err := vt.resolveToAddrPort(raddr) @@ -291,8 +279,7 @@ func tcpClientForward(vt *VirtualTun, raddr *addressPort, conn net.Conn) { return } - go connForward(sconn, conn) - go connForward(conn, sconn) + proxyCopy(sconn, conn) } // STDIOTcpForward starts a new connection via wireguard and forward traffic from `conn` @@ -310,8 +297,7 @@ func STDIOTcpForward(vt *VirtualTun, raddr *addressPort, input *os.File, output return } - go connForward(input, sconn) - go connForward(sconn, output) + proxyCopy(sconn, stdioConn{in: input, out: output}) } // SpawnRoutine spawns a local TCP server which acts as a proxy to the specified target @@ -363,9 +349,7 @@ func tcpServerForward(vt *VirtualTun, raddr *addressPort, conn net.Conn) { return } - go connForward(sconn, conn) - go connForward(conn, sconn) - + proxyCopy(sconn, conn) } // SpawnRoutine spawns a TCP server on wireguard which acts as a proxy to the specified target diff --git a/sni.go b/sni.go index ea2ac197..5bf85322 100644 --- a/sni.go +++ b/sni.go @@ -38,15 +38,7 @@ func peekClientHello(conn net.Conn) (string, io.ReadWriteCloser, error) { }, }).Handshake() - wrappedConn := struct { - io.Reader - io.Writer - io.Closer - }{ - Reader: io.MultiReader(peekedBytes, conn), - Writer: conn, - Closer: conn, - } + wrappedConn := readerConn{Conn: conn, r: io.MultiReader(peekedBytes, conn)} var serverName string if hello != nil { @@ -57,7 +49,8 @@ func peekClientHello(conn net.Conn) (string, io.ReadWriteCloser, error) { return serverName, wrappedConn, err } -// Get SNI hostname, dial out through tunnel, then proxy data +// Get SNI hostname, dial out through tunnel, then proxy data until both +// directions are done func sniProxyForward(dial func(string, string) (net.Conn, error), conn net.Conn) error { if err := conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { return fmt.Errorf("set read deadline failed: %w", err) @@ -82,8 +75,7 @@ func sniProxyForward(dial func(string, string) (net.Conn, error), conn net.Conn) return fmt.Errorf("tun tcp dial failed: %w", err) } - go connForward(clientConn, backendConn) - go connForward(backendConn, clientConn) + proxyCopy(clientConn, backendConn) return nil } diff --git a/sni_test.go b/sni_test.go new file mode 100644 index 00000000..d9f1ef09 --- /dev/null +++ b/sni_test.go @@ -0,0 +1,83 @@ +package wireproxy + +import ( + "crypto/tls" + "errors" + "io" + "net" + "testing" + "time" +) + +// captureConn records what a TLS client writes and then fails the handshake. +type captureConn struct { + net.Conn + written []byte +} + +func (c *captureConn) Write(p []byte) (int, error) { + c.written = append(c.written, p...) + return len(p), nil +} +func (c *captureConn) Read([]byte) (int, error) { return 0, errors.New("capture only") } + +func clientHelloFor(t *testing.T, serverName string) []byte { + t.Helper() + cc := &captureConn{} + _ = tls.Client(cc, &tls.Config{ServerName: serverName}).Handshake() + if len(cc.written) == 0 { + t.Fatal("no ClientHello captured") + } + return cc.written +} + +func TestSNIProxyHalfClose(t *testing.T) { + hello := clientHelloFor(t, "example.test") + + client, proxyConn := tcpPair(t) + proxyBackend, backend := tcpPair(t) + + var dialed string + dial := func(network, address string) (net.Conn, error) { + dialed = address + return proxyBackend, nil + } + + done := make(chan error, 1) + go func() { done <- sniProxyForward(dial, proxyConn) }() + + // The backend answers only once the client has finished sending. + go func() { + req, _ := io.ReadAll(backend) + _, _ = backend.Write([]byte("got ")) + _, _ = backend.Write([]byte{byte(len(req) % 256)}) + _ = backend.Close() + }() + + _ = client.SetDeadline(time.Now().Add(5 * time.Second)) + if _, err := client.Write(hello); err != nil { + t.Fatal(err) + } + if err := client.CloseWrite(); err != nil { + t.Fatal(err) + } + reply, err := io.ReadAll(client) + if err != nil { + t.Fatal(err) + } + if want := append([]byte("got "), byte(len(hello)%256)); string(reply) != string(want) { + t.Fatalf("reply %q, want %q", reply, want) + } + + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("sniProxyForward did not return") + } + if dialed != "example.test:443" { + t.Fatalf("dialed %q", dialed) + } +} From 3117a350e16d92a7f8da865dedffd99c0feb23c3 Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:34:20 -0600 Subject: [PATCH 04/10] http: time out clients that do not send a request An idle or slow client could hold a goroutine and file descriptor forever, because nothing bounded http.ReadRequest. Set a 30 second read deadline before reading the request and clear it afterwards, before the connection is tunnelled (as the SNI proxy does for the ClientHello). Co-Authored-By: Claude Sonnet 5.5 --- http.go | 13 ++++++++++ http_test.go | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) diff --git a/http.go b/http.go index 69c0550d..41572fdb 100644 --- a/http.go +++ b/http.go @@ -10,10 +10,15 @@ import ( "net" "net/http" "strings" + "time" ) const proxyAuthHeaderKey = "Proxy-Authorization" +// httpReadRequestTimeout bounds how long a client may take to send its request +// line and headers. +var httpReadRequestTimeout = 30 * time.Second + type HTTPServer struct { config *HTTPConfig @@ -132,12 +137,20 @@ func (s *HTTPServer) serve(conn net.Conn) { _ = conn.Close() } }() + if err := conn.SetReadDeadline(time.Now().Add(httpReadRequestTimeout)); err != nil { + log.Printf("set read deadline failed: %s\n", err) + return + } var rd = bufio.NewReader(conn) req, err := http.ReadRequest(rd) if err != nil { log.Printf("read request failed: %s\n", err) return } + if err := conn.SetReadDeadline(time.Time{}); err != nil { + log.Printf("clear read deadline failed: %s\n", err) + return + } code, err := s.authenticate(req) if err != nil { diff --git a/http_test.go b/http_test.go index ef8fa51b..efb44833 100644 --- a/http_test.go +++ b/http_test.go @@ -293,3 +293,73 @@ func TestHTTPServerConnectHalfClose(t *testing.T) { t.Fatalf("got %q after half-close", got) } } + +func setReadRequestTimeout(t *testing.T, d time.Duration) { + t.Helper() + old := httpReadRequestTimeout + httpReadRequestTimeout = d + t.Cleanup(func() { httpReadRequestTimeout = old }) +} + +func TestHTTPServerReadRequestTimeout(t *testing.T) { + setReadRequestTimeout(t, 100*time.Millisecond) + addr := startTestProxy(t, &HTTPServer{}) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + + // An incomplete request line, then silence. + if _, err := clientConn.Write([]byte("GET http://example.test/ HT")); err != nil { + t.Fatal(err) + } + + _ = clientConn.SetReadDeadline(time.Now().Add(5 * time.Second)) + if _, err := clientConn.Read(make([]byte, 1)); err != io.EOF { + t.Fatalf("expected the proxy to close the idle connection, got %v", err) + } +} + +func TestHTTPServerReadDeadlineClearedForTunnel(t *testing.T) { + setReadRequestTimeout(t, 100*time.Millisecond) + echo := startEchoServer(t) + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, echo) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := clientConn.Write([]byte("CONNECT example.test:443 HTTP/1.1\r\nHost: example.test:443\r\n\r\n")); err != nil { + t.Fatal(err) + } + rd := bufio.NewReader(clientConn) + for { + line, err := rd.ReadString('\n') + if err != nil { + t.Fatal(err) + } + if line == "\r\n" { + break + } + } + + // Stay idle for longer than the request timeout, then use the tunnel. + time.Sleep(300 * time.Millisecond) + if _, err := clientConn.Write([]byte("ping")); err != nil { + t.Fatal(err) + } + buf := make([]byte, 4) + if _, err := io.ReadFull(rd, buf); err != nil || string(buf) != "ping" { + t.Fatalf("tunnel closed by the request read deadline: %q, %v", buf, err) + } +} From b0497df05845bdb0a9e5de9c4f7fff3ac1e3821e Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:34:44 -0600 Subject: [PATCH 05/10] routine: add a connect timeout to RoutedDial The HTTP and SNI proxies dialled with no deadline (Tnet.Dial / net.Dial), so a dead tunnel or target made the client wait for netstack's SYN retries, about two minutes. Dial with a 30 second context on both the tunnel path (Tnet.DialContext) and the direct path (net.Dialer.DialContext). Co-Authored-By: Claude Sonnet 5.5 --- routine.go | 18 ++++++++++++++++-- routine_test.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 routine_test.go diff --git a/routine.go b/routine.go index d158c159..3f4b0b0a 100644 --- a/routine.go +++ b/routine.go @@ -169,11 +169,25 @@ func (passthroughResolver) Resolve(ctx context.Context, name string) (context.Co // and dials everything else directly. Used by the HTTP and SNI proxies, whose // dial callbacks receive the destination hostname intact. func (d VirtualTun) RoutedDial(router *DomainRouter) func(network, address string) (net.Conn, error) { + var direct net.Dialer + return routedDial(router, routedDialTimeout, d.Tnet.DialContext, direct.DialContext) +} + +// routedDialTimeout bounds a dial made by RoutedDial. Without it a dead tunnel +// or target makes the caller wait for the TCP SYN retries (about two minutes in +// netstack). +const routedDialTimeout = 30 * time.Second + +type dialContextFunc func(ctx context.Context, network, address string) (net.Conn, error) + +func routedDial(router *DomainRouter, timeout time.Duration, tunnel, direct dialContextFunc) func(network, address string) (net.Conn, error) { return func(network, address string) (net.Conn, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() if router.route(hostFromAddr(address)) { - return d.Tnet.Dial(network, address) + return tunnel(ctx, network, address) } - return net.Dial(network, address) + return direct(ctx, network, address) } } diff --git a/routine_test.go b/routine_test.go new file mode 100644 index 00000000..31c4db5e --- /dev/null +++ b/routine_test.go @@ -0,0 +1,41 @@ +package wireproxy + +import ( + "context" + "net" + "regexp" + "testing" + "time" +) + +func TestRoutedDialTimesOut(t *testing.T) { + router := NewDomainRouter([]*regexp.Regexp{regexp.MustCompile(`^tunnel\.test$`)}, false) + + // A dial that only returns when its context ends, like an unreachable host. + var tunnelCalls, directCalls int + blocking := func(calls *int) dialContextFunc { + return func(ctx context.Context, network, address string) (net.Conn, error) { + *calls++ + if _, ok := ctx.Deadline(); !ok { + t.Error("dial context has no deadline") + } + <-ctx.Done() + return nil, ctx.Err() + } + } + dial := routedDial(router, 50*time.Millisecond, blocking(&tunnelCalls), blocking(&directCalls)) + + for _, address := range []string{"tunnel.test:443", "direct.test:443"} { + start := time.Now() + _, err := dial("tcp", address) + if err == nil { + t.Fatalf("%s: expected an error", address) + } + if elapsed := time.Since(start); elapsed > 5*time.Second { + t.Fatalf("%s: dial took %s", address, elapsed) + } + } + if tunnelCalls != 1 || directCalls != 1 { + t.Fatalf("tunnel dialled %d times, direct %d times; want 1 each", tunnelCalls, directCalls) + } +} From 122f65a745ab88064822370770b6f4e97e984dbd Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:35:58 -0600 Subject: [PATCH 06/10] http: proxy plain requests of any method, one origin connection each Only GET was accepted for plain-HTTP requests (everything else got 405), and after the first request the client connection was piped raw to the origin it named, so a keep-alive follow-up for a different host went to the wrong server. Route every non-CONNECT method through the plain-HTTP handler, send Connection: close to the origin, and relay only that one response before closing both ends. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- http.go | 21 +++++++---- http_test.go | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 113 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index cd6f0718..60212715 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ of wireproxy by [@artem-russkikh](https://github.com/artem-russkikh). # Feature - TCP static routing for client and server -- SOCKS5/HTTP proxy (currently only CONNECT is supported) +- SOCKS5/HTTP proxy (SOCKS5 supports CONNECT only; the HTTP proxy supports CONNECT and plain HTTP requests of any method, each on its own connection to the origin) - Transparent TLS ([SNI](https://en.wikipedia.org/wiki/Server_Name_Indication)) proxy # TODO diff --git a/http.go b/http.go index 41572fdb..9389297a 100644 --- a/http.go +++ b/http.go @@ -119,6 +119,9 @@ func (s *HTTPServer) handle(req *http.Request) (peer net.Conn, err error) { } removeHopByHopHeaders(req.Header) + // One origin connection per request: ask the origin to close after the + // response. + req.Close = true err = req.Write(peer) if err != nil { @@ -164,15 +167,10 @@ func (s *HTTPServer) serve(conn net.Conn) { } var peer net.Conn - switch req.Method { - case http.MethodConnect: + if req.Method == http.MethodConnect { peer, err = s.handleConn(req, conn) - case http.MethodGet: + } else { peer, err = s.handle(req) - default: - _ = responseWith(req, http.StatusMethodNotAllowed).Write(conn) - log.Printf("unsupported protocol: %s\n", req.Method) - return } if err != nil { if peer != nil { @@ -186,6 +184,15 @@ func (s *HTTPServer) serve(conn net.Conn) { return } + if req.Method != http.MethodConnect { + // The origin connection was dialled for this request's host only, so + // relay just its response and close both ends: a follow-up request on + // the client's keep-alive connection must not reach this origin. + defer func() { _ = peer.Close() }() + _, _ = copyPooled(conn, peer) + return + } + handled = true // rd may already hold bytes the client sent after the request. diff --git a/http_test.go b/http_test.go index efb44833..2399b959 100644 --- a/http_test.go +++ b/http_test.go @@ -6,6 +6,8 @@ import ( "net" "net/http" "net/http/httptest" + "strings" + "sync/atomic" "testing" "time" ) @@ -363,3 +365,99 @@ func TestHTTPServerReadDeadlineClearedForTunnel(t *testing.T) { t.Fatalf("tunnel closed by the request read deadline: %q, %v", buf, err) } } + +func TestHTTPServerForwardsNonGetMethods(t *testing.T) { + type seen struct { + method, body string + close bool + } + got := make(chan seen, 1) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + got <- seen{r.Method, string(body), r.Close} + _, _ = w.Write([]byte("done")) + })) + defer ts.Close() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ts.Listener.Addr().String()) + }, + } + addr := startTestProxy(t, server) + + for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodHead} { + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + req, err := http.NewRequest(method, "http://"+ts.Listener.Addr().String()+"/x", strings.NewReader("payload")) + if err != nil { + t.Fatal(err) + } + if err := req.Write(clientConn); err != nil { + t.Fatal(err) + } + resp, err := http.ReadResponse(bufio.NewReader(clientConn), req) + if err != nil { + t.Fatalf("%s: %v", method, err) + } + if resp.StatusCode != http.StatusOK { + t.Fatalf("%s: status %d", method, resp.StatusCode) + } + _ = resp.Body.Close() + _ = clientConn.Close() + + select { + case s := <-got: + if s.method != method || s.body != "payload" || !s.close { + t.Fatalf("%s: origin saw %+v", method, s) + } + case <-time.After(5 * time.Second): + t.Fatalf("%s: origin did not receive the request", method) + } + } +} + +// A keep-alive follow-up for another host must not be piped to the first origin. +func TestHTTPServerPlainRequestUsesOneOriginConnection(t *testing.T) { + var requests atomic.Int32 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + _, _ = w.Write([]byte("first")) + })) + defer ts.Close() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ts.Listener.Addr().String()) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + two := "GET http://a.test/ HTTP/1.1\r\nHost: a.test\r\n\r\n" + + "GET http://b.test/ HTTP/1.1\r\nHost: b.test\r\n\r\n" + if _, err := clientConn.Write([]byte(two)); err != nil { + t.Fatal(err) + } + + all, err := io.ReadAll(clientConn) + if err != nil { + t.Fatalf("expected the proxy to close the client connection after the response: %v", err) + } + if n := strings.Count(string(all), "HTTP/1.1 200"); n != 1 { + t.Fatalf("got %d responses, want 1: %q", n, all) + } + if n := requests.Load(); n != 1 { + t.Fatalf("origin saw %d requests, want 1", n) + } +} From 08e2ac77ca3468709a55477e80691ebccba9dcf5 Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:42:08 -0600 Subject: [PATCH 07/10] proxy: bound a half-closed copy and stop logging our own close After one direction of proxyCopy reached EOF and was half-closed, the other direction could stay open forever, a file descriptor and goroutine leak the previous close-on-first-EOF behaviour did not have. Close both connections when the remaining direction has read no data for proxyIdleTimeout (2 minutes, restarted on every read that returns data). Errors the other direction reports because proxyCopy itself closed the connections (gonet returns opaque errors, not net.ErrClosed, after a local Close) are no longer logged as "Cannot forward traffic". Co-Authored-By: Claude Sonnet 5.5 --- proxy.go | 70 ++++++++++++++++++++++---- proxy_test.go | 135 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 194 insertions(+), 11 deletions(-) diff --git a/proxy.go b/proxy.go index 9422cc39..14d1a2ab 100644 --- a/proxy.go +++ b/proxy.go @@ -6,6 +6,8 @@ import ( "net" "os" "sync" + "sync/atomic" + "time" ) const copyBufferSize = 32 * 1024 @@ -36,38 +38,84 @@ func copyPooled(dst io.Writer, src io.Reader) (int64, error) { return io.CopyBuffer(writerOnly{dst}, readerOnly{src}, *bp) } +// proxyIdleTimeout bounds how long a half-closed proxyCopy, or a plain-HTTP +// response relay, waits for more data from the other side. +var proxyIdleTimeout = 2 * time.Minute + +// activityReader calls onRead after every read that returned data. +type activityReader struct { + io.Reader + onRead func() +} + +func (r activityReader) Read(p []byte) (int, error) { + n, err := r.Reader.Read(p) + if n > 0 { + r.onRead() + } + return n, err +} + +type proxyState struct { + a, b io.ReadWriteCloser + idle *time.Timer + d time.Duration + // closing is set before we close the connections ourselves, so errors that + // our own Close causes in the other direction are not logged. + closing atomic.Bool + halfClosed atomic.Bool +} + +func (s *proxyState) closeBoth() { + s.closing.Store(true) + _ = s.a.Close() + _ = s.b.Close() +} + // copyHalf copies src to dst. When src reaches EOF it shuts down the write side -// of dst so the other end sees EOF while the reverse direction keeps going. -// If that is not possible, or the copy failed, both connections are closed. -func copyHalf(dst, src io.ReadWriteCloser) { - _, err := copyPooled(dst, src) - if err != nil && !errors.Is(err, net.ErrClosed) { +// of dst so the other end sees EOF while the reverse direction keeps going, +// bounded by the idle timeout. If that is not possible, or the copy failed, +// both connections are closed. +func (s *proxyState) copyHalf(dst, src io.ReadWriteCloser) { + _, err := copyPooled(dst, activityReader{src, func() { + if s.halfClosed.Load() { + s.idle.Reset(s.d) + } + }}) + if err != nil && !s.closing.Load() && !errors.Is(err, net.ErrClosed) { errorLogger.Printf("Cannot forward traffic: %s\n", err.Error()) } if err == nil { if cw, ok := dst.(closeWriter); ok && cw.CloseWrite() == nil { + s.halfClosed.Store(true) + s.idle.Reset(s.d) return } } - _ = dst.Close() - _ = src.Close() + s.closeBoth() } // proxyCopy copies data in both directions between a and b, honouring -// half-close, and closes both once both directions are finished (or one fails). -// It blocks until then. +// half-close, and closes both once both directions are finished (or one fails, +// or the remaining direction is idle for proxyIdleTimeout after the other +// finished). It blocks until then. func proxyCopy(a, b io.ReadWriteCloser) { + s := &proxyState{a: a, b: b, d: proxyIdleTimeout} + s.idle = time.AfterFunc(s.d, s.closeBoth) + s.idle.Stop() + var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() - copyHalf(a, b) + s.copyHalf(a, b) }() go func() { defer wg.Done() - copyHalf(b, a) + s.copyHalf(b, a) }() wg.Wait() + s.idle.Stop() _ = a.Close() _ = b.Close() } diff --git a/proxy_test.go b/proxy_test.go index 02614e7a..f5785932 100644 --- a/proxy_test.go +++ b/proxy_test.go @@ -2,8 +2,11 @@ package wireproxy import ( "bytes" + "errors" "io" + "log" "net" + "strings" "testing" "time" ) @@ -148,3 +151,135 @@ func TestCopyPooledUsesBuffer(t *testing.T) { t.Fatalf("copyPooled = %d, %v, %q", n, err, dst.String()) } } + +func setProxyIdleTimeout(t *testing.T, d time.Duration) { + t.Helper() + old := proxyIdleTimeout + proxyIdleTimeout = d + t.Cleanup(func() { proxyIdleTimeout = old }) +} + +// After one side half-closes, a silent other side must not linger forever. +func TestProxyCopyIdleAfterHalfClose(t *testing.T) { + setProxyIdleTimeout(t, 100*time.Millisecond) + client, proxyA := tcpPair(t) + proxyB, origin := tcpPair(t) + + done := make(chan struct{}) + go func() { + proxyCopy(proxyA, proxyB) + close(done) + }() + + if err := client.CloseWrite(); err != nil { + t.Fatal(err) + } + // The origin sees EOF but never replies or closes. + _ = origin.SetReadDeadline(time.Now().Add(5 * time.Second)) + if _, err := origin.Read(make([]byte, 1)); err != io.EOF { + t.Fatalf("origin read: %v", err) + } + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("proxyCopy did not give up on the idle half-closed connection") + } +} + +// The idle timeout is not an absolute deadline: it restarts on every read. +func TestProxyCopyIdleTimeoutResetsOnActivity(t *testing.T) { + setProxyIdleTimeout(t, 200*time.Millisecond) + client, proxyA := tcpPair(t) + proxyB, origin := tcpPair(t) + + go proxyCopy(proxyA, proxyB) + + go func() { + for i := 0; i < 6; i++ { + time.Sleep(80 * time.Millisecond) + _, _ = origin.Write([]byte("x")) + } + _ = origin.Close() + }() + + _ = client.SetDeadline(time.Now().Add(5 * time.Second)) + if err := client.CloseWrite(); err != nil { + t.Fatal(err) + } + got, err := io.ReadAll(client) + if err != nil || string(got) != "xxxxxx" { + t.Fatalf("got %q, %v", got, err) + } +} + +// opaqueErrConn blocks in Read until it is closed, then fails with an error +// that is not net.ErrClosed (like gonet after a local Close). +type opaqueErrConn struct { + closed chan struct{} + err error +} + +func (c *opaqueErrConn) Read([]byte) (int, error) { + <-c.closed + return 0, c.err +} +func (c *opaqueErrConn) Write(p []byte) (int, error) { return len(p), nil } +func (c *opaqueErrConn) Close() error { + select { + case <-c.closed: + default: + close(c.closed) + } + return nil +} + +func captureErrorLog(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + old := errorLogger + errorLogger = log.New(&buf, "", 0) + t.Cleanup(func() { errorLogger = old }) + return &buf +} + +func TestProxyCopyDoesNotLogOwnClose(t *testing.T) { + buf := captureErrorLog(t) + client, proxyA := tcpPair(t) + fake := &opaqueErrConn{closed: make(chan struct{}), err: errors.New("endpoint is closed for receive")} + + done := make(chan struct{}) + go func() { + proxyCopy(proxyA, fake) + close(done) + }() + + // EOF from the client: fake has no CloseWrite, so both sides get closed, + // which makes fake's Read fail with an opaque error. + _ = client.Close() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("proxyCopy did not return") + } + if buf.Len() != 0 { + t.Fatalf("logged an error caused by our own close: %q", buf.String()) + } +} + +func TestProxyCopyLogsRealError(t *testing.T) { + buf := captureErrorLog(t) + _, proxyA := tcpPair(t) + fake := &failingReadConn{err: errors.New("boom")} + + proxyCopy(proxyA, fake) + if !strings.Contains(buf.String(), "boom") { + t.Fatalf("real error not logged: %q", buf.String()) + } +} + +type failingReadConn struct{ err error } + +func (c *failingReadConn) Read([]byte) (int, error) { return 0, c.err } +func (c *failingReadConn) Write(p []byte) (int, error) { return len(p), nil } +func (c *failingReadConn) Close() error { return nil } From fabb533645e7c2b764b06e0d9f30aba010ddf626 Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:43:57 -0600 Subject: [PATCH 08/10] http: parse plain-HTTP responses; keep upgrades and 100-continue working The plain-HTTP handler wrote the request and then blindly piped the origin's bytes back, which had three problems: - A WebSocket (Connection: upgrade + Upgrade) request lost its upgrade headers to the hop-by-hop stripping. Keep those two headers when the client asked for an upgrade and, if the origin answers 101, tunnel the connection with proxyCopy (including bytes sent right after the 101). - "Expect: 100-continue" stalled: the request was written in full before anything was read, but the client sends the body only after the 100. Write the request concurrently with relaying the response and forward interim 1xx responses. - An origin that ignored "Connection: close" kept the client waiting after a complete response. Read the response with http.ReadResponse, so the relay ends at the response's framing, and cut the origin off if it sends or receives nothing for proxyIdleTimeout. A chunked request body is covered by a test. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- http.go | 139 ++++++++++++++++++++++++------ http_test.go | 236 +++++++++++++++++++++++++++++++++++++++++++++++++++ proxy.go | 22 +++++ 4 files changed, 371 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 60212715..6058cf1c 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ of wireproxy by [@artem-russkikh](https://github.com/artem-russkikh). # Feature - TCP static routing for client and server -- SOCKS5/HTTP proxy (SOCKS5 supports CONNECT only; the HTTP proxy supports CONNECT and plain HTTP requests of any method, each on its own connection to the origin) +- SOCKS5/HTTP proxy (SOCKS5 supports CONNECT only; the HTTP proxy supports CONNECT and plain HTTP requests of any method, each on its own connection to the origin, and tunnels protocol upgrades such as WebSocket) - Transparent TLS ([SNI](https://en.wikipedia.org/wiki/Server_Name_Indication)) proxy # TODO diff --git a/http.go b/http.go index 9389297a..d339ebba 100644 --- a/http.go +++ b/http.go @@ -6,6 +6,7 @@ import ( "crypto/tls" "encoding/base64" "fmt" + "io" "log" "net" "net/http" @@ -106,31 +107,122 @@ func (s *HTTPServer) handleConn(req *http.Request, conn net.Conn) (peer net.Conn return } -func (s *HTTPServer) handle(req *http.Request) (peer net.Conn, err error) { +// isUpgrade returns the requested protocol if the client asked for a protocol +// upgrade (e.g. WebSocket) with both Connection: upgrade and an Upgrade header. +func isUpgrade(h http.Header) string { + for _, v := range h.Values("Connection") { + for _, token := range strings.Split(v, ",") { + if strings.EqualFold(strings.TrimSpace(token), "upgrade") { + return h.Get("Upgrade") + } + } + } + return "" +} + +// writeInterim writes a 1xx response (100 Continue, 101 Switching Protocols) +// to the client. +func writeInterim(w io.Writer, resp *http.Response) error { + if _, err := fmt.Fprintf(w, "HTTP/1.1 %s\r\n", resp.Status); err != nil { + return err + } + if err := resp.Header.Write(w); err != nil { + return err + } + _, err := io.WriteString(w, "\r\n") + return err +} + +// handle forwards one plain-HTTP request to the origin on its own connection +// and relays the response. rd holds any bytes of the client connection that +// were read ahead of the request. +func (s *HTTPServer) handle(req *http.Request, conn net.Conn, rd io.Reader) error { addr := req.Host if !strings.Contains(addr, ":") { port := "80" addr = net.JoinHostPort(addr, port) } - peer, err = s.dial("tcp", addr) + peer, err := s.dial("tcp", addr) if err != nil { - return peer, fmt.Errorf("tun tcp dial failed: %w", err) + return fmt.Errorf("tun tcp dial failed: %w", err) } + defer func() { _ = peer.Close() }() + upgrade := isUpgrade(req.Header) removeHopByHopHeaders(req.Header) - // One origin connection per request: ask the origin to close after the - // response. - req.Close = true - - err = req.Write(peer) - if err != nil { - _ = peer.Close() - peer = nil - return peer, fmt.Errorf("conn write failed: %w", err) + if upgrade != "" { + // Keep the upgrade handshake (e.g. WebSocket) so it can be tunnelled. + req.Header.Set("Connection", "Upgrade") + req.Header.Set("Upgrade", upgrade) + } else { + // One origin connection per request: ask the origin to close after + // the response. + req.Close = true } - return + // An origin that goes silent must not hold the connection forever. + d := proxyIdleTimeout + idle := time.AfterFunc(d, func() { _ = peer.Close() }) + defer idle.Stop() + oc := idleConn{Conn: peer, reset: func() { idle.Reset(d) }} + + // Write the request while relaying the response, so that an interim + // response (100 Continue) reaches a client that is waiting for it before it + // sends the body. + written := make(chan error, 1) + go func() { + err := req.Write(oc) + if err != nil { + _ = peer.Close() + } + written <- err + }() + + br := bufio.NewReader(oc) + for { + resp, err := http.ReadResponse(br, req) + if err != nil { + // Do not wait for the writer: it may be blocked reading a + // request body the client has not sent. serve closes the client + // connection, which unblocks it. + select { + case werr := <-written: + if werr != nil { + return fmt.Errorf("conn write failed: %w", werr) + } + default: + } + return fmt.Errorf("read response failed: %w", err) + } + + if resp.StatusCode == http.StatusSwitchingProtocols && upgrade != "" { + if err := writeInterim(conn, resp); err != nil { + return err + } + if err := <-written; err != nil { + return fmt.Errorf("conn write failed: %w", err) + } + idle.Stop() + // Tunnel from here on. The origin's reads are no longer + // idle-tracked, and br may hold bytes sent right after the 101. + buffered, _ := br.Peek(br.Buffered()) + ahead := append([]byte(nil), buffered...) + proxyCopy(readerConn{Conn: conn, r: rd}, readerConn{Conn: peer, r: io.MultiReader(bytes.NewReader(ahead), peer)}) + return nil + } + if resp.StatusCode >= 100 && resp.StatusCode < 200 && resp.StatusCode != http.StatusSwitchingProtocols { + if err := writeInterim(conn, resp); err != nil { + return err + } + continue + } + + resp.Close = true + err = resp.Write(conn) + _ = resp.Body.Close() + return err + } } func (s *HTTPServer) serve(conn net.Conn) { @@ -166,12 +258,14 @@ func (s *HTTPServer) serve(conn net.Conn) { return } - var peer net.Conn - if req.Method == http.MethodConnect { - peer, err = s.handleConn(req, conn) - } else { - peer, err = s.handle(req) + if req.Method != http.MethodConnect { + if err := s.handle(req, conn, rd); err != nil { + log.Printf("proxy request failed: %s\n", err) + } + return } + + peer, err := s.handleConn(req, conn) if err != nil { if peer != nil { _ = peer.Close() @@ -184,15 +278,6 @@ func (s *HTTPServer) serve(conn net.Conn) { return } - if req.Method != http.MethodConnect { - // The origin connection was dialled for this request's host only, so - // relay just its response and close both ends: a follow-up request on - // the client's keep-alive connection must not reach this origin. - defer func() { _ = peer.Close() }() - _, _ = copyPooled(conn, peer) - return - } - handled = true // rd may already hold bytes the client sent after the request. diff --git a/http_test.go b/http_test.go index 2399b959..523a5f5e 100644 --- a/http_test.go +++ b/http_test.go @@ -2,6 +2,7 @@ package wireproxy import ( "bufio" + "errors" "io" "net" "net/http" @@ -461,3 +462,238 @@ func TestHTTPServerPlainRequestUsesOneOriginConnection(t *testing.T) { t.Fatalf("origin saw %d requests, want 1", n) } } + +// startRawOrigin accepts connections and hands each to handle. +func startRawOrigin(t *testing.T, handle func(conn net.Conn)) *HTTPServer { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go func() { + defer func() { _ = conn.Close() }() + handle(conn) + }() + } + }() + return &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ln.Addr().String()) + }, + } +} + +func TestHTTPServerPlainRequestChunkedBody(t *testing.T) { + type seen struct { + body string + te []string + } + got := make(chan seen, 1) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + got <- seen{string(body), r.TransferEncoding} + _, _ = w.Write([]byte("ok")) + })) + defer ts.Close() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ts.Listener.Addr().String()) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + raw := "POST http://a.test/upload HTTP/1.1\r\nHost: a.test\r\nTransfer-Encoding: chunked\r\n\r\n" + + "5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n" + if _, err := clientConn.Write([]byte(raw)); err != nil { + t.Fatal(err) + } + resp, err := http.ReadResponse(bufio.NewReader(clientConn), nil) + if err != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("response: %v, %v", resp, err) + } + + select { + case s := <-got: + if s.body != "hello world" || len(s.te) != 1 || s.te[0] != "chunked" { + t.Fatalf("origin saw %+v", s) + } + case <-time.After(5 * time.Second): + t.Fatal("origin did not receive the request") + } +} + +func TestHTTPServerExpectContinue(t *testing.T) { + // net/http answers "100 Continue" when the handler reads the body. + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + _, _ = w.Write([]byte("got " + string(body))) + })) + defer ts.Close() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ts.Listener.Addr().String()) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + headers := "POST http://a.test/ HTTP/1.1\r\nHost: a.test\r\nContent-Length: 5\r\nExpect: 100-continue\r\n\r\n" + if _, err := clientConn.Write([]byte(headers)); err != nil { + t.Fatal(err) + } + + // Like curl, send the body only after the 100 Continue. + rd := bufio.NewReader(clientConn) + interim, err := http.ReadResponse(rd, nil) + if err != nil { + t.Fatalf("no interim response before the body was sent: %v", err) + } + if interim.StatusCode != http.StatusContinue { + t.Fatalf("interim status %d", interim.StatusCode) + } + if _, err := clientConn.Write([]byte("hello")); err != nil { + t.Fatal(err) + } + resp, err := http.ReadResponse(rd, nil) + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK || string(body) != "got hello" { + t.Fatalf("final response %d %q", resp.StatusCode, body) + } +} + +func TestHTTPServerUpgrade(t *testing.T) { + server := startRawOrigin(t, func(conn net.Conn) { + br := bufio.NewReader(conn) + req, err := http.ReadRequest(br) + if err != nil { + return + } + if req.Header.Get("Upgrade") != "websocket" || !strings.EqualFold(req.Header.Get("Connection"), "Upgrade") || + req.Header.Get("Proxy-Authorization") != "" { + _, _ = conn.Write([]byte("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n")) + return + } + // "frame" is sent in the same write as the 101. + _, _ = conn.Write([]byte("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\nframe")) + _, _ = io.Copy(conn, br) + }) + server.auth = CredentialValidator{"u", "p"} + server.authRequired = true + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + raw := "GET http://a.test/ws HTTP/1.1\r\nHost: a.test\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n" + + "Proxy-Authorization: Basic dTpw\r\nProxy-Connection: keep-alive\r\n\r\n" + if _, err := clientConn.Write([]byte(raw)); err != nil { + t.Fatal(err) + } + + rd := bufio.NewReader(clientConn) + resp, err := http.ReadResponse(rd, nil) + if err != nil { + t.Fatal(err) + } + if resp.StatusCode != http.StatusSwitchingProtocols || resp.Header.Get("Upgrade") != "websocket" { + t.Fatalf("response %d %v", resp.StatusCode, resp.Header) + } + + buf := make([]byte, len("frame")) + if _, err := io.ReadFull(rd, buf); err != nil || string(buf) != "frame" { + t.Fatalf("bytes after the 101 were lost: %q, %v", buf, err) + } + if _, err := clientConn.Write([]byte("ping")); err != nil { + t.Fatal(err) + } + buf = make([]byte, 4) + if _, err := io.ReadFull(rd, buf); err != nil || string(buf) != "ping" { + t.Fatalf("tunnel did not echo: %q, %v", buf, err) + } +} + +// An origin that ignores "Connection: close" and keeps the connection open +// must not keep the client waiting after a complete response. +func TestHTTPServerPlainResponseEndsAtFraming(t *testing.T) { + server := startRawOrigin(t, func(conn net.Conn) { + _, _ = http.ReadRequest(bufio.NewReader(conn)) + _, _ = conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")) + _, _ = io.Copy(io.Discard, conn) // never closes by itself + }) + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := clientConn.Write([]byte("GET http://a.test/ HTTP/1.1\r\nHost: a.test\r\n\r\n")); err != nil { + t.Fatal(err) + } + all, err := io.ReadAll(clientConn) + if err != nil { + t.Fatalf("client connection was not closed after the response: %v", err) + } + if !strings.HasSuffix(string(all), "\r\n\r\nok") { + t.Fatalf("unexpected response %q", all) + } +} + +// An origin that stalls mid-response is cut off after the idle timeout. +func TestHTTPServerPlainResponseIdleTimeout(t *testing.T) { + setProxyIdleTimeout(t, 100*time.Millisecond) + server := startRawOrigin(t, func(conn net.Conn) { + _, _ = http.ReadRequest(bufio.NewReader(conn)) + _, _ = conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\npart")) + _, _ = io.Copy(io.Discard, conn) + }) + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := clientConn.Write([]byte("GET http://a.test/ HTTP/1.1\r\nHost: a.test\r\n\r\n")); err != nil { + t.Fatal(err) + } + // The truncated response ends in an error or EOF, not a deadline timeout. + _, err = io.ReadAll(clientConn) + var ne net.Error + if errors.As(err, &ne) && ne.Timeout() { + t.Fatalf("proxy did not cut off the stalled origin: %v", err) + } +} diff --git a/proxy.go b/proxy.go index 14d1a2ab..28b0b46d 100644 --- a/proxy.go +++ b/proxy.go @@ -56,6 +56,28 @@ func (r activityReader) Read(p []byte) (int, error) { return n, err } +// idleConn calls reset after every read or write that moved data. +type idleConn struct { + net.Conn + reset func() +} + +func (c idleConn) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + if n > 0 { + c.reset() + } + return n, err +} + +func (c idleConn) Write(p []byte) (int, error) { + n, err := c.Conn.Write(p) + if n > 0 { + c.reset() + } + return n, err +} + type proxyState struct { a, b io.ReadWriteCloser idle *time.Timer From 0132a3260c9437179c2b332915497963023ef252 Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:47:56 -0600 Subject: [PATCH 09/10] http: strip hop-by-hop headers from relayed plain-HTTP responses The origin's Keep-Alive, Proxy-Authenticate and any header named in its Connection header describe the origin connection, not the client's, and were passed through. Remove them (the proxy sets Connection: close itself). A 101 response keeps its Connection and Upgrade headers. A test also checks that chunked response trailer values reach the client. Co-Authored-By: Claude Sonnet 5.5 --- http.go | 3 +++ http_test.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/http.go b/http.go index d339ebba..85a31ec9 100644 --- a/http.go +++ b/http.go @@ -218,6 +218,9 @@ func (s *HTTPServer) handle(req *http.Request, conn net.Conn, rd io.Reader) erro continue } + // The origin's connection management does not apply to the client + // connection, which is closed after this response. + removeHopByHopHeaders(resp.Header) resp.Close = true err = resp.Write(conn) _ = resp.Body.Close() diff --git a/http_test.go b/http_test.go index 523a5f5e..a2d041cc 100644 --- a/http_test.go +++ b/http_test.go @@ -697,3 +697,54 @@ func TestHTTPServerPlainResponseIdleTimeout(t *testing.T) { t.Fatalf("proxy did not cut off the stalled origin: %v", err) } } + +func TestHTTPServerPlainResponseHeadersAndTrailers(t *testing.T) { + server := startRawOrigin(t, func(conn net.Conn) { + _, _ = http.ReadRequest(bufio.NewReader(conn)) + _, _ = conn.Write([]byte("HTTP/1.1 200 OK\r\n" + + "Transfer-Encoding: chunked\r\n" + + "Trailer: X-Sum\r\n" + + "Connection: keep-alive, X-Custom-Hop\r\n" + + "Keep-Alive: timeout=5\r\n" + + "Proxy-Authenticate: Basic\r\n" + + "X-Custom-Hop: 1\r\n" + + "X-Keep-Me: yes\r\n\r\n" + + "5\r\nhello\r\n0\r\nX-Sum: abc\r\n\r\n")) + _, _ = io.Copy(io.Discard, conn) + }) + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := clientConn.Write([]byte("GET http://a.test/ HTTP/1.1\r\nHost: a.test\r\n\r\n")); err != nil { + t.Fatal(err) + } + resp, err := http.ReadResponse(bufio.NewReader(clientConn), nil) + if err != nil { + t.Fatal(err) + } + body, err := io.ReadAll(resp.Body) + if err != nil || string(body) != "hello" { + t.Fatalf("body %q, %v", body, err) + } + + for _, name := range []string{"Keep-Alive", "Proxy-Authenticate", "X-Custom-Hop"} { + if v := resp.Header.Get(name); v != "" { + t.Errorf("client saw %s=%q", name, v) + } + } + if resp.Header.Get("X-Keep-Me") != "yes" { + t.Errorf("end-to-end header dropped: %v", resp.Header) + } + if !resp.Close { + t.Errorf("expected Connection: close, headers %v", resp.Header) + } + if got := resp.Trailer.Get("X-Sum"); got != "abc" { + t.Errorf("trailer X-Sum = %q, want abc (trailer %v)", got, resp.Trailer) + } +} From 6d749465829158eea03f94bbe040d1ef81ad334a Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:56:47 -0600 Subject: [PATCH 10/10] http: do not log a client that closes before sending a request A connection closed before any request byte (port probe, load balancer health check) made http.ReadRequest return io.EOF, logged as "read request failed". Skip that case; truncated requests (io.ErrUnexpectedEOF), timeouts and other read errors are still logged. Co-Authored-By: Claude Sonnet 5.5 --- http.go | 7 ++++++- http_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/http.go b/http.go index 85a31ec9..8576a588 100644 --- a/http.go +++ b/http.go @@ -242,7 +242,12 @@ func (s *HTTPServer) serve(conn net.Conn) { var rd = bufio.NewReader(conn) req, err := http.ReadRequest(rd) if err != nil { - log.Printf("read request failed: %s\n", err) + // io.EOF means the client closed before sending any byte (a port + // probe or health check), which is not worth a log line. A request + // cut short is io.ErrUnexpectedEOF and is still logged. + if err != io.EOF { + log.Printf("read request failed: %s\n", err) + } return } if err := conn.SetReadDeadline(time.Time{}); err != nil { diff --git a/http_test.go b/http_test.go index a2d041cc..cbf18d92 100644 --- a/http_test.go +++ b/http_test.go @@ -2,11 +2,14 @@ package wireproxy import ( "bufio" + "bytes" "errors" "io" + "log" "net" "net/http" "net/http/httptest" + "os" "strings" "sync/atomic" "testing" @@ -325,6 +328,49 @@ func TestHTTPServerReadRequestTimeout(t *testing.T) { } } +// A client that connects and closes without sending anything (a port probe or +// load balancer health check) is not an error, but a truncated request is. +func TestHTTPServerReadRequestLogging(t *testing.T) { + var logs bytes.Buffer + log.SetOutput(&logs) + t.Cleanup(func() { log.SetOutput(os.Stderr) }) + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = listener.Close() }) + + // serveAfter has a client write write (if not empty) and close, then + // returns what serve logged for that connection. + serveAfter := func(write string) string { + logs.Reset() + client, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + if write != "" { + if _, err := client.Write([]byte(write)); err != nil { + t.Fatal(err) + } + } + _ = client.Close() + server, err := listener.Accept() + if err != nil { + t.Fatal(err) + } + (&HTTPServer{}).serve(server) + return logs.String() + } + + if got := serveAfter(""); got != "" { + t.Errorf("empty connection logged %q, want nothing", got) + } + if got := serveAfter("GET http://example.test/ HT"); !strings.Contains(got, "read request failed") { + t.Errorf("truncated request logged %q, want a read request failure", got) + } +} + func TestHTTPServerReadDeadlineClearedForTunnel(t *testing.T) { setReadRequestTimeout(t, 100*time.Millisecond) echo := startEchoServer(t)