Clash.Meta/listener/http/upgrade.go

96 lines
1.9 KiB
Go
Raw Normal View History

package http
import (
2022-04-27 05:14:03 +08:00
"context"
"crypto/tls"
"net"
"net/http"
"strings"
2022-04-27 05:14:03 +08:00
"time"
"github.com/Dreamacro/clash/adapter/inbound"
N "github.com/Dreamacro/clash/common/net"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/transport/socks5"
)
func isUpgradeRequest(req *http.Request) bool {
return strings.EqualFold(req.Header.Get("Connection"), "Upgrade")
}
2022-04-27 14:42:58 +08:00
func handleUpgrade(localConn net.Conn, source net.Addr, request *http.Request, in chan<- C.ConnContext) (resp *http.Response) {
removeProxyHeaders(request.Header)
removeExtraHTTPHostPort(request)
address := request.Host
if _, _, err := net.SplitHostPort(address); err != nil {
2022-04-27 05:14:03 +08:00
port := "80"
if request.TLS != nil {
port = "443"
}
address = net.JoinHostPort(address, port)
}
dstAddr := socks5.ParseAddr(address)
if dstAddr == nil {
return
}
left, right := net.Pipe()
2022-04-27 14:42:58 +08:00
in <- inbound.NewHTTP(dstAddr, source, right)
2022-04-27 05:14:03 +08:00
var remoteServer *N.BufferedConn
if request.TLS != nil {
tlsConn := tls.Client(left, &tls.Config{
ServerName: request.URL.Hostname(),
})
2022-04-27 05:14:03 +08:00
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
defer cancel()
if tlsConn.HandshakeContext(ctx) != nil {
_ = localConn.Close()
_ = left.Close()
return
}
remoteServer = N.NewBufferedConn(tlsConn)
} else {
remoteServer = N.NewBufferedConn(left)
}
2022-04-27 05:14:03 +08:00
defer func() {
_ = remoteServer.Close()
}()
2022-04-27 05:14:03 +08:00
err := request.Write(remoteServer)
if err != nil {
2022-04-27 05:14:03 +08:00
_ = localConn.Close()
return
}
2022-04-27 05:14:03 +08:00
resp, err = http.ReadResponse(remoteServer.Reader(), request)
if err != nil {
2022-04-27 05:14:03 +08:00
_ = localConn.Close()
return
}
if resp.StatusCode == http.StatusSwitchingProtocols {
2022-04-27 05:14:03 +08:00
removeProxyHeaders(resp.Header)
err = localConn.SetReadDeadline(time.Time{}) // set to not time out
if err != nil {
return
}
err = resp.Write(localConn)
if err != nil {
return
}
N.Relay(remoteServer, localConn) // blocking here
_ = localConn.Close()
resp = nil
}
2022-04-27 05:14:03 +08:00
return
}