Current File : /home/mmdealscpanel/yummmdeals.com/rhn.zip
PK���Z�G$���__init__.pynu�[���#
# __init__.py
#
# Copyright (c) 2011--2013 Red Hat, Inc.
#
"""
rhn - A collection of modules used by Red Hat Network Classic
"""

PK���Zg7B=�|�|
transports.pynu�[���#
# Helper transport objects
#
# Copyright (c) 2002--2016 Red Hat, Inc.
#
# Author: Mihai Ibanescu <misa@redhat.com>
# Based on what was previously shipped as cgiwrap:
#   - Cristian Gafton <gafton@redhat.com>
#   - Erik Troan <ewt@redhat.com>


# Transport objects
import os
import sys
import time
from rhn import connections
from rhn.i18n import sstr, bstr
from rhn.SmartIO import SmartIO
from rhn.UserDictCase import UserDictCase

try: # python2
    import xmlrpclib
    from types import IntType, StringType, ListType
except ImportError: # python3
    import xmlrpc.client as xmlrpclib
    IntType = int
    StringType = bytes
    ListType = list

__version__ = "2.8.62.8.6-8.module_el8.10.0+6858+3ddf28328.module_el8.10.0+6858+3ddf2832"

# XXX
COMPRESS_LEVEL = 6

# Exceptions
class NotProcessed(Exception):
    pass

class Transport(xmlrpclib.Transport):
    user_agent = "rhn.rpclib.py/%s" % __version__

    def __init__(self, transfer=0, encoding=0, refreshCallback=None,
            progressCallback=None, use_datetime=None, timeout=None):
        self._use_builtin_types = False
        self._transport_flags = {'transfer' : 0, 'encoding' : 0}
        self.set_transport_flags(transfer=transfer, encoding=encoding)
        self._headers = UserDictCase()
        self.verbose = 0
        self.connection = None
        self.method = "POST"
        self._lang = None
        self.refreshCallback = refreshCallback
        self.progressCallback = progressCallback
        self.bufferSize = 16384
        self.headers_in = None
        self.response_status = None
        self.response_reason = None
        self._redirected = None
        self._use_datetime = use_datetime
        self.timeout = timeout

    # set the progress callback
    def set_progress_callback(self, progressCallback, bufferSize=16384):
        self.progressCallback = progressCallback
        self.bufferSize = bufferSize

    # set the refresh callback
    def set_refresh_callback(self, refreshCallback):
        self.refreshCallback = refreshCallback

    # set the buffer size
    # The bigger this is, the faster the read is, but the more seldom is the
    # progress callback called
    def set_buffer_size(self, bufferSize):
        if bufferSize is None:
            # No buffer size specified; go with 16k
            bufferSize = 16384

        self.bufferSize = bufferSize

    # set the request method
    def set_method(self, method):
        if method not in ("GET", "POST"):
            raise IOError("Unknown request method %s" % method)
        self.method = method

    # reset the transport options
    def set_transport_flags(self, transfer=None, encoding=None, **kwargs):
        # For backwards compatibility, we keep transfer and encoding as
        # positional parameters (they could come in as kwargs easily)

        self._transport_flags.update(kwargs)
        if transfer is not None:
            self._transport_flags['transfer'] = transfer
        if encoding is not None:
            self._transport_flags['encoding'] = encoding
        self.validate_transport_flags()

    def get_transport_flags(self):
        return self._transport_flags.copy()

    def validate_transport_flags(self):
        # Transfer and encoding are guaranteed to be there
        transfer = self._transport_flags.get('transfer')
        transfer = lookupTransfer(transfer, strict=1)
        self._transport_flags['transfer'] = transfer

        encoding = self._transport_flags.get('encoding')
        encoding = lookupEncoding(encoding, strict=1)
        self._transport_flags['encoding'] = encoding

    # Add arbitrary additional headers.
    def set_header(self, name, arg):
        if type(arg) in [ type([]), type(()) ]:
            # Multivalued header
            self._headers[name] = [str(a) for a in arg]
        else:
            self._headers[name] = str(arg)

    def add_header(self, name, arg):
        if name in self._headers:
            vlist = self._headers[name]
            if not isinstance(vlist, ListType):
                vlist = [ vlist ]
        else:
            vlist = self._headers[name] = []
        vlist.append(str(arg))

    def clear_headers(self):
        self._headers.clear()

    def get_connection(self, host):
        if self.verbose:
            print("Connecting via http to %s" % (host, ))
        if self.timeout:
            return connections.HTTPConnection(host, timeout=self.timeout)
        else:
            return connections.HTTPConnection(host)

    def request(self, host, handler, request_body, verbose=0):
        # issue XML-RPC request
        # XXX: automatically compute how to send depending on how much data
        #      you want to send

        # XXX Deal with HTTP/1.1 if necessary
        self.verbose = verbose

        # implement BASIC HTTP AUTHENTICATION
        host, extra_headers, x509 = self.get_host_info(host)
        if not extra_headers:
            extra_headers = []
        # Establish the connection
        connection = self.get_connection(host)
        # Setting the user agent. Only interesting for SSL tunnels, in any
        # other case the general headers are good enough.
        connection.set_user_agent(self.user_agent)
        if self.verbose:
            connection.set_debuglevel(self.verbose - 1)
        # Get the output object to push data with
        req = Output(connection=connection, method=self.method)
        req.set_transport_flags(**self._transport_flags)

        # Add the extra headers
        req.set_header('User-Agent', self.user_agent)
        for header, value in list(self._headers.items()) + extra_headers:
            # Output.set_header correctly deals with multivalued headers now
            req.set_header(header, value)

        # Content-Type
        req.set_header("Content-Type", "text/xml")
        req.process(request_body)

        # Host and Content-Length are set by HTTP*Connection
        for h in ['Content-Length', 'Host']:
            req.clear_header(h)

        headers, fd = req.send_http(host, handler)

        if self.verbose:
            print("Incoming headers:")
            for header, value in headers.items():
                print("\t%s : %s" % (header, value))

        if fd.status in (301, 302):
            self._redirected = headers["Location"]
            self.response_status = fd.status
            return None

        # Save the headers
        self.headers_in = headers
        self.response_status = fd.status
        self.response_reason = fd.reason

        return self._process_response(fd, connection)

    def _process_response(self, fd, connection):
        # Now use the Input class in case we get an enhanced response
        resp = Input(self.headers_in, progressCallback=self.progressCallback,
                bufferSize=self.bufferSize)

        fd = resp.decode(fd)

        if isinstance(fd, InputStream):
            # When the File object goes out of scope, so will the InputStream;
            # that will eventually call the connection's close() method and
            # cleanly reap it
            f = File(fd.fd, fd.length, fd.name, bufferSize=self.bufferSize,
                progressCallback=self.progressCallback)
            # Set the File's close method to the connection's
            # Note that calling the HTTPResponse's close() is not enough,
            # since the main socket would remain open, and this is
            # particularily bad with SSL
            f.close = connection.close
            return f

        # We can safely close the connection now; if we had an
        # application/octet/stream (for which Input.read passes the original
        # socket object), Input.decode would return an InputStream,
        # so we wouldn't reach this point
        connection.close()

        return self.parse_response(fd)

    # Give back the new URL if redirected
    def redirected(self):
        return self._redirected

    # Rewrite parse_response to provide refresh callbacks
    def parse_response(self, f):
        # read response from input file, and parse it

        p, u = self.getparser()

        while 1:
            response = f.read(1024)
            if not response:
                break
            if self.refreshCallback:
                self.refreshCallback()
            if self.verbose:
                print("body:", repr(response))
            p.feed(response)

        f.close()
        p.close()
        return u.close()


    def setlang(self, lang):
        self._lang = lang

class SafeTransport(Transport):
    def __init__(self, transfer=0, encoding=0, refreshCallback=None,
                progressCallback=None, trusted_certs=None, timeout=None):
        Transport.__init__(self, transfer, encoding,
            refreshCallback=refreshCallback, progressCallback=progressCallback,
            timeout=timeout)
        self.trusted_certs = []
        for certfile in (trusted_certs or []):
            self.add_trusted_cert(certfile)

    def add_trusted_cert(self, certfile):
        if not os.access(certfile, os.R_OK):
            raise ValueError("Certificate file %s is not accessible" % certfile)
        self.trusted_certs.append(certfile)

    def get_connection(self, host):
        # implement BASIC HTTP AUTHENTICATION
        host, extra_headers, x509 = self.get_host_info(host)
        if self.verbose:
            print("Connecting via https to %s" % (host, ))
        if self.timeout:
            return connections.HTTPSConnection(host,
                    trusted_certs=self.trusted_certs, timeout=self.timeout)
        else:
            return connections.HTTPSConnection(host,
                    trusted_certs=self.trusted_certs)


class ProxyTransport(Transport):
    def __init__(self, proxy, proxyUsername=None, proxyPassword=None,
            transfer=0, encoding=0, refreshCallback=None, progressCallback=None,
            timeout=None):
        Transport.__init__(self, transfer, encoding,
            refreshCallback=refreshCallback, progressCallback=progressCallback,
            timeout=timeout)
        self._proxy = proxy
        self._proxy_username = proxyUsername
        self._proxy_password = proxyPassword

    def get_connection(self, host):
        if self.verbose:
            print("Connecting via http to %s proxy %s, username %s, pass %s" % (
                host, self._proxy, self._proxy_username, self._proxy_password))
        if self.timeout:
            return connections.HTTPProxyConnection(self._proxy, host,
                username=self._proxy_username, password=self._proxy_password,
                timeout=self.timeout)
        else:
            return connections.HTTPProxyConnection(self._proxy, host,
                username=self._proxy_username, password=self._proxy_password)

class SafeProxyTransport(ProxyTransport):
    def __init__(self, proxy, proxyUsername=None, proxyPassword=None,
            transfer=0, encoding=0, refreshCallback=None,
            progressCallback=None, trusted_certs=None, timeout=None):
        ProxyTransport.__init__(self, proxy,
            proxyUsername=proxyUsername, proxyPassword=proxyPassword,
            transfer=transfer, encoding=encoding,
            refreshCallback=refreshCallback,
            progressCallback=progressCallback,
            timeout=timeout)
        self.trusted_certs = []
        for certfile in (trusted_certs or []):
            self.add_trusted_cert(certfile)

    def add_trusted_cert(self, certfile):
        if not os.access(certfile, os.R_OK):
            raise ValueError("Certificate file %s is not accessible" % certfile)
        self.trusted_certs.append(certfile)

    def get_connection(self, host):
        if self.verbose:
            print("Connecting via https to %s proxy %s, username %s, pass %s" % (
                host, self._proxy, self._proxy_username, self._proxy_password))
        if self.timeout:
            return connections.HTTPSProxyConnection(self._proxy, host,
                username=self._proxy_username, password=self._proxy_password,
                trusted_certs=self.trusted_certs, timeout=self.timeout)
        else:
            return connections.HTTPSProxyConnection(self._proxy, host,
                username=self._proxy_username, password=self._proxy_password,
                trusted_certs=self.trusted_certs)

# ============================================================================
# Extended capabilities for transport
#
# We allow for the following possible headers:
#
# Content-Transfer-Encoding:
#       This header tells us how the POST data is encoded in what we read.
#       If it is not set, we assume plain text that can be passed along
#       without any other modification. If set, valid values are:
#       - binary : straight binary data
#       - base64 : will pass through base64 decoder to get the binary data
#
# Content-Encoding:
#       This header tells us what should we do with the binary data obtained
#       after acting on the Content-Transfer-Encoding header. Valid values:
#       - x-gzip : will need to pass through GNU gunzip-like to get plain
#                  text out
#       - x-zlib : this denotes the Python's own zlib bindings which are a
#                  datastream based on gzip, but not quite
#       - x-gpg : will need to pass through GPG to get out the text we want

# ============================================================================
# Input class to automate reading the posting from the network
# Having to work with environment variables blows, though
class Input:
    def __init__(self, headers=None, progressCallback=None, bufferSize=1024,
            max_mem_size=16384):
        self.transfer = None
        self.encoding = None
        self.type = None
        self.length = 0
        self.lang = "C"
        self.name = ""
        self.progressCallback = progressCallback
        self.bufferSize = bufferSize
        self.max_mem_size = max_mem_size

        if not headers:
            # we need to get them from environment
            if "HTTP_CONTENT_TRANSFER_ENCODING" in os.environ:
                self.transfer = os.environ["HTTP_CONTENT_TRANSFER_ENCODING"].lower()
            if "HTTP_CONTENT_ENCODING" in os.environ:
                self.encoding = os.environ["HTTP_CONTENT_ENCODING"].lower()
            if "CONTENT-TYPE" in os.environ:
                self.type = os.environ["CONTENT-TYPE"].lower()
            if "CONTENT_LENGTH" in os.environ:
                self.length = int(os.environ["CONTENT_LENGTH"])
            if "HTTP_ACCEPT_LANGUAGE" in os.environ:
                self.lang = os.environ["HTTP_ACCEPT_LANGUAGE"]
            if "HTTP_X_PACKAGE_FILENAME" in os.environ:
                self.name = os.environ["HTTP_X_PACKAGE_FILENAME"]
        else:
            # The stupid httplib screws up the headers from the HTTP repsonse
            # and converts them to lowercase. This means that we have to
            # convert to lowercase all the dictionary keys in case somebody calls
            # us with sane values --gaftonc (actually mimetools is the culprit)
            for header in headers.keys():
                value = headers[header]
                h = header.lower()
                if h == "content-length":
                    try:
                        self.length = int(value)
                    except ValueError:
                        self.length = 0
                elif h == "content-transfer-encoding":
                    # RFC 2045 #6.1: case insensitive
                    self.transfer = value.lower()
                elif h == "content-encoding":
                    # RFC 2616 #3.5: case insensitive
                    self.encoding = value.lower()
                elif h == "content-type":
                    # RFC 2616 #3.7: case insensitive
                    self.type = value.lower()
                elif h == "accept-language":
                    # RFC 2616 #3.10: case insensitive
                    self.lang = value.lower()
                elif h == "x-package-filename":
                    self.name = value

        self.io = None

    def read(self, fd = sys.stdin):
        # The octet-streams are passed right back
        if self.type == "application/octet-stream":
            return

        if self.length:
            # Read exactly the amount of data we were told
            self.io = _smart_read(fd, self.length,
                bufferSize=self.bufferSize,
                progressCallback=self.progressCallback,
                max_mem_size=self.max_mem_size)
        else:
            # Oh well, no clue; read until EOF (hopefully)
            self.io = _smart_total_read(fd)

        if not self.transfer or self.transfer == "binary":
            return
        elif self.transfer == "base64":
            import base64
            old_io = self.io
            old_io.seek(0, 0)
            self.io = SmartIO(max_mem_size=self.max_mem_size)
            base64.decode(old_io, self.io)
        else:
            raise NotImplementedError(self.transfer)

    def decode(self, fd = sys.stdin):
        # The octet-stream data are passed right back
        if self.type == "application/octet-stream":
            return InputStream(fd, self.length, self.name, close=fd.close)

        if not self.io:
            self.read(fd)

        # At this point self.io exists (the only case when self.read() does
        # not initialize self.io is when content-type is
        # "application/octet-stream" - and we already dealt with that case

        # We can now close the file descriptor
        if hasattr(fd, "close"):
            fd.close()

        # Now we have the binary goo
        if not self.encoding or self.encoding == "__plain":
            # all is fine.
            pass
        elif self.encoding in ("x-zlib", "deflate"):
            import zlib
            obj = zlib.decompressobj()
            self.io.seek(0, 0)
            data = obj.decompress(self.io.read()) + obj.flush()
            del obj
            self.length = len(data)
            self.io = SmartIO(max_mem_size=self.max_mem_size)
            self.io.write(data)
        elif self.encoding in ("x-gzip", "gzip"):
            import gzip
            self.io.seek(0, 0)
            gz = gzip.GzipFile(mode="rb", compresslevel = COMPRESS_LEVEL,
                               fileobj=self.io)
            data = gz.read()
            self.length = len(data)
            self.io = SmartIO(max_mem_size=self.max_mem_size)
            self.io.write(data)
        elif self.encoding == "x-gpg":
            # XXX: should be written
            raise NotImplementedError(self.transfer, self.encoding)
        else:
            raise NotImplementedError(self.transfer, self.encoding)

        # Play nicely and rewind the file descriptor
        self.io.seek(0, 0)
        return self.io

    def getlang(self):
        return self.lang

# Utility functions

def _smart_total_read(fd, bufferSize=1024, max_mem_size=16384):
    """
    Tries to read data from the supplied stream, and puts the results into a
    StmartIO object. The data will be in memory or in a temporary file,
    depending on how much it's been read
    Returns a SmartIO object
    """
    io = SmartIO(max_mem_size=max_mem_size)
    while 1:
        chunk = fd.read(bufferSize)
        if not chunk:
            # EOF reached
            break
        io.write(chunk)

    return io

def _smart_read(fd, amt, bufferSize=1024, progressCallback=None,
        max_mem_size=16384):
    # Reads amt bytes from fd, or until the end of file, whichever
    # occurs first
    # The function will read in memory if the amout to be read is smaller than
    # max_mem_size, or to a temporary file otherwise
    #
    # Unlike read(), _smart_read tries to return exactly the requested amount
    # (whereas read will return _up_to_ that amount). Reads from sockets will
    # usually reaturn less data, or the read can be interrupted
    #
    # Inspired by Greg Stein's httplib.py (the standard in python 2.x)
    #
    # support for progress callbacks added
    startTime = time.time()
    lastTime = startTime
    buf = SmartIO(max_mem_size=max_mem_size)

    origsize = amt
    while amt > 0:
        curTime = time.time()
        l = min(bufferSize, amt)
        chunk = fd.read(l)
        # read guarantees that len(chunk) <= l
        l = len(chunk)
        if not l:
            # Oops. Most likely EOF
            break

        # And since the original l was smaller than amt, we know amt >= 0
        amt = amt - l
        buf.write(chunk)
        if progressCallback is None:
            # No progress callback, so don't do fancy computations
            continue
        # We update the progress callback if:
        #  we haven't updated it for more than a secord, or
        #  it's the last read (amt == 0)
        if curTime - lastTime >= 1 or amt == 0:
            lastTime = curTime
            # use float() so that we force float division in the next step
            bytesRead = float(origsize - amt)
            # if amt == 0, on a fast machine it is possible to have
            # curTime - lastTime == 0, so add an epsilon to prevent a division
            # by zero
            speed = bytesRead / ((curTime - startTime) + .000001)
            if origsize == 0:
                secs = 0
            else:
                # speed != 0 because bytesRead > 0
                # (if bytesRead == 0 then origsize == amt, which means a read
                # of 0 length; but that's impossible since we already checked
                # that l is non-null
                secs = amt / speed
            progressCallback(bytesRead, origsize, speed, secs)

    # Now rewind the SmartIO
    buf.seek(0, 0)
    return buf

class InputStream:
    def __init__(self, fd, length, name = "<unknown>", close=None):
        self.fd = fd
        self.length = int(length)
        self.name = name
        # Close function
        self.close = close
    def __repr__(self):
        return "Input data is a stream of %d bytes for file %s.\n" % (self.length, self.name)


# ============================================================================
# Output class that will be used to build the temporary output string
class BaseOutput:
    # DEFINES for instances use
    # Content-Encoding
    ENCODE_NONE = 0
    ENCODE_GZIP = 1
    ENCODE_ZLIB = 2
    ENCODE_GPG  = 3

    # Content-Transfer-Encoding
    TRANSFER_NONE   = 0
    TRANSFER_BINARY = 1
    TRANSFER_BASE64 = 2

     # Mappings to make things easy
    encodings = [
         [None, "__plain"],     # ENCODE_NONE
         ["x-gzip", "gzip"],    # ENCODE_GZIP
         ["x-zlib", "deflate"], # ENCODE_ZLIB
         ["x-gpg"],             # ENCODE_GPG
    ]
    transfers = [
         None,          # TRANSFER_NONE
         "binary",      # TRANSFRE_BINARY
         "base64",      # TRANSFER_BASE64
    ]

    def __init__(self, transfer=0, encoding=0, connection=None, method="POST"):
        # Assumes connection is an instance of HTTPConnection
        if connection:
            if not isinstance(connection, connections.HTTPConnection):
                raise Exception("Expected an HTTPConnection type object")

        self.method = method

        # Store the connection
        self._connection = connection

        self.data = None
        self.headers = UserDictCase()
        self.encoding = 0
        self.transfer = 0
        self.transport_flags = {}
        # for authenticated proxies
        self.username = None
        self.password = None
        # Fields to keep the information about the server
        self._host = None
        self._handler = None
        self._http_type = None
        self._protocol = None
        # Initialize self.transfer and self.encoding
        self.set_transport_flags(transfer=transfer, encoding=encoding)

        # internal flags
        self.__processed = 0

    def set_header(self, name, arg):
        if type(arg) in [ type([]), type(()) ]:
            # Multi-valued header
            #
            # Per RFC 2616, section 4.2 (Message Headers):
            # Multiple message-header fields with the same field-name MAY be
            # present in a message if and only if the entire field-value for
            # the header field is defined as a comma-separated list [i.e.
            # #(values)]. It MUST be possible to combine the multiple header
            # fields into one "field-name: field-value" pair, without
            # changing the semantics of the message, by appending each
            # subsequent field-value to the first, each separated by a comma.
            self.headers[name] = ','.join(map(str, arg))
        else:
            self.headers[name] = str(arg)

    def clear_header(self, name):
        if name in self.headers:
            del self.headers[name]

    def process(self, data):
        # Assume straight text/xml
        self.data = data

        # Content-Encoding header
        if self.encoding == self.ENCODE_GZIP:
            import gzip
            encoding_name = self.encodings[self.ENCODE_GZIP][0]
            self.set_header("Content-Encoding", encoding_name)
            f = SmartIO(force_mem=1)
            gz = gzip.GzipFile(mode="wb", compresslevel=COMPRESS_LEVEL,
                               fileobj = f)
            if sys.version_info[0] == 3:
                gz.write(bstr(data))
            else:
                gz.write(sstr(data))
            gz.close()
            self.data = f.getvalue()
            f.close()
        elif self.encoding == self.ENCODE_ZLIB:
            import zlib
            encoding_name = self.encodings[self.ENCODE_ZLIB][0]
            self.set_header("Content-Encoding", encoding_name)
            obj = zlib.compressobj(COMPRESS_LEVEL)
            self.data = obj.compress(data) + obj.flush()
        elif self.encoding == self.ENCODE_GPG:
            # XXX: fix me.
            raise NotImplementedError(self.transfer, self.encoding)
            encoding_name = self.encodings[self.ENCODE_GPG][0]
            self.set_header("Content-Encoding", encoding_name)

        # Content-Transfer-Encoding header
        if self.transfer == self.TRANSFER_BINARY:
            transfer_name = self.transfers[self.TRANSFER_BINARY]
            self.set_header("Content-Transfer-Encoding", transfer_name)
            self.set_header("Content-Type", "application/binary")
        elif self.transfer == self.TRANSFER_BASE64:
            import base64
            transfer_name = self.transfers[self.TRANSFER_BASE64]
            self.set_header("Content-Transfer-Encoding", transfer_name)
            self.set_header("Content-Type", "text/base64")
            self.data = base64.encodestring(self.data)

        self.set_header("Content-Length", len(self.data))

        rpc_version = __version__
        if len(__version__.split()) > 1:
            rpc_version = __version__.split()[1]

        # other headers
        self.set_header("X-Transport-Info",
            'Extended Capabilities Transport (C) Red Hat, Inc (version %s)' %
            rpc_version)
        self.__processed = 1

    # reset the transport options
    def set_transport_flags(self, transfer=0, encoding=0, **kwargs):
        self.transfer = transfer
        self.encoding = encoding
        self.transport_flags.update(kwargs)

    def send_http(self, host, handler="/RPC2"):
        if not self.__processed:
            raise NotProcessed

        self._host = host

        if self._connection is None:
            raise Exception("No connection object found")
        self._connection.connect()
        # wrap self data into binary object, otherwise HTTPConnection.request
        # will encode it as ISO-8859-1 https://docs.python.org/3/library/http.client.html#httpconnection-objects
        self._connection.request(self.method, handler, body=bstr(self.data), headers=self.headers)

        response = self._connection.getresponse()

        if not self.response_acceptable(response):
            raise xmlrpclib.ProtocolError("%s %s" %
                (self._host, handler),
                response.status, response.reason, response.msg)

        # A response object has read() and close() methods, so we can safely
        # pass the whole object back
        return response.msg, response

    def response_acceptable(self, response):
        """Returns true if the response is acceptable"""
        if response.status == 200:
            return 1
        if response.status in (301, 302):
            return 1
        if response.status != 206:
            return 0
        # If the flag is not set, it's unacceptable
        if not self.transport_flags.get('allow_partial_content'):
            return 0
        if response.msg['Content-Type'] != 'application/octet-stream':
            # Don't allow anything else to be requested as a range, it could
            # break the XML parser
            return 0
        return 1

    def close(self):
        if self._connection:
            self._connection.close()
            self._connection = None

def lookupTransfer(transfer, strict=0):
    """Given a string or numeric representation of a transfer, return the
    transfer code"""
    if transfer is None:
        # Plain
        return 0
    if isinstance(transfer, IntType) and 0 <= transfer < len(Output.transfers):
        return transfer
    if isinstance(transfer, StringType):
        for i in range(len(Output.transfers)):
            if Output.transfers[i] == transfer.lower():
                return i
    if strict:
        raise ValueError("Unsupported transfer %s" % transfer)
    # Return default
    return 0

def lookupEncoding(encoding, strict=0):
    """Given a string or numeric representation of an encoding, return the
    encoding code"""
    if encoding is None:
        # Plain
        return 0
    if isinstance(encoding, IntType) and 0 <= encoding < len(Output.encodings):
        return encoding
    if isinstance(encoding, StringType):
        for i in range(len(Output.encodings)):
            if encoding.lower() in Output.encodings[i]:
                return i
    if strict:
        raise ValueError("Unsupported encoding %s" % encoding)
    # Return default
    return 0

Output = BaseOutput

# File object
class File:
    def __init__(self, file_obj, length = 0, name = None,
            progressCallback=None, bufferSize=16384):
        self.length = length
        self.file_obj = file_obj
        self.close = file_obj.close
        self.bufferSize=bufferSize
        self.name = ""
        if name:
            self.name = name[name.rfind("/")+1:]
        self.progressCallback = progressCallback

    def __len__(self):
        return self.length

    def read(self, amt=None):
        # If they want to read everything, use _smart_read
        if amt is None:
            fd = self._get_file()
            return fd.read()

        return self.file_obj.read(amt)

    def read_to_file(self, file):
        """Copies the contents of this File object into another file
        object"""
        fd = self._get_file()
        while 1:
            buf = fd.read(self.bufferSize)
            if not buf:
                break
            if sys.version_info[0] == 3:
                file.write(bstr(buf))
            else:
                file.write(sstr(buf))
        return file

    def _get_file(self):
        """Read everything into a temporary file and call the progress
        callbacks if the file length is defined, or just reads till EOF"""
        if self.length:
            io = _smart_read(self.file_obj, self.length,
                bufferSize=self.bufferSize,
                progressCallback=self.progressCallback)
            io.seek(0, 0)
        else:
            # Read everuthing - no callbacks involved
            io = _smart_total_read(self.file_obj, bufferSize=self.bufferSize)
        io.seek(0, 0)
        return io

    def __del__(self):
        if self.close:
            self.close()
            self.close = None
PK���Z��{	{	nonblocking.pynu�[���#
#
#

import select
import fcntl
import os

class NonBlockingFile:
    def __init__(self, fd):
        # Keep a copy of the file descriptor
        self.fd = fd
        fcntl.fcntl(self.fd.fileno(), fcntl.F_SETFL, os.O_NDELAY)
        # Set the callback-related stuff
        self.read_fd_set = []
        self.write_fd_set = []
        self.exc_fd_set = []
        self.user_data = None
        self.callback = None

    def set_callback(self, read_fd_set, write_fd_set, exc_fd_set,
            user_data, callback):
        self.read_fd_set = read_fd_set
        # Make the objects non-blocking
        for f in self.read_fd_set:
            fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NDELAY)

        self.write_fd_set = write_fd_set
        self.exc_fd_set = exc_fd_set
        self.user_data = user_data
        self.callback = callback

    def read(self, amt=0):
        while 1:
            status_changed = 0
            readfds = self.read_fd_set + [self.fd]
            writefds = self.write_fd_set
            excfds = self.exc_fd_set
            print("Calling select", readfds)
            readfds, writefds, excfds = select.select(readfds, writefds, excfds)
            print("Select returned", readfds, writefds, excfds)
            if self.fd in readfds:
                # Our own file descriptor has changed status
                # Mark this, but also try to call the callback with the rest
                # of the file descriptors that changed status
                status_changed = 1
                readfds.remove(self.fd)
            if self.callback and (readfds or writefds or excfds):
                self.callback(readfds, writefds, excfds, self.user_data)
            if status_changed:
                break
        print("Returning")
        return self.fd.read(amt)

    def write(self, data):
        return self.fd.write(data)

    def __getattr__(self, name):
        return getattr(self.fd, name)

def callback(r, w, e, user_data):
    print("Callback called", r, w, e)
    print(r[0].read())

if __name__ == '__main__':
    import socket

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("localhost", 5555))
    f = s.makefile()
    ss = NonBlockingFile(f)

    s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s2.connect(("localhost", 5556))
    f = s2.makefile()
    ss.set_callback([f], [], [], None, callback)

    xx = ss.read()
    print(len(xx))
PK���Z#4�RDDtb.pynu�[���#
# Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import sys

try:
    PY3 = sys.version_info.major >= 3
except AttributeError:
    PY3 = False

if PY3:
    def raise_with_tb(e):
        raise e
else:
    exec("""
def raise_with_tb(e):
    raise e, None, sys.exc_info()[2]
""")
PK���Z^�QGactions/__init__.pynuȯ��#!/usr/libexec/platform-python
PK���Ztf��actions/up2date_config.pynuȯ��#!/usr/libexec/platform-python

# Copyright (c) 1999--2018 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Adrian Likins <alikins@redhat.com>
#

import os
import re

from up2date_client import config

cfg = config.initUp2dateConfig()

__rhnexport__ = ["update", "get"]

argVerbose = 0


def update(configdict, cache_only=None):
    """Invoke this to change the ondisk configuration of up2date"""
    if cache_only:
        return (0, "no-ops for caching", {})
    if argVerbose > 1:
        print("called update_up2date_config")

    if type(configdict) != type({}):
        return (13, "Invalid arguments passed to function", {})

    unknownparams = []
    if cfg["disallowConfChanges"]:
        skipParams = cfg["disallowConfChanges"]
    else:
        skipParams = []
    for param in configdict.keys():
        # dont touch params in the skip params list
        if param in skipParams:
            continue
        # write out all params, even ones we dont know about
        # could be useful
        cfg.set(param, configdict[param])

    if len(unknownparams):
        return unknownparams

    cfg.save()

    return (0, "config updated", {})


def get(cache_only=None):
    """Reterieve the current configuration of up2date"""
    if cache_only:
        return (0, "no-ops for caching", {})
    if argVerbose > 1:
        print("called get_up2date_config")

    ret = {}
    for k in cfg.keys():
        ret[k] = cfg[k]
    return (0, "configuration retrived", {"data": ret})


def main():
    configdatatup = get()
    configdata = configdatatup[2]["data"]

    import time

    timestamp = time.time()

    configdata["timeStampTest"] = timestamp
    print(configdata)
    import pprint

    pprint.pprint(update(configdata))

    configdata["serverURL"] = "https://xmlrpc.cln.cloudlinux.com/XMLRPC/"
    configdata["serverURLipv6"] = "https://ipv6.xmlrpc.cln.cloudlinux.com/XMLRPC/"
    pprint.pprint(update(configdata))


if __name__ == "__main__":
    main()
PK���Zo��6��+actions/__pycache__/hardware.cpython-36.pycnu�[���3

ge8hI�@sRddlmZddlmZddlmZdZdgZd
dd�Zdd�Zed	krNe�dS)�)�hardware)�up2dateAuth)�	rpcServer�refresh_listNc	Csh|rddifStj�}tj�}tdkr.td�y|jjtj	�|�Wntd�ddifSddifS)	Nrzno-ops for caching�zCalled refresh_hardwarez3ERROR: sending hardware database for System Profile�z Error refreshing system hardwarezhardware list refreshed)
rZHardwarerZ	getServer�
argVerbose�printZregistrationZrefresh_hw_profilerZgetSystemId)Z
cache_onlyZhardwareList�s�r�/usr/lib/python3.6/hardware.pyrs


