Beispiel #1
0
    def request(self, host, handler, request_body, verbose=0):
        # issue XML-RPC request

        h = self.make_connection(host)
        if verbose:
            h.set_debuglevel(1)

        tries = 0
        atype = None
        realm = None

        while(tries < 3):
            self.send_request(h, handler, request_body)
            self.send_host(h, host)
            self.send_user_agent(h)
            if atype:
                # This line will bork if self.setAuthClient has not
                # been issued. That is a programming error, fix your code!
                auths = self._auth_client.getAuth(atype, realm)
                _logger.debug("sending authorization: %s", auths)
                h.putheader('Authorization', auths)
            self.send_content(h, request_body)

            resp = h._conn.getresponse()
            #  except BadStatusLine, e:
            tries += 1

            if resp.status == 401:
                if 'www-authenticate' in resp.msg:
                    (atype,realm) = resp.msg.getheader('www-authenticate').split(' ',1)
                    data1 = resp.read()
                    if data1:
                        log.warning("Why have data on a 401 auth. message?")
                    if realm.startswith('realm="') and realm.endswith('"'):
                        realm = realm[7:-1]
                    _logger.debug("Resp: %r %r", resp.version,resp.isclosed(), resp.will_close)
                    _logger.debug("Want to do auth %s for realm %s", atype, realm)
                    if atype != 'Basic':
                        raise ProtocolError(host+handler, 403,
                                        "Unknown authentication method: %s" % atype, resp.msg)
                    continue # with the outer while loop
                else:
                    raise ProtocolError(host+handler, 403,
                                'Server-incomplete authentication', resp.msg)

            if resp.status != 200:
                raise ProtocolError( host + handler,
                    resp.status, resp.reason, resp.msg )

            self.verbose = verbose

            try:
                sock = h._conn.sock
            except AttributeError:
                sock = None

            return self._parse_response(h.getfile(), sock, resp)

        raise ProtocolError(host+handler, 403, "No authentication.",'')
Beispiel #2
0
        def request(self, host, handler, request_body, verbose=0):
            # issue XML-RPC request
            h = self.make_connection(host)
            if verbose:
                h.set_debuglevel(1)

            self.send_request(h, handler, request_body)
            self.send_host(h, host)
            self.send_user_agent(h)
            self.send_content(h, request_body)

            errcode, errmsg, headers = h.getreply()
            if errcode != 200:
                raise ProtocolError(host + handler, errcode, errmsg, headers)

            self.verbose = verbose

            # Here's where we differ from the superclass. It says:
            # try:
            #     sock = h._conn.sock
            # except AttributeError:
            #     sock = None
            # return self._parse_response(h.getfile(), sock)

            return self.parse_response(h.getfile())
Beispiel #3
0
    def __has_valid_connection(self, needs_extended_permissions=True):
        """
        Checks whether the connection is valid and whether the user
        has the required permissions.
        """
        if not self.is_valid_connection:
            raise ProtocolError(url=self.url,
                                errcode=404,
                                errmsg='Not found',
                                headers=None)

        if needs_extended_permissions and self.get_only:
            raise ProtocolError(url=self.url,
                                errcode=401,
                                errmsg='Authorization Required.',
                                headers=None)
Beispiel #4
0
    def request(self, host, handler, request_body, verbose=0):
        # issue XML-RPC request
        h = self.make_connection(host)
        if verbose:
            h.set_debuglevel(1)

        self.send_request(h, handler, request_body)
        self.send_host(h, host)
        self.send_user_agent(h)
        self.send_content(h, request_body)

        errcode, errmsg, headers = h.getreply()

        if errcode != 200:
            raise ProtocolError(
                host + handler,
                errcode, errmsg,
                headers
                )

        self.setCookie(headers.getheaders('set-cookie'))

        self.verbose = verbose

        try:
            sock = h._conn.sock
        except AttributeError:
            sock = None

        return self._parse_response(h.getfile(), sock)     
