online.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. from urllib.parse import urlparse
  3. from time import time
  4. import threading
  5. import requests.exceptions
  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 or ''
  77. hostname = str(urlparse(response.url or '').netloc)
  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. # suppose everything will be alright
  102. requests_exception = False
  103. suspended_time = None
  104. try:
  105. # send requests and parse the results
  106. search_results = self._search_basic(query, params)
  107. # check if the engine accepted the request
  108. if search_results is not None:
  109. # yes, so add results
  110. result_container.extend(self.engine_name, search_results)
  111. # update engine time when there is no exception
  112. engine_time = time() - start_time
  113. page_load_time = poolrequests.get_time_for_thread()
  114. result_container.add_timing(self.engine_name, engine_time, page_load_time)
  115. with threading.RLock():
  116. self.engine.stats['engine_time'] += engine_time
  117. self.engine.stats['engine_time_count'] += 1
  118. # update stats with the total HTTP time
  119. self.engine.stats['page_load_time'] += page_load_time
  120. self.engine.stats['page_load_count'] += 1
  121. except Exception as e:
  122. record_exception(self.engine_name, e)
  123. # Timing
  124. engine_time = time() - start_time
  125. page_load_time = poolrequests.get_time_for_thread()
  126. result_container.add_timing(self.engine_name, engine_time, page_load_time)
  127. # Record the errors
  128. with threading.RLock():
  129. self.engine.stats['errors'] += 1
  130. if (issubclass(e.__class__, requests.exceptions.Timeout)):
  131. result_container.add_unresponsive_engine(self.engine_name, 'HTTP timeout')
  132. # requests timeout (connect or read)
  133. logger.error("engine {0} : HTTP requests timeout"
  134. "(search duration : {1} s, timeout: {2} s) : {3}"
  135. .format(self.engine_name, engine_time, timeout_limit, e.__class__.__name__))
  136. requests_exception = True
  137. elif (issubclass(e.__class__, requests.exceptions.RequestException)):
  138. result_container.add_unresponsive_engine(self.engine_name, 'HTTP error')
  139. # other requests exception
  140. logger.exception("engine {0} : requests exception"
  141. "(search duration : {1} s, timeout: {2} s) : {3}"
  142. .format(self.engine_name, engine_time, timeout_limit, e))
  143. requests_exception = True
  144. elif (issubclass(e.__class__, SearxEngineCaptchaException)):
  145. result_container.add_unresponsive_engine(self.engine_name, 'CAPTCHA required')
  146. logger.exception('engine {0} : CAPTCHA'.format(self.engine_name))
  147. suspended_time = e.suspended_time # pylint: disable=no-member
  148. elif (issubclass(e.__class__, SearxEngineTooManyRequestsException)):
  149. result_container.add_unresponsive_engine(self.engine_name, 'too many requests')
  150. logger.exception('engine {0} : Too many requests'.format(self.engine_name))
  151. suspended_time = e.suspended_time # pylint: disable=no-member
  152. elif (issubclass(e.__class__, SearxEngineAccessDeniedException)):
  153. result_container.add_unresponsive_engine(self.engine_name, 'blocked')
  154. logger.exception('engine {0} : Searx is blocked'.format(self.engine_name))
  155. suspended_time = e.suspended_time # pylint: disable=no-member
  156. else:
  157. result_container.add_unresponsive_engine(self.engine_name, 'unexpected crash')
  158. # others errors
  159. logger.exception('engine {0} : exception : {1}'.format(self.engine_name, e))
  160. else:
  161. if getattr(threading.current_thread(), '_timeout', False):
  162. record_error(self.engine_name, 'Timeout')
  163. # suspend the engine if there is an HTTP error
  164. # or suspended_time is defined
  165. with threading.RLock():
  166. if requests_exception or suspended_time:
  167. # update continuous_errors / suspend_end_time
  168. self.engine.continuous_errors += 1
  169. if suspended_time is None:
  170. suspended_time = min(settings['search']['max_ban_time_on_fail'],
  171. self.engine.continuous_errors * settings['search']['ban_time_on_fail'])
  172. self.engine.suspend_end_time = time() + suspended_time
  173. else:
  174. # reset the suspend variables
  175. self.engine.continuous_errors = 0
  176. self.engine.suspend_end_time = 0
  177. def get_default_tests(self):
  178. tests = {}
  179. tests['simple'] = {
  180. 'matrix': {'query': ('life', 'computer')},
  181. 'result_container': ['not_empty'],
  182. }
  183. if getattr(self.engine, 'paging', False):
  184. tests['paging'] = {
  185. 'matrix': {'query': 'time',
  186. 'pageno': (1, 2, 3)},
  187. 'result_container': ['not_empty'],
  188. 'test': ['unique_results']
  189. }
  190. if 'general' in self.engine.categories:
  191. # avoid documentation about HTML tags (<time> and <input type="time">)
  192. tests['paging']['matrix']['query'] = 'news'
  193. if getattr(self.engine, 'time_range', False):
  194. tests['time_range'] = {
  195. 'matrix': {'query': 'news',
  196. 'time_range': (None, 'day')},
  197. 'result_container': ['not_empty'],
  198. 'test': ['unique_results']
  199. }
  200. if getattr(self.engine, 'supported_languages', []):
  201. tests['lang_fr'] = {
  202. 'matrix': {'query': 'paris', 'lang': 'fr'},
  203. 'result_container': ['not_empty', ('has_language', 'fr')],
  204. }
  205. tests['lang_en'] = {
  206. 'matrix': {'query': 'paris', 'lang': 'en'},
  207. 'result_container': ['not_empty', ('has_language', 'en')],
  208. }
  209. if getattr(self.engine, 'safesearch', False):
  210. tests['safesearch'] = {
  211. 'matrix': {'query': 'porn',
  212. 'safesearch': (0, 2)},
  213. 'test': ['unique_results']
  214. }
  215. return tests