cCstt��dS)N)r	rrrrr�main(sr
�__main__)N)	Zup2date_clientrrrrZ
__rhnexport__rr
�__name__rrrr�<module>
s
PK���Z8f2p��1actions/__pycache__/up2date_config.cpython-36.pycnu�[���3

ge8h��@s^ddlZddlZddlmZej�ZddgZdZd
dd�Zddd�Z	dd�Z
ed	krZe
�dS)�N)�config�update�getcCs�|rddifStdkrtd�t|�ti�kr8ddifSg}tdrNtd}ng}x*|j�D]}||krjq\tj|||�q\Wt|�r�|Stj�ddifS)	z9Invoke this to change the ondisk configuration of up2daterzno-ops for caching�zcalled update_up2date_config�
z$Invalid arguments passed to functionZdisallowConfChangeszconfig updated)�
argVerbose�print�type�cfg�keys�set�lenZsave)Z
configdict�
cache_onlyZ
unknownparamsZ
skipParamsZparam�r�$/usr/lib/python3.6/up2date_config.pyrs$


cCsN|rddifStdkrtd�i}xtj�D]}t|||<q,Wddd|ifS)z.Reterieve the current configuration of up2daterzno-ops for cachingrzcalled get_up2date_configzconfiguration retrived�data)rrr
r)r�ret�krrrr3s
cCsjt�}|dd}ddl}|j�}||d<t|�ddl}|jt|��d|d<d|d<|jt|��dS)	N�rrZ
timeStampTestz)https://xmlrpc.cln.cloudlinux.com/XMLRPC/Z	serverURLz.https://ipv6.xmlrpc.cln.cloudlinux.com/XMLRPC/Z
serverURLipv6)r�timer�pprintr)Z
configdatatupZ
configdatarZ	timestamprrrr�main@sr�__main__)N)N)�os�reZup2date_clientrZinitUp2dateConfigr
Z
__rhnexport__rrrr�__name__rrrr�<module>s


PK���Z"�nм � 1actions/__pycache__/packages.cpython-36.opt-1.pycnu�[���3

.޾g.�@s�ddlZddlZddlZddlZddlmZddlmZddlmZddlm	Z	ej
�ZdZddd	d
ddd
gZ
d!dd�Zd"dd�Zd#dd�Zd$dd
�Zd%dd�Zd&dd	�Zdd�Zd'dd
�Zd(dd�Zggdddfdd�Zdd�Zdd �ZdS))�N)�
up2dateLog)�config)�rpmUtils)�rhnPackageInfoz/var/lib/up2date/dbtimestamp�update�remove�refresh_list�
fullUpdate�checkNeedUpdate�runTransaction�verifycsj|rddifSt|t�s"ddifStjd|�tddd�}|jj�j���fd	d
�|D�}t||d|d�S)z0We have been told that we should remove packagesrzno-ops for caching�
z$Invalid arguments passed to functionzCalled remove_packagesTF)�load_system_repo�load_available_reposcsg|]}t�|��qS�)�_package_tup2obj)�.0�tup)�	installedr�/usr/lib/python3.6/packages.py�
<listcomp>:szremove.<locals>.<listcomp>)r�
allow_erasing�
cache_only)	�
isinstance�list�log�	log_debug�	_dnf_base�sack�queryr�_dnf_transaction)�package_listr�base�	to_remover)rrr-s


cCs�t|t�sddifStjd|�tddd�}|jj�j�}|jj�j�}d}g}g}�x"|D�]}t	|�dkrx|j
d�|\}	}
}}}
|
dkr�|dkr�|dkr�|
dkr�|j|	d	�r�tjd
|	�q\|dkr�d}|j|	|
d�j�}t
||�}|�sd
t|�}tjd|�|j
|�q\x`|D]N}|j|�}|dk�rHtjdt|��Pn|dk�rtjdt|��P�qW|j
|�q\W|�s�|�r�dddj|�ddd�f}n
ddif}|jj�|j�|St|||d�S)z:We have been told that we should retrieve/install packagesr
z$Invalid arguments passed to functionz
Called updateT)rrN��)�namezPackage %s is already installedr)r&�archz,Package %s is not available for installationzE: zPackage %s already installedz6More recent version of package %s is already installed� z-Failed: Packages failed to install properly:
�
�1�package_install_failure)�versionr&z$Requested packages already installed)�installr)rrrrrrrr�	available�len�append�filterZlatestr�_package_tup2strZlog_meZevr_cmp�join�_plugins�_unload�closer )r!rr"rr.�errZerrmsgs�
to_install�packager&r,�release�epochr'�pkgsZ
requested_pkg�pkgZpkg_cmp�retrrrr?s`











cCs�|rddifStddd�}|jj�j�}|jj�j�}g}g}xd|ddd�D]P}|\}}	t||�}
|	dkr~|
r~|j|
�qP|	dkrP|
rPt||�}|j|�qPW|r�|r�dd	ifSt|||d|d
�S)z� Run a transaction on a group of packages.
        This was historicaly meant as generic call, but
        is only called for rollback.
    rzno-ops for cachingT)rr�packagesN�e�iz6Requested package actions have already been performed.)r-rrr)rrrrr.rr0r )Ztransaction_datarr"rr.r8r#Zpackage_objectr9�actionr=�newrrrr�s&



cCstddd�}t|d|d�S)z$ Update all packages on the system. T)rr)�full_updater)rr )�forcerr"rrrr	�sc	Cs�|rddifSi}d}tj�}|dr.|d}d|}ytj|�d}Wndd|fSytjt�d}Wnd}YnX||dkr�dd	|fS|dkr�yttd
�}|j�Wndd|fStdd
�S)z� Check if the locally installed package list changed, if
        needed the list is updated on the server
        In case of error avoid pushing data to stay safe
    rzno-ops for cachingz/var/lib/rpm�dbpathz%s/Packages�zunable to stat the rpm database�
zNrpm database not modified since last update (or package list recently updated)zw+z!unable to open the timestamp file�)�rhnsd)rZinitUp2dateConfig�os�stat�LAST_UPDATE_FILE�openr6r)	rJr�datarFZcfgZRPM_PACKAGE_FILEZdbtimeZlast�filerrrr
�s4




c	CsR|rddifStjd�d}ytj�Wntd�ddifSt�ddifS)	z3 push again the list of rpm packages to the server rzno-ops for cachingzCalled refresh_rpmlistNz8ERROR: refreshing remote package list for System Profile�zError refreshing package listzrpmlist refreshed)rrrZupdatePackageProfile�print�touch_time_stamp)rJrr>rrrr�s


cCs^yttd�}|j�WnddifStj�}ytjt||f�WnddtifSdS)Nzw+rz!unable to open the timestamp filez6unable to set the time stamp on the time stamp file %s)rNrMr6�timerK�utime)Zfile_d�trrrrS�s

rScCsvtjd�|rddifSi}d|d<d|d<tj|�\}}||d<t|�rld|d<d|d<||d	<d
d|fSdd|fS)
NzCalled packages.verifyrzno-ops for cachingzpackages.verifyr&r,Zverify_infoz packages.verify.missing_packages�missing_packages�+z-packages requested to be verified are missingzpackages verified)rrrZverifyPackagesr/)r?rrOr>rWrrrr�s


TcCs6tj�}|jjs|j�|r$|j�|jddd�|S)NT)rr)�dnfZBaser4ZpluginsZinit_pluginsZread_all_reposZ	fill_sack)rrr"rrrrsrFcCs�z�y�|r|j�n8x|D]}|r|j|�qWx|D]}|r6|j|�q6W|j|�tjd�t|j�svtj	j
d��|jjr�tjddd�|jjD��|j|jj�|jj
r�tjddd�|jj
D��|s�|j�W�ntj	jk
�r }z&i}d|d	<d
|d<dd
t|�|fSd}~Xn�tj	jk
�rf}z&i}d|d	<d|d<ddt|�|fSd}~Xn�tj	jk
�r�}z&i}d|d	<d|d<ddt|�|fSd}~Xn@tj	j
k
�r�}zd}	dt|�}
i}|	|
|fSd}~XnXWd|jj�|j�XddifS)zE
    command is an function excpecting dnf.Base() as an argument
    zDependencies Resolvedzempty transactionzDownloading and installing: cSsg|]}t|��qSr)�str)r�prrrr-sz$_dnf_transaction.<locals>.<listcomp>z
Removing: cSsg|]}t|��qSr)rZ)rr[rrrr1sr*r,r+r&r(z/Failed: Packages failed to install properly: %sNrZrpmremoveerrors�z%sZfailed_deps�z9Failed: packages requested raised dependency problems: %s�z)Error while executing packages action: %szUpdate Succeeded)r^)Zupgrade_allZpackage_installZpackage_removeZresolverrr/ZtransactionrY�
exceptions�ErrorZinstall_setZdownload_packagesZ
remove_setZdo_transactionZMarkingErrorrZZ
DepsolveErrorr4r5r6)r"r-rrDrrr=r@rOZstatus�messagerrrr s^







r c	Cs�|dd�\}}}}t|�dkr(|dnd}d|i}|dk	rPt|�dkrP||d<|dk	rlt|�dkrl||d<|dk	r�t|�dkr�t|�|d<|dk	r�t|�dkr�||d<|jf|�j�}|r�|dSdS)N�r&rr,r:r;r')r/�intr1Zrun)	�qrr&r,r:r;r'rr<rrrrUsrcCsD|dd�\}}}}}|sd}d||||f}|r>|d|7}|fS)z6 Create a package name from an rhn package tuple.
    N�0z%s-%s:%s-%sz.%sr)Zpackage_tup�n�v�rr@�aZpkginforrrr2gsr2)N)N)N)rN)NN)NN)N)TT)rKrTZdnf.exceptionsrYZdnf.cliZup2date_clientrrrrZinitLogrrMZ
__rhnexport__rrrr	r
rrSrrr rr2rrrr�<module>s:

E
 

)


=PK���Zh��kk1actions/__pycache__/systemid.cpython-36.opt-1.pycnu�[���3

ge8h��@sddlZdgZddd�ZdS)�N�disablecCsJ|rddifSd}t|d�}|jdtjtj��|f�|j�ddifS)z5We have been told that we should disable the systemidrzno-ops for cachingz/etc/sysconfig/rhn/disable�wz4Disable lock created on %s. RHN Server Message:

%s
z*systemId disable lock file has been writen)�open�write�timeZctime�close)ZmessageTextZ
cache_onlyZdisableFilePath�fd�r	�/usr/lib/python3.6/systemid.pyrs

)N)rZ
__rhnexport__rr	r	r	r
�<module>sPK���Z"�nм � +actions/__pycache__/packages.cpython-36.pycnu�[���3

.޾g.�@s�ddlZddlZddlZddlZddlmZddlmZddlmZddlm	Z	ej
�ZdZddd	d
ddd
gZ
d!dd�Zd"dd�Zd#dd�Zd$dd
�Zd%dd�Zd&dd	�Zdd�Zd'dd
�Zd(dd�Zggdddfdd�Zdd�Zdd �ZdS))�N)�
up2dateLog)�config)�rpmUtils)�rhnPackageInfoz/var/lib/up2date/dbtimestamp�update�remove�refresh_list�
fullUpdate�checkNeedUpdate�runTransaction�verifycsj|rddifSt|t�s"ddifStjd|�tddd�}|jj�j���fd	d
�|D�}t||d|d�S)z0We have been told that we should remove packagesrzno-ops for caching�
z$Invalid arguments passed to functionzCalled remove_packagesTF)�load_system_repo�load_available_reposcsg|]}t�|��qS�)�_package_tup2obj)�.0�tup)�	installedr�/usr/lib/python3.6/packages.py�
<listcomp>:szremove.<locals>.<listcomp>)r�
allow_erasing�
cache_only)	�
isinstance�list�log�	log_debug�	_dnf_base�sack�queryr�_dnf_transaction)�package_listr�base�	to_remover)rrr-s


cCs�t|t�sddifStjd|�tddd�}|jj�j�}|jj�j�}d}g}g}�x"|D�]}t	|�dkrx|j
d�|\}	}
}}}
|
dkr�|dkr�|dkr�|
dkr�|j|	d	�r�tjd
|	�q\|dkr�d}|j|	|
d�j�}t
||�}|�sd
t|�}tjd|�|j
|�q\x`|D]N}|j|�}|dk�rHtjdt|��Pn|dk�rtjdt|��P�qW|j
|�q\W|�s�|�r�dddj|�ddd�f}n
ddif}|jj�|j�|St|||d�S)z:We have been told that we should retrieve/install packagesr
z$Invalid arguments passed to functionz
Called updateT)rrN��)�namezPackage %s is already installedr)r&�archz,Package %s is not available for installationzE: zPackage %s already installedz6More recent version of package %s is already installed� z-Failed: Packages failed to install properly:
�
�1�package_install_failure)�versionr&z$Requested packages already installed)�installr)rrrrrrrr�	available�len�append�filterZlatestr�_package_tup2strZlog_meZevr_cmp�join�_plugins�_unload�closer )r!rr"rr.�errZerrmsgs�
to_install�packager&r,�release�epochr'�pkgsZ
requested_pkg�pkgZpkg_cmp�retrrrr?s`











cCs�|rddifStddd�}|jj�j�}|jj�j�}g}g}xd|ddd�D]P}|\}}	t||�}
|	dkr~|
r~|j|
�qP|	dkrP|
rPt||�}|j|�qPW|r�|r�dd	ifSt|||d|d
�S)z� Run a transaction on a group of packages.
        This was historicaly meant as generic call, but
        is only called for rollback.
    rzno-ops for cachingT)rr�packagesN�e�iz6Requested package actions have already been performed.)r-rrr)rrrrr.rr0r )Ztransaction_datarr"rr.r8r#Zpackage_objectr9�actionr=�newrrrr�s&



cCstddd�}t|d|d�S)z$ Update all packages on the system. T)rr)�full_updater)rr )�forcerr"rrrr	�sc	Cs�|rddifSi}d}tj�}|dr.|d}d|}ytj|�d}Wndd|fSytjt�d}Wnd}YnX||dkr�dd	|fS|dkr�yttd
�}|j�Wndd|fStdd
�S)z� Check if the locally installed package list changed, if
        needed the list is updated on the server
        In case of error avoid pushing data to stay safe
    rzno-ops for cachingz/var/lib/rpm�dbpathz%s/Packages�zunable to stat the rpm database�
zNrpm database not modified since last update (or package list recently updated)zw+z!unable to open the timestamp file�)�rhnsd)rZinitUp2dateConfig�os�stat�LAST_UPDATE_FILE�openr6r)	rJr�datarFZcfgZRPM_PACKAGE_FILEZdbtimeZlast�filerrrr
�s4




c	CsR|rddifStjd�d}ytj�Wntd�ddifSt�ddifS)	z3 push again the list of rpm packages to the server rzno-ops for cachingzCalled refresh_rpmlistNz8ERROR: refreshing remote package list for System Profile�zError refreshing package listzrpmlist refreshed)rrrZupdatePackageProfile�print�touch_time_stamp)rJrr>rrrr�s


cCs^yttd�}|j�WnddifStj�}ytjt||f�WnddtifSdS)Nzw+rz!unable to open the timestamp filez6unable to set the time stamp on the time stamp file %s)rNrMr6�timerK�utime)Zfile_d�trrrrS�s

rScCsvtjd�|rddifSi}d|d<d|d<tj|�\}}||d<t|�rld|d<d|d<||d	<d
d|fSdd|fS)
NzCalled packages.verifyrzno-ops for cachingzpackages.verifyr&r,Zverify_infoz packages.verify.missing_packages�missing_packages�+z-packages requested to be verified are missingzpackages verified)rrrZverifyPackagesr/)r?rrOr>rWrrrr�s


TcCs6tj�}|jjs|j�|r$|j�|jddd�|S)NT)rr)�dnfZBaser4ZpluginsZinit_pluginsZread_all_reposZ	fill_sack)rrr"rrrrsrFcCs�z�y�|r|j�n8x|D]}|r|j|�qWx|D]}|r6|j|�q6W|j|�tjd�t|j�svtj	j
d��|jjr�tjddd�|jjD��|j|jj�|jj
r�tjddd�|jj
D��|s�|j�W�ntj	jk
�r }z&i}d|d	<d
|d<dd
t|�|fSd}~Xn�tj	jk
�rf}z&i}d|d	<d|d<ddt|�|fSd}~Xn�tj	jk
�r�}z&i}d|d	<d|d<ddt|�|fSd}~Xn@tj	j
k
�r�}zd}	dt|�}
i}|	|
|fSd}~XnXWd|jj�|j�XddifS)zE
    command is an function excpecting dnf.Base() as an argument
    zDependencies Resolvedzempty transactionzDownloading and installing: cSsg|]}t|��qSr)�str)r�prrrr-sz$_dnf_transaction.<locals>.<listcomp>z
Removing: cSsg|]}t|��qSr)rZ)rr[rrrr1sr*r,r+r&r(z/Failed: Packages failed to install properly: %sNrZrpmremoveerrors�z%sZfailed_deps�z9Failed: packages requested raised dependency problems: %s�z)Error while executing packages action: %szUpdate Succeeded)r^)Zupgrade_allZpackage_installZpackage_removeZresolverrr/ZtransactionrY�
exceptions�ErrorZinstall_setZdownload_packagesZ
remove_setZdo_transactionZMarkingErrorrZZ
DepsolveErrorr4r5r6)r"r-rrDrrr=r@rOZstatus�messagerrrr s^







r c	Cs�|dd�\}}}}t|�dkr(|dnd}d|i}|dk	rPt|�dkrP||d<|dk	rlt|�dkrl||d<|dk	r�t|�dkr�t|�|d<|dk	r�t|�dkr�||d<|jf|�j�}|r�|dSdS)N�r&rr,r:r;r')r/�intr1Zrun)	�qrr&r,r:r;r'rr<rrrrUsrcCsD|dd�\}}}}}|sd}d||||f}|r>|d|7}|fS)z6 Create a package name from an rhn package tuple.
    N�0z%s-%s:%s-%sz.%sr)Zpackage_tup�n�v�rr@�aZpkginforrrr2gsr2)N)N)N)rN)NN)NN)N)TT)rKrTZdnf.exceptionsrYZdnf.cliZup2date_clientrrrrZinitLogrrMZ
__rhnexport__rrrr	r
rrSrrr rr2rrrr�<module>s:

E
 

)


=PK���Z8f2p��7actions/__pycache__/up2date_config.cpython-36.opt-1.pycnu�[���3

ge8h��@s^ddlZddlZddlmZej�ZddgZdZd
dd�Zddd�Z	dd�Z
ed	krZe
�dS)�N)�config�update�getcCs�|rddifStdkrtd�t|�ti�kr8ddifSg}tdrNtd}ng}x*|j�D]}||krjq\tj|||�q\Wt|�r�|Stj�ddifS)	z9Invoke this to change the ondisk configuration of up2daterzno-ops for caching�zcalled update_up2date_config�
z$Invalid arguments passed to functionZdisallowConfChangeszconfig updated)�
argVerbose�print�type�cfg�keys�set�lenZsave)Z
configdict�
cache_onlyZ
unknownparamsZ
skipParamsZparam�r�$/usr/lib/python3.6/up2date_config.pyrs$


cCsN|rddifStdkrtd�i}xtj�D]}t|||<q,Wddd|ifS)z.Reterieve the current configuration of up2daterzno-ops for cachingrzcalled get_up2date_configzconfiguration retrived�data)rrr
r)r�ret�krrrr3s
cCsjt�}|dd}ddl}|j�}||d<t|�ddl}|jt|��d|d<d|d<|jt|��dS)	N�rrZ
timeStampTestz)https://xmlrpc.cln.cloudlinux.com/XMLRPC/Z	serverURLz.https://ipv6.xmlrpc.cln.cloudlinux.com/XMLRPC/Z
serverURLipv6)r�timer�pprintr)Z
configdatatupZ
configdatarZ	timestamprrrr�main@sr�__main__)N)N)�os�reZup2date_clientrZinitUp2dateConfigr
Z
__rhnexport__rrrr�__name__rrrr�<module>s


PK���ZP	�%%/actions/__pycache__/errata.cpython-36.opt-1.pycnu�[���3

.޾g�	�@sfddlmZddlmZddlmZddlmZdgZdZdd�Zdd
d�Z	dd�Z
ed
krbe
�d	S)�)�	rhnserver)�up2dateAuth)�pkgUtils)�packages�update�cCstj�}|jjtj�|�S)N)rZ	RhnServerZerrataZ
getErrataInforZgetSystemId)Z	errata_id�s�r	�/usr/lib/python3.6/errata.py�__getErrataInfosrNc
Cs�g}t|�tg�tf�gkr"|g}x|D]}t|�}||}q(Wi}i}x4tjdd�D]$}|||d|d<|||d<qVWi}t|d�dk�rx�|D]|}d|d|df|kr�|||d|d<q�d|d|kr�|||d|d<q�|dd	kr�|d|kr�|||d<q�Wn*x(|D] }|d|k�r"|||d<�q"Wt|j��}|gk�r�i}	d
|	d<d|	d<||	d
<dd|	fStj||�S)N�)ZgetArch�nameZarchr�z%s%sz%snoarchZnoarch�0�versionzerrata.update.no_packagesZerratas�'z*No packages from that errata are available)	�typerrZgetInstalledPackageList�len�list�valuesrr)
ZerrataidlistZ
cache_onlyZpackagelistZerrataidZtmpListZcurrent_packages_with_archZcurrent_packages�p�u�datar	r	r
rsB



cCsttdg��dS)Ni�ie)�printrr	r	r	r
�mainPsr�__main__)N)Zup2date_clientrrrZrhn.actionsrZ
__rhnexport__ZACTION_VERSIONrrr�__name__r	r	r	r
�<module>
s
7PK���Zo��6��1actions/__pycache__/hardware.cpython-36.opt-1.pycnu�[���3

ge8hI�@sRddlmZddlmZddlmZdZdgZd
dd�Zdd�Zed	krNe�dS)�)�hardware)�up2dateAuth)�	rpcServer�refresh_listNc	Csh|rddifStj�}tj�}tdkr.td�y|jjtj	�|�Wntd�ddifSddifS)	Nrzno-ops for caching�zCalled refresh_hardwarez3ERROR: sending hardware database for System Profile�z Error refreshing system hardwarezhardware list refreshed)
rZHardwarerZ	getServer�
argVerbose�printZregistrationZrefresh_hw_profilerZgetSystemId)Z
cache_onlyZhardwareList�s�r�/usr/lib/python3.6/hardware.pyrs


cCstt��dS)N)r	rrrrr�main(sr
�__main__)N)	Zup2date_clientrrrrZ
__rhnexport__rr
�__name__rrrr�<module>
s
PK���Z�%O=��(actions/__pycache__/rhnsd.cpython-36.pycnu�[���3

ge8hS�@srddlZdgZd
dd�Zddd�Zedkrneed��eedd	��eed
d	d��eed	d��eed��dS)�N�	configurecCs�d}t|d�}|j�}d}d}g}xB|D]:}|j�}	|j|	�|	jdd�}
|
ddkrZ|}|d}q(W|dkrzd|||<|j�t|d�}d	j|�}|j|�|j�dS)
Nz/etc/sysconfig/rhn/rhnsd�rr�=�ZINTERVALzINTERVAL=%s�w�
)�open�	readlines�strip�append�split�close�join�write)�interval�
cache_onlyZrhnsdconfig�fd�lines�count�indexZtmplines�lineZtmp�comps�contents�r�/usr/lib/python3.6/rhnsd.py�
__configRhnsds(





rcCsb|rddifSd}|rByt|�d}Wntk
r@ddifSX|rXtjd�}|d}d|ifS)	Nrzno-ops for caching�zrhnsd interval config updated. �%z)Could not modify /etc/sysconfig/rhn/rhnsdz'/sbin/service rhnsd restart > /dev/nullzrhnsd restarted)r�IOError�os�system)r�restartr�msgZrcrrrr(s

�__main__Z240Z361rZ127)r!Z192)N)NNN)rZ
__rhnexport__rr�__name__�printrrrr�<module>s

PK���Zh��kk+actions/__pycache__/systemid.cpython-36.pycnu�[���3

ge8h��@sddlZdgZddd�ZdS)�N�disablecCsJ|rddifSd}t|d�}|jdtjtj��|f�|j�ddifS)z5We have been told that we should disable the systemidrzno-ops for cachingz/etc/sysconfig/rhn/disable�wz4Disable lock created on %s. RHN Server Message:

%s
z*systemId disable lock file has been writen)�open�write�timeZctime�close)ZmessageTextZ
cache_onlyZdisableFilePath�fd�r	�/usr/lib/python3.6/systemid.pyrs

)N)rZ
__rhnexport__rr	r	r	r
�<module>sPK���Z�A����)actions/__pycache__/reboot.cpython-36.pycnu�[���3

ge8hN�@s^ddlZdgZddlmZddlmZej�Zej�ZdZ	d
dd�Z
dd�Zed	krZe�dS)�N�reboot)�
up2dateLog)�config�c
Cs�|rddifStdr ddifStj�}ddi}dtj�d	d
}|s�y4|rftjdddd
d|g�ntjdddd|g�Wn"tk
r�d|d<dd|fSXtjd�dd|fS)Nrzno-ops for cachingZnoReboot�&z*Up2date is configured not to allow reboots�version�0zReboot of system "�z'" initiated by Spacewalk reboot action.z/sbin/shutdownz-rz-kz+3zreboot.reboot.shutdown_failed�name�"z Could not execute /sbin/shutdownzRebooting the system nowzReboot sucessfully started)�cfg�os�fork�uname�execvp�OSError�logZlog_me)�testZ
cache_only�pid�dataZreboot_message�r�/usr/lib/python3.6/reboot.pyrs"


cCsttdd��dS)Nr	)r)�printrrrrr�main1sr�__main__)NN)
r
Z
__rhnexport__Zup2date_clientrrZinitUp2dateConfigrZinitLogrZACTION_VERSIONrr�__name__rrrr�<module>	s
PK���Z�A����/actions/__pycache__/reboot.cpython-36.opt-1.pycnu�[���3

ge8hN�@s^ddlZdgZddlmZddlmZej�Zej�ZdZ	d
dd�Z
dd�Zed	krZe�dS)�N�reboot)�
up2dateLog)�config�c
Cs�|rddifStdr ddifStj�}ddi}dtj�d	d
}|s�y4|rftjdddd
d|g�ntjdddd|g�Wn"tk
r�d|d<dd|fSXtjd�dd|fS)Nrzno-ops for cachingZnoReboot�&z*Up2date is configured not to allow reboots�version�0zReboot of system "�z'" initiated by Spacewalk reboot action.z/sbin/shutdownz-rz-kz+3zreboot.reboot.shutdown_failed�name�"z Could not execute /sbin/shutdownzRebooting the system nowzReboot sucessfully started)�cfg�os�fork�uname�execvp�OSError�logZlog_me)�testZ
cache_only�pid�dataZreboot_message�r�/usr/lib/python3.6/reboot.pyrs"


cCsttdd��dS)Nr	)r)�printrrrrr�main1sr�__main__)NN)
r
Z
__rhnexport__Zup2date_clientrrZinitUp2dateConfigrZinitLogrZACTION_VERSIONrr�__name__rrrr�<module>	s
PK���Z�%O=��.actions/__pycache__/rhnsd.cpython-36.opt-1.pycnu�[���3

ge8hS�@srddlZdgZd
dd�Zddd�Zedkrneed��eedd	��eed
d	d��eed	d��eed��dS)�N�	configurecCs�d}t|d�}|j�}d}d}g}xB|D]:}|j�}	|j|	�|	jdd�}
|
ddkrZ|}|d}q(W|dkrzd|||<|j�t|d�}d	j|�}|j|�|j�dS)
Nz/etc/sysconfig/rhn/rhnsd�rr�=�ZINTERVALzINTERVAL=%s�w�
)�open�	readlines�strip�append�split�close�join�write)�interval�
cache_onlyZrhnsdconfig�fd�lines�count�indexZtmplines�lineZtmp�comps�contents�r�/usr/lib/python3.6/rhnsd.py�
__configRhnsds(





rcCsb|rddifSd}|rByt|�d}Wntk
r@ddifSX|rXtjd�}|d}d|ifS)	Nrzno-ops for caching�zrhnsd interval config updated. �%z)Could not modify /etc/sysconfig/rhn/rhnsdz'/sbin/service rhnsd restart > /dev/nullzrhnsd restarted)r�IOError�os�system)r�restartr�msgZrcrrrr(s

�__main__Z240Z361rZ127)r!Z192)N)NNN)rZ
__rhnexport__rr�__name__�printrrrr�<module>s

PK���Z�j��qq+actions/__pycache__/__init__.cpython-36.pycnu�[���3

ge8h�@sdS)N�rrr�/usr/lib/python3.6/__init__.py�<module>sPK���Z�j��qq1actions/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

