Exemple #1
0
def test_xml_loads():
    """
    Test the `ipalib.rpc.xml_loads` function.
    """
    f = rpc.xml_loads
    params = (binary_bytes, utf8_bytes, unicode_str, None)
    wrapped = rpc.xml_wrap(params, API_VERSION)

    # Test un-serializing an RPC request:
    data = dumps(wrapped, 'the_method', allow_none=True)
    (p, m) = f(data)
    assert_equal(m, u'the_method')
    assert_equal(p, params)

    # Test un-serializing an RPC response:
    data = dumps((wrapped,), methodresponse=True, allow_none=True)
    (tup, m) = f(data)
    assert m is None
    assert len(tup) == 1
    assert type(tup) is tuple
    assert_equal(tup[0], params)

    # Test un-serializing an RPC response containing a Fault:
    for error in (unicode_str, u'hello'):
        fault = Fault(69, error)
        data = dumps(fault, methodresponse=True, allow_none=True, encoding='UTF-8')
        e = raises(Fault, f, data)
        assert e.faultCode == 69
        assert_equal(e.faultString, error)
        assert type(e.faultString) is unicode
    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 = xmlrpc_client.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 = xmlrpc_client.dumps(response, methodresponse=1)
        except Fault as fault:
            response = xmlrpc_client.dumps(fault)
        except:
            # report exception back to server
            ftb = self.debug and '\n'+str(traceback.format_tb(sys.exc_info()[2])) or ''
            response = xmlrpc_client.dumps(
                xmlrpc_client.Fault(1, "%s:%s%s" % (sys.exc_info()[0], sys.exc_info()[1],ftb))
                )

        return response
