http_user_agent.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """
  4. Method ``http_user_agent``
  5. --------------------------
  6. The ``http_user_agent`` method evaluates a request as the request of a bot if
  7. the User-Agent_ header is unset or matches the regular expression
  8. :py:obj:`USER_AGENT`.
  9. .. _User-Agent:
  10. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
  11. """
  12. # pylint: disable=unused-argument
  13. from typing import Optional, Tuple
  14. import re
  15. import flask
  16. from searx.tools import config
  17. USER_AGENT = (
  18. r'('
  19. + r'unknown'
  20. + r'|[Cc][Uu][Rr][Ll]|[wW]get|Scrapy|splash|JavaFX|FeedFetcher|python-requests|Go-http-client|Java|Jakarta|okhttp'
  21. + r'|HttpClient|Jersey|Python|libwww-perl|Ruby|SynHttpClient|UniversalFeedParser|Googlebot|GoogleImageProxy'
  22. + r'|bingbot|Baiduspider|yacybot|YandexMobileBot|YandexBot|Yahoo! Slurp|MJ12bot|AhrefsBot|archive.org_bot|msnbot'
  23. + r'|MJ12bot|SeznamBot|linkdexbot|Netvibes|SMTBot|zgrab|James BOT|Sogou|Abonti|Pixray|Spinn3r|SemrushBot|Exabot'
  24. + r'|ZmEu|BLEXBot|bitlybot'
  25. # unmaintained Farside instances
  26. + r'|'
  27. + re.escape(r'Mozilla/5.0 (compatible; Farside/0.1.0; +https://farside.link)')
  28. # other bots and client to block
  29. + '|.*PetalBot.*'
  30. + r')'
  31. )
  32. """Regular expression that matches to User-Agent_ from known *bots*"""
  33. _regexp = None
  34. def regexp_user_agent():
  35. global _regexp # pylint: disable=global-statement
  36. if not _regexp:
  37. _regexp = re.compile(USER_AGENT)
  38. return _regexp
  39. def filter_request(request: flask.Request, cfg: config.Config) -> Optional[Tuple[int, str]]:
  40. user_agent = request.headers.get('User-Agent', 'unknown')
  41. if regexp_user_agent().match(user_agent):
  42. return (
  43. 429,
  44. f"bot detected, HTTP header User-Agent: {user_agent}",
  45. )
  46. return None