ge8h�@sdS)N�rrr�/usr/lib/python3.6/__init__.py�<module>sPK���ZP	�%%)actions/__pycache__/errata.cpython-36.pycnu�[���3

.޾g�	�@sfddlmZddlmZddlmZddlmZdgZdZdd�Zdd
d�Z	dd�Z
ed
krbe
�d	S)�)�	rhnserver)�up2dateAuth)�pkgUtils)�packages�update�cCstj�}|jjtj�|�S)N)rZ	RhnServerZerrataZ
getErrataInforZgetSystemId)Z	errata_id�s�r	�/usr/lib/python3.6/errata.py�__getErrataInfosrNc
Cs�g}t|�tg�tf�gkr"|g}x|D]}t|�}||}q(Wi}i}x4tjdd�D]$}|||d|d<|||d<qVWi}t|d�dk�rx�|D]|}d|d|df|kr�|||d|d<q�d|d|kr�|||d|d<q�|dd	kr�|d|kr�|||d<q�Wn*x(|D] }|d|k�r"|||d<�q"Wt|j��}|gk�r�i}	d
|	d<d|	d<||	d
<dd|	fStj||�S)N�)ZgetArch�nameZarchr�z%s%sz%snoarchZnoarch�0�versionzerrata.update.no_packagesZerratas�'z*No packages from that errata are available)	�typerrZgetInstalledPackageList�len�list�valuesrr)
ZerrataidlistZ
cache_onlyZpackagelistZerrataidZtmpListZcurrent_packages_with_archZcurrent_packages�p�u�datar	r	r
rsB



cCsttdg��dS)Ni�ie)�printrr	r	r	r
�mainPsr�__main__)N)Zup2date_clientrrrZrhn.actionsrZ
__rhnexport__ZACTION_VERSIONrrr�__name__r	r	r	r
�<module>
s
7PK���Z_��ZZactions/reboot.pynuȯ��#!/usr/libexec/platform-python

# Client code for Update Agent
# Copyright (c) 1999--2018 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Adrian Likins <alikins@redhat.com
#

import os

__rhnexport__ = [
    'reboot']

from up2date_client import up2dateLog
from up2date_client import config

cfg = config.initUp2dateConfig()
log = up2dateLog.initLog()

# action version we understand
ACTION_VERSION = 2

def reboot(test=None, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})

    if cfg['noReboot']:
        return (38, "Up2date is configured not to allow reboots", {})

    pid = os.fork()
    data = {'version': '0'}
    reboot_message = 'Reboot of system "' + os.uname()[1] + '" initiated by Spacewalk reboot action.'
    if not pid:
        try:
            if test:
                os.execvp("/sbin/shutdown", ['/sbin/shutdown','-r','-k', '+3', reboot_message])
            else:
                os.execvp("/sbin/shutdown", ['/sbin/shutdown','-r', '+3', reboot_message])
        except OSError:
            data['name'] = "reboot.reboot.shutdown_failed"
            return (34, "Could not execute /sbin/shutdown", data)

    log.log_me("Rebooting the system now")
    # no point in waiting around

    return (0, "Reboot sucessfully started", data)


def main():
    print(reboot(test=1))

if __name__ == "__main__":
    main()
PK���Z`��___actions/rhnsd.pynuȯ��#!/usr/libexec/platform-python

# Copyright (c) 1999--2018 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Adrian Likins <alikins@redhat.com>
#

import os

# mark this module as acceptable
__rhnexport__ = [
    'configure',
]

def __configRhnsd(interval, cache_only=None):
    rhnsdconfig = "/etc/sysconfig/rhn/rhnsd"
    fd = open(rhnsdconfig, "r")
    lines = fd.readlines()
    count = 0
    index = None
    tmplines = []
    for line in lines:
        tmp = line.strip()
        tmplines.append(tmp)
        comps = tmp.split("=", 1)
        if comps[0] == "INTERVAL":
            index = count
        count = count + 1

    if index != None:
        tmplines[index] = "INTERVAL=%s" % interval

    fd.close()
    fd = open(rhnsdconfig, "w")
    contents = "\n".join(tmplines)
    fd.write(contents)
    fd.close()


def configure(interval=None, restart=None, cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})
    msg = ""
    if interval:
        try:
            __configRhnsd(interval)
            msg = "rhnsd interval config updated. "
        except IOError:
            # i'm runing as root, must of been chattr'ed.
            # i'll resist the erge to unchattr this file
            return (37,"Could not modify /etc/sysconfig/rhn/rhnsd", {})

    if restart:
        rc = os.system("/sbin/service rhnsd restart > /dev/null")
        msg = msg + "rhnsd restarted"

    return(0,  msg, {})


if __name__ == "__main__":
    print(configure("240"))

    print(configure("361", 1))

    print(configure("127", restart=1))

    print(configure(restart=1))

    print(configure("192"))
PK���Zˣ����actions/systemid.pynuȯ��#!/usr/libexec/platform-python
#
# Copyright (c) 1999--2018 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Adrian Likins <alikins@redhat.com>

import time


# mark this module as acceptable
__rhnexport__ = [
    'disable',
]

def disable(messageText, cache_only=None):
    """We have been told that we should disable the systemid"""
    if cache_only:
        return (0, "no-ops for caching", {})

    disableFilePath = "/etc/sysconfig/rhn/disable"
    # open and shut off
    fd = open(disableFilePath, "w")
    fd.write("Disable lock created on %s. RHN Server Message:\n\n%s\n" % (
        time.ctime(time.time()), messageText))
    fd.close()

    # done if we survived this long
    return(0, "systemId disable lock file has been writen", {})

PK���Z=K'�..actions/packages.pynu�[���#
# Copyright (c) 2015--2017 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import os
import time

import dnf.exceptions
import dnf.cli

from up2date_client import up2dateLog
from up2date_client import config
from up2date_client import rpmUtils
from up2date_client import rhnPackageInfo

log = up2dateLog.initLog()

# file used to keep track of the next time rhn_check
# is allowed to update the package list on the server
LAST_UPDATE_FILE = "/var/lib/up2date/dbtimestamp"

# mark this module as acceptable
__rhnexport__ = [
    'update',
    'remove',
    'refresh_list',
    'fullUpdate',
    'checkNeedUpdate',
    'runTransaction',
    'verify'
]


def remove(package_list, cache_only=None):
    """We have been told that we should remove packages"""
    if cache_only:
        return (0, "no-ops for caching", {})

    if not isinstance(package_list, list):
        return (13, "Invalid arguments passed to function", {})

    log.log_debug("Called remove_packages", package_list)

    # initialize dnf
    base = _dnf_base(load_system_repo=True, load_available_repos=False)
    installed = base.sack.query().installed()
    to_remove = [_package_tup2obj(installed, tup) for tup in package_list]
    return _dnf_transaction(base, remove=to_remove, allow_erasing=True,
                            cache_only=cache_only)


def update(package_list, cache_only=None):
    """We have been told that we should retrieve/install packages"""
    if not isinstance(package_list, list):
        return (13, "Invalid arguments passed to function", {})

    log.log_debug("Called update", package_list)

    # initialize dnf
    base = _dnf_base(load_system_repo=True, load_available_repos=True)
    installed = base.sack.query().installed()
    available = base.sack.query().available()

    # skip already installed packages
    err = None
    errmsgs = []
    to_install = []
    for package in package_list:
        if len(package) < 5:
            package.append('')

        (name, version, release, epoch, arch) = package
        if version == '' and release == '' \
           and epoch == '' and arch == '' \
           and installed.filter(name=name):
            log.log_debug('Package %s is already installed' % name)
            continue

        if epoch == '':
            epoch = 0

        pkgs = installed.filter(name=name, arch=arch).latest()
        requested_pkg = _package_tup2obj(available, package)

        if not requested_pkg:
                err = 'Package %s is not available for installation' \
                      % _package_tup2str(package)
                log.log_me('E: ', err)
                errmsgs.append(err)
                continue

        for pkg in pkgs:
            pkg_cmp = pkg.evr_cmp(requested_pkg)
            if pkg_cmp == 0:
                log.log_debug('Package %s already installed'
                              % _package_tup2str(package))
                break
            elif pkg_cmp > 0:
                log.log_debug('More recent version of package %s is already installed'
                              % _package_tup2str(package))
                break
        else:
            to_install.append(requested_pkg)

    # Don't proceed further with empty list,
    # since this would result into an empty yum transaction
    if not to_install:
        if err:
            ret = (32, "Failed: Packages failed to install properly:\n" + '\n'.join(errmsgs),
                   {'version': '1', 'name': "package_install_failure"})
        else:
            ret = (0, "Requested packages already installed", {})
        # workaround for RhBug:1218071
        base._plugins._unload()
        base.close()
        return ret

    return _dnf_transaction(base, install=to_install, cache_only=cache_only)


def runTransaction(transaction_data, cache_only=None):
    """ Run a transaction on a group of packages.
        This was historicaly meant as generic call, but
        is only called for rollback.
    """
    if cache_only:
        return (0, "no-ops for caching", {})

    # initialize dnf
    base = _dnf_base(load_system_repo=True, load_available_repos=True)
    installed = base.sack.query().installed()
    available = base.sack.query().available()
    to_install = []
    to_remove = []
    for package_object in transaction_data['packages'][:]:
        [package, action] = package_object
        pkg = _package_tup2obj(installed, package)

        if action == 'e' and pkg:
            to_remove.append(pkg)
        elif action == 'i' and not pkg:
            new = _package_tup2obj(available, package)
            to_install.append(new)

    # Don't proceed further with empty package lists
    if not to_install and not to_remove:
        return (0, "Requested package actions have already been performed.", {})

    return _dnf_transaction(base, install=to_install, remove=to_remove,
                            allow_erasing=True, cache_only=cache_only)


def fullUpdate(force=0, cache_only=None):
    """ Update all packages on the system. """
    base = _dnf_base(load_system_repo=True, load_available_repos=True)
    return _dnf_transaction(base, full_update=True, cache_only=cache_only)


# The following functions are the same as the old up2date ones.
def checkNeedUpdate(rhnsd=None, cache_only=None):
    """ Check if the locally installed package list changed, if
        needed the list is updated on the server
        In case of error avoid pushing data to stay safe
    """
    if cache_only:
        return (0, "no-ops for caching", {})

    data = {}
    dbpath = "/var/lib/rpm"
    cfg = config.initUp2dateConfig()
    if cfg['dbpath']:
        dbpath = cfg['dbpath']
    RPM_PACKAGE_FILE = "%s/Packages" % dbpath

    try:
        dbtime = os.stat(RPM_PACKAGE_FILE)[8]  # 8 is st_mtime
    except:
        return (0, "unable to stat the rpm database", data)
    try:
        last = os.stat(LAST_UPDATE_FILE)[8]
    except:
        last = 0

    # Never update the package list more than once every 1/2 hour
    if last >= (dbtime - 10):
        return (0, "rpm database not modified since last update (or package "
                "list recently updated)", data)

    if last == 0:
        try:
            file = open(LAST_UPDATE_FILE, "w+")
            file.close()
        except:
            return (0, "unable to open the timestamp file", data)

    # call the refresh_list action with a argument so we know it's
    # from rhnsd
    return refresh_list(rhnsd=1)


def refresh_list(rhnsd=None, cache_only=None):
    """ push again the list of rpm packages to the server """
    if cache_only:
        return (0, "no-ops for caching", {})
    log.log_debug("Called refresh_rpmlist")

    ret = None

    try:
        rhnPackageInfo.updatePackageProfile()
    except:
        print("ERROR: refreshing remote package list for System Profile")
        return (20, "Error refreshing package list", {})

    touch_time_stamp()
    return (0, "rpmlist refreshed", {})


def touch_time_stamp():
    try:
        file_d = open(LAST_UPDATE_FILE, "w+")
        file_d.close()
    except:
        return (0, "unable to open the timestamp file", {})
    # Never update the package list more than once every hour.
    t = time.time()
    try:
        os.utime(LAST_UPDATE_FILE, (t, t))

    except:
        return (0, "unable to set the time stamp on the time stamp file %s"
                % LAST_UPDATE_FILE, {})


def verify(packages, cache_only=None):
    log.log_debug("Called packages.verify")
    if cache_only:
        return (0, "no-ops for caching", {})

    data = {}
    data['name'] = "packages.verify"
    data['version'] = 0
    ret, missing_packages = rpmUtils.verifyPackages(packages)

    data['verify_info'] = ret

    if len(missing_packages):
        data['name'] = "packages.verify.missing_packages"
        data['version'] = 0
        data['missing_packages'] = missing_packages
        return(43, "packages requested to be verified are missing", data)

    return (0, "packages verified", data)


def _dnf_base(load_system_repo=True, load_available_repos=True):
    # initialize dnf
    base = dnf.Base()

    if not base._plugins.plugins:
        base.init_plugins()
    if load_available_repos:
        base.read_all_repos()
    base.fill_sack(load_system_repo=True, load_available_repos=True)
    return base


def _dnf_transaction(base, install=[], remove=[], full_update=False,
                     allow_erasing=False, cache_only=None):
    """
    command is an function excpecting dnf.Base() as an argument
    """
    try:
        if full_update:
            base.upgrade_all()
        else:
            for pkg in install:
                if pkg:
                    base.package_install(pkg)
            for pkg in remove:
                if pkg:
                    base.package_remove(pkg)

        base.resolve(allow_erasing)
        log.log_debug("Dependencies Resolved")
        if not len(base.transaction):
            raise dnf.exceptions.Error('empty transaction')
        if base.transaction.install_set:
            log.log_debug("Downloading and installing: ",
                          [str(p) for p in base.transaction.install_set])
            base.download_packages(base.transaction.install_set)
        if base.transaction.remove_set:
            log.log_debug("Removing: ",
                          [str(p) for p in base.transaction.remove_set])
        if not cache_only:
            base.do_transaction()

    except dnf.exceptions.MarkingError as e:
        data = {}
        data['version'] = "1"
        data['name'] = "package_install_failure"

        return (32, "Failed: Packages failed to install "
                "properly: %s" % str(e), data)
    except dnf.exceptions.MarkingError as e:
        data = {}
        data['version'] = 0
        data['name'] = "rpmremoveerrors"

        return (15, "%s" % str(e), data)
    except dnf.exceptions.DepsolveError as e:
        data = {}
        data["version"] = "1"
        data["name"] = "failed_deps"
        return (18, "Failed: packages requested raised "
                "dependency problems: %s" % str(e), data)
    except dnf.exceptions.Error as e:
        status = 6,
        message = "Error while executing packages action: %s" % str(e)
        data = {}
        return (status, message, data)
    finally:
        # workaround for RhBug:1218071
        base._plugins._unload()
        base.close()

    return (0, "Update Succeeded", {})


def _package_tup2obj(q, tup):
    (name, version, release, epoch) = tup[:4]
    arch = tup[4] if len(tup) > 4 else None
    query = {'name': name}
    if version is not None and len(version) > 0:
        query['version'] = version
    if release is not None and len(release) > 0:
        query['release'] = release
    if epoch is not None and len(epoch) > 0:
        query['epoch'] = int(epoch)
    if arch is not None and len(arch) > 0:
        query['arch'] = arch
    pkgs = q.filter(**query).run()
    if pkgs:
        return pkgs[0]
    return None


def _package_tup2str(package_tup):
    """ Create a package name from an rhn package tuple.
    """
    n, v, r, e, a = package_tup[:]
    if not e:
        e = '0'
    pkginfo = '%s-%s:%s-%s' % (n, e, v, r)
    if a:
        pkginfo += '.%s' % (a)
    return (pkginfo,)

PK���Z\WL�UUactions/hardware.pynuȯ��#!/usr/libexec/platform-python


# Copyright (c) 1999--2018 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Adrian Likins <alikins@redhat.com>


# imports are a bit weird here to avoid name collions on "harware"
from up2date_client import hardware
from up2date_client import up2dateAuth
from up2date_client import rpcServer
argVerbose = 0

__rhnexport__ = [
    'refresh_list' ]

# resync hardware information with the server profile
def refresh_list(cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})

    # read all hardware in
    hardwareList = hardware.Hardware()

    s = rpcServer.getServer()

    if argVerbose > 1:
        print("Called refresh_hardware")

    try:
        s.registration.refresh_hw_profile(up2dateAuth.getSystemId(),
                                          hardwareList)
    except:
        print("ERROR: sending hardware database for System Profile")
        return (12, "Error refreshing system hardware", {})

    return (0, "hardware list refreshed", {})

def main():
        print(refresh_list())

if __name__ == "__main__":
        main()
PK���Z�6���	�	actions/errata.pynu�[���#
# Client code for Update Agent
# Copyright (c) 1999--2016 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Adrian Likins <alikins@redhat.com
#

# This file is copied from yum-rhn-plugin

from up2date_client import rhnserver
from up2date_client import up2dateAuth
from up2date_client import pkgUtils
from rhn.actions import packages

__rhnexport__ = [
    'update']

# action version we understand
ACTION_VERSION = 2

def __getErrataInfo(errata_id):
    s = rhnserver.RhnServer()
    return s.errata.getErrataInfo(up2dateAuth.getSystemId(), errata_id)

def update(errataidlist, cache_only=None):
    packagelist = []

    if type(errataidlist) not in [type([]), type(())]:
        errataidlist = [ errataidlist ]

    for errataid in errataidlist:
        tmpList = __getErrataInfo(errataid)
        packagelist = packagelist + tmpList

    current_packages_with_arch = {}
    current_packages ={}
    for p in pkgUtils.getInstalledPackageList(getArch=1):
        current_packages_with_arch[p['name'] + p['arch']] = p
        current_packages[p['name']] = p

    u = {}
    # only update packages that are currently installed
    # since an "applicable errata" may only contain some packages
    # that actually apply. aka kernel. Fun fun fun.

    if len(packagelist[0]) > 4:
        # Newer sats send down arch, filter using name+arch
        for p in packagelist:
            if "%s%s" % (p[0], p[4]) in current_packages_with_arch:
                u[p[0] + p[4]] = p
            elif "%snoarch" % p[0] in current_packages_with_arch:
                u[p[0] + p[4]] = p
            elif p[4] == "noarch" and p[0] in current_packages:
                u[p[0]] = p
    else:
        # 5.2 and older sats + hosted dont send arch
        for p in packagelist:
            if p[0] in current_packages:
                u[p[0]] = p


    # XXX: Fix me - once we keep all errata packages around,
    # this is the WRONG thing to do - we want to keep the specific versions
    # that the user has asked for.
    packagelist = list(u.values())

    if packagelist == []:
        data = {}
        data['version'] = "0"
        data['name'] = "errata.update.no_packages"
        data['erratas'] = errataidlist

        return (39,
                "No packages from that errata are available",
                data)

    return packages.update(packagelist, cache_only)


def main():
        print(update([23423423]))


if __name__ == "__main__":
        main()
PK���Zf��**-__pycache__/UserDictCase.cpython-36.opt-1.pycnu�[���3

U��Z��@sbyddlmZddlmZWn0ek
rLddlmZeZddlmZYnXGdd�de�ZdS)�)�UserDict)�
StringType)�reducec@s�eZdZd"dd�Zdd�Zdd�Zdd	�ZeZd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�ZdS)#�UserDictCaseNcCsi|_tj||�dS)N)�kcaser�__init__)�self�data�r
�"/usr/lib/python3.6/UserDictCase.pyrszUserDictCase.__init__cCst|t�r|j�S|SdS)z. Return the lower() of key if it is a string. N)�
isinstancer�lower)r�keyr
r
rZ__lower_string#s
zUserDictCase.__lower_stringcCs"|j|�}||j|<||j|<dS)N)�_UserDictCase__lower_stringr	r)rr�valueZlkeyr
r
r�__setitem__+s

zUserDictCase.__setitem__cCs|j|�}|j|S)N)rr	)rrr
r
r�__getitem__0s
zUserDictCase.__getitem__cCs|j|�}|j|=|j|=dS)N)rr	r)rrr
r
r�__delitem__6s
zUserDictCase.__delitem__cCs|j|�}||jkS)N)rr	)rrr
r
r�__contains__;s
zUserDictCase.__contains__cCs
|jj�S)N)r�values)rr
r
r�keys?szUserDictCase.keyscCs|j�j�S)N)�get_hash�items)rr
r
rrBszUserDictCase.itemscCs||kS)Nr
)rrr
r
r�has_keyEszUserDictCase.has_keycCs|jj�|jj�dS)N)r	�clearr)rr
r
rrIs
zUserDictCase.clearcCst|jfdd�|jj�i�S)NcSs|j||d|di�p|S)Nr�)�update)�a�tZhcr
r
r�<lambda>Osz'UserDictCase.get_hash.<locals>.<lambda>)rrr	r)rr
r
rrNszUserDictCase.get_hashcCs|j�S)N)r)rr
r
r�__getstate__SszUserDictCase.__getstate__cCs|j|�dS)N)r)r�stater
r
r�__setstate__WszUserDictCase.__setstate__cCs|j�S)N)r)rr
r
r�dict[szUserDictCase.dictcCs"x|j�D]\}}|||<q
WdS)N)r)rr#�k�vr
r
rr^szUserDictCase.updatecCs
t|j�S)N)�iterr	)rr
r
r�__iter__dszUserDictCase.__iter__)N)�__name__�
__module__�__qualname__rrrr�getrrrrrrrr r"r#rr'r
r
r
rrs"
rN)	r�typesr�ImportError�collections�bytes�	functoolsrrr
r
r
r�<module>sPK���Z�kull%__pycache__/i18n.cpython-36.opt-1.pycnu�[���3

U��Z��@sPddlmZyejdkZWnek
r2dZYnXdd�Zdd�Zdd	�Zd
S)�)�version_info�FcCs@tr"t|t�r|St|ddd�Snt|t�r0|St|dd�SdS)N�utf8�ignore)�errors)�PY3�
isinstance�strZunicode)�obj�r�/usr/lib/python3.6/i18n.py�ustrs

r
cCsDtr"t|t�r|St|ddd�Snt|t�r0|St|jdd��SdS)Nrr)r)rr�bytesr	�encode)r
rrr�bstr&s

rcCsDtr"t|t�r|St|ddd�Snt|t�r0|St|jdd��SdS)Nrr)r)rrr	r)r
rrr�sstr2s

rN)�sysr�majorr�AttributeErrorr
rrrrrr�<module>s
PK���Z����#__pycache__/tb.cpython-36.opt-1.pycnu�[���3

U��ZD�@sLddlZyejjdkZWnek
r0dZYnXer@dd�Zned�dS)�N�FcCs|�dS)N�)�err�/usr/lib/python3.6/tb.py�
raise_with_tbsrz<
def raise_with_tb(e):
    raise e, None, sys.exc_info()[2]
)�sys�version_info�majorZPY3�AttributeErrorr�execrrrr�<module>s

PK���Z�h��J�J%__pycache__/transports.cpython-36.pycnu�[���3

�U�f�|�@sZddlZddlZddlZddlmZddlmZmZddlm	Z	ddl
mZy ddlZddl
mZmZmZWn*ek
r�ddljZeZeZeZYnXdZdZGd	d
�d
e�ZGdd�dej�ZGd
d�de�ZGdd�de�ZGdd�de�ZGdd�d�Zd%dd�Z d&dd�Z!Gdd�d�Z"Gdd�d�Z#d'dd �Z$d(d!d"�Z%e#Z&Gd#d$�d$�Z'dS))�N)�connections)�sstr�bstr)�SmartIO)�UserDictCase)�IntType�
StringType�ListTypezI2.8.62.8.6-8.module_el8.10.0+6858+3ddf28328.module_el8.10.0+6858+3ddf2832�c@seZdZdS)�NotProcessedN)�__name__�
__module__�__qualname__�rr� /usr/lib/python3.6/transports.pyr$src@s�eZdZdeZd'dd�Zd(dd�Zd	d
�Zdd�Zd
d�Z	d)dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd*dd�Zdd �Zd!d"�Zd#d$�Zd%d&�ZdS)+�	Transportzrhn.rpclib.py/%srNcCszd|_ddd�|_|j||d�t�|_d|_d|_d|_d|_||_	||_
d|_d|_d|_
d|_d|_||_||_dS)NFr)�transfer�encoding�POSTi@)Z_use_builtin_types�_transport_flags�set_transport_flagsr�_headers�verbose�
connection�method�_lang�refreshCallback�progressCallback�
bufferSize�
headers_in�response_status�response_reason�_redirectedZ
_use_datetime�timeout)�selfrrrrZuse_datetimer#rrr�__init__*s"zTransport.__init__�@cCs||_||_dS)N)rr)r$rrrrr�set_progress_callback?szTransport.set_progress_callbackcCs
||_dS)N)r)r$rrrr�set_refresh_callbackDszTransport.set_refresh_callbackcCs|dkrd}||_dS)Ni@)r)r$rrrr�set_buffer_sizeJszTransport.set_buffer_sizecCs|dkrtd|��||_dS)N�GETrzUnknown request method %s)r*r)�IOErrorr)r$rrrr�
set_methodRszTransport.set_methodcKs<|jj|�|dk	r||jd<|dk	r0||jd<|j�dS)Nrr)r�update�validate_transport_flags)r$rr�kwargsrrrrXs

zTransport.set_transport_flagscCs
|jj�S)N)r�copy)r$rrr�get_transport_flagscszTransport.get_transport_flagscCsH|jjd�}t|dd�}||jd<|jjd�}t|dd�}||jd<dS)Nr�)�strictr)r�get�lookupTransfer�lookupEncoding)r$rrrrrr.fs
z"Transport.validate_transport_flagscCs@t|�tg�tf�gkr.dd�|D�|j|<nt|�|j|<dS)NcSsg|]}t|��qSr)�str)�.0�arrr�
<listcomp>tsz(Transport.set_header.<locals>.<listcomp>)�typerr7)r$�name�argrrr�
set_headerqszTransport.set_headercCsF||jkr&|j|}t|t�s4|g}ng}|j|<|jt|��dS)N)r�
isinstancer	�appendr7)r$r<r=Zvlistrrr�
add_headerxs


zTransport.add_headercCs|jj�dS)N)r�clear)r$rrr�
clear_headers�szTransport.clear_headerscCs8|jrtd|f�|jr*tj||jd�Stj|�SdS)NzConnecting via http to %s)r#)r�printr#r�HTTPConnection)r$�hostrrr�get_connection�s
zTransport.get_connectioncCsX||_|j|�\}}}|sg}|j|�}|j|j�|jrJ|j|jd�t||jd�}|jf|j	�|j
d|j�x*t|jj
��|D]\}	}
|j
|	|
�q�W|j
dd�|j|�xd
D]}|j|�q�W|j||�\}}
|j�rtd�x$|j
�D]\}	}
td	|	|
f�q�W|
jdk�r6|d|_|
j|_dS||_|
j|_|
j|_|j|
|�S)Nr2)rrz
User-AgentzContent-Typeztext/xml�Content-Length�HostzIncoming headers:z	%s : %s�-�.ZLocation)rHrI)rJrK)r�
get_host_inforGZset_user_agent�
user_agentZset_debuglevel�Outputrrrr>�listr�items�process�clear_header�	send_httprD�statusr"r r�reasonr!�_process_response)r$rF�handlerZrequest_bodyr�
extra_headers�x509rZreq�header�value�h�headers�fdrrr�request�s<



zTransport.requestcCsbt|j|j|jd�}|j|�}t|t�rPt|j|j	|j
|j|jd�}|j|_|S|j�|j|�S)N)rr)rr)
�Inputrrr�decoder?�InputStream�Filer^�lengthr<�close�parse_response)r$r^rZresp�frrrrV�s




zTransport._process_responsecCs|jS)N)r")r$rrr�
redirected�szTransport.redirectedcCsf|j�\}}x@|jd�}|sP|jr,|j�|jr@tdt|��|j|�qW|j�|j�|j�S)Nizbody:)Z	getparser�readrrrD�reprZfeedre)r$rg�p�u�responserrrrf�s
zTransport.parse_responsecCs
||_dS)N)r)r$�langrrr�setlang�szTransport.setlang)rrNNNN)r&)NN)r)rr
r�__version__rMr%r'r(r)r,rr1r.r>rArCrGr_rVrhrfrorrrrr's&


	
8rc@s&eZdZd	dd�Zdd�Zdd�ZdS)
�
SafeTransportrNcCs<tj||||||d�g|_x|p$gD]}|j|�q&WdS)N)rrr#)rr%�
trusted_certs�add_trusted_cert)r$rrrrrrr#�certfilerrrr%�s
zSafeTransport.__init__cCs*tj|tj�std|��|jj|�dS)Nz%Certificate file %s is not accessible)�os�access�R_OK�
ValueErrorrrr@)r$rtrrrrsszSafeTransport.add_trusted_certcCsR|j|�\}}}|jr$td|f�|jr>tj||j|jd�Stj||jd�SdS)NzConnecting via https to %s)rrr#)rr)rLrrDr#rZHTTPSConnectionrr)r$rFrXrYrrrrGszSafeTransport.get_connection)rrNNNN)rr
rr%rsrGrrrrrq�s
rqc@seZdZddd�Zdd�ZdS)�ProxyTransportNrc		Cs,tj||||||d�||_||_||_dS)N)rrr#)rr%�_proxy�_proxy_username�_proxy_password)	r$�proxy�
proxyUsername�
proxyPasswordrrrrr#rrrr%s
zProxyTransport.__init__cCs^|jr td||j|j|jf�|jrBtj|j||j|j|jd�Stj|j||j|jd�SdS)Nz8Connecting via http to %s proxy %s, username %s, pass %s)�username�passwordr#)r�r�)rrDrzr{r|r#rZHTTPProxyConnection)r$rFrrrrG#s


zProxyTransport.get_connection)NNrrNNN)rr
rr%rGrrrrrys
ryc@s&eZdZd	dd�Zdd�Zdd�ZdS)
�SafeProxyTransportNrc
CsBtj|||||||||	d�	g|_x|p*gD]}
|j|
�q,WdS)N)r~rrrrrr#)ryr%rrrs)r$r}r~rrrrrrrr#rtrrrr%0szSafeProxyTransport.__init__cCs*tj|tj�std|��|jj|�dS)Nz%Certificate file %s is not accessible)rurvrwrxrrr@)r$rtrrrrs=sz#SafeProxyTransport.add_trusted_certcCsf|jr td||j|j|jf�|jrFtj|j||j|j|j|jd�Stj|j||j|j|jd�SdS)Nz9Connecting via https to %s proxy %s, username %s, pass %s)r�r�rrr#)r�r�rr)	rrDrzr{r|r#rZHTTPSProxyConnectionrr)r$rFrrrrGBs

z!SafeProxyTransport.get_connection)NNrrNNNN)rr
rr%rsrGrrrrr�/s

r�c@s:eZdZddd�Zejfdd�Zejfdd	�Zd
d�ZdS)
r`N��@cCs�d|_d|_d|_d|_d|_d|_||_||_||_|s�dt	j
krTt	j
dj�|_dt	j
krnt	j
dj�|_dt	j
kr�t	j
dj�|_dt	j
kr�tt	j
d�|_dt	j
kr�t	j
d|_d	t	j
kr�t	j
d	|_n�x�|j
�D]�}||}|j�}|d
k�r&yt|�|_Wntk
�r"d|_YnXq�|dk�r<|j�|_q�|dk�rR|j�|_q�|d
k�rh|j�|_q�|dk�r~|j�|_q�|dkr�||_q�Wd|_dS)Nr�C�ZHTTP_CONTENT_TRANSFER_ENCODINGZHTTP_CONTENT_ENCODINGzCONTENT-TYPEZCONTENT_LENGTHZHTTP_ACCEPT_LANGUAGEZHTTP_X_PACKAGE_FILENAMEzcontent-lengthzcontent-transfer-encodingzcontent-encodingzcontent-typezaccept-languagezx-package-filename)rrr;rdrnr<rr�max_mem_sizeru�environ�lower�int�keysrx�io)r$r]rrr�rZr[r\rrrr%hsR











zInput.__init__cCs�|jdkrdS|jr2t||j|j|j|jd�|_n
t|�|_|jsN|jdkrRdS|jdkr�ddl	}|j}|j
dd�t|jd�|_|j||j�n
t
|j��dS)Nzapplication/octet-stream)rrr��binary�base64r)r�)r;rd�_smart_readrrr�r��_smart_total_readrr��seekrra�NotImplementedError)r$r^r�Zold_iorrrri�s"


