raise_for_httperror.py 2.7 KB

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