def test_xmlrequests(self): data = ( '<?xml version="1.0"?><methodCall><methodName>system.listMethods</methodName><params></params></methodCall>' ) response = self.client.post(self.rpc_path, data, "text/xml") self.assertEqual(response.status_code, 200) xmlrpclib.loads(response.content) # this will throw an exception with bad data
def test_xml_dumps(): """ Test the `ipalib.rpc.xml_dumps` function. """ f = rpc.xml_dumps params = (binary_bytes, utf8_bytes, unicode_str, None) # Test serializing an RPC request: data = f(params, API_VERSION, b'the_method') (p, m) = loads(data) assert_equal(m, u'the_method') assert type(p) is tuple assert rpc.xml_unwrap(p) == params # Test serializing an RPC response: data = f((params,), API_VERSION, methodresponse=True) (tup, m) = loads(data) assert m is None assert len(tup) == 1 assert type(tup) is tuple assert rpc.xml_unwrap(tup[0]) == params # Test serializing an RPC response containing a Fault: fault = Fault(69, unicode_str) data = f(fault, API_VERSION, methodresponse=True) e = raises(Fault, loads, data) assert e.faultCode == 69 assert_equal(e.faultString, unicode_str)
def makedict(xmlnodes): nodelist = [] for node in xmlnodes[0].childNodes: #print job.childNodes newdict = {} for attr in node.childNodes: if not attr.hasChildNodes(): element_data = '' else: element_data = attr.childNodes[0].data # print attr.nodeName, element_data attr_type = attr.getAttribute('type') if attr_type == 'bool': element_data = bool(element_data) elif attr_type == 'int': element_data = int(element_data) elif attr_type == 'float': element_data = float(element_data) elif attr_type == 'dict': attrdict = {} for x,y in xmlrpclib.loads(element_data)[0]: attrdict.update({x:y}) element_data = attrdict elif attr_type == 'list': # load list data using xmlrpc marshalling element_data = list(xmlrpclib.loads(element_data)[0]) newdict.update({attr.nodeName:element_data}) nodelist.append(newdict) return nodelist
def test_kwargs(self): xml = dumps((1, 2), 'kwargstest') ret = self.dispatcher.dispatch(xml) out, name = loads(ret) self.assertFalse(out[0]) ret = self.dispatcher.dispatch(xml, c=1) out, name = loads(ret) self.assertTrue(out[0]) xml = dumps((1,),'requestargtest') ret = self.dispatcher.dispatch(xml, request=True) out, name = loads(ret) self.assertTrue(out[0]) xml = """<?xml version='1.0'?> <methodCall> <methodName>withoutargstest</methodName> <params> </params> </methodCall> """ ret = self.dispatcher.dispatch(xml, request='fakerequest') out, name = loads(ret) self.assertTrue(out[0])
def test_bad_xml_input(self): request = Request.blank("/", method="POST", body="<foo") response = request.get_response(self.app) self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, response.body) try: xmlrpclib.loads(response.body) except xmlrpclib.Fault, e: self.assertEquals(repr(e), "<Fault -32700: 'Not well formed.'>")
def wrap(self, func, *p, **kw): try: try: parms, method = xmlrpclib.loads(request.body) except: parms, method = xmlrpclib.loads(urllib.unquote_plus(request.body)) rpcresponse = xmlrpclib.dumps((func(p[0], *parms),), methodresponse=1) except xmlrpclib.Fault, fault: rpcresponse = xmlrpclib.dumps(fault)
def test_kwargs(self): xml = dumps((1, 2), 'kwargstest') ret = self.dispatcher.dispatch(xml) out, name = loads(ret) self.assertFalse(out[0]) ret = self.dispatcher.dispatch(xml, c=1) out, name = loads(ret) self.assertTrue(out[0])
def test_datetime_before_1900(self): # same as before but with a date before 1900 dt = datetime.datetime(1, 02, 10, 11, 41, 23) s = xmlrpclib.dumps((dt,)) (newdt,), m = xmlrpclib.loads(s, use_datetime=1) self.assertEqual(newdt, dt) self.assertEqual(m, None) (newdt,), m = xmlrpclib.loads(s, use_datetime=0) self.assertEqual(newdt, xmlrpclib.DateTime('00010210T11:41:23'))
def main(argv): output_python=False if argv[0] == '-p': output_python=True argv.pop(0) host, methodname = argv[:2] respxml = do_scgi_xmlrpc_request(host, methodname, convert_params_to_native(argv[2:])) if not output_python: print respxml else: print xmlrpclib.loads(respxml)[0][0]
def test_dump_bare_date(self): # This checks that an unwrapped datetime.date object can be handled # by the marshalling code. This can't be done via test_dump_load() # since the unmarshaller produces a datetime object d = datetime.datetime(2005, 02, 10, 11, 41, 23).date() s = xmlrpclib.dumps((d,)) (newd,), m = xmlrpclib.loads(s, use_datetime=1) self.assertEquals(newd.date(), d) self.assertEquals(newd.time(), datetime.time(0, 0, 0)) self.assertEquals(m, None) (newdt,), m = xmlrpclib.loads(s, use_datetime=0) self.assertEquals(newdt, xmlrpclib.DateTime('20050210T00:00:00'))
def render_POST(self, request): request.content.seek(0, 0) request.setHeader("content-type", "text/xml") try: if self.useDateTime: args, functionPath = xmlrpclib.loads(request.content.read(), use_datetime=True) else: # Maintain backwards compatibility with Python < 2.5 args, functionPath = xmlrpclib.loads(request.content.read()) except Exception, e: f = Fault(self.FAILURE, "Can't deserialize input: %s" % (e,)) self._cbRender(f, request)
def test_dump_bare_datetime(self): # This checks that an unwrapped datetime.date object can be handled # by the marshalling code. This can't be done via test_dump_load() # since with use_datetime set to 1 the unmarshaller would create # datetime objects for the 'datetime[123]' keys as well dt = datetime.datetime(2005, 02, 10, 11, 41, 23) s = xmlrpclib.dumps((dt,)) (newdt,), m = xmlrpclib.loads(s, use_datetime=1) self.assertEqual(newdt, dt) self.assertEqual(m, None) (newdt,), m = xmlrpclib.loads(s, use_datetime=0) self.assertEqual(newdt, xmlrpclib.DateTime('20050210T11:41:23'))
def test_dump_bare_time(self): # This checks that an unwrapped datetime.time object can be handled # by the marshalling code. This can't be done via test_dump_load() # since the unmarshaller produces a datetime object t = datetime.datetime(2005, 02, 10, 11, 41, 23).time() s = xmlrpclib.dumps((t,)) (newt,), m = xmlrpclib.loads(s, use_datetime=1) today = datetime.datetime.now().date().strftime("%Y%m%d") self.assertEquals(newt.time(), t) self.assertEquals(newt.date(), datetime.datetime.now().date()) self.assertEquals(m, None) (newdt,), m = xmlrpclib.loads(s, use_datetime=0) self.assertEquals(newdt, xmlrpclib.DateTime('%sT11:41:23'%today))
def test_it_with_invalid_body(self): config = self.config config.include('pyramid_rpc.xmlrpc') config.add_xmlrpc_endpoint('rpc', '/api/xmlrpc') app = config.make_wsgi_app() app = TestApp(app) resp = app.post('/api/xmlrpc', content_type='text/xml', params='<') try: xmlrpclib.loads(resp.body) except xmlrpclib.Fault: exc = sys.exc_info()[1] # 2.5 compat self.assertEqual(exc.faultCode, -32700) else: # pragma: no cover raise AssertionError
def xmlrpc(): if request.method == 'GET': return render_template('xmlrpc-methods.html', methods = current_app.wl_server_methods) raw_data = request.get_data() params, method_name = xmlrpclib.loads(raw_data) if method_name.startswith('Util.'): method_name = method_name[len('Util.'):] if method_name not in current_app.wl_server_methods: return xmlrpclib.dumps(xmlrpclib.Fault("Method not found", "Method not found")) try: if method_name == 'test_me': result = params[0] else: method = getattr(current_app.wl_server_instance, 'do_%s' % method_name) result = method(*params) except: exc_type, exc_instance, _ = sys.exc_info() remote_exc_type = _get_type_name(exc_type) fault = xmlrpclib.Fault(remote_exc_type, repr(exc_instance.args)) log.error(__name__, 'Error on %s' % method_name) log.error_exc(__name__) return xmlrpclib.dumps(fault) return xmlrpclib.dumps( (result,))
def continue_request (self, data, request): params, method = xmlrpclib.loads (data) try: # generate response try: response = self.call (method, params) #if type(response) == type(()): response = (response,) except: # report exception back to server response = xmlrpclib.dumps ( xmlrpclib.Fault (1, "%s:%s" % (sys.exc_type, sys.exc_value)) ) else: response = xmlrpclib.dumps (response, methodresponse=1) except: import traceback traceback.print_exc() # internal error, report as HTTP server error request.error (500) else: # got a valid XML RPC response request['Content-Type'] = 'text/xml' request.push (response) request.done()
def do_POST(self): """ Access point from HTTP handler """ def onParent(pid, fromchild, tochild): self._server._registerChild(pid, fromchild) tochild.write("done\n") tochild.flush() def onChild(pid, fromparent, toparent): try: response = self._server._marshaled_dispatch(data) self._sendResponse(response) line = fromparent.readline() toparent.write("done\n") toparent.flush() except: logger(name="pathos.xmlrpc", level=30).error(print_exc_info()) os._exit(0) try: data = self.rfile.read(int(self.headers["content-length"])) params, method = xmlrpclib.loads(data) if method == "run": return spawn2(onParent, onChild) else: response = self._server._marshaled_dispatch(data) self._sendResponse(response) return except: self._debug.error(print_exc_info()) self.send_response(500) self.end_headers() return
def test_encode(self): for type, val in self._data: try: v = xrpcrequest._encoder[type](val) A = [xrpcrequest._values_start, xrpcrequest._values_head%{'name':'pvx','type':42,'count':43}, xrpcrequest._sample_head%{'stat':1, 'sevr':2, 'secs':3, 'nano':4}, xrpcrequest._sample_start, v, xrpcrequest._sample_foot, xrpcrequest._values_foot, xrpcrequest._values_end, ] A = ''.join(A) X = loads(A)[0][0] self.assertEqual(X, [{'count': 43, 'meta': {'alarm_high': 0.0, 'alarm_low': 0.0, 'disp_high': 0.0, 'disp_low': 0.0, 'prec': 0, 'type': 1, 'units': '', 'warn_high': 0.0, 'warn_low': 0.0}, 'name': 'pvx', 'type': 42, 'values': [{'nano': 4, 'secs': 3, 'sevr': 2, 'stat': 1, 'value': [val]}], }]) except: print 'Error in',type,val raise
def render(self, request): """ override method of xmlrpc python twisted framework @param request: raw request xmlrpc @type request: xml str @return: interpreted request """ args, functionPath = xmlrpclib.loads(request.content.read()) s = request.getSession() try: s.loggedin except AttributeError: s.loggedin = False # Set session expire timeout s.sessionTimeout = self.config.sessiontimeout # Check authorization using HTTP Basic cleartext_token = self.config.login + ":" + self.config.password token = request.getUser() + ":" + request.getPassword() if token != cleartext_token: logger.error("Invalid login / password for HTTP basic authentication") request.setResponseCode(http.UNAUTHORIZED) self._cbRender( xmlrpc.Fault(http.UNAUTHORIZED, "Unauthorized: invalid credentials to connect to the MMC agent, basic HTTP authentication is required"), request ) return server.NOT_DONE_YET if not s.loggedin: logger.debug("RPC method call from unauthenticated user: %s" % functionPath + str(args)) # Save the first sent HTTP headers, as they contain some # informations s.http_headers = request.received_headers.copy() else: logger.debug("RPC method call from user %s: %s" % (s.userid, functionPath + str(args))) try: if not s.loggedin and self._needAuth(functionPath): msg = "Authentication needed: %s" % functionPath logger.error(msg) raise Fault(8003, msg) else: if not s.loggedin and not self._needAuth(functionPath): # Provide a security context when a method which doesn't # require a user authentication is called s = request.getSession() s.userid = 'root' try: self._associateContext(request, s, s.userid) except Exception, e: s.loggedin = False logger.exception(e) f = Fault(8004, "MMC agent can't provide a security context") self._cbRender(f, request) return server.NOT_DONE_YET function = self._getFunction(functionPath, request) except Fault, f: self._cbRender(f, request)
def render(self, request): request.content.seek(0, 0) args, functionPath = xmlrpclib.loads(request.content.read()) try: function = self._getFunction(functionPath) except Fault, f: self._cbRender(f, request)
def xml_loads(data, encoding='UTF-8'): """ Decode the XML-RPC packet in ``data``, transparently unwrapping its params. This function will decode the XML-RPC packet in ``data`` using ``xmlrpclib.loads()`` (from the Python standard library). If ``data`` contains a fault, ``xmlrpclib.loads()`` will itself raise an ``xmlrpclib.Fault`` exception. Assuming an exception is not raised, this function will then unwrap the params in ``data`` using `xml_unwrap()`. Finally, a ``(params, methodname)`` tuple is returned containing the unwrapped params and the name of the method being called. If the packet contains no method name, ``methodname`` will be ``None``. For documentation on the ``xmlrpclib.loads()`` function, see: http://docs.python.org/library/xmlrpclib.html#convenience-functions Also see `xml_dumps()`. :param data: The XML-RPC packet to decode. """ try: (params, method) = loads(data) return (xml_unwrap(params), method) except Fault, e: raise decode_fault(e)
def decode(self): data = self.get_data().lstrip("URI:http://") if data: dict = xmlrpclib.loads(data)[0][0] else: dict = {} self.lifeTime = dict.get("lifeTime", None) self.delegate = dict.get("delegate", None) privStr = dict.get("privileges", None) if privStr: self.privileges = Rights(string=privStr) else: self.privileges = None gidCallerStr = dict.get("gidCaller", None) if gidCallerStr: self.gidCaller = GID(string=gidCallerStr) else: self.gidCaller = None gidObjectStr = dict.get("gidObject", None) if gidObjectStr: self.gidObject = GID(string=gidObjectStr) else: self.gidObject = None
def _marshaled_dispatch(self, data, dispatch_method = None): """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the prefered means of changing method dispatch behavior. """ params, method = xmlrpclib.loads(data) # generate response try: if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=1) except Fault, fault: response = xmlrpclib.dumps(fault)
def test_dump_none(self): value = alist + [None] arg1 = (alist + [None],) strg = xmlrpclib.dumps(arg1, allow_none=True) self.assertEqual(value, xmlrpclib.loads(strg)[0][0]) self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,))
def render(self, request): """This is a modified version of render() from XMLRPC that will pass keyword arguments with extra state information if it can. Currently this just consists of the current request. """ request.content.seek(0, 0) args, functionPath = xmlrpclib.loads(request.content.read()) try: function = self._getFunction(functionPath) except xmlrpc.NoSuchFunction: self._cbRender( xmlrpc.Fault(self.NOT_FOUND, "no such function %s" % functionPath), request ) else: request.setHeader("content-type", "text/xml") # Pass as many keyword args to the function as we can. # Note that this currently doesn't work on protected functions. kwargs = {} try: if 'request' in function.func_code.co_varnames: kwargs['request'] = request except AttributeError: pass defer.maybeDeferred(function, *args, **kwargs).addErrback( self._ebRender ).addCallback( self._cbRender, request ) return server.NOT_DONE_YET
def parse(self): if len(sys.argv) <> 2: util.SMlog("Failed to parse commandline; wrong number of arguments; argv = %s" % (repr(sys.argv))) raise xs_errors.XenError('BadRequest') # Debug logging of the actual incoming command from the caller. # util.SMlog( "" ) # util.SMlog( "SM.parse: DEBUG: args = %s,\n%s" % \ # ( sys.argv[0], \ # util.splitXmlText( util.hideMemberValuesInXmlParams( \ # sys.argv[1] ), showContd=True ) ), \ # priority=syslog.LOG_DEBUG ) try: params, methodname = xmlrpclib.loads(sys.argv[1]) self.cmd = methodname params = params[0] # expect a single struct self.params = params # params is a dictionary self.dconf = params['device_config'] if params.has_key('sr_uuid'): self.sr_uuid = params['sr_uuid'] if params.has_key('vdi_uuid'): self.vdi_uuid = params['vdi_uuid'] elif self.cmd == "vdi_create": self.vdi_uuid = util.gen_uuid () except Exception, e: util.SMlog("Failed to parse commandline; exception = %s argv = %s" % (str(e), repr(sys.argv))) raise xs_errors.XenError('BadRequest')
def test_dump_encoding(self): value = {test_support.u(r'key\u20ac\xa4'): test_support.u(r'value\u20ac\xa4')} strg = xmlrpclib.dumps((value,), encoding='iso-8859-15') strg = "<?xml version='1.0' encoding='iso-8859-15'?>" + strg self.assertEqual(xmlrpclib.loads(strg)[0][0], value) strg = xmlrpclib.dumps((value,), encoding='iso-8859-15', methodresponse=True) self.assertEqual(xmlrpclib.loads(strg)[0][0], value) methodname = test_support.u(r'method\u20ac\xa4') strg = xmlrpclib.dumps((value,), encoding='iso-8859-15', methodname=methodname) self.assertEqual(xmlrpclib.loads(strg)[0][0], value) self.assertEqual(xmlrpclib.loads(strg)[1], methodname)
def __call__(self, *args): # ~ print "%s%r"%(self.methodname, args) scheme, netloc, path, query, frag = urlparse.urlsplit(self.url) xmlreq = xmlrpclib.dumps(args, self.methodname) if scheme == "scgi": xmlresp = SCGIRequest(self.url).send(xmlreq).replace("<i8>", "<i4>").replace("</i8>", "</i4>") return xmlrpclib.loads(xmlresp)[0][0] # ~ return do_scgi_xmlrpc_request_py(self.url, self.methodname, args) elif scheme == "http": raise Exception("Unsupported protocol") elif scheme == "": xmlresp = SCGIRequest(self.url).send(xmlreq).replace("<i8>", "<i4>").replace("</i8>", "</i4>") return xmlrpclib.loads(xmlresp)[0][0] # raise Exception('Unsupported protocol') else: raise Exception("Unsupported protocol")
def _marshaled_dispatch(self, data, dispatch_method=None): """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the prefered means of changing method dispatch behavior. """ try: params, method = xmlrpclib.loads(data) # generate response if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except Exception: # report exception back to server exc_type, exc_value, exc_tb = sys.exc_info() response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none, ) return response
def make_api_call(uri, method, args=None, headers=None, http_headers=None, timeout=None, verbose=False): if args is None: args = tuple() try: largs = list(args) largs.insert(0, {'headers': headers}) payload = xmlrpclib.dumps(tuple(largs), methodname=method, allow_none=True) response = requests.post(uri, data=payload, headers=http_headers, timeout=timeout) response.raise_for_status() result = xmlrpclib.loads(response.content,)[0][0] return result except xmlrpclib.Fault, e: # These exceptions are formed from the XML-RPC spec # http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php error_mapping = { '-32700': NotWellFormed, '-32701': UnsupportedEncoding, '-32702': InvalidCharacter, '-32600': SpecViolation, '-32601': MethodNotFound, '-32602': InvalidMethodParameters, '-32603': InternalError, '-32500': ApplicationError, '-32400': RemoteSystemError, '-32300': TransportError, } raise error_mapping.get(e.faultCode, SoftLayerAPIError)( e.faultCode, e.faultString)
def importDbSettingsFromXML(self, node): """ """ version = node.getAttribute('version') if version: self.plomino_version = version child = node.firstChild while child is not None: name = child.nodeName if name == 'acl': anonymousaccessright = child.getAttribute( 'AnomynousAccessRight') self.AnomynousAccessRight = anonymousaccessright self.setPlominoPermissions("Anonymous", anonymousaccessright) authenticatedaccessright = child.getAttribute( 'AuthenticatedAccessRight') self.AuthenticatedAccessRight = authenticatedaccessright self.setPlominoPermissions("Authenticated", authenticatedaccessright) subchild = child.firstChild while subchild is not None: if subchild.nodeType == subchild.ELEMENT_NODE: result, method = xmlrpclib.loads(subchild.toxml()) object_type = subchild.getAttribute('id') if object_type == "SpecificRights": self.specific_rights = result[0] else: self.UserRoles = result[0] subchild = subchild.nextSibling else: if child.hasChildNodes(): field = self.Schema().getField(name) #field.set(self, child.firstChild.data) result = field.widget.process_form( self, field, {name: child.firstChild.data}) field.set(self, result[0]) child = child.nextSibling
def continue_request(self, data, request): params, method = xmlrpclib.loads(data) try: # generate response try: response = self.call(method, params) if type(response) != type(()): response = (response, ) except: # report exception back to server response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value))) else: response = xmlrpclib.dumps(response, methodresponse=1) except: # internal error, report as HTTP server error request.error(500) else: # got a valid XML RPC response request['Content-Type'] = 'text/xml' request.push(response) request.done()
def handle(self, source, data, method_map): """ Handle an XML-RPC or SOAP request from the specified source. """ # Parse request into method name and arguments try: interface = xmlrpclib self.protocol = 'xmlrpclib' (args, method) = xmlrpclib.loads(data) if method_map.has_key(method): method = method_map[method] methodresponse = True except Exception, e: if SOAPpy is not None: self.protocol = 'soap' interface = SOAPpy (r, header, body, attrs) = parseSOAPRPC(data, header = 1, body = 1, attrs = 1) method = r._name args = r._aslist() # XXX Support named arguments else: raise e
def roundtrip(data): """ Make sure the given data survives a marshal/unmarshal roundtrip >>> roundtrip((1,)) >>> roundtrip((1L,)) >>> roundtrip(("1",)) >>> roundtrip(([], [])) >>> roundtrip(((), ())) # @XMLRPC11 ([], []) >>> roundtrip(({"one": 1, "two": 2},)) >>> roundtrip(({},)) >>> roundtrip((xmlrpclib.DateTime(0), xmlrpclib.True, xmlrpclib.False)) >>> roundtrip((xmlrpclib.Binary("data"),)) >>> roundtrip(xmlrpclib.Fault(100, "cans of spam")) Traceback (most recent call last): Fault: <Fault 100: 'cans of spam'> >>> roundtrip(("hello", xmlrpclib.Binary("test"), 1, 2.0, [3, 4, 5])) """ body = xmlrpclib.dumps(data) result = xmlrpclib.loads(body)[0] if result != data: print result
def xmlrpc(request, func): """xmlrpc(request:Request, func:callable) : string Processes the body of an XML-RPC request, and calls 'func' with two arguments, a string containing the method name and a tuple of parameters. """ # Get contents of POST body if request.get_method() != 'POST': request.response.set_status(405, "Only the POST method is accepted") return "XML-RPC handlers only accept the POST method." length = int(request.environ['CONTENT_LENGTH']) data = request.stdin.read(length) # Parse arguments params, method = xmlrpclib.loads(data) try: result = func(method, params) except xmlrpclib.Fault, exc: result = exc
def wsgi_xmlrpc(environ, start_response): """ WSGI handler to return the versions.""" if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'].startswith(XML_RPC_PATH): length = int(environ['CONTENT_LENGTH']) data = environ['wsgi.input'].read(length) params, method = xmlrpclib.loads(data) path = environ['PATH_INFO'][len(XML_RPC_PATH):] if path.startswith('/'): path = path[1:] if path.endswith('/'): path = path[:-1] path = path.split('/') # All routes are hard-coded. if len(path) == 1 and path[0] == '' and method in ('version',): return xmlrpc_return(start_response, 'common', method, ()) # The body has been read, need to raise an exception (not return None). fault = xmlrpclib.Fault(RPC_FAULT_CODE_CLIENT_ERROR, '') response = xmlrpclib.dumps(fault, allow_none=None, encoding=None) start_response("200 OK", [('Content-Type','text/xml'), ('Content-Length', str(len(response)))]) return [response]
def recv(rfile): # Compute the size of an unsigned int n = struct.calcsize("L") # Read the first bytes to figure out the size buff = readSocket(rfile, n) if len(buff) != n: # Incomplete read raise CommunicationError( 0, "Expected %d bytes; got only %d" % (n, len(buff))) n, = struct.unpack("!L", buff) if n > 65536: # The buffer to be read is too big raise CommunicationError(1, "Block too big: %s" % len(buff)) buff = readSocket(rfile, n) if len(buff) != n: # Incomplete read raise CommunicationError( 0, "Expected %d bytes; got only %d" % (n, len(buff))) return loads(buff)
def wsgi_xmlrpc(environ, start_response): """ Two routes are available for XML-RPC /xmlrpc/<service> route returns faultCode as strings. This is a historic violation of the protocol kept for compatibility. /xmlrpc/2/<service> is a new route that returns faultCode as int and is therefore fully compliant. """ if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'].startswith('/xmlrpc/'): length = int(environ['CONTENT_LENGTH']) data = environ['wsgi.input'].read(length) # Distinguish betweed the 2 faultCode modes string_faultcode = True if environ['PATH_INFO'].startswith('/xmlrpc/2/'): service = environ['PATH_INFO'][len('/xmlrpc/2/'):] string_faultcode = False else: service = environ['PATH_INFO'][len('/xmlrpc/'):] params, method = xmlrpclib.loads(data) return xmlrpc_return(start_response, service, method, params, string_faultcode)
def loadFile(self, path): if self.midiSettings.IsShown(): self.midiSettings.Hide() self.panel.removeAllFxBalls() f = open(path, 'r') msg = f.read() f.close() result, method = xmlrpclib.loads(msg) dict = result[0] if 'new_soundgrain_file.sg' in path: self.currentFile = None self.currentPath = None title = '%s %s - ' % (NAME, SG_VERSION) self.status.SetStatusText("") else: self.currentFile = path self.currentPath = os.path.split(path)[0] title = '%s %s - %s' % (NAME, SG_VERSION, os.path.split(self.currentFile)[1]) self.panel.trajectories = [Trajectory(self.panel, i+1) for i in range(MAX_STREAMS)] self.panel.memorizedTrajectory = Trajectory(self.panel, -1) self.panel.memorizedId = {} self.controls.setSelected(0) self.setState(dict) self.SetTitle(title) self.panel.needBitmap = True size = self.GetSize() if size[0] > self.screen_size[0]: x = self.screen_size[0] - 50 else: x = size[0] if size[1] > self.screen_size[1]: y = self.screen_size[1] - 50 else: y = size[1] size = (x, y) wx.CallAfter(self.panel.Refresh) wx.CallLater(100, self.SetSize, size)
def _marshaled_dispatch(self, data, dispatch_method=None): """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the prefered means of changing method dispatch behavior. """ try: params, method = xmlrpclib.loads(data) # generate response if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response, ) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except Exception: # report exception back to server exc_type, exc_value, exc_tb = sys.exc_info() response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none, ) return response
def get_method_name(self, raw_post_data, request_format='xml'): ''' Gets the name of the method to be called given the post data and the format of the data ''' if request_format == 'xml': # xmlrpclib.loads could throw an exception, but this is fine # since _marshaled_dispatch would throw the same thing try: params, method = xmlrpclib.loads(raw_post_data) return method except Exception: return None else: try: # attempt to do a json decode on the data jsondict = json.loads(raw_post_data) if not isinstance(jsondict, dict) or 'method' not in jsondict: return None else: return jsondict['method'] except ValueError: return None
def server_view(request, root='/'): ''' Server view handling pingback requests. Include this view in your urlconf under any path you like and provide a link to this URL in your HTML: <link rel="pingback" href="..."/> Or send it in an HTTP server header: X-Pingback: ... The optional parameter "root" sets a root path within which server will consider incoming target URLs as its own. ''' try: args, method = xmlrpclib.loads(request.raw_post_data) if method != 'pingback.ping': raise errors.Error('Unknown method "%s"' % method) _handle_pingback(request, root, *args) result = xmlrpclib.dumps(('OK',), methodresponse=True) except xmlrpclib.Fault, fault: result = xmlrpclib.dumps(fault)
def getEnrolledClassesFromWebService(self): please_choose = "Please Choose" enrolledClasses = [] enrolledClasses.append(please_choose) # # emplid = self._computeStudentEmplid() # # strm = self.setDefaultPsterm() emplid = '0115341' strm = '0655' if strm == "error: no semester code found matching current date": logger.error('No current semester') return [' '] value = webService.getEnrolledClassesCX(emplid, strm) retlist = xmlrpclib.loads(value) try: for row in retlist[0]: subjects = row[0] catalognumber = row[1] sectionnumber = row[3] courseName = row[2] facultyFirstName = row[5] facultyLastName = row[6] instructorID1 = row[7] rowString = '%s - %s - %s - %s - %s %s - %s' % ( subjects, catalognumber, sectionnumber, courseName, facultyFirstName, facultyLastName, instructorID1) enrolledClasses.append(rowString) except: logger.error( 'No enrolled classes were returned by the web service') enrolledClasses.append( '*** Error: no enrolled classes were returned by the web service ***' ) return enrolledClasses
def _marshaled_dispatch(self, data, dispatch_method=None, path=None): try: params, method = xmlrpclib.loads(data) if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) response = (response, ) response = xmlrpclib.dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except Fault as fault: response = xmlrpclib.dumps(fault, allow_none=self.allow_none, encoding=self.encoding) except: exc_type, exc_value = sys.exc_info()[:2] response = xmlrpclib.dumps(xmlrpclib.Fault( 1, '%s:%s' % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none) return response
def _handler(self, req): log_debug(3, "Method", req.method) # Read all the request data = req.read() log_debug(7, "Received", data) # Decode the data try: params, methodname = xmlrpclib.loads(data) except: raise log_debug(5, params, methodname) try: f = self.get_function(methodname, req) except FunctionRetrievalError: e = sys.exc_info()[1] Traceback(methodname, req) return self._send_xmlrpc(req, rhnFault(3008, str(e), explain=0)) if len(params) < 2: params = [] else: params = params[1:] result = f(*params) if result: # Error of some sort return self._send_xmlrpc(req, rhnFault(3009)) # Presumably the function did all the sending log_debug(4, "Exiting OK") return apache.OK
def do_POST(self): try: # get arguments data = self.rfile.read(int(self.headers["content-length"])) params, method = xmlrpclib.loads(data) # generate response try: response = self.call(method, params) if type(response) != type(()): response = (response,) except: # report exception back to server response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)) ) else: response = xmlrpclib.dumps( response, methodresponse=1 ) except: # internal error, report as HTTP server error self.send_response(500) self.end_headers() else: # got a valid XML RPC response self.send_response(200) self.send_header("Content-type", "text/xml") self.send_header("Content-length", str(len(response))) self.end_headers() self.wfile.write(response) # shut down the connection (from Skip Montanaro) self.wfile.flush() self.connection.shutdown(1)
def flex_participant_destroy(): parameters = { 'authenticationUser': username, 'authenticationPassword': password, 'participantID': participantId } params = tuple([parameters]) xmlrpccall = xmlrpclib.dumps(params, 'flex.participant.destroy', encoding='UTF-8') response = requests.request( 'POST', url, data=xmlrpccall, headers={'Content-Type': 'application/xml'}, timeout=100, stream=False, ) if response.status_code == 200: result = xmlrpclib.loads(response.content, )[0] print result else: print '(flex.participant.destroy) Error' return -1
def conference_enumerate(): parameters = { 'activeFilter': False, 'authenticationUser': username, 'authenticationPassword': password } params = tuple([parameters]) xmlrpccall = xmlrpclib.dumps(params, 'conference.enumerate', encoding='UTF-8') response = requests.request( 'POST', url, data=xmlrpccall, headers={'Content-Type': 'application/xml'}, timeout=100, stream=False, ) if response.status_code == 200: result = xmlrpclib.loads(response.content, )[0] print result else: print '(conference.enumerate) Error' return -1
def test_multicall(self): self.d.register_method(self.add) class Request: content_type = 'text/xml' request = Request marshalled_list = [ { 'methodName': 'add', 'params': (1, 2) }, { 'methodName': 'add', 'params': (2, 3) }, ] xml = dumps((marshalled_list, ), 'system.multicall') ret = self.d.xmldispatch(xml.encode('utf-8'), request=request) out, name = loads(ret) self.assertEqual(out[0][0][0], 3) self.assertEqual(out[0][1][0], 5) request.content_type = 'json' call = { 'method': 'system.multicall', 'params': [marshalled_list], 'id': 1 } jsontxt = json.dumps(call) resp = self.d.jsondispatch(jsontxt.encode('utf-8'), request=request) jsondict = json.loads(resp) self.assertEqual(jsondict['result'][0], 3) self.assertEqual(jsondict['result'][1], 5)
def render(self, request): """ Overridden 'render' method which takes care of HTTP basic authorization """ if self._auth: cleartext_token = self._user + ':' + self._password user = request.getUser() passwd = request.getPassword() if user == '' and passwd == '': request.setResponseCode(http.UNAUTHORIZED) return 'Authorization required!' else: token = user + ':' + passwd if token != cleartext_token: request.setResponseCode(http.UNAUTHORIZED) return 'Authorization Failed!' request.content.seek(0, 0) args, functionPath = xmlrpclib.loads(request.content.read()) try: function = self._getFunction(functionPath) except xmlrpc.NoSuchFunction, f: self._cbRender(f, request)
def decode(self): data = self.get_data('subjectAltName') dict = {} if data: if data.lower().startswith('uri:http://<params>'): dict = xmlrpclib.loads(data[11:])[0][0] else: spl = data.split(', ') for val in spl: if val.lower().startswith('uri:urn:uuid:'): dict['uuid'] = uuid.UUID(val[4:]).int elif val.lower().startswith('uri:urn:publicid:idn+'): dict['urn'] = val[4:] elif val.lower().startswith('email:'): # FIXME: Ensure there isn't cruft in that address... # EG look for email:copy,.... dict['email'] = val[6:] self.uuid = dict.get("uuid", None) self.urn = dict.get("urn", None) self.hrn = dict.get("hrn", None) self.email = dict.get("email", None) if self.urn: self.hrn = urn_to_hrn(self.urn)[0]
def log_xmlrpc_request(remote_addr, user_agent, data): if conf.xmlrpc_request_log_file: try: with open(conf.xmlrpc_request_log_file, 'a') as f: params, method = xmlrpclib.loads(data) dogstatsd.increment('xmlrpc.request', tags=['method:{}'.format(method)]) record = json.dumps({ 'timestamp': datetime.datetime.utcnow().isoformat(), 'remote_addr': remote_addr, 'user_agent': user_agent, 'method': method, 'params': params, 'type': 'request', }) f.write(record + '\n') except Exception: pass
def render(self, request): """ override method of xmlrpc python twisted framework @param request: raw request xmlrpc @type request: xml str @return: interpreted request """ args, functionPath = xmlrpclib.loads(request.content.read()) function = getattr(self, "xmlrpc_%s"%(functionPath)) request.setHeader("content-type", "text/xml") start = time.time() def _printExecutionTime(start): self.logger.debug("Execution time: %f" % (time.time() - start)) def _cbRender(result, start, request, functionPath = None, args = None): _printExecutionTime(start) s = request.getSession() if result == None: result = 0 if isinstance(result, xmlrpc.Handler): result = result.result if not isinstance(result, Fault): result = (result,) try: self.logger.debug('Result for ' + str(functionPath) + ": " + str(result)) s = xmlrpclib.dumps(result, methodresponse=1) except Exception, e: f = Fault(self.FAILURE, "can't serialize output: " + str(e)) s = xmlrpclib.dumps(f, methodresponse=1) request.setHeader("content-length", str(len(s))) request.write(s) request.finish()
def do_POST(self): # Simplified version of SimpleXMLRPCRequestHandler.do_POST l = int(self.headers["Content-Length"]) request_txt = self.rfile.read(l) params, func = xmlrpclib.loads(request_txt) if self.path not in peers: self.send_response(404) self.end_headers() return self.send_response(200) self.end_headers() peer = peers[self.path] try: if not hasattr(peer, func): raise "No such method" result = getattr(peer, func)(*params) response = xmlrpclib.dumps((result, )) except: exc_type, exc_value, exc_tb = sys.exc_info() response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)), ) # need to call a function with (*params) self.wfile.write(response)
def test_no_pvs(self): A = xrpcrequest._values_start + xrpcrequest._values_end X = loads(A)[0][0] self.assertEqual(X, [])
def test_dump_load(self): self.assertEqual(alist, xmlrpclib.loads(xmlrpclib.dumps((alist,)))[0][0])
""" # We need to add the domain if it is missing if pci_device.count(':') == 1: pci_device = "0000:" + pci_device output = _run_command(["ls", "/sys/bus/pci/devices/" + pci_device + "/"]) if "physfn" in output: return "type-VF" if "virtfn" in output: return "type-PF" return "type-PCI" if __name__ == "__main__": # Support both serialized and non-serialized plugin approaches _, methodname = xmlrpclib.loads(sys.argv[1]) if methodname in ['query_gc', 'get_pci_device_details', 'get_pci_type', 'network_config']: utils.register_plugin_calls(query_gc, get_pci_device_details, get_pci_type, network_config) XenAPIPlugin.dispatch( {"host_data": host_data, "set_host_enabled": set_host_enabled, "host_shutdown": host_shutdown, "host_reboot": host_reboot, "host_start": host_start, "host_join": host_join, "get_config": get_config,
def getRpcRequest(self): length = int(self.headers.get("Content-Length", None)) args, method = xmlrpclib.loads(self.rfile.read(length)) args, kwargs = self.server.getParameters(args) return (method, args, kwargs)
d = self.proxy.callRemote('defer', {'a': self.value}) d.addCallback(self.assertEquals, {'a': self.value}) return d class XMLRPCAllowNoneTestCase(SerializationConfigMixin, unittest.TestCase): """ Tests for passing C{None} when the C{allowNone} flag is set. """ flagName = "allowNone" value = None try: xmlrpclib.loads(xmlrpclib.dumps(({}, {})), use_datetime=True) except TypeError: _datetimeSupported = False else: _datetimeSupported = True class XMLRPCUseDateTimeTestCase(SerializationConfigMixin, unittest.TestCase): """ Tests for passing a C{datetime.datetime} instance when the C{useDateTime} flag is set. """ flagName = "useDateTime" value = datetime.datetime(2000, 12, 28, 3, 45, 59)
def call_api(self, api_method, method_params=None): """Makes an api call. Args: api_method: The name of the method called in the api. method_params: A dict of parameters added to the request. Returns: The api response body parsed as a dict. Raises: Exception: Api method must not be None. Exception: Invalid ApiType. """ if api_method is None: raise Exception('Api method must not be None.') if method_params is None: method_params = {} if self.customer: method_params['subuser'] = self.customer if self.client_transaction_id is not None: method_params['clTRID'] = self.client_transaction_id if self.api_type == ApiType.XML_RPC: if sys.version_info.major == 3: payload = xmlrpc.client.dumps( (method_params, ), api_method, encoding='UTF-8').replace('\n', '') else: payload = xmlrpclib.dumps((method_params, ), api_method, encoding='UTF-8').replace('\n', '') elif self.api_type == ApiType.JSON_RPC: payload = str( json.dumps({ 'method': api_method, 'params': method_params })) else: raise Exception('Invalid ApiType.') headers = { 'Content-Type': 'text/xml; charset=UTF-8', 'User-Agent': 'DomRobot/' + ApiClient.CLIENT_VERSION + ' (Python ' + self.get_python_version() + ')' } response = self.api_session.post(self.api_url + self.api_type, data=payload.encode('UTF-8'), headers=headers) response.raise_for_status() if self.debug_mode: print('Request (' + api_method + '): ' + payload) print('Response (' + api_method + '): ' + response.text) if self.api_type == ApiType.XML_RPC: if sys.version_info.major == 3: return xmlrpc.client.loads(response.text)[0][0] else: return xmlrpclib.loads(response.text)[0][0] elif self.api_type == ApiType.JSON_RPC: return response.json()