settings_defaults.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Implementation of the default settings.
  3. """
  4. import typing
  5. import numbers
  6. import errno
  7. import os
  8. import logging
  9. from base64 import b64decode
  10. from os.path import dirname, abspath
  11. from .sxng_locales import sxng_locales
  12. searx_dir = abspath(dirname(__file__))
  13. logger = logging.getLogger('searx')
  14. OUTPUT_FORMATS = ['html', 'csv', 'json', 'rss']
  15. SXNG_LOCALE_TAGS = ['all', 'auto'] + list(l[0] for l in sxng_locales)
  16. SIMPLE_STYLE = ('auto', 'light', 'dark', 'black')
  17. CATEGORIES_AS_TABS = {
  18. 'general': {},
  19. 'images': {},
  20. 'videos': {},
  21. 'news': {},
  22. 'map': {},
  23. 'music': {},
  24. 'it': {},
  25. 'science': {},
  26. 'files': {},
  27. 'social media': {},
  28. }
  29. STR_TO_BOOL = {
  30. '0': False,
  31. 'false': False,
  32. 'off': False,
  33. '1': True,
  34. 'true': True,
  35. 'on': True,
  36. }
  37. _UNDEFINED = object()
  38. class SettingsValue:
  39. """Check and update a setting value"""
  40. def __init__(
  41. self,
  42. type_definition: typing.Union[None, typing.Any, typing.Tuple[typing.Any]] = None,
  43. default: typing.Any = None,
  44. environ_name: str = None,
  45. ):
  46. self.type_definition = (
  47. type_definition if type_definition is None or isinstance(type_definition, tuple) else (type_definition,)
  48. )
  49. self.default = default
  50. self.environ_name = environ_name
  51. @property
  52. def type_definition_repr(self):
  53. types_str = [t.__name__ if isinstance(t, type) else repr(t) for t in self.type_definition]
  54. return ', '.join(types_str)
  55. def check_type_definition(self, value: typing.Any) -> None:
  56. if value in self.type_definition:
  57. return
  58. type_list = tuple(t for t in self.type_definition if isinstance(t, type))
  59. if not isinstance(value, type_list):
  60. raise ValueError('The value has to be one of these types/values: {}'.format(self.type_definition_repr))
  61. def __call__(self, value: typing.Any) -> typing.Any:
  62. if value == _UNDEFINED:
  63. value = self.default
  64. # override existing value with environ
  65. if self.environ_name and self.environ_name in os.environ:
  66. value = os.environ[self.environ_name]
  67. if self.type_definition == (bool,):
  68. value = STR_TO_BOOL[value.lower()]
  69. self.check_type_definition(value)
  70. return value
  71. class SettingSublistValue(SettingsValue):
  72. """Check the value is a sublist of type definition."""
  73. def check_type_definition(self, value: typing.Any) -> typing.Any:
  74. if not isinstance(value, list):
  75. raise ValueError('The value has to a list')
  76. for item in value:
  77. if not item in self.type_definition[0]:
  78. raise ValueError('{} not in {}'.format(item, self.type_definition))
  79. class SettingsDirectoryValue(SettingsValue):
  80. """Check and update a setting value that is a directory path"""
  81. def check_type_definition(self, value: typing.Any) -> typing.Any:
  82. super().check_type_definition(value)
  83. if not os.path.isdir(value):
  84. raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), value)
  85. def __call__(self, value: typing.Any) -> typing.Any:
  86. if value == '':
  87. value = self.default
  88. return super().__call__(value)
  89. class SettingsBytesValue(SettingsValue):
  90. """str are base64 decoded"""
  91. def __call__(self, value: typing.Any) -> typing.Any:
  92. if isinstance(value, str):
  93. value = b64decode(value)
  94. return super().__call__(value)
  95. def apply_schema(settings, schema, path_list):
  96. error = False
  97. for key, value in schema.items():
  98. if isinstance(value, SettingsValue):
  99. try:
  100. settings[key] = value(settings.get(key, _UNDEFINED))
  101. except Exception as e: # pylint: disable=broad-except
  102. # don't stop now: check other values
  103. logger.error('%s: %s', '.'.join([*path_list, key]), e)
  104. error = True
  105. elif isinstance(value, dict):
  106. error = error or apply_schema(settings.setdefault(key, {}), schema[key], [*path_list, key])
  107. else:
  108. settings.setdefault(key, value)
  109. if len(path_list) == 0 and error:
  110. raise ValueError('Invalid settings.yml')
  111. return error
  112. SCHEMA = {
  113. 'general': {
  114. 'debug': SettingsValue(bool, False, 'SEARXNG_DEBUG'),
  115. 'instance_name': SettingsValue(str, 'SearXNG'),
  116. 'privacypolicy_url': SettingsValue((None, False, str), None),
  117. 'contact_url': SettingsValue((None, False, str), None),
  118. 'donation_url': SettingsValue((bool, str), "https://docs.searxng.org/donate.html"),
  119. 'enable_metrics': SettingsValue(bool, True),
  120. 'open_metrics': SettingsValue(str, ''),
  121. },
  122. 'brand': {
  123. 'issue_url': SettingsValue(str, 'https://github.com/searxng/searxng/issues'),
  124. 'new_issue_url': SettingsValue(str, 'https://github.com/searxng/searxng/issues/new'),
  125. 'docs_url': SettingsValue(str, 'https://docs.searxng.org'),
  126. 'public_instances': SettingsValue((False, str), 'https://searx.space'),
  127. 'wiki_url': SettingsValue(str, 'https://github.com/searxng/searxng/wiki'),
  128. 'custom': SettingsValue(dict, {'links': {}}),
  129. },
  130. 'search': {
  131. 'safe_search': SettingsValue((0, 1, 2), 0),
  132. 'autocomplete': SettingsValue(str, ''),
  133. 'autocomplete_min': SettingsValue(int, 4),
  134. 'favicon_resolver': SettingsValue(str, ''),
  135. 'default_lang': SettingsValue(tuple(SXNG_LOCALE_TAGS + ['']), ''),
  136. 'languages': SettingSublistValue(SXNG_LOCALE_TAGS, SXNG_LOCALE_TAGS),
  137. 'ban_time_on_fail': SettingsValue(numbers.Real, 5),
  138. 'max_ban_time_on_fail': SettingsValue(numbers.Real, 120),
  139. 'suspended_times': {
  140. 'SearxEngineAccessDenied': SettingsValue(numbers.Real, 86400),
  141. 'SearxEngineCaptcha': SettingsValue(numbers.Real, 86400),
  142. 'SearxEngineTooManyRequests': SettingsValue(numbers.Real, 3600),
  143. 'cf_SearxEngineCaptcha': SettingsValue(numbers.Real, 1296000),
  144. 'cf_SearxEngineAccessDenied': SettingsValue(numbers.Real, 86400),
  145. 'recaptcha_SearxEngineCaptcha': SettingsValue(numbers.Real, 604800),
  146. },
  147. 'formats': SettingsValue(list, OUTPUT_FORMATS),
  148. 'max_page': SettingsValue(int, 0),
  149. },
  150. 'server': {
  151. 'port': SettingsValue((int, str), 8888, 'SEARXNG_PORT'),
  152. 'bind_address': SettingsValue(str, '127.0.0.1', 'SEARXNG_BIND_ADDRESS'),
  153. 'limiter': SettingsValue(bool, False, 'SEARXNG_LIMITER'),
  154. 'public_instance': SettingsValue(bool, False, 'SEARXNG_PUBLIC_INSTANCE'),
  155. 'secret_key': SettingsValue(str, environ_name='SEARXNG_SECRET'),
  156. 'base_url': SettingsValue((False, str), False, 'SEARXNG_BASE_URL'),
  157. 'image_proxy': SettingsValue(bool, False, 'SEARXNG_IMAGE_PROXY'),
  158. 'http_protocol_version': SettingsValue(('1.0', '1.1'), '1.0'),
  159. 'method': SettingsValue(('POST', 'GET'), 'POST'),
  160. 'default_http_headers': SettingsValue(dict, {}),
  161. },
  162. 'redis': {
  163. 'url': SettingsValue((None, False, str), False, 'SEARXNG_REDIS_URL'),
  164. },
  165. 'ui': {
  166. 'static_path': SettingsDirectoryValue(str, os.path.join(searx_dir, 'static')),
  167. 'static_use_hash': SettingsValue(bool, False, 'SEARXNG_STATIC_USE_HASH'),
  168. 'templates_path': SettingsDirectoryValue(str, os.path.join(searx_dir, 'templates')),
  169. 'default_theme': SettingsValue(str, 'simple'),
  170. 'default_locale': SettingsValue(str, ''),
  171. 'theme_args': {
  172. 'simple_style': SettingsValue(SIMPLE_STYLE, 'auto'),
  173. },
  174. 'center_alignment': SettingsValue(bool, False),
  175. 'results_on_new_tab': SettingsValue(bool, False),
  176. 'advanced_search': SettingsValue(bool, False),
  177. 'query_in_title': SettingsValue(bool, False),
  178. 'infinite_scroll': SettingsValue(bool, False),
  179. 'cache_url': SettingsValue(str, 'https://web.archive.org/web/'),
  180. 'search_on_category_select': SettingsValue(bool, True),
  181. 'hotkeys': SettingsValue(('default', 'vim'), 'default'),
  182. 'url_formatting': SettingsValue(('pretty', 'full', 'host'), 'pretty'),
  183. },
  184. 'preferences': {
  185. 'lock': SettingsValue(list, []),
  186. },
  187. 'outgoing': {
  188. 'useragent_suffix': SettingsValue(str, ''),
  189. 'request_timeout': SettingsValue(numbers.Real, 3.0),
  190. 'enable_http2': SettingsValue(bool, True),
  191. 'verify': SettingsValue((bool, str), True),
  192. 'max_request_timeout': SettingsValue((None, numbers.Real), None),
  193. 'pool_connections': SettingsValue(int, 100),
  194. 'pool_maxsize': SettingsValue(int, 10),
  195. 'keepalive_expiry': SettingsValue(numbers.Real, 5.0),
  196. # default maximum redirect
  197. # from https://github.com/psf/requests/blob/8c211a96cdbe9fe320d63d9e1ae15c5c07e179f8/requests/models.py#L55
  198. 'max_redirects': SettingsValue(int, 30),
  199. 'retries': SettingsValue(int, 0),
  200. 'proxies': SettingsValue((None, str, dict), None),
  201. 'source_ips': SettingsValue((None, str, list), None),
  202. # Tor configuration
  203. 'using_tor_proxy': SettingsValue(bool, False),
  204. 'extra_proxy_timeout': SettingsValue(int, 0),
  205. 'networks': {},
  206. },
  207. 'result_proxy': {
  208. 'url': SettingsValue((None, str), None),
  209. 'key': SettingsBytesValue((None, bytes), None),
  210. 'proxify_results': SettingsValue(bool, False),
  211. },
  212. 'plugins': SettingsValue(list, []),
  213. 'enabled_plugins': SettingsValue((None, list), None),
  214. 'checker': {
  215. 'off_when_debug': SettingsValue(bool, True, None),
  216. 'scheduling': SettingsValue((None, dict), None, None),
  217. },
  218. 'categories_as_tabs': SettingsValue(dict, CATEGORIES_AS_TABS),
  219. 'engines': SettingsValue(list, []),
  220. 'doi_resolvers': {},
  221. }
  222. def settings_set_defaults(settings):
  223. apply_schema(settings, SCHEMA, [])
  224. return settings