Exemple #3
0
    def _marshaled_dispatch(self, data, dispatch_method=None, path=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 preferred means
        of changing method dispatch behavior.
        """

        try:
            params, method = loads(data, use_builtin_types=self.use_builtin_types)

            # 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 = dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding)
        except Fault as fault:
            response = dumps(fault, allow_none=self.allow_none, encoding=self.encoding)
        except:
            # report exception back to server
            exc_type, exc_value, exc_tb = sys.exc_info()
            response = dumps(
                Fault(1, "%s:%s" % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none
            )

        return response.encode(self.encoding)
Exemple #4
0
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 = xmlrpcclient.loads(request.raw_post_data)
        if method != 'pingback.ping':
            raise errors.Error('Unknown method "%s"' % method)
        _handle_pingback(request, root, *args)
        result = xmlrpcclient.dumps(('OK',), methodresponse=True)
    except xmlrpcclient.Fault as fault:
        result = xmlrpcclient.dumps(fault)
    except Exception as e:
        result = xmlrpcclient.dumps(errors.Error(str(e)))
    return http.HttpResponse(result)
Exemple #5
0
    def _marshaled_dispatch(self, data, dispatch_method=None):
        """override SimpleXMLRPCDispatcher._marshaled_dispatch() fault string"""

        try:
            import xmlrpc.client as client
            from xmlrpc.client import Fault
        except ImportError:
            import xmlrpclib as client
            from xmlrpclib import Fault

        params, method = client.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 = client.dumps(response, methodresponse=1)
        except Fault as fault: # breaks 2.5 compatibility
            fault.faultString = print_exc_info()
            response = client.dumps(fault)
        except:
            # report exception back to server
            response = client.dumps(
                client.Fault(1, "\n%s" % print_exc_info())
                )

        return _b(response)
Exemple #6
0
    def _cbRender(self, result, request, responseFailed=None):
        if responseFailed:
            return

        if isinstance(result, Handler):
            result = result.result
        if not isinstance(result, Fault):
            result = (result,)
        try:
            try:
                content = xmlrpclib.dumps(
                    result, methodresponse=True,
                    allow_none=self.allowNone)
            except Exception as e:
                f = Fault(self.FAILURE, "Can't serialize output: %s" % (e,))
                content = xmlrpclib.dumps(f, methodresponse=True,
                                          allow_none=self.allowNone)

            if isinstance(content, unicode):
                content = content.encode('utf8')
            request.setHeader(
                b"content-length", intToBytes(len(content)))
            request.write(content)
        except:
            log.err()
        request.finish()
    def test_bug_1164912(self):
        d = xmlrpclib.DateTime()
        ((new_d,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((d,), methodresponse=True))
        self.assertIsInstance(new_d.value, str)

        # Check that the output of dumps() is still an 8-bit string
        s = xmlrpclib.dumps((new_d,), methodresponse=True)
        self.assertIsInstance(s, str)
Exemple #8
0
def xmlrpc_marshal(value):
    ismethodresponse = not isinstance(value, xmlrpclib.Fault)
    if ismethodresponse:
        if not isinstance(value, tuple):
            value = (value,)
        body = xmlrpclib.dumps(value,  methodresponse=ismethodresponse)
    else:
        body = xmlrpclib.dumps(value)
    return body
Exemple #9
0
 def parse_responses(self, responses):
     try:
         if isinstance(responses[0], xmlrpclib.Fault):
             return xmlrpclib.dumps(responses[0])
     except IndexError:
         pass
     try:
         response_xml = xmlrpclib.dumps(responses, methodresponse=True)
     except TypeError:
         return self.faults.internal_error()
     return response_xml
Exemple #10
0
    def test_dump_encoding(self):
        value = '\u20ac'
        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 = strg.encode('iso-8859-15')
        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)
        strg = strg.encode('iso-8859-15')
        self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
Exemple #11
0
 def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
     try:
         (params, method) = loads(data, use_builtin_types=self.use_builtin_types)
         if dispatch_method is not None:
             response = dispatch_method(method, params)
         else:
             response = self._dispatch(method, params)
         response = (response,)
         response = dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding)
     except Fault as fault:
         response = dumps(fault, allow_none=self.allow_none, encoding=self.encoding)
     except:
         (exc_type, exc_value, exc_tb) = sys.exc_info()
         response = dumps(Fault(1, '%s:%s' % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none)
     return response.encode(self.encoding)
Exemple #12
0
def xmlrpc_handle_exception_int(e):
    if isinstance(e, odoo.exceptions.UserError):
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_WARNING, odoo.tools.ustr(e.value))
    elif isinstance(e, odoo.exceptions.RedirectWarning):
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_WARNING, str(e))
    elif isinstance(e, odoo.exceptions.MissingError):
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_WARNING, str(e))
    elif isinstance (e, odoo.exceptions.AccessError):
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_ACCESS_ERROR, str(e))
    elif isinstance(e, odoo.exceptions.AccessDenied):
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_ACCESS_DENIED, str(e))
    elif isinstance(e, odoo.exceptions.DeferredException):
        info = e.traceback
        # Which one is the best ?
        formatted_info = "".join(traceback.format_exception(*info))
        #formatted_info = odoo.tools.exception_to_unicode(e) + '\n' + info
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_APPLICATION_ERROR, formatted_info)
    else:
        info = sys.exc_info()
        # Which one is the best ?
        formatted_info = "".join(traceback.format_exception(*info))
        #formatted_info = odoo.tools.exception_to_unicode(e) + '\n' + info
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_APPLICATION_ERROR, formatted_info)

    return xmlrpclib.dumps(fault, allow_none=None)
Exemple #13
0
 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 respond(body, encoding='utf-8', allow_none=0):
    from xmlrpc.client import Fault, dumps
    if not isinstance(body, Fault):
        body = (body,)
    _set_response(dumps(body, methodresponse=1,
                        encoding=encoding,
                        allow_none=allow_none))
Exemple #15
0
    def __init__(
        self, path, host, method, user=None, password=None, allowNone=False, args=(), canceller=None, useDateTime=False
    ):
        """
        @param method: The name of the method to call.
        @type method: C{str}

        @param allowNone: allow the use of None values in parameters. It's
            passed to the underlying xmlrpclib implementation. Defaults to
            C{False}.
        @type allowNone: C{bool} or C{NoneType}

        @param args: the arguments to pass to the method.
        @type args: C{tuple}

        @param canceller: A 1-argument callable passed to the deferred as the
            canceller callback.
        @type canceller: callable or C{NoneType}
        """
        self.path, self.host = path, host
        self.user, self.password = user, password
        self.payload = payloadTemplate % (method, xmlrpclib.dumps(args, allow_none=allowNone))
        if isinstance(self.payload, unicode):
            self.payload = self.payload.encode("utf8")
        self.deferred = defer.Deferred(canceller)
        self.useDateTime = useDateTime
Exemple #16
0
    def send_rpc(self, cmd, in_fd, out_fd, *args, **kwargs):
        xml = _xmlrpc_client.dumps(sum(kwargs.items(), args), cmd)
        self._debug_fn(
            "calling ikiwiki procedure `{0}': [{1}]".format(cmd, repr(xml)))
        # ensure that encoded is a str (bytestring in Python 2, Unicode in 3)
        if str is bytes and not isinstance(xml, str):
            encoded = xml.encode('utf8')
        else:
            encoded = xml
        _IkiWikiExtPluginXMLRPCHandler._write(out_fd, encoded)

        self._debug_fn('reading response from ikiwiki...')

        response = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
        if str is bytes and not isinstance(response, str):
            xml = response.encode('utf8')
        else:
            xml = response
        self._debug_fn(
            'read response to procedure {0} from ikiwiki: [{1}]'.format(
                cmd, repr(xml)))
        if xml is None:
            # ikiwiki is going down
            self._debug_fn('ikiwiki is going down, and so are we...')
            raise GoingDown()

        data = _xmlrpc_client.loads(xml)[0][0]
        self._debug_fn(
            'parsed data from response to procedure {0}: [{1}]'.format(
                cmd, repr(data)))
        return data
Exemple #17
0
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
        service = environ['PATH_INFO'][len('/xmlrpc/'):]
        if environ['PATH_INFO'].startswith('/xmlrpc/2/'):
            service = service[len('2/'):]
            string_faultcode = False

        params, method = xmlrpclib.loads(data)
        try:
            result = odoo.http.dispatch_rpc(service, method, params)
            response = xmlrpclib.dumps((result,), methodresponse=1, allow_none=False)
        except Exception as e:
            if string_faultcode:
                response = xmlrpc_handle_exception_string(e)
            else:
                response = xmlrpc_handle_exception_int(e)

        return werkzeug.wrappers.Response(
            response=response,
            mimetype='text/xml',
        )(environ, start_response)
    def test_dump_big_int(self):
        if sys.maxsize > 2 ** 31 - 1:
            self.assertRaises(OverflowError, xmlrpclib.dumps, (int(2 ** 34),))

        xmlrpclib.dumps((xmlrpclib.MAXINT, xmlrpclib.MININT))
        self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MAXINT + 1,))
        self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MININT - 1,))

        def dummy_write(s):
            pass

        m = xmlrpclib.Marshaller()
        m.dump_int(xmlrpclib.MAXINT, dummy_write)
        m.dump_int(xmlrpclib.MININT, dummy_write)
        self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MAXINT + 1, dummy_write)
        self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MININT - 1, dummy_write)
Exemple #19
0
    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_builtin_types set to 1 the unmarshaller would create
        # datetime objects for the 'datetime[123]' keys as well
        dt = datetime.datetime(2005, 2, 10, 11, 41, 23)
        self.assertEqual(dt, xmlrpclib.DateTime('20050210T11:41:23'))
        s = xmlrpclib.dumps((dt,))

        result, m = xmlrpclib.loads(s, use_builtin_types=True)
        (newdt,) = result
        self.assertEqual(newdt, dt)
        self.assertIs(type(newdt), datetime.datetime)
        self.assertIsNone(m)

        result, m = xmlrpclib.loads(s, use_builtin_types=False)
        (newdt,) = result
        self.assertEqual(newdt, dt)
        self.assertIs(type(newdt), xmlrpclib.DateTime)
        self.assertIsNone(m)

        result, m = xmlrpclib.loads(s, use_datetime=True)
        (newdt,) = result
        self.assertEqual(newdt, dt)
        self.assertIs(type(newdt), datetime.datetime)
        self.assertIsNone(m)

        result, m = xmlrpclib.loads(s, use_datetime=False)
        (newdt,) = result
        self.assertEqual(newdt, dt)
        self.assertIs(type(newdt), xmlrpclib.DateTime)
        self.assertIsNone(m)
Exemple #20
0
    def __request(self, method_name, params):
        # call a method on the remote server

        request = xmlrpclib.dumps(params, method_name, encoding=self.__encoding, allow_none=self.__allow_none)
        response = self.__transport.request(self.__host, self.__handler, request, verbose=self.__verbose)
        if len(response) == 1:
            response = response[0]
        return response
Exemple #21
0
 def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
     try:
         response = self.dispatchers[path]._marshaled_dispatch(data, dispatch_method, path)
     except:
         (exc_type, exc_value) = sys.exc_info()[:2]
         response = dumps(Fault(1, '%s:%s' % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none)
         response = response.encode(self.encoding)
     return response
Exemple #22
0
 def test_newstyle_class(self):
     class T(object):
         pass
     t = T()
     t.x = 100
     t.y = "Hello"
     ((t2,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t,)))
     self.assertEqual(t2, t.__dict__)
Exemple #23
0
def xmlrpc_handle_exception_int(e):
    if isinstance(e, odoo.exceptions.UserError):
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_WARNING,
                                odoo.tools.ustr(e.value))
        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
    elif isinstance(e, odoo.exceptions.RedirectWarning):
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_WARNING, str(e))
        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
    elif isinstance(e, odoo.exceptions.MissingError):
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_WARNING, str(e))
        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
    elif isinstance(e, odoo.exceptions.AccessError):
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_ACCESS_ERROR, str(e))
        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
    elif isinstance(e, odoo.exceptions.AccessDenied):
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_ACCESS_DENIED, str(e))
        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
    elif isinstance(e, odoo.exceptions.DeferredException):
        info = e.traceback
        # Which one is the best ?
        formatted_info = "".join(traceback.format_exception(*info))
        #formatted_info = odoo.tools.exception_to_unicode(e) + '\n' + info
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_APPLICATION_ERROR,
                                formatted_info)
        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
    else:
        info = sys.exc_info()
        # Which one is the best ?
        formatted_info = "".join(traceback.format_exception(*info))
        #formatted_info = odoo.tools.exception_to_unicode(e) + '\n' + info
        fault = xmlrpclib.Fault(RPC_FAULT_CODE_APPLICATION_ERROR,
                                formatted_info)
        response = xmlrpclib.dumps(fault, allow_none=None, encoding=None)
    return response
    def _marshaled_dispatch(self, data, dispatch_method=None, path=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 preferred means
        of changing method dispatch behavior.
        """

        try:
            params, method = loads(data,
                                   use_builtin_types=self.use_builtin_types)

            # 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 = dumps(response,
                             methodresponse=1,
                             allow_none=self.allow_none,
                             encoding=self.encoding)
        except Fault as fault:
            response = dumps(fault,
                             allow_none=self.allow_none,
                             encoding=self.encoding)
        except:
            # report exception back to server
            exc_type, exc_value, exc_tb = sys.exc_info()
            try:
                response = dumps(
                    Fault(1, "%s:%s" % (exc_type, exc_value)),
                    encoding=self.encoding,
                    allow_none=self.allow_none,
                )
            finally:
                # Break reference cycle
                exc_type = exc_value = exc_tb = None

        return response.encode(self.encoding, 'xmlcharrefreplace')
    def test_dump_fault(self):
        f = xmlrpclib.Fault(42, "Test Fault")
        s = xmlrpclib.dumps((f,))
        (newf,), m = xmlrpclib.loads(s)
        self.assertEqual(newf, {"faultCode": 42, "faultString": "Test Fault"})
        self.assertEqual(m, None)

        s = xmlrpclib.Marshaller().dumps(f)
        self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
