settings_defaults.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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') + tuple(l[0] for l in languages)
  16. OSCAR_STYLE = ('logicodev', 'logicodev-dark', 'pointhi')
  17. CATEGORY_ORDER = [
  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. # compatibility
  39. SEARX_ENVIRON_VARIABLES = {
  40. 'SEARX_DISABLE_ETC_SETTINGS': 'SEARXNG_DISABLE_ETC_SETTINGS',
  41. 'SEARX_SETTINGS_PATH': 'SEARXNG_SETTINGS_PATH',
  42. 'SEARX_DEBUG': 'SEARXNG_DEBUG',
  43. 'SEARX_PORT': 'SEARXNG_PORT',
  44. 'SEARX_BIND_ADDRESS': 'SEARXNG_BIND_ADDRESS',
  45. 'SEARX_SECRET': 'SEARXNG_SECRET',
  46. }
  47. class SettingsValue:
  48. """Check and update a setting value
  49. """
  50. def __init__(self,
  51. type_definition: typing.Union[None, typing.Any, typing.Tuple[typing.Any]]=None,
  52. default: typing.Any=None,
  53. environ_name: str=None):
  54. self.type_definition = (
  55. type_definition
  56. if type_definition is None or isinstance(type_definition, tuple)
  57. 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 = [
  64. t.__name__ if isinstance(t, type) else repr(t)
  65. for t in self.type_definition
  66. ]
  67. return ', '.join(types_str)
  68. def check_type_definition(self, value: typing.Any) -> None:
  69. if value in self.type_definition:
  70. return
  71. type_list = tuple(t for t in self.type_definition if isinstance(t, type))
  72. if not isinstance(value, type_list):
  73. raise ValueError(
  74. 'The value has to be one of these types/values: {}'.format(
  75. self.type_definition_repr))
  76. def __call__(self, value: typing.Any) -> typing.Any:
  77. if value == _UNDEFINED:
  78. value = self.default
  79. # override existing value with environ
  80. if self.environ_name and self.environ_name in os.environ:
  81. value = os.environ[self.environ_name]
  82. if self.type_definition == (bool,):
  83. value = STR_TO_BOOL[value.lower()]
  84. self.check_type_definition(value)
  85. return value
  86. class SettingsDirectoryValue(SettingsValue):
  87. """Check and update a setting value that is a directory path
  88. """
  89. def check_type_definition(self, value: typing.Any) -> typing.Any:
  90. super().check_type_definition(value)
  91. if not os.path.isdir(value):
  92. raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), value)
  93. def __call__(self, value: typing.Any) -> typing.Any:
  94. if value == '':
  95. value = self.default
  96. return super().__call__(value)
  97. def apply_schema(settings, schema, path_list):
  98. error = False
  99. for key, value in schema.items():
  100. if isinstance(value, SettingsValue):
  101. try:
  102. settings[key] = value(settings.get(key, _UNDEFINED))
  103. except Exception as e: # pylint: disable=broad-except
  104. # don't stop now: check other values
  105. logger.error('%s: %s', '.'.join([*path_list, key]), e)
  106. error = True
  107. elif isinstance(value, dict):
  108. error = error or apply_schema(settings.setdefault(key, {}), schema[key], [*path_list, key])
  109. else:
  110. settings.setdefault(key, value)
  111. if len(path_list) == 0 and error:
  112. raise ValueError('Invalid settings.yml')
  113. return error
  114. SCHEMA = {
  115. 'general': {
  116. 'debug': SettingsValue(bool, False, 'SEARXNG_DEBUG'),
  117. 'instance_name': SettingsValue(str, 'SearXNG'),
  118. 'contact_url': SettingsValue((None, False, str), None),
  119. },
  120. 'brand': {
  121. 'issue_url': SettingsValue(str, None),
  122. 'new_issue_url': SettingsValue(str, None),
  123. 'docs_url': SettingsValue(str, None),
  124. 'public_instances': SettingsValue(str, None),
  125. 'wiki_url': SettingsValue(str, None),
  126. },
  127. 'search': {
  128. 'safe_search': SettingsValue((0,1,2), 0),
  129. 'autocomplete': SettingsValue(str, ''),
  130. 'default_lang': SettingsValue(LANGUAGE_CODES, ''),
  131. 'ban_time_on_fail': SettingsValue(numbers.Real, 5),
  132. 'max_ban_time_on_fail': SettingsValue(numbers.Real, 120),
  133. 'formats': SettingsValue(list, OUTPUT_FORMATS),
  134. },
  135. 'server': {
  136. 'port': SettingsValue((int,str), 8888, 'SEARXNG_PORT'),
  137. 'bind_address': SettingsValue(str, '127.0.0.1', 'SEARXNG_BIND_ADDRESS'),
  138. 'secret_key': SettingsValue(str, environ_name='SEARXNG_SECRET'),
  139. 'base_url': SettingsValue((False, str), False),
  140. 'image_proxy': SettingsValue(bool, False),
  141. 'http_protocol_version': SettingsValue(('1.0', '1.1'), '1.0'),
  142. 'method': SettingsValue(('POST', 'GET'), 'POST'),
  143. 'default_http_headers': SettingsValue(dict, {}),
  144. },
  145. 'ui': {
  146. 'static_path': SettingsDirectoryValue(str, os.path.join(searx_dir, 'static')),
  147. 'templates_path': SettingsDirectoryValue(str, os.path.join(searx_dir, 'templates')),
  148. 'default_theme': SettingsValue(str, 'oscar'),
  149. 'default_locale': SettingsValue(str, ''),
  150. 'theme_args': {
  151. 'oscar_style': SettingsValue(OSCAR_STYLE, 'logicodev'),
  152. },
  153. 'results_on_new_tab': SettingsValue(bool, False),
  154. 'advanced_search': SettingsValue(bool, False),
  155. 'categories_order': SettingsValue(list, CATEGORY_ORDER),
  156. },
  157. 'preferences': {
  158. 'lock': SettingsValue(list, []),
  159. },
  160. 'outgoing': {
  161. 'useragent_suffix': SettingsValue(str, ''),
  162. 'request_timeout': SettingsValue(numbers.Real, 3.0),
  163. 'enable_http2': SettingsValue(bool, True),
  164. 'max_request_timeout': SettingsValue((None, numbers.Real), None),
  165. # Magic number kept from previous code
  166. 'pool_connections': SettingsValue(int, 100),
  167. # Picked from constructor
  168. 'pool_maxsize': SettingsValue(int, 10),
  169. 'keepalive_expiry': SettingsValue(numbers.Real, 5.0),
  170. # default maximum redirect
  171. # from https://github.com/psf/requests/blob/8c211a96cdbe9fe320d63d9e1ae15c5c07e179f8/requests/models.py#L55
  172. 'max_redirects': SettingsValue(int, 30),
  173. 'retries': SettingsValue(int, 0),
  174. 'proxies': SettingsValue((None, str, dict), None),
  175. 'source_ips': SettingsValue((None, str, list), None),
  176. # Tor configuration
  177. 'using_tor_proxy': SettingsValue(bool, False),
  178. 'extra_proxy_timeout': SettingsValue(int, 0),
  179. 'networks': {
  180. },
  181. },
  182. 'plugins': SettingsValue((None, list), None),
  183. 'enabled_plugins': SettingsValue(list, []),
  184. 'checker': {
  185. 'off_when_debug': SettingsValue(bool, True),
  186. },
  187. 'engines': SettingsValue(list, []),
  188. 'doi_resolvers': {
  189. },
  190. }
  191. def settings_set_defaults(settings):
  192. # compatibility with searx variables
  193. for searx, searxng in SEARX_ENVIRON_VARIABLES.items():
  194. if searx in os.environ and searxng not in os.environ:
  195. os.environ[searxng] = os.environ[searx]
  196. logger.warning('%s uses value from %s', searxng, searx)
  197. apply_schema(settings, SCHEMA, [])
  198. return settings