mirror of
https://github.com/D-Modem/WebOne-go.git
synced 2026-11-28 12:38:05 -08:00
Merge pull request #4 from D-Modem/claude/project-thread-3q6bwe
Fetch over HTTP/3 and pass gRPC through CONNECT tunnels
This commit is contained in:
11 files changed
+820
-36
No files matched your search
@@ -76,7 +76,7 @@ What works:
|
||||
supported too.
|
||||
* HTTP/1.0 and HTTP/1.1 clients, with keep-alive. The reply uses chunked
|
||||
transfer only for HTTP/1.1 clients.
|
||||
* Fetching over HTTPS (and HTTP/2), with HTTP→HTTPS upgrades,
|
||||
* Fetching over HTTPS, HTTP/2 and HTTP/3 (see *HTTP/3 and gRPC*), with HTTP→HTTPS upgrades,
|
||||
`[ForceHttps]`, and redirect loop ("carousel") handling.
|
||||
* Sets of edits (`[Edit:...]`): every condition and action WebOne has, .NET
|
||||
regular expressions included (through
|
||||
@@ -174,6 +174,44 @@ between an old browser and the proxy should be treated as readable. Clients
|
||||
that use the plain HTTP proxy instead are not affected: the browser asks for
|
||||
`http://`, and the proxy fetches over modern HTTPS.
|
||||
|
||||
## HTTP/3 and gRPC
|
||||
|
||||
**HTTP/3.** The proxy fetches sites over HTTP/3 (QUIC, through
|
||||
[quic-go](https://github.com/quic-go/quic-go)) the way browsers do: a site
|
||||
is first reached over TCP, and once it says in `Alt-Svc` that it has HTTP/3,
|
||||
later requests to it use QUIC. If QUIC fails (UDP blocked, say), the site
|
||||
goes back to TCP for ten minutes, and a request without a body is retried
|
||||
there at once. `RemoteHttpVersion` (and `AddRequestHttpVersion` in edit
|
||||
sets) now takes `3.0` too:
|
||||
|
||||
| Rule | Toward servers |
|
||||
|---|---|
|
||||
| `auto` (default), `>1.1` | HTTP/1.1, HTTP/2, and HTTP/3 once a site offers it |
|
||||
| `=3.0` or `>2.0` | HTTP/3 only, straight away (fails where a site has none) |
|
||||
| `<3.0` | HTTP/1.1 and HTTP/2, never HTTP/3 |
|
||||
| `=1.1`, `<2.0` | HTTP/1.1 only |
|
||||
|
||||
HTTP/3 needs TLS 1.3, so it is off when `SecurityProtocols` leaves TLS 1.3
|
||||
out, and it is not used through an `UpperProxy` (QUIC can't go through an
|
||||
HTTP proxy). `DnsServer` applies to it as to TCP.
|
||||
|
||||
**gRPC.** gRPC needs HTTP/2 from end to end, trailers included, so it can't
|
||||
go through the proxy's HTTP/1 handling. It goes through `CONNECT` instead,
|
||||
which is what gRPC clients do with a proxy (`https_proxy=http://host:8080`):
|
||||
|
||||
* A CONNECT to port 443 that the proxy decrypts: a client that offers only
|
||||
`h2` in ALPN (as gRPC clients do) gets HTTP/2 from the proxy, and its
|
||||
requests go on to the site over HTTP/2 untouched, streamed both ways with
|
||||
their trailers. The URL lists still apply; edit sets do not. Browsers
|
||||
offer HTTP/1.1 too (or no ALPN at all), so they are handled as before.
|
||||
* `[NonHttpSslServers]` tunnels: the proxy now asks the server for what the
|
||||
client asked for in ALPN and gives the client the server's answer, so
|
||||
gRPC (and anything else that needs ALPN) works through them.
|
||||
* `[ConnectPassThrough]` and plain non-HTTP tunnels pass bytes as they are,
|
||||
so gRPC already worked there.
|
||||
|
||||
gRPC-Web runs over HTTP/1.1 and goes through the ordinary proxy.
|
||||
|
||||
## Differences from WebOne
|
||||
|
||||
### Not available in Go
|
||||
@@ -234,6 +272,8 @@ These are bugs or rough edges in WebOne 0.19.0 that the port does not copy:
|
||||
| `SslTrustOwnCA` | `[SecureProxy]` | trust the proxy's CA for fetched sites too |
|
||||
| `DnsServer` | `[Server]` | look sites up through this DNS server (`host` or `host:port`) |
|
||||
|
||||
`RemoteHttpVersion` also takes `3.0` (see *HTTP/3 and gRPC*).
|
||||
|
||||
`SslProtocols` and `SslCipherSuites` work as in WebOne, with SSL 2.0 and 3.0
|
||||
served by retrossl (above).
|
||||
|
||||
@@ -244,7 +284,7 @@ The version is reported as `0.19.0-go`.
|
||||
```
|
||||
cmd/webone the program: command line, CA loading, start-up
|
||||
internal/config webone.conf: loading, [Include:], variables, sets of edits
|
||||
internal/proxy the server, request handling, CONNECT (old SSL through retrossl), internal pages, FTP, video
|
||||
internal/proxy the server, request handling, CONNECT (old SSL through retrossl, HTTP/2 for gRPC), HTTP/3 fetching, internal pages, FTP, video
|
||||
internal/certs the CA, site certificates (MD5/SHA-1 signing), the BBS's CA
|
||||
internal/textenc code pages
|
||||
internal/rx .NET-style regular expressions, cached
|
||||
@@ -255,7 +295,8 @@ internal/logx the log, in WebOne's format
|
||||
certificates (including a BBS-style sub-CA chain), and the proxy end to end:
|
||||
HTTP/1.0 with edits and a code page, HTTPS fetching, alternate mode,
|
||||
keep-alive with chunked replies, internal pages, CONNECT with MITM (SSL
|
||||
2.0 and 3.0 clients included), and pass-through. retrossl has its own tests.
|
||||
2.0 and 3.0 clients included), gRPC-style HTTP/2 streams through CONNECT,
|
||||
HTTP/3 fetching after Alt-Svc, and pass-through. retrossl has its own tests.
|
||||
|
||||
## Licence
|
||||
|
||||
|
||||
@@ -7,4 +7,14 @@ require (
|
||||
golang.org/x/text v0.44.0
|
||||
)
|
||||
|
||||
require github.com/D-Modem/retrossl v0.0.0-20261111132527-5c74d8027d9e
|
||||
require (
|
||||
github.com/D-Modem/retrossl v0.0.0-20261111132527-5c74d8027d9e
|
||||
github.com/quic-go/quic-go v0.65.0
|
||||
golang.org/x/net v0.62.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
golang.org/x/crypto v0.58.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
)
|
||||
@@ -2,5 +2,23 @@ github.com/D-Modem/retrossl v0.0.0-20261111132527-5c74d8027d9e h1:4v6nEr6aSiE8H/
|
||||
github.com/D-Modem/retrossl v0.0.0-20261111132527-5c74d8027d9e/go.mod h1:+/qpHsaYk4DslA351ZMumscq9/Iwl/K5vS4PhUVLOR8=
|
||||
github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8=
|
||||
github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4TzM7MFjy0=
|
||||
github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.65.0 h1:BJQSjdTvLPLmWtaCupUphRbgxgpZhdO/GMpr9Eoe3B4=
|
||||
github.com/quic-go/quic-go v0.65.0/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
|
||||
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
+58
-20
@@ -103,13 +103,20 @@ func (t *transit) connectSecure() {
|
||||
return
|
||||
}
|
||||
c := t.established(true)
|
||||
tc, agreed, err := t.s.serveSecure(c, cfg, rc)
|
||||
tc, agreed, err := t.s.serveSecure(c, withH2(cfg), rc)
|
||||
if err != nil {
|
||||
t.log.Printf("!SSL Handshake failed: %s", handshakeError(err))
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
log := logx.New()
|
||||
if negotiated(tc) == "h2" {
|
||||
log.Printf(">SSL %s: %s, HTTP/2", host, agreed)
|
||||
t.s.serveH2(tc, t.req.RawURL)
|
||||
tc.Close()
|
||||
log.Printf("<Close SSL.")
|
||||
return
|
||||
}
|
||||
log.Printf(">SSL %s: %s", host, agreed)
|
||||
t.s.handleConn(tc, bufio.NewReaderSize(tc, 16*1024), true, host, log)
|
||||
tc.Close()
|
||||
@@ -193,26 +200,49 @@ func (t *transit) connectNonHttp(useTLS bool) {
|
||||
t.log.Printf(" Redirect connection to %s.", dst)
|
||||
}
|
||||
}
|
||||
var remote net.Conn
|
||||
var err error
|
||||
if useTLS {
|
||||
if cfg == nil {
|
||||
t.log.Printf("<SSL is disabled, goodbye.")
|
||||
return
|
||||
}
|
||||
tc, agreed, err := t.s.serveSecure(c, cfg, rc)
|
||||
if err != nil {
|
||||
t.log.Printf("!SSL client handshake failed: %s", handshakeError(err))
|
||||
// The server is reached during the client's handshake, offering
|
||||
// what the client offers in ALPN, so they agree on the same
|
||||
// protocol (gRPC needs "h2").
|
||||
base := cfg
|
||||
cfg = base.Clone()
|
||||
cfg.GetConfigForClient = func(h *tls.ClientHelloInfo) (*tls.Config, error) {
|
||||
if len(h.SupportedProtos) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if remote, err = t.dialTLS(target, parts[0], h.SupportedProtos); err != nil {
|
||||
return nil, nil // the handshake ends; the error is told after
|
||||
}
|
||||
cc := base.Clone()
|
||||
if p := negotiated(remote); p != "" {
|
||||
cc.NextProtos = []string{p}
|
||||
}
|
||||
return cc, nil
|
||||
}
|
||||
tc, agreed, herr := t.s.serveSecure(c, cfg, rc)
|
||||
if herr != nil {
|
||||
t.log.Printf("!SSL client handshake failed: %s", handshakeError(herr))
|
||||
if remote != nil {
|
||||
remote.Close()
|
||||
}
|
||||
return
|
||||
}
|
||||
if p := negotiated(tc); p != "" {
|
||||
agreed += ", " + p
|
||||
}
|
||||
t.log.Printf(" SSL: %s", agreed)
|
||||
c = tc
|
||||
}
|
||||
remote, err := t.s.up.dialer.Dial("tcp", target)
|
||||
if err == nil && useTLS {
|
||||
rc := tls.Client(remote, t.upstreamTLS(parts[0]))
|
||||
if err = rc.Handshake(); err != nil {
|
||||
remote.Close()
|
||||
if remote == nil && err == nil {
|
||||
remote, err = t.dialTLS(target, parts[0], nil)
|
||||
}
|
||||
remote = rc
|
||||
} else {
|
||||
remote, err = t.s.up.dialer.Dial("tcp", target)
|
||||
}
|
||||
if err != nil {
|
||||
t.log.Printf(" Connection failed: %v.", err)
|
||||
@@ -242,15 +272,7 @@ func (t *transit) connectDecrypt(server string) {
|
||||
c := t.established(false)
|
||||
defer c.Close()
|
||||
t.log.Printf(">Decrypt: %s", server)
|
||||
remote, err := t.s.up.dialer.Dial("tcp", server)
|
||||
if err == nil {
|
||||
t.log.Printf(" D tunnel connected.")
|
||||
rc := tls.Client(remote, t.upstreamTLS(host))
|
||||
if err = rc.Handshake(); err != nil {
|
||||
remote.Close()
|
||||
}
|
||||
remote = rc
|
||||
}
|
||||
remote, err := t.dialTLS(server, host, nil)
|
||||
if err != nil {
|
||||
t.log.Printf(" D connection failed: %v.", err)
|
||||
io.WriteString(c, "The proxy server is unable to connect with decryption: "+err.Error()+"\r\n")
|
||||
@@ -261,6 +283,22 @@ func (t *transit) connectDecrypt(server string) {
|
||||
t.log.Printf(" D connection to %s closed.", t.req.RawURL)
|
||||
}
|
||||
|
||||
// dialTLS connects to a server over TLS, offering protos in ALPN.
|
||||
func (t *transit) dialTLS(addr, host string, protos []string) (net.Conn, error) {
|
||||
raw, err := t.s.up.dialer.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg := t.upstreamTLS(host)
|
||||
cfg.NextProtos = protos
|
||||
tc := tls.Client(raw, cfg)
|
||||
if err := tc.Handshake(); err != nil {
|
||||
raw.Close()
|
||||
return nil, err
|
||||
}
|
||||
return tc, nil
|
||||
}
|
||||
|
||||
// upstreamTLS is the TLS client configuration toward a server.
|
||||
func (t *transit) upstreamTLS(host string) *tls.Config {
|
||||
c := t.s.up.tlsCfg.Clone()
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/logx"
|
||||
"golang.org/x/net/http2"
|
||||
)
|
||||
|
||||
// HTTP/2 inside CONNECT tunnels, for gRPC.
|
||||
//
|
||||
// Old browsers and today's ones offer HTTP/1.1 (or nothing) in ALPN, and
|
||||
// they go through the proxy's usual handling, edits and all. gRPC needs
|
||||
// HTTP/2 end to end, with trailers, and gRPC clients offer only "h2". Those
|
||||
// clients get HTTP/2 from the proxy, and their requests go on to the server
|
||||
// over HTTP/2 untouched, streamed both ways.
|
||||
|
||||
// h2Only: a client's ALPN list asks for HTTP/2 and not HTTP/1.1.
|
||||
func h2Only(protos []string) bool {
|
||||
return slices.Contains(protos, "h2") && !slices.Contains(protos, "http/1.1")
|
||||
}
|
||||
|
||||
// withH2 lets clients that speak only HTTP/2 have it on c.
|
||||
func withH2(c *tls.Config) *tls.Config {
|
||||
c.GetConfigForClient = func(h *tls.ClientHelloInfo) (*tls.Config, error) {
|
||||
if !h2Only(h.SupportedProtos) {
|
||||
return nil, nil
|
||||
}
|
||||
cc := c.Clone()
|
||||
cc.GetConfigForClient = nil
|
||||
cc.NextProtos = []string{"h2"}
|
||||
return cc, nil
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// negotiated is the ALPN protocol agreed on c, if c is Go's TLS.
|
||||
func negotiated(c net.Conn) string {
|
||||
if tc, ok := c.(*tls.Conn); ok {
|
||||
return tc.ConnectionState().NegotiatedProtocol
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// serveH2 serves HTTP/2 on a client's tunnel to target ("host:443"),
|
||||
// passing every request on to the server.
|
||||
func (s *Server) serveH2(c net.Conn, target string) {
|
||||
srv := &http2.Server{IdleTimeout: 5 * time.Minute, PermitProhibitedCipherSuites: true}
|
||||
srv.ServeConn(c, &http2.ServeConnOpts{Handler: s.h2Handler(target)})
|
||||
}
|
||||
|
||||
// h2Handler passes HTTP/2 requests to target over HTTP/2, as a reverse
|
||||
// proxy that keeps trailers and flushes at once (what gRPC needs).
|
||||
func (s *Server) h2Handler(target string) http.Handler {
|
||||
rp := &httputil.ReverseProxy{
|
||||
Rewrite: func(pr *httputil.ProxyRequest) {
|
||||
pr.Out.URL.Scheme = "https"
|
||||
pr.Out.URL.Host = target
|
||||
pr.Out.Host = pr.In.Host
|
||||
},
|
||||
Transport: s.up.h2,
|
||||
FlushInterval: -1,
|
||||
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
logx.Std.Printf(" HTTP/2 to %s failed: %v.", target, err)
|
||||
if isGRPC(r) {
|
||||
// gRPC clients read the status from headers, not the body
|
||||
w.Header().Set("Content-Type", "application/grpc")
|
||||
w.Header().Set("Grpc-Status", "14") // UNAVAILABLE
|
||||
w.Header().Set("Grpc-Message", "WebOne: "+err.Error())
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
http.Error(w, "WebOne: "+err.Error(), http.StatusBadGateway)
|
||||
},
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
host := r.Host
|
||||
if host == "" {
|
||||
host = target
|
||||
}
|
||||
u := "https://" + host + r.URL.RequestURI()
|
||||
log := logx.New()
|
||||
kind := "HTTP/2"
|
||||
if isGRPC(r) {
|
||||
kind = "gRPC"
|
||||
}
|
||||
log.Printf(">[%s] %s %s (%s %s)", target, r.Method, u, kind, r.RemoteAddr)
|
||||
if containsAny(u, s.cfg.UrlBlackList) ||
|
||||
(len(s.cfg.UrlWhiteList) > 0 && !containsAny(u, s.cfg.UrlWhiteList)) {
|
||||
log.Printf("<Blocked by URL list.")
|
||||
http.Error(w, "WebOne: this URL is not allowed.", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
rp.ServeHTTP(w, r)
|
||||
log.Printf("<Done.")
|
||||
})
|
||||
}
|
||||
|
||||
func isGRPC(r *http.Request) bool {
|
||||
return strings.HasPrefix(r.Header.Get("Content-Type"), "application/grpc")
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/http2"
|
||||
)
|
||||
|
||||
// grpcLike is a server that answers like gRPC: it echoes each request
|
||||
// message as it comes, then ends with trailers.
|
||||
func grpcLike(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.ProtoMajor != 2 {
|
||||
http.Error(w, "HTTP/2 only", http.StatusHTTPVersionNotSupported)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/grpc")
|
||||
w.Header().Set("Trailer", "Grpc-Status")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
br := bufio.NewReader(r.Body)
|
||||
for {
|
||||
line, err := br.ReadString('\n')
|
||||
if line != "" {
|
||||
fmt.Fprintf(w, "echo %s", line)
|
||||
w.(http.Flusher).Flush()
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
w.Header().Set("Grpc-Status", "0")
|
||||
}))
|
||||
srv.EnableHTTP2 = true
|
||||
srv.StartTLS()
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
// streamH2 sends two messages over one HTTP/2 stream, reading each echo
|
||||
// before sending the next, so the proxy must stream both ways.
|
||||
func streamH2(t *testing.T, tr *http2.Transport, url string) {
|
||||
t.Helper()
|
||||
pr, pw := io.Pipe()
|
||||
req, _ := http.NewRequest("POST", url, pr)
|
||||
req.Header.Set("Content-Type", "application/grpc")
|
||||
req.Header.Set("TE", "trailers")
|
||||
go io.WriteString(pw, "one\n") // the first message goes with the request
|
||||
resp, err := tr.RoundTrip(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
}
|
||||
br := bufio.NewReader(resp.Body)
|
||||
if l, _ := br.ReadString('\n'); l != "echo one\n" {
|
||||
t.Fatalf("first reply %q", l)
|
||||
}
|
||||
io.WriteString(pw, "two\n")
|
||||
if l, _ := br.ReadString('\n'); l != "echo two\n" {
|
||||
t.Fatalf("second reply %q", l)
|
||||
}
|
||||
pw.Close()
|
||||
io.Copy(io.Discard, br)
|
||||
if got := resp.Trailer.Get("Grpc-Status"); got != "0" {
|
||||
t.Errorf("trailer Grpc-Status %q, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConnectGRPC: a client that offers only h2 gets HTTP/2 inside a
|
||||
// CONNECT tunnel, and its stream reaches the server with trailers intact.
|
||||
func TestConnectGRPC(t *testing.T) {
|
||||
up := grpcLike(t)
|
||||
s, addr := startServer(t, "ValidateCertificates=no\n[SecureProxy]\nSslHashAlgorithm=SHA256\n")
|
||||
upAddr := up.Listener.Addr().String()
|
||||
s.up.h2.DialContext = func(ctx context.Context, network, a string) (net.Conn, error) {
|
||||
if a != "site.invalid:443" {
|
||||
return nil, fmt.Errorf("dialed %s", a)
|
||||
}
|
||||
return (&net.Dialer{}).DialContext(ctx, network, upAddr)
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
pool.AddCert(s.CA.Cert)
|
||||
tr := &http2.Transport{
|
||||
DialTLSContext: func(ctx context.Context, network, _ string, _ *tls.Config) (net.Conn, error) {
|
||||
c, br := connectTunnel(t, addr)
|
||||
c.SetDeadline(time.Time{})
|
||||
tc := tls.Client(&bufConn{Conn: c, r: br}, &tls.Config{ServerName: "site.invalid", RootCAs: pool, NextProtos: []string{"h2"}})
|
||||
if err := tc.Handshake(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p := tc.ConnectionState().NegotiatedProtocol; p != "h2" {
|
||||
return nil, fmt.Errorf("ALPN %q", p)
|
||||
}
|
||||
return tc, nil
|
||||
},
|
||||
}
|
||||
defer tr.CloseIdleConnections()
|
||||
streamH2(t, tr, "https://site.invalid/echo.Echo/Stream")
|
||||
|
||||
// a browser (http/1.1 offered too) still gets HTTP/1.1
|
||||
c, br := connectTunnel(t, addr)
|
||||
tc := tls.Client(&bufConn{Conn: c, r: br}, &tls.Config{ServerName: "site.invalid", RootCAs: pool, NextProtos: []string{"h2", "http/1.1"}})
|
||||
if err := tc.Handshake(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p := tc.ConnectionState().NegotiatedProtocol; p != "" {
|
||||
t.Errorf("browser got ALPN %q", p)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNonHttpTunnelALPN: a decrypting non-HTTP tunnel agrees on the
|
||||
// server's ALPN choice, so gRPC through it gets HTTP/2.
|
||||
func TestNonHttpTunnelALPN(t *testing.T) {
|
||||
up := grpcLike(t)
|
||||
upAddr := up.Listener.Addr().String()
|
||||
addr, _ := startProxy(t, "ValidateCertificates=no\nAllowNonHttpsCONNECT=yes\n[SecureProxy]\nSslHashAlgorithm=SHA256\n[NonHttpSslServers]\n127.0.0.1\n")
|
||||
tr := &http2.Transport{
|
||||
DialTLSContext: func(ctx context.Context, network, _ string, _ *tls.Config) (net.Conn, error) {
|
||||
c, err := net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", upAddr, upAddr)
|
||||
br := bufio.NewReader(c)
|
||||
if line, _ := br.ReadString('\n'); !strings.HasPrefix(line, "HTTP/1.1 200") {
|
||||
return nil, fmt.Errorf("CONNECT reply: %q", line)
|
||||
}
|
||||
for {
|
||||
if l, err := br.ReadString('\n'); err != nil || l == "\r\n" {
|
||||
break
|
||||
}
|
||||
}
|
||||
tc := tls.Client(&bufConn{Conn: c, r: br}, &tls.Config{InsecureSkipVerify: true, NextProtos: []string{"h2"}})
|
||||
if err := tc.Handshake(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p := tc.ConnectionState().NegotiatedProtocol; p != "h2" {
|
||||
return nil, fmt.Errorf("ALPN %q", p)
|
||||
}
|
||||
return tc, nil
|
||||
},
|
||||
}
|
||||
defer tr.CloseIdleConnections()
|
||||
streamH2(t, tr, "https://"+upAddr+"/echo.Echo/Stream")
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/config"
|
||||
"github.com/D-Modem/webone-go/internal/logx"
|
||||
"github.com/quic-go/quic-go"
|
||||
"github.com/quic-go/quic-go/http3"
|
||||
)
|
||||
|
||||
// h3Broken is how long a server whose HTTP/3 failed is reached over TCP
|
||||
// only.
|
||||
const h3Broken = 10 * time.Minute
|
||||
|
||||
// h3up fetches from servers over HTTP/3 (QUIC). It learns which servers
|
||||
// have HTTP/3 from their Alt-Svc headers, as browsers do.
|
||||
type h3up struct {
|
||||
client *http.Client
|
||||
tr *http3.Transport
|
||||
resolver *net.Resolver
|
||||
|
||||
sockOnce sync.Once
|
||||
sock *quic.Transport // one UDP socket for every server
|
||||
sockErr error
|
||||
|
||||
mu sync.Mutex
|
||||
alt map[string]altSvc // "host:port" → where its HTTP/3 is
|
||||
broken map[string]time.Time // "host:port" → TCP only until then
|
||||
}
|
||||
|
||||
type altSvc struct {
|
||||
addr string // "host:port" or ":port" (the same host)
|
||||
until time.Time
|
||||
}
|
||||
|
||||
// newH3 makes the HTTP/3 client, or gives nil when HTTP/3 can't be used:
|
||||
// through an upper proxy (QUIC can't go through one), or when
|
||||
// SecurityProtocols leaves out TLS 1.3.
|
||||
func newH3(base *tls.Config, resolver *net.Resolver, timeout time.Duration, viaProxy bool) *h3up {
|
||||
if viaProxy || (base.MaxVersion != 0 && base.MaxVersion < tls.VersionTLS13) {
|
||||
return nil
|
||||
}
|
||||
h := &h3up{
|
||||
resolver: resolver,
|
||||
alt: map[string]altSvc{},
|
||||
broken: map[string]time.Time{},
|
||||
}
|
||||
if h.resolver == nil {
|
||||
h.resolver = net.DefaultResolver
|
||||
}
|
||||
tc := base.Clone()
|
||||
tc.MinVersion, tc.MaxVersion = tls.VersionTLS13, 0
|
||||
h.tr = &http3.Transport{
|
||||
TLSClientConfig: tc,
|
||||
QUICConfig: &quic.Config{HandshakeIdleTimeout: min(timeout, 10*time.Second), MaxIdleTimeout: 90 * time.Second},
|
||||
DisableCompression: true, // decompressed in send, as asked
|
||||
Dial: h.dial,
|
||||
}
|
||||
h.client = &http.Client{
|
||||
Transport: h.tr,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// dial opens a QUIC connection to addr, or to where its Alt-Svc said.
|
||||
func (h *h3up) dial(ctx context.Context, addr string, tc *tls.Config, qc *quic.Config) (*quic.Conn, error) {
|
||||
h.sockOnce.Do(func() {
|
||||
var c *net.UDPConn
|
||||
if c, h.sockErr = net.ListenUDP("udp", nil); h.sockErr == nil {
|
||||
h.sock = &quic.Transport{Conn: c}
|
||||
}
|
||||
})
|
||||
if h.sockErr != nil {
|
||||
return nil, h.sockErr
|
||||
}
|
||||
target := addr
|
||||
if a, ok := h.altFor(addr); ok {
|
||||
target = a
|
||||
}
|
||||
host, port, err := net.SplitHostPort(target)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pn, err := strconv.Atoi(port)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ips, err := h.resolver.LookupNetIP(ctx, "ip", host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var last error
|
||||
for _, ip := range ips {
|
||||
ua := net.UDPAddrFromAddrPort(netip.AddrPortFrom(ip.Unmap(), uint16(pn)))
|
||||
qc, err := h.sock.DialEarly(ctx, ua, tc, qc)
|
||||
if err == nil {
|
||||
logx.Std.Printf(" HTTP/3 (QUIC) connection to %s.", target)
|
||||
return qc, nil
|
||||
}
|
||||
last = err
|
||||
}
|
||||
if last == nil {
|
||||
last = errors.New("no address for " + host)
|
||||
}
|
||||
return nil, last
|
||||
}
|
||||
|
||||
// altFor is where host:port's HTTP/3 is, if it said so lately.
|
||||
func (h *h3up) altFor(hostport string) (string, bool) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
a, ok := h.alt[hostport]
|
||||
if !ok || time.Now().After(a.until) {
|
||||
delete(h.alt, hostport)
|
||||
return "", false
|
||||
}
|
||||
if strings.HasPrefix(a.addr, ":") {
|
||||
host, _, _ := net.SplitHostPort(hostport)
|
||||
return net.JoinHostPort(host, a.addr[1:]), true
|
||||
}
|
||||
return a.addr, true
|
||||
}
|
||||
|
||||
// known: hostport has said it has HTTP/3, and it hasn't failed lately.
|
||||
func (h *h3up) known(hostport string) bool {
|
||||
h.mu.Lock()
|
||||
until, bad := h.broken[hostport]
|
||||
if bad && time.Now().After(until) {
|
||||
delete(h.broken, hostport)
|
||||
bad = false
|
||||
}
|
||||
h.mu.Unlock()
|
||||
if bad {
|
||||
return false
|
||||
}
|
||||
_, ok := h.altFor(hostport)
|
||||
return ok
|
||||
}
|
||||
|
||||
// learn reads a response's Alt-Svc headers for hostport.
|
||||
func (h *h3up) learn(hostport string, values []string) {
|
||||
if len(values) == 0 {
|
||||
return
|
||||
}
|
||||
a, clear, ok := parseAltSvcH3(values, time.Now())
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
switch {
|
||||
case clear:
|
||||
delete(h.alt, hostport)
|
||||
case ok:
|
||||
h.alt[hostport] = a
|
||||
}
|
||||
}
|
||||
|
||||
// failed marks hostport's HTTP/3 as not working for a while.
|
||||
func (h *h3up) failed(hostport string) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
delete(h.alt, hostport)
|
||||
h.broken[hostport] = time.Now().Add(h3Broken)
|
||||
}
|
||||
|
||||
// parseAltSvcH3 finds the "h3" entry in Alt-Svc headers (RFC 7838), such
|
||||
// as `h3=":443"; ma=86400, h3-29=":443"`. clear is Alt-Svc: clear.
|
||||
func parseAltSvcH3(values []string, now time.Time) (a altSvc, clear, ok bool) {
|
||||
for _, v := range values {
|
||||
for entry := range strings.SplitSeq(v, ",") {
|
||||
entry = strings.TrimSpace(entry)
|
||||
if strings.EqualFold(entry, "clear") {
|
||||
return altSvc{}, true, false
|
||||
}
|
||||
params := strings.Split(entry, ";")
|
||||
proto, auth, found := strings.Cut(strings.TrimSpace(params[0]), "=")
|
||||
if !found || proto != "h3" {
|
||||
continue
|
||||
}
|
||||
auth = strings.Trim(strings.TrimSpace(auth), `"`)
|
||||
if _, _, err := net.SplitHostPort(auth); err != nil {
|
||||
continue
|
||||
}
|
||||
maxAge := 24 * time.Hour
|
||||
for _, p := range params[1:] {
|
||||
k, val, _ := strings.Cut(strings.TrimSpace(p), "=")
|
||||
if strings.EqualFold(k, "ma") {
|
||||
if n, err := strconv.Atoi(strings.Trim(val, `"`)); err == nil {
|
||||
maxAge = time.Duration(n) * time.Second
|
||||
}
|
||||
}
|
||||
}
|
||||
if maxAge <= 0 {
|
||||
continue
|
||||
}
|
||||
return altSvc{addr: auth, until: now.Add(maxAge)}, false, true
|
||||
}
|
||||
}
|
||||
return altSvc{}, false, false
|
||||
}
|
||||
|
||||
// httpVersions reads a RemoteHttpVersion rule ("auto", "=1.1", ">2.0",
|
||||
// "<3.0" ...) as the HTTP versions it lets the proxy use toward servers.
|
||||
func httpVersions(rule string) (h1, h2, h3 bool) {
|
||||
if rule == "" || rule[0] == 'a' || len(rule) < 2 {
|
||||
return true, true, true
|
||||
}
|
||||
maj, minor, ok := config.ParseVersion(rule[1:])
|
||||
if !ok {
|
||||
return true, true, true
|
||||
}
|
||||
want := maj*10 + minor
|
||||
in := func(v int) bool {
|
||||
switch rule[0] {
|
||||
case '>':
|
||||
return v > want
|
||||
case '<':
|
||||
return v < want
|
||||
default:
|
||||
return v == want
|
||||
}
|
||||
}
|
||||
h1, h2, h3 = in(10) || in(11), in(20), in(30)
|
||||
if !h1 && !h2 && !h3 {
|
||||
return true, false, false
|
||||
}
|
||||
return h1, h2, h3
|
||||
}
|
||||
|
||||
// hostPort is u's "host:port", with the scheme's default port.
|
||||
func hostPort(scheme, host string) string {
|
||||
if _, _, err := net.SplitHostPort(host); err == nil {
|
||||
return host
|
||||
}
|
||||
if scheme == "https" {
|
||||
return net.JoinHostPort(host, "443")
|
||||
}
|
||||
return net.JoinHostPort(host, "80")
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/logx"
|
||||
"github.com/quic-go/quic-go/http3"
|
||||
)
|
||||
|
||||
func TestHTTPVersions(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
rule string
|
||||
h1, h2, h3 bool
|
||||
}{
|
||||
{"auto", true, true, true},
|
||||
{"=1.1", true, false, false},
|
||||
{"=1.0", true, false, false},
|
||||
{"=2.0", false, true, false},
|
||||
{"=3.0", false, false, true},
|
||||
{">1.1", false, true, true},
|
||||
{">2.0", false, false, true},
|
||||
{"<3.0", true, true, false},
|
||||
{"<2.0", true, false, false},
|
||||
{"<1.0", true, false, false}, // nothing: HTTP/1.1
|
||||
} {
|
||||
h1, h2, h3 := httpVersions(c.rule)
|
||||
if h1 != c.h1 || h2 != c.h2 || h3 != c.h3 {
|
||||
t.Errorf("%s: %v %v %v", c.rule, h1, h2, h3)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAltSvc(t *testing.T) {
|
||||
now := time.Now()
|
||||
a, clear, ok := parseAltSvcH3([]string{`h3-29=":443"; ma=10, h3=":8443"; ma=60`}, now)
|
||||
if !ok || clear || a.addr != ":8443" || !a.until.Equal(now.Add(time.Minute)) {
|
||||
t.Errorf("got %+v %v %v", a, clear, ok)
|
||||
}
|
||||
if _, _, ok := parseAltSvcH3([]string{`h2=":443"`}, now); ok {
|
||||
t.Error("h2 taken as h3")
|
||||
}
|
||||
if _, clear, _ := parseAltSvcH3([]string{"clear"}, now); !clear {
|
||||
t.Error("clear not seen")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHTTP3Upstream: a server that says it has HTTP/3 in Alt-Svc is
|
||||
// reached over HTTP/3 from then on, and "=3.0" uses it at once.
|
||||
func TestHTTP3Upstream(t *testing.T) {
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Alt-Svc", `h3=":`+r.URL.Query().Get("port")+`"; ma=60`)
|
||||
io.WriteString(w, r.Proto)
|
||||
})
|
||||
tcp := httptest.NewUnstartedServer(handler)
|
||||
tcp.EnableHTTP2 = true
|
||||
tcp.StartTLS()
|
||||
defer tcp.Close()
|
||||
port := tcp.Listener.Addr().(*net.TCPAddr).Port
|
||||
udp, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port})
|
||||
if err != nil {
|
||||
t.Skipf("UDP port %d: %v", port, err)
|
||||
}
|
||||
h3srv := &http3.Server{Handler: handler, TLSConfig: http3.ConfigureTLSConfig(tcp.TLS.Clone())}
|
||||
go h3srv.Serve(udp)
|
||||
defer h3srv.Close()
|
||||
|
||||
s, _ := startServer(t, "ValidateCertificates=no\n")
|
||||
if s.up.h3 == nil {
|
||||
t.Fatal("no HTTP/3 client")
|
||||
}
|
||||
url := "https://127.0.0.1:" + strconv.Itoa(port) + "/?port=" + strconv.Itoa(port)
|
||||
get := func(rule string) string {
|
||||
t.Helper()
|
||||
req, _ := http.NewRequest("GET", url, nil)
|
||||
resp, err := s.up.do(req, rule, logx.Std)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", rule, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return string(b)
|
||||
}
|
||||
if got := get("auto"); got != "HTTP/2.0" {
|
||||
t.Errorf("first request: %s", got)
|
||||
}
|
||||
if got := get("auto"); got != "HTTP/3.0" {
|
||||
t.Errorf("after Alt-Svc: %s", got)
|
||||
}
|
||||
if got := get("<3.0"); got != "HTTP/2.0" {
|
||||
t.Errorf("<3.0: %s", got)
|
||||
}
|
||||
s.up.h3.mu.Lock()
|
||||
clear(s.up.h3.alt)
|
||||
s.up.h3.mu.Unlock()
|
||||
if got := get("=3.0"); got != "HTTP/3.0" {
|
||||
t.Errorf("=3.0: %s", got)
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,13 @@ import (
|
||||
// startProxy runs a proxy with the given configuration text; it returns
|
||||
// the proxy's address and the CA.
|
||||
func startProxy(t *testing.T, conf string) (string, *certs.CA) {
|
||||
t.Helper()
|
||||
s, addr := startServer(t, conf)
|
||||
return addr, s.CA
|
||||
}
|
||||
|
||||
// startServer is startProxy giving the server itself.
|
||||
func startServer(t *testing.T, conf string) (*Server, string) {
|
||||
t.Helper()
|
||||
logx.SetConsole(io.Discard)
|
||||
dir := t.TempDir()
|
||||
@@ -57,7 +64,7 @@ func startProxy(t *testing.T, conf string) (string, *certs.CA) {
|
||||
}
|
||||
go s.Serve(ln)
|
||||
t.Cleanup(s.Stop)
|
||||
return ln.Addr().String(), ca
|
||||
return s, ln.Addr().String()
|
||||
}
|
||||
|
||||
// rawGet sends a request by hand (as an old browser would) and returns the
|
||||
|
||||
+59
-10
@@ -27,6 +27,9 @@ type upstream struct {
|
||||
auto *http.Client // HTTP/2 when the server offers it
|
||||
dialer *net.Dialer
|
||||
tlsCfg *tls.Config
|
||||
proxy func(*http.Request) (*url.URL, error)
|
||||
h3 *h3up // HTTP/3; nil when it can't be used
|
||||
h2 *http.Transport // HTTP/2 only, for gRPC and other HTTP/2-only clients
|
||||
}
|
||||
|
||||
func newUpstream(cfg *config.Config, extraRoots []*x509.Certificate) (*upstream, error) {
|
||||
@@ -69,6 +72,7 @@ func newUpstream(cfg *config.Config, extraRoots []*x509.Certificate) (*upstream,
|
||||
}
|
||||
|
||||
var proxy func(*http.Request) (*url.URL, error)
|
||||
explicitProxy := false
|
||||
switch strings.ToLower(strings.TrimSpace(cfg.UpperProxy)) {
|
||||
case "":
|
||||
proxy = http.ProxyFromEnvironment
|
||||
@@ -83,6 +87,7 @@ func newUpstream(cfg *config.Config, extraRoots []*x509.Certificate) (*upstream,
|
||||
return nil, fmt.Errorf("bad UpperProxy %q: %v", cfg.UpperProxy, err)
|
||||
}
|
||||
proxy = http.ProxyURL(pu)
|
||||
explicitProxy = true
|
||||
}
|
||||
|
||||
mk := func(h2 bool) *http.Client {
|
||||
@@ -109,6 +114,12 @@ func newUpstream(cfg *config.Config, extraRoots []*x509.Certificate) (*upstream,
|
||||
}
|
||||
u.h1 = mk(false)
|
||||
u.auto = mk(true)
|
||||
u.proxy = proxy
|
||||
u.h2 = mk(true).Transport.(*http.Transport)
|
||||
u.h2.Protocols = new(http.Protocols)
|
||||
u.h2.Protocols.SetHTTP2(true)
|
||||
u.h2.MaxIdleConnsPerHost = 2
|
||||
u.h3 = newH3(u.tlsCfg, u.dialer.Resolver, timeout, explicitProxy)
|
||||
return u, nil
|
||||
}
|
||||
|
||||
@@ -184,15 +195,7 @@ func (s *Server) send(op *operation) error {
|
||||
req.Header["User-Agent"] = []string{""} // Go would send its own
|
||||
}
|
||||
|
||||
client := s.up.auto
|
||||
switch v := op.HTTPVersion; {
|
||||
case v == "auto":
|
||||
case strings.HasSuffix(v, "1.1"), strings.HasSuffix(v, "1.0"):
|
||||
if v[0] != '>' {
|
||||
client = s.up.h1
|
||||
}
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
resp, err := s.up.do(req, op.HTTPVersion, op.log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -231,6 +234,52 @@ func (s *Server) send(op *operation) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// do sends req over the HTTP versions rule allows: HTTP/3 when the
|
||||
// server has said it has it (or when the rule allows nothing else), HTTP/2
|
||||
// or HTTP/1.1 otherwise.
|
||||
func (u *upstream) do(req *http.Request, rule string, log logger) (*http.Response, error) {
|
||||
h1, h2, h3 := httpVersions(rule)
|
||||
hp := hostPort(req.URL.Scheme, req.URL.Host)
|
||||
if h3 && u.useH3(req) && ((!h1 && !h2) || u.h3.known(hp)) {
|
||||
resp, err := u.h3.client.Do(req)
|
||||
if err == nil || (!h1 && !h2) {
|
||||
return resp, err
|
||||
}
|
||||
u.h3.failed(hp)
|
||||
log.Printf(" HTTP/3 to %s failed (%v), using TCP.", hp, err)
|
||||
if req.Body != nil && req.Body != http.NoBody {
|
||||
if req.GetBody == nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.Body, err = req.GetBody(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
client := u.auto
|
||||
if h1 && !h2 {
|
||||
client = u.h1
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err == nil && h3 && u.h3 != nil {
|
||||
u.h3.learn(hp, resp.Header.Values("Alt-Svc"))
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// useH3: HTTP/3 can carry req (HTTPS, and no upper proxy for it).
|
||||
func (u *upstream) useH3(req *http.Request) bool {
|
||||
if u.h3 == nil || req.URL.Scheme != "https" {
|
||||
return false
|
||||
}
|
||||
if u.proxy != nil {
|
||||
if p, err := u.proxy(req); err != nil || p != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// decodeError: the server's compressed content cannot be read
|
||||
// (InvalidDataException).
|
||||
type decodeError struct{ err error }
|
||||
@@ -244,7 +293,7 @@ func (s *Server) fetch(rawURL string) (*http.Response, error) {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", "WebOne/"+s.cfg.Vars.Value("WOVer"))
|
||||
resp, err := s.up.auto.Do(req)
|
||||
resp, err := s.up.do(req, s.cfg.RemoteHttpVersion, logx.Std)
|
||||
if err != nil {
|
||||
logx.Std.Printf(" Fetch %s failed: %v", rawURL, err)
|
||||
}
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@
|
||||
; SecurityProtocols=Forcely set SSL/TLS protocols that can be used for retrieving web content
|
||||
; ValidateCertificates=Break network operations when the remote TLS certificate is bad
|
||||
; MultipleHttp2Connections=Allow multiple HTTP/2 connections to servers
|
||||
; RemoteHttpVersion=Version of HTTP(S) protocol, used to communicate with servers (min/max/exact)
|
||||
; RemoteHttpVersion=Version of HTTP(S) protocol, used to communicate with servers (min/max/exact: 1.1, 2.0, 3.0)
|
||||
; ConnectionTimeout=Timeout to wait before the remote connection establishing times out (secs)
|
||||
; UpperProxy=Another proxy server, used by WebOne to connect to Internet (optional)
|
||||
; UserAgent=Override user-agent string to fetch uncut content
|
||||
|
||||
Reference in new issue
Block a user