settings_defaults.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 os.path import dirname, abspath
  11. from searx.languages import language_codes as languages
  12. searx_dir = abspath(dirname(__file__))
  13. logger = logging.getLogger('searx')
  14. OUTPUT_FORMATS = ['html', 'csv', 'json', 'rss']
  15. LANGUAGE_CODES = ['all'] + list(l[0] for l in languages)
  16. OSCAR_STYLE = ('logicodev', 'logicodev-dark', 'pointhi')
  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. def apply_schema(settings, schema, path_list):
  100. error = False
  101. for key, value in schema.items():
  102. if isinstance(value, SettingsValue):
  103. try:
  104. settings[key] = value(settings.get(key, _UNDEFINED))
  105. except Exception as e: # pylint: disable=broad-except
  106. # don't stop now: check other values
  107. logger.error('%s: %s', '.'.join([*path_list, key]), e)
  108. error = True
  109. elif isinstance(value, dict):
  110. error = error or apply_schema(settings.setdefault(key, {}), schema[key], [*path_list, key])
  111. else:
  112. settings.setdefault(key, value)
  113. if len(path_list) == 0 and error:
  114. raise ValueError('Invalid settings.yml')
  115. return error
  116. SCHEMA = {
  117. 'general': {
  118. 'debug': SettingsValue(bool, False, 'SEARXNG_DEBUG'),
  119. 'instance_name': SettingsValue(str, 'SearXNG'),
  120. 'contact_url': SettingsValue((None, False, str), None),
  121. 'enable_metrics': SettingsValue(bool, True),
  122. },
  123. 'brand': {
  124. 'issue_url': SettingsValue(str, 'https://github.com/searxng/searxng/issues'),
  125. 'new_issue_url': SettingsValue(str, 'https://github.com/searxng/searxng/issues/new'),
  126. 'docs_url': SettingsValue(str, 'https://docs.searxng.org'),
  127. 'public_instances': SettingsValue(str, 'https://searx.space'),
  128. 'wiki_url': SettingsValue(str, 'https://github.com/searxng/searxng/wiki'),
  129. },
  130. 'search': {
  131. 'safe_search': SettingsValue((0, 1, 2), 0),
  132. 'autocomplete': SettingsValue(str, ''),
  133. 'default_lang': SettingsValue(tuple(LANGUAGE_CODES + ['']), ''),
  134. 'languages': SettingSublistValue(LANGUAGE_CODES, LANGUAGE_CODES),
  135. 'ban_time_on_fail': SettingsValue(numbers.Real, 5),
  136. 'max_ban_time_on_fail': SettingsValue(numbers.Real, 120),
  137. 'formats': SettingsValue(list, OUTPUT_FORMATS),
  138. },
  139. 'server': {
  140. 'port': SettingsValue((int, str), 8888, 'SEARXNG_PORT'),
  141. 'bind_address': SettingsValue(str, '127.0.0.1', 'SEARXNG_BIND_ADDRESS'),
  142. 'secret_key': SettingsValue(str, environ_name='SEARXNG_SECRET'),
  143. 'base_url': SettingsValue((False, str), False),
  144. 'image_proxy': SettingsValue(bool, False),
  145. 'http_protocol_version': SettingsValue(('1.0', '1.1'), '1.0'),
  146. 'method': SettingsValue(('POST', 'GET'), 'POST'),
  147. 'default_http_headers': SettingsValue(dict, {}),
  148. },
  149. 'redis': {
  150. 'url': SettingsValue(str, 'unix:///usr/local/searxng-redis/run/redis.sock?db=0'),
  151. },
  152. 'ui': {
  153. 'static_path': SettingsDirectoryValue(str, os.path.join(searx_dir, 'static')),
  154. 'templates_path': SettingsDirectoryValue(str, os.path.join(searx_dir, 'templates')),
  155. 'default_theme': SettingsValue(str, 'oscar'),
  156. 'default_locale': SettingsValue(str, ''),
  157. 'theme_args': {
  158. 'oscar_style': SettingsValue(OSCAR_STYLE, 'logicodev'),
  159. 'simple_style': SettingsValue(SIMPLE_STYLE, 'auto'),
  160. },
  161. 'results_on_new_tab': SettingsValue(bool, False),
  162. 'advanced_search': SettingsValue(bool, False),
  163. 'query_in_title': SettingsValue(bool, False),
  164. },
  165. 'preferences': {
  166. 'lock': SettingsValue(list, []),
  167. },
  168. 'outgoing': {
  169. 'useragent_suffix': SettingsValue(str, ''),
  170. 'request_timeout': SettingsValue(numbers.Real, 3.0),
  171. 'enable_http2': SettingsValue(bool, True),
  172. 'max_request_timeout': SettingsValue((None, numbers.Real), None),
  173. # Magic number kept from previous code
  174. 'pool_connections': SettingsValue(int, 100),
  175. # Picked from constructor
  176. 'pool_maxsize': SettingsValue(int, 10),
  177. 'keepalive_expiry': SettingsValue(numbers.Real, 5.0),
  178. # default maximum redirect
  179. # from https://github.com/psf/requests/blob/8c211a96cdbe9fe320d63d9e1ae15c5c07e179f8/requests/models.py#L55
  180. 'max_redirects': SettingsValue(int, 30),
  181. 'retries': SettingsValue(int, 0),
  182. 'proxies': SettingsValue((None, str, dict), None),
  183. 'source_ips': SettingsValue((None, str, list), None),
  184. # Tor configuration
  185. 'using_tor_proxy': SettingsValue(bool, False),
  186. 'extra_proxy_timeout': SettingsValue(int, 0),
  187. 'networks': {},
  188. },
  189. 'plugins': SettingsValue(list, []),
  190. 'enabled_plugins': SettingsValue((None, list), None),
  191. 'checker': {
  192. 'off_when_debug': SettingsValue(bool, True),
  193. },
  194. 'categories_as_tabs': SettingsValue(dict, CATEGORIES_AS_TABS),
  195. 'engines': SettingsValue(list, []),
  196. 'doi_resolvers': {},
  197. }
  198. def settings_set_defaults(settings):
  199. # compatibility with searx variables
  200. for searx, searxng in SEARX_ENVIRON_VARIABLES.items():
  201. if searx in os.environ and searxng not in os.environ:
  202. os.environ[searxng] = os.environ[searx]
  203. logger.warning('%s uses value from %s', searxng, searx)
  204. apply_schema(settings, SCHEMA, [])
  205. return settings