network.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pylint: disable=global-statement
  4. # pylint: disable=missing-module-docstring, missing-class-docstring
  5. import atexit
  6. import asyncio
  7. import ipaddress
  8. from itertools import cycle
  9. from typing import Dict
  10. import httpx
  11. from searx import logger, searx_debug
  12. from .client import new_client, get_loop, AsyncHTTPTransportNoHttp
  13. from .raise_for_httperror import raise_for_httperror
  14. logger = logger.getChild('network')
  15. DEFAULT_NAME = '__DEFAULT__'
  16. NETWORKS: Dict[str, 'Network'] = {}
  17. # requests compatibility when reading proxy settings from settings.yml
  18. PROXY_PATTERN_MAPPING = {
  19. 'http': 'http://',
  20. 'https': 'https://',
  21. 'socks4': 'socks4://',
  22. 'socks5': 'socks5://',
  23. 'socks5h': 'socks5h://',
  24. 'http:': 'http://',
  25. 'https:': 'https://',
  26. 'socks4:': 'socks4://',
  27. 'socks5:': 'socks5://',
  28. 'socks5h:': 'socks5h://',
  29. }
  30. ADDRESS_MAPPING = {'ipv4': '0.0.0.0', 'ipv6': '::'}
  31. class Network:
  32. __slots__ = (
  33. 'enable_http',
  34. 'verify',
  35. 'enable_http2',
  36. 'max_connections',
  37. 'max_keepalive_connections',
  38. 'keepalive_expiry',
  39. 'local_addresses',
  40. 'proxies',
  41. 'using_tor_proxy',
  42. 'max_redirects',
  43. 'retries',
  44. 'retry_on_http_error',
  45. '_local_addresses_cycle',
  46. '_proxies_cycle',
  47. '_clients',
  48. '_logger',
  49. )
  50. _TOR_CHECK_RESULT = {}
  51. def __init__(
  52. # pylint: disable=too-many-arguments
  53. self,
  54. enable_http=True,
  55. verify=True,
  56. enable_http2=False,
  57. max_connections=None,
  58. max_keepalive_connections=None,
  59. keepalive_expiry=None,
  60. proxies=None,
  61. using_tor_proxy=False,
  62. local_addresses=None,
  63. retries=0,
  64. retry_on_http_error=None,
  65. max_redirects=30,
  66. logger_name=None,
  67. ):
  68. self.enable_http = enable_http
  69. self.verify = verify
  70. self.enable_http2 = enable_http2
  71. self.max_connections = max_connections
  72. self.max_keepalive_connections = max_keepalive_connections
  73. self.keepalive_expiry = keepalive_expiry
  74. self.proxies = proxies
  75. self.using_tor_proxy = using_tor_proxy
  76. self.local_addresses = local_addresses
  77. self.retries = retries
  78. self.retry_on_http_error = retry_on_http_error
  79. self.max_redirects = max_redirects
  80. self._local_addresses_cycle = self.get_ipaddress_cycle()
  81. self._proxies_cycle = self.get_proxy_cycles()
  82. self._clients = {}
  83. self._logger = logger.getChild(logger_name) if logger_name else logger
  84. self.check_parameters()
  85. def check_parameters(self):
  86. for address in self.iter_ipaddresses():
  87. if '/' in address:
  88. ipaddress.ip_network(address, False)
  89. else:
  90. ipaddress.ip_address(address)
  91. if self.proxies is not None and not isinstance(self.proxies, (str, dict)):
  92. raise ValueError('proxies type has to be str, dict or None')
  93. def iter_ipaddresses(self):
  94. local_addresses = self.local_addresses
  95. if not local_addresses:
  96. return
  97. if isinstance(local_addresses, str):
  98. local_addresses = [local_addresses]
  99. for address in local_addresses:
  100. yield address
  101. def get_ipaddress_cycle(self):
  102. while True:
  103. count = 0
  104. for address in self.iter_ipaddresses():
  105. if '/' in address:
  106. for a in ipaddress.ip_network(address, False).hosts():
  107. yield str(a)
  108. count += 1
  109. else:
  110. a = ipaddress.ip_address(address)
  111. yield str(a)
  112. count += 1
  113. if count == 0:
  114. yield None
  115. def iter_proxies(self):
  116. if not self.proxies:
  117. return
  118. # https://www.python-httpx.org/compatibility/#proxy-keys
  119. if isinstance(self.proxies, str):
  120. yield 'all://', [self.proxies]
  121. else:
  122. for pattern, proxy_url in self.proxies.items():
  123. pattern = PROXY_PATTERN_MAPPING.get(pattern, pattern)
  124. if isinstance(proxy_url, str):
  125. proxy_url = [proxy_url]
  126. yield pattern, proxy_url
  127. def get_proxy_cycles(self):
  128. proxy_settings = {}
  129. for pattern, proxy_urls in self.iter_proxies():
  130. proxy_settings[pattern] = cycle(proxy_urls)
  131. while True:
  132. # pylint: disable=stop-iteration-return
  133. yield tuple((pattern, next(proxy_url_cycle)) for pattern, proxy_url_cycle in proxy_settings.items())
  134. async def log_response(self, response: httpx.Response):
  135. request = response.request
  136. status = f"{response.status_code} {response.reason_phrase}"
  137. response_line = f"{response.http_version} {status}"
  138. content_type = response.headers.get("Content-Type")
  139. content_type = f' ({content_type})' if content_type else ''
  140. self._logger.debug(f'HTTP Request: {request.method} {request.url} "{response_line}"{content_type}')
  141. @staticmethod
  142. async def check_tor_proxy(client: httpx.AsyncClient, proxies) -> bool:
  143. if proxies in Network._TOR_CHECK_RESULT:
  144. return Network._TOR_CHECK_RESULT[proxies]
  145. result = True
  146. # ignore client._transport because it is not used with all://
  147. for transport in client._mounts.values(): # pylint: disable=protected-access
  148. if isinstance(transport, AsyncHTTPTransportNoHttp):
  149. continue
  150. if getattr(transport, "_pool") and getattr(
  151. transport._pool, "_rdns", False # pylint: disable=protected-access
  152. ):
  153. continue
  154. return False
  155. response = await client.get("https://check.torproject.org/api/ip", timeout=60)
  156. if not response.json()["IsTor"]:
  157. result = False
  158. Network._TOR_CHECK_RESULT[proxies] = result
  159. return result
  160. async def get_client(self, verify=None, max_redirects=None):
  161. verify = self.verify if verify is None else verify
  162. max_redirects = self.max_redirects if max_redirects is None else max_redirects
  163. local_address = next(self._local_addresses_cycle)
  164. proxies = next(self._proxies_cycle) # is a tuple so it can be part of the key
  165. key = (verify, max_redirects, local_address, proxies)
  166. hook_log_response = self.log_response if searx_debug else None
  167. if key not in self._clients or self._clients[key].is_closed:
  168. client = new_client(
  169. self.enable_http,
  170. verify,
  171. self.enable_http2,
  172. self.max_connections,
  173. self.max_keepalive_connections,
  174. self.keepalive_expiry,
  175. dict(proxies),
  176. local_address,
  177. 0,
  178. max_redirects,
  179. hook_log_response,
  180. )
  181. if self.using_tor_proxy and not await self.check_tor_proxy(client, proxies):
  182. await client.aclose()
  183. raise httpx.ProxyError('Network configuration problem: not using Tor')
  184. self._clients[key] = client
  185. return self._clients[key]
  186. async def aclose(self):
  187. async def close_client(client):
  188. try:
  189. await client.aclose()
  190. except httpx.HTTPError:
  191. pass
  192. await asyncio.gather(*[close_client(client) for client in self._clients.values()], return_exceptions=False)
  193. @staticmethod
  194. def extract_kwargs_clients(kwargs):
  195. kwargs_clients = {}
  196. if 'verify' in kwargs:
  197. kwargs_clients['verify'] = kwargs.pop('verify')
  198. if 'max_redirects' in kwargs:
  199. kwargs_clients['max_redirects'] = kwargs.pop('max_redirects')
  200. if 'allow_redirects' in kwargs:
  201. # see https://github.com/encode/httpx/pull/1808
  202. kwargs['follow_redirects'] = kwargs.pop('allow_redirects')
  203. return kwargs_clients
  204. @staticmethod
  205. def extract_do_raise_for_httperror(kwargs):
  206. do_raise_for_httperror = True
  207. if 'raise_for_httperror' in kwargs:
  208. do_raise_for_httperror = kwargs['raise_for_httperror']
  209. del kwargs['raise_for_httperror']
  210. return do_raise_for_httperror
  211. @staticmethod
  212. def patch_response(response, do_raise_for_httperror):
  213. if isinstance(response, httpx.Response):
  214. # requests compatibility (response is not streamed)
  215. # see also https://www.python-httpx.org/compatibility/#checking-for-4xx5xx-responses
  216. response.ok = not response.is_error
  217. # raise an exception
  218. if do_raise_for_httperror:
  219. raise_for_httperror(response)
  220. return response
  221. def is_valid_response(self, response):
  222. # pylint: disable=too-many-boolean-expressions
  223. if (
  224. (self.retry_on_http_error is True and 400 <= response.status_code <= 599)
  225. or (isinstance(self.retry_on_http_error, list) and response.status_code in self.retry_on_http_error)
  226. or (isinstance(self.retry_on_http_error, int) and response.status_code == self.retry_on_http_error)
  227. ):
  228. return False
  229. return True
  230. async def call_client(self, stream, method, url, **kwargs):
  231. retries = self.retries
  232. was_disconnected = False
  233. do_raise_for_httperror = Network.extract_do_raise_for_httperror(kwargs)
  234. kwargs_clients = Network.extract_kwargs_clients(kwargs)
  235. while retries >= 0: # pragma: no cover
  236. client = await self.get_client(**kwargs_clients)
  237. try:
  238. if stream:
  239. response = client.stream(method, url, **kwargs)
  240. else:
  241. response = await client.request(method, url, **kwargs)
  242. if self.is_valid_response(response) or retries <= 0:
  243. return Network.patch_response(response, do_raise_for_httperror)
  244. except httpx.RemoteProtocolError as e:
  245. if not was_disconnected:
  246. # the server has closed the connection:
  247. # try again without decreasing the retries variable & with a new HTTP client
  248. was_disconnected = True
  249. await client.aclose()
  250. self._logger.warning('httpx.RemoteProtocolError: the server has disconnected, retrying')
  251. continue
  252. if retries <= 0:
  253. raise e
  254. except (httpx.RequestError, httpx.HTTPStatusError) as e:
  255. if retries <= 0:
  256. raise e
  257. retries -= 1
  258. async def request(self, method, url, **kwargs):
  259. return await self.call_client(False, method, url, **kwargs)
  260. async def stream(self, method, url, **kwargs):
  261. return await self.call_client(True, method, url, **kwargs)
  262. @classmethod
  263. async def aclose_all(cls):
  264. await asyncio.gather(*[network.aclose() for network in NETWORKS.values()], return_exceptions=False)
  265. def get_network(name=None):
  266. return NETWORKS.get(name or DEFAULT_NAME)
  267. def check_network_configuration():
  268. async def check():
  269. exception_count = 0
  270. for network in NETWORKS.values():
  271. if network.using_tor_proxy:
  272. try:
  273. await network.get_client()
  274. except Exception: # pylint: disable=broad-except
  275. network._logger.exception('Error') # pylint: disable=protected-access
  276. exception_count += 1
  277. return exception_count
  278. future = asyncio.run_coroutine_threadsafe(check(), get_loop())
  279. exception_count = future.result()
  280. if exception_count > 0:
  281. raise RuntimeError("Invalid network configuration")
  282. def initialize(settings_engines=None, settings_outgoing=None):
  283. # pylint: disable=import-outside-toplevel)
  284. from searx.engines import engines
  285. from searx import settings
  286. # pylint: enable=import-outside-toplevel)
  287. settings_engines = settings_engines or settings['engines']
  288. settings_outgoing = settings_outgoing or settings['outgoing']
  289. # default parameters for AsyncHTTPTransport
  290. # see https://github.com/encode/httpx/blob/e05a5372eb6172287458b37447c30f650047e1b8/httpx/_transports/default.py#L108-L121 # pylint: disable=line-too-long
  291. default_params = {
  292. 'enable_http': False,
  293. 'verify': settings_outgoing['verify'],
  294. 'enable_http2': settings_outgoing['enable_http2'],
  295. 'max_connections': settings_outgoing['pool_connections'],
  296. 'max_keepalive_connections': settings_outgoing['pool_maxsize'],
  297. 'keepalive_expiry': settings_outgoing['keepalive_expiry'],
  298. 'local_addresses': settings_outgoing['source_ips'],
  299. 'using_tor_proxy': settings_outgoing['using_tor_proxy'],
  300. 'proxies': settings_outgoing['proxies'],
  301. 'max_redirects': settings_outgoing['max_redirects'],
  302. 'retries': settings_outgoing['retries'],
  303. 'retry_on_http_error': None,
  304. }
  305. def new_network(params, logger_name=None):
  306. nonlocal default_params
  307. result = {}
  308. result.update(default_params)
  309. result.update(params)
  310. if logger_name:
  311. result['logger_name'] = logger_name
  312. return Network(**result)
  313. def iter_networks():
  314. nonlocal settings_engines
  315. for engine_spec in settings_engines:
  316. engine_name = engine_spec['name']
  317. engine = engines.get(engine_name)
  318. if engine is None:
  319. continue
  320. network = getattr(engine, 'network', None)
  321. yield engine_name, engine, network
  322. if NETWORKS:
  323. done()
  324. NETWORKS.clear()
  325. NETWORKS[DEFAULT_NAME] = new_network({}, logger_name='default')
  326. NETWORKS['ipv4'] = new_network({'local_addresses': '0.0.0.0'}, logger_name='ipv4')
  327. NETWORKS['ipv6'] = new_network({'local_addresses': '::'}, logger_name='ipv6')
  328. # define networks from outgoing.networks
  329. for network_name, network in settings_outgoing['networks'].items():
  330. NETWORKS[network_name] = new_network(network, logger_name=network_name)
  331. # define networks from engines.[i].network (except references)
  332. for engine_name, engine, network in iter_networks():
  333. if network is None:
  334. network = {}
  335. for attribute_name, attribute_value in default_params.items():
  336. if hasattr(engine, attribute_name):
  337. network[attribute_name] = getattr(engine, attribute_name)
  338. else:
  339. network[attribute_name] = attribute_value
  340. NETWORKS[engine_name] = new_network(network, logger_name=engine_name)
  341. elif isinstance(network, dict):
  342. NETWORKS[engine_name] = new_network(network, logger_name=engine_name)
  343. # define networks from engines.[i].network (references)
  344. for engine_name, engine, network in iter_networks():
  345. if isinstance(network, str):
  346. NETWORKS[engine_name] = NETWORKS[network]
  347. # the /image_proxy endpoint has a dedicated network.
  348. # same parameters than the default network, but HTTP/2 is disabled.
  349. # It decreases the CPU load average, and the total time is more or less the same
  350. if 'image_proxy' not in NETWORKS:
  351. image_proxy_params = default_params.copy()
  352. image_proxy_params['enable_http2'] = False
  353. NETWORKS['image_proxy'] = new_network(image_proxy_params, logger_name='image_proxy')
  354. @atexit.register
  355. def done():
  356. """Close all HTTP client
  357. Avoid a warning at exit
  358. See https://github.com/encode/httpx/pull/2026
  359. Note: since Network.aclose has to be async, it is not possible to call this method on Network.__del__
  360. So Network.aclose is called here using atexit.register
  361. """
  362. try:
  363. loop = get_loop()
  364. if loop:
  365. future = asyncio.run_coroutine_threadsafe(Network.aclose_all(), loop)
  366. # wait 3 seconds to close the HTTP clients
  367. future.result(3)
  368. finally:
  369. NETWORKS.clear()
  370. NETWORKS[DEFAULT_NAME] = Network()