Beispiel #5
0
    def single_request(self, host, handler, request_body, verbose=0):
        # issue XML-RPC request

        h = self.make_connection(host)
        if verbose:
            h.set_debuglevel(1)

        try:
            self.send_request(h, handler, request_body)
            self.send_host(h, host)
            # 			self.send_user_agent(h)
            self.send_content(h, request_body)

            response = h.getresponse(buffering=True)
            if response.status == 200:
                self.verbose = verbose
                return self.parse_response(response)
        except Fault:
            raise
        except Exception:
            # All unexpected errors leave connection in
            # a strange state, so we clear it.
            self.close()
            raise

        # discard any response data and raise exception
        if (response.getheader("content-length", 0)):
            response.read()
        raise ProtocolError(
            host + handler,
            response.status,
            response.reason,
            response.msg,
        )
Beispiel #6
0
        def request(self, host, handler, request_body, verbose=0):
            h = self.make_connection(host)
            if verbose:
                h.set_debuglevel(1)

            self.send_request(h, handler, request_body)
            self.send_host(h, host)
            self.send_user_agent(h)
            self.send_content(h, request_body)

            errcode, errmsg, headers = h.getreply()

            if errcode != 200:
                raise ProtocolError(host + handler, errcode, errmsg, headers)

            self.verbose = verbose

            try:
                sock = h._conn.sock
            except AttributeError:
                sock = None

            # ADDED
            self.cookie = headers.get('set-cookie') or self.cookie
            logger.debug('CookieTransportHelper, request, cookie=%s' %
                         (self.cookie, ))
            # END ADDED

            return self._parse_response(h.getfile(), sock)
Beispiel #7
0
    def request(self, host, handler, request_body, verbose=0):
        # issue XML-RPC request
        h = self.make_connection(host)

        if verbose:
            h.set_debuglevel(1)

        self.send_request(h, handler, request_body)
        self.send_host(h, host)
        self.send_user_agent(h)

        if self.cookie is not None:
            h.putheader("Cookie", self.cookie)

        self.send_content(h, request_body)
        errcode, errmsg, headers = h.getreply()

        self.cookie = headers.getheader('set-cookie') or self.cookie

        if errcode != 200:
            raise ProtocolError(host + handler, errcode, errmsg, headers)

        # do not print the response body
        self.verbose = False

        return self.parse_response(h.getfile())
Beispiel #8
0
    def request(self, host, handler, request_body, verbose=0):
        # issue XML-RPC request

        h = self.make_connection(host)
        if verbose:
            h.set_debuglevel(1)

        self.send_request(h, handler, request_body)
        self.send_host(h, host)
        self.send_user_agent(h)
        self.send_content(h, request_body)

        resp = h._conn.getresponse()
        # TODO: except BadStatusLine, e:

        errcode, errmsg, headers = resp.status, resp.reason, resp.msg

        if errcode != 200:
            raise ProtocolError(host + handler, errcode, errmsg, headers)

        self.verbose = verbose

        try:
            sock = h._conn.sock
        except AttributeError:
            sock = None

        return self._parse_response(h.getfile(), sock, resp)
Beispiel #9
0
    def request(self, host, handler, request_body, verbose=0):
        '''
		Send a complete request, and parse the response.
		
		 @param host Target host.
		 @param handler Target PRC handler.
		 @param request_body XML-RPC request body.
		 @param verbose Debugging flag.
		 @return XML response.
		'''
        # issue XML-RPC request

        self.verbose = verbose

        h = self.make_connection(host)
        if verbose:
            h.set_debuglevel(1)

        self.send_request(h, handler, request_body)
        self.send_host(h, host)
        self.send_auth(h, self.proxy_username, self.proxy_password)
        self.send_user_agent(h)
        self.send_content(h, request_body)

        errcode, errmsg, headers = h.getreply()

        if errcode != 200:
            raise ProtocolError(host + handler, errcode, errmsg, headers)

        return self.parse_response(h.getfile())