z
Input.readcCs^|jdkr t||j|j|jd�S|js0|j|�t|d�rB|j�|jsT|jdkrVn�|jdkr�ddl	}|j
�}|jjdd�|j|jj��|j
�}~t|�|_t|jd�|_|jj|�n�|jdk�r ddl}|jjdd�|jdt|jd�}|j�}t|�|_t|jd�|_|jj|�n*|jd
k�r<t|j|j��nt|j|j��|jjdd�|jS)Nzapplication/octet-stream)rere�__plain�x-zlib�deflater)r��x-gzip�gzip�rb)�mode�
compresslevel�fileobjzx-gpg)r�r�)r�r�)r;rbrdr<rer�ri�hasattrr�zlibZ
decompressobjr�Z
decompress�flush�lenrr��writer��GzipFile�COMPRESS_LEVELr�r)r$r^r��obj�datar��gzrrrra�s>






zInput.decodecCs|jS)N)rn)r$rrr�getlang�sz
Input.getlang)NNr�r�)	rr
rr%�sys�stdinrirar�rrrrr`gs

70r`��@cCs.t|d�}x|j|�}|sP|j|�qW|S)z�
    Tries to read data from the supplied stream, and puts the results into a
    StmartIO object. The data will be in memory or in a temporary file,
    depending on how much it's been read
    Returns a SmartIO object
    )r�)rrir�)r^rr�r��chunkrrrr��s

r�cCs�tj�}|}t|d�}|}x�|dkr�tj�}	t||�}
|j|
�}t|�}
|
sNP||
}|j|�|dkrjq|	|dks~|dkr|	}t||�}||	|d}
|dkr�d}n||
}||||
|�qW|jdd�|S)N)r�rr2g���ư>)�timer�minrir�r��floatr�)r^�amtrrr�Z	startTimeZlastTime�bufZorigsizeZcurTime�lr�Z	bytesReadZspeedZsecsrrrr�s2




r�c@seZdZddd�Zdd�ZdS)rb�	<unknown>NcCs ||_t|�|_||_||_dS)N)r^r�rdr<re)r$r^rdr<rerrrr%=s
zInputStream.__init__cCsd|j|jfS)Nz0Input data is a stream of %d bytes for file %s.
)rdr<)r$rrr�__repr__CszInputStream.__repr__)r�N)rr
rr%r�rrrrrb<s
rbc@s�eZdZdZdZdZdZdZdZdZ	ddgddgd	d
gdggZ
ddd
gZd dd�Zdd�Z
dd�Zdd�Zd!dd�Zd"dd�Zdd�Zdd�ZdS)#�
BaseOutputrr2��Nr�zx-gzipr�zx-zlibr�zx-gpgr�r�rcCs�|rt|tj�std��||_||_d|_t�|_d|_	d|_
i|_d|_d|_
d|_d|_d|_d|_|j||d�d|_dS)Nz&Expected an HTTPConnection type objectr)rr)r?rrE�	Exceptionr�_connectionr�rr]rr�transport_flagsr�r��_hostZ_handlerZ
_http_typeZ	_protocolr�_BaseOutput__processed)r$rrrrrrrr%cs$zBaseOutput.__init__cCsBt|�tg�tf�gkr0djtt|��|j|<nt|�|j|<dS)N�,)r;�join�mapr7r])r$r<r=rrrr>�szBaseOutput.set_headercCs||jkr|j|=dS)N)r])r$r<rrrrR�s
zBaseOutput.clear_headercCs�||_|j|jkr�ddl}|j|jd}|jd|�tdd�}|jdt|d�}t	j
ddkrn|jt|��n|jt
|��|j�|j�|_|j�n�|j|jkr�ddl}|j|jd}|jd|�|jt�}|j|�|j�|_n8|j|jk�r t|j|j��|j|jd}|jd|�|j|jk�rT|j|j}|jd|�|jd	d
�nH|j|jk�r�ddl}	|j|j}|jd|�|jd	d�|	j|j�|_|jdt|j��t}
ttj��dk�r�tj�d}
|jd
d|
�d|_ dS)NrzContent-Encodingr2)Z	force_mem�wb)r�r�r�r�zContent-Transfer-EncodingzContent-Typezapplication/binaryztext/base64zContent-LengthzX-Transport-Infoz=Extended Capabilities Transport (C) Red Hat, Inc (version %s))!r�r�ENCODE_GZIPr��	encodingsr>rr�r�r��version_infor�rrre�getvalue�ENCODE_ZLIBr�Zcompressobj�compressr��
ENCODE_GPGr�r�TRANSFER_BINARY�	transfers�TRANSFER_BASE64r�Zencodestringr�rp�splitr�)r$r�r�Z
encoding_namergr�r�r�Z
transfer_namer�Zrpc_versionrrrrQ�sT



zBaseOutput.processcKs||_||_|jj|�dS)N)rrr�r-)r$rrr/rrrr�szBaseOutput.set_transport_flags�/RPC2cCs�|js
t�||_|jdkr"td��|jj�|jj|j|t|j	�|j
d�|jj�}|j|�s~t
jd|j|f|j|j|j��|j|fS)NzNo connection object found)Zbodyr]z%s %s)r�rr�r�r�Zconnectr_rrr�r]Zgetresponse�response_acceptable�	xmlrpclibZ
ProtocolErrorrTrU�msg)r$rFrWrmrrrrS�s




zBaseOutput.send_httpcCsP|jdkrdS|jd
krdS|jdkr*dS|jjd�s:dS|jdd	krLdSdS)z*Returns true if the response is acceptable��r2�-�.��rZallow_partial_contentzContent-Typezapplication/octet-stream)r�r�)rTr�r4r�)r$rmrrrr��s


zBaseOutput.response_acceptablecCs|jr|jj�d|_dS)N)r�re)r$rrrre�s
zBaseOutput.close)rrNr)rr)r�)rr
rZENCODE_NONEr�r�r�Z
TRANSFER_NONEr�r�r�r�r%r>rRrQrrSr�rerrrrr�Is,
8

r�cCs�|dkrdSt|t�r8d|ko.ttj�knr8|St|t�rpx,tttj��D]}tj||j�krR|SqRW|r�td|��dS)zTGiven a string or numeric representation of a transfer, return the
    transfer codeNrzUnsupported transfer %s)	r?rr�rNr�r�ranger�rx)rr3�irrrr5s(
r5cCs�|dkrdSt|t�r8d|ko.ttj�knr8|St|t�rpx,tttj��D]}|j�tj|krR|SqRW|r�td|��dS)zUGiven a string or numeric representation of an encoding, return the
    encoding codeNrzUnsupported encoding %s)	r?rr�rNr�rr�r�rx)rr3r�rrrr6s(
r6c@s@eZdZddd�Zdd�Zddd	�Zd
d�Zdd
�Zdd�ZdS)rcrN�@cCsF||_||_|j|_||_d|_|r<||jd�dd�|_||_dS)Nr��/r2)rd�file_objrerr<�rfindr)r$r�rdr<rrrrrr%&sz
File.__init__cCs|jS)N)rd)r$rrr�__len__1szFile.__len__cCs$|dkr|j�}|j�S|jj|�S)N)�	_get_filerir�)r$r�r^rrrri4sz	File.readcCsP|j�}xB|j|j�}|sPtjddkr:|jt|��q
|jt|��q
W|S)zHCopies the contents of this File object into another file
        objectrr�)r�rirr�r�r�rr)r$�filer^r�rrr�read_to_file<szFile.read_to_filecCsL|jr,t|j|j|j|jd�}|jdd�nt|j|jd�}|jdd�|S)z�Read everything into a temporary file and call the progress
        callbacks if the file length is defined, or just reads till EOF)rrr)r)rdr�r�rrr�r�)r$r�rrrr�Js

zFile._get_filecCs|jr|j�d|_dS)N)re)r$rrr�__del__XszFile.__del__)rNNr�)N)	rr
rr%r�rir�r�r�rrrrrc%s


rc)r�r�)r�Nr�)r)r)(rur�r�ZrhnrZrhn.i18nrrZrhn.SmartIOrZrhn.UserDictCaserr��typesrrr	�ImportErrorZ
xmlrpc.clientZclientr��bytesrOrpr�r�rrrqryr�r`r�r�rbr�r5r6rNrcrrrr�<module>
sD

V8	

;
8

PK���Zf��**'__pycache__/UserDictCase.cpython-36.pycnu�[���3

U��Z��@sbyddlmZddlmZWn0ek
rLddlmZeZddlmZYnXGdd�de�ZdS)�)�UserDict)�
StringType)�reducec@s�eZdZd"dd�Zdd�Zdd�Zdd	�ZeZd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�ZdS)#�UserDictCaseNcCsi|_tj||�dS)N)�kcaser�__init__)�self�data�r
�"/usr/lib/python3.6/UserDictCase.pyrszUserDictCase.__init__cCst|t�r|j�S|SdS)z. Return the lower() of key if it is a string. N)�
isinstancer�lower)r�keyr
r
rZ__lower_string#s
zUserDictCase.__lower_stringcCs"|j|�}||j|<||j|<dS)N)�_UserDictCase__lower_stringr	r)rr�valueZlkeyr
r
r�__setitem__+s

zUserDictCase.__setitem__cCs|j|�}|j|S)N)rr	)rrr
r
r�__getitem__0s
zUserDictCase.__getitem__cCs|j|�}|j|=|j|=dS)N)rr	r)rrr
r
r�__delitem__6s
zUserDictCase.__delitem__cCs|j|�}||jkS)N)rr	)rrr
r
r�__contains__;s
zUserDictCase.__contains__cCs
|jj�S)N)r�values)rr
r
r�keys?szUserDictCase.keyscCs|j�j�S)N)�get_hash�items)rr
r
rrBszUserDictCase.itemscCs||kS)Nr
)rrr
r
r�has_keyEszUserDictCase.has_keycCs|jj�|jj�dS)N)r	�clearr)rr
r
rrIs
zUserDictCase.clearcCst|jfdd�|jj�i�S)NcSs|j||d|di�p|S)Nr�)�update)�a�tZhcr
r
r�<lambda>Osz'UserDictCase.get_hash.<locals>.<lambda>)rrr	r)rr
r
rrNszUserDictCase.get_hashcCs|j�S)N)r)rr
r
r�__getstate__SszUserDictCase.__getstate__cCs|j|�dS)N)r)r�stater
r
r�__setstate__WszUserDictCase.__setstate__cCs|j�S)N)r)rr
r
r�dict[szUserDictCase.dictcCs"x|j�D]\}}|||<q
WdS)N)r)rr#�k�vr
r
rr^szUserDictCase.updatecCs
t|j�S)N)�iterr	)rr
r
r�__iter__dszUserDictCase.__iter__)N)�__name__�
__module__�__qualname__rrrr�getrrrrrrrr r"r#rr'r
r
r
rrs"
rN)	r�typesr�ImportError�collections�bytes�	functoolsrrr
r
r
r�<module>sPK���Z�u4�G�G!__pycache__/rpclib.cpython-36.pycnu�[���3

�U�f�^�@s`dZddlZddlZddlZddlmZddlmZddlm	Z	y<ddl
Z
ddlmZm
Z
mZmZmZmZddlmZmZWnFek
r�ddljZ
eZeZ
eZeZeZeZddlmZmZYnXdZd	d
�Zdd�Z d
d�Z!Gdd�de"�Z#Gdd�d�Z$Gdd�de$�Z%Gdd�de&�Z'Gdd�de&�Z(dd�Z)Gdd�d�Z*Gdd�de*�Z+dd �Z,dS)!zI2.8.62.8.6-8.module_el8.10.0+6858+3ddf28328.module_el8.10.0+6858+3ddf2832�N)�
transports)�sstr)�UserDictCase)�ListType�	TupleType�
StringType�UnicodeType�DictType�DictionaryType)�	splittype�	splithost�c	Cs"ytjtj|�dSdSdS)z5 Returns true if n is IPv6 address, false otherwise. TFN)�socketZ	inet_ptonZAF_INET6)�n�r�/usr/lib/python3.6/rpclib.py�
check_ipv6.s
rc	Cs�|jdd�}d}d}d}d}t|�dkr^|d}|djdd�}|d}t|�dkrf|d}n|d}|ddkr�tjdtd�\}}|jd�jd	�}n6t|�r�|}n(|jdd�}|d}t|�dkr�|d}||||fS)
z| Function used to split host information in an URL per RFC 2396
        handle full hostname like user:passwd@host:port
    �@�N�r�:�[z(?<=\]):�])�split�len�reZip_port�lstrip�rstripr)	Z
hoststring�l�hostZport�userZpasswdZhostportZuserinfo�arrrrr�
split_host6s,
r"cCs8|dkrtd��|jdd�}t|�dkr0|d}t|�S)NzHost string cannot be nullz://rr)�
ValueErrorrrr")�proxyr!rrr�get_proxy_info[sr%c@seZdZdS)�MalformedURIErrorN)�__name__�
__module__�__qualname__rrrrr&gsr&c	@seZdZdZejZejZej	Z
ejZd;dd�Z
d<dd�Zdd	�Zd
d�Zdd
�Zdd�Zd=dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�ZeZd'd(�Zd>d)d*�Z d+d,�Z!d-d.�Z"d/d0�Z#d1d2�Z$d3d4�Z%d?d5d6�Z&d7d8�Z'd9d:�Z(dS)@�Servera7uri [,options] -> a logical connection to an XML-RPC server

    uri is the connection point on the server, given as
    scheme://host/target.

    The standard implementation always supports the "http" scheme.  If
    SSL socket support is available (Python 2.0), it also supports
    "https".

    If the target part and the slash preceding it are both omitted,
    "/RPC2" is assumed.

    The following options can be given as keyword arguments:

        transport: a transport factory
        encoding: the request encoding (default is UTF-8)
        verbose: verbosity level
        proxy: use an HTTP proxy
        username: username for authenticated HTTP proxy
        password: password for authenticated HTTP proxy

    All 8-bit strings passed to the server proxy are assumed to use
    the given encoding.
    NrcCs6|dkrZt|�\}}}
}|dk	r.d||f}n|}|
dk	rZ|dkrZ|
}|dk	rZ|dkrZ|}t|�|_d|_d|_d|_||_||_||_|
|_	t
tj��dkr�tj�d|_
nt|_
|j�|dkr�d|_|j|j||||
�}nd|_d|_d|_||_g|_d|_||_||_|j|�|j|	�d|_t�|_dS)Nz%s:%srr)r%r�_uri�_refreshCallback�_progressCallback�_bufferSize�_proxy�	_username�	_password�_timeoutr�__version__r�rpc_version�_reset_host_handler_and_type�_allow_redirect�default_transport�_type�_redirected�use_handler_path�
_transport�_trusted_cert_files�_lang�	_encoding�_verbose�set_refresh_callback�set_progress_callback�send_handlerr�_headers)�self�uri�	transport�encoding�verboser$�username�password�refreshCallback�progressCallback�timeoutZphZppZpuZpwrrr�__init__�sJ



zServer.__init__cCsZ|r4|dkr |j||||d�}qV|j||||d�}n"|dkrJ|j|d�}n|j|d�}|S)N�https)Z
proxyUsernameZ
proxyPasswordrM)rM)�_transport_class_https_proxy�_transport_class_proxy�_transport_class_https�_transport_class)rD�typer$rIrJrMrFrrrr7�szServer.default_transportcCs
||_dS)N)r6)rDZallowrrr�allow_redirect�szServer.allow_redirectcCs|js
dS|jS)N)r6r9)rDrrr�
redirected�szServer.redirectedcCs||_|jj|�dS)N)r,r;r@)rDrKrrrr@�szServer.set_refresh_callbackcCs||_|jj|�dS)N)r.r;�set_buffer_size)rD�
bufferSizerrrrW�szServer.set_buffer_size�@cCs||_|jj||�dS)N)r-r;rA)rDrLrXrrrrA�szServer.set_progress_callbackcCstj|||jd�S)N)rG)�	xmlrpclib�dumpsr>)rD�params�
methodnamerrr�	_req_body�szServer._req_bodycCs|jr|jjSdS)N)r;Z
headers_in)rDrrr�get_response_headers�szServer.get_response_headerscCs|jr|jjSdS)N)r;�response_status)rDrrr�get_response_status�szServer.get_response_statuscCs|jr|jjSdS)N)r;Zresponse_reason)rDrrr�get_response_reasonszServer.get_response_reasonc	Cs�|j�}|sdS|jd�}|s"dStd|j��}|ddks@t�t|�dksPt�|djd�}t|�dksnt�|\}}|dkr�d}nt|�}|jd	�\}}|t|�t|�d
�}|S)aSReturns a dictionary with three values:
            length: the total length of the entity-body (can be None)
            first_byte_pos: the position of the first byte (zero based)
            last_byte_pos: the position of the last byte (zero based)
           The range is inclusive; that is, a response 8-9/102 means two bytes
        Nz
Content-Ranger�bytesrr�/�*�-)ZlengthZfirst_byte_posZ
last_byte_pos)r_�get�filterr�AssertionErrorr�int)	rD�headersZ
content_ranger!�brangeZ	total_len�start�end�resultrrr�get_content_ranges(
zServer.get_content_rangecCs$|j�}|sdSd|kr |dSdS)Nz
Accept-Ranges)r_)rDrkrrr�
accept_ranges)szServer.accept_rangescCs�t|j�\}}|dkrtd��t|�dks:|dd�dkr>t�|dkrR|j�|_n||_|jdkrjtd	��t|�\|_|_	|j	s�d
|_	dS)z Reset the attributes:
            self._host, self._handler, self._type
            according the value of self._uri.
        Nzmissing protocol in uri�rrz//�httprOzunsupported XML-RPC protocolz/RPC2)rsrO)
rr+r&r�lowerr8�IOErrorr�_host�_handler)rDrTrErrrr51s
z#Server._reset_host_handler_and_typecs�d}g}x�|D]�}t|�}|tks*|tkr>tj|dt|��}nf|tkr^t�fdd�|D��}nF|tkrz�fdd�|D�}n*|t	ks�|t
kr�t�fdd�|j�D��}|j
|�qWt|�dkr�|d	St|�Sd
S)a> Strip characters, which are not allowed according:
            http://www.w3.org/TR/2006/REC-xml-20060816/#charsets
            From spec:
            Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]  /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
        z#[\x00-\x09]|[\x0b-\x0c]|[\x0e-\x1f]�c3s|]}�j|�VqdS)N)�_strip_characters)�.0�i)rDrr�	<genexpr>Usz+Server._strip_characters.<locals>.<genexpr>csg|]}�j|��qSr)ry)rzr{)rDrr�
<listcomp>Wsz,Server._strip_characters.<locals>.<listcomp>csg|]\}}�j||��qSr)ry)rz�name�val)rDrrr}YsrrN)rTrrr�subrr�tuplerr	r
�dict�items�appendr)rD�argsZregexpro�itemZ	item_typer)rDrryHs 
zServer._strip_charactersc
Cs�d}d}|j��xt|tkr$td��|jj�x$|jj�D]\}}|jj||�q:W|jjdd|j	�|jjdd�|j
r�|jjdd�|r�|jjd	d
�|jr�|jjd|j�|j|j
|�|�}y&|jj|j|j||jd�}|jj}	Wn2tjk
�r|j�r
�ntj�dj}	YnXd
|_|d7}|	dk�r:Pn|	dk�rLd|_q|jj�|_d|_d}|j
�srtd��|j�r�td|j|jf�t|j�\}
}|
d
k�r�|
j�}
|
dk�r�td|
��|jdk�r�|
dk�r�td��t |�\|_|_|j�sd|_|`|j!|
|j"|j#|j$|j%�|_|j&|j'�|j(|j)�|j*|j+�|j,|j-�|j.gkrt/|jd�rx|j.D]}|jj0|��qnWqWt1|t2j3��r�|St1|t4��r�t5|�dk�r�|d}|S)zL Call a method on the remote server
            we can handle redirections. rz!Unable to fetch requested PackagezX-Infoz+RPC Processor (C) Red Hat, Inc (version %s)zX-Client-VersionrzX-RHN-Transport-Capabilityzfollow-redirects=3zX-RHN-Redirect�0z
X-RHN-Path)rHN���-�.zRedirects not allowedz%s redirected to %srsrOz%Redirected to unsupported protocol %sz)HTTPS redirected to HTTP is not supportedz/RPC2�add_trusted_cert)r�r�)rsrO)6r5�MAX_REDIRECTIONS�InvalidRedirectionErrorr;Z
clear_headersrCr��
set_header�
add_headerr4r6rBr^ry�requestrvrwr?r`rZZ
ProtocolErrorr:�sys�exc_info�errcoder9rV�printr+rrtr8rr7r/r0r1r2rAr-r@r,rWr.�setlangr=r<�hasattrr��
isinstancerZFilerr)
rDr]r\Zredirect_responseZretry�k�vr�ZresponseZ
save_response�typrE�certfilerrr�_requestbs�









zServer._requestcCsd|jj|j|jfS)Nz
<%s for %s%s>)�	__class__r'rvrw)rDrrr�__repr__�szServer.__repr__cCst|j|�S)N)�_Methodr�)rDr~rrr�__getattr__�szServer.__getattr__cKs,|js
dS|j||d��|jjf|�dS)N)�transferrG)r;�update�set_transport_flags)rDr�rG�kwargsrrrr��s
zServer.set_transport_flagscCs|js
iS|jj�S)N)r;�get_transport_flags)rDrrrr��szServer.get_transport_flagscCsdS)Nr)rDrrr�reset_transport_flags�szServer.reset_transport_flagscCs@t|�tg�tf�gkr.dd�|D�|j|<nt|�|j|<dS)NcSsg|]}t|��qSr)�str)rz�arrrr}�sz%Server.set_header.<locals>.<listcomp>)rTrCr�)rDr~�argrrrr��szServer.set_headercCsF||jkr&|j|}t|t�s4|g}ng}|j|<|jt|��dS)N)rCr�rr�r�)rDr~r�Zvlistrrrr�s


zServer.add_headercCs(||_|jr$t|jd�r$|jj|�dS)Nr�)r=r;r�r�)rDZlangrrrr�
szServer.setlangcCstd��dS)NzThis method is deprecated)�NotImplementedError)rDZca_chainrrr�use_CA_chainszServer.use_CA_chaincCs.|jj|�|jr*t|jd�r*|jj|�dS)Nr�)r<r�r;r�r�)rDr�rrrr�szServer.add_trusted_certcCs|jr|jj�d|_dS)N)r;�close)rDrrrr�s
zServer.close)	NNrNNNNNN)NNNN)rY)rr)N))r'r(r)�__doc__rZ	TransportrSZ
SafeTransportrRZProxyTransportrQZSafeProxyTransportrPrNr7rUrVr@rWrAr^r_rarbrprqr5ryr�r��__str__r�r�r�r�r�r�r�r�r�r�rrrrr*lsH
C

#s



r*c	@s\eZdZdddddidddf	dd�Zdd�Zdd�Zdd	d
�Zdd�Zd
d�Zddd�Z	dS)�	GETServerNrcCsBtj||||||||	|
d�	||_||_|j|_|jddd�dS)N)r$rIrJrFrKrLrM)�offset�amount)r*rNZ_client_versionrCrw�
_orig_handler�	set_range)rDrErFr$rIrJZclient_versionrkrKrLrMrrrrNszGETServer.__init__cCs$|st|�dkrtd��tdd�|jjd��}|d|d|gt|dd��}ddj|�|_|j|_|j	r�|j
r�|j�|_x$|jj
�D]\}}|jj||�q�W|jdk	�r |jdkr�t|j�d}|jdk	r�|t|j|jd�}ndt|j�}|jjd	d
|�|jjdd�dS)
Nrz$Required parameter channel not foundcSs|dkS)Nrxr)�xrrr�<lambda>5sz%GETServer._req_body.<locals>.<lambda>rdz$RHNrrfZRangezbytes=)�allow_partial_contentrx)r�	Exceptionrhr�r�list�joinrwrBr9r:�
_new_req_bodyrCr�r;r��_offsetr��_amountr�)rDr\r]Zh_compsZhndl�hr�rlrrrr^1s&"


zGETServer._req_bodycCst|j�\}}t|�\}}|S)N)rr9r)rDrTZtmpuriZsiteZhandlerrrrr�UszGETServer._new_req_bodycCs�|dk	rByt|�}Wn,tk
r@td|dtj�d��YnX|dk	r�yt|�}Wn,tk
r�td|dtj�d��YnX|dkr�td|��||_||_dS)NzInvalid value `%s' for offsetrzInvalid value `%s' for amountr)rjr#�
RangeErrorr�r�r�r�)rDr�r�rrrr�ZszGETServer.set_rangecCs|jjdd�dS)Nr)r�)r;r�)rDrrrr�oszGETServer.reset_transport_flagscCst|j|�S)N)�
SlicingMethodr�)rDr~rrrr�rszGETServer.__getattr__cCs$tj||||||d�}|jd�|S)N)r$rIrJrMZGET)r*r7Z
set_method)rDrTr$rIrJrM�retrrrr7vs
zGETServer.default_transport)NN)NNNN)
r'r(r)rNr^r�r�r�r�r7rrrrr�s$
r�c@seZdZdS)r�N)r'r(r)rrrrr�|sr�c@seZdZdS)r�N)r'r(r)rrrrr�sr�cCs>ddl}t||j�s*||kr&||gSgSdd�|j|�D�S)NrcSs g|]}|jdd�dj��qS)rr)r�strip)rzr�rrrr}�sz#getHeaderValues.<locals>.<listcomp>)�	mimetoolsr�ZMessageZgetallmatchingheaders)rkr~r�rrr�getHeaderValues�s
r�c@s4eZdZdZdd�Zdd�Zdd�Zdd	�ZeZd
S)r�z{ some magic to bind an XML-RPC method to an RPC server.
        supports "nested" methods (e.g. examples.getStateName)
    cCs||_||_dS)N)�_send�_name)rD�sendr~rrrrN�sz_Method.__init__cCst|jd|j|f�S)Nz%s.%s)r�r�r�)rDr~rrrr��sz_Method.__getattr__cGs|j|j|�S)N)r�r�)rDr�rrr�__call__�sz_Method.__call__cCsd|jj|j|jfS)Nz<%s %s (%s)>)r�r'r�r�)rDrrrr��sz_Method.__repr__N)	r'r(r)r�rNr�r�r�r�rrrrr��sr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)	r�z;
    A "slicing method" allows for byte range requests
    cCstj|||�d|_dS)N)r�rNr�)rDr�r~rrrrN�szSlicingMethod.__init__cCst|jd|j|f�S)Nz%s.%s)r�r�r�)rDr~rrrr��szSlicingMethod.__getattr__cOs�|jd�|_|jd�|_y|jjj|j|jd�Wntk
rFYnX|j|j|�}y|jjj�Wntk
rzYnX|S)Nr�r�)r�r�)	rgr�r�r�Zim_selfr��AttributeErrorr�r�)rDr�r�rorrrr��szSlicingMethod.__call__N)r'r(r)r�rNr�r�rrrrr��sr�cCsbd}d}d}||kr t||�}d}||krZt||�}|rZdj|�}ddl}d|j|�}||fS)z% Reports the error from the headers. rrxzX-RHN-Fault-CodezX-RHN-Fault-StringNz%s)rjr�r��base64Zdecodestring)rkr��errmsg�sZ_sListZ_sr�rrr�reportError�s

r�)-r3rrr�ZrhnrZrhn.i18nrZrhn.UserDictCaserrZ�typesrrrrr	r
Zurllibrr�ImportErrorZ
xmlrpc.clientZclientr�r�rcr�r�Zurllib.parser�rr"r%rur&r*r�r�r�r�r�r�r�r�rrrr�<module>sF 
%5^
PK���Z�h��J�J+__pycache__/transports.cpython-36.opt-1.pycnu�[���3

�U�f�|�@sZddlZddlZddlZddlmZddlmZmZddlm	Z	ddl
mZy ddlZddl
mZmZmZWn*ek
r�ddljZeZeZeZYnXdZdZGd	d
�d
e�ZGdd�dej�ZGd
d�de�ZGdd�de�ZGdd�de�ZGdd�d�Zd%dd�Z d&dd�Z!Gdd�d�Z"Gdd�d�Z#d'dd �Z$d(d!d"�Z%e#Z&Gd#d$�d$�Z'dS))�N)�connections)�sstr�bstr)�SmartIO)�UserDictCase)�IntType�
StringType�ListTypezI2.8.62.8.6-8.module_el8.10.0+6858+3ddf28328.module_el8.10.0+6858+3ddf2832�c@seZdZdS)�NotProcessedN)�__name__�
__module__�__qualname__�rr� /usr/lib/python3.6/transports.pyr$src@s�eZdZdeZd'dd�Zd(dd�Zd	d
�Zdd�Zd
d�Z	d)dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zd*dd�Zdd �Zd!d"�Zd#d$�Zd%d&�ZdS)+�	Transportzrhn.rpclib.py/%srNcCszd|_ddd�|_|j||d�t�|_d|_d|_d|_d|_||_	||_
d|_d|_d|_
d|_d|_||_||_dS)NFr)�transfer�encoding�POSTi@)Z_use_builtin_types�_transport_flags�set_transport_flagsr�_headers�verbose�
connection�method�_lang�refreshCallback�progressCallback�
bufferSize�
headers_in�response_status�response_reason�_redirectedZ
_use_datetime�timeout)�selfrrrrZuse_datetimer#rrr�__init__*s"zTransport.__init__�@cCs||_||_dS)N)rr)r$rrrrr�set_progress_callback?szTransport.set_progress_callbackcCs
||_dS)N)r)r$rrrr�set_refresh_callbackDszTransport.set_refresh_callbackcCs|dkrd}||_dS)Ni@)r)r$rrrr�set_buffer_sizeJszTransport.set_buffer_sizecCs|dkrtd|��||_dS)N�GETrzUnknown request method %s)r*r)�IOErrorr)r$rrrr�
set_methodRszTransport.set_methodcKs<|jj|�|dk	r||jd<|dk	r0||jd<|j�dS)Nrr)r�update�validate_transport_flags)r$rr�kwargsrrrrXs

