impl.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. import gc
  3. import typing
  4. import types
  5. import functools
  6. import itertools
  7. from time import time
  8. from timeit import default_timer
  9. from urllib.parse import urlparse
  10. import re
  11. from langdetect import detect_langs
  12. from langdetect.lang_detect_exception import LangDetectException
  13. import httpx
  14. from searx import network, logger
  15. from searx.utils import gen_useragent
  16. from searx.results import ResultContainer
  17. from searx.search.models import SearchQuery, EngineRef
  18. from searx.search.processors import EngineProcessor
  19. from searx.metrics import counter_inc
  20. logger = logger.getChild('searx.search.checker')
  21. HTML_TAGS = [
  22. 'embed', 'iframe', 'object', 'param', 'picture', 'source', 'svg', 'math', 'canvas', 'noscript', 'script',
  23. 'del', 'ins', 'area', 'audio', 'img', 'map', 'track', 'video', 'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite',
  24. 'code', 'data', 'dfn', 'em', 'i', 'kdb', 'mark', 'q', 'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'small',
  25. 'span', 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr', 'style', 'blockquote', 'dd', 'div', 'dl', 'dt',
  26. 'figcaption', 'figure', 'hr', 'li', 'ol', 'p', 'pre', 'ul', 'button', 'datalist', 'fieldset', 'form', 'input',
  27. 'label', 'legend', 'meter', 'optgroup', 'option', 'output', 'progress', 'select', 'textarea', 'applet',
  28. 'frame', 'frameset'
  29. ]
  30. def get_check_no_html():
  31. rep = ['<' + tag + '[^\>]*>' for tag in HTML_TAGS]
  32. rep += ['</' + tag + '>' for tag in HTML_TAGS]
  33. pattern = re.compile('|'.join(rep))
  34. def f(text):
  35. return pattern.search(text.lower()) is None
  36. return f
  37. _check_no_html = get_check_no_html()
  38. def _is_url(url):
  39. try:
  40. result = urlparse(url)
  41. except ValueError:
  42. return False
  43. if result.scheme not in ('http', 'https'):
  44. return False
  45. return True
  46. @functools.lru_cache(maxsize=8192)
  47. def _download_and_check_if_image(image_url: str) -> bool:
  48. """Download an URL and check if the Content-Type starts with "image/"
  49. This function should not be called directly: use _is_url_image
  50. otherwise the cache of functools.lru_cache contains data: URL which might be huge.
  51. """
  52. retry = 2
  53. while retry > 0:
  54. a = time()
  55. try:
  56. # use "image_proxy" (avoid HTTP/2)
  57. network.set_context_network_name('image_proxy')
  58. stream = network.stream('GET', image_url, timeout=10.0, allow_redirects=True, headers={
  59. 'User-Agent': gen_useragent(),
  60. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  61. 'Accept-Language': 'en-US;q=0.5,en;q=0.3',
  62. 'Accept-Encoding': 'gzip, deflate, br',
  63. 'DNT': '1',
  64. 'Connection': 'keep-alive',
  65. 'Upgrade-Insecure-Requests': '1',
  66. 'Sec-GPC': '1',
  67. 'Cache-Control': 'max-age=0'
  68. })
  69. r = next(stream)
  70. r.close()
  71. if r.status_code == 200:
  72. is_image = r.headers.get('content-type', '').startswith('image/')
  73. else:
  74. is_image = False
  75. del r
  76. del stream
  77. return is_image
  78. except httpx.TimeoutException:
  79. logger.error('Timeout for %s: %i', image_url, int(time() - a))
  80. retry -= 1
  81. except httpx.HTTPError:
  82. logger.exception('Exception for %s', image_url)
  83. return False
  84. return False
  85. def _is_url_image(image_url) -> bool:
  86. """Normalize image_url
  87. """
  88. if not isinstance(image_url, str):
  89. return False
  90. if image_url.startswith('//'):
  91. image_url = 'https:' + image_url
  92. if image_url.startswith('data:'):
  93. return image_url.startswith('data:image/')
  94. if not _is_url(image_url):
  95. return False
  96. return _download_and_check_if_image(image_url)
  97. def _search_query_to_dict(search_query: SearchQuery) -> typing.Dict[str, typing.Any]:
  98. return {
  99. 'query': search_query.query,
  100. 'lang': search_query.lang,
  101. 'pageno': search_query.pageno,
  102. 'safesearch': search_query.safesearch,
  103. 'time_range': search_query.time_range,
  104. }
  105. def _search_query_diff(sq1: SearchQuery, sq2: SearchQuery)\
  106. -> typing.Tuple[typing.Dict[str, typing.Any], typing.Dict[str, typing.Any]]:
  107. param1 = _search_query_to_dict(sq1)
  108. param2 = _search_query_to_dict(sq2)
  109. common = {}
  110. diff = {}
  111. for k, value1 in param1.items():
  112. value2 = param2[k]
  113. if value1 == value2:
  114. common[k] = value1
  115. else:
  116. diff[k] = (value1, value2)
  117. return (common, diff)
  118. class TestResults:
  119. __slots__ = 'errors', 'logs', 'languages'
  120. def __init__(self):
  121. self.errors: typing.Dict[str, typing.List[str]] = {}
  122. self.logs: typing.Dict[str, typing.List[typing.Any]] = {}
  123. self.languages: typing.Set[str] = set()
  124. def add_error(self, test, message, *args):
  125. # message to self.errors
  126. errors_for_test = self.errors.setdefault(test, [])
  127. if message not in errors_for_test:
  128. errors_for_test.append(message)
  129. # (message, *args) to self.logs
  130. logs_for_test = self.logs.setdefault(test, [])
  131. if (message, *args) not in logs_for_test:
  132. logs_for_test.append((message, *args))
  133. def add_language(self, language):
  134. self.languages.add(language)
  135. @property
  136. def succesfull(self):
  137. return len(self.errors) == 0
  138. def __iter__(self):
  139. for test_name, errors in self.errors.items():
  140. for error in sorted(errors):
  141. yield (test_name, error)
  142. class ResultContainerTests:
  143. __slots__ = 'test_name', 'search_query', 'result_container', 'languages', 'stop_test', 'test_results'
  144. def __init__(self,
  145. test_results: TestResults,
  146. test_name: str,
  147. search_query: SearchQuery,
  148. result_container: ResultContainer):
  149. self.test_name = test_name
  150. self.search_query = search_query
  151. self.result_container = result_container
  152. self.languages: typing.Set[str] = set()
  153. self.test_results = test_results
  154. self.stop_test = False
  155. @property
  156. def result_urls(self):
  157. results = self.result_container.get_ordered_results()
  158. return [result['url'] for result in results if 'url' in result]
  159. def _record_error(self, message: str, *args) -> None:
  160. sq = _search_query_to_dict(self.search_query)
  161. sqstr = ' '.join(['{}={!r}'.format(k, v) for k, v in sq.items()])
  162. self.test_results.add_error(self.test_name, message, *args, '(' + sqstr + ')')
  163. def _add_language(self, text: str) -> typing.Optional[str]:
  164. try:
  165. r = detect_langs(str(text)) # pylint: disable=E1101
  166. except LangDetectException:
  167. return None
  168. if len(r) > 0 and r[0].prob > 0.95:
  169. self.languages.add(r[0].lang)
  170. self.test_results.add_language(r[0].lang)
  171. return None
  172. def _check_result(self, result):
  173. if not _check_no_html(result.get('title', '')):
  174. self._record_error('HTML in title', repr(result.get('title', '')))
  175. if not _check_no_html(result.get('content', '')):
  176. self._record_error('HTML in content', repr(result.get('content', '')))
  177. if result.get('url') is None:
  178. self._record_error('url is None')
  179. self._add_language(result.get('title', ''))
  180. self._add_language(result.get('content', ''))
  181. template = result.get('template', 'default.html')
  182. if template == 'default.html':
  183. return
  184. if template == 'code.html':
  185. return
  186. if template == 'torrent.html':
  187. return
  188. if template == 'map.html':
  189. return
  190. if template == 'images.html':
  191. thumbnail_src = result.get('thumbnail_src')
  192. if thumbnail_src is not None:
  193. if not _is_url_image(thumbnail_src):
  194. self._record_error('thumbnail_src URL is invalid', thumbnail_src)
  195. elif not _is_url_image(result.get('img_src')):
  196. self._record_error('img_src URL is invalid', result.get('img_src'))
  197. if template == 'videos.html' and not _is_url_image(result.get('thumbnail')):
  198. self._record_error('thumbnail URL is invalid', result.get('img_src'))
  199. def _check_results(self, results: list):
  200. for result in results:
  201. self._check_result(result)
  202. def _check_answers(self, answers):
  203. for answer in answers:
  204. if not _check_no_html(answer):
  205. self._record_error('HTML in answer', answer)
  206. def _check_infoboxes(self, infoboxes):
  207. for infobox in infoboxes:
  208. if not _check_no_html(infobox.get('content', '')):
  209. self._record_error('HTML in infobox content', infobox.get('content', ''))
  210. self._add_language(infobox.get('content', ''))
  211. for attribute in infobox.get('attributes', {}):
  212. if not _check_no_html(attribute.get('value', '')):
  213. self._record_error('HTML in infobox attribute value', attribute.get('value', ''))
  214. def check_basic(self):
  215. if len(self.result_container.unresponsive_engines) > 0:
  216. for message in self.result_container.unresponsive_engines:
  217. self._record_error(message[1] + ' ' + (message[2] or ''))
  218. self.stop_test = True
  219. return
  220. results = self.result_container.get_ordered_results()
  221. if len(results) > 0:
  222. self._check_results(results)
  223. if len(self.result_container.answers) > 0:
  224. self._check_answers(self.result_container.answers)
  225. if len(self.result_container.infoboxes) > 0:
  226. self._check_infoboxes(self.result_container.infoboxes)
  227. def has_infobox(self):
  228. """Check the ResultContainer has at least one infobox"""
  229. if len(self.result_container.infoboxes) == 0:
  230. self._record_error('No infobox')
  231. def has_answer(self):
  232. """Check the ResultContainer has at least one answer"""
  233. if len(self.result_container.answers) == 0:
  234. self._record_error('No answer')
  235. def has_language(self, lang):
  236. """Check at least one title or content of the results is written in the `lang`.
  237. Detected using pycld3, may be not accurate"""
  238. if lang not in self.languages:
  239. self._record_error(lang + ' not found')
  240. def not_empty(self):
  241. """Check the ResultContainer has at least one answer or infobox or result"""
  242. result_types = set()
  243. results = self.result_container.get_ordered_results()
  244. if len(results) > 0:
  245. result_types.add('results')
  246. if len(self.result_container.answers) > 0:
  247. result_types.add('answers')
  248. if len(self.result_container.infoboxes) > 0:
  249. result_types.add('infoboxes')
  250. if len(result_types) == 0:
  251. self._record_error('No result')
  252. def one_title_contains(self, title: str):
  253. """Check one of the title contains `title` (case insensitive comparaison)"""
  254. title = title.lower()
  255. for result in self.result_container.get_ordered_results():
  256. if title in result['title'].lower():
  257. return
  258. self._record_error(('{!r} not found in the title'.format(title)))
  259. class CheckerTests:
  260. __slots__ = 'test_results', 'test_name', 'result_container_tests_list'
  261. def __init__(self,
  262. test_results: TestResults,
  263. test_name: str,
  264. result_container_tests_list: typing.List[ResultContainerTests]):
  265. self.test_results = test_results
  266. self.test_name = test_name
  267. self.result_container_tests_list = result_container_tests_list
  268. def unique_results(self):
  269. """Check the results of each ResultContainer is unique"""
  270. urls_list = [rct.result_urls for rct in self.result_container_tests_list]
  271. if len(urls_list[0]) > 0:
  272. # results on the first page
  273. for i, urls_i in enumerate(urls_list):
  274. for j, urls_j in enumerate(urls_list):
  275. if i < j and urls_i == urls_j:
  276. common, diff = _search_query_diff(self.result_container_tests_list[i].search_query,
  277. self.result_container_tests_list[j].search_query)
  278. common_str = ' '.join(['{}={!r}'.format(k, v) for k, v in common.items()])
  279. diff1_str = ', ' .join(['{}={!r}'.format(k, v1) for (k, (v1, v2)) in diff.items()])
  280. diff2_str = ', ' .join(['{}={!r}'.format(k, v2) for (k, (v1, v2)) in diff.items()])
  281. self.test_results.add_error(self.test_name,
  282. 'results are identitical for {} and {} ({})'
  283. .format(diff1_str, diff2_str, common_str))
  284. class Checker:
  285. __slots__ = 'processor', 'tests', 'test_results'
  286. def __init__(self, processor: EngineProcessor):
  287. self.processor = processor
  288. self.tests = self.processor.get_tests()
  289. self.test_results = TestResults()
  290. @property
  291. def engineref_list(self):
  292. engine_name = self.processor.engine_name
  293. engine_category = self.processor.engine.categories[0]
  294. return [EngineRef(engine_name, engine_category)]
  295. @staticmethod
  296. def search_query_matrix_iterator(engineref_list, matrix):
  297. p = []
  298. for name, values in matrix.items():
  299. if isinstance(values, (tuple, list)):
  300. l = [(name, value) for value in values]
  301. else:
  302. l = [(name, values)]
  303. p.append(l)
  304. for kwargs in itertools.product(*p):
  305. kwargs = {k: v for k, v in kwargs}
  306. query = kwargs['query']
  307. params = dict(kwargs)
  308. del params['query']
  309. yield SearchQuery(query, engineref_list, **params)
  310. def call_test(self, obj, test_description):
  311. if isinstance(test_description, (tuple, list)):
  312. method, args = test_description[0], test_description[1:]
  313. else:
  314. method = test_description
  315. args = ()
  316. if isinstance(method, str) and hasattr(obj, method):
  317. getattr(obj, method)(*args)
  318. elif isinstance(method, types.FunctionType):
  319. method(*args)
  320. else:
  321. self.test_results.add_error(obj.test_name,
  322. 'method {!r} ({}) not found for {}'
  323. .format(method, method.__class__.__name__, obj.__class__.__name__))
  324. def call_tests(self, obj, test_descriptions):
  325. for test_description in test_descriptions:
  326. self.call_test(obj, test_description)
  327. def search(self, search_query: SearchQuery) -> ResultContainer:
  328. result_container = ResultContainer()
  329. engineref_category = search_query.engineref_list[0].category
  330. params = self.processor.get_params(search_query, engineref_category)
  331. if params is not None:
  332. counter_inc('engine', search_query.engineref_list[0].name, 'search', 'count', 'sent')
  333. self.processor.search(search_query.query, params, result_container, default_timer(), 5)
  334. return result_container
  335. def get_result_container_tests(self, test_name: str, search_query: SearchQuery) -> ResultContainerTests:
  336. result_container = self.search(search_query)
  337. result_container_check = ResultContainerTests(self.test_results, test_name, search_query, result_container)
  338. result_container_check.check_basic()
  339. return result_container_check
  340. def run_test(self, test_name):
  341. test_parameters = self.tests[test_name]
  342. search_query_list = list(Checker.search_query_matrix_iterator(self.engineref_list, test_parameters['matrix']))
  343. rct_list = [self.get_result_container_tests(test_name, search_query) for search_query in search_query_list]
  344. stop_test = False
  345. if 'result_container' in test_parameters:
  346. for rct in rct_list:
  347. stop_test = stop_test or rct.stop_test
  348. if not rct.stop_test:
  349. self.call_tests(rct, test_parameters['result_container'])
  350. if not stop_test:
  351. if 'test' in test_parameters:
  352. checker_tests = CheckerTests(self.test_results, test_name, rct_list)
  353. self.call_tests(checker_tests, test_parameters['test'])
  354. def run(self):
  355. for test_name in self.tests:
  356. self.run_test(test_name)
  357. # clear cache
  358. _download_and_check_if_image.cache_clear()
  359. # force a garbage collector
  360. gc.collect()