http_user_agent.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 __future__ import annotations
  14. import re
  15. from ipaddress import (
  16. IPv4Network,
  17. IPv6Network,
  18. )
  19. import flask
  20. import werkzeug
  21. from searx.tools import config
  22. from ._helpers import too_many_requests
  23. USER_AGENT = (
  24. r'('
  25. + r'unknown'
  26. + r'|[Cc][Uu][Rr][Ll]|[wW]get|Scrapy|splash|JavaFX|FeedFetcher|python-requests|Go-http-client|Java|Jakarta|okhttp'
  27. + r'|HttpClient|Jersey|Python|libwww-perl|Ruby|SynHttpClient|UniversalFeedParser|Googlebot|GoogleImageProxy'
  28. + r'|bingbot|Baiduspider|yacybot|YandexMobileBot|YandexBot|Yahoo! Slurp|MJ12bot|AhrefsBot|archive.org_bot|msnbot'
  29. + r'|MJ12bot|SeznamBot|linkdexbot|Netvibes|SMTBot|zgrab|James BOT|Sogou|Abonti|Pixray|Spinn3r|SemrushBot|Exabot'
  30. + r'|ZmEu|BLEXBot|bitlybot'
  31. # unmaintained Farside instances
  32. + r'|'
  33. + re.escape(r'Mozilla/5.0 (compatible; Farside/0.1.0; +https://farside.link)')
  34. # other bots and client to block
  35. + '|.*PetalBot.*'
  36. + r')'
  37. )
  38. """Regular expression that matches to User-Agent_ from known *bots*"""
  39. _regexp = None
  40. def regexp_user_agent():
  41. global _regexp # pylint: disable=global-statement
  42. if not _regexp:
  43. _regexp = re.compile(USER_AGENT)
  44. return _regexp
  45. def filter_request(
  46. network: IPv4Network | IPv6Network,
  47. request: flask.Request,
  48. cfg: config.Config,
  49. ) -> werkzeug.Response | None:
  50. user_agent = request.headers.get('User-Agent', 'unknown')
  51. if regexp_user_agent().match(user_agent):
  52. return too_many_requests(network, f"bot detected, HTTP header User-Agent: {user_agent}")
  53. return None