zTransport.set_transport_flagscCs
|jj�S)N)r�copy)r$rrr�get_transport_flagscszTransport.get_transport_flagscCsH|jjd�}t|dd�}||jd<|jjd�}t|dd�}||jd<dS)Nr�)�strictr)r�get�lookupTransfer�lookupEncoding)r$rrrrrr.fs
z"Transport.validate_transport_flagscCs@t|�tg�tf�gkr.dd�|D�|j|<nt|�|j|<dS)NcSsg|]}t|��qSr)�str)�.0�arrr�
<listcomp>tsz(Transport.set_header.<locals>.<listcomp>)�typerr7)r$�name�argrrr�
set_headerqszTransport.set_headercCsF||jkr&|j|}t|t�s4|g}ng}|j|<|jt|��dS)N)r�
isinstancer	�appendr7)r$r<r=Zvlistrrr�
add_headerxs


zTransport.add_headercCs|jj�dS)N)r�clear)r$rrr�
clear_headers�szTransport.clear_headerscCs8|jrtd|f�|jr*tj||jd�Stj|�SdS)NzConnecting via http to %s)r#)r�printr#r�HTTPConnection)r$�hostrrr�get_connection�s
zTransport.get_connectioncCsX||_|j|�\}}}|sg}|j|�}|j|j�|jrJ|j|jd�t||jd�}|jf|j	�|j
d|j�x*t|jj
��|D]\}	}
|j
|	|
�q�W|j
dd�|j|�xd
D]}|j|�q�W|j||�\}}
|j�rtd�x$|j
�D]\}	}
td	|	|
f�q�W|
jdk�r6|d|_|
j|_dS||_|
j|_|
j|_|j|
|�S)Nr2)rrz
User-AgentzContent-Typeztext/xml�Content-Length�HostzIncoming headers:z	%s : %s�-�.ZLocation)rHrI)rJrK)r�
get_host_inforGZset_user_agent�
user_agentZset_debuglevel�Outputrrrr>�listr�items�process�clear_header�	send_httprD�statusr"r r�reasonr!�_process_response)r$rF�handlerZrequest_bodyr�
extra_headers�x509rZreq�header�value�h�headers�fdrrr�request�s<



zTransport.requestcCsbt|j|j|jd�}|j|�}t|t�rPt|j|j	|j
|j|jd�}|j|_|S|j�|j|�S)N)rr)rr)
�Inputrrr�decoder?�InputStream�Filer^�lengthr<�close�parse_response)r$r^rZresp�frrrrV�s




zTransport._process_responsecCs|jS)N)r")r$rrr�
redirected�szTransport.redirectedcCsf|j�\}}x@|jd�}|sP|jr,|j�|jr@tdt|��|j|�qW|j�|j�|j�S)Nizbody:)Z	getparser�readrrrD�reprZfeedre)r$rg�p�u�responserrrrf�s
zTransport.parse_responsecCs
||_dS)N)r)r$�langrrr�setlang�szTransport.setlang)rrNNNN)r&)NN)r)rr
r�__version__rMr%r'r(r)r,rr1r.r>rArCrGr_rVrhrfrorrrrr's&


	
8rc@s&eZdZd	dd�Zdd�Zdd�ZdS)
�
SafeTransportrNcCs<tj||||||d�g|_x|p$gD]}|j|�q&WdS)N)rrr#)rr%�
trusted_certs�add_trusted_cert)r$rrrrrrr#�certfilerrrr%�s
zSafeTransport.__init__cCs*tj|tj�std|��|jj|�dS)Nz%Certificate file %s is not accessible)�os�access�R_OK�
ValueErrorrrr@)r$rtrrrrsszSafeTransport.add_trusted_certcCsR|j|�\}}}|jr$td|f�|jr>tj||j|jd�Stj||jd�SdS)NzConnecting via https to %s)rrr#)rr)rLrrDr#rZHTTPSConnectionrr)r$rFrXrYrrrrGszSafeTransport.get_connection)rrNNNN)rr
rr%rsrGrrrrrq�s
rqc@seZdZddd�Zdd�ZdS)�ProxyTransportNrc		Cs,tj||||||d�||_||_||_dS)N)rrr#)rr%�_proxy�_proxy_username�_proxy_password)	r$�proxy�
proxyUsername�
proxyPasswordrrrrr#rrrr%s
zProxyTransport.__init__cCs^|jr td||j|j|jf�|jrBtj|j||j|j|jd�Stj|j||j|jd�SdS)Nz8Connecting via http to %s proxy %s, username %s, pass %s)�username�passwordr#)r�r�)rrDrzr{r|r#rZHTTPProxyConnection)r$rFrrrrG#s


zProxyTransport.get_connection)NNrrNNN)rr
rr%rGrrrrrys
ryc@s&eZdZd	dd�Zdd�Zdd�ZdS)
�SafeProxyTransportNrc
CsBtj|||||||||	d�	g|_x|p*gD]}
|j|
�q,WdS)N)r~rrrrrr#)ryr%rrrs)r$r}r~rrrrrrrr#rtrrrr%0szSafeProxyTransport.__init__cCs*tj|tj�std|��|jj|�dS)Nz%Certificate file %s is not accessible)rurvrwrxrrr@)r$rtrrrrs=sz#SafeProxyTransport.add_trusted_certcCsf|jr td||j|j|jf�|jrFtj|j||j|j|j|jd�Stj|j||j|j|jd�SdS)Nz9Connecting via https to %s proxy %s, username %s, pass %s)r�r�rrr#)r�r�rr)	rrDrzr{r|r#rZHTTPSProxyConnectionrr)r$rFrrrrGBs

z!SafeProxyTransport.get_connection)NNrrNNNN)rr
rr%rsrGrrrrr�/s

r�c@s:eZdZddd�Zejfdd�Zejfdd	�Zd
d�ZdS)
r`N��@cCs�d|_d|_d|_d|_d|_d|_||_||_||_|s�dt	j
krTt	j
dj�|_dt	j
krnt	j
dj�|_dt	j
kr�t	j
dj�|_dt	j
kr�tt	j
d�|_dt	j
kr�t	j
d|_d	t	j
kr�t	j
d	|_n�x�|j
�D]�}||}|j�}|d
k�r&yt|�|_Wntk
�r"d|_YnXq�|dk�r<|j�|_q�|dk�rR|j�|_q�|d
k�rh|j�|_q�|dk�r~|j�|_q�|dkr�||_q�Wd|_dS)Nr�C�ZHTTP_CONTENT_TRANSFER_ENCODINGZHTTP_CONTENT_ENCODINGzCONTENT-TYPEZCONTENT_LENGTHZHTTP_ACCEPT_LANGUAGEZHTTP_X_PACKAGE_FILENAMEzcontent-lengthzcontent-transfer-encodingzcontent-encodingzcontent-typezaccept-languagezx-package-filename)rrr;rdrnr<rr�max_mem_sizeru�environ�lower�int�keysrx�io)r$r]rrr�rZr[r\rrrr%hsR











zInput.__init__cCs�|jdkrdS|jr2t||j|j|j|jd�|_n
t|�|_|jsN|jdkrRdS|jdkr�ddl	}|j}|j
dd�t|jd�|_|j||j�n
t
|j��dS)Nzapplication/octet-stream)rrr��binary�base64r)r�)r;rd�_smart_readrrr�r��_smart_total_readrr��seekrra�NotImplementedError)r$r^r�Zold_iorrrri�s"


z
Input.readcCs^|jdkr t||j|j|jd�S|js0|j|�t|d�rB|j�|jsT|jdkrVn�|jdkr�ddl	}|j
�}|jjdd�|j|jj��|j
�}~t|�|_t|jd�|_|jj|�n�|jdk�r ddl}|jjdd�|jdt|jd�}|j�}t|�|_t|jd�|_|jj|�n*|jd
k�r<t|j|j��nt|j|j��|jjdd�|jS)Nzapplication/octet-stream)rere�__plain�x-zlib�deflater)r��x-gzip�gzip�rb)�mode�
compresslevel�fileobjzx-gpg)r�r�)r�r�)r;rbrdr<rer�ri�hasattrr�zlibZ
decompressobjr�Z
decompress�flush�lenrr��writer��GzipFile�COMPRESS_LEVELr�r)r$r^r��obj�datar��gzrrrra�s>






zInput.decodecCs|jS)N)rn)r$rrr�getlang�sz
Input.getlang)NNr�r�)	rr
rr%�sys�stdinrirar�rrrrr`gs

70r`��@cCs.t|d�}x|j|�}|sP|j|�qW|S)z�
    Tries to read data from the supplied stream, and puts the results into a
    StmartIO object. The data will be in memory or in a temporary file,
    depending on how much it's been read
    Returns a SmartIO object
    )r�)rrir�)r^rr�r��chunkrrrr��s

r�cCs�tj�}|}t|d�}|}x�|dkr�tj�}	t||�}
|j|
�}t|�}
|
sNP||
}|j|�|dkrjq|	|dks~|dkr|	}t||�}||	|d}
|dkr�d}n||
}||||
|�qW|jdd�|S)N)r�rr2g���ư>)�timer�minrir�r��floatr�)r^�amtrrr�Z	startTimeZlastTime�bufZorigsizeZcurTime�lr�Z	bytesReadZspeedZsecsrrrr�s2




r�c@seZdZddd�Zdd�ZdS)rb�	<unknown>NcCs ||_t|�|_||_||_dS)N)r^r�rdr<re)r$r^rdr<rerrrr%=s
zInputStream.__init__cCsd|j|jfS)Nz0Input data is a stream of %d bytes for file %s.
)rdr<)r$rrr�__repr__CszInputStream.__repr__)r�N)rr
rr%r�rrrrrb<s
rbc@s�eZdZdZdZdZdZdZdZdZ	ddgddgd	d
gdggZ
ddd
gZd dd�Zdd�Z
dd�Zdd�Zd!dd�Zd"dd�Zdd�Zdd�ZdS)#�
BaseOutputrr2��Nr�zx-gzipr�zx-zlibr�zx-gpgr�r�rcCs�|rt|tj�std��||_||_d|_t�|_d|_	d|_
i|_d|_d|_
d|_d|_d|_d|_|j||d�d|_dS)Nz&Expected an HTTPConnection type objectr)rr)r?rrE�	Exceptionr�_connectionr�rr]rr�transport_flagsr�r��_hostZ_handlerZ
_http_typeZ	_protocolr�_BaseOutput__processed)r$rrrrrrrr%cs$zBaseOutput.__init__cCsBt|�tg�tf�gkr0djtt|��|j|<nt|�|j|<dS)N�,)r;�join�mapr7r])r$r<r=rrrr>�szBaseOutput.set_headercCs||jkr|j|=dS)N)r])r$r<rrrrR�s
zBaseOutput.clear_headercCs�||_|j|jkr�ddl}|j|jd}|jd|�tdd�}|jdt|d�}t	j
ddkrn|jt|��n|jt
|��|j�|j�|_|j�n�|j|jkr�ddl}|j|jd}|jd|�|jt�}|j|�|j�|_n8|j|jk�r t|j|j��|j|jd}|jd|�|j|jk�rT|j|j}|jd|�|jd	d
�nH|j|jk�r�ddl}	|j|j}|jd|�|jd	d�|	j|j�|_|jdt|j��t}
ttj��dk�r�tj�d}
|jd
d|
�d|_ dS)NrzContent-Encodingr2)Z	force_mem�wb)r�r�r�r�zContent-Transfer-EncodingzContent-Typezapplication/binaryztext/base64zContent-LengthzX-Transport-Infoz=Extended Capabilities Transport (C) Red Hat, Inc (version %s))!r�r�ENCODE_GZIPr��	encodingsr>rr�r�r��version_infor�rrre�getvalue�ENCODE_ZLIBr�Zcompressobj�compressr��
ENCODE_GPGr�r�TRANSFER_BINARY�	transfers�TRANSFER_BASE64r�Zencodestringr�rp�splitr�)r$r�r�Z
encoding_namergr�r�r�Z
transfer_namer�Zrpc_versionrrrrQ�sT



zBaseOutput.processcKs||_||_|jj|�dS)N)rrr�r-)r$rrr/rrrr�szBaseOutput.set_transport_flags�/RPC2cCs�|js
t�||_|jdkr"td��|jj�|jj|j|t|j	�|j
d�|jj�}|j|�s~t
jd|j|f|j|j|j��|j|fS)NzNo connection object found)Zbodyr]z%s %s)r�rr�r�r�Zconnectr_rrr�r]Zgetresponse�response_acceptable�	xmlrpclibZ
ProtocolErrorrTrU�msg)r$rFrWrmrrrrS�s




zBaseOutput.send_httpcCsP|jdkrdS|jd
krdS|jdkr*dS|jjd�s:dS|jdd	krLdSdS)z*Returns true if the response is acceptable��r2�-�.��rZallow_partial_contentzContent-Typezapplication/octet-stream)r�r�)rTr�r4r�)r$rmrrrr��s


zBaseOutput.response_acceptablecCs|jr|jj�d|_dS)N)r�re)r$rrrre�s
zBaseOutput.close)rrNr)rr)r�)rr
rZENCODE_NONEr�r�r�Z
TRANSFER_NONEr�r�r�r�r%r>rRrQrrSr�rerrrrr�Is,
8

r�cCs�|dkrdSt|t�r8d|ko.ttj�knr8|St|t�rpx,tttj��D]}tj||j�krR|SqRW|r�td|��dS)zTGiven a string or numeric representation of a transfer, return the
    transfer codeNrzUnsupported transfer %s)	r?rr�rNr�r�ranger�rx)rr3�irrrr5s(
r5cCs�|dkrdSt|t�r8d|ko.ttj�knr8|St|t�rpx,tttj��D]}|j�tj|krR|SqRW|r�td|��dS)zUGiven a string or numeric representation of an encoding, return the
    encoding codeNrzUnsupported encoding %s)	r?rr�rNr�rr�r�rx)rr3r�rrrr6s(
r6c@s@eZdZddd�Zdd�Zddd	�Zd
d�Zdd
�Zdd�ZdS)rcrN�@cCsF||_||_|j|_||_d|_|r<||jd�dd�|_||_dS)Nr��/r2)rd�file_objrerr<�rfindr)r$r�rdr<rrrrrr%&sz
File.__init__cCs|jS)N)rd)r$rrr�__len__1szFile.__len__cCs$|dkr|j�}|j�S|jj|�S)N)�	_get_filerir�)r$r�r^rrrri4sz	File.readcCsP|j�}xB|j|j�}|sPtjddkr:|jt|��q
|jt|��q
W|S)zHCopies the contents of this File object into another file
        objectrr�)r�rirr�r�r�rr)r$�filer^r�rrr�read_to_file<szFile.read_to_filecCsL|jr,t|j|j|j|jd�}|jdd�nt|j|jd�}|jdd�|S)z�Read everything into a temporary file and call the progress
        callbacks if the file length is defined, or just reads till EOF)rrr)r)rdr�r�rrr�r�)r$r�rrrr�Js

zFile._get_filecCs|jr|j�d|_dS)N)re)r$rrr�__del__XszFile.__del__)rNNr�)N)	rr
rr%r�rir�r�r�rrrrrc%s


rc)r�r�)r�Nr�)r)r)(rur�r�ZrhnrZrhn.i18nrrZrhn.SmartIOrZrhn.UserDictCaserr��typesrrr	�ImportErrorZ
xmlrpc.clientZclientr��bytesrOrpr�r�rrrqryr�r`r�r�rbr�r5r6rNrcrrrr�<module>
sD

V8	

;
8

PK���Z�b�b��,__pycache__/connections.cpython-36.opt-1.pycnu�[���3

�U�f�%�@s&ddlZddlZddlZddlmZddlmZddlmZddlm	Z	y(ddl
Z
ddl
mZmZm
Z
ddlZWn<ek
r�ddljZ
ddlmZmZm
Z
ddljZYnXGdd�de
j�ZGd	d
�d
e
j�ZGdd�de�ZGd
d�de�ZGdd�de�ZGdd�de�Zdd�Zdd�ZdS)�N)�python_version)�SSL)�nonblocking)�i18n)�_CS_REQ_SENT�_CS_IDLE�ResponseNotReadyc@seZdZdd�ZdS)�HTTPResponsecCs4t|jtj�stj|j�|_|jj|||||�dS)N)�
isinstance�fprZNonBlockingFile�set_callback)�self�rs�ws�ex�	user_data�callback�r�!/usr/lib/python3.6/connections.pyr szHTTPResponse.set_callbackN)�__name__�
__module__�__qualname__rrrrrr	sr	c@s@eZdZeZdejfdd�Zdd�Zdd�Z	dd	�Z
d
d�ZdS)�HTTPConnectionNcCs^t�dkr tjj||||d�ntjj|||�g|_g|_g|_d|_d|_d|_	||_
dS)Nz2.6.1)�timeoutz#rhn.connections $Revision$ (python))r�httplibr�__init__�_cb_rs�_cb_ws�_cb_ex�
_cb_user_data�_cb_callback�_user_agentr)r
�host�portrrrrr(s
zHTTPConnection.__init__cCs"||_||_||_||_||_dS)N)rrrrr )r
rrrrrrrrr5s
zHTTPConnection.set_callbackcCs
||_dS)N)r!)r
Z
user_agentrrr�set_user_agent=szHTTPConnection.set_user_agentcCs�|jr|jj�rd|_|jtks&|jr,t��|jdkrH|j|j|j�}n|j|j�}|jrv|j	|j
|j|j|j
|j�|j�t|_|jr�|j�n||_|S)z!Get the response from the server.Nr)Z_HTTPConnection__responseZisclosedZ_HTTPConnection__staterrZ
debuglevel�response_class�sockr rrrrr�beginr�
will_close�close)r
�responserrr�getresponseBs 

zHTTPConnection.getresponsecCstjj|�|jj|j�dS)N)rr�connectr&�
settimeoutr)r
rrrr,sszHTTPConnection.connect)rrrr	r%r�DEFAULT_TIMEOUTrrr$r+r,rrrrr%s
1rc@sBeZdZdddejfdd�Zdd�Zd
dd�Zd	d
�Zdd�Z	dS)�HTTPProxyConnectionNcCsPtj|||d�|j|j|_|_|j||�|j|j|_|_||_	||_
dS)N)r)rrr"r#�_HTTPProxyConnection__proxy� _HTTPProxyConnection__proxy_port�
_set_hostport�_host�_port�_HTTPProxyConnection__username�_HTTPProxyConnection__password)r
�proxyr"r#�username�passwordrrrrryszHTTPProxyConnection.__init__cCs.|j|j|j�tj|�|j|j|j�dS)N)r2r0r1rr,r3r4)r
rrrr,�s
zHTTPProxyConnection.connectrcCsN|j}|j|jkr$|dt|j�}d||f}tj||||d�|j�dS)N�:zhttp://%s%s)�	skip_host)r3r4�default_port�strr�
putrequest�_add_proxy_headers)r
�method�urlr;�hostnameZnewurlrrrr>�szHTTPProxyConnection.putrequestcCsX|js
dSd|j|jf}tjtj|��jtjd�tjd��}|jddtj|��dS)Nz%s:%s�
�zProxy-AuthorizationzBasic %s)	r5r6�base64Zencodestringr�bstr�replace�	putheaderZsstr)r
ZuserpassZenc_userpassrrrr?�s
$z&HTTPProxyConnection._add_proxy_headerscCs|j||�\|_|_dS)N)Z
_get_hostportr"r#)r
r"r#rrrr2�sz!HTTPProxyConnection._set_hostport)r)
rrrrr.rr,r>r?r2rrrrr/xs

r/c@s2eZdZeZejjZddej	fdd�Z
dd�ZdS)�HTTPSConnectionNcCs$tj||||d�|pg}||_dS)N)r)rr�
trusted_certs)r
r"r#rJrrrrr�szHTTPSConnection.__init__c	Cs�tj|j|jtjtj�}x�|D]�}|\}}}}}ytj|||�}Wntjk
r^d}wYnXy"|j|j|jf�|j|j	�Wn$tjk
r�|j
�d}wYnXPqW|dkr�tjd��tj||j
�|_|jj�dS)z'Connect to a host on a given (SSL) portNz0Unable to connect to the host and port specified)�socketZgetaddrinfor"r#Z	AF_UNSPECZSOCK_STREAM�errorr,r-rr)r�	SSLSocketrJr&�init_ssl)	r
�results�rZafZsocktype�protoZ	canonnameZsar&rrrr,�s*

zHTTPSConnection.connect)rrrr	r%rrIr<rr.rr,rrrrrI�s
rIc@seZdZdd�ZdS)�HTTPSProxyResponsecCstj|�d|_dS)Nr)r	r'r()r
rrrr'�s
zHTTPSProxyResponse.beginN)rrrr'rrrrrR�srRc@sBeZdZejZddddejfdd�Zdd�Zddd�Z	d	d
�Z
dS)�HTTPSProxyConnectionNc	Cs*tj|||||||d�|pg}||_dS)N)r)r/rrJ)r
r7r"r#r8r9rJrrrrr�s
zHTTPSProxyConnection.__init__cCs�tj|�d|j|jf}tj|d|�|j�tj|�|j}t	|_tj
|�}||_|j�|jdkr�|j�t
j||j|j|j��tj|j|j�|_|jj�dS)Nz%s:%sZCONNECT��)r/r,r3r4rr>r?Z
endheadersr%rRr+r)Zstatus�	xmlrpclibZ
ProtocolError�reason�msgrrMr&rJrN)r
r"r%r*rrrr,�s 



zHTTPSProxyConnection.connectrcCstj||||d�S)N)r;)rr>)r
r@rAr;rrrr>�szHTTPSProxyConnection.putrequestcCstj|�|jd|j�dS)Nz
User-Agent)r/r?rHr!)r
rrrr?�s
z'HTTPSProxyConnection._add_proxy_headers)r)rrrrIr<rr.rr,r>r?rrrrrS�s
rScCs$|dkrdStj|�}|jd�SdS)zJ Convert Internationalized domain name from Punycode (RFC3492) to Unicode N�idna)rrF�decode)rBrrr�idn_puny_to_unicode�s
rZcCs*|dkrdStj|�}tj|jd��SdS)zZ Convert domain name to Punycode (RFC3492). Hostname can be instance of string or Unicode NrX)rZustr�encode)rBrrr�idn_ascii_to_punys
r\)rEZencodings.idnaZ	encodingsrK�platformrZrhnrrrrrrrrU�ImportErrorZhttp.clientZclientZ
xmlrpc.clientr	rr/rIrRrSrZr\rrrr�<module>
s,
S,&.PK���Z~��RR$__pycache__/SSL.cpython-36.opt-1.pycnu�[���3

�U�f-+�@s�dZddlmZddlmZddlZddlZddlZddlmZddl	Z	dZ
eed�r^ejZ
nddlm
Z
Gd	d
�d
�Zdd�ZGd
d�dejej�ZdS)zK
rhn.SSL builds an abstraction on top of the objects provided by pyOpenSSL
�)�SSL)�cryptoN)�bstr�x�sslerror)�socket_errorc@s�eZdZdZd(dd�Zdd�Zdd�Zd)d	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zd*dd�Zd+dd�Zdd�Zd d!�Zd"d#�Zd$d%�ZeZeZd,d&d'�ZdS)-�	SSLSocketzM
    Class that wraps a pyOpenSSL Connection object, adding more methods
    NcCsnd|_d|_||_g|_|pg}x|D]}|j|�q&Wtj|_tj|_	d|_
d|_td�|_
d|_d|_dS)Ni r�)�_ctx�_connection�_sock�_trusted_certs�add_trusted_certrZ
SSLv23_METHOD�_ssl_methodZVERIFY_PEER�_ssl_verify_flags�_buffer_size�_posr�_buffer�_makefile_called�_closed)�self�socketZ
trusted_certs�f�r�/usr/lib/python3.6/SSL.py�__init__/s

zSSLSocket.__init__cCs0tj|tj�std|��|jj|jd��dS)zh
        Adds a trusted certificate to the certificate store of the SSL context
        object.
        z"Unable to read certificate file %szutf-8N)�os�access�R_OK�
ValueErrorr
�append�encode)r�filerrrrLszSSLSocket.add_trusted_certcCs�|j�tj|j�|_|jjtj�|jjtj�|jrVx"|jD]}|jj	|�q@Wnd|_
|jj|j
t�t
td�r�|jjtj�tj|j|j�|_|jj�dS)z1
        Initializes the SSL connection.
        r�OP_DONT_INSERT_EMPTY_FRAGMENTSN)�
_check_closedrZContextrr
Zset_optionsZOP_NO_SSLv2ZOP_NO_SSLv3r
Zload_verify_locationsrZ
set_verify�ssl_verify_callback�hasattrr#Z
ConnectionrrZset_connect_state)rrrrr�init_sslUs
zSSLSocket.init_sslcCs|r
||_|jd|_|S)zG
        Returns self, since we are a file-like object already
        �)rr)r�mode�bufsizerrr�makefilesszSSLSocket.makefilecCs,|jr
dS|js|j�dS|jd|_dS)z+
        Closes the SSL connection
        Nr()rr�
_really_close)rrrr�close�szSSLSocket.closecCsdS)Nr)rrrr�flush�szSSLSocket.flushcCs�|jdkrdSd}yt|jd�}Wn tk
rBt|jd�}YnX|dk	r�tjddkrp|�dkr�|jj�n|�dkr�|jj�|jj�d|_dS)NZstate_stringZget_state_stringr�s%SSL negotiation finished successfullyz%SSL negotiation finished successfullyr()r�getattr�AttributeError�sys�version_infoZshutdownr-r)rZ	get_staterrrr,�s




zSSLSocket._really_closecCs|jrtd��dS)NzI/O operation on closed file)rr)rrrrr$�szSSLSocket._check_closedcCs$t|j|�rt|j|�St|��dS)N)r&rr0r1)r�namerrr�__getattr__�szSSLSocket.__getattr__cCsdS)z'
        Returns false always.
        rr)rrrr�isatty�szSSLSocket.isattycCs|jS)N)r)rrrr�tell�szSSLSocket.tellrcCstd��dS)N�seek)�NotImplementedError)r�posr)rrrr8�szSSLSocket.seekcCsX|j�|j}t|j�}x�||ks,|dk�r|dk	rBt|||�}y:|jj|�}|j||_t|j�}|jj�}|dkrzPWqtj	k
r�PYqtj
k
r�tj�d}t
d|j�PYqtjk
r�|jtjd�Yqtjk
�r|jtjd�YqXqW|�r4|jd|�}|j|d�|_n|j}td�|_|jt|�|_|S)z@
        Reads up to amt bytes from the SSL connection.
        Nrr(z
SSL exception�readr	)r$r�lenr�minr�recv�pendingr�ZeroReturnErrorZSysCallErrorr2�exc_info�print�args�WantWriteError�_poll�select�POLLOUT�
WantReadError�POLLINrr)r�amt�buffer_sizeZ
buffer_length�datar?�e�retrrrr;�s<



zSSLSocket.readcCs|jt|��|dd�<t|�S)N)r;r<)rZbufrrr�readinto�szSSLSocket.readintocCsBtj�}|j|j|�|j|jj�d�}|gkr>td|��dS)Ni�zConnection timed out on %s)rFZpoll�registerrZ
gettimeout�TimeoutException)rZfilter_typeZcaller_nameZpoller�resrrrrE�s
zSSLSocket._pollcCs�|j�t|�}xvy*|jj|�}|t|�kr.P||d�}Wqtjk
r`|jtjd�Yqtj	k
r�|jtj
d�YqXqW|S)z/
        Writes to the SSL connection.
        N�write)r$r<r�sendrrDrErFrGrHrI)rrLZoriglenZsentrrrrS�szSSLSocket.writecCs
|j|�S)N)r;)rrJrrrr>szSSLSocket.recvcCsB|j��xd}|jjtd��}|dkr2|d}n|rHt|j�|krH|}|dk	r�|jd|�}|j|d�|_|jt|�|_|S|j}|r�t|j|t|j��}y|jj	|�}|j||_Wqt
jk
r�PYqt
jk
r�|j
tjd�Yqt
jk
�r|j
tjd�YqXqW|j}d|_|jt|�|_|S)zg
        Reads a single line (up to `length' characters long) from the SSL
        connection.
        N�
rr(�readliner	)r$r�findrr<rrr=rr>rr@rDrErFrGrHrI)rZlengthZ	charcount�irNr*rLrrrrVs:
zSSLSocket.readline)N)N)r)N)N)�__name__�
__module__�__qualname__�__doc__rrr'r+r-r.r,r$r5r6r7r8r;rOrErSr>rTZsendallrVrrrrr+s*
	



3rcCs|S)zb
    Verify callback, which will be called for each certificate in the
    certificate chain.
    r)ZconnZcertZerrnum�depth�okrrrr%Ksr%c@seZdZdd�Zdd�ZdS)rQcGs
||_dS)N)rC)rrCrrrrUszTimeoutException.__init__cCsdS)NzTimeout Exceptionr)rrrr�__str__XszTimeoutException.__str__N)rYrZr[rr_rrrrrQSsrQ)r\ZOpenSSLrrrrrFZrhn.i18nrr2ZDEFAULT_TIMEOUTr&rrZsslrr%�ErrorZtimeoutrQrrrr�<module>s 
"PK���Z����__pycache__/tb.cpython-36.pycnu�[���3

U��ZD�@sLddlZyejjdkZWnek
r0dZYnXer@dd�Zned�dS)�N�FcCs|�dS)N�)�err�/usr/lib/python3.6/tb.py�
raise_with_tbsrz<
def raise_with_tb(e):
    raise e, None, sys.exc_info()[2]
)�sys�version_info�majorZPY3�AttributeErrorr�execrrrr�<module>s

PK���Z�n�P&&"__pycache__/SmartIO.cpython-36.pycnu�[���3

U��Zt�@sXdZddlZyddlmZWn ek
r<ddlmZYnXGdd�d�Zdd�ZdS)	z*
This module implements the SmartIO class
�N)�StringIO)�BytesIOc@s:eZdZdZddd�Zdd�Zdd	�Zd
d�Zdd
�ZdS)�SmartIOa�
    The SmartIO class allows one to put a cap on the memory consumption.
    StringIO objects are very fast, because they are stored in memory, but
    if they are too big the memory footprint becomes noticeable.
    The write method of a SmartIO determines if the data that is to be added
    to the (initially) StrintIO object does not exceed a certain threshold; if
    it does, it switches the storage to a temporary disk file
    �@rcCs$||_t�|_|rd|_nd|_dS)N�r)�
_max_mem_sizer�_io�_fixed)�self�max_mem_sizeZ	force_mem�r�/usr/lib/python3.6/SmartIO.py�__init__s
zSmartIO.__init__cCs
||_dS)N)r)r
rrrr
�set_max_mem_size'szSmartIO.set_max_mem_sizecCs|jS)N)r)r
rrr
�get_max_mem_size*szSmartIO.get_max_mem_sizecCsP|js@t|�|jj�|jkr@t�}|j|jj��d|_||_|jj|�dS)Nr)r	�lenr�tellr�	_tempfile�write�getvalue)r
�dataZtmpfilerrr
r-sz
SmartIO.writecCst|j|�S)N)�getattrr)r
�namerrr
�__getattr__9szSmartIO.__getattr__N)rr)	�__name__�
__module__�__qualname__�__doc__rrrrrrrrr
rs
rcCs6ddl}|jdtj�d�\}}tj|�tj|d�S)Nrz_rhn_transports-%d-)�prefixzwb+)�tempfileZmkstemp�os�getpid�unlink�fdopen)r�fdZfnamerrr
r=s

