blob: 9435015144937826eb83269e88623583fc4fd68e [file] [log] [blame]
Fredrik Lundhb9056332001-07-11 17:42:21 +00001#
2# XML-RPC CLIENT LIBRARY
3# $Id$
4#
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00005# 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:
Martin v. Löwis37af9862004-08-20 07:31:37 +000011# this version is designed to work with Python 2.1 or newer.
Fredrik Lundhc4c062f2001-09-10 19:45:02 +000012#
Fredrik Lundhb9056332001-07-11 17:42:21 +000013# 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)
Fredrik Lundh78eedce2001-08-23 20:04:33 +000027# 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)
Fredrik Lundhc4c062f2001-09-10 19:45:02 +000029# 2001-09-03 fl Allow Transport subclass to override getparser
30# 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup)
Fredrik Lundh1538c232001-10-01 19:42:03 +000031# 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)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000033# 2001-10-02 fl More dumps microtuning
34# 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum)
Skip Montanaro5e9c71b2001-10-10 15:56:34 +000035# 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000036# 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems)
Fredrik Lundhb6ab93f2001-12-19 21:40:04 +000037# 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000038# 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
Fredrik Lundh1303c7c2002-10-22 18:23:00 +000043# 2002-10-22 fl Added basic authentication (based on code from Phillip Eby)
Martin v. Löwis541342f2003-07-12 07:53:04 +000044# 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
Martin v. Löwis45394c22003-10-31 13:49:36 +000050# 2003-10-31 mvl Add multicall support
Martin v. Löwis37af9862004-08-20 07:31:37 +000051# 2004-08-20 mvl Bump minimum supported Python version to 2.1
Benjamin Peterson4e9cefa2014-12-05 20:15:15 -050052# 2014-12-02 ch/doko Add workaround for gzip bomb vulnerability
Fredrik Lundhb9056332001-07-11 17:42:21 +000053#
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000054# Copyright (c) 1999-2002 by Secret Labs AB.
55# Copyright (c) 1999-2002 by Fredrik Lundh.
Fredrik Lundhb9056332001-07-11 17:42:21 +000056#
57# info@pythonware.com
58# http://www.pythonware.com
59#
60# --------------------------------------------------------------------
61# The XML-RPC client interface is
62#
Fredrik Lundh3d9addd2002-06-27 21:36:21 +000063# Copyright (c) 1999-2002 by Secret Labs AB
64# Copyright (c) 1999-2002 by Fredrik Lundh
Fredrik Lundhb9056332001-07-11 17:42:21 +000065#
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
Fred Drake1b410792001-09-04 18:55:03 +000089"""
90An XML-RPC client interface for Python.
91
92The marshalling and response parser code can also be used to
93implement XML-RPC servers.
94
Fred Drake1b410792001-09-04 18:55:03 +000095Exported exceptions:
96
Fredrik Lundhc4c062f2001-09-10 19:45:02 +000097 Error Base class for client errors
98 ProtocolError Indicates an HTTP protocol error
99 ResponseError Indicates a broken response package
100 Fault Indicates an XML-RPC fault package
Fred Drake1b410792001-09-04 18:55:03 +0000101
102Exported classes:
103
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000104 ServerProxy Represents a logical connection to an XML-RPC server
Fred Drake1b410792001-09-04 18:55:03 +0000105
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000106 MultiCall Executor of boxcared xmlrpc requests
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000107 DateTime dateTime wrapper for an ISO 8601 string or time tuple or
108 localtime integer value to generate a "dateTime.iso8601"
109 XML-RPC value
110 Binary binary data wrapper
Fred Drake1b410792001-09-04 18:55:03 +0000111
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000112 Marshaller Generate an XML-RPC params chunk from a Python data structure
113 Unmarshaller Unmarshal an XML-RPC response from incoming XML event message
114 Transport Handles an HTTP transaction to an XML-RPC server
115 SafeTransport Handles an HTTPS transaction to an XML-RPC server
Fred Drake1b410792001-09-04 18:55:03 +0000116
117Exported constants:
118
Florent Xiclunac4fec932011-10-30 20:19:32 +0100119 (none)
Fred Drake1b410792001-09-04 18:55:03 +0000120
121Exported functions:
122
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000123 getparser Create instance of the fastest available parser & attach
124 to an unmarshalling object
125 dumps Convert an argument tuple or a Fault instance to an XML-RPC
126 request (or response, if the methodresponse option is used).
127 loads Convert an XML-RPC packet to unmarshalled data plus a method
128 name (None if not present).
Fred Drake1b410792001-09-04 18:55:03 +0000129"""
130
Florent Xiclunac4fec932011-10-30 20:19:32 +0100131import base64
Florent Xicluna75861df2011-10-30 20:39:24 +0100132import sys
Florent Xiclunac4fec932011-10-30 20:19:32 +0100133import time
Florent Xiclunab6f019a2011-10-30 23:54:17 +0100134from datetime import datetime
Georg Brandl24420152008-05-26 16:32:26 +0000135import http.client
Ezio Melotti91932da2012-02-24 12:44:04 +0200136import urllib.parse
Georg Brandlcef803f2009-06-04 09:04:53 +0000137from xml.parsers import expat
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000138import errno
139from io import BytesIO
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +0000140try:
141 import gzip
Brett Cannoncd171c82013-07-04 17:43:24 -0400142except ImportError:
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +0000143 gzip = None #python can be built without zlib/gzip support
Fredrik Lundh1538c232001-10-01 19:42:03 +0000144
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000145# --------------------------------------------------------------------
146# Internal stuff
147
Neal Norwitzff113342007-04-17 08:42:15 +0000148def escape(s):
149 s = s.replace("&", "&")
150 s = s.replace("<", "&lt;")
151 return s.replace(">", "&gt;",)
Fredrik Lundh1538c232001-10-01 19:42:03 +0000152
Florent Xicluna75861df2011-10-30 20:39:24 +0100153# used in User-Agent header sent
154__version__ = sys.version[:3]
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000155
156# xmlrpc integer limits
Guido van Rossume2a383d2007-01-15 16:59:06 +0000157MAXINT = 2**31-1
158MININT = -2**31
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000159
160# --------------------------------------------------------------------
161# Error constants (from Dan Libby's specification at
162# http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php)
163
164# Ranges of errors
165PARSE_ERROR = -32700
166SERVER_ERROR = -32600
167APPLICATION_ERROR = -32500
168SYSTEM_ERROR = -32400
169TRANSPORT_ERROR = -32300
170
171# Specific errors
172NOT_WELLFORMED_ERROR = -32700
173UNSUPPORTED_ENCODING = -32701
174INVALID_ENCODING_CHAR = -32702
175INVALID_XMLRPC = -32600
176METHOD_NOT_FOUND = -32601
177INVALID_METHOD_PARAMS = -32602
178INTERNAL_ERROR = -32603
Fredrik Lundhb9056332001-07-11 17:42:21 +0000179
180# --------------------------------------------------------------------
181# Exceptions
182
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000183##
184# Base class for all kinds of client-side errors.
185
Fredrik Lundh78eedce2001-08-23 20:04:33 +0000186class Error(Exception):
Fred Drake1b410792001-09-04 18:55:03 +0000187 """Base class for client errors."""
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000188 def __str__(self):
189 return repr(self)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000190
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000191##
192# Indicates an HTTP-level protocol error. This is raised by the HTTP
193# transport layer, if the server returns an error code other than 200
194# (OK).
195#
196# @param url The target URL.
197# @param errcode The HTTP error code.
198# @param errmsg The HTTP error message.
199# @param headers The HTTP header dictionary.
200
Fredrik Lundhb9056332001-07-11 17:42:21 +0000201class ProtocolError(Error):
Fred Drake1b410792001-09-04 18:55:03 +0000202 """Indicates an HTTP protocol error."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000203 def __init__(self, url, errcode, errmsg, headers):
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000204 Error.__init__(self)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000205 self.url = url
206 self.errcode = errcode
207 self.errmsg = errmsg
208 self.headers = headers
209 def __repr__(self):
210 return (
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300211 "<%s for %s: %s %s>" %
212 (self.__class__.__name__, self.url, self.errcode, self.errmsg)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000213 )
214
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000215##
216# Indicates a broken XML-RPC response package. This exception is
217# raised by the unmarshalling layer, if the XML-RPC response is
218# malformed.
219
Fredrik Lundhb9056332001-07-11 17:42:21 +0000220class ResponseError(Error):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000221 """Indicates a broken response package."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000222 pass
223
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000224##
225# Indicates an XML-RPC fault response package. This exception is
226# raised by the unmarshalling layer, if the XML-RPC response contains
Florent Xiclunac4fec932011-10-30 20:19:32 +0100227# a fault string. This exception can also be used as a class, to
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000228# generate a fault XML-RPC message.
229#
230# @param faultCode The XML-RPC fault code.
231# @param faultString The XML-RPC fault string.
232
Fredrik Lundhb9056332001-07-11 17:42:21 +0000233class Fault(Error):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000234 """Indicates an XML-RPC fault package."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000235 def __init__(self, faultCode, faultString, **extra):
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000236 Error.__init__(self)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000237 self.faultCode = faultCode
238 self.faultString = faultString
239 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300240 return "<%s %s: %r>" % (self.__class__.__name__,
241 self.faultCode, self.faultString)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000242
243# --------------------------------------------------------------------
244# Special values
245
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000246##
Georg Brandl38eceaa2008-05-26 11:14:17 +0000247# Backwards compatibility
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000248
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000249boolean = Boolean = bool
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000250
251##
252# Wrapper for XML-RPC DateTime values. This converts a time value to
253# the format used by XML-RPC.
254# <p>
Florent Xicluna2738a642011-11-01 00:06:58 +0100255# The value can be given as a datetime object, as a string in the
256# format "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000257# time.localtime()), or an integer value (as returned by time.time()).
258# The wrapper uses time.localtime() to convert an integer to a time
259# tuple.
260#
Florent Xicluna2738a642011-11-01 00:06:58 +0100261# @param value The time, given as a datetime object, an ISO 8601 string,
262# a time tuple, or an integer time value.
263
264
265# Issue #13305: different format codes across platforms
266_day0 = datetime(1, 1, 1)
267if _day0.strftime('%Y') == '0001': # Mac OS X
268 def _iso8601_format(value):
269 return value.strftime("%Y%m%dT%H:%M:%S")
270elif _day0.strftime('%4Y') == '0001': # Linux
271 def _iso8601_format(value):
272 return value.strftime("%4Y%m%dT%H:%M:%S")
273else:
274 def _iso8601_format(value):
275 return value.strftime("%Y%m%dT%H:%M:%S").zfill(17)
276del _day0
277
Fredrik Lundhb9056332001-07-11 17:42:21 +0000278
Christian Heimesdae2a892008-04-19 00:55:37 +0000279def _strftime(value):
Florent Xiclunab6f019a2011-10-30 23:54:17 +0100280 if isinstance(value, datetime):
Florent Xicluna2738a642011-11-01 00:06:58 +0100281 return _iso8601_format(value)
Christian Heimesdae2a892008-04-19 00:55:37 +0000282
283 if not isinstance(value, (tuple, time.struct_time)):
284 if value == 0:
285 value = time.time()
286 value = time.localtime(value)
287
288 return "%04d%02d%02dT%02d:%02d:%02d" % value[:6]
289
Fredrik Lundhb9056332001-07-11 17:42:21 +0000290class DateTime:
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000291 """DateTime wrapper for an ISO 8601 string or time tuple or
292 localtime integer value to generate 'dateTime.iso8601' XML-RPC
293 value.
294 """
Fredrik Lundhb9056332001-07-11 17:42:21 +0000295
296 def __init__(self, value=0):
Christian Heimesdae2a892008-04-19 00:55:37 +0000297 if isinstance(value, str):
298 self.value = value
299 else:
300 self.value = _strftime(value)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000301
Christian Heimes05e8be12008-02-23 18:30:17 +0000302 def make_comparable(self, other):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000303 if isinstance(other, DateTime):
Christian Heimes05e8be12008-02-23 18:30:17 +0000304 s = self.value
305 o = other.value
Florent Xiclunab6f019a2011-10-30 23:54:17 +0100306 elif isinstance(other, datetime):
Christian Heimes05e8be12008-02-23 18:30:17 +0000307 s = self.value
Florent Xicluna2738a642011-11-01 00:06:58 +0100308 o = _iso8601_format(other)
Florent Xicluna3fa29f72011-10-30 20:18:50 +0100309 elif isinstance(other, str):
Christian Heimes05e8be12008-02-23 18:30:17 +0000310 s = self.value
311 o = other
312 elif hasattr(other, "timetuple"):
313 s = self.timetuple()
314 o = other.timetuple()
315 else:
316 otype = (hasattr(other, "__class__")
317 and other.__class__.__name__
318 or type(other))
319 raise TypeError("Can't compare %s and %s" %
320 (self.__class__.__name__, otype))
321 return s, o
322
323 def __lt__(self, other):
324 s, o = self.make_comparable(other)
325 return s < o
326
327 def __le__(self, other):
328 s, o = self.make_comparable(other)
329 return s <= o
330
331 def __gt__(self, other):
332 s, o = self.make_comparable(other)
333 return s > o
334
335 def __ge__(self, other):
336 s, o = self.make_comparable(other)
337 return s >= o
338
339 def __eq__(self, other):
340 s, o = self.make_comparable(other)
341 return s == o
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000342
343 def __ne__(self, other):
Christian Heimes05e8be12008-02-23 18:30:17 +0000344 s, o = self.make_comparable(other)
345 return s != o
346
347 def timetuple(self):
348 return time.strptime(self.value, "%Y%m%dT%H:%M:%S")
349
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000350 ##
351 # Get date/time value.
352 #
353 # @return Date/time value, as an ISO 8601 string.
354
355 def __str__(self):
356 return self.value
357
Fredrik Lundhb9056332001-07-11 17:42:21 +0000358 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300359 return "<%s %r at %#x>" % (self.__class__.__name__, self.value, id(self))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000360
361 def decode(self, data):
Neal Norwitzff113342007-04-17 08:42:15 +0000362 self.value = str(data).strip()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000363
364 def encode(self, out):
365 out.write("<value><dateTime.iso8601>")
366 out.write(self.value)
367 out.write("</dateTime.iso8601></value>\n")
368
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000369def _datetime(data):
370 # decode xml element contents into a DateTime structure.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000371 value = DateTime()
372 value.decode(data)
373 return value
374
Skip Montanaro174dd222005-05-14 20:54:16 +0000375def _datetime_type(data):
Florent Xiclunab6f019a2011-10-30 23:54:17 +0100376 return datetime.strptime(data, "%Y%m%dT%H:%M:%S")
Skip Montanaro174dd222005-05-14 20:54:16 +0000377
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000378##
379# Wrapper for binary data. This can be used to transport any kind
380# of binary data over XML-RPC, using BASE64 encoding.
381#
382# @param data An 8-bit string containing arbitrary data.
383
Fredrik Lundhb9056332001-07-11 17:42:21 +0000384class Binary:
Fred Drake1b410792001-09-04 18:55:03 +0000385 """Wrapper for binary data."""
Fredrik Lundhb9056332001-07-11 17:42:21 +0000386
387 def __init__(self, data=None):
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000388 if data is None:
389 data = b""
390 else:
Florent Xicluna61665192011-11-15 20:53:25 +0100391 if not isinstance(data, (bytes, bytearray)):
392 raise TypeError("expected bytes or bytearray, not %s" %
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000393 data.__class__.__name__)
394 data = bytes(data) # Make a copy of the bytes!
Fredrik Lundhb9056332001-07-11 17:42:21 +0000395 self.data = data
396
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000397 ##
398 # Get buffer contents.
399 #
400 # @return Buffer contents, as an 8-bit string.
401
402 def __str__(self):
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000403 return str(self.data, "latin-1") # XXX encoding?!
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000404
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000405 def __eq__(self, other):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000406 if isinstance(other, Binary):
407 other = other.data
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000408 return self.data == other
409
410 def __ne__(self, other):
411 if isinstance(other, Binary):
412 other = other.data
413 return self.data != other
Fredrik Lundhb9056332001-07-11 17:42:21 +0000414
415 def decode(self, data):
Georg Brandlb54d8012009-06-04 09:11:51 +0000416 self.data = base64.decodebytes(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000417
418 def encode(self, out):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000419 out.write("<value><base64>\n")
Georg Brandlb54d8012009-06-04 09:11:51 +0000420 encoded = base64.encodebytes(self.data)
Brett Cannon2dbde5e2007-07-30 03:50:35 +0000421 out.write(encoded.decode('ascii'))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000422 out.write("</base64></value>\n")
423
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000424def _binary(data):
425 # decode xml element contents into a Binary structure
Fredrik Lundhb9056332001-07-11 17:42:21 +0000426 value = Binary()
427 value.decode(data)
428 return value
429
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000430WRAPPERS = (DateTime, Binary)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000431
432# --------------------------------------------------------------------
433# XML parsers
434
Georg Brandlcef803f2009-06-04 09:04:53 +0000435class ExpatParser:
436 # fast expat parser for Python 2.0 and later.
437 def __init__(self, target):
438 self._parser = parser = expat.ParserCreate(None, None)
439 self._target = target
440 parser.StartElementHandler = target.start
441 parser.EndElementHandler = target.end
442 parser.CharacterDataHandler = target.data
443 encoding = None
444 target.xml(encoding, None)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000445
Georg Brandlcef803f2009-06-04 09:04:53 +0000446 def feed(self, data):
447 self._parser.Parse(data, 0)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000448
Georg Brandlcef803f2009-06-04 09:04:53 +0000449 def close(self):
450 self._parser.Parse("", 1) # end of data
451 del self._target, self._parser # get rid of circular references
Fredrik Lundhb9056332001-07-11 17:42:21 +0000452
Fredrik Lundhb9056332001-07-11 17:42:21 +0000453# --------------------------------------------------------------------
454# XML-RPC marshalling and unmarshalling code
455
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000456##
457# XML-RPC marshaller.
458#
459# @param encoding Default encoding for 8-bit strings. The default
460# value is None (interpreted as UTF-8).
461# @see dumps
462
Fredrik Lundhb9056332001-07-11 17:42:21 +0000463class Marshaller:
Fred Drake1b410792001-09-04 18:55:03 +0000464 """Generate an XML-RPC params chunk from a Python data structure.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000465
Fredrik Lundhc4c062f2001-09-10 19:45:02 +0000466 Create a Marshaller instance for each set of parameters, and use
467 the "dumps" method to convert your data (represented as a tuple)
468 to an XML-RPC params chunk. To write a fault response, pass a
469 Fault instance instead. You may prefer to use the "dumps" module
470 function for this purpose.
Fred Drake1b410792001-09-04 18:55:03 +0000471 """
Fredrik Lundhb9056332001-07-11 17:42:21 +0000472
473 # by the way, if you don't understand what's going on in here,
474 # that's perfectly ok.
475
Georg Brandlfe991052009-09-16 15:54:04 +0000476 def __init__(self, encoding=None, allow_none=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000477 self.memo = {}
478 self.data = None
479 self.encoding = encoding
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000480 self.allow_none = allow_none
Tim Petersc2659cf2003-05-12 20:19:37 +0000481
Fredrik Lundhb9056332001-07-11 17:42:21 +0000482 dispatch = {}
483
484 def dumps(self, values):
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000485 out = []
486 write = out.append
487 dump = self.__dump
Fredrik Lundhb9056332001-07-11 17:42:21 +0000488 if isinstance(values, Fault):
489 # fault instance
490 write("<fault>\n")
Martin v. Löwis541342f2003-07-12 07:53:04 +0000491 dump({'faultCode': values.faultCode,
492 'faultString': values.faultString},
493 write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000494 write("</fault>\n")
495 else:
496 # parameter block
Fredrik Lundhc266bb02001-08-23 20:13:08 +0000497 # FIXME: the xml-rpc specification allows us to leave out
498 # the entire <params> block if there are no parameters.
499 # however, changing this may break older code (including
500 # old versions of xmlrpclib.py), so this is better left as
501 # is for now. See @XMLRPC3 for more information. /F
Fredrik Lundhb9056332001-07-11 17:42:21 +0000502 write("<params>\n")
503 for v in values:
504 write("<param>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000505 dump(v, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000506 write("</param>\n")
507 write("</params>\n")
Neal Norwitzff113342007-04-17 08:42:15 +0000508 result = "".join(out)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000509 return result
510
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000511 def __dump(self, value, write):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000512 try:
513 f = self.dispatch[type(value)]
514 except KeyError:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000515 # check if this object can be marshalled as a structure
Florent Xicluna93dfee12011-10-30 20:22:25 +0100516 if not hasattr(value, '__dict__'):
Collin Winterce36ad82007-08-30 01:19:48 +0000517 raise TypeError("cannot marshal %s objects" % type(value))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000518 # check if this class is a sub-class of a basic type,
519 # because we don't know how to marshal these types
520 # (e.g. a string sub-class)
521 for type_ in type(value).__mro__:
522 if type_ in self.dispatch.keys():
Collin Winterce36ad82007-08-30 01:19:48 +0000523 raise TypeError("cannot marshal %s objects" % type(value))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000524 # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
525 # for the p3yk merge, this should probably be fixed more neatly.
526 f = self.dispatch["_arbitrary_instance"]
527 f(self, value, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000528
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000529 def dump_nil (self, value, write):
530 if not self.allow_none:
Collin Winterce36ad82007-08-30 01:19:48 +0000531 raise TypeError("cannot marshal None unless allow_none is enabled")
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000532 write("<value><nil/></value>")
Guido van Rossum13257902007-06-07 23:15:56 +0000533 dispatch[type(None)] = dump_nil
Tim Petersc2659cf2003-05-12 20:19:37 +0000534
Georg Brandl38eceaa2008-05-26 11:14:17 +0000535 def dump_bool(self, value, write):
536 write("<value><boolean>")
537 write(value and "1" or "0")
538 write("</boolean></value>\n")
539 dispatch[bool] = dump_bool
Skip Montanaro9a7c96a2003-01-22 18:17:25 +0000540
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000541 def dump_long(self, value, write):
Skip Montanaro5449e082001-10-17 22:53:33 +0000542 if value > MAXINT or value < MININT:
Serhiy Storchaka95949422013-08-27 19:40:23 +0300543 raise OverflowError("int exceeds XML-RPC limits")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000544 write("<value><int>")
545 write(str(int(value)))
546 write("</int></value>\n")
Guido van Rossum13257902007-06-07 23:15:56 +0000547 dispatch[int] = dump_long
Skip Montanaro5e9c71b2001-10-10 15:56:34 +0000548
Florent Xicluna2bb96f52011-10-23 22:11:00 +0200549 # backward compatible
550 dump_int = dump_long
551
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000552 def dump_double(self, value, write):
553 write("<value><double>")
554 write(repr(value))
555 write("</double></value>\n")
Guido van Rossum13257902007-06-07 23:15:56 +0000556 dispatch[float] = dump_double
Fredrik Lundhb9056332001-07-11 17:42:21 +0000557
Guido van Rossum54ad5232007-05-27 09:17:48 +0000558 def dump_unicode(self, value, write, escape=escape):
Guido van Rossum54ad5232007-05-27 09:17:48 +0000559 write("<value><string>")
560 write(escape(value))
561 write("</string></value>\n")
562 dispatch[str] = dump_unicode
Fredrik Lundhb9056332001-07-11 17:42:21 +0000563
Florent Xicluna61665192011-11-15 20:53:25 +0100564 def dump_bytes(self, value, write):
565 write("<value><base64>\n")
566 encoded = base64.encodebytes(value)
567 write(encoded.decode('ascii'))
568 write("</base64></value>\n")
569 dispatch[bytes] = dump_bytes
570 dispatch[bytearray] = dump_bytes
571
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000572 def dump_array(self, value, write):
573 i = id(value)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000574 if i in self.memo:
Collin Winterce36ad82007-08-30 01:19:48 +0000575 raise TypeError("cannot marshal recursive sequences")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000576 self.memo[i] = None
Fredrik Lundh1538c232001-10-01 19:42:03 +0000577 dump = self.__dump
Fredrik Lundhb9056332001-07-11 17:42:21 +0000578 write("<value><array><data>\n")
579 for v in value:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000580 dump(v, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000581 write("</data></array></value>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000582 del self.memo[i]
Guido van Rossum13257902007-06-07 23:15:56 +0000583 dispatch[tuple] = dump_array
584 dispatch[list] = dump_array
Fredrik Lundhb9056332001-07-11 17:42:21 +0000585
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000586 def dump_struct(self, value, write, escape=escape):
587 i = id(value)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000588 if i in self.memo:
Collin Winterce36ad82007-08-30 01:19:48 +0000589 raise TypeError("cannot marshal recursive dictionaries")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000590 self.memo[i] = None
Fredrik Lundh1538c232001-10-01 19:42:03 +0000591 dump = self.__dump
Fredrik Lundhb9056332001-07-11 17:42:21 +0000592 write("<value><struct>\n")
Andrew M. Kuchling5962f452004-06-05 12:35:58 +0000593 for k, v in value.items():
Fredrik Lundhb9056332001-07-11 17:42:21 +0000594 write("<member>\n")
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000595 if not isinstance(k, str):
Collin Winterce36ad82007-08-30 01:19:48 +0000596 raise TypeError("dictionary key must be string")
Fredrik Lundh1538c232001-10-01 19:42:03 +0000597 write("<name>%s</name>\n" % escape(k))
Andrew M. Kuchling5962f452004-06-05 12:35:58 +0000598 dump(v, write)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000599 write("</member>\n")
600 write("</struct></value>\n")
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000601 del self.memo[i]
Guido van Rossum13257902007-06-07 23:15:56 +0000602 dispatch[dict] = dump_struct
Fredrik Lundhb9056332001-07-11 17:42:21 +0000603
Florent Xiclunab6f019a2011-10-30 23:54:17 +0100604 def dump_datetime(self, value, write):
605 write("<value><dateTime.iso8601>")
606 write(_strftime(value))
607 write("</dateTime.iso8601></value>\n")
608 dispatch[datetime] = dump_datetime
Fred Drakeba613c32005-02-10 18:33:30 +0000609
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000610 def dump_instance(self, value, write):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000611 # check for special wrappers
612 if value.__class__ in WRAPPERS:
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000613 self.write = write
Fredrik Lundhb9056332001-07-11 17:42:21 +0000614 value.encode(self)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000615 del self.write
Fredrik Lundhb9056332001-07-11 17:42:21 +0000616 else:
617 # store instance attributes as a struct (really?)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000618 self.dump_struct(value.__dict__, write)
Guido van Rossume4dea982006-04-21 13:45:00 +0000619 dispatch[DateTime] = dump_instance
620 dispatch[Binary] = dump_instance
Thomas Wouters89f507f2006-12-13 04:49:30 +0000621 # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix
622 # for the p3yk merge, this should probably be fixed more neatly.
623 dispatch["_arbitrary_instance"] = dump_instance
Fredrik Lundhb9056332001-07-11 17:42:21 +0000624
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000625##
626# XML-RPC unmarshaller.
627#
628# @see loads
629
Fredrik Lundhb9056332001-07-11 17:42:21 +0000630class Unmarshaller:
Fred Drake1b410792001-09-04 18:55:03 +0000631 """Unmarshal an XML-RPC response, based on incoming XML event
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000632 messages (start, data, end). Call close() to get the resulting
Fred Drake1b410792001-09-04 18:55:03 +0000633 data structure.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000634
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000635 Note that this reader is fairly tolerant, and gladly accepts bogus
636 XML-RPC data without complaining (but not bogus XML).
Fred Drake1b410792001-09-04 18:55:03 +0000637 """
Fredrik Lundhb9056332001-07-11 17:42:21 +0000638
639 # and again, if you don't understand what's going on in here,
640 # that's perfectly ok.
641
Florent Xicluna61665192011-11-15 20:53:25 +0100642 def __init__(self, use_datetime=False, use_builtin_types=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000643 self._type = None
644 self._stack = []
645 self._marks = []
646 self._data = []
647 self._methodname = None
648 self._encoding = "utf-8"
649 self.append = self._stack.append
Florent Xicluna61665192011-11-15 20:53:25 +0100650 self._use_datetime = use_builtin_types or use_datetime
651 self._use_bytes = use_builtin_types
Fredrik Lundhb9056332001-07-11 17:42:21 +0000652
653 def close(self):
654 # return response tuple and target method
655 if self._type is None or self._marks:
656 raise ResponseError()
657 if self._type == "fault":
Guido van Rossum68468eb2003-02-27 20:14:51 +0000658 raise Fault(**self._stack[0])
Fredrik Lundhb9056332001-07-11 17:42:21 +0000659 return tuple(self._stack)
660
661 def getmethodname(self):
662 return self._methodname
663
664 #
665 # event handlers
666
667 def xml(self, encoding, standalone):
668 self._encoding = encoding
669 # FIXME: assert standalone == 1 ???
670
671 def start(self, tag, attrs):
672 # prepare to handle this element
673 if tag == "array" or tag == "struct":
674 self._marks.append(len(self._stack))
675 self._data = []
676 self._value = (tag == "value")
677
678 def data(self, text):
679 self._data.append(text)
680
Neal Norwitzff113342007-04-17 08:42:15 +0000681 def end(self, tag):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000682 # call the appropriate end tag handler
683 try:
684 f = self.dispatch[tag]
685 except KeyError:
686 pass # unknown tag ?
687 else:
Neal Norwitzff113342007-04-17 08:42:15 +0000688 return f(self, "".join(self._data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000689
690 #
691 # accelerator support
692
693 def end_dispatch(self, tag, data):
694 # dispatch data
695 try:
696 f = self.dispatch[tag]
697 except KeyError:
698 pass # unknown tag ?
699 else:
700 return f(self, data)
701
702 #
703 # element decoders
704
705 dispatch = {}
706
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000707 def end_nil (self, data):
708 self.append(None)
709 self._value = 0
710 dispatch["nil"] = end_nil
Tim Petersc2659cf2003-05-12 20:19:37 +0000711
Fredrik Lundh1538c232001-10-01 19:42:03 +0000712 def end_boolean(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000713 if data == "0":
714 self.append(False)
715 elif data == "1":
716 self.append(True)
717 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000718 raise TypeError("bad boolean value")
Fredrik Lundhb9056332001-07-11 17:42:21 +0000719 self._value = 0
720 dispatch["boolean"] = end_boolean
721
Fredrik Lundh1538c232001-10-01 19:42:03 +0000722 def end_int(self, data):
723 self.append(int(data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000724 self._value = 0
725 dispatch["i4"] = end_int
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000726 dispatch["i8"] = end_int
Fredrik Lundhb9056332001-07-11 17:42:21 +0000727 dispatch["int"] = end_int
728
Fredrik Lundh1538c232001-10-01 19:42:03 +0000729 def end_double(self, data):
730 self.append(float(data))
Fredrik Lundhb9056332001-07-11 17:42:21 +0000731 self._value = 0
732 dispatch["double"] = end_double
733
Fredrik Lundh1538c232001-10-01 19:42:03 +0000734 def end_string(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000735 if self._encoding:
Alexandre Vassalottie671fd22009-07-22 02:32:34 +0000736 data = data.decode(self._encoding)
737 self.append(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000738 self._value = 0
739 dispatch["string"] = end_string
740 dispatch["name"] = end_string # struct keys are always strings
741
742 def end_array(self, data):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000743 mark = self._marks.pop()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000744 # map arrays to Python lists
745 self._stack[mark:] = [self._stack[mark:]]
746 self._value = 0
747 dispatch["array"] = end_array
748
749 def end_struct(self, data):
Raymond Hettinger46ac8eb2002-06-30 03:39:14 +0000750 mark = self._marks.pop()
Fredrik Lundhb9056332001-07-11 17:42:21 +0000751 # map structs to Python dictionaries
752 dict = {}
753 items = self._stack[mark:]
754 for i in range(0, len(items), 2):
Alexandre Vassalottie671fd22009-07-22 02:32:34 +0000755 dict[items[i]] = items[i+1]
Fredrik Lundhb9056332001-07-11 17:42:21 +0000756 self._stack[mark:] = [dict]
757 self._value = 0
758 dispatch["struct"] = end_struct
759
Fredrik Lundh1538c232001-10-01 19:42:03 +0000760 def end_base64(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000761 value = Binary()
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000762 value.decode(data.encode("ascii"))
Florent Xicluna61665192011-11-15 20:53:25 +0100763 if self._use_bytes:
764 value = value.data
Fredrik Lundhb9056332001-07-11 17:42:21 +0000765 self.append(value)
766 self._value = 0
767 dispatch["base64"] = end_base64
768
Fredrik Lundh1538c232001-10-01 19:42:03 +0000769 def end_dateTime(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000770 value = DateTime()
Fredrik Lundh1538c232001-10-01 19:42:03 +0000771 value.decode(data)
Skip Montanaro174dd222005-05-14 20:54:16 +0000772 if self._use_datetime:
773 value = _datetime_type(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000774 self.append(value)
775 dispatch["dateTime.iso8601"] = end_dateTime
776
777 def end_value(self, data):
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000778 # if we stumble upon a value element with no internal
Fredrik Lundhb9056332001-07-11 17:42:21 +0000779 # elements, treat it as a string element
780 if self._value:
781 self.end_string(data)
782 dispatch["value"] = end_value
783
784 def end_params(self, data):
785 self._type = "params"
786 dispatch["params"] = end_params
787
788 def end_fault(self, data):
789 self._type = "fault"
790 dispatch["fault"] = end_fault
791
Fredrik Lundh1538c232001-10-01 19:42:03 +0000792 def end_methodName(self, data):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000793 if self._encoding:
Alexandre Vassalottie671fd22009-07-22 02:32:34 +0000794 data = data.decode(self._encoding)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000795 self._methodname = data
796 self._type = "methodName" # no params
797 dispatch["methodName"] = end_methodName
798
Martin v. Löwis45394c22003-10-31 13:49:36 +0000799## Multicall support
800#
Fredrik Lundhb9056332001-07-11 17:42:21 +0000801
Martin v. Löwis45394c22003-10-31 13:49:36 +0000802class _MultiCallMethod:
803 # some lesser magic to store calls made to a MultiCall object
804 # for batch execution
805 def __init__(self, call_list, name):
806 self.__call_list = call_list
807 self.__name = name
808 def __getattr__(self, name):
809 return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name))
810 def __call__(self, *args):
811 self.__call_list.append((self.__name, args))
812
Martin v. Löwis12237b32004-08-22 16:04:50 +0000813class MultiCallIterator:
Martin v. Löwis45394c22003-10-31 13:49:36 +0000814 """Iterates over the results of a multicall. Exceptions are
Andrew Svetlov737fb892012-12-18 21:14:22 +0200815 raised in response to xmlrpc faults."""
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000816
Martin v. Löwis12237b32004-08-22 16:04:50 +0000817 def __init__(self, results):
818 self.results = results
819
820 def __getitem__(self, i):
821 item = self.results[i]
822 if type(item) == type({}):
823 raise Fault(item['faultCode'], item['faultString'])
824 elif type(item) == type([]):
825 return item[0]
Martin v. Löwis45394c22003-10-31 13:49:36 +0000826 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000827 raise ValueError("unexpected type in multicall result")
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000828
Martin v. Löwis45394c22003-10-31 13:49:36 +0000829class MultiCall:
830 """server -> a object used to boxcar method calls
831
832 server should be a ServerProxy object.
833
834 Methods can be added to the MultiCall using normal
835 method call syntax e.g.:
836
837 multicall = MultiCall(server_proxy)
838 multicall.add(2,3)
839 multicall.get_address("Guido")
840
841 To execute the multicall, call the MultiCall object e.g.:
842
843 add_result, address = multicall()
844 """
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000845
Martin v. Löwis45394c22003-10-31 13:49:36 +0000846 def __init__(self, server):
847 self.__server = server
848 self.__call_list = []
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000849
Martin v. Löwis45394c22003-10-31 13:49:36 +0000850 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +0300851 return "<%s at %#x>" % (self.__class__.__name__, id(self))
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000852
Martin v. Löwis45394c22003-10-31 13:49:36 +0000853 __str__ = __repr__
854
855 def __getattr__(self, name):
856 return _MultiCallMethod(self.__call_list, name)
857
858 def __call__(self):
859 marshalled_list = []
860 for name, args in self.__call_list:
861 marshalled_list.append({'methodName' : name, 'params' : args})
862
863 return MultiCallIterator(self.__server.system.multicall(marshalled_list))
Raymond Hettingercc523fc2003-11-02 09:47:05 +0000864
Fredrik Lundhb9056332001-07-11 17:42:21 +0000865# --------------------------------------------------------------------
866# convenience functions
867
Georg Brandl38eceaa2008-05-26 11:14:17 +0000868FastMarshaller = FastParser = FastUnmarshaller = None
869
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000870##
871# Create a parser object, and connect it to an unmarshalling instance.
872# This function picks the fastest available XML parser.
873#
874# return A (parser, unmarshaller) tuple.
875
Florent Xicluna61665192011-11-15 20:53:25 +0100876def getparser(use_datetime=False, use_builtin_types=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000877 """getparser() -> parser, unmarshaller
878
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000879 Create an instance of the fastest available parser, and attach it
880 to an unmarshalling object. Return both objects.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000881 """
882 if FastParser and FastUnmarshaller:
Florent Xicluna61665192011-11-15 20:53:25 +0100883 if use_builtin_types:
Skip Montanaro174dd222005-05-14 20:54:16 +0000884 mkdatetime = _datetime_type
Florent Xicluna61665192011-11-15 20:53:25 +0100885 mkbytes = base64.decodebytes
886 elif use_datetime:
887 mkdatetime = _datetime_type
888 mkbytes = _binary
Skip Montanaro174dd222005-05-14 20:54:16 +0000889 else:
890 mkdatetime = _datetime
Florent Xicluna61665192011-11-15 20:53:25 +0100891 mkbytes = _binary
892 target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000893 parser = FastParser(target)
894 else:
Florent Xicluna61665192011-11-15 20:53:25 +0100895 target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000896 if FastParser:
897 parser = FastParser(target)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000898 else:
Georg Brandlcef803f2009-06-04 09:04:53 +0000899 parser = ExpatParser(target)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000900 return parser, target
901
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000902##
903# Convert a Python tuple or a Fault instance to an XML-RPC packet.
904#
905# @def dumps(params, **options)
906# @param params A tuple or Fault instance.
907# @keyparam methodname If given, create a methodCall request for
908# this method name.
909# @keyparam methodresponse If given, create a methodResponse packet.
910# If used with a tuple, the tuple must be a singleton (that is,
911# it must contain exactly one element).
912# @keyparam encoding The packet encoding.
913# @return A string containing marshalled data.
914
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000915def dumps(params, methodname=None, methodresponse=None, encoding=None,
Georg Brandlfe991052009-09-16 15:54:04 +0000916 allow_none=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000917 """data [,options] -> marshalled data
918
919 Convert an argument tuple or a Fault instance to an XML-RPC
920 request (or response, if the methodresponse option is used).
921
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000922 In addition to the data object, the following options can be given
923 as keyword arguments:
Fredrik Lundhb9056332001-07-11 17:42:21 +0000924
925 methodname: the method name for a methodCall packet
926
927 methodresponse: true to create a methodResponse packet.
928 If this option is used with a tuple, the tuple must be
929 a singleton (i.e. it can contain only one element).
930
931 encoding: the packet encoding (default is UTF-8)
932
Florent Xicluna61665192011-11-15 20:53:25 +0100933 All byte strings in the data structure are assumed to use the
Fredrik Lundhb9056332001-07-11 17:42:21 +0000934 packet encoding. Unicode strings are automatically converted,
Fredrik Lundhb0e8e9b2001-09-10 21:45:42 +0000935 where necessary.
Fredrik Lundhb9056332001-07-11 17:42:21 +0000936 """
937
Guido van Rossum13257902007-06-07 23:15:56 +0000938 assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance"
Fredrik Lundhb9056332001-07-11 17:42:21 +0000939 if isinstance(params, Fault):
940 methodresponse = 1
Guido van Rossum13257902007-06-07 23:15:56 +0000941 elif methodresponse and isinstance(params, tuple):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000942 assert len(params) == 1, "response tuple must be a singleton"
943
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000944 if not encoding:
Fredrik Lundhb9056332001-07-11 17:42:21 +0000945 encoding = "utf-8"
946
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000947 if FastMarshaller:
948 m = FastMarshaller(encoding)
949 else:
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +0000950 m = Marshaller(encoding, allow_none)
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000951
Fredrik Lundhb9056332001-07-11 17:42:21 +0000952 data = m.dumps(params)
953
954 if encoding != "utf-8":
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000955 xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000956 else:
957 xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
958
959 # standard XML-RPC wrappings
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000960 if methodname:
Fredrik Lundhb9056332001-07-11 17:42:21 +0000961 # a method call
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000962 if not isinstance(methodname, str):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000963 methodname = methodname.encode(encoding)
964 data = (
965 xmlheader,
966 "<methodCall>\n"
967 "<methodName>", methodname, "</methodName>\n",
968 data,
969 "</methodCall>\n"
970 )
971 elif methodresponse:
972 # a method response, or a fault structure
973 data = (
974 xmlheader,
975 "<methodResponse>\n",
976 data,
977 "</methodResponse>\n"
978 )
979 else:
980 return data # return as is
Neal Norwitzff113342007-04-17 08:42:15 +0000981 return "".join(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +0000982
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000983##
984# Convert an XML-RPC packet to a Python object. If the XML-RPC packet
985# represents a fault condition, this function raises a Fault exception.
986#
987# @param data An XML-RPC packet, given as an 8-bit string.
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000988# @return A tuple containing the unpacked data, and the method name
Fredrik Lundh3d9addd2002-06-27 21:36:21 +0000989# (None if not present).
990# @see Fault
991
Florent Xicluna61665192011-11-15 20:53:25 +0100992def loads(data, use_datetime=False, use_builtin_types=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +0000993 """data -> unmarshalled data, method name
994
995 Convert an XML-RPC packet to unmarshalled data plus a method
996 name (None if not present).
997
998 If the XML-RPC packet represents a fault condition, this function
999 raises a Fault exception.
1000 """
Florent Xicluna61665192011-11-15 20:53:25 +01001001 p, u = getparser(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001002 p.feed(data)
1003 p.close()
1004 return u.close(), u.getmethodname()
1005
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001006##
1007# Encode a string using the gzip content encoding such as specified by the
1008# Content-Encoding: gzip
1009# in the HTTP header, as described in RFC 1952
1010#
1011# @param data the unencoded data
1012# @return the encoded data
1013
1014def gzip_encode(data):
1015 """data -> gzip encoded data
1016
1017 Encode data using the gzip content encoding as described in RFC 1952
1018 """
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001019 if not gzip:
1020 raise NotImplementedError
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001021 f = BytesIO()
1022 gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
1023 gzf.write(data)
1024 gzf.close()
1025 encoded = f.getvalue()
1026 f.close()
1027 return encoded
1028
1029##
1030# Decode a string using the gzip content encoding such as specified by the
1031# Content-Encoding: gzip
1032# in the HTTP header, as described in RFC 1952
1033#
1034# @param data The encoded data
Benjamin Peterson4e9cefa2014-12-05 20:15:15 -05001035# @keyparam max_decode Maximum bytes to decode (20MB default), use negative
1036# values for unlimited decoding
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001037# @return the unencoded data
1038# @raises ValueError if data is not correctly coded.
Benjamin Peterson4e9cefa2014-12-05 20:15:15 -05001039# @raises ValueError if max gzipped payload length exceeded
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001040
Benjamin Peterson4e9cefa2014-12-05 20:15:15 -05001041def gzip_decode(data, max_decode=20971520):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001042 """gzip encoded data -> unencoded data
1043
1044 Decode data using the gzip content encoding as described in RFC 1952
1045 """
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001046 if not gzip:
1047 raise NotImplementedError
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001048 f = BytesIO(data)
1049 gzf = gzip.GzipFile(mode="rb", fileobj=f)
1050 try:
Benjamin Peterson4e9cefa2014-12-05 20:15:15 -05001051 if max_decode < 0: # no limit
1052 decoded = gzf.read()
1053 else:
1054 decoded = gzf.read(max_decode + 1)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001055 except OSError:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001056 raise ValueError("invalid data")
1057 f.close()
1058 gzf.close()
Benjamin Peterson4e9cefa2014-12-05 20:15:15 -05001059 if max_decode >= 0 and len(decoded) > max_decode:
1060 raise ValueError("max gzipped payload length exceeded")
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001061 return decoded
1062
1063##
1064# Return a decoded file-like object for the gzip encoding
1065# as described in RFC 1952.
1066#
1067# @param response A stream supporting a read() method
1068# @return a file-like object that the decoded data can be read() from
1069
Kristján Valur Jónsson9ab07312009-07-19 22:38:38 +00001070class GzipDecodedResponse(gzip.GzipFile if gzip else object):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001071 """a file-like object to decode a response encoded with the gzip
1072 method, as described in RFC 1952.
1073 """
1074 def __init__(self, response):
1075 #response doesn't support tell() and read(), required by
1076 #GzipFile
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001077 if not gzip:
1078 raise NotImplementedError
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001079 self.io = BytesIO(response.read())
1080 gzip.GzipFile.__init__(self, mode="rb", fileobj=self.io)
1081
1082 def close(self):
1083 gzip.GzipFile.close(self)
1084 self.io.close()
1085
Fredrik Lundhb9056332001-07-11 17:42:21 +00001086
1087# --------------------------------------------------------------------
1088# request dispatcher
1089
1090class _Method:
1091 # some magic to bind an XML-RPC method to an RPC server.
1092 # supports "nested" methods (e.g. examples.getStateName)
1093 def __init__(self, send, name):
1094 self.__send = send
1095 self.__name = name
1096 def __getattr__(self, name):
1097 return _Method(self.__send, "%s.%s" % (self.__name, name))
1098 def __call__(self, *args):
1099 return self.__send(self.__name, args)
1100
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001101##
1102# Standard transport class for XML-RPC over HTTP.
1103# <p>
1104# You can create custom transports by subclassing this method, and
1105# overriding selected methods.
Fredrik Lundhb9056332001-07-11 17:42:21 +00001106
1107class Transport:
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001108 """Handles an HTTP transaction to an XML-RPC server."""
Fredrik Lundhb9056332001-07-11 17:42:21 +00001109
1110 # client identifier (may be overridden)
Florent Xicluna75861df2011-10-30 20:39:24 +01001111 user_agent = "Python-xmlrpc/%s" % __version__
Fredrik Lundhb9056332001-07-11 17:42:21 +00001112
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001113 #if true, we'll request gzip encoding
1114 accept_gzip_encoding = True
1115
1116 # if positive, encode request using gzip if it exceeds this threshold
1117 # note that many server will get confused, so only use it if you know
1118 # that they can decode such a request
1119 encode_threshold = None #None = don't encode
1120
Florent Xicluna61665192011-11-15 20:53:25 +01001121 def __init__(self, use_datetime=False, use_builtin_types=False):
Skip Montanaro174dd222005-05-14 20:54:16 +00001122 self._use_datetime = use_datetime
Florent Xicluna61665192011-11-15 20:53:25 +01001123 self._use_builtin_types = use_builtin_types
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001124 self._connection = (None, None)
1125 self._extra_headers = []
Skip Montanaro174dd222005-05-14 20:54:16 +00001126
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001127 ##
1128 # Send a complete request, and parse the response.
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001129 # Retry request if a cached connection has disconnected.
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001130 #
1131 # @param host Target host.
1132 # @param handler Target PRC handler.
1133 # @param request_body XML-RPC request body.
1134 # @param verbose Debugging flag.
1135 # @return Parsed response.
1136
Georg Brandlfe991052009-09-16 15:54:04 +00001137 def request(self, host, handler, request_body, verbose=False):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001138 #retry request once if cached connection has gone cold
1139 for i in (0, 1):
1140 try:
1141 return self.single_request(host, handler, request_body, verbose)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001142 except OSError as e:
1143 if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED,
1144 errno.EPIPE):
Kristján Valur Jónsson43535d92009-07-03 23:23:50 +00001145 raise
1146 except http.client.BadStatusLine: #close after we sent request
1147 if i:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001148 raise
1149
Georg Brandlfe991052009-09-16 15:54:04 +00001150 def single_request(self, host, handler, request_body, verbose=False):
Fredrik Lundhb9056332001-07-11 17:42:21 +00001151 # issue XML-RPC request
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001152 try:
1153 http_conn = self.send_request(host, handler, request_body, verbose)
1154 resp = http_conn.getresponse()
1155 if resp.status == 200:
1156 self.verbose = verbose
1157 return self.parse_response(resp)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001158
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001159 except Fault:
1160 raise
1161 except Exception:
1162 #All unexpected errors leave connection in
1163 # a strange state, so we clear it.
1164 self.close()
1165 raise
Fredrik Lundhb9056332001-07-11 17:42:21 +00001166
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001167 #We got an error response.
1168 #Discard any response data and raise exception
1169 if resp.getheader("content-length", ""):
1170 resp.read()
1171 raise ProtocolError(
1172 host + handler,
1173 resp.status, resp.reason,
1174 dict(resp.getheaders())
1175 )
Fredrik Lundhb9056332001-07-11 17:42:21 +00001176
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001177
1178 ##
1179 # Create parser.
1180 #
1181 # @return A 2-tuple containing a parser and a unmarshaller.
Fredrik Lundhb9056332001-07-11 17:42:21 +00001182
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001183 def getparser(self):
1184 # get parser and unmarshaller
Florent Xicluna61665192011-11-15 20:53:25 +01001185 return getparser(use_datetime=self._use_datetime,
1186 use_builtin_types=self._use_builtin_types)
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001187
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001188 ##
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001189 # Get authorization info from host parameter
1190 # Host may be a string, or a (host, x509-dict) tuple; if a string,
1191 # it is checked for a "user:pw@host" format, and a "Basic
1192 # Authentication" header is added if appropriate.
1193 #
1194 # @param host Host descriptor (URL or (URL, x509 info) tuple).
1195 # @return A 3-tuple containing (actual host, extra headers,
1196 # x509 info). The header and x509 fields may be None.
1197
1198 def get_host_info(self, host):
1199
1200 x509 = {}
Guido van Rossum13257902007-06-07 23:15:56 +00001201 if isinstance(host, tuple):
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001202 host, x509 = host
1203
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001204 auth, host = urllib.parse.splituser(host)
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001205
1206 if auth:
Georg Brandlc8dcfb62009-02-13 10:50:01 +00001207 auth = urllib.parse.unquote_to_bytes(auth)
Georg Brandlb54d8012009-06-04 09:11:51 +00001208 auth = base64.encodebytes(auth).decode("utf-8")
Neal Norwitzff113342007-04-17 08:42:15 +00001209 auth = "".join(auth.split()) # get rid of whitespace
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001210 extra_headers = [
1211 ("Authorization", "Basic " + auth)
1212 ]
1213 else:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001214 extra_headers = []
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001215
1216 return host, extra_headers, x509
1217
1218 ##
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001219 # Connect to server.
1220 #
1221 # @param host Target host.
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001222 # @return An HTTPConnection object
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001223
Fredrik Lundhb9056332001-07-11 17:42:21 +00001224 def make_connection(self, host):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001225 #return an existing connection if possible. This allows
1226 #HTTP/1.1 keep-alive.
1227 if self._connection and host == self._connection[0]:
1228 return self._connection[1]
Fredrik Lundhb9056332001-07-11 17:42:21 +00001229 # create a HTTP connection object from a host descriptor
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001230 chost, self._extra_headers, x509 = self.get_host_info(host)
1231 self._connection = host, http.client.HTTPConnection(chost)
1232 return self._connection[1]
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001233
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001234 ##
1235 # Clear any cached connection object.
1236 # Used in the event of socket errors.
1237 #
1238 def close(self):
1239 if self._connection[1]:
1240 self._connection[1].close()
1241 self._connection = (None, None)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001242
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001243 ##
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001244 # Send HTTP request.
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001245 #
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001246 # @param host Host descriptor (URL or (URL, x509 info) tuple).
1247 # @param handler Targer RPC handler (a path relative to host)
1248 # @param request_body The XML-RPC request body
1249 # @param debug Enable debugging if debug is true.
1250 # @return An HTTPConnection.
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001251
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001252 def send_request(self, host, handler, request_body, debug):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001253 connection = self.make_connection(host)
1254 headers = self._extra_headers[:]
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001255 if debug:
1256 connection.set_debuglevel(1)
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001257 if self.accept_gzip_encoding and gzip:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001258 connection.putrequest("POST", handler, skip_accept_encoding=True)
1259 headers.append(("Accept-Encoding", "gzip"))
1260 else:
1261 connection.putrequest("POST", handler)
1262 headers.append(("Content-Type", "text/xml"))
1263 headers.append(("User-Agent", self.user_agent))
1264 self.send_headers(connection, headers)
1265 self.send_content(connection, request_body)
Jeremy Hylton5d8a88a2007-08-14 16:47:39 +00001266 return connection
Fredrik Lundhb9056332001-07-11 17:42:21 +00001267
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001268 ##
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001269 # Send request headers.
1270 # This function provides a useful hook for subclassing
1271 #
1272 # @param connection httpConnection.
1273 # @param headers list of key,value pairs for HTTP headers
1274
1275 def send_headers(self, connection, headers):
1276 for key, val in headers:
1277 connection.putheader(key, val)
1278
1279 ##
1280 # Send request body.
1281 # This function provides a useful hook for subclassing
1282 #
1283 # @param connection httpConnection.
1284 # @param request_body XML-RPC request body.
1285
1286 def send_content(self, connection, request_body):
1287 #optionally encode the request
1288 if (self.encode_threshold is not None and
Kristján Valur Jónssonaefde242009-07-19 22:29:24 +00001289 self.encode_threshold < len(request_body) and
1290 gzip):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001291 connection.putheader("Content-Encoding", "gzip")
1292 request_body = gzip_encode(request_body)
1293
1294 connection.putheader("Content-Length", str(len(request_body)))
1295 connection.endheaders(request_body)
1296
1297 ##
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001298 # Parse response.
1299 #
1300 # @param file Stream.
1301 # @return Response tuple and target method.
1302
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001303 def parse_response(self, response):
1304 # read response data from httpresponse, and parse it
Senthil Kumaranf34445f2010-12-08 08:04:49 +00001305 # Check for new http response object, otherwise it is a file object.
1306 if hasattr(response, 'getheader'):
1307 if response.getheader("Content-Encoding", "") == "gzip":
1308 stream = GzipDecodedResponse(response)
1309 else:
1310 stream = response
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001311 else:
1312 stream = response
Fredrik Lundhb9056332001-07-11 17:42:21 +00001313
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001314 p, u = self.getparser()
Fredrik Lundhb9056332001-07-11 17:42:21 +00001315
1316 while 1:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001317 data = stream.read(1024)
1318 if not data:
Fredrik Lundhb9056332001-07-11 17:42:21 +00001319 break
1320 if self.verbose:
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001321 print("body:", repr(data))
1322 p.feed(data)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001323
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001324 if stream is not response:
1325 stream.close()
Fredrik Lundhb9056332001-07-11 17:42:21 +00001326 p.close()
1327
1328 return u.close()
1329
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001330##
1331# Standard transport class for XML-RPC over HTTPS.
1332
Fredrik Lundhb9056332001-07-11 17:42:21 +00001333class SafeTransport(Transport):
Fredrik Lundhc4c062f2001-09-10 19:45:02 +00001334 """Handles an HTTPS transaction to an XML-RPC server."""
Fredrik Lundhb9056332001-07-11 17:42:21 +00001335
Benjamin Petersonc1da3d12014-11-29 23:32:57 -05001336 def __init__(self, use_datetime=False, use_builtin_types=False, *,
1337 context=None):
1338 super().__init__(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
1339 self.context = context
1340
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001341 # FIXME: mostly untested
1342
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001343 def make_connection(self, host):
1344 if self._connection and host == self._connection[0]:
1345 return self._connection[1]
1346
Senthil Kumaran6a0b5c42010-11-18 17:08:48 +00001347 if not hasattr(http.client, "HTTPSConnection"):
Fredrik Lundh1303c7c2002-10-22 18:23:00 +00001348 raise NotImplementedError(
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001349 "your version of http.client doesn't support HTTPS")
1350 # create a HTTPS connection object from a host descriptor
1351 # host may be a string, or a (host, x509-dict) tuple
1352 chost, self._extra_headers, x509 = self.get_host_info(host)
1353 self._connection = host, http.client.HTTPSConnection(chost,
Benjamin Petersonc1da3d12014-11-29 23:32:57 -05001354 None, context=self.context, **(x509 or {}))
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001355 return self._connection[1]
Fredrik Lundhb9056332001-07-11 17:42:21 +00001356
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001357##
1358# Standard server proxy. This class establishes a virtual connection
1359# to an XML-RPC server.
1360# <p>
1361# This class is available as ServerProxy and Server. New code should
1362# use ServerProxy, to avoid confusion.
1363#
1364# @def ServerProxy(uri, **options)
1365# @param uri The connection point on the server.
1366# @keyparam transport A transport factory, compatible with the
1367# standard transport class.
1368# @keyparam encoding The default encoding used for 8-bit strings
1369# (default is UTF-8).
1370# @keyparam verbose Use a true value to enable debugging output.
1371# (printed to standard output).
1372# @see Transport
1373
Fredrik Lundhb9056332001-07-11 17:42:21 +00001374class ServerProxy:
1375 """uri [,options] -> a logical connection to an XML-RPC server
1376
1377 uri is the connection point on the server, given as
1378 scheme://host/target.
1379
1380 The standard implementation always supports the "http" scheme. If
1381 SSL socket support is available (Python 2.0), it also supports
1382 "https".
1383
1384 If the target part and the slash preceding it are both omitted,
1385 "/RPC2" is assumed.
1386
1387 The following options can be given as keyword arguments:
1388
1389 transport: a transport factory
1390 encoding: the request encoding (default is UTF-8)
1391
1392 All 8-bit strings passed to the server proxy are assumed to use
1393 the given encoding.
1394 """
1395
Georg Brandlfe991052009-09-16 15:54:04 +00001396 def __init__(self, uri, transport=None, encoding=None, verbose=False,
Benjamin Petersonc1da3d12014-11-29 23:32:57 -05001397 allow_none=False, use_datetime=False, use_builtin_types=False,
1398 *, context=None):
Fredrik Lundhb9056332001-07-11 17:42:21 +00001399 # establish a "logical" server connection
1400
1401 # get the url
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001402 type, uri = urllib.parse.splittype(uri)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001403 if type not in ("http", "https"):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001404 raise OSError("unsupported XML-RPC protocol")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001405 self.__host, self.__handler = urllib.parse.splithost(uri)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001406 if not self.__handler:
1407 self.__handler = "/RPC2"
1408
1409 if transport is None:
1410 if type == "https":
Florent Xicluna61665192011-11-15 20:53:25 +01001411 handler = SafeTransport
Benjamin Petersonc1da3d12014-11-29 23:32:57 -05001412 extra_kwargs = {"context": context}
Fredrik Lundhb9056332001-07-11 17:42:21 +00001413 else:
Florent Xicluna61665192011-11-15 20:53:25 +01001414 handler = Transport
Benjamin Petersonc1da3d12014-11-29 23:32:57 -05001415 extra_kwargs = {}
Florent Xicluna61665192011-11-15 20:53:25 +01001416 transport = handler(use_datetime=use_datetime,
Benjamin Petersonc1da3d12014-11-29 23:32:57 -05001417 use_builtin_types=use_builtin_types,
1418 **extra_kwargs)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001419 self.__transport = transport
1420
Senthil Kumaranb3af08f2009-04-01 20:20:43 +00001421 self.__encoding = encoding or 'utf-8'
Fredrik Lundhb9056332001-07-11 17:42:21 +00001422 self.__verbose = verbose
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001423 self.__allow_none = allow_none
Tim Petersc2659cf2003-05-12 20:19:37 +00001424
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001425 def __close(self):
1426 self.__transport.close()
1427
Fredrik Lundhb9056332001-07-11 17:42:21 +00001428 def __request(self, methodname, params):
1429 # call a method on the remote server
1430
Andrew M. Kuchlinga4c2b742003-04-25 00:26:51 +00001431 request = dumps(params, methodname, encoding=self.__encoding,
Senthil Kumaranb3af08f2009-04-01 20:20:43 +00001432 allow_none=self.__allow_none).encode(self.__encoding)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001433
1434 response = self.__transport.request(
1435 self.__host,
1436 self.__handler,
1437 request,
1438 verbose=self.__verbose
1439 )
1440
1441 if len(response) == 1:
1442 response = response[0]
1443
1444 return response
1445
1446 def __repr__(self):
1447 return (
Serhiy Storchaka465e60e2014-07-25 23:36:00 +03001448 "<%s for %s%s>" %
1449 (self.__class__.__name__, self.__host, self.__handler)
Fredrik Lundhb9056332001-07-11 17:42:21 +00001450 )
1451
1452 __str__ = __repr__
Raymond Hettingercc523fc2003-11-02 09:47:05 +00001453
Fredrik Lundhb9056332001-07-11 17:42:21 +00001454 def __getattr__(self, name):
1455 # magic method dispatcher
1456 return _Method(self.__request, name)
1457
1458 # note: to call a remote object with an non-standard name, use
1459 # result getattr(server, "strange-python-name")(args)
1460
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001461 def __call__(self, attr):
1462 """A workaround to get special attributes on the ServerProxy
1463 without interfering with the magic __getattr__
1464 """
1465 if attr == "close":
1466 return self.__close
1467 elif attr == "transport":
1468 return self.__transport
1469 raise AttributeError("Attribute %r not found" % (attr,))
1470
Brett Cannon33a40002014-03-21 11:24:40 -04001471 def __enter__(self):
1472 return self
1473
1474 def __exit__(self, *args):
1475 self.__close()
1476
Fredrik Lundh78eedce2001-08-23 20:04:33 +00001477# compatibility
Fredrik Lundh3d9addd2002-06-27 21:36:21 +00001478
Fredrik Lundhb9056332001-07-11 17:42:21 +00001479Server = ServerProxy
1480
1481# --------------------------------------------------------------------
1482# test code
1483
1484if __name__ == "__main__":
1485
1486 # simple test program (from the XML-RPC specification)
1487
Senthil Kumaran939e2db2014-01-12 16:06:58 -08001488 # local server, available from Lib/xmlrpc/server.py
1489 server = ServerProxy("http://localhost:8000")
Fredrik Lundhb9056332001-07-11 17:42:21 +00001490
Fredrik Lundhb9056332001-07-11 17:42:21 +00001491 try:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001492 print(server.currentTime.getCurrentTime())
Guido van Rossumb940e112007-01-10 16:19:56 +00001493 except Error as v:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001494 print("ERROR", v)
Martin v. Löwis12237b32004-08-22 16:04:50 +00001495
1496 multi = MultiCall(server)
Senthil Kumaran939e2db2014-01-12 16:06:58 -08001497 multi.getData()
1498 multi.pow(2,9)
1499 multi.add(1,2)
Martin v. Löwis12237b32004-08-22 16:04:50 +00001500 try:
1501 for response in multi():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001502 print(response)
Guido van Rossumb940e112007-01-10 16:19:56 +00001503 except Error as v:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001504 print("ERROR", v)