diff --git a/adapter/outbound/vless.go b/adapter/outbound/vless.go index e50e80ec7..0cdaff5a1 100644 --- a/adapter/outbound/vless.go +++ b/adapter/outbound/vless.go @@ -72,12 +72,26 @@ type VlessOption struct { } type XHTTPOptions struct { - Path string `proxy:"path,omitempty"` - Host string `proxy:"host,omitempty"` - Mode string `proxy:"mode,omitempty"` - Headers map[string]string `proxy:"headers,omitempty"` - NoGRPCHeader bool `proxy:"no-grpc-header,omitempty"` - XPaddingBytes string `proxy:"x-padding-bytes,omitempty"` + Path string `proxy:"path,omitempty"` + Host string `proxy:"host,omitempty"` + Mode string `proxy:"mode,omitempty"` + Headers map[string]string `proxy:"headers,omitempty"` + NoGRPCHeader bool `proxy:"no-grpc-header,omitempty"` + XPaddingBytes string `proxy:"x-padding-bytes,omitempty"` + DownloadSettings *XHTTPDownloadSettings `proxy:"download-settings,omitempty"` +} + +type XHTTPDownloadSettings struct { + Server string `proxy:"server,omitempty"` + Port int `proxy:"port,omitempty"` + Network string `proxy:"network,omitempty"` + RealityOpts RealityOptions `proxy:"reality-opts,omitempty"` + Host string `proxy:"host,omitempty"` + Path string `proxy:"path,omitempty"` + Mode string `proxy:"mode,omitempty"` + ServerName string `proxy:"servername,omitempty"` + ClientFingerprint string `proxy:"client-fingerprint,omitempty"` + SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"` } func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) { @@ -241,6 +255,47 @@ func (v *Vless) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (ne return conn, nil } +func (v *Vless) streamTLSConnWith( + ctx context.Context, + conn net.Conn, + isH2 bool, + addr string, + tlsEnabled bool, + serverName string, + alpn []string, + skipCertVerify bool, + clientFingerprint string, + realityConfig *tlsC.RealityConfig, +) (net.Conn, error) { + if tlsEnabled { + host, _, _ := net.SplitHostPort(addr) + + tlsOpts := vmess.TLSConfig{ + Host: host, + SkipCertVerify: skipCertVerify, + FingerPrint: v.option.Fingerprint, + Certificate: v.option.Certificate, + PrivateKey: v.option.PrivateKey, + ClientFingerprint: clientFingerprint, + ECH: v.echConfig, + Reality: realityConfig, + NextProtos: alpn, + } + + if isH2 { + tlsOpts.NextProtos = []string{"h2"} + } + + if serverName != "" { + tlsOpts.Host = serverName + } + + return vmess.StreamTLSConn(ctx, conn, &tlsOpts) + } + + return conn, nil +} + func (v *Vless) dialXHTTPConn() (net.Conn, error) { requestHost := v.option.XHTTPOpts.Host if requestHost == "" { @@ -260,7 +315,73 @@ func (v *Vless) dialXHTTPConn() (net.Conn, error) { XPaddingBytes: v.option.XHTTPOpts.XPaddingBytes, } + if ds := v.option.XHTTPOpts.DownloadSettings; ds != nil { + if ds.Network != "" && ds.Network != "xhttp" { + return nil, fmt.Errorf("xhttp download-settings network must be xhttp") + } + + realityCfg, err := ds.RealityOpts.Parse() + if err != nil { + return nil, err + } + + cfg.DownloadSettings = &xhttp.DownloadConfig{ + Server: ds.Server, + Port: ds.Port, + Reality: realityCfg, + Host: ds.Host, + Path: ds.Path, + Mode: ds.Mode, + ServerName: ds.ServerName, + ClientFingerprint: ds.ClientFingerprint, + SkipCertVerify: ds.SkipCertVerify, + } + } + + if cfg.DownloadSettings != nil && cfg.Mode == "stream-one" { + return nil, fmt.Errorf(`xhttp mode "stream-one" cannot be used with download-settings`) + } + mode := cfg.EffectiveMode(v.realityConfig != nil) + + downloadAddr := v.addr + downloadTLSEnabled := v.option.TLS + downloadServerName := v.option.ServerName + downloadReality := v.realityConfig + downloadSkipCertVerify := v.option.SkipCertVerify + downloadClientFingerprint := v.option.ClientFingerprint + downloadALPN := v.option.ALPN + + if ds := cfg.DownloadSettings; ds != nil { + server := v.option.Server + port := v.option.Port + + if ds.Server != "" { + server = ds.Server + } + if ds.Port != 0 { + port = ds.Port + } + + downloadAddr = net.JoinHostPort(server, strconv.Itoa(port)) + + if ds.Reality != nil { + downloadReality = ds.Reality + downloadTLSEnabled = true + } + + if ds.ServerName != "" { + downloadServerName = ds.ServerName + } + + if ds.ClientFingerprint != "" { + downloadClientFingerprint = ds.ClientFingerprint + } + + if ds.SkipCertVerify { + downloadSkipCertVerify = true + } + } transport := xhttp.NewTransport( func(ctx context.Context) (net.Conn, error) { return v.dialer.DialContext(ctx, "tcp", v.addr) @@ -270,16 +391,42 @@ func (v *Vless) dialXHTTPConn() (net.Conn, error) { }, ) + downloadTransport := xhttp.NewTransport( + func(ctx context.Context) (net.Conn, error) { + return v.dialer.DialContext(ctx, "tcp", downloadAddr) + }, + func(ctx context.Context, raw net.Conn, isH2 bool) (net.Conn, error) { + return v.streamTLSConnWith( + ctx, + raw, + isH2, + downloadAddr, + downloadTLSEnabled, + downloadServerName, + downloadALPN, + downloadSkipCertVerify, + downloadClientFingerprint, + downloadReality, + ) + }, + ) switch mode { case "stream-one": return xhttp.DialStreamOne(cfg, transport) + case "stream-up": + return xhttp.DialStreamUp( + cfg, + transport, + downloadTransport, + v.option.Server, + v.option.Port, + ) case "packet-up": return xhttp.DialPacketUp(cfg, transport) default: return nil, fmt.Errorf("xhttp mode %s is not implemented yet", mode) } } - func (v *Vless) dialContext(ctx context.Context) (c net.Conn, err error) { switch v.option.Network { case "xhttp": diff --git a/listener/inbound/vless_test.go b/listener/inbound/vless_test.go index 5b5d68f89..aaccd5f18 100644 --- a/listener/inbound/vless_test.go +++ b/listener/inbound/vless_test.go @@ -391,3 +391,63 @@ func TestInboundVless_Reality_XHTTP(t *testing.T) { } testInboundVless(t, inboundOptions, outboundOptions) } + +func TestInboundVless_XHTTP_DownloadSettings(t *testing.T) { + inboundOptions := inbound.VlessOption{ + Certificate: tlsCertificate, + PrivateKey: tlsPrivateKey, + XHTTPConfig: inbound.XHTTPConfig{ + Path: "/vless-xhttp", + Host: "example.com", + Mode: "auto", + }, + } + outboundOptions := outbound.VlessOption{ + TLS: true, + Fingerprint: tlsFingerprint, + SkipCertVerify: true, + ServerName: "example.org", + ClientFingerprint: "chrome", + Network: "xhttp", + XHTTPOpts: outbound.XHTTPOptions{ + Path: "/vless-xhttp", + Host: "example.com", + Mode: "auto", + DownloadSettings: &outbound.XHTTPDownloadSettings{ + Server: "example.com", + Port: 443, + Network: "xhttp", + Host: "example.com", + Path: "/vless-xhttp", + Mode: "stream-up", + ServerName: "example.org", + ClientFingerprint: "chrome", + SkipCertVerify: true, + }, + }, + } + testInboundVlessTLS(t, inboundOptions, outboundOptions, false) +} + +func TestInboundVless_XHTTP_StreamUp(t *testing.T) { + inboundOptions := inbound.VlessOption{ + Certificate: tlsCertificate, + PrivateKey: tlsPrivateKey, + XHTTPConfig: inbound.XHTTPConfig{ + Path: "/vless-xhttp", + Host: "example.com", + Mode: "stream-up", + }, + } + outboundOptions := outbound.VlessOption{ + TLS: true, + Fingerprint: tlsFingerprint, + Network: "xhttp", + XHTTPOpts: outbound.XHTTPOptions{ + Path: "/vless-xhttp", + Host: "example.com", + Mode: "stream-up", + }, + } + testInboundVlessTLS(t, inboundOptions, outboundOptions, false) +} diff --git a/listener/sing_vless/server.go b/listener/sing_vless/server.go index 76566df98..80b876b33 100644 --- a/listener/sing_vless/server.go +++ b/listener/sing_vless/server.go @@ -148,7 +148,7 @@ func New(config LC.VlessServer, tunnel C.Tunnel, additions ...inbound.Addition) } if config.XHTTPConfig.Mode != "" { switch config.XHTTPConfig.Mode { - case "auto": + case "auto", "stream-up": default: return nil, errors.New("unsupported xhttp mode") } diff --git a/transport/xhttp/client.go b/transport/xhttp/client.go index 4390d6564..337c3d615 100644 --- a/transport/xhttp/client.go +++ b/transport/xhttp/client.go @@ -11,6 +11,7 @@ import ( "strconv" "sync" + "github.com/metacubex/mihomo/common/contextutils" "github.com/metacubex/mihomo/common/httputils" "github.com/metacubex/http" @@ -107,7 +108,7 @@ func DialStreamOne(cfg *Config, transport http.RoundTripper) (net.Conn, error) { } req.Host = cfg.Host - if err := cfg.FillStreamRequest(req); err != nil { + if err := cfg.FillStreamRequest(req, ""); err != nil { _ = pr.Close() _ = pw.Close() return nil, err @@ -137,6 +138,140 @@ func DialStreamOne(cfg *Config, transport http.RoundTripper) (net.Conn, error) { return conn, nil } +func DialStreamUp( + cfg *Config, + uploadTransport http.RoundTripper, + downloadTransport http.RoundTripper, + address string, + port int, +) (net.Conn, error) { + host := cfg.Host + if host == "" { + host = address + } + + downloadCfg := cfg + if ds := cfg.DownloadSettings; ds != nil { + downloadCfg = &Config{ + Host: ds.Host, + Path: ds.Path, + Mode: ds.Mode, + Headers: cfg.Headers, + NoGRPCHeader: cfg.NoGRPCHeader, + XPaddingBytes: cfg.XPaddingBytes, + DownloadSettings: nil, + } + } + + downloadHost := downloadCfg.Host + if downloadHost == "" { + downloadHost = host + } + + _ = port + + streamURL := url.URL{ + Scheme: "https", + Host: host, + Path: cfg.NormalizedPath(), + } + + downloadURL := url.URL{ + Scheme: "https", + Host: downloadHost, + Path: downloadCfg.NormalizedPath(), + } + + ctx := context.Background() + conn := &Conn{} + + sessionID := newSessionID() + + downloadReq, err := http.NewRequestWithContext( + httputils.NewAddrContext(&conn.NetAddr, contextutils.WithoutCancel(ctx)), + http.MethodGet, + downloadURL.String(), + nil, + ) + if err != nil { + httputils.CloseTransport(uploadTransport) + httputils.CloseTransport(downloadTransport) + return nil, err + } + + if err := downloadCfg.FillDownloadRequest(downloadReq, sessionID); err != nil { + httputils.CloseTransport(uploadTransport) + httputils.CloseTransport(downloadTransport) + return nil, err + } + downloadReq.Host = downloadHost + + downloadResp, err := downloadTransport.RoundTrip(downloadReq) + if err != nil { + httputils.CloseTransport(uploadTransport) + httputils.CloseTransport(downloadTransport) + return nil, err + } + if downloadResp.StatusCode != http.StatusOK { + _ = downloadResp.Body.Close() + httputils.CloseTransport(uploadTransport) + httputils.CloseTransport(downloadTransport) + return nil, fmt.Errorf("xhttp stream-up download bad status: %s", downloadResp.Status) + } + + pr, pw := io.Pipe() + + uploadReq, err := http.NewRequestWithContext( + contextutils.WithoutCancel(ctx), + http.MethodPost, + streamURL.String(), + pr, + ) + if err != nil { + _ = downloadResp.Body.Close() + _ = pr.Close() + _ = pw.Close() + httputils.CloseTransport(uploadTransport) + httputils.CloseTransport(downloadTransport) + return nil, err + } + + if err := cfg.FillStreamRequest(uploadReq, sessionID); err != nil { + _ = downloadResp.Body.Close() + _ = pr.Close() + _ = pw.Close() + httputils.CloseTransport(uploadTransport) + httputils.CloseTransport(downloadTransport) + return nil, err + } + uploadReq.Host = host + + go func() { + resp, err := uploadTransport.RoundTrip(uploadReq) + if err != nil { + _ = pw.CloseWithError(err) + return + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, resp.Body) + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + _ = pw.CloseWithError(fmt.Errorf("xhttp stream-up upload bad status: %s", resp.Status)) + } + }() + + conn.writer = pw + conn.reader = downloadResp.Body + conn.onClose = func() { + _ = downloadResp.Body.Close() + _ = pr.Close() + httputils.CloseTransport(uploadTransport) + httputils.CloseTransport(downloadTransport) + } + + return conn, nil +} + func DialPacketUp(cfg *Config, transport http.RoundTripper) (net.Conn, error) { sessionID := newSessionID() diff --git a/transport/xhttp/config.go b/transport/xhttp/config.go index eda9e26bf..6cf220fad 100644 --- a/transport/xhttp/config.go +++ b/transport/xhttp/config.go @@ -9,15 +9,29 @@ import ( "strings" "github.com/metacubex/http" + tlsC "github.com/metacubex/mihomo/component/tls" ) type Config struct { - Host string - Path string - Mode string - Headers map[string]string - NoGRPCHeader bool - XPaddingBytes string + Host string + Path string + Mode string + Headers map[string]string + NoGRPCHeader bool + XPaddingBytes string + DownloadSettings *DownloadConfig +} + +type DownloadConfig struct { + Server string + Port int + Reality *tlsC.RealityConfig + Host string + Path string + Mode string + ServerName string + ClientFingerprint string + SkipCertVerify bool } func (c *Config) NormalizedMode() string { @@ -33,6 +47,9 @@ func (c *Config) EffectiveMode(hasReality bool) string { return mode } if hasReality { + if c.DownloadSettings != nil { + return "stream-up" + } return "stream-one" } return "packet-up" @@ -126,7 +143,7 @@ func parseRange(s string) (int, int, error) { return minVal, maxVal, nil } -func (c *Config) FillStreamRequest(req *http.Request) error { +func (c *Config) FillStreamRequest(req *http.Request, sessionID string) error { req.Header = c.RequestHeader() paddingValue, err := c.RandomPadding() @@ -143,6 +160,8 @@ func (c *Config) FillStreamRequest(req *http.Request) error { req.Header.Set("Referer", rawURL+sep+"x_padding="+paddingValue) } + c.ApplyMetaToRequest(req, sessionID, "") + if req.Body != nil && !c.NoGRPCHeader { req.Header.Set("Content-Type", "application/grpc") } diff --git a/transport/xhttp/server.go b/transport/xhttp/server.go index 311a50e6a..e4b3c7c6c 100644 --- a/transport/xhttp/server.go +++ b/transport/xhttp/server.go @@ -242,6 +242,45 @@ func (h *requestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } + // stream-up upload: POST /path/{session} + if r.Method == http.MethodPost && len(parts) == 1 { + sessionID := parts[0] + session := h.getSession(sessionID) + if session == nil { + http.Error(w, "unknown xhttp session", http.StatusBadRequest) + return + } + + buf := make([]byte, 32*1024) + var seq uint64 + + for { + n, err := r.Body.Read(buf) + if n > 0 { + if pushErr := session.uploadQueue.Push(Packet{ + Seq: seq, + Payload: buf[:n], + }); pushErr != nil { + http.Error(w, pushErr.Error(), http.StatusInternalServerError) + return + } + seq++ + } + + if err == io.EOF { + break + } + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + } + + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusOK) + return + } + // packet-up upload: POST /path/{session}/{seq} if r.Method == http.MethodPost && len(parts) == 2 { sessionID := parts[0]