raise_for_httperror.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Raise exception for an HTTP response is an error.
  3. """
  4. from searx.exceptions import (
  5. SearxEngineCaptchaException,
  6. SearxEngineTooManyRequestsException,
  7. SearxEngineAccessDeniedException,
  8. )
  9. from searx import get_setting
  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(
  29. message='Cloudflare CAPTCHA', suspended_time=get_setting('search.suspended_times.cf_SearxEngineCaptcha')
  30. )
  31. if is_cloudflare_firewall(resp):
  32. raise SearxEngineAccessDeniedException(
  33. message='Cloudflare Firewall',
  34. suspended_time=get_setting('search.suspended_times.cf_SearxEngineAccessDenied'),
  35. )
  36. def raise_for_recaptcha(resp):
  37. if resp.status_code == 503 and '"https://www.google.com/recaptcha/' in resp.text:
  38. raise SearxEngineCaptchaException(
  39. message='ReCAPTCHA', suspended_time=get_setting('search.suspended_times.recaptcha_SearxEngineCaptcha')
  40. )
  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(message='HTTP error ' + str(resp.status_code))
  58. if resp.status_code == 429:
  59. raise SearxEngineTooManyRequestsException()
  60. resp.raise_for_status()