r)	rr Z	cStringIOr�ImportError�iorrrrrrr
�<module>
s+PK���Z��u�__&__pycache__/nonblocking.cpython-36.pycnu�[���3

U��Z{	�@s�ddlZddlZddlZGdd�d�Zdd�Zedkr�ddlZejejej�Z	e	j
d
�e	j�Zee�Z
ejejej�Zej
d�ej�Ze
jegggde�e
j�Zeee��dS)�Nc@s6eZdZdd�Zdd�Zd
dd�Zdd	�Zd
d�ZdS)�NonBlockingFilecCs@||_tj|jj�tjtj�g|_g|_g|_d|_	d|_
dS)N)�fd�fcntl�fileno�F_SETFL�os�O_NDELAY�read_fd_set�write_fd_set�
exc_fd_set�	user_data�callback)�selfr�r�!/usr/lib/python3.6/nonblocking.py�__init__
szNonBlockingFile.__init__cCsH||_x$|jD]}tj|j�tjtj�qW||_||_||_||_	dS)N)
r	rrrrrr
rrr
)rr	r
rrr
�frrr�set_callbackszNonBlockingFile.set_callbackrcCs�x�d}|j|jg}|j}|j}td|�tj|||�\}}}td|||�|j|krfd}|j|j�|jr�|sx|sx|r�|j||||j�|rPqWtd�|jj	|�S)NrzCalling selectzSelect returned�Z	Returning)
r	rr
r�print�select�remover
r�read)rZamtZstatus_changedZreadfdsZwritefdsZexcfdsrrrr!s"

zNonBlockingFile.readcCs|jj|�S)N)r�write)r�datarrrr7szNonBlockingFile.writecCst|j|�S)N)�getattrr)r�namerrr�__getattr__:szNonBlockingFile.__getattr__N)r)�__name__�
__module__�__qualname__rrrrrrrrrr	s

rcCs"td|||�t|dj��dS)NzCallback calledr)rr)�r�w�errrrr
=sr
�__main__�	localhost��)r%r&)r%r')rrrrr
rZsocketZAF_INETZSOCK_STREAM�sZconnect�makefilerZss�s2rrZxxr�lenrrrr�<module>s 4

PK���Z����&__pycache__/connections.cpython-36.pycnu�[���3

�U�f�%�@s&ddlZddlZddlZddlmZddlmZddlmZddlm	Z	y(ddl
Z
ddl
mZmZm
Z
ddlZWn<ek
r�ddljZ
ddlmZmZm
Z
ddljZYnXGdd�de
j�ZGd	d
�d
e
j�ZGdd�de�ZGd
d�de�ZGdd�de�ZGdd�de�Zdd�Zdd�ZdS)�N)�python_version)�SSL)�nonblocking)�i18n)�_CS_REQ_SENT�_CS_IDLE�ResponseNotReadyc@seZdZdd�ZdS)�HTTPResponsecCs4t|jtj�stj|j�|_|jj|||||�dS)N)�
isinstance�fprZNonBlockingFile�set_callback)�self�rs�ws�ex�	user_data�callback�r�!/usr/lib/python3.6/connections.pyr szHTTPResponse.set_callbackN)�__name__�
__module__�__qualname__rrrrrr	sr	c@s@eZdZeZdejfdd�Zdd�Zdd�Z	dd	�Z
d
d�ZdS)�HTTPConnectionNcCs^t�dkr tjj||||d�ntjj|||�g|_g|_g|_d|_d|_d|_	||_
dS)Nz2.6.1)�timeoutz#rhn.connections $Revision$ (python))r�httplibr�__init__�_cb_rs�_cb_ws�_cb_ex�
_cb_user_data�_cb_callback�_user_agentr)r
�host�portrrrrr(s
zHTTPConnection.__init__cCs"||_||_||_||_||_dS)N)rrrrr )r
rrrrrrrrr5s
zHTTPConnection.set_callbackcCs
||_dS)N)r!)r
Z
user_agentrrr�set_user_agent=szHTTPConnection.set_user_agentcCs�|jr|jj�rd|_|jtks&|jr,t��|jdkrH|j|j|j�}n|j|j�}|jrv|j	|j
|j|j|j
|j�|j�|jtjks�t�t|_|jr�|j�n||_|S)z!Get the response from the server.Nr)Z_HTTPConnection__responseZisclosedZ_HTTPConnection__staterrZ
debuglevel�response_class�sockr rrrrr�begin�
will_closerZ_UNKNOWN�AssertionErrorr�close)r
�responserrr�getresponseBs"

zHTTPConnection.getresponsecCstjj|�|jj|j�dS)N)rr�connectr&�
settimeoutr)r
rrrr-sszHTTPConnection.connect)rrrr	r%r�DEFAULT_TIMEOUTrrr$r,r-rrrrr%s
1rc@sBeZdZdddejfdd�Zdd�Zd
dd�Zd	d
�Zdd�Z	dS)�HTTPProxyConnectionNcCsPtj|||d�|j|j|_|_|j||�|j|j|_|_||_	||_
dS)N)r)rrr"r#�_HTTPProxyConnection__proxy� _HTTPProxyConnection__proxy_port�
_set_hostport�_host�_port�_HTTPProxyConnection__username�_HTTPProxyConnection__password)r
�proxyr"r#�username�passwordrrrrryszHTTPProxyConnection.__init__cCs.|j|j|j�tj|�|j|j|j�dS)N)r3r1r2rr-r4r5)r
rrrr-�s
zHTTPProxyConnection.connectrcCsN|j}|j|jkr$|dt|j�}d||f}tj||||d�|j�dS)N�:zhttp://%s%s)�	skip_host)r4r5�default_port�strr�
putrequest�_add_proxy_headers)r
�method�urlr<�hostnameZnewurlrrrr?�szHTTPProxyConnection.putrequestcCsX|js
dSd|j|jf}tjtj|��jtjd�tjd��}|jddtj|��dS)Nz%s:%s�
�zProxy-AuthorizationzBasic %s)	r6r7�base64Zencodestringr�bstr�replace�	putheaderZsstr)r
ZuserpassZenc_userpassrrrr@�s
$z&HTTPProxyConnection._add_proxy_headerscCs|j||�\|_|_dS)N)Z
_get_hostportr"r#)r
r"r#rrrr3�sz!HTTPProxyConnection._set_hostport)r)
rrrrr/rr-r?r@r3rrrrr0xs

r0c@s2eZdZeZejjZddej	fdd�Z
dd�ZdS)�HTTPSConnectionNcCs$tj||||d�|pg}||_dS)N)r)rr�
trusted_certs)r
r"r#rKrrrrr�szHTTPSConnection.__init__c	Cs�tj|j|jtjtj�}x�|D]�}|\}}}}}ytj|||�}Wntjk
r^d}wYnXy"|j|j|jf�|j|j	�Wn$tjk
r�|j
�d}wYnXPqW|dkr�tjd��tj||j
�|_|jj�dS)z'Connect to a host on a given (SSL) portNz0Unable to connect to the host and port specified)�socketZgetaddrinfor"r#Z	AF_UNSPECZSOCK_STREAM�errorr-r.rr*r�	SSLSocketrKr&�init_ssl)	r
�results�rZafZsocktype�protoZ	canonnameZsar&rrrr-�s*

zHTTPSConnection.connect)rrrr	r%rrJr=rr/rr-rrrrrJ�s
rJc@seZdZdd�ZdS)�HTTPSProxyResponsecCstj|�d|_dS)Nr)r	r'r()r
rrrr'�s
zHTTPSProxyResponse.beginN)rrrr'rrrrrS�srSc@sBeZdZejZddddejfdd�Zdd�Zddd�Z	d	d
�Z
dS)�HTTPSProxyConnectionNc	Cs*tj|||||||d�|pg}||_dS)N)r)r0rrK)r
r8r"r#r9r:rKrrrrr�s
zHTTPSProxyConnection.__init__cCs�tj|�d|j|jf}tj|d|�|j�tj|�|j}t	|_tj
|�}||_|j�|jdkr�|j�t
j||j|j|j��tj|j|j�|_|jj�dS)Nz%s:%sZCONNECT��)r0r-r4r5rr?r@Z
endheadersr%rSr,r*Zstatus�	xmlrpclibZ
ProtocolError�reason�msgrrNr&rKrO)r
r"r%r+rrrr-�s 



zHTTPSProxyConnection.connectrcCstj||||d�S)N)r<)rr?)r
rArBr<rrrr?�szHTTPSProxyConnection.putrequestcCstj|�|jd|j�dS)Nz
User-Agent)r0r@rIr!)r
rrrr@�s
z'HTTPSProxyConnection._add_proxy_headers)r)rrrrJr=rr/rr-r?r@rrrrrT�s
rTcCs$|dkrdStj|�}|jd�SdS)zJ Convert Internationalized domain name from Punycode (RFC3492) to Unicode N�idna)rrG�decode)rCrrr�idn_puny_to_unicode�s
r[cCs*|dkrdStj|�}tj|jd��SdS)zZ Convert domain name to Punycode (RFC3492). Hostname can be instance of string or Unicode NrY)rZustr�encode)rCrrr�idn_ascii_to_punys
r])rFZencodings.idnaZ	encodingsrL�platformrZrhnrrrrrrrrV�ImportErrorZhttp.clientZclientZ
xmlrpc.clientr	rr0rJrSrTr[r]rrrr�<module>
s,
S,&.PK���Z��u�__,__pycache__/nonblocking.cpython-36.opt-1.pycnu�[���3

U��Z{	�@s�ddlZddlZddlZGdd�d�Zdd�Zedkr�ddlZejejej�Z	e	j
d
�e	j�Zee�Z
ejejej�Zej
d�ej�Ze
jegggde�e
j�Zeee��dS)�Nc@s6eZdZdd�Zdd�Zd
dd�Zdd	�Zd
d�ZdS)�NonBlockingFilecCs@||_tj|jj�tjtj�g|_g|_g|_d|_	d|_
dS)N)�fd�fcntl�fileno�F_SETFL�os�O_NDELAY�read_fd_set�write_fd_set�
exc_fd_set�	user_data�callback)�selfr�r�!/usr/lib/python3.6/nonblocking.py�__init__
szNonBlockingFile.__init__cCsH||_x$|jD]}tj|j�tjtj�qW||_||_||_||_	dS)N)
r	rrrrrr
rrr
)rr	r
rrr
�frrr�set_callbackszNonBlockingFile.set_callbackrcCs�x�d}|j|jg}|j}|j}td|�tj|||�\}}}td|||�|j|krfd}|j|j�|jr�|sx|sx|r�|j||||j�|rPqWtd�|jj	|�S)NrzCalling selectzSelect returned�Z	Returning)
r	rr
r�print�select�remover
r�read)rZamtZstatus_changedZreadfdsZwritefdsZexcfdsrrrr!s"

zNonBlockingFile.readcCs|jj|�S)N)r�write)r�datarrrr7szNonBlockingFile.writecCst|j|�S)N)�getattrr)r�namerrr�__getattr__:szNonBlockingFile.__getattr__N)r)�__name__�
__module__�__qualname__rrrrrrrrrr	s

rcCs"td|||�t|dj��dS)NzCallback calledr)rr)�r�w�errrrr
=sr
�__main__�	localhost��)r%r&)r%r')rrrrr
rZsocketZAF_INETZSOCK_STREAM�sZconnect�makefilerZss�s2rrZxxr�lenrrrr�<module>s 4

PK���Z�n�P&&(__pycache__/SmartIO.cpython-36.opt-1.pycnu�[���3

U��Zt�@sXdZddlZyddlmZWn ek
r<ddlmZYnXGdd�d�Zdd�ZdS)	z*
This module implements the SmartIO class
�N)�StringIO)�BytesIOc@s:eZdZdZddd�Zdd�Zdd	�Zd
d�Zdd
�ZdS)�SmartIOa�
    The SmartIO class allows one to put a cap on the memory consumption.
    StringIO objects are very fast, because they are stored in memory, but
    if they are too big the memory footprint becomes noticeable.
    The write method of a SmartIO determines if the data that is to be added
    to the (initially) StrintIO object does not exceed a certain threshold; if
    it does, it switches the storage to a temporary disk file
    �@rcCs$||_t�|_|rd|_nd|_dS)N�r)�
_max_mem_sizer�_io�_fixed)�self�max_mem_sizeZ	force_mem�r�/usr/lib/python3.6/SmartIO.py�__init__s
zSmartIO.__init__cCs
||_dS)N)r)r
rrrr
�set_max_mem_size'szSmartIO.set_max_mem_sizecCs|jS)N)r)r
rrr
�get_max_mem_size*szSmartIO.get_max_mem_sizecCsP|js@t|�|jj�|jkr@t�}|j|jj��d|_||_|jj|�dS)Nr)r	�lenr�tellr�	_tempfile�write�getvalue)r
�dataZtmpfilerrr
r-sz
SmartIO.writecCst|j|�S)N)�getattrr)r
�namerrr
�__getattr__9szSmartIO.__getattr__N)rr)	�__name__�
__module__�__qualname__�__doc__rrrrrrrrr
rs
rcCs6ddl}|jdtj�d�\}}tj|�tj|d�S)Nrz_rhn_transports-%d-)�prefixzwb+)�tempfileZmkstemp�os�getpid�unlink�fdopen)r�fdZfnamerrr
r=s

r)	rr Z	cStringIOr�ImportError�iorrrrrrr
�<module>
s+PK���Z*��
�
,__pycache__/rhnLockfile.cpython-36.opt-1.pycnu�[���3

U��Zc
�@s~ddlZddlZddlZddlmZmZddlmZddlZGdd�de�Z	Gdd�d�Z
dd	�Zed
krzej
e�pvd�dS)�N)�EWOULDBLOCK�EEXIST)�bstrc@seZdZdZdS)�LockfileLockedExceptionz$thrown ONLY when pid file is locked.N)�__name__�
__module__�__qualname__�__doc__�r
r
�!/usr/lib/python3.6/rhnLockfile.pyrsrc@s*eZdZdZd	dd�Zdd�Zdd�ZdS)
�Lockfilez�class that provides simple access to a PID-style lockfile.

    methods: __init__(lockfile), acquire(), and release()
    NOTE: currently acquires upon init
    The *.pid file will be acquired, or an LockfileLockedException is raised.
    NcCs�tjjtjjtjj|���|_||_|js4tj�|_tjj|j�}tjj	|�s�ytj
|�Wn8tk
r�tj
�d}t|d�r�|jtkr�n�YnXtj|jtjtjBtjB�|_|j�dS)zlcreate (if need be), and acquire lock on lockfile

        lockfile example: '/var/run/up2date.pid'
        ��errnoN)�os�path�abspath�
expanduser�
expandvars�lockfile�pid�getpid�dirname�exists�makedirs�OSError�sys�exc_info�hasattrrr�open�O_RDWR�O_CREAT�O_SYNC�f�acquire)�selfrrr�er
r
r�__init__$s"
zLockfile.__init__c
Cs�ytj|jtjtjB�WnDtk
r^tj�djt	krXt
d|jdtj�d��n�YnXtj|jtjd�t
j|jd�t
j|jtt|j�d��dS)z5acquire the lock; else raise LockfileLockedException.r
zcannot acquire lock on %s.N�r�
)�fcntl�flockr"ZLOCK_EXZLOCK_NB�IOErrorrrrrrrZF_SETFDr�	ftruncate�writer�strr)r$r
r
rr#EszLockfile.acquirecCs,tj|j�tj|jtj�tj|j�dS)N)r�unlinkrr)r*r"ZLOCK_UN�close)r$r
r
r�releaseVszLockfile.release)N)rrrr	r&r#r1r
r
r
rrs
!rcCszytd�}Wn6tk
rBtjjdtj�d�tjd
�Yn4Xtd�td�ddl}|j	d�|j
�td	�dS)z	test codez
./test.pidz%s
r
zlock acquired z...sleeping for 10 secondsrN�
zlock released ���)rrr�stderrr-r�exit�print�timeZsleepr1)�Lr7r
r
r�main]s
r9�__main__)rrr)rrrZrhn.i18nr�	Exceptionrrr9rr5r
r
r
r�<module>sBPK���Z*��
�
&__pycache__/rhnLockfile.cpython-36.pycnu�[���3

U��Zc
�@s~ddlZddlZddlZddlmZmZddlmZddlZGdd�de�Z	Gdd�d�Z
dd	�Zed
krzej
e�pvd�dS)�N)�EWOULDBLOCK�EEXIST)�bstrc@seZdZdZdS)�LockfileLockedExceptionz$thrown ONLY when pid file is locked.N)�__name__�
__module__�__qualname__�__doc__�r
r
�!/usr/lib/python3.6/rhnLockfile.pyrsrc@s*eZdZdZd	dd�Zdd�Zdd�ZdS)
�Lockfilez�class that provides simple access to a PID-style lockfile.

    methods: __init__(lockfile), acquire(), and release()
    NOTE: currently acquires upon init
    The *.pid file will be acquired, or an LockfileLockedException is raised.
    NcCs�tjjtjjtjj|���|_||_|js4tj�|_tjj|j�}tjj	|�s�ytj
|�Wn8tk
r�tj
�d}t|d�r�|jtkr�n�YnXtj|jtjtjBtjB�|_|j�dS)zlcreate (if need be), and acquire lock on lockfile

        lockfile example: '/var/run/up2date.pid'
        ��errnoN)�os�path�abspath�
expanduser�
expandvars�lockfile�pid�getpid�dirname�exists�makedirs�OSError�sys�exc_info�hasattrrr�open�O_RDWR�O_CREAT�O_SYNC�f�acquire)�selfrrr�er
r
r�__init__$s"
zLockfile.__init__c
Cs�ytj|jtjtjB�WnDtk
r^tj�djt	krXt
d|jdtj�d��n�YnXtj|jtjd�t
j|jd�t
j|jtt|j�d��dS)z5acquire the lock; else raise LockfileLockedException.r
zcannot acquire lock on %s.N�r�
)�fcntl�flockr"ZLOCK_EXZLOCK_NB�IOErrorrrrrrrZF_SETFDr�	ftruncate�writer�strr)r$r
r
rr#EszLockfile.acquirecCs,tj|j�tj|jtj�tj|j�dS)N)r�unlinkrr)r*r"ZLOCK_UN�close)r$r
r
r�releaseVszLockfile.release)N)rrrr	r&r#r1r
r
r
rrs
!rcCszytd�}Wn6tk
rBtjjdtj�d�tjd
�Yn4Xtd�td�ddl}|j	d�|j
�td	�dS)z	test codez
./test.pidz%s
r
zlock acquired z...sleeping for 10 secondsrN�
zlock released ���)rrr�stderrr-r�exit�print�timeZsleepr1)�Lr7r
r
r�main]s
r9�__main__)rrr)rrrZrhn.i18nr�	Exceptionrrr9rr5r
r
r
r�<module>sBPK���Z/F�J4G4G'__pycache__/rpclib.cpython-36.opt-1.pycnu�[���3

�U�f�^�@s`dZddlZddlZddlZddlmZddlmZddlm	Z	y<ddl
Z
ddlmZm
Z
mZmZmZmZddlmZmZWnFek
r�ddljZ
eZeZ
eZeZeZeZddlmZmZYnXdZd	d
�Zdd�Z d
d�Z!Gdd�de"�Z#Gdd�d�Z$Gdd�de$�Z%Gdd�de&�Z'Gdd�de&�Z(dd�Z)Gdd�d�Z*Gdd�de*�Z+dd �Z,dS)!zI2.8.62.8.6-8.module_el8.10.0+6858+3ddf28328.module_el8.10.0+6858+3ddf2832�N)�
transports)�sstr)�UserDictCase)�ListType�	TupleType�
StringType�UnicodeType�DictType�DictionaryType)�	splittype�	splithost�c	Cs"ytjtj|�dSdSdS)z5 Returns true if n is IPv6 address, false otherwise. TFN)�socketZ	inet_ptonZAF_INET6)�n�r�/usr/lib/python3.6/rpclib.py�
check_ipv6.s
rc	Cs�|jdd�}d}d}d}d}t|�dkr^|d}|djdd�}|d}t|�dkrf|d}n|d}|ddkr�tjdtd�\}}|jd�jd	�}n6t|�r�|}n(|jdd�}|d}t|�dkr�|d}||||fS)
z| Function used to split host information in an URL per RFC 2396
        handle full hostname like user:passwd@host:port
    �@�N�r�:�[z(?<=\]):�])�split�len�reZip_port�lstrip�rstripr)	Z
hoststring�l�hostZport�userZpasswdZhostportZuserinfo�arrrrr�
split_host6s,
r"cCs8|dkrtd��|jdd�}t|�dkr0|d}t|�S)NzHost string cannot be nullz://rr)�
ValueErrorrrr")�proxyr!rrr�get_proxy_info[sr%c@seZdZdS)�MalformedURIErrorN)�__name__�
__module__�__qualname__rrrrr&gsr&c	@seZdZdZejZejZej	Z
ejZd;dd�Z
d<dd�Zdd	�Zd
d�Zdd
�Zdd�Zd=dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�ZeZd'd(�Zd>d)d*�Z d+d,�Z!d-d.�Z"d/d0�Z#d1d2�Z$d3d4�Z%d?d5d6�Z&d7d8�Z'd9d:�Z(dS)@�Servera7uri [,options] -> a logical connection to an XML-RPC server

    uri is the connection point on the server, given as
    scheme://host/target.

    The standard implementation always supports the "http" scheme.  If
    SSL socket support is available (Python 2.0), it also supports
    "https".

    If the target part and the slash preceding it are both omitted,
    "/RPC2" is assumed.

    The following options can be given as keyword arguments:

        transport: a transport factory
        encoding: the request encoding (default is UTF-8)
        verbose: verbosity level
        proxy: use an HTTP proxy
        username: username for authenticated HTTP proxy
        password: password for authenticated HTTP proxy

    All 8-bit strings passed to the server proxy are assumed to use
    the given encoding.
    NrcCs6|dkrZt|�\}}}
}|dk	r.d||f}n|}|
dk	rZ|dkrZ|
}|dk	rZ|dkrZ|}t|�|_d|_d|_d|_||_||_||_|
|_	t
tj��dkr�tj�d|_
nt|_
|j�|dkr�d|_|j|j||||
�}nd|_d|_d|_||_g|_d|_||_||_|j|�|j|	�d|_t�|_dS)Nz%s:%srr)r%r�_uri�_refreshCallback�_progressCallback�_bufferSize�_proxy�	_username�	_password�_timeoutr�__version__r�rpc_version�_reset_host_handler_and_type�_allow_redirect�default_transport�_type�_redirected�use_handler_path�
_transport�_trusted_cert_files�_lang�	_encoding�_verbose�set_refresh_callback�set_progress_callback�send_handlerr�_headers)�self�uri�	transport�encoding�verboser$�username�password�refreshCallback�progressCallback�timeoutZphZppZpuZpwrrr�__init__�sJ



zServer.__init__cCsZ|r4|dkr |j||||d�}qV|j||||d�}n"|dkrJ|j|d�}n|j|d�}|S)N�https)Z
proxyUsernameZ
proxyPasswordrM)rM)�_transport_class_https_proxy�_transport_class_proxy�_transport_class_https�_transport_class)rD�typer$rIrJrMrFrrrr7�szServer.default_transportcCs
||_dS)N)r6)rDZallowrrr�allow_redirect�szServer.allow_redirectcCs|js
dS|jS)N)r6r9)rDrrr�
redirected�szServer.redirectedcCs||_|jj|�dS)N)r,r;r@)rDrKrrrr@�szServer.set_refresh_callbackcCs||_|jj|�dS)N)r.r;�set_buffer_size)rD�
bufferSizerrrrW�szServer.set_buffer_size�@cCs||_|jj||�dS)N)r-r;rA)rDrLrXrrrrA�szServer.set_progress_callbackcCstj|||jd�S)N)rG)�	xmlrpclib�dumpsr>)rD�params�
methodnamerrr�	_req_body�szServer._req_bodycCs|jr|jjSdS)N)r;Z
headers_in)rDrrr�get_response_headers�szServer.get_response_headerscCs|jr|jjSdS)N)r;�response_status)rDrrr�get_response_status�szServer.get_response_statuscCs|jr|jjSdS)N)r;Zresponse_reason)rDrrr�get_response_reasonszServer.get_response_reasonc	Cs�|j�}|sdS|jd�}|s"dStd|j��}|djd�}|\}}|dkrTd}nt|�}|jd�\}}|t|�t|�d�}|S)aSReturns a dictionary with three values:
            length: the total length of the entity-body (can be None)
            first_byte_pos: the position of the first byte (zero based)
            last_byte_pos: the position of the last byte (zero based)
           The range is inclusive; that is, a response 8-9/102 means two bytes
        Nz
Content-Ranger�/�*�-)ZlengthZfirst_byte_posZ
last_byte_pos)r_�get�filterr�int)	rD�headersZ
content_ranger!�brangeZ	total_len�start�end�resultrrr�get_content_ranges"
zServer.get_content_rangecCs$|j�}|sdSd|kr |dSdS)Nz
Accept-Ranges)r_)rDrirrr�
accept_ranges)szServer.accept_rangescCs�t|j�\}}|dkrtd��t|�dks:|dd�dkr>t�|dkrR|j�|_n||_|jdkrjtd	��t|�\|_|_	|j	s�d
|_	dS)z Reset the attributes:
            self._host, self._handler, self._type
            according the value of self._uri.
        Nzmissing protocol in uri�rrz//�httprOzunsupported XML-RPC protocolz/RPC2)rqrO)
rr+r&r�lowerr8�IOErrorr�_host�_handler)rDrTrErrrr51s
z#Server._reset_host_handler_and_typecs�d}g}x�|D]�}t|�}|tks*|tkr>tj|dt|��}nf|tkr^t�fdd�|D��}nF|tkrz�fdd�|D�}n*|t	ks�|t
kr�t�fdd�|j�D��}|j
|�qWt|�dkr�|d	St|�Sd
S)a> Strip characters, which are not allowed according:
            http://www.w3.org/TR/2006/REC-xml-20060816/#charsets
            From spec:
            Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]  /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
        z#[\x00-\x09]|[\x0b-\x0c]|[\x0e-\x1f]�c3s|]}�j|�VqdS)N)�_strip_characters)�.0�i)rDrr�	<genexpr>Usz+Server._strip_characters.<locals>.<genexpr>csg|]}�j|��qSr)rw)rxry)rDrr�
<listcomp>Wsz,Server._strip_characters.<locals>.<listcomp>csg|]\}}�j||��qSr)rw)rx�name�val)rDrrr{YsrrN)rTrrr�subrr�tuplerr	r
�dict�items�appendr)rD�argsZregexprm�itemZ	item_typer)rDrrwHs 
zServer._strip_charactersc
Cs�d}d}|j��xt|tkr$td��|jj�x$|jj�D]\}}|jj||�q:W|jjdd|j	�|jjdd�|j
r�|jjdd�|r�|jjd	d
�|jr�|jjd|j�|j|j
|�|�}y&|jj|j|j||jd�}|jj}	Wn2tjk
�r|j�r
�ntj�dj}	YnXd
|_|d7}|	dk�r:Pn|	dk�rLd|_q|jj�|_d|_d}|j
�srtd��|j�r�td|j|jf�t|j�\}
}|
d
k�r�|
j�}
|
dk�r�td|
��|jdk�r�|
dk�r�td��t |�\|_|_|j�sd|_|`|j!|
|j"|j#|j$|j%�|_|j&|j'�|j(|j)�|j*|j+�|j,|j-�|j.gkrt/|jd�rx|j.D]}|jj0|��qnWqWt1|t2j3��r�|St1|t4��r�t5|�dk�r�|d}|S)zL Call a method on the remote server
            we can handle redirections. rz!Unable to fetch requested PackagezX-Infoz+RPC Processor (C) Red Hat, Inc (version %s)zX-Client-VersionrzX-RHN-Transport-Capabilityzfollow-redirects=3zX-RHN-Redirect�0z
