Fix: if http proxy Upgrade failure

This commit is contained in:
yaling888
2022-04-26 23:58:23 +08:00
parent ca4961a146
commit 7c50c068f5
5 changed files with 50 additions and 38 deletions

View File

@@ -62,20 +62,22 @@ func HandleConn(c net.Conn, in chan<- C.ConnContext, cache *cache.Cache[string,
request.RequestURI = ""
if isUpgradeRequest(request) {
handleUpgrade(conn, request, in)
return // hijack connection
if resp = handleUpgrade(conn, request, in); resp == nil {
return // hijack connection
}
}
RemoveHopByHopHeaders(request.Header)
RemoveExtraHTTPHostPort(request)
if resp == nil {
RemoveHopByHopHeaders(request.Header)
RemoveExtraHTTPHostPort(request)
if request.URL.Scheme == "" || request.URL.Host == "" {
resp = responseWith(request, http.StatusBadRequest)
} else {
resp, err = client.Do(request)
if err != nil {
resp = responseWith(request, http.StatusBadGateway)
if request.URL.Scheme == "" || request.URL.Host == "" {
resp = responseWith(request, http.StatusBadRequest)
} else {
resp, err = client.Do(request)
if err != nil {
resp = responseWith(request, http.StatusBadGateway)
}
}
}
@@ -96,7 +98,7 @@ func HandleConn(c net.Conn, in chan<- C.ConnContext, cache *cache.Cache[string,
}
}
conn.Close()
_ = conn.Close()
}
func Authenticate(request *http.Request, cache *cache.Cache[string, bool]) *http.Response {

View File

@@ -4,6 +4,7 @@ import (
"net"
"net/http"
"strings"
"time"
"github.com/Dreamacro/clash/adapter/inbound"
N "github.com/Dreamacro/clash/common/net"
@@ -15,9 +16,7 @@ func isUpgradeRequest(req *http.Request) bool {
return strings.EqualFold(req.Header.Get("Connection"), "Upgrade")
}
func handleUpgrade(conn net.Conn, request *http.Request, in chan<- C.ConnContext) {
defer conn.Close()
func handleUpgrade(conn net.Conn, request *http.Request, in chan<- C.ConnContext) (resp *http.Response) {
removeProxyHeaders(request.Header)
RemoveExtraHTTPHostPort(request)
@@ -36,26 +35,36 @@ func handleUpgrade(conn net.Conn, request *http.Request, in chan<- C.ConnContext
in <- inbound.NewHTTP(dstAddr, conn.RemoteAddr(), right)
bufferedLeft := N.NewBufferedConn(left)
defer bufferedLeft.Close()
defer func() {
_ = bufferedLeft.Close()
}()
err := request.Write(bufferedLeft)
if err != nil {
return
}
resp, err := http.ReadResponse(bufferedLeft.Reader(), request)
if err != nil {
return
}
removeProxyHeaders(resp.Header)
err = resp.Write(conn)
resp, err = http.ReadResponse(bufferedLeft.Reader(), request)
if err != nil {
return
}
if resp.StatusCode == http.StatusSwitchingProtocols {
removeProxyHeaders(resp.Header)
err = conn.SetReadDeadline(time.Time{})
if err != nil {
return
}
err = resp.Write(conn)
if err != nil {
return
}
N.Relay(bufferedLeft, conn)
_ = conn.Close()
resp = nil
}
return
}

View File

@@ -8,7 +8,7 @@ import (
"strings"
)
// removeHopByHopHeaders remove Proxy-* headers
// removeProxyHeaders remove Proxy-* headers
func removeProxyHeaders(header http.Header) {
header.Del("Proxy-Connection")
header.Del("Proxy-Authenticate")