Beispiel #1
0
    def captured_headers(self):
        """
        Captures the request headers. Yields the {header : value} dictionary,
        where keys are in lower case.
        """
        # Redirect the standard output, to catch jsonrpclib verbose messages
        stdout = sys.stdout
        sys.stdout = f = StringIO()
        headers = {}
        yield headers
        sys.stdout = stdout

        # Extract the sent request content
        request_lines = f.getvalue().splitlines()
        request_lines = list(filter(lambda l: l.startswith("send:"),
                                    request_lines))
        request_line = request_lines[0].split("send: ") [-1]

        # Convert it to a string
        try:
            # Use eval to convert the representation into a string
            request_line = from_bytes(eval(request_line))
        except:
            # Keep the received version
            pass

        # Extract headers
        raw_headers = request_line.splitlines()[1:-1]
        raw_headers = map(lambda h: re.split(":\s?", h, 1), raw_headers)
        for header, value in raw_headers:
            headers[header.lower()] = value
Beispiel #2
0
    def captured_headers(self):
        """
        Captures the request headers. Yields the {header : value} dictionary,
        where keys are in lower case.
        """
        # Redirect the standard output, to catch jsonrpclib verbose messages
        stdout = sys.stdout
        sys.stdout = f = StringIO()
        headers = {}
        yield headers
        sys.stdout = stdout

        # Extract the sent request content
        request_lines = f.getvalue().splitlines()
        request_lines = list(
            filter(lambda l: l.startswith("send:"), request_lines))
        request_line = request_lines[0].split("send: ")[-1]

        # Convert it to a string
        try:
            # Use eval to convert the representation into a string
            request_line = from_bytes(eval(request_line))
        except:
            # Keep the received version
            pass

        # Extract headers
        raw_headers = request_line.splitlines()[1:-1]
        raw_headers = map(lambda h: re.split(r":\s?", h, 1), raw_headers)
        for header, value in raw_headers:
            headers[header.lower()] = value
    def do_POST(self):
        """
        Handles POST requests
        """
        if not self.is_rpc_path_valid():
            self.report_404()
            return

        # Retrieve the configuration
        config = getattr(self.server, 'json_config', jsonrpclib.config.DEFAULT)

        try:
            # Read the request body
            max_chunk_size = 10 * 1024 * 1024
            size_remaining = int(self.headers["content-length"])
            chunks = []
            while size_remaining:
                chunk_size = min(size_remaining, max_chunk_size)
                chunks.append(utils.from_bytes(self.rfile.read(chunk_size)))
                size_remaining -= len(chunks[-1])
            data = ''.join(chunks)

            # Execute the method
            response = self.server._marshaled_dispatch(data)

            # No exception: send a 200 OK
            self.send_response(200)

        except:
            # Exception: send 500 Server Error
            self.send_response(500)
            err_lines = traceback.format_exc().splitlines()
            trace_string = '{0} | {1}'.format(err_lines[-3], err_lines[-1])
            fault = jsonrpclib.Fault(-32603,
                                     'Server error: {0}'.format(trace_string),
                                     config=config)
            response = fault.response()

        if response is None:
            # Avoid to send None
            response = ''

        # Convert the response to the valid string format
        response = utils.to_bytes(response)

        # Send it
        self.send_header("Content-type", config.content_type)
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        self.wfile.write(response)
        self.wfile.flush()
        self.connection.shutdown(1)
    def do_POST(self):
        """
        Handles POST requests
        """
        if not self.is_rpc_path_valid():
            self.report_404()
            return

        # Retrieve the configuration
        config = getattr(self.server, 'json_config', jsonrpclib.config.DEFAULT)

        try:
            # Read the request body
            max_chunk_size = 10 * 1024 * 1024
            size_remaining = int(self.headers["content-length"])
            chunks = []
            while size_remaining:
                chunk_size = min(size_remaining, max_chunk_size)
                chunks.append(utils.from_bytes(self.rfile.read(chunk_size)))
                size_remaining -= len(chunks[-1])
            data = ''.join(chunks)

            # Execute the method
            response = self.server._marshaled_dispatch(data)

            # No exception: send a 200 OK
            self.send_response(200)

        except:
            # Exception: send 500 Server Error
            self.send_response(500)
            err_lines = traceback.format_exc().splitlines()
            trace_string = '{0} | {1}'.format(err_lines[-3], err_lines[-1])
            fault = jsonrpclib.Fault(-32603, 'Server error: {0}'
                                     .format(trace_string), config=config)
            response = fault.response()

        if response is None:
            # Avoid to send None
            response = ''

        # Convert the response to the valid string format
        response = utils.to_bytes(response)

        # Send it
        self.send_header("Content-type", config.content_type)
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        self.wfile.write(response)
        self.wfile.flush()
        self.connection.shutdown(1)
