base_request.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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
  23. from ycm import vimsupport
  24. from ycmd.utils import ToBytes, GetCurrentDirectory
  25. from ycmd.hmac_utils import CreateRequestHmac, CreateHmac
  26. from ycmd.responses import ServerError, UnknownExtraConf
  27. _HEADERS = { 'content-type': 'application/json' }
  28. _CONNECT_TIMEOUT_SEC = 0.01
  29. # Setting this to None seems to screw up the Requests/urllib3 libs.
  30. _READ_TIMEOUT_SEC = 30
  31. _HMAC_HEADER = 'x-ycm-hmac'
  32. _logger = logging.getLogger( __name__ )
  33. class BaseRequest:
  34. def __init__( self ):
  35. self._should_resend = False
  36. def Start( self ):
  37. pass
  38. def Done( self ):
  39. return True
  40. def Response( self ):
  41. return {}
  42. def ShouldResend( self ):
  43. return self._should_resend
  44. def HandleFuture( self,
  45. future,
  46. display_message = True,
  47. truncate_message = False ):
  48. """Get the server response from a |future| object and catch any exception
  49. while doing so. If an exception is raised because of a unknown
  50. .ycm_extra_conf.py file, load the file or ignore it after asking the user.
  51. An identical request should be sent again to the server. For other
  52. exceptions, log the exception and display its message to the user on the Vim
  53. status line. Unset the |display_message| parameter to hide the message from
  54. the user. Set the |truncate_message| parameter to avoid hit-enter prompts
  55. from this message."""
  56. try:
  57. try:
  58. return _JsonFromFuture( future )
  59. except UnknownExtraConf as e:
  60. if vimsupport.Confirm( str( e ) ):
  61. _LoadExtraConfFile( e.extra_conf_file )
  62. else:
  63. _IgnoreExtraConfFile( e.extra_conf_file )
  64. self._should_resend = True
  65. except BaseRequest.Requests().exceptions.ConnectionError as e:
  66. # We don't display this exception to the user since it is likely to happen
  67. # for each subsequent request (typically if the server crashed) and we
  68. # don't want to spam the user with it.
  69. _logger.error( e )
  70. except Exception as e:
  71. _logger.exception( 'Error while handling server response' )
  72. if display_message:
  73. DisplayServerException( e, truncate_message )
  74. return None
  75. # This method blocks
  76. # |timeout| is num seconds to tolerate no response from server before giving
  77. # up; see Requests docs for details (we just pass the param along).
  78. # See the HandleFuture method for the |display_message| and |truncate_message|
  79. # parameters.
  80. def GetDataFromHandler( self,
  81. handler,
  82. timeout = _READ_TIMEOUT_SEC,
  83. display_message = True,
  84. truncate_message = False,
  85. payload = None ):
  86. return self.HandleFuture(
  87. self.GetDataFromHandlerAsync( handler, timeout, payload ),
  88. display_message,
  89. truncate_message )
  90. def GetDataFromHandlerAsync( self,
  91. handler,
  92. timeout = _READ_TIMEOUT_SEC,
  93. payload = None ):
  94. return BaseRequest._TalkToHandlerAsync(
  95. '', handler, 'GET', timeout, payload )
  96. # This is the blocking version of the method. See below for async.
  97. # |timeout| is num seconds to tolerate no response from server before giving
  98. # up; see Requests docs for details (we just pass the param along).
  99. # See the HandleFuture method for the |display_message| and |truncate_message|
  100. # parameters.
  101. def PostDataToHandler( self,
  102. data,
  103. handler,
  104. timeout = _READ_TIMEOUT_SEC,
  105. display_message = True,
  106. truncate_message = False ):
  107. return self.HandleFuture(
  108. BaseRequest.PostDataToHandlerAsync( data, handler, timeout ),
  109. display_message,
  110. truncate_message )
  111. # This returns a future! Use HandleFuture to get the value.
  112. # |timeout| is num seconds to tolerate no response from server before giving
  113. # up; see Requests docs for details (we just pass the param along).
  114. @staticmethod
  115. def PostDataToHandlerAsync( data, handler, timeout = _READ_TIMEOUT_SEC ):
  116. return BaseRequest._TalkToHandlerAsync( data, handler, 'POST', timeout )
  117. # This returns a future! Use HandleFuture to get the value.
  118. # |method| is either 'POST' or 'GET'.
  119. # |timeout| is num seconds to tolerate no response from server before giving
  120. # up; see Requests docs for details (we just pass the param along).
  121. @staticmethod
  122. def _TalkToHandlerAsync( data,
  123. handler,
  124. method,
  125. timeout = _READ_TIMEOUT_SEC,
  126. payload = None ):
  127. request_uri = _BuildUri( handler )
  128. if method == 'POST':
  129. sent_data = _ToUtf8Json( data )
  130. headers = BaseRequest._ExtraHeaders( method,
  131. request_uri,
  132. sent_data )
  133. _logger.debug( 'POST %s\n%s\n%s', request_uri, headers, sent_data )
  134. return BaseRequest.Session().post(
  135. request_uri,
  136. data = sent_data,
  137. headers = headers,
  138. timeout = ( _CONNECT_TIMEOUT_SEC, timeout ) )
  139. headers = BaseRequest._ExtraHeaders( method, request_uri )
  140. _logger.debug( 'GET %s (%s)\n%s', request_uri, payload, headers )
  141. return BaseRequest.Session().get(
  142. request_uri,
  143. headers = headers,
  144. timeout = ( _CONNECT_TIMEOUT_SEC, timeout ),
  145. params = payload )
  146. @staticmethod
  147. def _ExtraHeaders( method, request_uri, request_body = None ):
  148. if not request_body:
  149. request_body = bytes( b'' )
  150. headers = dict( _HEADERS )
  151. headers[ _HMAC_HEADER ] = b64encode(
  152. CreateRequestHmac( ToBytes( method ),
  153. ToBytes( urlparse( request_uri ).path ),
  154. request_body,
  155. BaseRequest.hmac_secret ) )
  156. return headers
  157. # These two methods exist to avoid importing the requests module at startup;
  158. # reducing loading time since this module is slow to import.
  159. @classmethod
  160. def Requests( cls ):
  161. try:
  162. return cls.requests
  163. except AttributeError:
  164. import requests
  165. cls.requests = requests
  166. return requests
  167. @classmethod
  168. def Session( cls ):
  169. try:
  170. return cls.session
  171. except AttributeError:
  172. from ycm.unsafe_thread_pool_executor import UnsafeThreadPoolExecutor
  173. from requests_futures.sessions import FuturesSession
  174. executor = UnsafeThreadPoolExecutor( max_workers = 30 )
  175. cls.session = FuturesSession( executor = executor )
  176. return cls.session
  177. server_location = ''
  178. hmac_secret = ''
  179. def BuildRequestData( buffer_number = None ):
  180. """Build request for the current buffer or the buffer with number
  181. |buffer_number| if specified."""
  182. working_dir = GetCurrentDirectory()
  183. current_buffer = vim.current.buffer
  184. if buffer_number and current_buffer.number != buffer_number:
  185. # Cursor position is irrelevant when filepath is not the current buffer.
  186. buffer_object = vim.buffers[ buffer_number ]
  187. filepath = vimsupport.GetBufferFilepath( buffer_object )
  188. return {
  189. 'filepath': filepath,
  190. 'line_num': 1,
  191. 'column_num': 1,
  192. 'working_dir': working_dir,
  193. 'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( buffer_object,
  194. filepath )
  195. }
  196. current_filepath = vimsupport.GetBufferFilepath( current_buffer )
  197. line, column = vimsupport.CurrentLineAndColumn()
  198. return {
  199. 'filepath': current_filepath,
  200. 'line_num': line + 1,
  201. 'column_num': column + 1,
  202. 'working_dir': working_dir,
  203. 'file_data': vimsupport.GetUnsavedAndSpecifiedBufferData( current_buffer,
  204. current_filepath )
  205. }
  206. def _JsonFromFuture( future ):
  207. response = future.result()
  208. _logger.debug( 'RX: %s\n%s', response, response.text )
  209. _ValidateResponseObject( response )
  210. if response.status_code == BaseRequest.Requests().codes.server_error:
  211. raise MakeServerException( response.json() )
  212. # We let Requests handle the other status types, we only handle the 500
  213. # error code.
  214. response.raise_for_status()
  215. if response.text:
  216. return response.json()
  217. return None
  218. def _LoadExtraConfFile( filepath ):
  219. BaseRequest().PostDataToHandler( { 'filepath': filepath },
  220. 'load_extra_conf_file' )
  221. def _IgnoreExtraConfFile( filepath ):
  222. BaseRequest().PostDataToHandler( { 'filepath': filepath },
  223. 'ignore_extra_conf_file' )
  224. def DisplayServerException( exception, truncate_message = False ):
  225. serialized_exception = str( exception )
  226. # We ignore the exception about the file already being parsed since it comes
  227. # up often and isn't something that's actionable by the user.
  228. if 'already being parsed' in serialized_exception:
  229. return
  230. vimsupport.PostVimMessage( serialized_exception, truncate = truncate_message )
  231. def _ToUtf8Json( data ):
  232. return ToBytes( json.dumps( data ) if data else None )
  233. def _ValidateResponseObject( response ):
  234. our_hmac = CreateHmac( response.content, BaseRequest.hmac_secret )
  235. their_hmac = ToBytes( b64decode( response.headers[ _HMAC_HEADER ] ) )
  236. if not compare_digest( our_hmac, their_hmac ):
  237. raise RuntimeError( 'Received invalid HMAC for response!' )
  238. return True
  239. def _BuildUri( handler ):
  240. return ToBytes( urljoin( BaseRequest.server_location, handler ) )
  241. def MakeServerException( data ):
  242. if data[ 'exception' ][ 'TYPE' ] == UnknownExtraConf.__name__:
  243. return UnknownExtraConf( data[ 'exception' ][ 'extra_conf_file' ] )
  244. return ServerError( f'{ data[ "exception" ][ "TYPE" ] }: '
  245. f'{ data[ "message" ] }' )