jsonrpclib.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. # Copyright 2014 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Module to implement the JSON-RPC protocol.
  5. This module uses xmlrpclib as the base and only overrides those
  6. portions that implement the XML-RPC protocol. These portions are rewritten
  7. to use the JSON-RPC protocol instead.
  8. When large portions of code need to be rewritten the original code and
  9. comments are preserved. The intention here is to keep the amount of code
  10. change to a minimum.
  11. This module only depends on default Python modules. No third party code is
  12. required to use this module.
  13. """
  14. import json
  15. import urllib
  16. import xmlrpclib as _base
  17. __version__ = '1.0.0'
  18. gzip_encode = _base.gzip_encode
  19. class Error(Exception):
  20. def __str__(self):
  21. return repr(self)
  22. class ProtocolError(Error):
  23. """Indicates a JSON protocol error."""
  24. def __init__(self, url, errcode, errmsg, headers):
  25. Error.__init__(self)
  26. self.url = url
  27. self.errcode = errcode
  28. self.errmsg = errmsg
  29. self.headers = headers
  30. def __repr__(self):
  31. return (
  32. '<ProtocolError for %s: %s %s>' %
  33. (self.url, self.errcode, self.errmsg))
  34. class ResponseError(Error):
  35. """Indicates a broken response package."""
  36. pass
  37. class Fault(Error):
  38. """Indicates an JSON-RPC fault package."""
  39. def __init__(self, code, message):
  40. Error.__init__(self)
  41. if not isinstance(code, int):
  42. raise ProtocolError('Fault code must be an integer.')
  43. self.code = code
  44. self.message = message
  45. def __repr__(self):
  46. return (
  47. '<Fault %s: %s>' %
  48. (self.code, repr(self.message))
  49. )
  50. def CreateRequest(methodname, params, ident=''):
  51. """Create a valid JSON-RPC request.
  52. Args:
  53. methodname: The name of the remote method to invoke.
  54. params: The parameters to pass to the remote method. This should be a
  55. list or tuple and able to be encoded by the default JSON parser.
  56. Returns:
  57. A valid JSON-RPC request object.
  58. """
  59. request = {
  60. 'jsonrpc': '2.0',
  61. 'method': methodname,
  62. 'params': params,
  63. 'id': ident
  64. }
  65. return request
  66. def CreateRequestString(methodname, params, ident=''):
  67. """Create a valid JSON-RPC request string.
  68. Args:
  69. methodname: The name of the remote method to invoke.
  70. params: The parameters to pass to the remote method.
  71. These parameters need to be encode-able by the default JSON parser.
  72. ident: The request identifier.
  73. Returns:
  74. A valid JSON-RPC request string.
  75. """
  76. return json.dumps(CreateRequest(methodname, params, ident))
  77. def CreateResponse(data, ident):
  78. """Create a JSON-RPC response.
  79. Args:
  80. data: The data to return.
  81. ident: The response identifier.
  82. Returns:
  83. A valid JSON-RPC response object.
  84. """
  85. if isinstance(data, Fault):
  86. response = {
  87. 'jsonrpc': '2.0',
  88. 'error': {
  89. 'code': data.code,
  90. 'message': data.message},
  91. 'id': ident
  92. }
  93. else:
  94. response = {
  95. 'jsonrpc': '2.0',
  96. 'response': data,
  97. 'id': ident
  98. }
  99. return response
  100. def CreateResponseString(data, ident):
  101. """Create a JSON-RPC response string.
  102. Args:
  103. data: The data to return.
  104. ident: The response identifier.
  105. Returns:
  106. A valid JSON-RPC response object.
  107. """
  108. return json.dumps(CreateResponse(data, ident))
  109. def ParseHTTPResponse(response):
  110. """Parse an HTTP response object and return the JSON object.
  111. Args:
  112. response: An HTTP response object.
  113. Returns:
  114. The returned JSON-RPC object.
  115. Raises:
  116. ProtocolError: if the object format is not correct.
  117. Fault: If a Fault error is returned from the server.
  118. """
  119. # Check for new http response object, else it is a file object
  120. if hasattr(response, 'getheader'):
  121. if response.getheader('Content-Encoding', '') == 'gzip':
  122. stream = _base.GzipDecodedResponse(response)
  123. else:
  124. stream = response
  125. else:
  126. stream = response
  127. data = ''
  128. while 1:
  129. chunk = stream.read(1024)
  130. if not chunk:
  131. break
  132. data += chunk
  133. response = json.loads(data)
  134. ValidateBasicJSONRPCData(response)
  135. if 'response' in response:
  136. ValidateResponse(response)
  137. return response['response']
  138. elif 'error' in response:
  139. ValidateError(response)
  140. code = response['error']['code']
  141. message = response['error']['message']
  142. raise Fault(code, message)
  143. else:
  144. raise ProtocolError('No valid JSON returned')
  145. def ValidateRequest(data):
  146. """Validate a JSON-RPC request object.
  147. Args:
  148. data: The JSON-RPC object (dict).
  149. Raises:
  150. ProtocolError: if the object format is not correct.
  151. """
  152. ValidateBasicJSONRPCData(data)
  153. if 'method' not in data or 'params' not in data:
  154. raise ProtocolError('JSON is not a valid request')
  155. def ValidateResponse(data):
  156. """Validate a JSON-RPC response object.
  157. Args:
  158. data: The JSON-RPC object (dict).
  159. Raises:
  160. ProtocolError: if the object format is not correct.
  161. """
  162. ValidateBasicJSONRPCData(data)
  163. if 'response' not in data:
  164. raise ProtocolError('JSON is not a valid response')
  165. def ValidateError(data):
  166. """Validate a JSON-RPC error object.
  167. Args:
  168. data: The JSON-RPC object (dict).
  169. Raises:
  170. ProtocolError: if the object format is not correct.
  171. """
  172. ValidateBasicJSONRPCData(data)
  173. if ('error' not in data or
  174. 'code' not in data['error'] or
  175. 'message' not in data['error']):
  176. raise ProtocolError('JSON is not a valid error response')
  177. def ValidateBasicJSONRPCData(data):
  178. """Validate a basic JSON-RPC object.
  179. Args:
  180. data: The JSON-RPC object (dict).
  181. Raises:
  182. ProtocolError: if the object format is not correct.
  183. """
  184. error = None
  185. if not isinstance(data, dict):
  186. error = 'JSON data is not a dictionary'
  187. elif 'jsonrpc' not in data or data['jsonrpc'] != '2.0':
  188. error = 'JSON is not a valid JSON RPC 2.0 message'
  189. elif 'id' not in data:
  190. error = 'JSON data missing required id entry'
  191. if error:
  192. raise ProtocolError(error)
  193. class Transport(_base.Transport):
  194. """RPC transport class.
  195. This class extends the functionality of xmlrpclib.Transport and only
  196. overrides the operations needed to change the protocol from XML-RPC to
  197. JSON-RPC.
  198. """
  199. user_agent = 'jsonrpclib.py/' + __version__
  200. def send_content(self, connection, request_body):
  201. """Send the request."""
  202. connection.putheader('Content-Type','application/json')
  203. #optionally encode the request
  204. if (self.encode_threshold is not None and
  205. self.encode_threshold < len(request_body) and
  206. gzip):
  207. connection.putheader('Content-Encoding', 'gzip')
  208. request_body = gzip_encode(request_body)
  209. connection.putheader('Content-Length', str(len(request_body)))
  210. connection.endheaders(request_body)
  211. def single_request(self, host, handler, request_body, verbose=0):
  212. """Issue a single JSON-RPC request."""
  213. h = self.make_connection(host)
  214. if verbose:
  215. h.set_debuglevel(1)
  216. try:
  217. self.send_request(h, handler, request_body)
  218. self.send_host(h, host)
  219. self.send_user_agent(h)
  220. self.send_content(h, request_body)
  221. response = h.getresponse(buffering=True)
  222. if response.status == 200:
  223. self.verbose = verbose
  224. return self.parse_response(response)
  225. except Fault:
  226. raise
  227. except Exception:
  228. # All unexpected errors leave connection in
  229. # a strange state, so we clear it.
  230. self.close()
  231. raise
  232. # discard any response data and raise exception
  233. if response.getheader('content-length', 0):
  234. response.read()
  235. raise ProtocolError(
  236. host + handler,
  237. response.status, response.reason,
  238. response.msg,
  239. )
  240. def parse_response(self, response):
  241. """Parse the HTTP resoponse from the server."""
  242. return ParseHTTPResponse(response)
  243. class SafeTransport(_base.SafeTransport):
  244. """Transport class for HTTPS servers.
  245. This class extends the functionality of xmlrpclib.SafeTransport and only
  246. overrides the operations needed to change the protocol from XML-RPC to
  247. JSON-RPC.
  248. """
  249. def parse_response(self, response):
  250. return ParseHTTPResponse(response)
  251. class ServerProxy(_base.ServerProxy):
  252. """Proxy class to the RPC server.
  253. This class extends the functionality of xmlrpclib.ServerProxy and only
  254. overrides the operations needed to change the protocol from XML-RPC to
  255. JSON-RPC.
  256. """
  257. def __init__(self, uri, transport=None, encoding=None, verbose=0,
  258. allow_none=0, use_datetime=0):
  259. urltype, _ = urllib.splittype(uri)
  260. if urltype not in ('http', 'https'):
  261. raise IOError('unsupported JSON-RPC protocol')
  262. _base.ServerProxy.__init__(self, uri, transport, encoding, verbose,
  263. allow_none, use_datetime)
  264. if transport is None:
  265. if type == 'https':
  266. transport = SafeTransport(use_datetime=use_datetime)
  267. else:
  268. transport = Transport(use_datetime=use_datetime)
  269. self.__transport = transport
  270. def __request(self, methodname, params):
  271. """Call a method on the remote server."""
  272. request = CreateRequestString(methodname, params)
  273. response = self.__transport.request(
  274. self.__host,
  275. self.__handler,
  276. request,
  277. verbose=self.__verbose
  278. )
  279. return response