X-RHN-Path)rHN���-�.zRedirects not allowedz%s redirected to %srqrOz%Redirected to unsupported protocol %sz)HTTPS redirected to HTTP is not supportedz/RPC2�add_trusted_cert)r�r�)rqrO)6r5�MAX_REDIRECTIONS�InvalidRedirectionErrorr;Z
clear_headersrCr��
set_header�
add_headerr4r6rBr^rw�requestrtrur?r`rZZ
ProtocolErrorr:�sys�exc_info�errcoder9rV�printr+rrrr8rr7r/r0r1r2rAr-r@r,rWr.�setlangr=r<�hasattrr��
isinstancerZFilerr)
rDr]r\Zredirect_responseZretry�k�vr�ZresponseZ
save_response�typrE�certfilerrr�_requestbs�









zServer._requestcCsd|jj|j|jfS)Nz
<%s for %s%s>)�	__class__r'rtru)rDrrr�__repr__�szServer.__repr__cCst|j|�S)N)�_Methodr�)rDr|rrr�__getattr__�szServer.__getattr__cKs,|js
dS|j||d��|jjf|�dS)N)�transferrG)r;�update�set_transport_flags)rDr�rG�kwargsrrrr��s
zServer.set_transport_flagscCs|js
iS|jj�S)N)r;�get_transport_flags)rDrrrr��szServer.get_transport_flagscCsdS)Nr)rDrrr�reset_transport_flags�szServer.reset_transport_flagscCs@t|�tg�tf�gkr.dd�|D�|j|<nt|�|j|<dS)NcSsg|]}t|��qSr)�str)rx�arrrr{�sz%Server.set_header.<locals>.<listcomp>)rTrCr�)rDr|�argrrrr��szServer.set_headercCsF||jkr&|j|}t|t�s4|g}ng}|j|<|jt|��dS)N)rCr�rr�r�)rDr|r�Zvlistrrrr�s


zServer.add_headercCs(||_|jr$t|jd�r$|jj|�dS)Nr�)r=r;r�r�)rDZlangrrrr�
szServer.setlangcCstd��dS)NzThis method is deprecated)�NotImplementedError)rDZca_chainrrr�use_CA_chainszServer.use_CA_chaincCs.|jj|�|jr*t|jd�r*|jj|�dS)Nr�)r<r�r;r�r�)rDr�rrrr�szServer.add_trusted_certcCs|jr|jj�d|_dS)N)r;�close)rDrrrr�s
zServer.close)	NNrNNNNNN)NNNN)rY)rr)N))r'r(r)�__doc__rZ	TransportrSZ
SafeTransportrRZProxyTransportrQZSafeProxyTransportrPrNr7rUrVr@rWrAr^r_rarbrnror5rwr�r��__str__r�r�r�r�r�r�r�r�r�r�rrrrr*lsH
C

#s



r*c	@s\eZdZdddddidddf	dd�Zdd�Zdd�Zdd	d
�Zdd�Zd
d�Zddd�Z	dS)�	GETServerNrcCsBtj||||||||	|
d�	||_||_|j|_|jddd�dS)N)r$rIrJrFrKrLrM)�offset�amount)r*rNZ_client_versionrCru�
_orig_handler�	set_range)rDrErFr$rIrJZclient_versionrirKrLrMrrrrNszGETServer.__init__cCs$|st|�dkrtd��tdd�|jjd��}|d|d|gt|dd��}ddj|�|_|j|_|j	r�|j
r�|j�|_x$|jj
�D]\}}|jj||�q�W|jdk	�r |jdkr�t|j�d}|jdk	r�|t|j|jd�}ndt|j�}|jjd	d
|�|jjdd�dS)
Nrz$Required parameter channel not foundcSs|dkS)Nrvr)�xrrr�<lambda>5sz%GETServer._req_body.<locals>.<lambda>rcz$RHNrreZRangezbytes=)�allow_partial_contentrv)r�	Exceptionrgr�r�list�joinrurBr9r:�
_new_req_bodyrCr�r;r��_offsetr��_amountr�)rDr\r]Zh_compsZhndl�hr�rjrrrr^1s&"


zGETServer._req_bodycCst|j�\}}t|�\}}|S)N)rr9r)rDrTZtmpuriZsiteZhandlerrrrr�UszGETServer._new_req_bodycCs�|dk	rByt|�}Wn,tk
r@td|dtj�d��YnX|dk	r�yt|�}Wn,tk
r�td|dtj�d��YnX|dkr�td|��||_||_dS)NzInvalid value `%s' for offsetrzInvalid value `%s' for amountr)rhr#�
RangeErrorr�r�r�r�)rDr�r�rrrr�ZszGETServer.set_rangecCs|jjdd�dS)Nr)r�)r;r�)rDrrrr�oszGETServer.reset_transport_flagscCst|j|�S)N)�
SlicingMethodr�)rDr|rrrr�rszGETServer.__getattr__cCs$tj||||||d�}|jd�|S)N)r$rIrJrMZGET)r*r7Z
set_method)rDrTr$rIrJrM�retrrrr7vs
zGETServer.default_transport)NN)NNNN)
r'r(r)rNr^r�r�r�r�r7rrrrr�s$
r�c@seZdZdS)r�N)r'r(r)rrrrr�|sr�c@seZdZdS)r�N)r'r(r)rrrrr�sr�cCs>ddl}t||j�s*||kr&||gSgSdd�|j|�D�S)NrcSs g|]}|jdd�dj��qS)rr)r�strip)rxr�rrrr{�sz#getHeaderValues.<locals>.<listcomp>)�	mimetoolsr�ZMessageZgetallmatchingheaders)rir|r�rrr�getHeaderValues�s
r�c@s4eZdZdZdd�Zdd�Zdd�Zdd	�ZeZd
S)r�z{ some magic to bind an XML-RPC method to an RPC server.
        supports "nested" methods (e.g. examples.getStateName)
    cCs||_||_dS)N)�_send�_name)rD�sendr|rrrrN�sz_Method.__init__cCst|jd|j|f�S)Nz%s.%s)r�r�r�)rDr|rrrr��sz_Method.__getattr__cGs|j|j|�S)N)r�r�)rDr�rrr�__call__�sz_Method.__call__cCsd|jj|j|jfS)Nz<%s %s (%s)>)r�r'r�r�)rDrrrr��sz_Method.__repr__N)	r'r(r)r�rNr�r�r�r�rrrrr��sr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)	r�z;
    A "slicing method" allows for byte range requests
    cCstj|||�d|_dS)N)r�rNr�)rDr�r|rrrrN�szSlicingMethod.__init__cCst|jd|j|f�S)Nz%s.%s)r�r�r�)rDr|rrrr��szSlicingMethod.__getattr__cOs�|jd�|_|jd�|_y|jjj|j|jd�Wntk
rFYnX|j|j|�}y|jjj�Wntk
rzYnX|S)Nr�r�)r�r�)	rfr�r�r�Zim_selfr��AttributeErrorr�r�)rDr�r�rmrrrr��szSlicingMethod.__call__N)r'r(r)r�rNr�r�rrrrr��sr�cCsbd}d}d}||kr t||�}d}||krZt||�}|rZdj|�}ddl}d|j|�}||fS)z% Reports the error from the headers. rrvzX-RHN-Fault-CodezX-RHN-Fault-StringNz%s)rhr�r��base64Zdecodestring)rir��errmsg�sZ_sListZ_sr�rrr�reportError�s

r�)-r3rrr�ZrhnrZrhn.i18nrZrhn.UserDictCaserrZ�typesrrrrr	r
Zurllibrr�ImportErrorZ
xmlrpc.clientZclientr�r�bytesr�r�Zurllib.parser�rr"r%rsr&r*r�r�r�r�r�r�r�r�rrrr�<module>sF 
%5^
PK���Z����#__pycache__/__init__.cpython-36.pycnu�[���3

U��Z��@sdZdS)z?
rhn - A collection of modules used by Red Hat Network Classic
N)�__doc__�rr�/usr/lib/python3.6/__init__.py�<module>sPK���Z����)__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

U��Z��@sdZdS)z?
rhn - A collection of modules used by Red Hat Network Classic
N)�__doc__�rr�/usr/lib/python3.6/__init__.py�<module>sPK���Z~��RR__pycache__/SSL.cpython-36.pycnu�[���3

�U�f-+�@s�dZddlmZddlmZddlZddlZddlZddlmZddl	Z	dZ
eed�r^ejZ
nddlm
Z
Gd	d
�d
�Zdd�ZGd
d�dejej�ZdS)zK
rhn.SSL builds an abstraction on top of the objects provided by pyOpenSSL
�)�SSL)�cryptoN)�bstr�x�sslerror)�socket_errorc@s�eZdZdZd(dd�Zdd�Zdd�Zd)d	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zd*dd�Zd+dd�Zdd�Zd d!�Zd"d#�Zd$d%�ZeZeZd,d&d'�ZdS)-�	SSLSocketzM
    Class that wraps a pyOpenSSL Connection object, adding more methods
    NcCsnd|_d|_||_g|_|pg}x|D]}|j|�q&Wtj|_tj|_	d|_
d|_td�|_
d|_d|_dS)Ni r�)�_ctx�_connection�_sock�_trusted_certs�add_trusted_certrZ
SSLv23_METHOD�_ssl_methodZVERIFY_PEER�_ssl_verify_flags�_buffer_size�_posr�_buffer�_makefile_called�_closed)�self�socketZ
trusted_certs�f�r�/usr/lib/python3.6/SSL.py�__init__/s

zSSLSocket.__init__cCs0tj|tj�std|��|jj|jd��dS)zh
        Adds a trusted certificate to the certificate store of the SSL context
        object.
        z"Unable to read certificate file %szutf-8N)�os�access�R_OK�
ValueErrorr
�append�encode)r�filerrrrLszSSLSocket.add_trusted_certcCs�|j�tj|j�|_|jjtj�|jjtj�|jrVx"|jD]}|jj	|�q@Wnd|_
|jj|j
t�t
td�r�|jjtj�tj|j|j�|_|jj�dS)z1
        Initializes the SSL connection.
        r�OP_DONT_INSERT_EMPTY_FRAGMENTSN)�
_check_closedrZContextrr
Zset_optionsZOP_NO_SSLv2ZOP_NO_SSLv3r
Zload_verify_locationsrZ
set_verify�ssl_verify_callback�hasattrr#Z
ConnectionrrZset_connect_state)rrrrr�init_sslUs
zSSLSocket.init_sslcCs|r
||_|jd|_|S)zG
        Returns self, since we are a file-like object already
        �)rr)r�mode�bufsizerrr�makefilesszSSLSocket.makefilecCs,|jr
dS|js|j�dS|jd|_dS)z+
        Closes the SSL connection
        Nr()rr�
_really_close)rrrr�close�szSSLSocket.closecCsdS)Nr)rrrr�flush�szSSLSocket.flushcCs�|jdkrdSd}yt|jd�}Wn tk
rBt|jd�}YnX|dk	r�tjddkrp|�dkr�|jj�n|�dkr�|jj�|jj�d|_dS)NZstate_stringZget_state_stringr�s%SSL negotiation finished successfullyz%SSL negotiation finished successfullyr()r�getattr�AttributeError�sys�version_infoZshutdownr-r)rZ	get_staterrrr,�s




zSSLSocket._really_closecCs|jrtd��dS)NzI/O operation on closed file)rr)rrrrr$�szSSLSocket._check_closedcCs$t|j|�rt|j|�St|��dS)N)r&rr0r1)r�namerrr�__getattr__�szSSLSocket.__getattr__cCsdS)z'
        Returns false always.
        rr)rrrr�isatty�szSSLSocket.isattycCs|jS)N)r)rrrr�tell�szSSLSocket.tellrcCstd��dS)N�seek)�NotImplementedError)r�posr)rrrr8�szSSLSocket.seekcCsX|j�|j}t|j�}x�||ks,|dk�r|dk	rBt|||�}y:|jj|�}|j||_t|j�}|jj�}|dkrzPWqtj	k
r�PYqtj
k
r�tj�d}t
d|j�PYqtjk
r�|jtjd�Yqtjk
�r|jtjd�YqXqW|�r4|jd|�}|j|d�|_n|j}td�|_|jt|�|_|S)z@
        Reads up to amt bytes from the SSL connection.
        Nrr(z
SSL exception�readr	)r$r�lenr�minr�recv�pendingr�ZeroReturnErrorZSysCallErrorr2�exc_info�print�args�WantWriteError�_poll�select�POLLOUT�
WantReadError�POLLINrr)r�amt�buffer_sizeZ
buffer_length�datar?�e�retrrrr;�s<



zSSLSocket.readcCs|jt|��|dd�<t|�S)N)r;r<)rZbufrrr�readinto�szSSLSocket.readintocCsBtj�}|j|j|�|j|jj�d�}|gkr>td|��dS)Ni�zConnection timed out on %s)rFZpoll�registerrZ
gettimeout�TimeoutException)rZfilter_typeZcaller_nameZpoller�resrrrrE�s
zSSLSocket._pollcCs�|j�t|�}xvy*|jj|�}|t|�kr.P||d�}Wqtjk
r`|jtjd�Yqtj	k
r�|jtj
d�YqXqW|S)z/
        Writes to the SSL connection.
        N�write)r$r<r�sendrrDrErFrGrHrI)rrLZoriglenZsentrrrrS�szSSLSocket.writecCs
|j|�S)N)r;)rrJrrrr>szSSLSocket.recvcCsB|j��xd}|jjtd��}|dkr2|d}n|rHt|j�|krH|}|dk	r�|jd|�}|j|d�|_|jt|�|_|S|j}|r�t|j|t|j��}y|jj	|�}|j||_Wqt
jk
r�PYqt
jk
r�|j
tjd�Yqt
jk
�r|j
tjd�YqXqW|j}d|_|jt|�|_|S)zg
        Reads a single line (up to `length' characters long) from the SSL
        connection.
        N�
rr(�readliner	)r$r�findrr<rrr=rr>rr@rDrErFrGrHrI)rZlengthZ	charcount�irNr*rLrrrrVs:
zSSLSocket.readline)N)N)r)N)N)�__name__�
__module__�__qualname__�__doc__rrr'r+r-r.r,r$r5r6r7r8r;rOrErSr>rTZsendallrVrrrrr+s*
	



3rcCs|S)zb
    Verify callback, which will be called for each certificate in the
    certificate chain.
    r)ZconnZcertZerrnum�depth�okrrrr%Ksr%c@seZdZdd�Zdd�ZdS)rQcGs
||_dS)N)rC)rrCrrrrUszTimeoutException.__init__cCsdS)NzTimeout Exceptionr)rrrr�__str__XszTimeoutException.__str__N)rYrZr[rr_rrrrrQSsrQ)r\ZOpenSSLrrrrrFZrhn.i18nrr2ZDEFAULT_TIMEOUTr&rrZsslrr%�ErrorZtimeoutrQrrrr�<module>s 
"PK���Z�kull__pycache__/i18n.cpython-36.pycnu�[���3

U��Z��@sPddlmZyejdkZWnek
r2dZYnXdd�Zdd�Zdd	�Zd
S)�)�version_info�FcCs@tr"t|t�r|St|ddd�Snt|t�r0|St|dd�SdS)N�utf8�ignore)�errors)�PY3�
isinstance�strZunicode)�obj�r�/usr/lib/python3.6/i18n.py�ustrs

r
cCsDtr"t|t�r|St|ddd�Snt|t�r0|St|jdd��SdS)Nrr)r)rr�bytesr	�encode)r
rrr�bstr&s

rcCsDtr"t|t�r|St|ddd�Snt|t�r0|St|jdd��SdS)Nrr)r)rrr	r)r
rrr�sstr2s

