diff --git a/go.mod b/go.mod index 715d41f..d2e0777 100644 --- a/go.mod +++ b/go.mod @@ -2,6 +2,11 @@ module opencode2api go 1.24 -require golang.org/x/crypto v0.41.0 +require ( + github.com/andybalholm/brotli v1.1.1 + github.com/klauspost/compress v1.18.0 + github.com/refraction-networking/utls v1.8.2 + golang.org/x/crypto v0.41.0 +) require golang.org/x/sys v0.35.0 // indirect diff --git a/go.sum b/go.sum index 9e67244..e295d23 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,11 @@ +github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= +github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo= +github.com/refraction-networking/utls v1.8.2/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM= +github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= +github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go index 5b957e0..367019c 100644 --- a/internal/gateway/pool.go +++ b/internal/gateway/pool.go @@ -23,15 +23,18 @@ import ( ) // proxyTransport is one configured proxy route, or "direct", with its own HTTP -// client. pool marks a rotating proxy pool entry (#pool or pool+), whose -// health is never tracked. healthy is cleared by proxy-route failures and set -// again by upstream HTTP responses (see syncProxyResult) or a passing health -// check; checking claims the single health check allowed in flight. +// clients: client for regular traffic and bun for the free-model traffic that +// goes out disguised as the Bun runtime (see Gateway.inferenceClient). pool +// marks a rotating proxy pool entry (#pool or pool+), whose health is never +// tracked. healthy is cleared by proxy-route failures and set again by +// upstream HTTP responses (see syncProxyResult) or a passing health check; +// checking claims the single health check allowed in flight. type proxyTransport struct { index int name string pool bool client *http.Client + bun *http.Client healthy atomic.Bool checking atomic.Bool } @@ -260,11 +263,13 @@ func (p *proxyTransports) healthCounts() (total, healthy int) { return len(p.items), healthy } -// transportPool builds one HTTP client per configured proxy entry, each -// starting healthy, with responseHeaderTimeout as its header wait. A #pool -// entry gets an HTTP/1.1 transport without keep-alives, so every attempt opens -// a new connection through the pool; "direct" dials the upstream without any -// proxy, ignoring the proxy environment variables. +// transportPool builds the HTTP clients of every configured proxy entry, each +// entry starting healthy: a regular client and a Bun-disguised one +// (httpx.BunTransport) sharing the proxy, connect timeout, idle settings and +// responseHeaderTimeout as their header wait. A #pool entry gets HTTP/1.1 +// transports without keep-alives, so every attempt opens a new connection +// through the pool; "direct" dials the upstream without any proxy, ignoring +// the proxy environment variables. func transportPool(proxies []string, cfg config.PerformanceConfig, responseHeaderTimeout time.Duration) (*proxyTransports, error) { p := &proxyTransports{items: make([]*proxyTransport, 0, len(proxies))} for _, raw := range proxies { @@ -296,6 +301,7 @@ func transportPool(proxies []string, cfg config.PerformanceConfig, responseHeade Timeout: time.Duration(cfg.ConnectTimeoutSeconds) * time.Second, KeepAlive: 30 * time.Second, }).DialContext + var proxyURL *url.URL if clean == "direct" { transport.Proxy = nil } else { @@ -304,8 +310,20 @@ func transportPool(proxies []string, cfg config.PerformanceConfig, responseHeade return nil, fmt.Errorf("parse proxy %s: %w", config.RedactURL(raw), err) } transport.Proxy = http.ProxyURL(u) + proxyURL = u } - proxy := &proxyTransport{index: len(p.items), name: raw, pool: isPool, client: &http.Client{Transport: transport}} + bun, err := httpx.NewBunTransport(httpx.BunOptions{ + Proxy: proxyURL, + ConnectTimeout: time.Duration(cfg.ConnectTimeoutSeconds) * time.Second, + ResponseHeaderTimeout: responseHeaderTimeout, + IdleConnTimeout: transport.IdleConnTimeout, + MaxIdleConnsPerHost: cfg.MaxIdleConnsPerHost, + DisableKeepAlives: isPool, + }) + if err != nil { + return nil, fmt.Errorf("proxy %s: %w", config.RedactURL(raw), err) + } + proxy := &proxyTransport{index: len(p.items), name: raw, pool: isPool, client: &http.Client{Transport: transport}, bun: &http.Client{Transport: bun}} proxy.healthy.Store(true) p.items = append(p.items, proxy) } diff --git a/internal/gateway/probe.go b/internal/gateway/probe.go index 17b3e68..822673d 100644 --- a/internal/gateway/probe.go +++ b/internal/gateway/probe.go @@ -108,14 +108,14 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult // Prefer the v1 lane (/zen) before falling back to the v2 // /inference origin. for _, baseURL := range g.anonymousUpstreams() { - lanes = append(lanes, lane{anonymousZenKey, "anonymous", baseURL, node.proxy.client}) + lanes = append(lanes, lane{anonymousZenKey, "anonymous", baseURL, g.inferenceClient(node.proxy, baseURL, model)}) } } } cursor := g.zenNodes.CursorFor(ids.Session) if node := cursor.Next(); node != nil { if proxy := g.zenNodes.Proxy(node); proxy != nil { - lanes = append(lanes, lane{node.key, "zen", g.cfg.Upstream.Zen, proxy.client}) + lanes = append(lanes, lane{node.key, "zen", g.cfg.Upstream.Zen, g.inferenceClient(proxy, g.cfg.Upstream.Zen, model)}) } } result := probeResult{reason: "no_probe_channel"} diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 78b67cc..e584b33 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -370,7 +370,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b } setRequestCredential(ctx, config.TierZen, "anonymous", "anonymous", true, node.proxy) started := time.Now() - resp, err := doInferenceAttempt(node.proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout) + resp, err := doInferenceAttempt(g.inferenceClient(node.proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout) duration := time.Since(started) if ctx.Err() != nil { // The parent budget expired while this attempt was in flight. Its @@ -434,6 +434,19 @@ func (g *Gateway) anonymousUpstreams() []string { return []string{models.V1Base, g.cfg.Upstream.Anonymous} } +// inferenceClient picks the client of proxy for a request for model to +// baseURL. Free-model traffic to the /zen and /inference lanes goes through +// the Bun client (see httpx.BunTransport), whose TLS ClientHello and HTTP/1.1 +// header layout match the runtime of the official OpenCode clients; every +// other request, including the Go tier (/zen/go), keeps the regular client. +func (g *Gateway) inferenceClient(proxy *proxyTransport, baseURL, model string) *http.Client { + lane := strings.ToLower(strings.TrimRight(strings.TrimSpace(baseURL), "/")) + if g.catalog.IsFreeModel(model) && (models.IsV1Upstream(baseURL) || strings.HasSuffix(lane, "/inference")) { + return proxy.bun + } + return proxy.client +} + // v1ReadTool is the single tool name required by the v1 free-tier gate // (/zen). Unlike the v2 /inference gate, it does not require a // shell/edit/glob/grep toolset and does not validate tool descriptions or @@ -967,7 +980,7 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, req.Close = true } started := time.Now() - resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout) + resp, err := doInferenceAttempt(g.inferenceClient(proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout) duration := time.Since(started) g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+1, keyID, "key", false, proxy, resp, err, duration) if err != nil { @@ -1049,7 +1062,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies keyID := config.KeyDisplayID(node.key) setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy) attemptStarted := time.Now() - resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout) + resp, err := doInferenceAttempt(g.inferenceClient(proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout) attemptDuration := time.Since(attemptStarted) if ctx.Err() != nil { // The request budget expired while this attempt was in flight. A diff --git a/internal/httpx/bun.go b/internal/httpx/bun.go new file mode 100644 index 0000000..369319e --- /dev/null +++ b/internal/httpx/bun.go @@ -0,0 +1,590 @@ +package httpx + +import ( + "bufio" + "compress/flate" + "compress/gzip" + "compress/zlib" + "context" + "errors" + "fmt" + "io" + "maps" + "net" + "net/http" + "net/http/httptrace" + "net/url" + "os" + "slices" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "github.com/andybalholm/brotli" + "github.com/klauspost/compress/zstd" +) + +// BunOptions configures a BunTransport. The fields mirror their namesakes on +// http.Transport; a nil Proxy dials the upstream directly. +type BunOptions struct { + Proxy *url.URL + ConnectTimeout time.Duration + ResponseHeaderTimeout time.Duration + IdleConnTimeout time.Duration + MaxIdleConnsPerHost int + DisableKeepAlives bool +} + +// BunTransport is an http.RoundTripper that puts requests on the wire the way +// Bun's fetch does, so they look like they come from an official OpenCode +// client (the 1.x and 2.x CLIs both run on Bun). net/http cannot do that: +// crypto/tls always sends Go's own ClientHello, and its HTTP/1.1 writer orders +// and canonicalizes headers its own way. BunTransport handshakes with Bun's +// BoringSSL ClientHello through uTLS (bunClientHello), speaks HTTP/1.1 only, +// the one ALPN protocol Bun offers, and lays requests out like Bun (see +// bunRequestHead). Like fetch it decodes gzip, deflate, br and zstd bodies. +// +// Idle connections are pooled per host, up to MaxIdleConnsPerHost, until +// IdleConnTimeout. A pooled connection the server closes is dropped while it +// is idle, and a reused connection the server drops before answering is +// retried once on a fresh one. Unlike http.Transport it does not cap the +// connections per host. +type BunTransport struct { + proxy *url.URL + dialer *net.Dialer + responseHeaderTimeout time.Duration + idleTimeout time.Duration + maxIdlePerHost int + keepAlive bool + + mu sync.Mutex + idle map[string][]*bunConn +} + +// NewBunTransport builds a BunTransport from options. A MaxIdleConnsPerHost +// of zero keeps http.DefaultMaxIdleConnsPerHost, as http.Transport does. +func NewBunTransport(options BunOptions) (*BunTransport, error) { + if options.Proxy != nil { + switch options.Proxy.Scheme { + case "http", "https", "socks5", "socks5h": + default: + return nil, fmt.Errorf("unsupported proxy scheme %q", options.Proxy.Scheme) + } + } + maxIdle := options.MaxIdleConnsPerHost + if maxIdle == 0 { + maxIdle = http.DefaultMaxIdleConnsPerHost + } + return &BunTransport{ + proxy: options.Proxy, + dialer: &net.Dialer{Timeout: options.ConnectTimeout, KeepAlive: 30 * time.Second}, + responseHeaderTimeout: options.ResponseHeaderTimeout, + idleTimeout: options.IdleConnTimeout, + maxIdlePerHost: maxIdle, + keepAlive: !options.DisableKeepAlives, + idle: map[string][]*bunConn{}, + }, nil +} + +// bunConn is one upstream connection. While it is pooled, a watcher goroutine +// blocks in a one-byte Peek so a server that closes it is noticed before it +// is handed out again; watched is closed once that goroutine returns, and +// watchErr holds what ended the Peek. +type bunConn struct { + net.Conn + key string + br *bufio.Reader + bw *bufio.Writer + idleAt time.Time + timer *time.Timer + watched chan struct{} + watchErr error +} + +// RoundTrip sends req and returns the response headers; the body is read +// straight off the connection. The request body is read fully before +// anything is sent. Header names and values must be valid HTTP fields. Once +// the request context ends, the error is its cause, as with http.Transport. +func (t *BunTransport) RoundTrip(req *http.Request) (*http.Response, error) { + body, err := readRequestBody(req) + if err != nil { + return nil, err + } + u := req.URL + if u == nil || u.Host == "" || u.Scheme != "https" && u.Scheme != "http" { + return nil, fmt.Errorf("bun transport: unsupported request URL %q", u) + } + head, decompress, err := bunRequestHead(req, body) + if err != nil { + return nil, err + } + ctx := req.Context() + trace := httptrace.ContextClientTrace(ctx) + port := u.Port() + if port == "" { + port = "443" + if u.Scheme == "http" { + port = "80" + } + } + addr := net.JoinHostPort(u.Hostname(), port) + key := u.Scheme + "://" + addr + for retried := false; ; retried = true { + c, info, err := t.getConn(ctx, u.Scheme, key, addr, u.Hostname()) + if err != nil { + return nil, bunContextError(ctx, err) + } + if trace != nil && trace.GotConn != nil { + trace.GotConn(info) + } + resp, dropped, err := t.exchange(ctx, c, req, head, body, decompress, trace) + if err == nil { + return resp, nil + } + if info.Reused && dropped && !retried && ctx.Err() == nil { + continue + } + return nil, bunContextError(ctx, err) + } +} + +// readRequestBody reads and closes the body of req. It returns nil for a +// request without a body and a non-nil, possibly empty slice otherwise. +func readRequestBody(req *http.Request) ([]byte, error) { + if req.Body == nil || req.Body == http.NoBody { + return nil, nil + } + defer req.Body.Close() + return io.ReadAll(req.Body) +} + +// bunContextError returns the cause of ctx once it has ended, and err +// otherwise. +func bunContextError(ctx context.Context, err error) error { + if cause := context.Cause(ctx); cause != nil { + return cause + } + return err +} + +// getConn returns a pooled connection for key, skipping ones that died while +// idle, or dials a new one. +func (t *BunTransport) getConn(ctx context.Context, scheme, key, addr, serverName string) (*bunConn, httptrace.GotConnInfo, error) { + for c := t.takeIdle(key); c != nil; c = t.takeIdle(key) { + if c.reclaim() { + return c, httptrace.GotConnInfo{Conn: c.Conn, Reused: true, WasIdle: true, IdleTime: time.Since(c.idleAt)}, nil + } + c.Close() + } + conn, err := t.dial(ctx, scheme, addr, serverName) + if err != nil { + return nil, httptrace.GotConnInfo{}, err + } + c := &bunConn{Conn: conn, key: key, br: bufio.NewReader(conn), bw: bufio.NewWriter(conn)} + return c, httptrace.GotConnInfo{Conn: conn}, nil +} + +// exchange writes one request on c and reads the response headers. On success +// the response body owns c; on failure c is closed, and dropped reports +// whether the server dropped the connection before the first response byte, +// which a reused connection may retry. +func (t *BunTransport) exchange(ctx context.Context, c *bunConn, req *http.Request, head, body []byte, decompress bool, trace *httptrace.ClientTrace) (*http.Response, bool, error) { + stop := context.AfterFunc(ctx, func() { c.Close() }) + fail := func(err error, dropped bool) (*http.Response, bool, error) { + stop() + c.Close() + var timeout net.Error + if t.responseHeaderTimeout > 0 && ctx.Err() == nil && errors.As(err, &timeout) && timeout.Timeout() { + err = fmt.Errorf("bun transport: timeout awaiting response headers: %w", err) + } + return nil, dropped, err + } + _, err := c.bw.Write(head) + if err == nil { + _, err = c.bw.Write(body) + } + if err == nil { + err = c.bw.Flush() + } + if trace != nil && trace.WroteRequest != nil { + trace.WroteRequest(httptrace.WroteRequestInfo{Err: err}) + } + if err != nil { + return fail(err, isConnDropped(err)) + } + if t.responseHeaderTimeout > 0 { + _ = c.SetReadDeadline(time.Now().Add(t.responseHeaderTimeout)) + } + if _, err := c.br.Peek(1); err != nil { + return fail(err, isConnDropped(err)) + } + if trace != nil && trace.GotFirstResponseByte != nil { + trace.GotFirstResponseByte() + } + resp, err := http.ReadResponse(c.br, req) + // Skip interim 1xx responses such as 103 Early Hints. + for err == nil && resp.StatusCode < 200 && resp.StatusCode != http.StatusSwitchingProtocols { + resp, err = http.ReadResponse(c.br, req) + } + if err != nil { + return fail(err, false) + } + _ = c.SetReadDeadline(time.Time{}) + raw := &bunBody{t: t, c: c, ctx: ctx, stop: stop, src: resp.Body, reusable: t.keepAlive && !req.Close && !resp.Close} + if resp.Body == http.NoBody { + raw.finish(true) + return resp, false, nil + } + resp.Body = raw + if encoding := strings.ToLower(strings.TrimSpace(resp.Header.Get("Content-Encoding"))); decompress && isBunEncoding(encoding) { + resp.Body = &bunDecoder{body: raw, encoding: encoding} + resp.Header.Del("Content-Encoding") + resp.Header.Del("Content-Length") + resp.ContentLength = -1 + resp.Uncompressed = true + } + return resp, false, nil +} + +// isConnDropped reports whether err says the server closed or reset the +// connection. +func isConnDropped(err error) bool { + return errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.ECONNABORTED) || errors.Is(err, syscall.EPIPE) +} + +// takeIdle removes and returns the most recently pooled connection for key, +// or nil when there is none. +func (t *BunTransport) takeIdle(key string) *bunConn { + t.mu.Lock() + defer t.mu.Unlock() + conns := t.idle[key] + if len(conns) == 0 { + return nil + } + c := conns[len(conns)-1] + t.setIdle(key, conns[:len(conns)-1]) + return c +} + +// putIdle pools c once its response has been read to the end, or closes it +// when the pool for its host is full, and starts its idle watcher. +func (t *BunTransport) putIdle(c *bunConn) { + t.mu.Lock() + if len(t.idle[c.key]) >= t.maxIdlePerHost { + t.mu.Unlock() + c.Close() + return + } + c.idleAt = time.Now() + c.watched = make(chan struct{}) + c.timer = nil + if t.idleTimeout > 0 { + c.timer = time.AfterFunc(t.idleTimeout, func() { + if t.removeIdle(c) { + c.Close() + } + }) + } + t.idle[c.key] = append(t.idle[c.key], c) + t.mu.Unlock() + go func() { + _, c.watchErr = c.br.Peek(1) + if t.removeIdle(c) { + c.Close() + } + close(c.watched) + }() +} + +// removeIdle removes c from the pool and reports whether it was still there. +func (t *BunTransport) removeIdle(c *bunConn) bool { + t.mu.Lock() + defer t.mu.Unlock() + conns := t.idle[c.key] + index := slices.Index(conns, c) + if index < 0 { + return false + } + t.setIdle(c.key, slices.Delete(conns, index, index+1)) + return true +} + +// setIdle stores the pooled connections of key, dropping an empty entry. The +// caller must hold mu. +func (t *BunTransport) setIdle(key string, conns []*bunConn) { + if len(conns) == 0 { + delete(t.idle, key) + return + } + t.idle[key] = conns +} + +// reclaim stops the idle watcher of a connection just taken from the pool and +// reports whether the connection is still usable: the watcher's Peek must +// have ended on the deadline set here, not on data or a close from the +// server. A read timeout leaves the TLS state intact, so the connection can +// carry the next request. +func (c *bunConn) reclaim() bool { + if c.timer != nil { + c.timer.Stop() + } + _ = c.SetReadDeadline(time.Unix(1, 0)) + <-c.watched + return errors.Is(c.watchErr, os.ErrDeadlineExceeded) && c.SetReadDeadline(time.Time{}) == nil +} + +// CloseIdleConnections closes every pooled connection. http.Client calls it +// from its own CloseIdleConnections. +func (t *BunTransport) CloseIdleConnections() { + t.mu.Lock() + idle := t.idle + t.idle = map[string][]*bunConn{} + t.mu.Unlock() + for _, conns := range idle { + for _, c := range conns { + c.Close() + } + } +} + +// bunBody is a response body read straight off its connection. Reading it to +// the end hands the connection back to the pool when it is reusable; closing +// it early, a read error or the end of the request context closes the +// connection instead, since an HTTP/1.1 connection with a pending body cannot +// carry another request. src is never closed: closing an unfinished net/http +// body drains it, which would block on an event stream. +type bunBody struct { + t *BunTransport + c *bunConn + ctx context.Context + stop func() bool + src io.Reader + reusable bool + once sync.Once +} + +func (b *bunBody) Read(p []byte) (int, error) { + n, err := b.src.Read(p) + if err == io.EOF { + b.finish(true) + } else if err != nil { + err = bunContextError(b.ctx, err) + b.finish(false) + } + return n, err +} + +func (b *bunBody) Close() error { + b.finish(false) + return nil +} + +// finish releases the connection once: back to the pool when the body ended +// cleanly on a reusable connection whose context was still live, closed +// otherwise. +func (b *bunBody) finish(ended bool) { + b.once.Do(func() { + if b.stop() && ended && b.reusable { + b.t.putIdle(b.c) + return + } + b.c.Close() + }) +} + +// isBunEncoding reports whether encoding is a Content-Encoding the transport +// decodes, the ones its Accept-Encoding offers. +func isBunEncoding(encoding string) bool { + switch encoding { + case "gzip", "x-gzip", "deflate", "br", "zstd": + return true + } + return false +} + +// bunDecoder decompresses a response body. The decoder is built on the first +// Read, so RoundTrip never waits for a compression header. +type bunDecoder struct { + body *bunBody + encoding string + reader io.Reader + release func() + err error +} + +func (d *bunDecoder) Read(p []byte) (int, error) { + if d.err != nil { + return 0, d.err + } + if d.reader == nil { + if d.reader, d.release, d.err = newBunDecoder(d.encoding, d.body); d.err != nil { + return 0, d.err + } + } + n, err := d.reader.Read(p) + if err != nil { + d.err = err + if d.release != nil { + d.release() + } + if err == io.EOF { + // A decoder can stop at the end of its own stream and leave the + // transfer framing, such as the last chunk, unread. Consuming it + // lets the connection go back to the pool. + _, _ = io.Copy(io.Discard, io.LimitReader(d.body, 4<<10)) + } + } + return n, err +} + +func (d *bunDecoder) Close() error { + return d.body.Close() +} + +// newBunDecoder returns a reader decoding r for encoding and, when the +// decoder holds resources, a function releasing them. Bodies are capped at an +// 8 MiB zstd window, the limit RFC 9659 sets for HTTP. +func newBunDecoder(encoding string, r io.Reader) (io.Reader, func(), error) { + switch encoding { + case "deflate": + // "deflate" means zlib-wrapped data (RFC 9110), but some servers send + // a raw DEFLATE stream, so both are accepted. + reader := bufio.NewReader(r) + header, err := reader.Peek(2) + if err != nil { + return nil, nil, err + } + if header[0]&0x0f == 8 && (uint16(header[0])<<8|uint16(header[1]))%31 == 0 { + decoder, err := zlib.NewReader(reader) + return decoder, nil, err + } + return flate.NewReader(reader), nil, nil + case "br": + return brotli.NewReader(r), nil, nil + case "zstd": + // A single-threaded decoder runs on the reading goroutine and starts + // none of its own. + decoder, err := zstd.NewReader(r, zstd.WithDecoderConcurrency(1), zstd.WithDecoderMaxWindow(8<<20)) + if err != nil { + return nil, nil, err + } + return decoder, decoder.Close, nil + default: + decoder, err := gzip.NewReader(r) + return decoder, nil, err + } +} + +// bunCommonHeaders lists the request headers WebKit knows by name, in the +// spelling and order Bun's fetch writes them: ahead of every other header, +// alphabetically. +var bunCommonHeaders = []string{ + "Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Authorization", "Cache-Control", + "Connection", "Content-Encoding", "Content-Language", "Content-Length", "Content-Type", "Cookie", "DNT", + "Expect", "Host", "If-None-Match", "Keep-Alive", "Last-Event-Id", "Origin", "Pragma", + "Proxy-Authorization", "Range", "Referer", "Sec-Fetch-Mode", "TE", "Upgrade-Insecure-Requests", + "User-Agent", +} + +// bunRequestHead renders the request line and headers of req the way Bun's +// fetch writes them for body (nil when the request has none): +// 1. the headers of bunCommonHeaders, in that order and spelling; +// 2. every other header, lowercased as both OpenCode clients hand them to +// fetch, and sorted as the 1.x AI SDK passes them; +// 3. the headers fetch adds itself: Connection, then User-Agent and Accept +// unless the caller set them, Host, Accept-Encoding unless the caller set +// it, and Content-Length when there is a body. +// +// An Accept of "*/*" is written where fetch adds its default, since that is +// where the official clients' Accept appears. Host, Connection, +// Content-Length and Transfer-Encoding belong to the transport, so caller +// values for them are ignored. decompress reports whether the transport added +// Accept-Encoding and so decodes the response. +func bunRequestHead(req *http.Request, body []byte) ([]byte, bool, error) { + values := make(map[string]string, len(req.Header)) + for name, list := range req.Header { + for _, value := range list { + if !validHeaderField(name, value) { + return nil, false, fmt.Errorf("bun transport: invalid header field %q", name) + } + } + lower := strings.ToLower(name) + if len(list) == 0 || lower == "host" || lower == "connection" || lower == "content-length" || lower == "transfer-encoding" { + continue + } + value := strings.Join(list, ", ") + if previous, ok := values[lower]; ok { + value = previous + ", " + value + } + values[lower] = value + } + if values["accept"] == "*/*" { + delete(values, "accept") + } + _, hasUserAgent := values["user-agent"] + _, hasAccept := values["accept"] + _, hasEncoding := values["accept-encoding"] + method := req.Method + if method == "" { + method = http.MethodGet + } + var head strings.Builder + head.WriteString(method + " " + req.URL.RequestURI() + " HTTP/1.1\r\n") + for _, name := range bunCommonHeaders { + lower := strings.ToLower(name) + if value, ok := values[lower]; ok { + head.WriteString(name + ": " + value + "\r\n") + delete(values, lower) + } + } + for _, name := range slices.Sorted(maps.Keys(values)) { + head.WriteString(name + ": " + values[name] + "\r\n") + } + head.WriteString("Connection: keep-alive\r\n") + if !hasUserAgent { + head.WriteString("User-Agent: Bun/" + v1BunVersion + "\r\n") + } + if !hasAccept { + head.WriteString("Accept: */*\r\n") + } + // fetch takes Host from the parsed URL, which omits a default port. + host := req.Host + if host == "" { + host = req.URL.Host + } + if req.URL.Scheme == "https" { + host = strings.TrimSuffix(host, ":443") + } else { + host = strings.TrimSuffix(host, ":80") + } + head.WriteString("Host: " + host + "\r\n") + if !hasEncoding { + head.WriteString("Accept-Encoding: gzip, deflate, br, zstd\r\n") + } + if body != nil { + head.WriteString("Content-Length: " + strconv.Itoa(len(body)) + "\r\n") + } + head.WriteString("\r\n") + return []byte(head.String()), !hasEncoding, nil +} + +// validHeaderField reports whether name is an HTTP token and value carries no +// control characters other than tab, so a field cannot split the request. +func validHeaderField(name, value string) bool { + if name == "" { + return false + } + for i := 0; i < len(name); i++ { + if b := name[i]; b <= ' ' || b >= 0x7f || strings.IndexByte(`"(),/:;<=>?@[\]{}`, b) >= 0 { + return false + } + } + for i := 0; i < len(value); i++ { + if b := value[i]; b < ' ' && b != '\t' || b == 0x7f { + return false + } + } + return true +} diff --git a/internal/httpx/bun_dial.go b/internal/httpx/bun_dial.go new file mode 100644 index 0000000..4f8e410 --- /dev/null +++ b/internal/httpx/bun_dial.go @@ -0,0 +1,312 @@ +package httpx + +import ( + "bufio" + "context" + "crypto/tls" + "encoding/base64" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "time" + + utls "github.com/refraction-networking/utls" +) + +// bunHandshakeTimeout bounds the proxy negotiation and the TLS handshake of a +// new connection, the TLSHandshakeTimeout the regular clients inherit from +// http.DefaultTransport. +const bunHandshakeTimeout = 10 * time.Second + +// bunClientHello returns the ClientHello of Bun's fetch, captured from Bun +// 1.4.3. Bun links its own BoringSSL, so the hello is the same on every +// platform: JA4 t13d1713h1, no GREASE, no padding, http/1.1 as the only ALPN +// protocol and X25519MLKEM768 as the first key share. uTLS keeps handshake +// state in the extensions, so every connection needs a fresh spec. +func bunClientHello() *utls.ClientHelloSpec { + return &utls.ClientHelloSpec{ + TLSVersMin: utls.VersionTLS12, + TLSVersMax: utls.VersionTLS13, + CipherSuites: []uint16{ + utls.TLS_AES_128_GCM_SHA256, + utls.TLS_AES_256_GCM_SHA384, + utls.TLS_CHACHA20_POLY1305_SHA256, + utls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + utls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + utls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, + utls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + utls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, + utls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, + utls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, + utls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + utls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + utls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, + utls.TLS_RSA_WITH_AES_128_GCM_SHA256, + utls.TLS_RSA_WITH_AES_256_GCM_SHA384, + utls.TLS_RSA_WITH_AES_128_CBC_SHA, + utls.TLS_RSA_WITH_AES_256_CBC_SHA, + }, + CompressionMethods: []uint8{0}, + Extensions: []utls.TLSExtension{ + &utls.SNIExtension{}, + &utls.ExtendedMasterSecretExtension{}, + &utls.RenegotiationInfoExtension{Renegotiation: utls.RenegotiateOnceAsClient}, + &utls.SupportedCurvesExtension{Curves: []utls.CurveID{utls.X25519MLKEM768, utls.X25519, utls.CurveP256, utls.CurveP384}}, + &utls.SupportedPointsExtension{SupportedPoints: []uint8{0}}, + &utls.SessionTicketExtension{}, + &utls.ALPNExtension{AlpnProtocols: []string{"http/1.1"}}, + &utls.StatusRequestExtension{}, + &utls.SignatureAlgorithmsExtension{SupportedSignatureAlgorithms: []utls.SignatureScheme{ + utls.ECDSAWithP256AndSHA256, + utls.PSSWithSHA256, + utls.PKCS1WithSHA256, + utls.ECDSAWithP384AndSHA384, + utls.PSSWithSHA384, + utls.PKCS1WithSHA384, + utls.PSSWithSHA512, + utls.PKCS1WithSHA512, + utls.PKCS1WithSHA1, + }}, + &utls.SCTExtension{}, + &utls.KeyShareExtension{KeyShares: []utls.KeyShare{{Group: utls.X25519MLKEM768}, {Group: utls.X25519}}}, + &utls.PSKKeyExchangeModesExtension{Modes: []uint8{utls.PskModeDHE}}, + &utls.SupportedVersionsExtension{Versions: []uint16{utls.VersionTLS13, utls.VersionTLS12}}, + }, + } +} + +// dial opens a connection to addr ("host:port"), through the transport's +// proxy when it has one, and completes the Bun TLS handshake with serverName +// for https. A proxy failure comes back as a *net.OpError whose Op is +// "proxyconnect" or "socks connect", the shape net/http uses, so the gateway +// classifies proxy failures of both transports alike. +func (t *BunTransport) dial(ctx context.Context, scheme, addr, serverName string) (net.Conn, error) { + var conn net.Conn + var err error + if t.proxy == nil { + conn, err = t.dialer.DialContext(ctx, "tcp", addr) + } else { + conn, err = t.dialProxy(ctx, addr) + } + if err != nil || scheme != "https" { + return conn, err + } + tlsConn := utls.UClient(conn, &utls.Config{ServerName: serverName}, utls.HelloCustom) + if err := tlsConn.ApplyPreset(bunClientHello()); err != nil { + conn.Close() + return nil, err + } + handshakeCtx, cancel := context.WithTimeout(ctx, bunHandshakeTimeout) + defer cancel() + if err := tlsConn.HandshakeContext(handshakeCtx); err != nil { + conn.Close() + return nil, err + } + return tlsConn, nil +} + +// dialProxy opens a tunnel to addr through the transport's proxy: an HTTP +// CONNECT for http and https proxies (the latter over standard TLS, which +// only the proxy sees), or a SOCKS5 CONNECT. Like net/http it lets a socks5 +// proxy resolve host names too, so socks5 and socks5h behave the same. +func (t *BunTransport) dialProxy(ctx context.Context, addr string) (net.Conn, error) { + op := "proxyconnect" + socks := t.proxy.Scheme == "socks5" || t.proxy.Scheme == "socks5h" + if socks { + op = "socks connect" + } + conn, err := t.dialer.DialContext(ctx, "tcp", proxyAddr(t.proxy)) + if err != nil { + return nil, &net.OpError{Op: op, Net: "tcp", Err: err} + } + stop := context.AfterFunc(ctx, func() { conn.Close() }) + _ = conn.SetDeadline(time.Now().Add(bunHandshakeTimeout)) + if t.proxy.Scheme == "https" { + tlsConn := tls.Client(conn, &tls.Config{ServerName: t.proxy.Hostname()}) + if err = tlsConn.HandshakeContext(ctx); err == nil { + conn = tlsConn + } + } + if err == nil { + if socks { + err = socks5Connect(conn, t.proxy.User, addr) + } else { + conn, err = httpConnect(conn, t.proxy.User, addr) + } + } + if !stop() && err == nil { + err = ctx.Err() + } + if err == nil { + err = conn.SetDeadline(time.Time{}) + } + if err != nil { + conn.Close() + return nil, &net.OpError{Op: op, Net: "tcp", Err: err} + } + return conn, nil +} + +// proxyAddr returns the "host:port" of a proxy URL, defaulting the port by +// scheme the way net/http does. +func proxyAddr(proxy *url.URL) string { + port := proxy.Port() + if port == "" { + switch proxy.Scheme { + case "https": + port = "443" + case "socks5", "socks5h": + port = "1080" + default: + port = "80" + } + } + return net.JoinHostPort(proxy.Hostname(), port) +} + +// httpConnect asks an HTTP proxy on conn for a tunnel to addr, with Basic +// Proxy-Authorization when user is set. Bytes the proxy sent past its 2xx +// answer are kept in front of the returned connection. +func httpConnect(conn net.Conn, user *url.Userinfo, addr string) (net.Conn, error) { + request := "CONNECT " + addr + " HTTP/1.1\r\nHost: " + addr + "\r\n" + if user != nil { + password, _ := user.Password() + request += "Proxy-Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(user.Username()+":"+password)) + "\r\n" + } + if _, err := io.WriteString(conn, request+"\r\n"); err != nil { + return conn, err + } + reader := bufio.NewReader(conn) + resp, err := http.ReadResponse(reader, &http.Request{Method: http.MethodConnect}) + if err != nil { + return conn, err + } + if resp.StatusCode/100 != 2 { + return conn, fmt.Errorf("proxy refused CONNECT: %s", resp.Status) + } + if reader.Buffered() > 0 { + return &bufferedConn{Conn: conn, reader: reader}, nil + } + return conn, nil +} + +// bufferedConn is a net.Conn whose reads drain reader first, for a tunnel the +// proxy already wrote into while answering CONNECT. +type bufferedConn struct { + net.Conn + reader *bufio.Reader +} + +func (c *bufferedConn) Read(p []byte) (int, error) { return c.reader.Read(p) } + +// socksReplies names the SOCKS5 reply codes (RFC 1928, section 6). +var socksReplies = map[byte]string{ + 1: "general SOCKS server failure", + 2: "connection not allowed by ruleset", + 3: "network unreachable", + 4: "host unreachable", + 5: "connection refused", + 6: "TTL expired", + 7: "command not supported", + 8: "address type not supported", +} + +// socks5Connect runs a SOCKS5 CONNECT to addr on conn (RFC 1928), offering +// username/password authentication (RFC 1929) when user is set. Host names +// are sent as is for the proxy to resolve. +func socks5Connect(conn net.Conn, user *url.Userinfo, addr string) error { + host, portText, err := net.SplitHostPort(addr) + if err != nil { + return err + } + port, err := strconv.ParseUint(portText, 10, 16) + if err != nil { + return fmt.Errorf("invalid port %q", portText) + } + methods := []byte{0x00} + if user != nil { + methods = append(methods, 0x02) + } + if _, err := conn.Write(append([]byte{5, byte(len(methods))}, methods...)); err != nil { + return err + } + reply := make([]byte, 2) + if _, err := io.ReadFull(conn, reply); err != nil { + return err + } + if reply[0] != 5 { + return fmt.Errorf("unexpected protocol version %d", reply[0]) + } + switch { + case reply[1] == 0x00: + case reply[1] == 0x02 && user != nil: + name := user.Username() + password, _ := user.Password() + if len(name) == 0 || len(name) > 255 || len(password) > 255 { + return errors.New("invalid username/password") + } + auth := append([]byte{1, byte(len(name))}, name...) + auth = append(append(auth, byte(len(password))), password...) + if _, err := conn.Write(auth); err != nil { + return err + } + if _, err := io.ReadFull(conn, reply); err != nil { + return err + } + if reply[1] != 0 { + return errors.New("username/password authentication failed") + } + default: + return errors.New("no acceptable authentication methods") + } + request := []byte{5, 1, 0} + if ip := net.ParseIP(host); ip == nil { + if len(host) > 255 { + return errors.New("FQDN too long") + } + request = append(append(request, 3, byte(len(host))), host...) + } else if ip4 := ip.To4(); ip4 != nil { + request = append(append(request, 1), ip4...) + } else { + request = append(append(request, 4), ip.To16()...) + } + if _, err := conn.Write(binary.BigEndian.AppendUint16(request, uint16(port))); err != nil { + return err + } + header := make([]byte, 4) + if _, err := io.ReadFull(conn, header); err != nil { + return err + } + if header[0] != 5 { + return fmt.Errorf("unexpected protocol version %d", header[0]) + } + if header[1] != 0 { + if text, ok := socksReplies[header[1]]; ok { + return errors.New(text) + } + return fmt.Errorf("unknown SOCKS reply %d", header[1]) + } + // Skip the bound address and port the proxy reports. + var skip int + switch header[3] { + case 1: + skip = net.IPv4len + case 4: + skip = net.IPv6len + case 3: + length := make([]byte, 1) + if _, err := io.ReadFull(conn, length); err != nil { + return err + } + skip = int(length[0]) + default: + return fmt.Errorf("unknown address type %d", header[3]) + } + _, err = io.ReadFull(conn, make([]byte, skip+2)) + return err +}