Preserve custom Host headers for WebSocket requests (#6172)

Co-authored-by: cuteNBD <206630735+bingdongni@users.noreply.github.com>
This commit is contained in:
cuteNBD 2026-11-04 17:18:06 +08:00 • committed by GitHub
parent bf8b9956e0
commit 74f50122fb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 95 additions and 2 deletions

View file

@ -521,6 +521,8 @@ class Connect(object):
# Prepare HTTP headers
headers = forgeHeaders({HTTP_HEADER.COOKIE: cookie, HTTP_HEADER.USER_AGENT: ua, HTTP_HEADER.REFERER: referer, HTTP_HEADER.HOST: host or getHeader(dict(conf.httpHeaders), HTTP_HEADER.HOST) or getHostHeader(url)}, base=None if target else {})
# WebSocket builds its own default Host, but must preserve explicit overrides.
customWsHost = webSocket and bool(host or getHeader(dict(conf.httpHeaders), HTTP_HEADER.HOST) or getHeader(auxHeaders, HTTP_HEADER.HOST) is not None)
if HTTP_HEADER.COOKIE in headers:
cookie = headers[HTTP_HEADER.COOKIE]
@ -573,9 +575,13 @@ class Connect(object):
if ':' in line:
header, value = line.split(':', 1)
headers[header] = value
if webSocket and header.upper() == HTTP_HEADER.HOST.upper():
headers[HTTP_HEADER.HOST] = value
customWsHost = True
if conf.localhost:
headers[HTTP_HEADER.HOST] = "localhost"
customWsHost = True
for key, value in list(headers.items()):
if key.upper() == HTTP_HEADER.ACCEPT_ENCODING.upper():
@ -600,7 +606,7 @@ class Connect(object):
try:
ws.settimeout(WEBSOCKET_INITIAL_TIMEOUT if kb.webSocketRecvCount is None else timeout)
wsHeaders = tuple("%s: %s" % (getUnicode(key), getUnicode(value)) for key, value in headers.items() if getUnicode(key).upper() != HTTP_HEADER.HOST.upper())
ws.connect(url, header=wsHeaders, cookie=cookie) # WebSocket will add Host field of headers automatically
ws.connect(url, header=wsHeaders, cookie=cookie, host_header=getHeader(headers, HTTP_HEADER.HOST) if customWsHost else None)
ws.send(urldecode(post or ""))
_page = []

View file

@ -58,7 +58,7 @@ class WebSocket(object):
if self.sock is not None:
self.sock.settimeout(timeout)
def connect(self, url, header=None, cookie=None):
def connect(self, url, header=None, cookie=None, host_header=None):
parts = _urllib.parse.urlsplit(url)
secure = parts.scheme == "wss"
host = parts.hostname
@ -75,6 +75,8 @@ class WebSocket(object):
hostport = "[%s]" % host if ":" in host else host # bracket IPv6 literals
if port != (443 if secure else 80): # Note: only the scheme's own default port gets omitted
hostport = "%s:%d" % (hostport, port)
if host_header is not None:
hostport = getText(host_header)
key = getText(base64.b64encode(os.urandom(16)))
lines = ["GET %s HTTP/1.1" % resource,