Exemple #26
0
	def prepare(self):
		"""
		Prepare the query, marshall the payload, create binary data and calculate length (size).
		"""
		self.packet = dumps(self.args, methodname=self.method, allow_none=True).encode()
		self.length = len(self.packet)

		if (self.length + 8) > self._client.MAX_REQUEST_SIZE:
			raise TransportException('The prepared query is larger than the maximum request size, we will not send this query!')
Exemple #27
0
    def send(self, params, methodName):
        brequest = dumps(params, methodname=methodName, allow_none=True).encode()
        blength = len(brequest).to_bytes(4, byteorder='little')
        handler = self.handler
        self.handler += 1
        bhandler = handler.to_bytes(4, byteorder='little')

        self.socket.send(blength + bhandler + brequest)
        return handler
Exemple #28
0
    def test_dump_fault(self):
        f = xmlrpclib.Fault(42, 'Test Fault')
        s = xmlrpclib.dumps((f,))
        (newf,), m = xmlrpclib.loads(s)
        self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
        self.assertEqual(m, None)

        s = xmlrpclib.Marshaller().dumps(f)
        self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
Exemple #29
0
    def test_dump_fault(self):
        f = xmlrpclib.Fault(42, 'Test Fault')
        s = xmlrpclib.dumps((f, ))
        (newf, ), m = xmlrpclib.loads(s)
        self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
        self.assertEqual(m, None)

        s = xmlrpclib.Marshaller().dumps(f)
        self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
