raise_for_httperror.py 2.6 KB

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