Beispiel #10
0
    def single_request(self, host, handler, request_body, verbose=0):
        # Based on Python 2.7's xmllib.Transport.single_request
        try:
            h = self.make_connection(host)

            if verbose:
                h.set_debuglevel(1)

            self.get_auth_info()

            while True:
                if six.PY2:
                    # pylint: disable=no-value-for-parameter
                    self.send_request(h, handler, request_body)
                    # pylint: enable=no-value-for-parameter
                    self.send_host(h, host)
                    self.send_user_agent(h)
                    self.send_content(h, request_body)
                    response = h.getresponse(buffering=True)
                else:
                    self.__send_request(h, host, handler, request_body,
                                        verbose)
                    response = h.getresponse()

                if response.status != 200:
                    # Must read response (even if it is empty)
                    # before sending another request.
                    #
                    # https://docs.python.org/3/library/http.client.html
                    #   #http.client.HTTPConnection.getresponse
                    #
                    # https://pagure.io/freeipa/issue/7752
                    #
                    response.read()

                    if response.status == 401:
                        if not self._auth_complete(response):
                            continue

                    raise ProtocolError(host + handler, response.status,
                                        response.reason, response.msg)

                self.verbose = verbose
                if not self._auth_complete(response):
                    continue
                return self.parse_response(response)
        except gssapi.exceptions.GSSError as e:
            self._handle_exception(e)
        except RemoteDisconnected:
            # keep-alive connection was terminated by remote peer, close
            # connection and let transport handle reconnect for us.
            self.close()
            logger.debug("HTTP server has closed connection (%s)", host)
            raise
        except BaseException as e:
            # Unexpected exception may leave connections in a bad state.
            self.close()
            logger.debug("HTTP connection destroyed (%s)", host, exc_info=True)
            raise
Beispiel #11
0
 def send_content(self, connection, request_body):
     try:
         return SafeTransport.send_content(self, connection, request_body)
     except socket.error, e:
         # BBB: On Python < 2.7, HTTP connection is wrapped
         raise ProtocolError(
             getattr(connection, '_conn', connection).host, -1,
             "Could not connect to server", None)
Beispiel #12
0
    def values(self, key, channels, start_sec, start_nano, end_sec, end_nano,
               count, interpolation):
        check_type(key, int, 'INT')
        check_type(channels, (list, tuple), 'ARRAY')
        for value in [
                start_sec, start_nano, end_sec, end_nano, count, interpolation
        ]:
            if not isinstance(value, int):
                raise ProtocolError('cr01arc01/cgi-bin/ArchiveDataServer.cgi',
                                    codes.xmlrpc.INTERNAL,
                                    'Internal Server Error', None)
        if not 0 <= interpolation <= 4:
            raise Fault(codes.archiver.ARGUMENT_ERROR,
                        'Invalid how={0}'.format(interpolation))
        if interpolation != 0:
            raise Exception('Only raw interpolation is supported by'
                            'MockArchiver.')
        key = str(key)
        self._check_key(key)
        archive_data = self._archives[key]['data']
        return_data = []

        start = start_sec + 1e-9 * start_nano
        end = end_sec + 1e-9 * end_nano

        for channel in channels:
            try:
                channel_data = archive_data[channel].copy()
                channel_values = channel_data['values']
                for index, value in enumerate(channel_values):
                    time = value['secs'] + 1e-9 * value['nano']
                    if not start <= time <= end:
                        channel_values.pop(index)
                del channel_values[count:]
            except KeyError:
                channel_data = {
                    'count': 1,
                    'meta': {
                        'alarm_high': 0.0,
                        'alarm_low': 0.0,
                        'disp_high': 10.0,
                        'disp_low': 0.0,
                        'prec': 1,
                        'type': 1,
                        'units': '<NO DATA>',
                        'warn_high': 0.0,
                        'warn_low': 0.0
                    },
                    'name': channel,
                    'type': 1,
                    'values': []
                }
            return_data.append(channel_data)
        return return_data
