command.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. '''
  2. searx is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU Affero General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. searx is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU Affero General Public License for more details.
  10. You should have received a copy of the GNU Affero General Public License
  11. along with searx. If not, see < http://www.gnu.org/licenses/ >.
  12. '''
  13. import re
  14. from os.path import expanduser, isabs, realpath, commonprefix
  15. from shlex import split as shlex_split
  16. from subprocess import Popen, PIPE
  17. from threading import Thread
  18. from searx import logger
  19. offline = True
  20. paging = True
  21. command = []
  22. delimiter = {}
  23. parse_regex = {}
  24. query_type = ''
  25. query_enum = []
  26. environment_variables = {}
  27. working_dir = realpath('.')
  28. result_separator = '\n'
  29. result_template = 'key-value.html'
  30. timeout = 4.0
  31. _command_logger = logger.getChild('command')
  32. _compiled_parse_regex = {}
  33. def init(engine_settings):
  34. check_parsing_options(engine_settings)
  35. if 'command' not in engine_settings:
  36. raise ValueError('engine command : missing configuration key: command')
  37. global command, working_dir, result_template, delimiter, parse_regex, timeout, environment_variables
  38. command = engine_settings['command']
  39. if 'working_dir' in engine_settings:
  40. working_dir = engine_settings['working_dir']
  41. if not isabs(engine_settings['working_dir']):
  42. working_dir = realpath(working_dir)
  43. if 'parse_regex' in engine_settings:
  44. parse_regex = engine_settings['parse_regex']
  45. for result_key, regex in parse_regex.items():
  46. _compiled_parse_regex[result_key] = re.compile(regex, flags=re.MULTILINE)
  47. if 'delimiter' in engine_settings:
  48. delimiter = engine_settings['delimiter']
  49. if 'environment_variables' in engine_settings:
  50. environment_variables = engine_settings['environment_variables']
  51. def search(query, params):
  52. cmd = _get_command_to_run(query)
  53. if not cmd:
  54. return []
  55. results = []
  56. reader_thread = Thread(target=_get_results_from_process, args=(results, cmd, params['pageno']))
  57. reader_thread.start()
  58. reader_thread.join(timeout=timeout)
  59. return results
  60. def _get_command_to_run(query):
  61. params = shlex_split(query.decode('utf-8'))
  62. __check_query_params(params)
  63. cmd = []
  64. for c in command:
  65. if c == '{{QUERY}}':
  66. cmd.extend(params)
  67. else:
  68. cmd.append(c)
  69. return cmd
  70. def _get_results_from_process(results, cmd, pageno):
  71. leftover = ''
  72. count = 0
  73. start, end = __get_results_limits(pageno)
  74. with Popen(cmd, stdout=PIPE, stderr=PIPE, env=environment_variables) as process:
  75. line = process.stdout.readline()
  76. while line:
  77. buf = leftover + line.decode('utf-8')
  78. raw_results = buf.split(result_separator)
  79. if raw_results[-1]:
  80. leftover = raw_results[-1]
  81. raw_results = raw_results[:-1]
  82. for raw_result in raw_results:
  83. result = __parse_single_result(raw_result)
  84. if result is None:
  85. _command_logger.debug('skipped result:', raw_result)
  86. continue
  87. if start <= count and count <= end:
  88. result['template'] = result_template
  89. results.append(result)
  90. count += 1
  91. if end < count:
  92. return results
  93. line = process.stdout.readline()
  94. return_code = process.wait(timeout=timeout)
  95. if return_code != 0:
  96. raise RuntimeError('non-zero return code when running command', cmd, return_code)
  97. def __get_results_limits(pageno):
  98. start = (pageno - 1) * 10
  99. end = start + 9
  100. return start, end
  101. def __check_query_params(params):
  102. if not query_type:
  103. return
  104. if query_type == 'path':
  105. query_path = params[-1]
  106. query_path = expanduser(query_path)
  107. if commonprefix([realpath(query_path), working_dir]) != working_dir:
  108. raise ValueError('requested path is outside of configured working directory')
  109. elif query_type == 'enum' and len(query_enum) > 0:
  110. for param in params:
  111. if param not in query_enum:
  112. raise ValueError('submitted query params is not allowed', param, 'allowed params:', query_enum)
  113. def check_parsing_options(engine_settings):
  114. """ Checks if delimiter based parsing or regex parsing is configured correctly """
  115. if 'delimiter' not in engine_settings and 'parse_regex' not in engine_settings:
  116. raise ValueError('failed to init settings for parsing lines: missing delimiter or parse_regex')
  117. if 'delimiter' in engine_settings and 'parse_regex' in engine_settings:
  118. raise ValueError('failed to init settings for parsing lines: too many settings')
  119. if 'delimiter' in engine_settings:
  120. if 'chars' not in engine_settings['delimiter'] or 'keys' not in engine_settings['delimiter']:
  121. raise ValueError
  122. def __parse_single_result(raw_result):
  123. """ Parses command line output based on configuration """
  124. result = {}
  125. if delimiter:
  126. elements = raw_result.split(delimiter['chars'], maxsplit=len(delimiter['keys']) - 1)
  127. if len(elements) != len(delimiter['keys']):
  128. return {}
  129. for i in range(len(elements)):
  130. result[delimiter['keys'][i]] = elements[i]
  131. if parse_regex:
  132. for result_key, regex in _compiled_parse_regex.items():
  133. found = regex.search(raw_result)
  134. if not found:
  135. return {}
  136. result[result_key] = raw_result[found.start():found.end()]
  137. return result