raise_for_httperror.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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) or (
  13. '/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(message='Cloudflare CAPTCHA', suspended_time=3600 * 24 * 15)
  29. if is_cloudflare_firewall(resp):
  30. raise SearxEngineAccessDeniedException(message='Cloudflare Firewall', suspended_time=3600 * 24)
  31. def raise_for_recaptcha(resp):
  32. if resp.status_code == 503 and '"https://www.google.com/recaptcha/' in resp.text:
  33. raise SearxEngineCaptchaException(message='ReCAPTCHA', suspended_time=3600 * 24 * 7)
  34. def raise_for_captcha(resp):
  35. raise_for_cloudflare_captcha(resp)
  36. raise_for_recaptcha(resp)
  37. def raise_for_httperror(resp):
  38. """Raise exception for an HTTP response is an error.
  39. Args:
  40. resp (requests.Response): Response to check
  41. Raises:
  42. requests.HTTPError: raise by resp.raise_for_status()
  43. searx.exceptions.SearxEngineAccessDeniedException: raise when the HTTP status code is 402 or 403.
  44. searx.exceptions.SearxEngineTooManyRequestsException: raise when the HTTP status code is 429.
  45. searx.exceptions.SearxEngineCaptchaException: raise when if CATPCHA challenge is detected.
  46. """
  47. if resp.status_code and resp.status_code >= 400:
  48. raise_for_captcha(resp)
  49. if resp.status_code in (402, 403):
  50. raise SearxEngineAccessDeniedException(
  51. message='HTTP error ' + str(resp.status_code), suspended_time=3600 * 24
  52. )
  53. if resp.status_code == 429:
  54. raise SearxEngineTooManyRequestsException()
  55. resp.raise_for_status()