Beispiel #13
0
    def single_request(self, host, handler, request_body, verbose=0):
        # Based on Python 2.7's xmllib.Transport.single_request
        try:
            h = self.make_connection(host)

            if verbose:
                h.set_debuglevel(1)

            self.get_auth_info()

            while True:
                if six.PY2:
                    # pylint: disable=no-value-for-parameter
                    self.send_request(h, handler, request_body)
                    # pylint: enable=no-value-for-parameter
                    self.send_host(h, host)
                    self.send_user_agent(h)
                    self.send_content(h, request_body)
                    response = h.getresponse(buffering=True)
                else:
                    self.__send_request(h, host, handler, request_body, verbose)
                    response = h.getresponse()

                if response.status != 200:
                    if (response.getheader("content-length", 0)):
                        response.read()

                    if response.status == 401:
                        if not self._auth_complete(response):
                            continue

                    raise ProtocolError(
                        host + handler,
                        response.status, response.reason,
                        response.msg)

                self.verbose = verbose
                if not self._auth_complete(response):
                    continue
                return self.parse_response(response)
        except gssapi.exceptions.GSSError as e:
            self._handle_exception(e)
        except RemoteDisconnected:
            # keep-alive connection was terminated by remote peer, close
            # connection and let transport handle reconnect for us.
            self.close()
            logger.debug("HTTP server has closed connection (%s)", host)
            raise
        except BaseException as e:
            # Unexpected exception may leave connections in a bad state.
            self.close()
            logger.debug("HTTP connection destroyed (%s)",
                         host, exc_info=True)
            raise
Beispiel #14
0
    def _request(self, trans, method, path, uparams, request_body):
        """
            @param trans a TCPTransport object
        """
        # issue XML-RPC request
        max_tries = getattr(trans, "_auth_tries", 3)
        tries = 0
        host = trans._http_host
        h = None

        while(tries < max_tries):
            resp = None
            if not h:
                h = trans.make_connection(host)

            tries += 1
            try:
                h.putrequest(method, path+uparams, skip_accept_encoding=1)
                trans.send_host(h, host)
                trans.send_user_agent(h)
            except httplib.CannotSendRequest:
                if h: h.close()
                continue

            if trans._auth_client:
                trans._auth_client.putRequest(trans._auth_type, trans._auth_realm,
                                              h, host, path)
            trans.send_content(h, request_body)

            try:
                resp = h.getresponse()
            except httplib.BadStatusLine, e:
                if e.line and e.line != "''": # BadStatusLine does a repr(line)
                    # something else, not a broken connection
                    raise
                if h: h.close()
                if resp: resp.close()
                continue

            try:
                if trans._auth_client:
                    aresp = trans._auth_client.parseResponse(resp, trans, host+path)
                    if resp.status == 401 and aresp:
                        continue

                if resp.status == 401:
                    raise ProtocolError(host+path, 403,
                                    'Server-incomplete authentication', resp.msg)
            except Exception:
                if resp: resp.close()
                raise

            return resp # as is, the whole object, open
Beispiel #15
0
    def request(self, host, handler, request_body, verbose=0):
        self.verbose = verbose
        response = self.client.post(handler,
                                    request_body,
                                    content_type="text/xml")

        status_code, msg, headers = response.status_code, STATUS_CODE_TEXT.get(
            response.status_code, str(response.status_code)), response.items()

        if response.status_code != 200:
            raise ProtocolError(host + handler, status_code, msg, headers)

        return self._parse_response(response.content, None)
Beispiel #16
0
    def request(self, host, handler, request_body, verbose=False):
        parser, unmarshaller = getparser()

        response = self.client.post(handler, request_body, 'text/xml')

        if response.status_code != 200:
            raise ProtocolError(
                '%s%s' % (host, handler),
                response.status_code,
                responses.get(response.status_code, ''),
                dict(response.items()),
            )

        parser.feed(response.content)

        return unmarshaller.close()
