settings_defaults.py 9.2 KB

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