client.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. #
  2. # XML-RPC CLIENT LIBRARY
  3. # $Id$
  4. #
  5. # an XML-RPC client interface for Python.
  6. #
  7. # the marshalling and response parser code can also be used to
  8. # implement XML-RPC servers.
  9. #
  10. # Notes:
  11. # this version is designed to work with Python 2.1 or newer.
  12. #
  13. # History:
  14. # 1999-01-14 fl Created
  15. # 1999-01-15 fl Changed dateTime to use localtime
  16. # 1999-01-16 fl Added Binary/base64 element, default to RPC2 service
  17. # 1999-01-19 fl Fixed array data element (from Skip Montanaro)
  18. # 1999-01-21 fl Fixed dateTime constructor, etc.
  19. # 1999-02-02 fl Added fault handling, handle empty sequences, etc.
  20. # 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro)
  21. # 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8)
  22. # 2000-11-28 fl Changed boolean to check the truth value of its argument
  23. # 2001-02-24 fl Added encoding/Unicode/SafeTransport patches
  24. # 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1)
  25. # 2001-03-28 fl Make sure response tuple is a singleton
  26. # 2001-03-29 fl Don't require empty params element (from Nicholas Riley)
  27. # 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2)
  28. # 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod)
  29. # 2001-09-03 fl Allow Transport subclass to override getparser
  30. # 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup)
  31. # 2001-10-01 fl Remove containers from memo cache when done with them
  32. # 2001-10-01 fl Use faster escape method (80% dumps speedup)
  33. # 2001-10-02 fl More dumps microtuning
  34. # 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum)
  35. # 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow
  36. # 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems)
  37. # 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix)
  38. # 2002-03-17 fl Avoid buffered read when possible (from James Rucker)
  39. # 2002-04-07 fl Added pythondoc comments
  40. # 2002-04-16 fl Added __str__ methods to datetime/binary wrappers
  41. # 2002-05-15 fl Added error constants (from Andrew Kuchling)
  42. # 2002-06-27 fl Merged with Python CVS version
  43. # 2002-10-22 fl Added basic authentication (based on code from Phillip Eby)
  44. # 2003-01-22 sm Add support for the bool type
  45. # 2003-02-27 gvr Remove apply calls
  46. # 2003-04-24 sm Use cStringIO if available
  47. # 2003-04-25 ak Add support for nil
  48. # 2003-06-15 gn Add support for time.struct_time
  49. # 2003-07-12 gp Correct marshalling of Faults
  50. # 2003-10-31 mvl Add multicall support
  51. # 2004-08-20 mvl Bump minimum supported Python version to 2.1
  52. # 2014-12-02 ch/doko Add workaround for gzip bomb vulnerability
  53. #
  54. # Copyright (c) 1999-2002 by Secret Labs AB.
  55. # Copyright (c) 1999-2002 by Fredrik Lundh.
  56. #
  57. # info@pythonware.com
  58. # http://www.pythonware.com
  59. #
  60. # --------------------------------------------------------------------
  61. # The XML-RPC client interface is
  62. #
  63. # Copyright (c) 1999-2002 by Secret Labs AB
  64. # Copyright (c) 1999-2002 by Fredrik Lundh
  65. #
  66. # By obtaining, using, and/or copying this software and/or its
  67. # associated documentation, you agree that you have read, understood,
  68. # and will comply with the following terms and conditions:
  69. #
  70. # Permission to use, copy, modify, and distribute this software and
  71. # its associated documentation for any purpose and without fee is
  72. # hereby granted, provided that the above copyright notice appears in
  73. # all copies, and that both that copyright notice and this permission
  74. # notice appear in supporting documentation, and that the name of
  75. # Secret Labs AB or the author not be used in advertising or publicity
  76. # pertaining to distribution of the software without specific, written
  77. # prior permission.
  78. #
  79. # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  80. # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
  81. # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
  82. # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
  83. # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  84. # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  85. # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  86. # OF THIS SOFTWARE.
  87. # --------------------------------------------------------------------
  88. """
  89. An XML-RPC client interface for Python.
  90. The marshalling and response parser code can also be used to
  91. implement XML-RPC servers.
  92. Exported exceptions:
  93. Error Base class for client errors
  94. ProtocolError Indicates an HTTP protocol error
  95. ResponseError Indicates a broken response package
  96. Fault Indicates an XML-RPC fault package
  97. Exported classes:
  98. ServerProxy Represents a logical connection to an XML-RPC server
  99. MultiCall Executor of boxcared xmlrpc requests
  100. DateTime dateTime wrapper for an ISO 8601 string or time tuple or
  101. localtime integer value to generate a "dateTime.iso8601"
  102. XML-RPC value
  103. Binary binary data wrapper
  104. Marshaller Generate an XML-RPC params chunk from a Python data structure
  105. Unmarshaller Unmarshal an XML-RPC response from incoming XML event message
  106. Transport Handles an HTTP transaction to an XML-RPC server
  107. SafeTransport Handles an HTTPS transaction to an XML-RPC server
  108. Exported constants:
  109. (none)
  110. Exported functions:
  111. getparser Create instance of the fastest available parser & attach
  112. to an unmarshalling object
  113. dumps Convert an argument tuple or a Fault instance to an XML-RPC
  114. request (or response, if the methodresponse option is used).
  115. loads Convert an XML-RPC packet to unmarshalled data plus a method
  116. name (None if not present).
  117. """
  118. import base64
  119. import sys
  120. import time
  121. from datetime import datetime
  122. from decimal import Decimal
  123. import http.client
  124. import urllib.parse
  125. from xml.parsers import expat
  126. import errno
  127. from io import BytesIO
  128. try:
  129. import gzip
  130. except ImportError:
  131. gzip = None #python can be built without zlib/gzip support
  132. # --------------------------------------------------------------------
  133. # Internal stuff
  134. def escape(s):
  135. s = s.replace("&", "&")
  136. s = s.replace("<", "&lt;")
  137. return s.replace(">", "&gt;",)
  138. # used in User-Agent header sent
  139. __version__ = '%d.%d' % sys.version_info[:2]
  140. # xmlrpc integer limits
  141. MAXINT = 2**31-1
  142. MININT = -2**31
  143. # --------------------------------------------------------------------
  144. # Error constants (from Dan Libby's specification at
  145. # http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php)
  146. # Ranges of errors
  147. PARSE_ERROR = -32700
  148. SERVER_ERROR = -32600
  149. APPLICATION_ERROR = -32500
  150. SYSTEM_ERROR = -32400
  151. TRANSPORT_ERROR = -32300
  152. # Specific errors
  153. NOT_WELLFORMED_ERROR = -32700
  154. UNSUPPORTED_ENCODING = -32701
  155. INVALID_ENCODING_CHAR = -32702
  156. INVALID_XMLRPC = -32600
  157. METHOD_NOT_FOUND = -32601
  158. INVALID_METHOD_PARAMS = -32602
  159. INTERNAL_ERROR = -32603
  160. # --------------------------------------------------------------------
  161. # Exceptions
  162. ##
  163. # Base class for all kinds of client-side errors.
  164. class Error(Exception):
  165. """Base class for client errors."""
  166. __str__ = object.__str__
  167. ##
  168. # Indicates an HTTP-level protocol error. This is raised by the HTTP
  169. # transport layer, if the server returns an error code other than 200
  170. # (OK).
  171. #
  172. # @param url The target URL.
  173. # @param errcode The HTTP error code.
  174. # @param errmsg The HTTP error message.
  175. # @param headers The HTTP header dictionary.
  176. class ProtocolError(Error):
  177. """Indicates an HTTP protocol error."""
  178. def __init__(self, url, errcode, errmsg, headers):
  179. Error.__init__(self)
  180. self.url = url
  181. self.errcode = errcode
  182. self.errmsg = errmsg
  183. self.headers = headers
  184. def __repr__(self):
  185. return (
  186. "<%s for %s: %s %s>" %
  187. (self.__class__.__name__, self.url, self.errcode, self.errmsg)
  188. )
  189. ##
  190. # Indicates a broken XML-RPC response package. This exception is
  191. # raised by the unmarshalling layer, if the XML-RPC response is
  192. # malformed.
  193. class ResponseError(Error):
  194. """Indicates a broken response package."""
  195. pass
  196. ##
  197. # Indicates an XML-RPC fault response package. This exception is
  198. # raised by the unmarshalling layer, if the XML-RPC response contains
  199. # a fault string. This exception can also be used as a class, to
  200. # generate a fault XML-RPC message.
  201. #
  202. # @param faultCode The XML-RPC fault code.
  203. # @param faultString The XML-RPC fault string.
  204. class Fault(Error):
  205. """Indicates an XML-RPC fault package."""
  206. def __init__(self, faultCode, faultString, **extra):
  207. Error.__init__(self)
  208. self.faultCode = faultCode
  209. self.faultString = faultString
  210. def __repr__(self):
  211. return "<%s %s: %r>" % (self.__class__.__name__,
  212. self.faultCode, self.faultString)
  213. # --------------------------------------------------------------------
  214. # Special values
  215. ##
  216. # Backwards compatibility
  217. boolean = Boolean = bool
  218. ##
  219. # Wrapper for XML-RPC DateTime values. This converts a time value to
  220. # the format used by XML-RPC.
  221. # <p>
  222. # The value can be given as a datetime object, as a string in the
  223. # format "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by
  224. # time.localtime()), or an integer value (as returned by time.time()).
  225. # The wrapper uses time.localtime() to convert an integer to a time
  226. # tuple.
  227. #
  228. # @param value The time, given as a datetime object, an ISO 8601 string,
  229. # a time tuple, or an integer time value.
  230. # Issue #13305: different format codes across platforms
  231. _day0 = datetime(1, 1, 1)
  232. def _try(fmt):
  233. try:
  234. return _day0.strftime(fmt) == '0001'
  235. except ValueError:
  236. return False
  237. if _try('%Y'): # Mac OS X
  238. def _iso8601_format(value):
  239. return value.strftime("%Y%m%dT%H:%M:%S")
  240. elif _try('%4Y'): # Linux
  241. def _iso8601_format(value):
  242. return value.strftime("%4Y%m%dT%H:%M:%S")
  243. else:
  244. def _iso8601_format(value):
  245. return value.strftime("%Y%m%dT%H:%M:%S").zfill(17)
  246. del _day0
  247. del _try
  248. def _strftime(value):
  249. if isinstance(value, datetime):
  250. return _iso8601_format(value)
  251. if not isinstance(value, (tuple, time.struct_time)):
  252. if value == 0:
  253. value = time.time()
  254. value = time.localtime(value)
  255. return "%04d%02d%02dT%02d:%02d:%02d" % value[:6]
  256. class DateTime:
  257. """DateTime wrapper for an ISO 8601 string or time tuple or
  258. localtime integer value to generate 'dateTime.iso8601' XML-RPC
  259. value.
  260. """
  261. def __init__(self, value=0):
  262. if isinstance(value, str):
  263. self.value = value
  264. else:
  265. self.value = _strftime(value)
  266. def make_comparable(self, other):
  267. if isinstance(other, DateTime):
  268. s = self.value
  269. o = other.value
  270. elif isinstance(other, datetime):
  271. s = self.value
  272. o = _iso8601_format(other)
  273. elif isinstance(other, str):
  274. s = self.value
  275. o = other
  276. elif hasattr(other, "timetuple"):
  277. s = self.timetuple()
  278. o = other.timetuple()
  279. else:
  280. s = self
  281. o = NotImplemented
  282. return s, o
  283. def __lt__(self, other):
  284. s, o = self.make_comparable(other)
  285. if o is NotImplemented:
  286. return NotImplemented
  287. return s < o
  288. def __le__(self, other):
  289. s, o = self.make_comparable(other)
  290. if o is NotImplemented:
  291. return NotImplemented
  292. return s <= o
  293. def __gt__(self, other):
  294. s, o = self.make_comparable(other)
  295. if o is NotImplemented:
  296. return NotImplemented
  297. return s > o
  298. def __ge__(self, other):
  299. s, o = self.make_comparable(other)
  300. if o is NotImplemented:
  301. return NotImplemented
  302. return s >= o
  303. def __eq__(self, other):
  304. s, o = self.make_comparable(other)
  305. if o is NotImplemented:
  306. return NotImplemented
  307. return s == o
  308. def timetuple(self):
  309. return time.strptime(self.value, "%Y%m%dT%H:%M:%S")
  310. ##
  311. # Get date/time value.
  312. #
  313. # @return Date/time value, as an ISO 8601 string.
  314. def __str__(self):
  315. return self.value
  316. def __repr__(self):
  317. return "<%s %r at %#x>" % (self.__class__.__name__, self.value, id(self))
  318. def decode(self, data):
  319. self.value = str(data).strip()
  320. def encode(self, out):
  321. out.write("<value><dateTime.iso8601>")
  322. out.write(self.value)
  323. out.write("</dateTime.iso8601></value>\n")
  324. def _datetime(data):
  325. # decode xml element contents into a DateTime structure.
  326. value = DateTime()
  327. value.decode(data)
  328. return value
  329. def _datetime_type(data):
  330. return datetime.strptime(data, "%Y%m%dT%H:%M:%S")
  331. ##
  332. # Wrapper for binary data. This can be used to transport any kind
  333. # of binary data over XML-RPC, using BASE64 encoding.
  334. #
  335. # @param data An 8-bit string containing arbitrary data.
  336. class Binary:
  337. """Wrapper for binary data."""
  338. def __init__(self, data=None):
  339. if data is None:
  340. data = b""
  341. else:
  342. if not isinstance(data, (bytes, bytearray)):
  343. raise TypeError("expected bytes or bytearray, not %s" %
  344. data.__class__.__name__)
  345. data = bytes(data) # Make a copy of the bytes!
  346. self.data = data
  347. ##
  348. # Get buffer contents.
  349. #
  350. # @return Buffer contents, as an 8-bit string.
  351. def __str__(self):
  352. return str(self.data, "latin-1") # XXX encoding?!
  353. def __eq__(self, other):
  354. if isinstance(other, Binary):
  355. other = other.data
  356. return self.data == other
  357. def decode(self, data):
  358. self.data = base64.decodebytes(data)
  359. def encode(self, out):
  360. out.write("<value><base64>\n")
  361. encoded = base64.encodebytes(self.data)
  362. out.write(encoded.decode('ascii'))
  363. out.write("</base64></value>\n")
  364. def _binary(data):
  365. # decode xml element contents into a Binary structure
  366. value = Binary()
  367. value.decode(data)
  368. return value
  369. WRAPPERS = (DateTime, Binary)
  370. # --------------------------------------------------------------------
  371. # XML parsers
  372. class ExpatParser:
  373. # fast expat parser for Python 2.0 and later.
  374. def __init__(self, target):
  375. self._parser = parser = expat.ParserCreate(None, None)
  376. self._target = target
  377. parser.StartElementHandler = target.start
  378. parser.EndElementHandler = target.end
  379. parser.CharacterDataHandler = target.data
  380. encoding = None
  381. target.xml(encoding, None)
  382. def feed(self, data):
  383. self._parser.Parse(data, False)
  384. def close(self):
  385. try:
  386. parser = self._parser
  387. except AttributeError:
  388. pass
  389. else:
  390. del self._target, self._parser # get rid of circular references
  391. parser.Parse(b"", True) # end of data
  392. # --------------------------------------------------------------------
  393. # XML-RPC marshalling and unmarshalling code
  394. ##
  395. # XML-RPC marshaller.
  396. #
  397. # @param encoding Default encoding for 8-bit strings. The default
  398. # value is None (interpreted as UTF-8).
  399. # @see dumps
  400. class Marshaller:
  401. """Generate an XML-RPC params chunk from a Python data structure.
  402. Create a Marshaller instance for each set of parameters, and use
  403. the "dumps" method to convert your data (represented as a tuple)
  404. to an XML-RPC params chunk. To write a fault response, pass a
  405. Fault instance instead. You may prefer to use the "dumps" module
  406. function for this purpose.
  407. """
  408. # by the way, if you don't understand what's going on in here,
  409. # that's perfectly ok.
  410. def __init__(self, encoding=None, allow_none=False):
  411. self.memo = {}
  412. self.data = None
  413. self.encoding = encoding
  414. self.allow_none = allow_none
  415. dispatch = {}
  416. def dumps(self, values):
  417. out = []
  418. write = out.append
  419. dump = self.__dump
  420. if isinstance(values, Fault):
  421. # fault instance
  422. write("<fault>\n")
  423. dump({'faultCode': values.faultCode,
  424. 'faultString': values.faultString},
  425. write)
  426. write("</fault>\n")
  427. else:
  428. # parameter block
  429. # FIXME: the xml-rpc specification allows us to leave out
  430. # the entire <params> block if there are no parameters.
  431. # however, changing this may break older code (including
  432. # old versions of xmlrpclib.py), so this is better left as
  433. # is for now. See @XMLRPC3 for more information. /F
  434. write("<params>\n")
  435. for v in values:
  436. write("<param>\n")
  437. dump(v, write)
  438. write("</param>\n")
  439. write("</params>\n")
  440. result = "".join(out)
  441. return result
  442. def __dump(self, value, write):
  443. try:
  444. f = self.dispatch[type(value)]
  445. except KeyError:
  446. # check if this object can be marshalled as a structure
  447. if not hasattr(value, '__dict__'):
  448. raise TypeError("cannot marshal %s objects" % type(value))
  449. # check if this class is a sub-class of a basic type,
  450. # because we don't know how to marshal these types
  451. # (e.g. a string sub-class)
  452. for type_ in type(value).__mro__:
  453. if type_ in self.dispatch.keys():
  454. raise TypeError("cannot marshal %s objects" % type(value))
  455. # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
  456. # for the p3yk merge, this should probably be fixed more neatly.
  457. f = self.dispatch["_arbitrary_instance"]
  458. f(self, value, write)
  459. def dump_nil (self, value, write):
  460. if not self.allow_none:
  461. raise TypeError("cannot marshal None unless allow_none is enabled")
  462. write("<value><nil/></value>")
  463. dispatch[type(None)] = dump_nil
  464. def dump_bool(self, value, write):
  465. write("<value><boolean>")
  466. write(value and "1" or "0")
  467. write("</boolean></value>\n")
  468. dispatch[bool] = dump_bool
  469. def dump_long(self, value, write):
  470. if value > MAXINT or value < MININT:
  471. raise OverflowError("int exceeds XML-RPC limits")
  472. write("<value><int>")
  473. write(str(int(value)))
  474. write("</int></value>\n")
  475. dispatch[int] = dump_long
  476. # backward compatible
  477. dump_int = dump_long
  478. def dump_double(self, value, write):
  479. write("<value><double>")
  480. write(repr(value))
  481. write("</double></value>\n")
  482. dispatch[float] = dump_double
  483. def dump_unicode(self, value, write, escape=escape):
  484. write("<value><string>")
  485. write(escape(value))
  486. write("</string></value>\n")
  487. dispatch[str] = dump_unicode
  488. def dump_bytes(self, value, write):
  489. write("<value><base64>\n")
  490. encoded = base64.encodebytes(value)
  491. write(encoded.decode('ascii'))
  492. write("</base64></value>\n")
  493. dispatch[bytes] = dump_bytes
  494. dispatch[bytearray] = dump_bytes
  495. def dump_array(self, value, write):
  496. i = id(value)
  497. if i in self.memo:
  498. raise TypeError("cannot marshal recursive sequences")
  499. self.memo[i] = None
  500. dump = self.__dump
  501. write("<value><array><data>\n")
  502. for v in value:
  503. dump(v, write)
  504. write("</data></array></value>\n")
  505. del self.memo[i]
  506. dispatch[tuple] = dump_array
  507. dispatch[list] = dump_array
  508. def dump_struct(self, value, write, escape=escape):
  509. i = id(value)
  510. if i in self.memo:
  511. raise TypeError("cannot marshal recursive dictionaries")
  512. self.memo[i] = None
  513. dump = self.__dump
  514. write("<value><struct>\n")
  515. for k, v in value.items():
  516. write("<member>\n")
  517. if not isinstance(k, str):
  518. raise TypeError("dictionary key must be string")
  519. write("<name>%s</name>\n" % escape(k))
  520. dump(v, write)
  521. write("</member>\n")
  522. write("</struct></value>\n")
  523. del self.memo[i]
  524. dispatch[dict] = dump_struct
  525. def dump_datetime(self, value, write):
  526. write("<value><dateTime.iso8601>")
  527. write(_strftime(value))
  528. write("</dateTime.iso8601></value>\n")
  529. dispatch[datetime] = dump_datetime
  530. def dump_instance(self, value, write):
  531. # check for special wrappers
  532. if value.__class__ in WRAPPERS:
  533. self.write = write
  534. value.encode(self)
  535. del self.write
  536. else:
  537. # store instance attributes as a struct (really?)
  538. self.dump_struct(value.__dict__, write)
  539. dispatch[DateTime] = dump_instance
  540. dispatch[Binary] = dump_instance
  541. # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
  542. # for the p3yk merge, this should probably be fixed more neatly.
  543. dispatch["_arbitrary_instance"] = dump_instance
  544. ##
  545. # XML-RPC unmarshaller.
  546. #
  547. # @see loads
  548. class Unmarshaller:
  549. """Unmarshal an XML-RPC response, based on incoming XML event
  550. messages (start, data, end). Call close() to get the resulting
  551. data structure.
  552. Note that this reader is fairly tolerant, and gladly accepts bogus
  553. XML-RPC data without complaining (but not bogus XML).
  554. """
  555. # and again, if you don't understand what's going on in here,
  556. # that's perfectly ok.
  557. def __init__(self, use_datetime=False, use_builtin_types=False):
  558. self._type = None
  559. self._stack = []
  560. self._marks = []
  561. self._data = []
  562. self._value = False
  563. self._methodname = None
  564. self._encoding = "utf-8"
  565. self.append = self._stack.append
  566. self._use_datetime = use_builtin_types or use_datetime
  567. self._use_bytes = use_builtin_types
  568. def close(self):
  569. # return response tuple and target method
  570. if self._type is None or self._marks:
  571. raise ResponseError()
  572. if self._type == "fault":
  573. raise Fault(**self._stack[0])
  574. return tuple(self._stack)
  575. def getmethodname(self):
  576. return self._methodname
  577. #
  578. # event handlers
  579. def xml(self, encoding, standalone):
  580. self._encoding = encoding
  581. # FIXME: assert standalone == 1 ???
  582. def start(self, tag, attrs):
  583. # prepare to handle this element
  584. if ':' in tag:
  585. tag = tag.split(':')[-1]
  586. if tag == "array" or tag == "struct":
  587. self._marks.append(len(self._stack))
  588. self._data = []
  589. if self._value and tag not in self.dispatch:
  590. raise ResponseError("unknown tag %r" % tag)
  591. self._value = (tag == "value")
  592. def data(self, text):
  593. self._data.append(text)
  594. def end(self, tag):
  595. # call the appropriate end tag handler
  596. try:
  597. f = self.dispatch[tag]
  598. except KeyError:
  599. if ':' not in tag:
  600. return # unknown tag ?
  601. try:
  602. f = self.dispatch[tag.split(':')[-1]]
  603. except KeyError:
  604. return # unknown tag ?
  605. return f(self, "".join(self._data))
  606. #
  607. # accelerator support
  608. def end_dispatch(self, tag, data):
  609. # dispatch data
  610. try:
  611. f = self.dispatch[tag]
  612. except KeyError:
  613. if ':' not in tag:
  614. return # unknown tag ?
  615. try:
  616. f = self.dispatch[tag.split(':')[-1]]
  617. except KeyError:
  618. return # unknown tag ?
  619. return f(self, data)
  620. #
  621. # element decoders
  622. dispatch = {}
  623. def end_nil (self, data):
  624. self.append(None)
  625. self._value = 0
  626. dispatch["nil"] = end_nil
  627. def end_boolean(self, data):
  628. if data == "0":
  629. self.append(False)
  630. elif data == "1":
  631. self.append(True)
  632. else:
  633. raise TypeError("bad boolean value")
  634. self._value = 0
  635. dispatch["boolean"] = end_boolean
  636. def end_int(self, data):
  637. self.append(int(data))
  638. self._value = 0
  639. dispatch["i1"] = end_int
  640. dispatch["i2"] = end_int
  641. dispatch["i4"] = end_int
  642. dispatch["i8"] = end_int
  643. dispatch["int"] = end_int
  644. dispatch["biginteger"] = end_int
  645. def end_double(self, data):
  646. self.append(float(data))
  647. self._value = 0
  648. dispatch["double"] = end_double
  649. dispatch["float"] = end_double
  650. def end_bigdecimal(self, data):
  651. self.append(Decimal(data))
  652. self._value = 0
  653. dispatch["bigdecimal"] = end_bigdecimal
  654. def end_string(self, data):
  655. if self._encoding:
  656. data = data.decode(self._encoding)
  657. self.append(data)
  658. self._value = 0
  659. dispatch["string"] = end_string
  660. dispatch["name"] = end_string # struct keys are always strings
  661. def end_array(self, data):
  662. mark = self._marks.pop()
  663. # map arrays to Python lists
  664. self._stack[mark:] = [self._stack[mark:]]
  665. self._value = 0
  666. dispatch["array"] = end_array
  667. def end_struct(self, data):
  668. mark = self._marks.pop()
  669. # map structs to Python dictionaries
  670. dict = {}
  671. items = self._stack[mark:]
  672. for i in range(0, len(items), 2):
  673. dict[items[i]] = items[i+1]
  674. self._stack[mark:] = [dict]
  675. self._value = 0
  676. dispatch["struct"] = end_struct
  677. def end_base64(self, data):
  678. value = Binary()
  679. value.decode(data.encode("ascii"))
  680. if self._use_bytes:
  681. value = value.data
  682. self.append(value)
  683. self._value = 0
  684. dispatch["base64"] = end_base64
  685. def end_dateTime(self, data):
  686. value = DateTime()
  687. value.decode(data)
  688. if self._use_datetime:
  689. value = _datetime_type(data)
  690. self.append(value)
  691. dispatch["dateTime.iso8601"] = end_dateTime
  692. def end_value(self, data):
  693. # if we stumble upon a value element with no internal
  694. # elements, treat it as a string element
  695. if self._value:
  696. self.end_string(data)
  697. dispatch["value"] = end_value
  698. def end_params(self, data):
  699. self._type = "params"
  700. dispatch["params"] = end_params
  701. def end_fault(self, data):
  702. self._type = "fault"
  703. dispatch["fault"] = end_fault
  704. def end_methodName(self, data):
  705. if self._encoding:
  706. data = data.decode(self._encoding)
  707. self._methodname = data
  708. self._type = "methodName" # no params
  709. dispatch["methodName"] = end_methodName
  710. ## Multicall support
  711. #
  712. class _MultiCallMethod:
  713. # some lesser magic to store calls made to a MultiCall object
  714. # for batch execution
  715. def __init__(self, call_list, name):
  716. self.__call_list = call_list
  717. self.__name = name
  718. def __getattr__(self, name):
  719. return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name))
  720. def __call__(self, *args):
  721. self.__call_list.append((self.__name, args))
  722. class MultiCallIterator:
  723. """Iterates over the results of a multicall. Exceptions are
  724. raised in response to xmlrpc faults."""
  725. def __init__(self, results):
  726. self.results = results
  727. def __getitem__(self, i):
  728. item = self.results[i]
  729. if type(item) == type({}):
  730. raise Fault(item['faultCode'], item['faultString'])
  731. elif type(item) == type([]):
  732. return item[0]
  733. else:
  734. raise ValueError("unexpected type in multicall result")
  735. class MultiCall:
  736. """server -> an object used to boxcar method calls
  737. server should be a ServerProxy object.
  738. Methods can be added to the MultiCall using normal
  739. method call syntax e.g.:
  740. multicall = MultiCall(server_proxy)
  741. multicall.add(2,3)
  742. multicall.get_address("Guido")
  743. To execute the multicall, call the MultiCall object e.g.:
  744. add_result, address = multicall()
  745. """
  746. def __init__(self, server):
  747. self.__server = server
  748. self.__call_list = []
  749. def __repr__(self):
  750. return "<%s at %#x>" % (self.__class__.__name__, id(self))
  751. def __getattr__(self, name):
  752. return _MultiCallMethod(self.__call_list, name)
  753. def __call__(self):
  754. marshalled_list = []
  755. for name, args in self.__call_list:
  756. marshalled_list.append({'methodName' : name, 'params' : args})
  757. return MultiCallIterator(self.__server.system.multicall(marshalled_list))
  758. # --------------------------------------------------------------------
  759. # convenience functions
  760. FastMarshaller = FastParser = FastUnmarshaller = None
  761. ##
  762. # Create a parser object, and connect it to an unmarshalling instance.
  763. # This function picks the fastest available XML parser.
  764. #
  765. # return A (parser, unmarshaller) tuple.
  766. def getparser(use_datetime=False, use_builtin_types=False):
  767. """getparser() -> parser, unmarshaller
  768. Create an instance of the fastest available parser, and attach it
  769. to an unmarshalling object. Return both objects.
  770. """
  771. if FastParser and FastUnmarshaller:
  772. if use_builtin_types:
  773. mkdatetime = _datetime_type
  774. mkbytes = base64.decodebytes
  775. elif use_datetime:
  776. mkdatetime = _datetime_type
  777. mkbytes = _binary
  778. else:
  779. mkdatetime = _datetime
  780. mkbytes = _binary
  781. target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault)
  782. parser = FastParser(target)
  783. else:
  784. target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
  785. if FastParser:
  786. parser = FastParser(target)
  787. else:
  788. parser = ExpatParser(target)
  789. return parser, target
  790. ##
  791. # Convert a Python tuple or a Fault instance to an XML-RPC packet.
  792. #
  793. # @def dumps(params, **options)
  794. # @param params A tuple or Fault instance.
  795. # @keyparam methodname If given, create a methodCall request for
  796. # this method name.
  797. # @keyparam methodresponse If given, create a methodResponse packet.
  798. # If used with a tuple, the tuple must be a singleton (that is,
  799. # it must contain exactly one element).
  800. # @keyparam encoding The packet encoding.
  801. # @return A string containing marshalled data.
  802. def dumps(params, methodname=None, methodresponse=None, encoding=None,
  803. allow_none=False):
  804. """data [,options] -> marshalled data
  805. Convert an argument tuple or a Fault instance to an XML-RPC
  806. request (or response, if the methodresponse option is used).
  807. In addition to the data object, the following options can be given
  808. as keyword arguments:
  809. methodname: the method name for a methodCall packet
  810. methodresponse: true to create a methodResponse packet.
  811. If this option is used with a tuple, the tuple must be
  812. a singleton (i.e. it can contain only one element).
  813. encoding: the packet encoding (default is UTF-8)
  814. All byte strings in the data structure are assumed to use the
  815. packet encoding. Unicode strings are automatically converted,
  816. where necessary.
  817. """
  818. assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance"
  819. if isinstance(params, Fault):
  820. methodresponse = 1
  821. elif methodresponse and isinstance(params, tuple):
  822. assert len(params) == 1, "response tuple must be a singleton"
  823. if not encoding:
  824. encoding = "utf-8"
  825. if FastMarshaller:
  826. m = FastMarshaller(encoding)
  827. else:
  828. m = Marshaller(encoding, allow_none)
  829. data = m.dumps(params)
  830. if encoding != "utf-8":
  831. xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
  832. else:
  833. xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
  834. # standard XML-RPC wrappings
  835. if methodname:
  836. # a method call
  837. data = (
  838. xmlheader,
  839. "<methodCall>\n"
  840. "<methodName>", methodname, "</methodName>\n",
  841. data,
  842. "</methodCall>\n"
  843. )
  844. elif methodresponse:
  845. # a method response, or a fault structure
  846. data = (
  847. xmlheader,
  848. "<methodResponse>\n",
  849. data,
  850. "</methodResponse>\n"
  851. )
  852. else:
  853. return data # return as is
  854. return "".join(data)
  855. ##
  856. # Convert an XML-RPC packet to a Python object. If the XML-RPC packet
  857. # represents a fault condition, this function raises a Fault exception.
  858. #
  859. # @param data An XML-RPC packet, given as an 8-bit string.
  860. # @return A tuple containing the unpacked data, and the method name
  861. # (None if not present).
  862. # @see Fault
  863. def loads(data, use_datetime=False, use_builtin_types=False):
  864. """data -> unmarshalled data, method name
  865. Convert an XML-RPC packet to unmarshalled data plus a method
  866. name (None if not present).
  867. If the XML-RPC packet represents a fault condition, this function
  868. raises a Fault exception.
  869. """
  870. p, u = getparser(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
  871. p.feed(data)
  872. p.close()
  873. return u.close(), u.getmethodname()
  874. ##
  875. # Encode a string using the gzip content encoding such as specified by the
  876. # Content-Encoding: gzip
  877. # in the HTTP header, as described in RFC 1952
  878. #
  879. # @param data the unencoded data
  880. # @return the encoded data
  881. def gzip_encode(data):
  882. """data -> gzip encoded data
  883. Encode data using the gzip content encoding as described in RFC 1952
  884. """
  885. if not gzip:
  886. raise NotImplementedError
  887. f = BytesIO()
  888. with gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) as gzf:
  889. gzf.write(data)
  890. return f.getvalue()
  891. ##
  892. # Decode a string using the gzip content encoding such as specified by the
  893. # Content-Encoding: gzip
  894. # in the HTTP header, as described in RFC 1952
  895. #
  896. # @param data The encoded data
  897. # @keyparam max_decode Maximum bytes to decode (20 MiB default), use negative
  898. # values for unlimited decoding
  899. # @return the unencoded data
  900. # @raises ValueError if data is not correctly coded.
  901. # @raises ValueError if max gzipped payload length exceeded
  902. def gzip_decode(data, max_decode=20971520):
  903. """gzip encoded data -> unencoded data
  904. Decode data using the gzip content encoding as described in RFC 1952
  905. """
  906. if not gzip:
  907. raise NotImplementedError
  908. with gzip.GzipFile(mode="rb", fileobj=BytesIO(data)) as gzf:
  909. try:
  910. if max_decode < 0: # no limit
  911. decoded = gzf.read()
  912. else:
  913. decoded = gzf.read(max_decode + 1)
  914. except OSError:
  915. raise ValueError("invalid data")
  916. if max_decode >= 0 and len(decoded) > max_decode:
  917. raise ValueError("max gzipped payload length exceeded")
  918. return decoded
  919. ##
  920. # Return a decoded file-like object for the gzip encoding
  921. # as described in RFC 1952.
  922. #
  923. # @param response A stream supporting a read() method
  924. # @return a file-like object that the decoded data can be read() from
  925. class GzipDecodedResponse(gzip.GzipFile if gzip else object):
  926. """a file-like object to decode a response encoded with the gzip
  927. method, as described in RFC 1952.
  928. """
  929. def __init__(self, response):
  930. #response doesn't support tell() and read(), required by
  931. #GzipFile
  932. if not gzip:
  933. raise NotImplementedError
  934. self.io = BytesIO(response.read())
  935. gzip.GzipFile.__init__(self, mode="rb", fileobj=self.io)
  936. def close(self):
  937. try:
  938. gzip.GzipFile.close(self)
  939. finally:
  940. self.io.close()
  941. # --------------------------------------------------------------------
  942. # request dispatcher
  943. class _Method:
  944. # some magic to bind an XML-RPC method to an RPC server.
  945. # supports "nested" methods (e.g. examples.getStateName)
  946. def __init__(self, send, name):
  947. self.__send = send
  948. self.__name = name
  949. def __getattr__(self, name):
  950. return _Method(self.__send, "%s.%s" % (self.__name, name))
  951. def __call__(self, *args):
  952. return self.__send(self.__name, args)
  953. ##
  954. # Standard transport class for XML-RPC over HTTP.
  955. # <p>
  956. # You can create custom transports by subclassing this method, and
  957. # overriding selected methods.
  958. class Transport:
  959. """Handles an HTTP transaction to an XML-RPC server."""
  960. # client identifier (may be overridden)
  961. user_agent = "Python-xmlrpc/%s" % __version__
  962. #if true, we'll request gzip encoding
  963. accept_gzip_encoding = True
  964. # if positive, encode request using gzip if it exceeds this threshold
  965. # note that many servers will get confused, so only use it if you know
  966. # that they can decode such a request
  967. encode_threshold = None #None = don't encode
  968. def __init__(self, use_datetime=False, use_builtin_types=False,
  969. *, headers=()):
  970. self._use_datetime = use_datetime
  971. self._use_builtin_types = use_builtin_types
  972. self._connection = (None, None)
  973. self._headers = list(headers)
  974. self._extra_headers = []
  975. ##
  976. # Send a complete request, and parse the response.
  977. # Retry request if a cached connection has disconnected.
  978. #
  979. # @param host Target host.
  980. # @param handler Target PRC handler.
  981. # @param request_body XML-RPC request body.
  982. # @param verbose Debugging flag.
  983. # @return Parsed response.
  984. def request(self, host, handler, request_body, verbose=False):
  985. #retry request once if cached connection has gone cold
  986. for i in (0, 1):
  987. try:
  988. return self.single_request(host, handler, request_body, verbose)
  989. except http.client.RemoteDisconnected:
  990. if i:
  991. raise
  992. except OSError as e:
  993. if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED,
  994. errno.EPIPE):
  995. raise
  996. def single_request(self, host, handler, request_body, verbose=False):
  997. # issue XML-RPC request
  998. try:
  999. http_conn = self.send_request(host, handler, request_body, verbose)
  1000. resp = http_conn.getresponse()
  1001. if resp.status == 200:
  1002. self.verbose = verbose
  1003. return self.parse_response(resp)
  1004. except Fault:
  1005. raise
  1006. except Exception:
  1007. #All unexpected errors leave connection in
  1008. # a strange state, so we clear it.
  1009. self.close()
  1010. raise
  1011. #We got an error response.
  1012. #Discard any response data and raise exception
  1013. if resp.getheader("content-length", ""):
  1014. resp.read()
  1015. raise ProtocolError(
  1016. host + handler,
  1017. resp.status, resp.reason,
  1018. dict(resp.getheaders())
  1019. )
  1020. ##
  1021. # Create parser.
  1022. #
  1023. # @return A 2-tuple containing a parser and an unmarshaller.
  1024. def getparser(self):
  1025. # get parser and unmarshaller
  1026. return getparser(use_datetime=self._use_datetime,
  1027. use_builtin_types=self._use_builtin_types)
  1028. ##
  1029. # Get authorization info from host parameter
  1030. # Host may be a string, or a (host, x509-dict) tuple; if a string,
  1031. # it is checked for a "user:pw@host" format, and a "Basic
  1032. # Authentication" header is added if appropriate.
  1033. #
  1034. # @param host Host descriptor (URL or (URL, x509 info) tuple).
  1035. # @return A 3-tuple containing (actual host, extra headers,
  1036. # x509 info). The header and x509 fields may be None.
  1037. def get_host_info(self, host):
  1038. x509 = {}
  1039. if isinstance(host, tuple):
  1040. host, x509 = host
  1041. auth, host = urllib.parse._splituser(host)
  1042. if auth:
  1043. auth = urllib.parse.unquote_to_bytes(auth)
  1044. auth = base64.encodebytes(auth).decode("utf-8")
  1045. auth = "".join(auth.split()) # get rid of whitespace
  1046. extra_headers = [
  1047. ("Authorization", "Basic " + auth)
  1048. ]
  1049. else:
  1050. extra_headers = []
  1051. return host, extra_headers, x509
  1052. ##
  1053. # Connect to server.
  1054. #
  1055. # @param host Target host.
  1056. # @return An HTTPConnection object
  1057. def make_connection(self, host):
  1058. #return an existing connection if possible. This allows
  1059. #HTTP/1.1 keep-alive.
  1060. if self._connection and host == self._connection[0]:
  1061. return self._connection[1]
  1062. # create a HTTP connection object from a host descriptor
  1063. chost, self._extra_headers, x509 = self.get_host_info(host)
  1064. self._connection = host, http.client.HTTPConnection(chost)
  1065. return self._connection[1]
  1066. ##
  1067. # Clear any cached connection object.
  1068. # Used in the event of socket errors.
  1069. #
  1070. def close(self):
  1071. host, connection = self._connection
  1072. if connection:
  1073. self._connection = (None, None)
  1074. connection.close()
  1075. ##
  1076. # Send HTTP request.
  1077. #
  1078. # @param host Host descriptor (URL or (URL, x509 info) tuple).
  1079. # @param handler Target RPC handler (a path relative to host)
  1080. # @param request_body The XML-RPC request body
  1081. # @param debug Enable debugging if debug is true.
  1082. # @return An HTTPConnection.
  1083. def send_request(self, host, handler, request_body, debug):
  1084. connection = self.make_connection(host)
  1085. headers = self._headers + self._extra_headers
  1086. if debug:
  1087. connection.set_debuglevel(1)
  1088. if self.accept_gzip_encoding and gzip:
  1089. connection.putrequest("POST", handler, skip_accept_encoding=True)
  1090. headers.append(("Accept-Encoding", "gzip"))
  1091. else:
  1092. connection.putrequest("POST", handler)
  1093. headers.append(("Content-Type", "text/xml"))
  1094. headers.append(("User-Agent", self.user_agent))
  1095. self.send_headers(connection, headers)
  1096. self.send_content(connection, request_body)
  1097. return connection
  1098. ##
  1099. # Send request headers.
  1100. # This function provides a useful hook for subclassing
  1101. #
  1102. # @param connection httpConnection.
  1103. # @param headers list of key,value pairs for HTTP headers
  1104. def send_headers(self, connection, headers):
  1105. for key, val in headers:
  1106. connection.putheader(key, val)
  1107. ##
  1108. # Send request body.
  1109. # This function provides a useful hook for subclassing
  1110. #
  1111. # @param connection httpConnection.
  1112. # @param request_body XML-RPC request body.
  1113. def send_content(self, connection, request_body):
  1114. #optionally encode the request
  1115. if (self.encode_threshold is not None and
  1116. self.encode_threshold < len(request_body) and
  1117. gzip):
  1118. connection.putheader("Content-Encoding", "gzip")
  1119. request_body = gzip_encode(request_body)
  1120. connection.putheader("Content-Length", str(len(request_body)))
  1121. connection.endheaders(request_body)
  1122. ##
  1123. # Parse response.
  1124. #
  1125. # @param file Stream.
  1126. # @return Response tuple and target method.
  1127. def parse_response(self, response):
  1128. # read response data from httpresponse, and parse it
  1129. # Check for new http response object, otherwise it is a file object.
  1130. if hasattr(response, 'getheader'):
  1131. if response.getheader("Content-Encoding", "") == "gzip":
  1132. stream = GzipDecodedResponse(response)
  1133. else:
  1134. stream = response
  1135. else:
  1136. stream = response
  1137. p, u = self.getparser()
  1138. while 1:
  1139. data = stream.read(1024)
  1140. if not data:
  1141. break
  1142. if self.verbose:
  1143. print("body:", repr(data))
  1144. p.feed(data)
  1145. if stream is not response:
  1146. stream.close()
  1147. p.close()
  1148. return u.close()
  1149. ##
  1150. # Standard transport class for XML-RPC over HTTPS.
  1151. class SafeTransport(Transport):
  1152. """Handles an HTTPS transaction to an XML-RPC server."""
  1153. def __init__(self, use_datetime=False, use_builtin_types=False,
  1154. *, headers=(), context=None):
  1155. super().__init__(use_datetime=use_datetime,
  1156. use_builtin_types=use_builtin_types,
  1157. headers=headers)
  1158. self.context = context
  1159. # FIXME: mostly untested
  1160. def make_connection(self, host):
  1161. if self._connection and host == self._connection[0]:
  1162. return self._connection[1]
  1163. if not hasattr(http.client, "HTTPSConnection"):
  1164. raise NotImplementedError(
  1165. "your version of http.client doesn't support HTTPS")
  1166. # create a HTTPS connection object from a host descriptor
  1167. # host may be a string, or a (host, x509-dict) tuple
  1168. chost, self._extra_headers, x509 = self.get_host_info(host)
  1169. self._connection = host, http.client.HTTPSConnection(chost,
  1170. None, context=self.context, **(x509 or {}))
  1171. return self._connection[1]
  1172. ##
  1173. # Standard server proxy. This class establishes a virtual connection
  1174. # to an XML-RPC server.
  1175. # <p>
  1176. # This class is available as ServerProxy and Server. New code should
  1177. # use ServerProxy, to avoid confusion.
  1178. #
  1179. # @def ServerProxy(uri, **options)
  1180. # @param uri The connection point on the server.
  1181. # @keyparam transport A transport factory, compatible with the
  1182. # standard transport class.
  1183. # @keyparam encoding The default encoding used for 8-bit strings
  1184. # (default is UTF-8).
  1185. # @keyparam verbose Use a true value to enable debugging output.
  1186. # (printed to standard output).
  1187. # @see Transport
  1188. class ServerProxy:
  1189. """uri [,options] -> a logical connection to an XML-RPC server
  1190. uri is the connection point on the server, given as
  1191. scheme://host/target.
  1192. The standard implementation always supports the "http" scheme. If
  1193. SSL socket support is available (Python 2.0), it also supports
  1194. "https".
  1195. If the target part and the slash preceding it are both omitted,
  1196. "/RPC2" is assumed.
  1197. The following options can be given as keyword arguments:
  1198. transport: a transport factory
  1199. encoding: the request encoding (default is UTF-8)
  1200. All 8-bit strings passed to the server proxy are assumed to use
  1201. the given encoding.
  1202. """
  1203. def __init__(self, uri, transport=None, encoding=None, verbose=False,
  1204. allow_none=False, use_datetime=False, use_builtin_types=False,
  1205. *, headers=(), context=None):
  1206. # establish a "logical" server connection
  1207. # get the url
  1208. p = urllib.parse.urlsplit(uri)
  1209. if p.scheme not in ("http", "https"):
  1210. raise OSError("unsupported XML-RPC protocol")
  1211. self.__host = p.netloc
  1212. self.__handler = urllib.parse.urlunsplit(["", "", *p[2:]])
  1213. if not self.__handler:
  1214. self.__handler = "/RPC2"
  1215. if transport is None:
  1216. if p.scheme == "https":
  1217. handler = SafeTransport
  1218. extra_kwargs = {"context": context}
  1219. else:
  1220. handler = Transport
  1221. extra_kwargs = {}
  1222. transport = handler(use_datetime=use_datetime,
  1223. use_builtin_types=use_builtin_types,
  1224. headers=headers,
  1225. **extra_kwargs)
  1226. self.__transport = transport
  1227. self.__encoding = encoding or 'utf-8'
  1228. self.__verbose = verbose
  1229. self.__allow_none = allow_none
  1230. def __close(self):
  1231. self.__transport.close()
  1232. def __request(self, methodname, params):
  1233. # call a method on the remote server
  1234. request = dumps(params, methodname, encoding=self.__encoding,
  1235. allow_none=self.__allow_none).encode(self.__encoding, 'xmlcharrefreplace')
  1236. response = self.__transport.request(
  1237. self.__host,
  1238. self.__handler,
  1239. request,
  1240. verbose=self.__verbose
  1241. )
  1242. if len(response) == 1:
  1243. response = response[0]
  1244. return response
  1245. def __repr__(self):
  1246. return (
  1247. "<%s for %s%s>" %
  1248. (self.__class__.__name__, self.__host, self.__handler)
  1249. )
  1250. def __getattr__(self, name):
  1251. # magic method dispatcher
  1252. return _Method(self.__request, name)
  1253. # note: to call a remote object with a non-standard name, use
  1254. # result getattr(server, "strange-python-name")(args)
  1255. def __call__(self, attr):
  1256. """A workaround to get special attributes on the ServerProxy
  1257. without interfering with the magic __getattr__
  1258. """
  1259. if attr == "close":
  1260. return self.__close
  1261. elif attr == "transport":
  1262. return self.__transport
  1263. raise AttributeError("Attribute %r not found" % (attr,))
  1264. def __enter__(self):
  1265. return self
  1266. def __exit__(self, *args):
  1267. self.__close()
  1268. # compatibility
  1269. Server = ServerProxy
  1270. # --------------------------------------------------------------------
  1271. # test code
  1272. if __name__ == "__main__":
  1273. # simple test program (from the XML-RPC specification)
  1274. # local server, available from Lib/xmlrpc/server.py
  1275. server = ServerProxy("http://localhost:8000")
  1276. try:
  1277. print(server.currentTime.getCurrentTime())
  1278. except Error as v:
  1279. print("ERROR", v)
  1280. multi = MultiCall(server)
  1281. multi.getData()
  1282. multi.pow(2,9)
  1283. multi.add(1,2)
  1284. try:
  1285. for response in multi():
  1286. print(response)
  1287. except Error as v:
  1288. print("ERROR", v)