Exemple #30
0
    def test_newstyle_class(self):
        class T(object):
            pass

        t = T()
        t.x = 100
        t.y = "Hello"
        ((t2, ), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t, )))
        self.assertEqual(t2, t.__dict__)
Exemple #31
0
    def test_datetime_before_1900(self):
        # same as before but with a date before 1900
        dt = datetime.datetime(1,  2, 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'))
Exemple #32
0
    def test_datetime_before_1900(self):
        # same as before but with a date before 1900
        dt = datetime.datetime(1, 2, 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 test_dump_encoding(self):
     value = {'key€¤': 'value€¤'}
     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 = strg.encode('iso-8859-15', 'xmlcharrefreplace')
     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)
     strg = strg.encode('iso-8859-15', 'xmlcharrefreplace')
     self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
     methodname = 'method€¤'
     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 test_dump_big_int(self):
        if sys.maxsize > 2**31 - 1:
            self.assertRaises(OverflowError, xmlrpclib.dumps, (int(2**34), ))
        xmlrpclib.dumps((xmlrpclib.MAXINT, xmlrpclib.MININT))
        self.assertRaises(OverflowError, xmlrpclib.dumps,
                          (xmlrpclib.MAXINT + 1, ))
        self.assertRaises(OverflowError, xmlrpclib.dumps,
                          (xmlrpclib.MININT - 1, ))

        def dummy_write(s):
            pass

        m = xmlrpclib.Marshaller()
        m.dump_int(xmlrpclib.MAXINT, dummy_write)
        m.dump_int(xmlrpclib.MININT, dummy_write)
        self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MAXINT + 1,
                          dummy_write)
        self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MININT - 1,
                          dummy_write)