Beispiel #17
0
    def request(self, host, handler, request_body, verbose):
        """
        Make an xmlrpc request.
        """
        headers = {
            'User-Agent': self.user_agent,
            'Content-Type': 'text/xml',
        }
        url = self._build_url(host, handler)

        try:
            resp = self.session.post(url,
                                     data=request_body,
                                     headers=headers,
                                     proxies=self.session.proxies)
            resp.raise_for_status()

        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 407:  # Proxy Authentication Required
                handle_proxy_407(url, self.session)
                # Try again
                return self.request(host, handler, request_body, verbose)
            else:
                raise

        except requests.exceptions.ConnectionError as e:
            # requests isn't so nice here. For whatever reason, https gives this
            # error and http gives the above error. Also, there is no status_code
            # attribute here. We have to just check if it looks like 407.  See
            # https://github.com/kennethreitz/requests/issues/2061.
            if "407" in str(e):  # Proxy Authentication Required
                handle_proxy_407(url, self.session)
                # Try again
                return self.request(host, handler, request_body, verbose)
            else:
                raise

        except requests.RequestException as e:
            raise ProtocolError(url, resp.status_code, str(e), resp.headers)

        else:
            return self.parse_response(resp)
Beispiel #18
0
    def request(self, host, handler, request_body, verbose=0):
        # issue XML-RPC request

        try:
            h = self.make_connection(host)
            if verbose:
                h.set_debuglevel(1)

            self.send_request(h, handler, request_body)
        except httplib.CannotSendRequest:
            # try once more..
            if h: h.close()
            h = self.make_connection(host)
            if verbose:
                h.set_debuglevel(1)

            self.send_request(h, handler, request_body)

        self.send_host(h, host)
        self.send_user_agent(h)
        self.send_content(h, request_body)

        resp = None
        try:
            resp = h._conn.getresponse()
            # TODO: except BadStatusLine, e:

            errcode, errmsg, headers = resp.status, resp.reason, resp.msg
            if errcode != 200:
                raise ProtocolError(host + handler, errcode, errmsg, headers)

            self.verbose = verbose

            try:
                sock = h._conn.sock
            except AttributeError:
                sock = None

            return self._parse_response(resp)
        finally:
            if resp: resp.close()
Beispiel #19
0
    def single_request(self, host, handler, request_body, verbose=0):
        # This method is almost the same as:
        # http://hg.python.org/cpython/file/2.7/Lib/xmlrpclib.py#l1281

        h = self.make_connection(host)
        if verbose:
            h.set_debuglevel(1)

        try:
            self.send_request(h, handler, request_body)
            self.send_host(h, host)
            self.send_user_agent(h)
            self.send_content(h, request_body)

            response = h.getresponse(buffering=True)
            ## for debugging:
            #print(host, handler)
            #print(request_body)
            #print(response.getheaders())
            #print(response.read())
            if response.status == 200:
                self.verbose = verbose
                cookie_header = response.getheader('set-cookie')
                if cookie_header: self.__cookie = cookie_header
                return self.parse_response(response)
        except Fault:
            raise
        except Exception:
            # All unexpected errors leave connection in
            # a strange state, so we clear it.
            self.close()
            raise
        #discard any response data and raise exception
        if (response.getheader("content-length", 0)):
            response.read()
        raise ProtocolError(
            host + handler,
            response.status,
            response.reason,
            response.msg,
        )
Beispiel #20
0
    def single_request(self, host, handler, request_body, verbose=0):
        # Based on Python 2.7's xmllib.Transport.single_request
        try:
            h = SSLTransport.make_connection(self, host)

            if verbose:
                h.set_debuglevel(1)

            while True:
                if six.PY2:
                    # pylint: disable=no-value-for-parameter
                    self.send_request(h, handler, request_body)
                    # pylint: enable=no-value-for-parameter
                    self.send_host(h, host)
                    self.send_user_agent(h)
                    self.send_content(h, request_body)
                    response = h.getresponse(buffering=True)
                else:
                    self.__send_request(h, host, handler, request_body,
                                        verbose)
                    response = h.getresponse()

                if response.status != 200:
                    if (response.getheader("content-length", 0)):
                        response.read()

                    if response.status == 401:
                        if not self._auth_complete(response):
                            continue

                    raise ProtocolError(host + handler, response.status,
                                        response.reason, response.msg)

                self.verbose = verbose
                if not self._auth_complete(response):
                    continue
                return self.parse_response(response)
        except gssapi.exceptions.GSSError as e:
            self._handle_exception(e)
        finally:
            self.close()
