raise_for_httperror.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pylint: disable=missing-function-docstring
  4. """Raise exception for an HTTP response is an error.
  5. """
  6. from searx.exceptions import (
  7. SearxEngineCaptchaException,
  8. SearxEngineTooManyRequestsException,
  9. SearxEngineAccessDeniedException,
  10. )
  11. def is_cloudflare_challenge(resp):
  12. if resp.status_code in [429, 503]:
  13. if (('__cf_chl_jschl_tk__=' in resp.text)
  14. or ('/cdn-cgi/challenge-platform/' in resp.text
  15. and 'orchestrate/jsch/v1' in resp.text
  16. and 'window._cf_chl_enter(' in resp.text
  17. )):
  18. return True
  19. if resp.status_code == 403 and '__cf_chl_captcha_tk__=' in resp.text:
  20. return True
  21. return False
  22. def is_cloudflare_firewall(resp):
  23. return resp.status_code == 403 and '<span class="cf-error-code">1020</span>' in resp.text
  24. def raise_for_cloudflare_captcha(resp):
  25. if resp.headers.get('Server', '').startswith('cloudflare'):
  26. if is_cloudflare_challenge(resp):
  27. # https://support.cloudflare.com/hc/en-us/articles/200170136-Understanding-Cloudflare-Challenge-Passage-Captcha-
  28. # suspend for 2 weeks
  29. raise SearxEngineCaptchaException(
  30. message='Cloudflare CAPTCHA',
  31. suspended_time=3600 * 24 * 15
  32. )
  33. if is_cloudflare_firewall(resp):
  34. raise SearxEngineAccessDeniedException(
  35. message='Cloudflare Firewall', suspended_time=3600 * 24
  36. )
  37. def raise_for_recaptcha(resp):
  38. if (resp.status_code == 503
  39. and '"https://www.google.com/recaptcha/' in resp.text
  40. ):
  41. raise SearxEngineCaptchaException(message='ReCAPTCHA', suspended_time=3600 * 24 * 7)
  42. def raise_for_captcha(resp):
  43. raise_for_cloudflare_captcha(resp)
  44. raise_for_recaptcha(resp)
  45. def raise_for_httperror(resp):
  46. """Raise exception for an HTTP response is an error.
  47. Args:
  48. resp (requests.Response): Response to check
  49. Raises:
  50. requests.HTTPError: raise by resp.raise_for_status()
  51. searx.exceptions.SearxEngineAccessDeniedException: raise when the HTTP status code is 402 or 403.
  52. searx.exceptions.SearxEngineTooManyRequestsException: raise when the HTTP status code is 429.
  53. searx.exceptions.SearxEngineCaptchaException: raise when if CATPCHA challenge is detected.
  54. """
  55. if resp.status_code and resp.status_code >= 400:
  56. raise_for_captcha(resp)
  57. if resp.status_code in (402, 403):
  58. raise SearxEngineAccessDeniedException(
  59. message='HTTP error ' + str(resp.status_code),
  60. suspended_time=3600 * 24
  61. )
  62. if resp.status_code == 429:
  63. raise SearxEngineTooManyRequestsException()
  64. resp.raise_for_status()