Exemple #35
0
 def _encode_request(self, method, params=None):
     if isinstance(params, (list, tuple)):
         params = tuple(params)
     else:
         params = self._encode_params(params)
     try:
         return dumps(params, method, encoding='utf-8',
                      allow_none=True).encode('utf-8', 'xmlcharrefreplace')
     except OverflowError as e:
         raise RequestError('ID value exceeds XML-RPC limits')
Exemple #36
0
 async def execute(self, method, *args):
     payload = dumps(args, methodname=method, allow_none=True)
     body = gzip.compress(payload.encode('utf8'))
     try:
         res = await self.loop.run_in_executor(None, self.__request, body)
         data, _ = loads(res.text, use_datetime=True)
         if isinstance(
                 data,
             (tuple, list)) and len(data) > 0 and len(data[0]) > 0:
             if isinstance(data[0][0], dict) and 'faultCode' in data[0][0]:
                 raise DedimaniaFault(faultCode=data[0][0]['faultCode'],
                                      faultString=data[0][0]['faultString'])
             self.retries = 0
             return data[0]
         raise DedimaniaTransportException(
             'Invalid response from dedimania!')
     except (ConnectionError, ReadTimeout) as e:
         raise DedimaniaTransportException(e) from e
     except ConnectTimeout as e:
         raise DedimaniaTransportException(e) from e
     except DedimaniaTransportException:
         # Try to setup new session.
         self.retries += 1
         if self.retries > 5:
             raise DedimaniaTransportException(
                 'Dedimania didn\'t gave the right answer after few retries!'
             )
         self.client = requests.session()
         try:
             await self.authenticate()
             return await self.execute(method, *args)
         except Exception as e:
             logger.error(
                 'XML-RPC Fault retrieved from Dedimania: {}'.format(
                     str(e)))
             handle_exception(e, __name__, 'execute')
             raise DedimaniaTransportException(
                 'Could not retrieve data from dedimania!')
     except DedimaniaFault as e:
         if 'Bad SessionId' in e.faultString:
             try:
                 self.retries += 1
                 if self.retries > 5:
                     raise DedimaniaTransportException(
                         'Max retries reached for reauthenticating with dedimania!'
                     )
                 await self.authenticate()
                 return await self.execute(method, *args)
             except:
                 return
         logger.error('XML-RPC Fault retrieved from Dedimania: {}'.format(
             str(e)))
         handle_exception(e, __name__, 'execute')
         raise DedimaniaTransportException(
             'Could not retrieve data from dedimania!')
def sign(data):
    """Return <data> signed with the default GPG key."""
    msg = dumps((data,), methodresponse = True)
    p = _popen_gpg('--armor', '--sign', '--keyring', '/etc/planetlab/secring.gpg', '--no-default-keyring')
    p.stdin.write(msg)
    p.stdin.close()
    signed_msg = p.stdout.read()
    p.stdout.close()
    p.stderr.close()
    p.wait()
    return signed_msg
Exemple #38
0
 def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
     try:
         response = self.dispatchers[path]._marshaled_dispatch(
             data, dispatch_method, path)
     except:
         exc_type, exc_value = sys.exc_info()[:2]
         response = dumps(Fault(1, '%s:%s' % (exc_type, exc_value)),
                          encoding=self.encoding,
                          allow_none=self.allow_none)
         response = response.encode(self.encoding, 'xmlcharrefreplace')
     return response