Beispiel #5
0
    def close(self):
        if not self.data:
            return ''

        else:
            data = type(self.data[0])().join(self.data)
            try:
                # Convert the whole final string
                data = utils.from_bytes(data)
            except:
                # Try a pass-through
                pass

            return data
Beispiel #6
0
    def close(self):
        """
        Unmarshalls the buffered data
        """
        if not self.data:
            return ''
        else:
            # Use type to have a valid join (str vs. bytes)
            data = type(self.data[0])().join(self.data)
            try:
                # Convert the whole final string
                data = utils.from_bytes(data)
            except:
                # Try a pass-through
                pass

            return data
Beispiel #7
0
    def close(self):
        """
        Unmarshalls the buffered data
        """
        if not self.data:
            return ''
        else:
            # Use type to have a valid join (str vs. bytes)
            data = type(self.data[0])().join(self.data)
            try:
                # Convert the whole final string
                data = utils.from_bytes(data)
            except:
                # Try a pass-through
                pass

            return data
Beispiel #8
0
    def captured_headers(self, check_duplicates=True):
        """
        Captures the request headers. Yields the {header : value} dictionary,
        where keys are in lower case.

        :param check_duplicates: If True, raises an error if a header appears
                                 twice
        """
        # Redirect the standard output, to catch jsonrpclib verbose messages
        stdout = sys.stdout
        sys.stdout = f = StringIO()
        headers = {}
        yield headers
        sys.stdout = stdout

        # Extract the sent request content
        request_lines = f.getvalue().splitlines()
        request_lines = list(
            filter(lambda l: l.startswith("send:"), request_lines))
        request_line = request_lines[0].split("send: ")[-1]

        # Convert it to a string
        try:
            # Use eval to convert the representation into a string
            request_line = from_bytes(eval(request_line))
        except:
            # Keep the received version
            pass

        # Extract headers
        raw_headers = request_line.splitlines()[1:-1]
        raw_headers = map(lambda h: re.split(r":\s?", h, 1), raw_headers)
        for header, value in raw_headers:
            header = header.lower()
            if check_duplicates and header in headers:
                raise KeyError("Header defined twice: {0}".format(header))
            headers[header] = value
Beispiel #9
0
    def captured_headers(self, check_duplicates=True):
        """
        Captures the request headers. Yields the {header : value} dictionary,
        where keys are in lower case.

        :param check_duplicates: If True, raises an error if a header appears
                                 twice
        """
        # Redirect the standard output, to catch jsonrpclib verbose messages
        stdout = sys.stdout
        sys.stdout = f = StringIO()
        headers = {}
        yield headers
        sys.stdout = stdout

        # Extract the sent request content
        request_lines = f.getvalue().splitlines()
        request_lines = list(filter(lambda l: l.startswith("send:"),
                                    request_lines))
        request_line = request_lines[0].split("send: ")[-1]

        # Convert it to a string
        try:
            # Use eval to convert the representation into a string
            request_line = from_bytes(eval(request_line))
        except:
            # Keep the received version
            pass

        # Extract headers
        raw_headers = request_line.splitlines()[1:-1]
        raw_headers = map(lambda h: re.split(r":\s?", h, 1), raw_headers)
        for header, value in raw_headers:
            header = header.lower()
            if check_duplicates and header in headers:
                raise KeyError("Header defined twice: {0}".format(header))
            headers[header] = value
