Fix h2c transport

This commit is contained in:
世界
2022-11-09 11:49:01 +08:00
parent 9a01d52a2c
commit b0235c6257
4 changed files with 44 additions and 12 deletions

View File

@@ -16,6 +16,9 @@ import (
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
sHttp "github.com/sagernet/sing/protocol/http"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
)
var _ adapter.V2RayServerTransport = (*Server)(nil)
@@ -25,6 +28,8 @@ type Server struct {
handler N.TCPConnectionHandler
errorHandler E.Handler
httpServer *http.Server
h2Server *http2.Server
h2cHandler http.Handler
host []string
path string
method string
@@ -44,6 +49,7 @@ func NewServer(ctx context.Context, options option.V2RayHTTPOptions, tlsConfig *
path: options.Path,
method: options.Method,
headers: make(http.Header),
h2Server: new(http2.Server),
}
if server.method == "" {
server.method = "PUT"
@@ -60,10 +66,16 @@ func NewServer(ctx context.Context, options option.V2RayHTTPOptions, tlsConfig *
MaxHeaderBytes: http.DefaultMaxHeaderBytes,
TLSConfig: tlsConfig,
}
server.h2cHandler = h2c.NewHandler(server, server.h2Server)
return server
}
func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
if request.Method == "PRI" && len(request.Header) == 0 && request.URL.Path == "*" && request.Proto == "HTTP/2.0" {
s.h2cHandler.ServeHTTP(writer, request)
return
}
host := request.Host
if len(s.host) > 0 && !common.Contains(s.host, host) {
writer.WriteHeader(http.StatusBadRequest)
@@ -119,6 +131,10 @@ func (s *Server) badRequest(request *http.Request, err error) {
}
func (s *Server) Serve(listener net.Listener) error {
err := http2.ConfigureServer(s.httpServer, s.h2Server)
if err != nil {
return err
}
if s.httpServer.TLSConfig == nil {
return s.httpServer.Serve(listener)
} else {