Exemple #39
0
 def response(cls, data, request):
     if isinstance(data, TrytonException):
         data = client.Fault(data.code, str(data))
     elif isinstance(data, Exception):
         data = client.Fault(255, str(data))
     else:
         data = (data, )
     return Response(client.dumps(data,
                                  methodresponse=True,
                                  allow_none=True),
                     content_type='text/xml')
Exemple #40
0
    def test_dump_encoding(self):
        value = {'key\u20ac\xa4':
                 '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 = strg.encode('iso-8859-15', 'xmlcharrefreplace')
        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)
        strg = strg.encode('iso-8859-15', 'xmlcharrefreplace')
        self.assertEqual(xmlrpclib.loads(strg)[0][0], value)

        methodname = '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)
Exemple #41
0
 def serialize(self):
     self.__xmlrpc_serialized = True
     if self.uri[-1] != "/":
         self.uri += "/"
         self.path += "/"
     data = xmlrpclib.dumps(self.params, self.method,
                            allow_none=1).encode("utf8")
     self.headers["Content-Type"] = "text/xml; charset=utf-8"
     cl = len(data)
     self.headers["Content-Length"] = cl
     self.set_content_length(cl)
     return data
Exemple #42
0
 def dispatch(self, request, *args, **kwargs):
     rpc_call = loads(request.body.decode('utf-8'))
     rpc_args = rpc_call[0]
     method_name = rpc_call[1]
     try:
         # noinspection PyCallingNonCallable
         src_result = self.methods[method_name](request, rpc_args, *args, **kwargs)
         result = src_result,
     except Exception as e:
         result = Fault(e.__class__.__name__, str(e))
     data = dumps(result, method_name, True)
     return HttpResponse(data, content_type='application/xml+rpc')
Exemple #43
0
def xmlrpc_handle_exception_string(e):
    if isinstance(e, odoo.exceptions.UserError):
        fault = xmlrpclib.Fault('warning -- %s\n\n%s' % (e.name, e.value), '')
        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
    elif isinstance(e, odoo.exceptions.RedirectWarning):
        fault = xmlrpclib.Fault('warning -- Warning\n\n' + str(e), '')
    elif isinstance(e, odoo.exceptions.MissingError):
        fault = xmlrpclib.Fault('warning -- MissingError\n\n' + str(e), '')
        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
    elif isinstance(e, odoo.exceptions.AccessError):
        fault = xmlrpclib.Fault('warning -- AccessError\n\n' + str(e), '')
        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
    elif isinstance(e, odoo.exceptions.AccessDenied):
        fault = xmlrpclib.Fault('AccessDenied', str(e))
        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
    elif isinstance(e, odoo.exceptions.DeferredException):
        info = e.traceback
        formatted_info = "".join(traceback.format_exception(*info))
        fault = xmlrpclib.Fault(odoo.tools.ustr(e), formatted_info)
        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
    #InternalError
    else:
        info = sys.exc_info()
        formatted_info = "".join(traceback.format_exception(*info))
        fault = xmlrpclib.Fault(odoo.tools.exception_to_unicode(e),
                                formatted_info)
        response = xmlrpclib.dumps(fault, allow_none=None, encoding=None)
    return response
Exemple #44
0
 def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
     try:
         response = self.dispatchers[path]._marshaled_dispatch(
             data, dispatch_method, path)
     except BaseException as exc:
         # report low level exception back to server
         # (each dispatcher should have handled their own
         # exceptions)
         response = dumps(Fault(1, "%s:%s" % (type(exc), exc)),
                          encoding=self.encoding,
                          allow_none=self.allow_none)
         response = response.encode(self.encoding, 'xmlcharrefreplace')
     return response
Exemple #45
0
    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, 2, 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'))
Exemple #46
0
 def dispatch(self, request, *args, **kwargs):
     rpc_call = loads(request.body.decode('utf-8'))
     rpc_args = rpc_call[0]
     method_name = rpc_call[1]
     try:
         # noinspection PyCallingNonCallable
         src_result = self.methods[method_name](request, rpc_args, *args,
                                                **kwargs)
         result = src_result,
     except Exception as e:
         result = Fault(e.__class__.__name__, str(e))
     data = dumps(result, method_name, True)
     return HttpResponse(data, content_type='application/xml+rpc')
