online.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. from time import time
  3. import threading
  4. import asyncio
  5. import httpx
  6. import searx.poolrequests as poolrequests
  7. from searx.engines import settings
  8. from searx import logger
  9. from searx.utils import gen_useragent
  10. from searx.exceptions import (SearxEngineAccessDeniedException, SearxEngineCaptchaException,
  11. SearxEngineTooManyRequestsException,)
  12. from searx.metrology.error_recorder import record_exception, record_error
  13. from searx.search.processors.abstract import EngineProcessor
  14. logger = logger.getChild('search.processor.online')
  15. def default_request_params():
  16. return {
  17. 'method': 'GET',
  18. 'headers': {},
  19. 'data': {},
  20. 'url': '',
  21. 'cookies': {},
  22. 'verify': True,
  23. 'auth': None
  24. }
  25. class OnlineProcessor(EngineProcessor):
  26. engine_type = 'online'
  27. def get_params(self, search_query, engine_category):
  28. params = super().get_params(search_query, engine_category)
  29. if params is None:
  30. return None
  31. # skip suspended engines
  32. if self.engine.suspend_end_time >= time():
  33. logger.debug('Engine currently suspended: %s', self.engine_name)
  34. return None
  35. # add default params
  36. params.update(default_request_params())
  37. # add an user agent
  38. params['headers']['User-Agent'] = gen_useragent()
  39. return params
  40. def _send_http_request(self, params):
  41. # create dictionary which contain all
  42. # informations about the request
  43. request_args = dict(
  44. headers=params['headers'],
  45. cookies=params['cookies'],
  46. verify=params['verify'],
  47. auth=params['auth']
  48. )
  49. # setting engine based proxies
  50. if hasattr(self.engine, 'proxies'):
  51. request_args['proxies'] = poolrequests.get_proxies(self.engine.proxies)
  52. # max_redirects
  53. max_redirects = params.get('max_redirects')
  54. if max_redirects:
  55. request_args['max_redirects'] = max_redirects
  56. # allow_redirects
  57. if 'allow_redirects' in params:
  58. request_args['allow_redirects'] = params['allow_redirects']
  59. # soft_max_redirects
  60. soft_max_redirects = params.get('soft_max_redirects', max_redirects or 0)
  61. # raise_for_status
  62. request_args['raise_for_httperror'] = params.get('raise_for_httperror', True)
  63. # specific type of request (GET or POST)
  64. if params['method'] == 'GET':
  65. req = poolrequests.get
  66. else:
  67. req = poolrequests.post
  68. request_args['data'] = params['data']
  69. # send the request
  70. response = req(params['url'], **request_args)
  71. # check soft limit of the redirect count
  72. if len(response.history) > soft_max_redirects:
  73. # unexpected redirect : record an error
  74. # but the engine might still return valid results.
  75. status_code = str(response.status_code or '')
  76. reason = response.reason_phrase or ''
  77. hostname = response.url.host
  78. record_error(self.engine_name,
  79. '{} redirects, maximum: {}'.format(len(response.history), soft_max_redirects),
  80. (status_code, reason, hostname))
  81. return response
  82. def _search_basic(self, query, params):
  83. # update request parameters dependent on
  84. # search-engine (contained in engines folder)
  85. self.engine.request(query, params)
  86. # ignoring empty urls
  87. if params['url'] is None:
  88. return None
  89. if not params['url']:
  90. return None
  91. # send request
  92. response = self._send_http_request(params)
  93. # parse the response
  94. response.search_params = params
  95. return self.engine.response(response)
  96. def search(self, query, params, result_container, start_time, timeout_limit):
  97. # set timeout for all HTTP requests
  98. poolrequests.set_timeout_for_thread(timeout_limit, start_time=start_time)
  99. # reset the HTTP total time
  100. poolrequests.reset_time_for_thread()
  101. # enable HTTP only if explicitly enabled
  102. poolrequests.set_enable_http_protocol(self.engine.enable_http)
  103. # suppose everything will be alright
  104. http_exception = False
  105. suspended_time = None
  106. try:
  107. # send requests and parse the results
  108. search_results = self._search_basic(query, params)
  109. # check if the engine accepted the request
  110. if search_results is not None:
  111. # yes, so add results
  112. result_container.extend(self.engine_name, search_results)
  113. # update engine time when there is no exception
  114. engine_time = time() - start_time
  115. page_load_time = poolrequests.get_time_for_thread()
  116. result_container.add_timing(self.engine_name, engine_time, page_load_time)
  117. with threading.RLock():
  118. self.engine.stats['engine_time'] += engine_time
  119. self.engine.stats['engine_time_count'] += 1
  120. # update stats with the total HTTP time
  121. self.engine.stats['page_load_time'] += page_load_time
  122. self.engine.stats['page_load_count'] += 1
  123. except Exception as e:
  124. record_exception(self.engine_name, e)
  125. # Timing
  126. engine_time = time() - start_time
  127. page_load_time = poolrequests.get_time_for_thread()
  128. result_container.add_timing(self.engine_name, engine_time, page_load_time)
  129. # Record the errors
  130. with threading.RLock():
  131. self.engine.stats['errors'] += 1
  132. if (issubclass(e.__class__, (httpx.TimeoutException, asyncio.TimeoutError))):
  133. result_container.add_unresponsive_engine(self.engine_name, 'HTTP timeout')
  134. # requests timeout (connect or read)
  135. logger.error("engine {0} : HTTP requests timeout"
  136. "(search duration : {1} s, timeout: {2} s) : {3}"
  137. .format(self.engine_name, engine_time, timeout_limit, e.__class__.__name__))
  138. http_exception = True
  139. elif (issubclass(e.__class__, (httpx.HTTPError, httpx.StreamError))):
  140. result_container.add_unresponsive_engine(self.engine_name, 'HTTP error')
  141. # other requests exception
  142. logger.exception("engine {0} : requests exception"
  143. "(search duration : {1} s, timeout: {2} s) : {3}"
  144. .format(self.engine_name, engine_time, timeout_limit, e))
  145. http_exception = True
  146. elif (issubclass(e.__class__, SearxEngineCaptchaException)):
  147. result_container.add_unresponsive_engine(self.engine_name, 'CAPTCHA required')
  148. logger.exception('engine {0} : CAPTCHA'.format(self.engine_name))
  149. suspended_time = e.suspended_time # pylint: disable=no-member
  150. elif (issubclass(e.__class__, SearxEngineTooManyRequestsException)):
  151. result_container.add_unresponsive_engine(self.engine_name, 'too many requests')
  152. logger.exception('engine {0} : Too many requests'.format(self.engine_name))
  153. suspended_time = e.suspended_time # pylint: disable=no-member
  154. elif (issubclass(e.__class__, SearxEngineAccessDeniedException)):
  155. result_container.add_unresponsive_engine(self.engine_name, 'blocked')
  156. logger.exception('engine {0} : Searx is blocked'.format(self.engine_name))
  157. suspended_time = e.suspended_time # pylint: disable=no-member
  158. else:
  159. result_container.add_unresponsive_engine(self.engine_name, 'unexpected crash')
  160. # others errors
  161. logger.exception('engine {0} : exception : {1}'.format(self.engine_name, e))
  162. else:
  163. if getattr(threading.current_thread(), '_timeout', False):
  164. record_error(self.engine_name, 'Timeout')
  165. # suspend the engine if there is an HTTP error
  166. # or suspended_time is defined
  167. with threading.RLock():
  168. if http_exception or suspended_time:
  169. # update continuous_errors / suspend_end_time
  170. self.engine.continuous_errors += 1
  171. if suspended_time is None:
  172. suspended_time = min(settings['search']['max_ban_time_on_fail'],
  173. self.engine.continuous_errors * settings['search']['ban_time_on_fail'])
  174. self.engine.suspend_end_time = time() + suspended_time
  175. else:
  176. # reset the suspend variables
  177. self.engine.continuous_errors = 0
  178. self.engine.suspend_end_time = 0
  179. def get_default_tests(self):
  180. tests = {}
  181. tests['simple'] = {
  182. 'matrix': {'query': ('life', 'computer')},
  183. 'result_container': ['not_empty'],
  184. }
  185. if getattr(self.engine, 'paging', False):
  186. tests['paging'] = {
  187. 'matrix': {'query': 'time',
  188. 'pageno': (1, 2, 3)},
  189. 'result_container': ['not_empty'],
  190. 'test': ['unique_results']
  191. }
  192. if 'general' in self.engine.categories:
  193. # avoid documentation about HTML tags (<time> and <input type="time">)
  194. tests['paging']['matrix']['query'] = 'news'
  195. if getattr(self.engine, 'time_range', False):
  196. tests['time_range'] = {
  197. 'matrix': {'query': 'news',
  198. 'time_range': (None, 'day')},
  199. 'result_container': ['not_empty'],
  200. 'test': ['unique_results']
  201. }
  202. if getattr(self.engine, 'supported_languages', []):
  203. tests['lang_fr'] = {
  204. 'matrix': {'query': 'paris', 'lang': 'fr'},
  205. 'result_container': ['not_empty', ('has_language', 'fr')],
  206. }
  207. tests['lang_en'] = {
  208. 'matrix': {'query': 'paris', 'lang': 'en'},
  209. 'result_container': ['not_empty', ('has_language', 'en')],
  210. }
  211. if getattr(self.engine, 'safesearch', False):
  212. tests['safesearch'] = {
  213. 'matrix': {'query': 'porn',
  214. 'safesearch': (0, 2)},
  215. 'test': ['unique_results']
  216. }
  217. return tests