Beispiel #21
0
    def request(self, host, handler, request_body, verbose=0):
        """Make an XMLRPC request.

        Uses the configured proxy server to make the connection.
        """
        url = urlunparse((self.scheme, host, handler, '', '', ''))
        headers = {'Content-type': 'text/xml'}
        request = Request(url, request_body, headers)
        try:
            response = self.opener.open(request, timeout=self.timeout).read()
        except HTTPError as he:
            raise ProtocolError(request.get_full_url(), he.code, he.msg,
                                he.hdrs)
        else:
            traceback_info(response)
            # In Python2.6 the api is self._parse_response, in 2.7 it is
            # self.parse_response and no longer takes the 'sock' argument
            parse = getattr(self, '_parse_response', None)
            if parse is not None:
                # Compatibility with python 2.6
                return parse(StringIO(response), None)
            return self.parse_response(StringIO(response))
Beispiel #22
0
    def request(self, host, handler, request_body, verbose=0):
        req = Request(self.uri)
        req.add_header('User-Agent', self.user_agent)
        req.add_header('Content-Type', 'text/xml')

        if hasattr(self, 'accept_gzip_encoding') and self.accept_gzip_encoding:
            req.add_header('Accept-Encoding', 'gzip')

        req.add_data(request_body)

        resp = self.opener.open(req)

        # In Python 2, resp is a urllib.addinfourl instance, which does not
        # have the getheader method that parse_response expects.
        if not hasattr(resp, 'getheader'):
            resp.getheader = resp.headers.getheader

        if resp.code == 200:
            self.verbose = verbose
            return self.parse_response(resp)

        resp.close()
        raise ProtocolError(self.uri, resp.status, resp.reason, resp.msg)
Beispiel #23
0
    def request(self, host, handler, request_body, verbose=0):
        """Make an XMLRPC request.

        Uses the configured proxy server to make the connection.
        """
        url = urlunparse((self.scheme, host, handler, '', '', ''))
        # httplib can raise a UnicodeDecodeError when using a Unicode
        # URL, a non-ASCII body and a proxy. http://bugs.python.org/issue12398
        url = six.ensure_binary(url)
        try:
            with override_timeout(self.timeout):
                response = urlfetch(
                    url, method='POST', headers={'Content-Type': 'text/xml'},
                    data=request_body, cookies=self.cookie_jar,
                    hooks={'response': repost_on_redirect_hook},
                    use_proxy=True)
        except requests.HTTPError as e:
            raise ProtocolError(
                url.decode('utf-8'), e.response.status_code, e.response.reason,
                e.response.headers)
        else:
            traceback_info(response.text)
            return self.parse_response(BytesIO(response.content))
    def request(self, host, handler, request_body, verbose=0):
        # issue XML-RPC request

        h = self.make_connection(host)
        if verbose:
            h.set_debuglevel(1)

        self.send_request(h, handler, request_body)
        self.send_host(h, host)
        self.send_user_agent(h)
        self.send_content(h, request_body)

        response = h.getresponse()

        if response.status != 200:
            raise ProtocolError(host + handler, response.status,
                                response.reason, response.msg.headers)

        payload = response.read()
        parser, unmarshaller = self.getparser()
        parser.feed(payload)
        parser.close()

        return unmarshaller.close()
Beispiel #25
0
    def request(self, host, handler, request_body, verbose=0):
        # Override the xmlrpc request object so we have more control over
        # the response and can sift through the response headers.
        # issue XML-RPC request

        h = self.make_connection(host)
        if verbose:
            h.set_debuglevel(1)

        try:
            self.send_request(h, handler, request_body)
            self.send_host(h, host)
            self.send_user_agent(h)
            self.send_content(h, request_body)

            response = h._conn.getresponse()
            if response.status == 200:
                self.verbose = verbose
                return self.parse_response(response)
        except Fault:
            raise
        except Exception:
            # All unexpected errors leave connection in
            # a strange state, so we clear it.
            h.close()
            raise

        #discard any response data and raise exception
        if (response.getheader("content-length", 0)):
            response.read()
        raise ProtocolError(
            host + handler,
            response.status,
            response.reason,
            response.msg,
        )