Exemple #47
0
    def fetch_rpc(self, method_name, args):
        """Call a method in our XML-RPC API, return the response as a dict.

        The Motor-Blog server emulates WordPress's XML-RPC API, which is the
        MetaWeblog API plus WordPress extensions. Motor-Blog emulates only
        enough of the API to support MarsEdit.
        """
        body = xmlrpclib.dumps(args, method_name, allow_none=1)
        api_url = self.reverse_url('api')
        response = self.fetch(api_url, method='POST', body=body)
        self.assertEqual(200, response.code)
        (data, ), _ = xmlrpclib.loads(response.body)
        return data
Exemple #48
0
    def __marshaled_dispatch(self, data, dispatch_method=None):
        params, method = my_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=True)
        except xmlrpclib.Fault:
            fault = sys.exc_info()[1]
            response = xmlrpclib.dumps(fault)
        except:
            # report exception back to server
            response = xmlrpclib.dumps(
                xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)))
            print_debug_exception()

        return response
Exemple #49
0
 def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
     try:
         response = self.dispatchers[path]._marshaled_dispatch(
            data, dispatch_method, path)
     except:
         # report low level exception back to server
         # (each dispatcher should have handled their own
         # exceptions)
         exc_type, exc_value = sys.exc_info()[:2]
         response = dumps(
             Fault(1, "%s:%s" % (exc_type, exc_value)),
             encoding=self.encoding, allow_none=self.allow_none)
         response = response.encode(self.encoding)
     return response
 def test_datetime_before_1900(self):
     dt = datetime.datetime(1, 2, 10, 11, 41, 23)
     self.assertEqual(dt, xmlrpclib.DateTime('00010210T11:41:23'))
     s = xmlrpclib.dumps((dt, ))
     result, m = xmlrpclib.loads(s, use_builtin_types=True)
     newdt, = result
     self.assertEqual(newdt, dt)
     self.assertIs(type(newdt), datetime.datetime)
     self.assertIsNone(m)
     result, m = xmlrpclib.loads(s, use_builtin_types=False)
     newdt, = result
     self.assertEqual(newdt, dt)
     self.assertIs(type(newdt), xmlrpclib.DateTime)
     self.assertIsNone(m)
Exemple #51
0
    def __request(self, method_name, params):
        # call a method on the remote server

        request = xmlrpclib.dumps(params,
                                  method_name,
                                  encoding=self.__encoding,
                                  allow_none=self.__allow_none)
        response = self.__transport.request(self.__host,
                                            self.__handler,
                                            request,
                                            verbose=self.__verbose)
        if len(response) == 1:
            response = response[0]
        return response
Exemple #52
0
 def do_POST(self):
     length = int(self.headers.get("Content-Length"))
     self.rfile.read(length)
     if self.handled:
         self.close_connection = True
         return
     response = xmlrpclib.dumps((5, ), methodresponse=True)
     response = response.encode()
     self.send_response(http.HTTPStatus.OK)
     self.send_header("Content-Length", len(response))
     self.end_headers()
     self.wfile.write(response)
     self.handled = True
     self.close_connection = False
Exemple #53
0
 def dispatch(self, request):
     import_rpc_methods()
     rpc_call = loads(request.body.decode('utf-8'))
     rpc_args = rpc_call[0]
     method_name = rpc_call[1]
     try:
         connection = self.methods[method_name]
         src_result = connection(request, *rpc_args)
         result = src_result,
     except Exception as e:
         logger.exception('Exception in XML RPC call')
         result = Fault(e.__class__.__name__, str(e))
     data = dumps(result, method_name, True)
     return HttpResponse(data, content_type='application/xml+rpc')
Exemple #54
0
 def run_rpc_command(self, params, method):
     response = None
     try:
         xml_request = client.dumps((params, ), method)
         #print(params)
         self.headers['Content-length'] = len(xml_request)
         self.rpcserver.request("POST", "/Air", "", self.headers)
         self.rpcserver.send(xml_request.encode())
         rpc_response = self.rpcserver.getresponse()
         xml_response = rpc_response.read()
         response = client.loads(xml_response)
     except client.Fault as e:
         print("There is an error. FaultError: {}, FaultString: {}".format(
             e.faultCode, e.faultString))
     return response