Beispiel #10
0
    def do_POST(self):
        """
        Handles POST requests
        """
        if not self.is_rpc_path_valid():
            self.report_404()
            return

        # Retrieve the configuration
        config = getattr(self.server, 'json_config', jsonrpclib.config.DEFAULT)

        try:
            # Read the request body
            max_chunk_size = 10 * 1024 * 1024
            size_remaining = int(self.headers["content-length"])
            chunks = []
            while size_remaining:
                chunk_size = min(size_remaining, max_chunk_size)
                raw_chunk = self.rfile.read(chunk_size)
                if not raw_chunk:
                    break
                chunks.append(utils.from_bytes(raw_chunk))
                size_remaining -= len(chunks[-1])
            data = ''.join(chunks)

            try:
                # Decode content
                data = self.decode_request_content(data)
                if data is None:
                    # Unknown encoding, response has been sent
                    return
            except AttributeError:
                # Available since Python 2.7
                pass

            # Execute the method
            response = self.server._marshaled_dispatch(
                data, getattr(self, '_dispatch', None), self.path)

            # No exception: send a 200 OK
            self.send_response(200)
        except:
            # Exception: send 500 Server Error
            self.send_response(500)
            err_lines = traceback.format_exc().splitlines()
            trace_string = '{0} | {1}'.format(err_lines[-3], err_lines[-1])
            fault = jsonrpclib.Fault(-32603, 'Server error: {0}'
                                     .format(trace_string), config=config)
            _logger.exception("Server-side error: %s", fault)
            response = fault.response()

        if response is None:
            # Avoid to send None
            response = ''

        # Convert the response to the valid string format
        response = utils.to_bytes(response)

        # Send it
        self.send_header("Content-type", config.content_type)
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        if response:
            self.wfile.write(response)
    def do_POST(self):
        """
        Handles POST requests
        """
        if not self.is_rpc_path_valid():
            self.report_404()
            return

        # Retrieve the configuration
        config = getattr(self.server, 'json_config', jsonrpclib.config.DEFAULT)

        try:
            # Read the request body
            max_chunk_size = 10 * 1024 * 1024
            size_remaining = int(self.headers["content-length"])
            chunks = []
            while size_remaining:
                chunk_size = min(size_remaining, max_chunk_size)
                raw_chunk = self.rfile.read(chunk_size)
                if not raw_chunk:
                    break
                chunks.append(utils.from_bytes(raw_chunk))
                size_remaining -= len(chunks[-1])
            data = ''.join(chunks)

            try:
                # Decode content
                data = self.decode_request_content(data)
                if data is None:
                    # Unknown encoding, response has been sent
                    return
            except AttributeError:
                # Available since Python 2.7
                pass

            # Execute the method
            response = self.server._marshaled_dispatch(
                data, getattr(self, '_dispatch', None), self.path)

            # No exception: send a 200 OK
            self.send_response(200)
        except:
            # Exception: send 500 Server Error
            self.send_response(500)
            err_lines = traceback.format_exc().splitlines()
            trace_string = '{0} | {1}'.format(err_lines[-3], err_lines[-1])
            fault = jsonrpclib.Fault(-32603, 'Server error: {0}'
                                     .format(trace_string), config=config)
            _logger.exception("Server-side error: %s", fault)
            response = fault.response()

        if response is None:
            # Avoid to send None
            response = ''

        # Convert the response to the valid string format
        response = utils.to_bytes(response)

        # Send it
        self.send_header("Content-type", config.content_type)
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        if response:
            self.wfile.write(response)