Beispiel #26
0
    def request(self, host, handler, request_body, verbose=0):
        # issue XML-RPC request
        max_tries = getattr(self, "_auth_tries", 3)
        tries = 0
        atype = None
        realm = None
        h = None

        while (tries < max_tries):
            if not h:
                h = self.make_connection(host)
                if verbose:
                    h.set_debuglevel(1)

            tries += 1
            try:
                self.send_request(h, handler, request_body)
                self.send_host(h, host)
                self.send_user_agent(h)
            except httplib.CannotSendRequest:
                if h: h.close()
                continue

            if atype:
                # This line will bork if self.setAuthClient has not
                # been issued. That is a programming error, fix your code!
                auths = self._auth_client.getAuth(atype, realm)
                h.putheader('Authorization', auths)
            self.send_content(h, request_body)

            resp = h._conn.getresponse()
            #  except BadStatusLine, e:

            if resp.status == 401:
                if 'www-authenticate' in resp.msg:
                    (atype,
                     realm) = resp.msg.getheader('www-authenticate').split(
                         ' ', 1)
                    data1 = resp.read()
                    if realm.startswith('realm="') and realm.endswith('"'):
                        realm = realm[7:-1]
                    # print "Resp:", resp.version,resp.isclosed(), resp.will_close
                    #print "Want to do auth %s for realm %s" % (atype, realm)
                    if atype != 'Basic':
                        raise ProtocolError(
                            host + handler, 403,
                            "Unknown authentication method: %s" % atype,
                            resp.msg)
                    continue  # with the outer while loop
                else:
                    raise ProtocolError(host + handler, 403,
                                        'Server-incomplete authentication',
                                        resp.msg)

            if resp.status != 200:
                raise ProtocolError(host + handler, resp.status, resp.reason,
                                    resp.msg)

            self.verbose = verbose

            try:
                sock = h._conn.sock
            except AttributeError:
                sock = None

            return self._parse_response(resp)

        raise ProtocolError(host + handler, 403, "No authentication", '')
Beispiel #27
0
    def request(self, path, params=None, data=None, request_type="JSON", callback=None):
        """ A complete HTTP request on this side-channel

            @param path string path, shall begin with '/'
            @param params dictionary of parameters, to be url-encoded (TODO)
            @param data raw data, to be encoded according to `request_type`
            @param request_type  {JSON|...} affects content-type and request method
            @param callback function(response) to be called instead of default processor

            This function, by default, will process the returned content according
            to its "Content-Type". Will raise an exception on 4xx or 5xx errors.
            If you want to manipulate the response, do provide a `callback`, where
            you can read the status and http headers.
        """
        self._logger.debug("request for %s", path)
        body = None
        content_type = 'text/plain'
        uparams = ''
        if params:
            assert isinstance(params, dict), type(params)
            params = params.copy()
            for k, v in params.items():
                if isinstance(v, unicode):
                    params[k] = v.encode('utf-8')
            uparams = '?'+urllib.urlencode(params)

        path = self._base_path + path

        if not data:
            method = 'GET'
        elif request_type == 'JSON':
            method = 'POST'
            content_type = 'application/json'
            body = json.dumps(data, cls=json_helpers.JsonEncoder2)
        else:
            raise NotImplementedError("Request type: %s" %request_type)

        resp = None
        saved_content_type = None
        try:
            conn = self.__session.connections.borrow(self.__session.conn_timeout)
            # override the transport , restore later
            saved_content_type = conn._transport._content_type
            conn._transport._content_type = content_type
            resp = self._request(conn._transport, method, path, uparams, body)

            if callback:
                return callback(resp)
            else:
                if resp.status == 204:
                    resp.read() # just in case there is content, in violation of RFC
                    return True
                elif resp.status != 200:
                    resp.read()
                    raise ProtocolError(conn.host + path,
                                resp.status, resp.reason, resp.msg )

                return self._decode_response(resp)
        finally:
            if conn and conn._transport:
                conn._transport._content_type = saved_content_type
            if resp: resp.close()
            self.__session.connections.free(conn)
