client.py 48 KB

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