base_request.py 9.9 KB

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