Exemple #55
0
 def setBody(self, body, title='', is_error=0, bogus_str_search=None):
     if isinstance(body, xmlrpclib.Fault):
         # Convert Fault object to XML-RPC response.
         body = xmlrpclib.dumps(body, methodresponse=1, allow_none=True)
     else:
         # Marshall our body as an XML-RPC response. Strings will be sent
         # strings, integers as integers, etc. We do *not* convert
         # everything to a string first.
         # Previously this had special handling if the response
         # was a Python None. This is now patched in xmlrpclib to
         # allow Nones nested inside data structures too.
         try:
             body = xmlrpclib.dumps((body, ),
                                    methodresponse=1,
                                    allow_none=True)
         except ConflictError:
             raise
         except:
             self.exception()
             return
     # Set our body to the XML-RPC message, and fix our MIME type.
     self._real.setBody(body)
     self._real.setHeader('content-type', 'text/xml')
     return self
Exemple #56
0
    def _cbRender(self, result, request, responseFailed=None):
        if responseFailed:
            return

        if isinstance(result, Handler):
            result = result.result
        if not isinstance(result, Fault):
            result = (result, )
        try:
            try:
                content = xmlrpclib.dumps(result,
                                          methodresponse=True,
                                          allow_none=self.allowNone)
            except Exception as e:
                f = Fault(self.FAILURE, "Can't serialize output: %s" % (e, ))
                content = xmlrpclib.dumps(f,
                                          methodresponse=True,
                                          allow_none=self.allowNone)

            request.setHeader("content-length", str(len(content)))
            request.write(content)
        except:
            log.err()
        request.finish()
Exemple #57
0
    def _marshaled_dispatch(self, data, path=None):
        """
        Override function from SimpleXMLRPCDispatcher to handle coroutines RPC case
        """
        try:
            params, method = loads(data, use_builtin_types=self.use_builtin_types)

            response = yield from self._dispatch(method, params)
            # wrap response in a singleton tuple
            response = (response,)
            response = dumps(response, methodresponse=1,
                             allow_none=self.allow_none, encoding=self.encoding)
        except Fault as fault:
            response = dumps(fault, allow_none=self.allow_none,
                             encoding=self.encoding)
        except:
            # report exception back to server
            exc_type, exc_value, exc_tb = sys.exc_info()
            response = dumps(
                Fault(1, "%s:%s" % (exc_type, exc_value)),
                encoding=self.encoding, allow_none=self.allow_none,
                )

        return response.encode(self.encoding)
 def test_dump_bytes(self):
     sample = b'my dog has fleas'
     self.assertEqual(sample, xmlrpclib.Binary(sample))
     for type_ in (bytes, bytearray, xmlrpclib.Binary):
         value = type_(sample)
         s = xmlrpclib.dumps((value, ))
         result, m = xmlrpclib.loads(s, use_builtin_types=True)
         newvalue, = result
         self.assertEqual(newvalue, sample)
         self.assertIs(type(newvalue), bytes)
         self.assertIsNone(m)
         result, m = xmlrpclib.loads(s, use_builtin_types=False)
         newvalue, = result
         self.assertEqual(newvalue, sample)
         self.assertIs(type(newvalue), xmlrpclib.Binary)
         self.assertIsNone(m)
Exemple #59
0
    def __init__(self, *args, encoding: Optional[str] = None, **kwargs):
        if 'body' not in kwargs and 'params' in kwargs:
            kw = dict((k, kwargs.pop(k)) for k in DUMPS_ARGS if k in kwargs)
            kwargs['body'] = xmlrpclib.dumps(**kw)

        # spec defines that requests must use POST method
        kwargs.setdefault('method', 'POST')

        # xmlrpc query multiples times over the same url
        kwargs.setdefault('dont_filter', True)

        # restore encoding
        if encoding is not None:
            kwargs['encoding'] = encoding

        super().__init__(*args, **kwargs)
        self.headers.setdefault('Content-Type', 'text/xml')
Exemple #60
0
    def handle_rpc(self, in_fd, out_fd):
        self._debug_fn('waiting for procedure calls from ikiwiki...')
        xml = _IkiWikiExtPluginXMLRPCHandler._read(in_fd)
        if xml is None:
            # ikiwiki is going down
            self._debug_fn('ikiwiki is going down, and so are we...')
            raise GoingDown()

        self._debug_fn(
            'received procedure call from ikiwiki: [{0}]'.format(xml))
        params, method = _xmlrpc_client.loads(xml)
        ret = self._dispatcher.dispatch(method, params)
        xml = _xmlrpc_client.dumps((ret, ), methodresponse=True)
        self._debug_fn(
            'sending procedure response to ikiwiki: [{0}]'.format(xml))
        _IkiWikiExtPluginXMLRPCHandler._write(out_fd, xml)
        return ret