base_request.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. # Copyright (C) 2013-2018 YouCompleteMe contributors
  2. #
  3. # This file is part of YouCompleteMe.
  4. #
  5. # YouCompleteMe is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # YouCompleteMe is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  17. import logging
  18. import json
  19. import vim
  20. from base64 import b64decode, b64encode
  21. from hmac import compare_digest
  22. from urllib.parse import urljoin, urlparse, urlencode
  23. from urllib.request import Request, urlopen
  24. from urllib.error import URLError, HTTPError
  25. from ycm import vimsupport
  26. from ycmd.utils import ToBytes, GetCurrentDirectory, ToUnicode
  27. from ycmd.hmac_utils import CreateRequestHmac, CreateHmac
  28. from ycmd.responses import ServerError, UnknownExtraConf
  29. HTTP_SERVER_ERROR = 500
  30. _HEADERS = { 'content-type': 'application/json' }
  31. _CONNECT_TIMEOUT_SEC = 0.01
  32. # Setting this to None seems to screw up the Requests/urllib3 libs.
  33. _READ_TIMEOUT_SEC = 30
  34. _HMAC_HEADER = 'x-ycm-hmac'
  35. _logger = logging.getLogger( __name__ )
  36. class BaseRequest:
  37. def __init__( self ):
  38. self._should_resend = False
  39. def Start( self ):
  40. pass
  41. def Done( self ):
  42. return True
  43. def Response( self ):
  44. return {}
  45. def ShouldResend( self ):
  46. return self._should_resend
  47. def HandleFuture( self,
  48. future,
  49. display_message = True,
  50. truncate_message = False ):
  51. """Get the server response from a |future| object and catch any exception
  52. while doing so. If an exception is raised because of a unknown
  53. .ycm_extra_conf.py file, load the file or ignore it after asking the user.
  54. An identical request should be sent again to the server. For other
  55. exceptions, log the exception and display its message to the user on the Vim
  56. status line. Unset the |display_message| parameter to hide the message from
  57. the user. Set the |truncate_message| parameter to avoid hit-enter prompts
  58. from this message."""
  59. try:
  60. try:
  61. return _JsonFromFuture( future )
  62. except UnknownExtraConf as e:
  63. if vimsupport.Confirm( str( e ) ):
  64. _LoadExtraConfFile( e.extra_conf_file )
  65. else:
  66. _IgnoreExtraConfFile( e.extra_conf_file )
  67. self._should_resend = True
  68. except URLError as e:
  69. # We don't display this exception to the user since it is likely to happen
  70. # for each subsequent request (typically if the server crashed) and we
  71. # don't want to spam the user with it.
  72. _logger.error( e )
  73. except Exception as e:
  74. _logger.exception( 'Error while handling server response' )
  75. if display_message:
  76. DisplayServerException( e, truncate_message )
  77. return None
  78. # This method blocks
  79. # |timeout| is num seconds to tolerate no response from server before giving
  80. # up; see Requests docs for details (we just pass the param along).
  81. # See the HandleFuture method for the |display_message| and |truncate_message|
  82. # parameters.
  83. def GetDataFromHandler( self,
  84. handler,
  85. timeout = _READ_TIMEOUT_SEC,
  86. display_message = True,
  87. truncate_message = False,
  88. payload = None ):
  89. return self.HandleFuture(
  90. self.GetDataFromHandlerAsync( handler, timeout, payload ),
  91. display_message,
  92. truncate_message )
  93. def GetDataFromHandlerAsync( self,
  94. handler,
  95. timeout = _READ_TIMEOUT_SEC,
  96. payload = None ):
  97. return BaseRequest._TalkToHandlerAsync(
  98. '', handler, 'GET', timeout, payload )
  99. # This is the blocking version of the method. See below for async.
  100. # |timeout| is num seconds to tolerate no response from server before giving
  101. # up; see Requests docs for details (we just pass the param along).
  102. # See the HandleFuture method for the |display_message| and |truncate_message|
  103. # parameters.
  104. def PostDataToHandler( self,
  105. data,
  106. handler,
  107. timeout = _READ_TIMEOUT_SEC,
  108. display_message = True,
  109. truncate_message = False ):
  110. return self.HandleFuture(
  111. BaseRequest.PostDataToHandlerAsync( data, handler, timeout ),
  112. display_message,
  113. truncate_message )
  114. # This returns a future! Use HandleFuture to get the value.
  115. # |timeout| is num seconds to tolerate no response from server before giving
  116. # up; see Requests docs for details (we just pass the param along).
  117. @staticmethod
  118. def PostDataToHandlerAsync( data, handler, timeout = _READ_TIMEOUT_SEC ):
  119. return BaseRequest._TalkToHandlerAsync( data, handler, 'POST', timeout )
  120. # This returns a future! Use HandleFuture to get the value.
  121. # |method| is either 'POST' or 'GET'.
  122. # |timeout| is num seconds to tolerate no response from server before giving
  123. # up; see Requests docs for details (we just pass the param along).
  124. @staticmethod
  125. def _TalkToHandlerAsync( data,
  126. handler,
  127. method,
  128. timeout = _READ_TIMEOUT_SEC,
  129. payload = None ):
  130. def _MakeRequest( data, handler, method, timeout, payload ):
  131. request_uri = _BuildUri( handler )
  132. if method == 'POST':
  133. sent_data = _ToUtf8Json( data )
  134. headers = BaseRequest._ExtraHeaders( method,
  135. request_uri,
  136. sent_data )
  137. _logger.debug( 'POST %s\n%s\n%s', request_uri, headers, sent_data )
  138. else:
  139. headers = BaseRequest._ExtraHeaders( method, request_uri )
  140. if payload:
  141. request_uri += ToBytes( f'?{ urlencode( payload ) }' )
  142. _logger.debug( 'GET %s (%s)\n%s', request_uri, payload, headers )
  143. return urlopen(
  144. Request(
  145. ToUnicode( request_uri ),
  146. data = sent_data if data else None,
  147. headers = headers,
  148. method = method ),
  149. timeout = max( _CONNECT_TIMEOUT_SEC, timeout ) )
  150. return BaseRequest.Executor().submit(
  151. _MakeRequest,
  152. data,
  153. handler,
  154. method,
  155. timeout,
  156. payload )
  157. @staticmethod
  158. def _ExtraHeaders( method, request_uri, request_body = None ):
  159. if not request_body:
  160. request_body = bytes( b'' )
  161. headers = dict( _HEADERS )
  162. headers[ _HMAC_HEADER ] = b64encode(
  163. CreateRequestHmac( ToBytes( method ),
  164. ToBytes( urlparse( request_uri ).path ),
  165. request_body,
  166. BaseRequest.hmac_secret ) )
  167. return headers
  168. # This method exists to avoid importing the requests module at startup;
  169. # reducing loading time since this module is slow to import.
  170. @classmethod
  171. def Executor( cls ):
  172. try:
  173. return cls.executor
  174. except AttributeError:
  175. from ycm.unsafe_thread_pool_executor import UnsafeThreadPoolExecutor
  176. cls.executor = UnsafeThreadPoolExecutor( max_workers = 30 )
  177. return cls.executor
  178. server_location = ''
  179. hmac_secret = ''
  180. def BuildRequestData( buffer_number = None ):
  181. """Build request for the current buffer or the buffer with number
  182. |buffer_number| if specified."""
  183. working_dir = GetCurrentDirectory()
  184. current_buffer = vim.current.buffer
  185. if buffer_number and current_buffer.number != buffer_number:
  186. # Cursor position is irrelevant when filepath is not the current buffer.
  187. buffer_object = vim.buffers[ buffer_number ]
  188. filepath = vimsupport.GetBufferFilepath( buffer_object )
  189. return {
  190. 'filepath': filepath,
  191. 'line_num': 1,
  192. 'column_num': 1,
  193. 'working_dir': working_dir,
  194. 'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( buffer_object,
  195. filepath )
  196. }
  197. current_filepath = vimsupport.GetBufferFilepath( current_buffer )
  198. line, column = vimsupport.CurrentLineAndColumn()
  199. return {
  200. 'filepath': current_filepath,
  201. 'line_num': line + 1,
  202. 'column_num': column + 1,
  203. 'working_dir': working_dir,
  204. 'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( current_buffer,
  205. current_filepath )
  206. }
  207. def BuildRequestDataForLocation( file : str, line : int, column : int ):
  208. buffer_number = vimsupport.GetBufferNumberForFilename(
  209. file,
  210. create_buffer_if_needed = True )
  211. try:
  212. vim.eval( f'bufload( "{ file }" )' )
  213. except vim.error as e:
  214. if 'E325' not in str( e ):
  215. raise
  216. buffer = vim.buffers[ buffer_number ]
  217. file_data = vimsupport.GetUnsavedAndSpecifiedBufferData( buffer, file )
  218. return {
  219. 'filepath': file,
  220. 'line_num': line,
  221. 'column_num': column,
  222. 'working_dir': GetCurrentDirectory(),
  223. 'file_data': file_data
  224. }
  225. def _JsonFromFuture( future ):
  226. try:
  227. response = future.result()
  228. response_text = response.read()
  229. _ValidateResponseObject( response, response_text )
  230. response.close()
  231. if response_text:
  232. return json.loads( response_text )
  233. return None
  234. except HTTPError as response:
  235. if response.code == HTTP_SERVER_ERROR:
  236. response_text = response.read()
  237. response.close()
  238. if response_text:
  239. raise MakeServerException( json.loads( response_text ) )
  240. else:
  241. return None
  242. raise
  243. def _LoadExtraConfFile( filepath ):
  244. BaseRequest().PostDataToHandler( { 'filepath': filepath },
  245. 'load_extra_conf_file' )
  246. def _IgnoreExtraConfFile( filepath ):
  247. BaseRequest().PostDataToHandler( { 'filepath': filepath },
  248. 'ignore_extra_conf_file' )
  249. def DisplayServerException( exception, truncate_message = False ):
  250. serialized_exception = str( exception )
  251. # We ignore the exception about the file already being parsed since it comes
  252. # up often and isn't something that's actionable by the user.
  253. if 'already being parsed' in serialized_exception:
  254. return
  255. vimsupport.PostVimMessage( serialized_exception, truncate = truncate_message )
  256. def _ToUtf8Json( data ):
  257. return ToBytes( json.dumps( data ) if data else None )
  258. def _ValidateResponseObject( response, response_text ):
  259. if not response_text:
  260. return
  261. our_hmac = CreateHmac( response_text, BaseRequest.hmac_secret )
  262. their_hmac = ToBytes( b64decode( response.headers[ _HMAC_HEADER ] ) )
  263. if not compare_digest( our_hmac, their_hmac ):
  264. raise RuntimeError( 'Received invalid HMAC for response!' )
  265. def _BuildUri( handler ):
  266. return ToBytes( urljoin( BaseRequest.server_location, handler ) )
  267. def MakeServerException( data ):
  268. _logger.debug( 'Server exception: %s', data )
  269. if data[ 'exception' ][ 'TYPE' ] == UnknownExtraConf.__name__:
  270. return UnknownExtraConf( data[ 'exception' ][ 'extra_conf_file' ] )
  271. return ServerError( f'{ data[ "exception" ][ "TYPE" ] }: '
  272. f'{ data[ "message" ] }' )