rN)�sysr�majorr�AttributeErrorr
rrrrrr�<module>s
PK���Z��?�c
c
rhnLockfile.pynu�[���#
# Copyright (c) 2008--2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import os
import sys
import fcntl
from errno import EWOULDBLOCK, EEXIST
from rhn.i18n import bstr
import fcntl

class LockfileLockedException(Exception):
    """thrown ONLY when pid file is locked."""
    pass

class Lockfile:

    """class that provides simple access to a PID-style lockfile.

    methods: __init__(lockfile), acquire(), and release()
    NOTE: currently acquires upon init
    The *.pid file will be acquired, or an LockfileLockedException is raised.
    """

    def __init__(self, lockfile, pid=None):
        """create (if need be), and acquire lock on lockfile

        lockfile example: '/var/run/up2date.pid'
        """

        # cleanup the path and assign it.
        self.lockfile = os.path.abspath(
                          os.path.expanduser(
                            os.path.expandvars(lockfile)))

        self.pid = pid
        if not self.pid:
            self.pid = os.getpid()

        # create the directory structure
        dirname = os.path.dirname(self.lockfile)
        if not os.path.exists(dirname):
            try:
                os.makedirs(dirname)
            except OSError:
                e = sys.exc_info()[1]
                if hasattr(e, 'errno') and e.errno == EEXIST:
                    # race condition... dirname exists now.
                    pass
                else:
                    raise

        # open the file -- non-destructive read-write, unless it needs
        # to be created XXX: potential race condition upon create?
        self.f = os.open(self.lockfile, os.O_RDWR|os.O_CREAT|os.O_SYNC)
        self.acquire()

    def acquire(self):
        """acquire the lock; else raise LockfileLockedException."""

        try:
            fcntl.flock(self.f, fcntl.LOCK_EX|fcntl.LOCK_NB)
        except IOError:
            if sys.exc_info()[1].errno == EWOULDBLOCK:
                raise LockfileLockedException(
                  "cannot acquire lock on %s." % self.lockfile, None, sys.exc_info()[2])
            else:
                raise
        # unlock upon exit
        fcntl.fcntl(self.f, fcntl.F_SETFD, 1)
        # truncate and write the pid
        os.ftruncate(self.f, 0)
        os.write(self.f, bstr(str(self.pid) + '\n'))

    def release(self):
        # Remove the lock file
        os.unlink(self.lockfile)
        fcntl.flock(self.f, fcntl.LOCK_UN)
        os.close(self.f)


def main():
    """test code"""

    try:
        L = Lockfile('./test.pid')
    except LockfileLockedException:
        sys.stderr.write("%s\n" % sys.exc_info()[1])
        sys.exit(-1)
    else:
        print("lock acquired ")
        print("...sleeping for 10 seconds")
        import time
        time.sleep(10)
        L.release()
        print("lock released ")

if __name__ == '__main__':
    # test code
    sys.exit(main() or 0)

PK���Z��k��i18n.pynu�[���#
# This module contains all the RPC-related functions the RHN code uses
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

from sys import version_info

try:
    PY3 = version_info.major >= 3
except AttributeError:
    PY3 = False


def ustr(obj):
    # converts object to unicode like object
    if PY3: # python3
        if isinstance(obj, str):
            return obj
        else:
            return str(obj, 'utf8', errors='ignore')
    else: # python2
        if isinstance(obj, unicode):
            return obj
        return unicode(obj, 'utf8', 'ignore')

def bstr(obj):
    # converts object to bytes like object
    if PY3: # python3
        if isinstance(obj, bytes):
            return obj
        else:
            return bytes(obj, 'utf8', errors='ignore')
    else: # python2
        if isinstance(obj, str):
            return obj
        return str(obj.encode('utf8', 'ignore'))

def sstr(obj):
    # converts object to string
    if PY3: # python3
        if isinstance(obj, str):
            return obj
        else:
            return str(obj, 'utf8', errors='ignore')
    else: # python2
        if isinstance(obj, str):
            return obj
        return str(obj.encode('utf8', 'ignore'))
PK���Zʕe�-+-+SSL.pynu�[���#
# Higher-level SSL objects used by rpclib
#
# Copyright (c) 2002--2017 Red Hat, Inc.
#
# Author: Mihai Ibanescu <misa@redhat.com>
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.


"""
rhn.SSL builds an abstraction on top of the objects provided by pyOpenSSL
"""

from OpenSSL import SSL
# SSL.crypto is provided to other modules
from OpenSSL import crypto
import os

import socket
import select
from rhn.i18n import bstr
import sys

DEFAULT_TIMEOUT = 120

if hasattr(socket, 'sslerror'):
    socket_error = socket.sslerror
else:
    from ssl import socket_error

class SSLSocket:
    """
    Class that wraps a pyOpenSSL Connection object, adding more methods
    """
    def __init__(self, socket, trusted_certs=None):
        # SSL.Context object
        self._ctx = None
        # SSL.Connection object
        self._connection = None
        self._sock = socket
        self._trusted_certs = []
        # convert None to empty list
        trusted_certs = trusted_certs or []
        for f in trusted_certs:
            self.add_trusted_cert(f)
        # SSL method to use
        self._ssl_method = SSL.SSLv23_METHOD
        # Flags to pass to the SSL layer
        self._ssl_verify_flags = SSL.VERIFY_PEER

        # Buffer size for reads
        self._buffer_size = 8192

        # Position, for tell()
        self._pos = 0
        # Buffer
        self._buffer = bstr("")

        # Flag to show if makefile() was called
        self._makefile_called = 0

        self._closed = None

    def add_trusted_cert(self, file):
        """
        Adds a trusted certificate to the certificate store of the SSL context
        object.
        """
        if not os.access(file, os.R_OK):
            raise ValueError("Unable to read certificate file %s" % file)
        self._trusted_certs.append(file.encode("utf-8"))

    def init_ssl(self):
        """
        Initializes the SSL connection.
        """
        self._check_closed()
        # Get a context
        self._ctx = SSL.Context(self._ssl_method)
        self._ctx.set_options(SSL.OP_NO_SSLv2)
        self._ctx.set_options(SSL.OP_NO_SSLv3)
        if self._trusted_certs:
            # We have been supplied with trusted CA certs
            for f in self._trusted_certs:
                self._ctx.load_verify_locations(f)
        else:
            # Reset the verify flags
            self._ssl_verify_flags = 0

        self._ctx.set_verify(self._ssl_verify_flags, ssl_verify_callback)
        if hasattr(SSL, "OP_DONT_INSERT_EMPTY_FRAGMENTS"):
            # Certain SSL implementations break when empty fragments are
            # initially sent (even if sending them is compliant to
            # SSL 3.0 and TLS 1.0 specs). Play it safe and disable this
            # feature (openssl 0.9.6e and later)
            self._ctx.set_options(SSL.OP_DONT_INSERT_EMPTY_FRAGMENTS)

        # Init the connection
        self._connection = SSL.Connection(self._ctx, self._sock)
        # Place the connection in client mode
        self._connection.set_connect_state()

    def makefile(self, mode, bufsize=None):
        """
        Returns self, since we are a file-like object already
        """
        if bufsize:
            self._buffer_size = bufsize

        # Increment the counter with the number of times we've called makefile
        # - we don't want close to actually close things until all the objects
        # that originally called makefile() are gone
        self._makefile_called = self._makefile_called + 1
        return self

    def close(self):
        """
        Closes the SSL connection
        """
        # XXX Normally sock.makefile does a dup() on the socket file
        # descriptor; httplib relies on this, but there is no dup for an ssl
        # connection; so we have to count how may times makefile() was called
        if self._closed:
            # Nothing to do
            return
        if not self._makefile_called:
            self._really_close()
            return
        self._makefile_called = self._makefile_called - 1

    # BZ 1464157 - Python 3 http attempts to call this method during close,
    # at least add it empty
    def flush(self):
        pass

    def _really_close(self):
        # No connection was established
        if self._connection is None:
            return
        get_state = None
        try:
            get_state = getattr(self._connection, 'state_string')
        except AttributeError:
            get_state = getattr(self._connection, 'get_state_string')

        if get_state is not None:
            # for Python 3
            if sys.version_info[0] == 3:
                if get_state() == b'SSL negotiation finished successfully':
                    self._connection.shutdown()
            # for Python 2
            else:
                if get_state() == 'SSL negotiation finished successfully':
                    self._connection.shutdown()

        self._connection.close()
        self._closed = 1

    def _check_closed(self):
        if self._closed:
            raise ValueError("I/O operation on closed file")

    def __getattr__(self, name):
        if hasattr(self._connection, name):
            return getattr(self._connection, name)
        raise AttributeError(name)

    # File methods
    def isatty(self):
        """
        Returns false always.
        """
        return 0

    def tell(self):
        return self._pos

    def seek(self, pos, mode=0):
        raise NotImplementedError("seek")

    def read(self, amt=None):
        """
        Reads up to amt bytes from the SSL connection.
        """
        self._check_closed()
        # Initially, the buffer size is the default buffer size.
        # Unfortunately, pending() does not return meaningful data until
        # recv() is called, so we only adjust the buffer size after the
        # first read
        buffer_size = self._buffer_size

        buffer_length = len(self._buffer)
        # Read only the specified amount of data
        while buffer_length < amt or amt is None:
            # if amt is None (read till the end), fills in self._buffer
            if amt is not None:
                buffer_size = min(amt - buffer_length, buffer_size)

            try:
                data = self._connection.recv(buffer_size)

                self._buffer = self._buffer + data
                buffer_length = len(self._buffer)

                # More bytes to read?
                pending = self._connection.pending()
                if pending == 0:
                    # we're done here
                    break
            except SSL.ZeroReturnError:
                # Nothing more to be read
                break
            except SSL.SysCallError:
                e = sys.exc_info()[1]
                print("SSL exception", e.args)
                break
            except SSL.WantWriteError:
                self._poll(select.POLLOUT, 'read')
            except SSL.WantReadError:
                self._poll(select.POLLIN, 'read')

        if amt:
            ret = self._buffer[:amt]
            self._buffer = self._buffer[amt:]
        else:
            ret = self._buffer
            self._buffer = bstr("")

        self._pos = self._pos + len(ret)
        return ret

    def readinto(self, buf):
        buf[:] = self.read(len(buf))
        return len(buf)

    def _poll(self, filter_type, caller_name):
        poller = select.poll()
        poller.register(self._sock, filter_type)
        res = poller.poll(self._sock.gettimeout() * 1000)
        if res == []:
            raise TimeoutException("Connection timed out on %s" % caller_name)

    def write(self, data):
        """
        Writes to the SSL connection.
        """
        self._check_closed()

        # XXX Should use sendall
        # sent = self._connection.sendall(data)
        origlen = len(data)
        while True:
            try:
                sent = self._connection.send(data)
                if sent == len(data):
                    break
                data = data[sent:]
            except SSL.WantWriteError:
                self._poll(select.POLLOUT, 'write')
            except SSL.WantReadError:
                self._poll(select.POLLIN, 'write')

        return origlen

    def recv(self, amt):
        return self.read(amt)

    send = write

    sendall = write

    def readline(self, length=None):
        """
        Reads a single line (up to `length' characters long) from the SSL
        connection.
        """
        self._check_closed()
        while True:
            # charcount contains the number of chars to be outputted (or None
            # if none to be outputted at this time)
            charcount = None
            i = self._buffer.find(bstr('\n'))
            if i >= 0:
                # Go one char past newline
                charcount = i + 1
            elif length and len(self._buffer) >= length:
                charcount = length

            if charcount is not None:
                ret = self._buffer[:charcount]
                self._buffer = self._buffer[charcount:]
                self._pos = self._pos + len(ret)
                return ret

            # Determine the number of chars to be read next
            bufsize = self._buffer_size
            if length:
                # we know length > len(self._buffer)
                bufsize = min(self._buffer_size, length - len(self._buffer))

            try:
                data = self._connection.recv(bufsize)
                self._buffer = self._buffer + data
            except SSL.ZeroReturnError:
                # Nothing more to be read
                break
            except SSL.WantWriteError:
                self._poll(select.POLLOUT, 'readline')
            except SSL.WantReadError:
                self._poll(select.POLLIN, 'readline')

        # We got here if we're done reading, so return everything
        ret = self._buffer
        self._buffer = ""
        self._pos = self._pos + len(ret)
        return ret


def ssl_verify_callback(conn, cert, errnum, depth, ok):
    """
    Verify callback, which will be called for each certificate in the
    certificate chain.
    """
    # Nothing by default
    return ok

class TimeoutException(SSL.Error, socket.timeout):

    def __init__(self, *args):
        self.args = args

    def __str__(self):
        return "Timeout Exception"
PK���Z����UserDictCase.pynu�[���#
# Copyright (c) 2001--2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
#
# This file implements a case insensitive dictionary on top of the
# UserDict standard python class
#


try: # python2
    from UserDict import UserDict
    from types import StringType
except ImportError: # python3
    from collections import UserDict
    StringType = bytes
    from functools import reduce

# A dictionary with case insensitive keys
class UserDictCase(UserDict):
    def __init__(self, data = None):
        self.kcase = {}
        UserDict.__init__(self, data)

    def __lower_string(self, key):
        """ Return the lower() of key if it is a string. """
        if isinstance(key, StringType):
            return key.lower()
        else:
            return key

    # some methods used to make the class work as a dictionary
    def __setitem__(self, key, value):
        lkey = self.__lower_string(key)
        self.data[lkey] = value
        self.kcase[lkey] = key

    def __getitem__(self, key):
        key = self.__lower_string(key)
        return self.data[key]

    get = __getitem__

    def __delitem__(self, key):
        key = self.__lower_string(key)
        del self.data[key]
        del self.kcase[key]

    def __contains__(self, key):
        key = self.__lower_string(key)
        return key in self.data

    def keys(self):
        return self.kcase.values()

    def items(self):
        return self.get_hash().items()

    def has_key(self, key):
        # obsoleted, left for compatibility with older python
        return key in self

    def clear(self):
        self.data.clear()
        self.kcase.clear()

    # return this data as a real hash
    def get_hash(self):
        return reduce(lambda a, t, hc=self.kcase:
                      a.update({ hc[t[0]] : t[1]}) or a, self.data.items(), {})

    # return the data for marshalling
    def __getstate__(self):
        return self.get_hash()

    # we need a setstate because of the __getstate__ presence screws up deepcopy
    def __setstate__(self, state):
        self.__init__(state)

    # get a dictionary out of this instance ({}.update doesn't get instances)
    def dict(self):
        return self.get_hash()

    def update(self, dict):
        for (k, v) in dict.items():
            self[k] = v

    # Expose an iterator. This would normally fail if there is no iter()
    # function defined - but __iter__ will never be called on python 1.5.2
    def __iter__(self):
        return iter(self.data)
PK���Z[w\��^�^	rpclib.pynu�[���#
# This module contains all the RPC-related functions the RHN code uses
#
# Copyright (c) 2005--2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

__version__ = "2.8.62.8.6-8.module_el8.10.0+6858+3ddf28328.module_el8.10.0+6858+3ddf2832"

import socket
import re
import sys

from rhn import transports
from rhn.i18n import sstr
from rhn.UserDictCase import UserDictCase

try: # python2
    import xmlrpclib
    from types import ListType, TupleType, StringType, UnicodeType, DictType, DictionaryType
    from urllib import splittype, splithost
except ImportError: # python3
    import xmlrpc.client as xmlrpclib
    ListType = list
    TupleType = tuple
    StringType = bytes
    UnicodeType = str
    DictType = dict
    DictionaryType = dict
    from urllib.parse import splittype, splithost

# Redirection handling

MAX_REDIRECTIONS = 5

def check_ipv6(n):
    """ Returns true if n is IPv6 address, false otherwise. """
    try:
        socket.inet_pton(socket.AF_INET6, n)
        return True
    except:
        return False

def split_host(hoststring):
    """ Function used to split host information in an URL per RFC 2396
        handle full hostname like user:passwd@host:port
    """
    l = hoststring.split('@', 1)
    host = None
    port = None
    user = None
    passwd = None

    if len(l) == 2:
        hostport = l[1]
        # userinfo present
        userinfo = l[0].split(':', 1)
        user = userinfo[0]
        if len(userinfo) == 2:
            passwd = userinfo[1]
    else:
        hostport = l[0]

    # Now parse hostport
    if hostport[0] == '[':
        # IPv6 with port
        host, port = re.split('(?<=\]):', ip_port, 1)
        host = host.lstrip('[').rstrip(']')
    elif check_ipv6(hostport):
        # just IPv6
        host = hostport
    else:
        # IPv4
        arr = hostport.split(':', 1)
        host = arr[0]
        if len(arr) == 2:
            port = arr[1]

    return (host, port, user, passwd)

def get_proxy_info(proxy):
    if proxy == None:
        raise ValueError("Host string cannot be null")

    arr = proxy.split('://', 1)
    if len(arr) == 2:
        # scheme found, strip it
        proxy = arr[1]

    return split_host(proxy)


class MalformedURIError(IOError):
    pass


# Originaly taken from xmlrpclib.ServerProxy, now changed most of the code
class Server:
    """uri [,options] -> a logical connection to an XML-RPC server

    uri is the connection point on the server, given as
    scheme://host/target.

    The standard implementation always supports the "http" scheme.  If
    SSL socket support is available (Python 2.0), it also supports
    "https".

    If the target part and the slash preceding it are both omitted,
    "/RPC2" is assumed.

    The following options can be given as keyword arguments:

        transport: a transport factory
        encoding: the request encoding (default is UTF-8)
        verbose: verbosity level
        proxy: use an HTTP proxy
        username: username for authenticated HTTP proxy
        password: password for authenticated HTTP proxy

    All 8-bit strings passed to the server proxy are assumed to use
    the given encoding.
    """

    # Default factories
    _transport_class = transports.Transport
    _transport_class_https = transports.SafeTransport
    _transport_class_proxy = transports.ProxyTransport
    _transport_class_https_proxy = transports.SafeProxyTransport
    def __init__(self, uri, transport=None, encoding=None, verbose=0,
        proxy=None, username=None, password=None, refreshCallback=None,
        progressCallback=None, timeout=None):
        # establish a "logical" server connection

        #
        # First parse the proxy information if available
        #
        if proxy != None:
            (ph, pp, pu, pw) = get_proxy_info(proxy)

            if pp is not None:
                proxy = "%s:%s" % (ph, pp)
            else:
                proxy = ph

            # username and password will override whatever was passed in the
            # URL
            if pu is not None and username is None:
                username = pu

                if pw is not None and password is None:
                    password = pw

        self._uri = sstr(uri)
        self._refreshCallback = None
        self._progressCallback = None
        self._bufferSize = None
        self._proxy = proxy
        self._username = username
        self._password = password
        self._timeout = timeout

        if len(__version__.split()) > 1:
            self.rpc_version = __version__.split()[1]
        else:
            self.rpc_version = __version__

        self._reset_host_handler_and_type()

        if transport is None:
            self._allow_redirect = 1
            transport = self.default_transport(self._type, proxy, username,
                    password, timeout)
        else:
            #
            # dont allow redirect on unknow transports, that should be
            # set up independantly
            #
            self._allow_redirect = 0

        self._redirected = None
        self.use_handler_path = 1
        self._transport = transport

        self._trusted_cert_files = []
        self._lang = None

        self._encoding = encoding
        self._verbose = verbose

        self.set_refresh_callback(refreshCallback)
        self.set_progress_callback(progressCallback)

        # referer, which redirect us to new handler
        self.send_handler=None

        self._headers = UserDictCase()

    def default_transport(self, type, proxy=None, username=None, password=None,
            timeout=None):
        if proxy:
            if type == 'https':
                transport = self._transport_class_https_proxy(proxy,
                    proxyUsername=username, proxyPassword=password, timeout=timeout)
            else:
                transport = self._transport_class_proxy(proxy,
                    proxyUsername=username, proxyPassword=password, timeout=timeout)
        else:
            if type == 'https':
                transport = self._transport_class_https(timeout=timeout)
            else:
                transport = self._transport_class(timeout=timeout)
        return transport

    def allow_redirect(self, allow):
        self._allow_redirect = allow

    def redirected(self):
        if not self._allow_redirect:
            return None
        return self._redirected

    def set_refresh_callback(self, refreshCallback):
        self._refreshCallback = refreshCallback
        self._transport.set_refresh_callback(refreshCallback)

    def set_buffer_size(self, bufferSize):
        self._bufferSize = bufferSize
        self._transport.set_buffer_size(bufferSize)

    def set_progress_callback(self, progressCallback, bufferSize=16384):
        self._progressCallback = progressCallback
        self._transport.set_progress_callback(progressCallback, bufferSize)

    def _req_body(self, params, methodname):
        return xmlrpclib.dumps(params, methodname, encoding=self._encoding)

    def get_response_headers(self):
        if self._transport:
            return self._transport.headers_in
        return None

    def get_response_status(self):
        if self._transport:
            return self._transport.response_status
        return None

    def get_response_reason(self):
        if self._transport:
            return self._transport.response_reason
        return None

    def get_content_range(self):
        """Returns a dictionary with three values:
            length: the total length of the entity-body (can be None)
            first_byte_pos: the position of the first byte (zero based)
            last_byte_pos: the position of the last byte (zero based)
           The range is inclusive; that is, a response 8-9/102 means two bytes
        """
        headers = self.get_response_headers()
        if not headers:
            return None
        content_range = headers.get('Content-Range')
        if not content_range:
            return None
        arr = filter(None, content_range.split())
        assert arr[0] == "bytes"
        assert len(arr) == 2
        arr = arr[1].split('/')
        assert len(arr) == 2

        brange, total_len = arr
        if total_len == '*':
            # Per RFC, the server is allowed to use * if the length of the
            # entity-body is unknown or difficult to determine
            total_len = None
        else:
            total_len = int(total_len)

        start, end = brange.split('-')
        result = {
            'length'            : total_len,
            'first_byte_pos'    : int(start),
            'last_byte_pos'     : int(end),
        }
        return result

    def accept_ranges(self):
        headers = self.get_response_headers()
        if not headers:
            return None
        if 'Accept-Ranges' in headers:
            return headers['Accept-Ranges']
        return None

    def _reset_host_handler_and_type(self):
        """ Reset the attributes:
            self._host, self._handler, self._type
            according the value of self._uri.
        """
        # get the url
        type, uri = splittype(self._uri)
        if type is None:
            raise MalformedURIError("missing protocol in uri")
        # with a real uri passed in, uri will now contain "//hostname..." so we
        # need at least 3 chars for it to maybe be ok...
        if len(uri) < 3 or uri[0:2] != "//":
            raise MalformedURIError
        if type != None:
            self._type = type.lower()
        else:
            self._type = type
        if self._type not in ("http", "https"):
            raise IOError("unsupported XML-RPC protocol")
        self._host, self._handler = splithost(uri)
        if not self._handler:
            self._handler = "/RPC2"

    def _strip_characters(self, *args):
        """ Strip characters, which are not allowed according:
            http://www.w3.org/TR/2006/REC-xml-20060816/#charsets
            From spec:
            Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]  /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
        """
        regexp = r'[\x00-\x09]|[\x0b-\x0c]|[\x0e-\x1f]'
        result=[]
        for item in args:
            item_type = type(item)
            if item_type == StringType or item_type == UnicodeType:
                item = re.sub(regexp, '', sstr(item))
            elif item_type == TupleType:
                item = tuple(self._strip_characters(i) for i in item)
            elif item_type == ListType:
                item = [self._strip_characters(i) for i in item]
            elif item_type == DictType or item_type == DictionaryType:
                item = dict([(self._strip_characters(name, val)) for name, val in item.items()])
            # else: some object - should take care of himself
            #        numbers - are safe
            result.append(item)
        if len(result) == 1:
            return result[0]
        else:
            return tuple(result)

    def _request(self, methodname, params):
        """ Call a method on the remote server
            we can handle redirections. """
        # the loop is used to handle redirections
        redirect_response = 0
        retry = 0

        self._reset_host_handler_and_type()

        while 1:
            if retry >= MAX_REDIRECTIONS:
                raise InvalidRedirectionError(
                      "Unable to fetch requested Package")

            # Clear the transport headers first
            self._transport.clear_headers()
            for k, v in self._headers.items():
                self._transport.set_header(k, v)

            self._transport.add_header("X-Info",
                'RPC Processor (C) Red Hat, Inc (version %s)' %
                self.rpc_version)
            # identify the capability set of this client to the server
            self._transport.set_header("X-Client-Version", 1)

            if self._allow_redirect:
                # Advertise that we follow redirects
                #changing the version from 1 to 2 to support backward compatibility
                self._transport.add_header("X-RHN-Transport-Capability",
                    "follow-redirects=3")

            if redirect_response:
                self._transport.add_header('X-RHN-Redirect', '0')
                if self.send_handler:
                    self._transport.add_header('X-RHN-Path', self.send_handler)

            request = self._req_body(self._strip_characters(params), methodname)

            try:
                response = self._transport.request(self._host, \
                                self._handler, request, verbose=self._verbose)
                save_response = self._transport.response_status
            except xmlrpclib.ProtocolError:
                if self.use_handler_path:
                    raise
                else:
                     save_response = sys.exc_info()[1].errcode

            self._redirected = None
            retry += 1
            if save_response == 200:
                # exit redirects loop and return response
                break
            elif save_response not in (301, 302):
                # Retry pkg fetch
                 self.use_handler_path = 1
                 continue
            # rest of loop is run only if we are redirected (301, 302)
            self._redirected = self._transport.redirected()
            self.use_handler_path = 0
            redirect_response = 1

            if not self._allow_redirect:
                raise InvalidRedirectionError("Redirects not allowed")

            if self._verbose:
                print("%s redirected to %s" % (self._uri, self._redirected))

            typ, uri = splittype(self._redirected)

            if typ != None:
                typ = typ.lower()
            if typ not in ("http", "https"):
                raise InvalidRedirectionError(
                    "Redirected to unsupported protocol %s" % typ)

            #
            # We forbid HTTPS -> HTTP for security reasons
            # Note that HTTP -> HTTPS -> HTTP is allowed (because we compare
            # the protocol for the redirect with the original one)
            #
            if self._type == "https" and typ == "http":
                raise InvalidRedirectionError(
                    "HTTPS redirected to HTTP is not supported")

            self._host, self._handler = splithost(uri)
            if not self._handler:
                self._handler = "/RPC2"

            # Create a new transport for the redirected service and
            # set up the parameters on the new transport
            del self._transport
            self._transport = self.default_transport(typ, self._proxy,
                    self._username, self._password, self._timeout)
            self.set_progress_callback(self._progressCallback)
            self.set_refresh_callback(self._refreshCallback)
            self.set_buffer_size(self._bufferSize)
            self.setlang(self._lang)

            if self._trusted_cert_files != [] and \
                hasattr(self._transport, "add_trusted_cert"):
                for certfile in self._trusted_cert_files:
                    self._transport.add_trusted_cert(certfile)
            # Then restart the loop to try the new entry point.

        if isinstance(response, transports.File):
            # Just return the file
            return response

        # an XML-RPC encoded data structure
        if isinstance(response, TupleType) and len(response) == 1:
            response = response[0]

        return response

    def __repr__(self):
        return (
            "<%s for %s%s>" %
            (self.__class__.__name__, self._host, self._handler)
            )

    __str__ = __repr__

    def __getattr__(self, name):
        # magic method dispatcher
        return _Method(self._request, name)

    # note: to call a remote object with an non-standard name, use
    # result getattr(server, "strange-python-name")(args)

    def set_transport_flags(self, transfer=0, encoding=0, **kwargs):
        if not self._transport:
            # Nothing to do
            return
        kwargs.update({
            'transfer'  : transfer,
            'encoding'  : encoding,
        })
        self._transport.set_transport_flags(**kwargs)

    def get_transport_flags(self):
        if not self._transport:
            # Nothing to do
            return {}
        return self._transport.get_transport_flags()

    def reset_transport_flags(self):
        # Does nothing
        pass

    # Allow user-defined additional headers.
    def set_header(self, name, arg):
        if type(arg) in [ type([]), type(()) ]:
            # Multivalued header
            self._headers[name] = [str(a) for a in arg]
        else:
            self._headers[name] = str(arg)

    def add_header(self, name, arg):
        if name in self._headers:
            vlist = self._headers[name]
            if not isinstance(vlist, ListType):
                vlist = [ vlist ]
        else:
            vlist = self._headers[name] = []
        vlist.append(str(arg))

    # Sets the i18n options
    def setlang(self, lang):
        self._lang = lang
        if self._transport and hasattr(self._transport, "setlang"):
            self._transport.setlang(lang)

    # Sets the CA chain to be used
    def use_CA_chain(self, ca_chain = None):
        raise NotImplementedError("This method is deprecated")

    def add_trusted_cert(self, certfile):
        self._trusted_cert_files.append(certfile)
        if self._transport and hasattr(self._transport, "add_trusted_cert"):
            self._transport.add_trusted_cert(certfile)

    def close(self):
        if self._transport:
            self._transport.close()
            self._transport = None

# RHN GET server
class GETServer(Server):
    def __init__(self, uri, transport=None, proxy=None, username=None,
            password=None, client_version=2, headers={}, refreshCallback=None,
            progressCallback=None, timeout=None):
        Server.__init__(self, uri,
            proxy=proxy,
            username=username,
            password=password,
            transport=transport,
            refreshCallback=refreshCallback,
            progressCallback=progressCallback,
            timeout=timeout)
        self._client_version = client_version
        self._headers = headers
        # Back up the original handler, since we mangle it
        self._orig_handler = self._handler
        # Download resumption
        self.set_range(offset=None, amount=None)

    def _req_body(self, params, methodname):
        if not params or len(params) < 1:
            raise Exception("Required parameter channel not found")
        # Strip the multiple / from the handler
        h_comps = filter(lambda x: x != '', self._orig_handler.split('/'))
        # Set the handler we are going to request
        hndl = h_comps + ["$RHN", params[0], methodname] + list(params[1:])
        self._handler = '/' + '/'.join(hndl)

        #save the constructed handler in case of redirect
        self.send_handler = self._handler

        # Add headers
        #override the handler to replace /XMLRPC with pkg path
        if self._redirected and not self.use_handler_path:
           self._handler = self._new_req_body()

        for h, v in self._headers.items():
            self._transport.set_header(h, v)

        if self._offset is not None:
            if self._offset >= 0:
                brange = str(self._offset) + '-'
                if self._amount is not None:
                    brange = brange + str(self._offset + self._amount - 1)
            else:
                # The last bytes
                # amount is ignored in this case
                brange = '-' + str(-self._offset)

            self._transport.set_header('Range', "bytes=" + brange)
            # Flag that we allow for partial content
            self._transport.set_transport_flags(allow_partial_content=1)
        # GET requests have empty body
        return ""

    def _new_req_body(self):
        type, tmpuri = splittype(self._redirected)
        site, handler = splithost(tmpuri)
        return handler

    def set_range(self, offset=None, amount=None):
        if offset is not None:
            try:
                offset = int(offset)
            except ValueError:
                # Error
                raise RangeError("Invalid value `%s' for offset" % offset, None, sys.exc_info()[2])

        if amount is not None:
            try:
                amount = int(amount)
            except ValueError:
                # Error
                raise RangeError("Invalid value `%s' for amount" % amount, None, sys.exc_info()[2])

            if amount <= 0:
                raise RangeError("Invalid value `%s' for amount" % amount)

        self._amount = amount
        self._offset = offset

    def reset_transport_flags(self):
        self._transport.set_transport_flags(allow_partial_content=0)

    def __getattr__(self, name):
        # magic method dispatcher
        return SlicingMethod(self._request, name)

    def default_transport(self, type, proxy=None, username=None, password=None,
            timeout=None):
        ret = Server.default_transport(self, type, proxy=proxy, username=username, password=password, timeout=timeout)
        ret.set_method("GET")
        return ret

class RangeError(Exception):
    pass

class InvalidRedirectionError(Exception):
    pass

def getHeaderValues(headers, name):
    import mimetools
    if not isinstance(headers, mimetools.Message):
        if name in headers:
            return [headers[name]]
        return []

    return [x.split(':', 1)[1].strip() for x in
            headers.getallmatchingheaders(name)]

class _Method:
    """ some magic to bind an XML-RPC method to an RPC server.
        supports "nested" methods (e.g. examples.getStateName)
    """
    def __init__(self, send, name):
        self._send = send
        self._name = name
    def __getattr__(self, name):
        return _Method(self._send, "%s.%s" % (self._name, name))
    def __call__(self, *args):
        return self._send(self._name, args)
    def __repr__(self):
        return (
            "<%s %s (%s)>" %
            (self.__class__.__name__, self._name, self._send)
            )
    __str__ = __repr__


class SlicingMethod(_Method):
    """
    A "slicing method" allows for byte range requests
    """
    def __init__(self, send, name):
        _Method.__init__(self, send, name)
        self._offset = None
    def __getattr__(self, name):
        return SlicingMethod(self._send, "%s.%s" % (self._name, name))
    def __call__(self, *args, **kwargs):
        self._offset = kwargs.get('offset')
        self._amount = kwargs.get('amount')

        # im_self is a pointer to self, so we can modify the class underneath
        try:
            self._send.im_self.set_range(offset=self._offset,
                amount=self._amount)
        except AttributeError:
            pass

        result = self._send(self._name, args)

        # Reset "sticky" transport flags
        try:
            self._send.im_self.reset_transport_flags()
        except AttributeError:
            pass

        return result


def reportError(headers):
    """ Reports the error from the headers. """
    errcode = 0
    errmsg = ""
    s = "X-RHN-Fault-Code"
    if s in headers:
        errcode = int(headers[s])
    s = "X-RHN-Fault-String"
    if s in headers:
        _sList = getHeaderValues(headers, s)
        if _sList:
            _s = ''.join(_sList)
            import base64
            errmsg = "%s" % base64.decodestring(_s)

    return errcode, errmsg

PK���Z#ћNtt
SmartIO.pynu�[���#
# Smart IO class
#
# Copyright (c) 2002--2016 Red Hat, Inc.
#
# Author: Mihai Ibanescu <misa@redhat.com>

"""
This module implements the SmartIO class
"""

import os
try: # python2
    from cStringIO import StringIO
except ImportError: # python3
    from io import BytesIO as StringIO

class SmartIO:
    """
    The SmartIO class allows one to put a cap on the memory consumption.
    StringIO objects are very fast, because they are stored in memory, but
    if they are too big the memory footprint becomes noticeable.
    The write method of a SmartIO determines if the data that is to be added
    to the (initially) StrintIO object does not exceed a certain threshold; if
    it does, it switches the storage to a temporary disk file
    """
    def __init__(self, max_mem_size=16384, force_mem=0):
        self._max_mem_size = max_mem_size
        self._io = StringIO()
        # self._fixed is a flag to show if we're supposed to consider moving
        # the StringIO object into a tempfile
        # Invariant: if self._fixed == 0, we have a StringIO (if self._fixed
        # is 1 and force_mem was 0, then we have a file)
        if force_mem:
            self._fixed = 1
        else:
            self._fixed = 0

    def set_max_mem_size(self, max_mem_size):
        self._max_mem_size = max_mem_size

    def get_max_mem_size(self):
        return self._max_mem_size

    def write(self, data):
        if not self._fixed:
            # let's consider moving it to a file
            if len(data) + self._io.tell() > self._max_mem_size:
                # We'll overflow, change to a tempfile
                tmpfile = _tempfile()
                tmpfile.write(self._io.getvalue())
                self._fixed = 1
                self._io = tmpfile

        self._io.write(data)

    def __getattr__(self, name):
        return getattr(self._io, name)

# Creates a temporary file and passes back its file descriptor
def _tempfile():
    import tempfile
    (fd, fname) = tempfile.mkstemp(prefix="_rhn_transports-%d-" \
                                   % os.getpid())
    # tempfile, unlink it
    os.unlink(fname)
    return os.fdopen(fd, "wb+")
PK���Z��{��%�%connections.pynu�[���#
# Connection objects
#
# Copyright (c) 2002--2016 Red Hat, Inc.
#
# Author: Mihai Ibanescu <misa@redhat.com>



import base64
import encodings.idna
import socket
from platform import python_version
from rhn import SSL
from rhn import nonblocking
from rhn import i18n

try: # python2
    import httplib
    # Import into the local namespace some httplib-related names
    from httplib import _CS_REQ_SENT, _CS_IDLE, ResponseNotReady

    import xmlrpclib
except ImportError: # python3
    import http.client as httplib
    # Import into the local namespace some httplib-related names
    from http.client import _CS_REQ_SENT, _CS_IDLE, ResponseNotReady

    import xmlrpc.client as xmlrpclib

class HTTPResponse(httplib.HTTPResponse):
    def set_callback(self, rs, ws, ex, user_data, callback):
        if not isinstance(self.fp, nonblocking.NonBlockingFile):
            self.fp = nonblocking.NonBlockingFile(self.fp)
        self.fp.set_callback(rs, ws, ex, user_data, callback)

class HTTPConnection(httplib.HTTPConnection):
    response_class = HTTPResponse

    def __init__(self, host, port=None, timeout=SSL.DEFAULT_TIMEOUT):
        if python_version() >= '2.6.1':
            httplib.HTTPConnection.__init__(self, host, port, timeout=timeout)
        else:
            httplib.HTTPConnection.__init__(self, host, port)
        self._cb_rs = []
        self._cb_ws = []
        self._cb_ex = []
        self._cb_user_data = None
        self._cb_callback = None
        self._user_agent = "rhn.connections $Revision$ (python)"
        self.timeout = timeout

    def set_callback(self, rs, ws, ex, user_data, callback):
        # XXX check the params
        self._cb_rs = rs
        self._cb_ws = ws
        self._cb_ex = ex
        self._cb_user_data = user_data
        self._cb_callback = callback

    def set_user_agent(self, user_agent):
        self._user_agent = user_agent

    # XXX Had to copy the function from httplib.py, because the nonblocking
    # framework had to be initialized
    def getresponse(self):
        "Get the response from the server."

        # check if a prior response has been completed
        if self.__response and self.__response.isclosed():
            self.__response = None

        #
        # if a prior response exists, then it must be completed (otherwise, we
        # cannot read this response's header to determine the connection-close
        # behavior)
        #
        # note: if a prior response existed, but was connection-close, then the
        # socket and response were made independent of this HTTPConnection
        # object since a new request requires that we open a whole new
        # connection
        #
        # this means the prior response had one of two states:
        #   1) will_close: this connection was reset and the prior socket and
        #                  response operate independently
        #   2) persistent: the response was retained and we await its
        #                  isclosed() status to become true.
        #
        if self.__state != _CS_REQ_SENT or self.__response:
            raise ResponseNotReady()

        if self.debuglevel > 0:
            response = self.response_class(self.sock, self.debuglevel)
        else:
            response = self.response_class(self.sock)

        # The only modification compared to the stock HTTPConnection
        if self._cb_callback:
            response.set_callback(self._cb_rs, self._cb_ws, self._cb_ex,
                self._cb_user_data, self._cb_callback)

        response.begin()
        assert response.will_close != httplib._UNKNOWN
        self.__state = _CS_IDLE

        if response.will_close:
            # this effectively passes the connection to the response
            self.close()
        else:
            # remember this, so we can tell when it is complete
            self.__response = response

        return response

    def connect(self):
        httplib.HTTPConnection.connect(self)
        self.sock.settimeout(self.timeout)


class HTTPProxyConnection(HTTPConnection):
    def __init__(self, proxy, host, port=None, username=None, password=None,
            timeout=SSL.DEFAULT_TIMEOUT):
        # The connection goes through the proxy
        HTTPConnection.__init__(self, proxy, timeout=timeout)
        # save the proxy values
        self.__proxy, self.__proxy_port = self.host, self.port
        # self.host and self.port will point to the real host
        self._set_hostport(host, port)
        # save the host and port
        self._host, self._port = self.host, self.port
        # Authenticated proxies support
        self.__username = username
        self.__password = password

    def connect(self):
        # We are actually connecting to the proxy
        self._set_hostport(self.__proxy, self.__proxy_port)
        HTTPConnection.connect(self)
        # Restore the real host and port
        self._set_hostport(self._host, self._port)

    def putrequest(self, method, url, skip_host=0):
        # The URL has to include the real host
        hostname = self._host
        if self._port != self.default_port:
            hostname = hostname + ':' + str(self._port)
        newurl = "http://%s%s" % (hostname, url)
        # Piggyback on the parent class
        HTTPConnection.putrequest(self, method, newurl, skip_host=skip_host)
        # Add proxy-specific headers
        self._add_proxy_headers()

    def _add_proxy_headers(self):
        if not self.__username:
            return
        # Authenticated proxy
        userpass = "%s:%s" % (self.__username, self.__password)
        enc_userpass = base64.encodestring(i18n.bstr(userpass)).replace(i18n.bstr("\n"), i18n.bstr(""))
        self.putheader("Proxy-Authorization", "Basic %s" % i18n.sstr(enc_userpass))

    def _set_hostport(self, host, port):
        (self.host, self.port) = self._get_hostport(host, port)

class HTTPSConnection(HTTPConnection):
    response_class = HTTPResponse
    default_port = httplib.HTTPSConnection.default_port

    def __init__(self, host, port=None, trusted_certs=None,
            timeout=SSL.DEFAULT_TIMEOUT):
        HTTPConnection.__init__(self, host, port, timeout=timeout)
        trusted_certs = trusted_certs or []
        self.trusted_certs = trusted_certs

    def connect(self):
        "Connect to a host on a given (SSL) port"
        results = socket.getaddrinfo(self.host, self.port,
            socket.AF_UNSPEC, socket.SOCK_STREAM)

        for r in results:
            af, socktype, proto, canonname, sa = r
            try:
                sock = socket.socket(af, socktype, proto)
            except socket.error:
                sock = None
                continue

            try:
                sock.connect((self.host, self.port))
                sock.settimeout(self.timeout)
            except socket.error:
                sock.close()
                sock = None
                continue
            break

        if sock is None:
            raise socket.error("Unable to connect to the host and port specified")

        self.sock = SSL.SSLSocket(sock, self.trusted_certs)
        self.sock.init_ssl()

class HTTPSProxyResponse(HTTPResponse):
    def begin(self):
        HTTPResponse.begin(self)
        self.will_close = 0

class HTTPSProxyConnection(HTTPProxyConnection):
    default_port = HTTPSConnection.default_port

    def __init__(self, proxy, host, port=None, username=None, password=None,
            trusted_certs=None, timeout=SSL.DEFAULT_TIMEOUT):
        HTTPProxyConnection.__init__(self, proxy, host, port, username,
                password, timeout=timeout)
        trusted_certs = trusted_certs or []
        self.trusted_certs = trusted_certs

    def connect(self):
        # Set the connection with the proxy
        HTTPProxyConnection.connect(self)
        # Use the stock HTTPConnection putrequest
        host = "%s:%s" % (self._host, self._port)
        HTTPConnection.putrequest(self, "CONNECT", host)
        # Add proxy-specific stuff
        self._add_proxy_headers()
        # And send the request
        HTTPConnection.endheaders(self)
        # Save the response class
        response_class = self.response_class
        # And replace the response class with our own one, which does not
        # close the connection after
        self.response_class = HTTPSProxyResponse
        response = HTTPConnection.getresponse(self)
        # Restore the response class
        self.response_class = response_class
        # Close the response object manually
        response.close()
        if response.status != 200:
            # Close the connection manually
            self.close()
            raise xmlrpclib.ProtocolError(host,
                response.status, response.reason, response.msg)
        self.sock = SSL.SSLSocket(self.sock, self.trusted_certs)
        self.sock.init_ssl()

    def putrequest(self, method, url, skip_host=0):
        return HTTPConnection.putrequest(self, method, url, skip_host=skip_host)

    def _add_proxy_headers(self):
        HTTPProxyConnection._add_proxy_headers(self)
        # Add a User-Agent header
        self.putheader("User-Agent", self._user_agent)

def idn_puny_to_unicode(hostname):
    """ Convert Internationalized domain name from Punycode (RFC3492) to Unicode """
    if hostname is None:
        return None
    else:
        hostname = i18n.bstr(hostname)
        return hostname.decode('idna')

def idn_ascii_to_puny(hostname):
    """ Convert domain name to Punycode (RFC3492). Hostname can be instance of string or Unicode """
    if hostname is None:
        return None
    else:
        hostname = i18n.ustr(hostname)
        return i18n.ustr(hostname.encode('idna'))
PK���Z�G$���__init__.pynu�[���PK���Zg7B=�|�|
�transports.pynu�[���PK���Z��{	{	�}nonblocking.pynu�[���PK���Z#4�RDD��tb.pynu�[���PK���Z^�QG�actions/__init__.pynuȯ��PK���Ztf��{�actions/up2date_config.pynuȯ��PK���Zo��6��+�actions/__pycache__/hardware.cpython-36.pycnu�[���PK���Z8f2p��1��actions/__pycache__/up2date_config.cpython-36.pycnu�[���PK���Z"�nм � 1o�actions/__pycache__/packages.cpython-36.opt-1.pycnu�[���PK���Zh��kk1��actions/__pycache__/systemid.cpython-36.opt-1.pycnu�[���PK���Z"�nм � +X�actions/__pycache__/packages.cpython-36.pycnu�[���PK���Z8f2p��7o�actions/__pycache__/up2date_config.cpython-36.opt-1.pycnu�[���PK���ZP	�%%/_�actions/__pycache__/errata.cpython-36.opt-1.pycnu�[���PK���Zo��6��1��actions/__pycache__/hardware.cpython-36.opt-1.pycnu�[���PK���Z�%O=��(��actions/__pycache__/rhnsd.cpython-36.pycnu�[���PK���Zh��kk+>�actions/__pycache__/systemid.cpython-36.pycnu�[���PK���Z�A����)�actions/__pycache__/reboot.cpython-36.pycnu�[���PK���Z�A����/actions/__pycache__/reboot.cpython-36.opt-1.pycnu�[���PK���Z�%O=��. actions/__pycache__/rhnsd.cpython-36.opt-1.pycnu�[���PK���Z�j��qq+uactions/__pycache__/__init__.cpython-36.pycnu�[���PK���Z�j��qq1A
actions/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK���ZP	�%%)actions/__pycache__/errata.cpython-36.pycnu�[���PK���Z_��ZZ�actions/reboot.pynuȯ��PK���Z`��___,actions/rhnsd.pynuȯ��PK���Zˣ����� actions/systemid.pynuȯ��PK���Z=K'�..�#actions/packages.pynu�[���PK���Z\WL�UUZRactions/hardware.pynuȯ��PK���Z�6���	�	�Vactions/errata.pynu�[���PK���Zf��**-�`__pycache__/UserDictCase.cpython-36.opt-1.pycnu�[���PK���Z�kull%Om__pycache__/i18n.cpython-36.opt-1.pycnu�[���PK���Z����#q__pycache__/tb.cpython-36.opt-1.pycnu�[���PK���Z�h��J�J%s__pycache__/transports.cpython-36.pycnu�[���PK���Zf��**'�__pycache__/UserDictCase.cpython-36.pycnu�[���PK���Z�u4�G�G!��__pycache__/rpclib.cpython-36.pycnu�[���PK���Z�h��J�J+e__pycache__/transports.cpython-36.opt-1.pycnu�[���PK���Z�b�b��,m]__pycache__/connections.cpython-36.opt-1.pycnu�[���PK���Z~��RR$�z__pycache__/SSL.cpython-36.opt-1.pycnu�[���PK���Z����F�__pycache__/tb.cpython-36.pycnu�[���PK���Z�n�P&&"3�__pycache__/SmartIO.cpython-36.pycnu�[���PK���Z��u�__&��__pycache__/nonblocking.cpython-36.pycnu�[���PK���Z����&`�__pycache__/connections.cpython-36.pycnu�[���PK���Z��u�__,��__pycache__/nonblocking.cpython-36.opt-1.pycnu�[���PK���Z�n�P&&(y�__pycache__/SmartIO.cpython-36.opt-1.pycnu�[���PK���Z*��
�
,��__pycache__/rhnLockfile.cpython-36.opt-1.pycnu�[���PK���Z*��
�
&��__pycache__/rhnLockfile.cpython-36.pycnu�[���PK���Z/F�J4G4G'��__pycache__/rpclib.cpython-36.opt-1.pycnu�[���PK���Z����#B6__pycache__/__init__.cpython-36.pycnu�[���PK���Z����)Q7__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK���Z~��RRf8__pycache__/SSL.cpython-36.pycnu�[���PK���Z�kullU__pycache__/i18n.cpython-36.pycnu�[���PK���Z��?�c
c
�XrhnLockfile.pynu�[���PK���Z��k��bfi18n.pynu�[���PK���Zʕe�-+-+�mSSL.pynu�[���PK���Z�����UserDictCase.pynu�[���PK���Z[w\��^�^	�rpclib.pynu�[���PK���Z#ћNtt
%SmartIO.pynu�[���PK���Z��{��%�%�connections.pynu�[���PK99i3