limiter.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """.. _limiter src:
  4. Limiter
  5. =======
  6. .. sidebar:: info
  7. The limiter requires a :ref:`Redis <settings redis>` database.
  8. Bot protection / IP rate limitation. The intention of rate limitation is to
  9. limit suspicious requests from an IP. The motivation behind this is the fact
  10. that SearXNG passes through requests from bots and is thus classified as a bot
  11. itself. As a result, the SearXNG engine then receives a CAPTCHA or is blocked
  12. by the search engine (the origin) in some other way.
  13. To avoid blocking, the requests from bots to SearXNG must also be blocked, this
  14. is the task of the limiter. To perform this task, the limiter uses the methods
  15. from the :py:obj:`searx.botdetection`.
  16. To enable the limiter activate:
  17. .. code:: yaml
  18. server:
  19. ...
  20. limiter: true # rate limit the number of request on the instance, block some bots
  21. and set the redis-url connection. Check the value, it depends on your redis DB
  22. (see :ref:`settings redis`), by example:
  23. .. code:: yaml
  24. redis:
  25. url: unix:///usr/local/searxng-redis/run/redis.sock?db=0
  26. """
  27. from typing import Optional, Tuple
  28. from pathlib import Path
  29. import flask
  30. import pytomlpp as toml
  31. from searx import logger
  32. from searx.tools import config
  33. from searx.botdetection import (
  34. http_accept,
  35. http_accept_encoding,
  36. http_accept_language,
  37. http_connection,
  38. http_user_agent,
  39. ip_limit,
  40. )
  41. LIMITER_CFG_SCHEMA = Path(__file__).parent / "limiter.toml"
  42. """Base configuration (schema) of the botdetection."""
  43. LIMITER_CFG = Path('/etc/searxng/limiter.toml')
  44. """Lokal Limiter configuration."""
  45. CFG_DEPRECATED = {
  46. # "dummy.old.foo": "config 'dummy.old.foo' exists only for tests. Don't use it in your real project config."
  47. }
  48. CFG = None
  49. def get_cfg() -> config.Config:
  50. if CFG is None:
  51. init_cfg(logger)
  52. return CFG
  53. def init_cfg(log):
  54. global CFG # pylint: disable=global-statement
  55. CFG = config.Config(cfg_schema=toml.load(LIMITER_CFG_SCHEMA), deprecated=CFG_DEPRECATED)
  56. if not LIMITER_CFG.exists():
  57. log.warning("missing config file: %s", LIMITER_CFG)
  58. return
  59. log.info("load config file: %s", LIMITER_CFG)
  60. try:
  61. upd_cfg = toml.load(LIMITER_CFG)
  62. except toml.DecodeError as exc:
  63. msg = str(exc).replace('\t', '').replace('\n', ' ')
  64. log.error("%s: %s", LIMITER_CFG, msg)
  65. raise
  66. is_valid, issue_list = CFG.validate(upd_cfg)
  67. for msg in issue_list:
  68. log.error(str(msg))
  69. if not is_valid:
  70. raise TypeError(f"schema of {LIMITER_CFG} is invalid, can't cutomize limiter configuration from!")
  71. CFG.update(upd_cfg)
  72. def filter_request(request: flask.Request) -> Optional[Tuple[int, str]]:
  73. if request.path == '/healthz':
  74. return None
  75. for func in [
  76. http_user_agent,
  77. ]:
  78. val = func.filter_request(request, CFG)
  79. if val is not None:
  80. return val
  81. if request.path == '/search':
  82. for func in [
  83. http_accept,
  84. http_accept_encoding,
  85. http_accept_language,
  86. http_connection,
  87. http_user_agent,
  88. ip_limit,
  89. ]:
  90. val = func.filter_request(request, CFG)
  91. if val is not None:
  92. return val
  93. return None