Beispiel #28
0
    def values(
        self,
        key,
        channels,
        start_sec,
        start_nano,
        end_sec,
        end_nano,
        count,
        interpolation,
    ):
        check_type(key, int, "INT")
        check_type(channels, (list, tuple), "ARRAY")
        for value in [
                start_sec, start_nano, end_sec, end_nano, count, interpolation
        ]:
            if not isinstance(value, int):
                raise ProtocolError(
                    "cr01arc01/cgi-bin/ArchiveDataServer.cgi",
                    codes.xmlrpc.INTERNAL,
                    "Internal Server Error",
                    None,
                )
        if not 0 <= interpolation <= 4:
            raise Fault(codes.archiver.ARGUMENT_ERROR,
                        "Invalid how={0}".format(interpolation))
        if interpolation != 0:
            raise Exception(
                "Only raw interpolation is supported by MockArchiver.")
        key = str(key)
        self._check_key(key)
        archive_data = self._archives[key]["data"]
        return_data = []

        start = start_sec + 1e-9 * start_nano
        end = end_sec + 1e-9 * end_nano

        for channel in channels:
            try:
                channel_data = archive_data[channel].copy()
                channel_values = channel_data["values"]
                for index, value in enumerate(channel_values):
                    time = value["secs"] + 1e-9 * value["nano"]
                    if not start <= time <= end:
                        channel_values.pop(index)
                del channel_values[count:]
            except KeyError:
                channel_data = {
                    "count": 1,
                    "meta": {
                        "alarm_high": 0.0,
                        "alarm_low": 0.0,
                        "disp_high": 10.0,
                        "disp_low": 0.0,
                        "prec": 1,
                        "type": 1,
                        "units": "<NO DATA>",
                        "warn_high": 0.0,
                        "warn_low": 0.0,
                    },
                    "name": channel,
                    "type": 1,
                    "values": [],
                }
            return_data.append(channel_data)
        return return_data
Beispiel #29
0
class SideChannel(object):
    """Out of band request, re-using libclient transport
    """
    _logger = logging.getLogger('RPC.side-channel')

    def __init__(self, session, base_path=""):
        assert isinstance(session, Session)
        self.__session = session
        self._base_path = base_path % session.conn_args


    def _request(self, trans, method, path, uparams, request_body):
        """
            @param trans a TCPTransport object
        """
        # issue XML-RPC request
        max_tries = getattr(trans, "_auth_tries", 3)
        tries = 0
        host = trans._http_host
        h = None

        while(tries < max_tries):
            resp = None
            if not h:
                h = trans.make_connection(host)

            tries += 1
            try:
                h.putrequest(method, path+uparams, skip_accept_encoding=1)
                trans.send_host(h, host)
                trans.send_user_agent(h)
            except httplib.CannotSendRequest:
                if h: h.close()
                continue

            if trans._auth_client:
                trans._auth_client.putRequest(trans._auth_type, trans._auth_realm,
                                              h, host, path)
            trans.send_content(h, request_body)

            try:
                resp = h.getresponse()
            except httplib.BadStatusLine, e:
                if e.line and e.line != "''": # BadStatusLine does a repr(line)
                    # something else, not a broken connection
                    raise
                if h: h.close()
                if resp: resp.close()
                continue

            try:
                if trans._auth_client:
                    aresp = trans._auth_client.parseResponse(resp, trans, host+path)
                    if resp.status == 401 and aresp:
                        continue

                if resp.status == 401:
                    raise ProtocolError(host+path, 403,
                                    'Server-incomplete authentication', resp.msg)
            except Exception:
                if resp: resp.close()
                raise

            return resp # as is, the whole object, open

        raise ProtocolError(host+path, 403, "No authentication",'')
Beispiel #30
0
 def _getExternalBugTrackersAndWatches(self, bug_tracker, bug_watches):
     raise ProtocolError(
         "http://example.com/", self.error_code, "Borked", "")