7from ssl
import SSLContext
9from typing
import Any, Dict
12from httpx_socks
import AsyncProxyTransport
13from python_socks
import parse_proxy_url, ProxyConnectionError, ProxyTimeoutError, ProxyError
16from searx
import logger
22logger = logger.getChild(
'searx.network.client')
24SSLCONTEXTS: Dict[Any, SSLContext] = {}
28 """Shuffle httpx's default ciphers of a SSL context randomly.
30 From `What Is TLS Fingerprint and How to Bypass It`_
32 > When implementing TLS fingerprinting, servers can't operate based on a
33 > locked-in whitelist database of fingerprints. New fingerprints appear
34 > when web clients or TLS libraries release new versions. So, they have to
35 > live off a blocklist database instead.
37 > It's safe to leave the first three as is but shuffle the remaining ciphers
38 > and you can bypass the TLS fingerprint check.
40 .. _What Is TLS Fingerprint and How to Bypass It:
41 https://www.zenrows.com/blog/what-is-tls-fingerprint#how-to-bypass-tls-fingerprinting
44 c_list = httpx._config.DEFAULT_CIPHERS.split(
':')
45 sc_list, c_list = c_list[:3], c_list[3:]
46 random.shuffle(c_list)
47 ssl_context.set_ciphers(
":".join(sc_list + c_list))
50def get_sslcontexts(proxy_url=None, cert=None, verify=True, trust_env=True, http2=False):
51 key = (proxy_url, cert, verify, trust_env, http2)
52 if key
not in SSLCONTEXTS:
53 SSLCONTEXTS[key] = httpx.create_ssl_context(cert, verify, trust_env, http2)
55 return SSLCONTEXTS[key]
61 The constructor is blank because httpx.AsyncHTTPTransport.__init__ creates an SSLContext unconditionally:
62 https://github.com/encode/httpx/blob/0f61aa58d66680c239ce43c8cdd453e7dc532bfc/httpx/_transports/default.py#L271
64 Each SSLContext consumes more than 500kb of memory, since there is about one network per engine.
66 In consequence, this class overrides all public methods
68 For reference: https://github.com/encode/httpx/issues/2298
77 raise httpx.UnsupportedProtocol(
'HTTP protocol is disabled')
94class AsyncProxyTransportFixed(AsyncProxyTransport):
95 """Fix httpx_socks.AsyncProxyTransport
97 Map python_socks exceptions to httpx.ProxyError exceptions
103 except ProxyConnectionError
as e:
104 raise httpx.ProxyError(
"ProxyConnectionError: " + e.strerror, request=request)
from e
105 except ProxyTimeoutError
as e:
106 raise httpx.ProxyError(
"ProxyTimeoutError: " + e.args[0], request=request)
from e
107 except ProxyError
as e:
108 raise httpx.ProxyError(
"ProxyError: " + e.args[0], request=request)
from e
117 socks5h =
'socks5h://'
118 if proxy_url.startswith(socks5h):
119 proxy_url =
'socks5://' + proxy_url[len(socks5h) :]
122 proxy_type, proxy_host, proxy_port, proxy_username, proxy_password = parse_proxy_url(proxy_url)
123 verify =
get_sslcontexts(proxy_url,
None, verify,
True, http2)
if verify
is True else verify
125 proxy_type=proxy_type,
126 proxy_host=proxy_host,
127 proxy_port=proxy_port,
128 username=proxy_username,
129 password=proxy_password,
134 local_address=local_address,
141 verify =
get_sslcontexts(
None,
None, verify,
True, http2)
if verify
is True else verify
142 return httpx.AsyncHTTPTransport(
147 proxy=httpx._config.Proxy(proxy_url)
if proxy_url
else None,
148 local_address=local_address,
159 max_keepalive_connections,
167 limit = httpx.Limits(
168 max_connections=max_connections,
169 max_keepalive_connections=max_keepalive_connections,
170 keepalive_expiry=keepalive_expiry,
174 for pattern, proxy_url
in proxies.items():
175 if not enable_http
and pattern.startswith(
'http://'):
177 if proxy_url.startswith(
'socks4://')
or proxy_url.startswith(
'socks5://')
or proxy_url.startswith(
'socks5h://'):
179 verify, enable_http2, local_address, proxy_url, limit, retries
182 mounts[pattern] =
get_transport(verify, enable_http2, local_address, proxy_url, limit, retries)
187 transport =
get_transport(verify, enable_http2, local_address,
None, limit, retries)
190 if hook_log_response:
191 event_hooks = {
'response': [hook_log_response]}
193 return httpx.AsyncClient(
196 max_redirects=max_redirects,
197 event_hooks=event_hooks,
210 'httpcore.connection',
216 logging.getLogger(logger_name).setLevel(logging.WARNING)
221 LOOP = asyncio.new_event_loop()
224 thread = threading.Thread(
__init__(self, *args, **kwargs)
None __aexit__(self, exc_type=None, exc_value=None, traceback=None)
handle_async_request(self, request)
handle_async_request(self, request)
new_client(enable_http, verify, enable_http2, max_connections, max_keepalive_connections, keepalive_expiry, proxies, local_address, retries, max_redirects, hook_log_response)
get_transport_for_socks_proxy(verify, http2, local_address, proxy_url, limit, retries)
get_sslcontexts(proxy_url=None, cert=None, verify=True, trust_env=True, http2=False)
shuffle_ciphers(ssl_context)
get_transport(verify, http2, local_address, proxy_url, limit, retries)