Current File : /home/mmdealscpanel/yummmdeals.com/up2date_client.tar
pmPlugin.py000064400000005453150516774040006731 0ustar00# Client code for enabling plugin
# Copyright (c) 2000--2016 Red Hat, Inc.

import os
import re
import rpm

# global variables
try:
   from dnf import __version__
   PM_PLUGIN_CONF = '/etc/dnf/plugins/spacewalk.conf'
   PM_PLUGIN_NAME = 'dnf-plugin-spacewalk'
   PM_NAME        = 'dnf'
except ImportError:
   PM_PLUGIN_CONF = '/etc/yum/pluginconf.d/rhnplugin.conf'
   PM_PLUGIN_NAME = 'yum-rhn-plugin'
   PM_NAME        = 'yum'

def pluginEnable():
    """Enables plugin, may throw IOError"""
    conf_changed = 0
    plugin_present = 0
    if PluginPackagePresent():
        plugin_present = 1
        if PluginConfPresent():
            if not PluginEnabled():
                enablePlugin()
                conf_changed = 1
        else:
            createDefaultPluginConf()
            conf_changed = 1
    elif os.path.exists("/usr/lib/zypp/plugins/services/spacewalk"):
        """SUSE zypp plugin is installed"""
        plugin_present = 1
    return plugin_present, conf_changed

def PluginPackagePresent():
    """ Returns positive number if plugin package is installed, otherwise it return 0 """
    ts = rpm.TransactionSet()
    headers = ts.dbMatch('providename', PM_PLUGIN_NAME)
    return headers.count()

def PluginConfPresent():
    """ Returns true if PM_PLUGIN_CONF is presented """
    try:
        os.stat(PM_PLUGIN_CONF)
        return True
    except OSError:
        return False

def createDefaultPluginConf():
    """ Create file PM_PLUGIN_CONF, with default values """
    f = open(PM_PLUGIN_CONF, 'w')
    f.write("""[main]
enabled = 1
gpgcheck = 1""")
    f.close()

def PluginEnabled():
    """ Returns True if plugin is enabled
        Can thrown IOError exception.
    """
    f = open(PM_PLUGIN_CONF, 'r')
    lines = f.readlines()
    f.close()
    main_section = False
    result = False
    for line in lines:
        if re.match("^\[.*]", line):
            if re.match("^\[main]", line):
                main_section = True
            else:
                main_section = False
        if main_section:
            m = re.match('^\s*enabled\s*=\s*([0-9])', line)
            if m:
                if int(m.group(1)):
                    result = True
                else:
                    result = False
    return result

def enablePlugin():
    """ enable plugin by setting enabled=1 in file PM_PLUGIN_CONF
        Can thrown IOError exception.
    """
    f = open(PM_PLUGIN_CONF, 'r')
    lines = f.readlines()
    f.close()
    main_section = False
    f = open(PM_PLUGIN_CONF, 'w')
    for line in lines:
        if re.match("^\[.*]", line):
            if re.match("^\[main]", line):
                main_section = True
            else:
                main_section = False
        if main_section:
            line = re.sub('^(\s*)enabled\s*=.+', r'\1enabled = 1', line)
        f.write(line)
    f.close()
debUtils.py000064400000005416150516774040006710 0ustar00# Client code for Update Agent
# Copyright (c) 2011--2016 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Simon Lukasik
#         Lukas Durfina
#

import os
import apt
import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext


# FIXME: After Debian bug 187019 is resolved
def verifyPackages(packages):
    cache = apt.Cache()
    missing_packages = []
    for package in packages:
        pkg = cache[package[0]]
        if pkg == None or not pkg.is_installed:
            missing_packages.append(package)

    return [], missing_packages

def parseVRE(version):
    epoch = ''
    release = 'X'
    if version.find(':') != -1:
        epoch, version = version.split(':')
    if version.find('-') != -1:
        tmp = version.split('-')
        version = '-'.join(tmp[:-1])
        release = tmp[-1]
    return version, release, epoch

def installTime(pkg_name, pkg_arch):
    dir = '/var/lib/dpkg/info'
    files = [ '%s.list' % pkg_name,
              '%s:%s.list' % (pkg_name, pkg_arch) ]
    # In edge cases, pkg_name can include the arch but the .list file does not
    if ':' in pkg_name:
        files.append('%s.list' % (pkg_name[:pkg_name.index(':')]))
    for f in files:
        path = os.path.join(dir,f)
        if os.path.isfile(path):
            return os.path.getmtime(path)
    return 0

#FIXME: Using Apt cache might not be an ultimate solution.
# It could be better to parse /var/lib/dpkg/status manually.
# Apt cache might not contain all the packages.
def getInstalledPackageList(msgCallback = None, progressCallback = None,
                            getArch=None, getInfo = None):
    """ Return list of packages. Package is dict with following keys:
        name, epoch, version, release and optionaly arch.
    """
    if msgCallback != None:
        msgCallback(_("Getting list of packages installed on the system"))
    cache = apt.Cache()

    total = 0
    for pkg in cache:
        if pkg.installed != None:
            total += 1

    count = 0
    pkg_list = []
    for pkg in cache:
        if pkg.installed == None:
            continue
        version, release, epoch = parseVRE(pkg.installed.version)
        package = {
            'name': pkg.name,
            'epoch': epoch,
            'version': version,
            'release': release,
            'arch': pkg.installed.architecture + '-deb',
            'installtime': installTime(pkg.name, pkg.installed.architecture)
            }
        pkg_list.append(package)

        if progressCallback != None:
            progressCallback(count, total)
        count = count + 1

    pkg_list.sort(key=lambda package: package['version'])
    return pkg_list

def setDebugVerbosity():
    pass
__init__.py000064400000000000150516774040006654 0ustar00pkgUtils.py000064400000000447150516774040006736 0ustar00# Client code for Update Agent
# Copyright (c) 2011--2016 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Simon Lukasik

from up2date_client.pkgplatform import getPlatform

if getPlatform() == 'deb':
    from up2date_client.debUtils import *
else:
    from up2date_client.rpmUtils import *

rhnreg_constants.py000064400000044211150516774040010512 0ustar00# -*- coding: utf-8 -*-
#
# String constants for the RHN Register TUI/GUI.
# Copyright (c) 2000--2016 Red Hat, Inc.
#
# Author:
#       James Slagle <jslagle@redhat.com>


from up2date_client.pmPlugin import PM_PLUGIN_NAME, PM_NAME

import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

COPYRIGHT_TEXT        = _(u"Copyright © 2006--2014 Red Hat, Inc. All rights reserved.")

# Satellite URL Window
SATELLITE_URL_WINDOW  = _("Enter your CloudLinux Network URL.")
SATELLITE_URL_TEXT    = _("Please enter the location of your CloudLinux Network "
                          "server and of its SSL "
                          "certificate. The SSL certificate is only required "
                          "if you will be connecting over https (recommended).")
SATELLITE_URL_PROMPT  = _("Satellite URL:")
SATELLITE_URL_PROMPT2 = _("SSL certificate:")
SATELLITE_REQUIRED    = _("You must enter a valid Satellite URL.")
SSL_REQUIRED          = _("If you are using https you must enter the location "
                          "of a valid SSL certificate.")

# Connect Window
CONNECT_WINDOW        = _("Attempting to contact the Spacewalk server.")
CONNECT_WINDOW_TEXT   = _("We are attempting to contact the CloudLinux Network "
                          "Network server at %s.")
CONNECT_WINDOW_TEXT2  = _("A proxy was specified at %s.")

# Start Window
START_REGISTER_WINDOW = _("System Registration")
START_REGISTER_TEXT   = _("This assistant will guide you through "
                          "connecting your system to "
                          "CloudLinux Network to receive software "
                          "updates, including "
                          "security updates, to keep your system supported "
                          "and compliant.  "
                          "You will need the following at this time:\n\n"
                          " * A network connection\n"
                          " * Your CloudLinux Login & password\n"
                          " * The location of a CloudLinux Network "
                          "or Proxy\n\n")

# Why Register Window
WHY_REGISTER          = _("Why Should I Connect to CLN? ...")
WHY_REGISTER_WINDOW   = _("Why Register")
WHY_REGISTER_TEXT     = _("Connecting your system to CloudLinux Network allows you to take full "
                          "advantage of the benefits of a paid subscription, including:")
WHY_REGISTER_SEC      = _("Security & Updates:")
WHY_REGISTER_DLD      = _("Downloads & Upgrades:")
WHY_REGISTER_SUPP     = _("Support:")
WHY_REGISTER_COMP     = _("Compliance:")
WHY_REGISTER_SEC_TXT  = _("Receive the latest software updates, including security updates, keeping this "
                          "CloudLinux system updated and secure.")
WHY_REGISTER_DLD_TXT  = _("Download installation images for CloudLinux releases, "
                          "including new releases.")
WHY_REGISTER_SUPP_TXT = _("Access to the technical support experts at CloudLinux for help "
                          "with any issues you might encounter with this system.")
WHY_REGISTER_COMP_TXT = _("Stay in compliance with your subscription agreement "
                          "and manage subscriptions "
                          "for systems connected to your account.")
WHY_REGISTER_TIP      = _("Tip: CloudLinux values your privacy: "
                          "http://www.cloudlinux.com/company/privacy/")
BACK_REGISTER         = _("Take me back to the registration")

# Confirm Quit Window
CONFIRM_QUIT           = _("Software Update Not Set Up")
CONFIRM_QUIT_SURE       = _("Are you sure you don't want to connect your system to CloudLinux Network? "
                           "You'll miss out on the benefits of a CloudLinux subscription:\n")
CONFIRM_QUIT_WILLNOT       = _("You will not be able to take advantage of these subscription privileges without connecting "
                           "your system to CloudLinux Network.\n")
CONTINUE_REGISTERING   = _("Take me back to the setup process.")
REGISTER_LATER2        = _("I'll register later.")

# Info Window
REGISTER_WINDOW   = _("CloudLinux Account")
LOGIN_PROMPT      = _("Please enter your login information for the %s "
                    "CloudLinux Network:\n\n")
HOSTED_LOGIN      = _("CloudLinux Login:")
LOGIN             = _("Login:")
PASSWORD          = _("Password:")
LOGIN_TIP         = _("Tip: Forgot your login or password?  Contact your "
                      "Satellite's Organization Administrator.")
USER_REQUIRED     = _("Please enter a desired login.")
PASSWORD_REQUIRED = _("Please enter and verify a password.")

# OS Release Window
SELECT_OSRELEASE             = _("Operating System Release Version")
OS_VERSION                   = _("Operating System version:")
MINOR_RELEASE                = _(" Minor Release: ")
LIMITED_UPDATES              = _("Limited Updates Only")
ALL_UPDATES                  = _("All available updates")
CONFIRM_OS_RELEASE_SELECTION = _("Confirm operating system release selection")
CONFIRM_OS_ALL               = _("Your system will be subscribed to the base"
                                 " software channel to receive all available"
                                 " updates.")

# Hardware Window
HARDWARE_WINDOW = _("Create Profile - Hardware")
HARDWARE_WINDOW_DESC1 = _("A Profile Name is a descriptive name that"
                          " you choose to identify this System Profile"
                          " on the CloudLinux Network web pages. Optionally,"
                          " include a computer serial or identification number.")
HARDWARE_WINDOW_DESC2 = _("Additional hardware information including PCI"
                          " devices, disk sizes and mount points will be"
                          " included in the profile.")
HARDWARE_WINDOW_CHECKBOX = _("Include the following information about hardware"
                             " and network:")

# Packages Window
PACKAGES_WINDOW         = _("Create Profile - Packages")
PACKAGES_WINDOW_DESC1   = _("RPM information is important to determine what"
                          " updated software packages are relevant to this"
                          " system.")
PACKAGES_WINDOW_DESC2   = _("Include RPM packages installed on this system"
                          " in my System Profile")
PACKAGES_WINDOW_UNCHECK = _("You may deselect individual packages by"
                            " unchecking them below.")
PACKAGES_WINDOW_PKGLIST = _("Building Package List")

# Product Window
EMAIL                  = _("*Email Address:")

SYSTEM_ALREADY_SETUP = _("System Already Registered")
SYSTEM_ALREADY_REGISTERED = _("It appears this system has already been set up for software updates:")
SYSTEM_ALREADY_REGISTERED_CONT = _("Are you sure you would like to continue?")

RHSM_SYSTEM_ALREADY_REGISTERED = _("This system has already been registered using CloudLinux Subscription Management.\n\n"
                                "Your system is being registered again using CloudLinux Network"
                                " or CloudLinux Network Proxy technology. CloudLinux recommends that customers only register once.\n\n"
                                "To learn more about RHN Classic/CloudLinux Network registration and technologies please consult this"
                                " Knowledge Base Article: https://access.redhat.com/kb/docs/DOC-45563")

# Send Window
SEND_WINDOW      = _("Send Profile Information to CloudLinux Network")
SEND_WINDOW_DESC = _("We are finished collecting information for the System Profile.\n\n"
                     "Press \"Next\" to send this System Profile to CloudLinux Network.  "
                     "Click \"Cancel\" and no information will be sent.  "
                     "You can run the registration program later by "
                     "typing `rhn_register` at the command line.")

# Sending Window
SENDING_WINDOW = _("Sending Profile to CloudLinux Network")

# Finish Window
FINISH_WINDOW           = _("Updates Configured")
FINISH_WINDOW_TEXT_TUI  = _("You may now run '%s update' from this system's "
                            "command line to get the latest "
                            "software updates from CloudLinux Network. You will need to run this "
                            "periodically to "
                            "get the latest updates. Alternatively, you may configure this "
                            "system for automatic software updates (also known as 'auto errata update') "
                            "via the CloudLinux Network web interface.  (Instructions for this are in chapter 6 "
                            "of the CLN Reference Guide, available from the 'Help' button in the main Red "
                            "Hat Network Satellite web interface.)") % PM_NAME

# Review Window
REVIEW_WINDOW           = _("Review Subscription")
REVIEW_WINDOW_PROMPT    = _("Please review the subscription details below:")
SUB_NUM                 = _("The installation number %s was activated during "
                            "this system's initial connection to CloudLinux Network.")
SUB_NUM_RESULT          = _("Subscriptions have been activated for the following "
                            "CloudLinux products/services:")
CHANNELS_TITLE          = _("Software Channel Subscriptions:")
OK_CHANNELS             = _("This system will receive updates from the "
                            "following software channels:")
CHANNELS_SAT_WARNING    = _("Warning: Only installed product listed above will receive "
                            "updates and support. If you would like "
                            "to receive updates for additional products, please "
                            "login to your satellite web interface "
                            "and subscribe this system to the appropriate "
                            "software channels. See Kbase article "
                            "for more details. "
                            "(http://kbase.redhat.com/faq/docs/DOC-11313)")
PM_PLUGIN_WARNING       = _("Warning: %s is not present, could not enable it.\n"
                            "Automatic updates will not work.") % (PM_PLUGIN_NAME)
PM_PLUGIN_CONF_CHANGED  = _("Note: %s has been enabled.") % (PM_PLUGIN_NAME)
PM_PLUGIN_CONF_ERROR    = _("Warning: An error occurred during enabling %s.\n"
                            "%s is not enabled.\n"
                            "Automatic updates will not work.") % (PM_PLUGIN_NAME, PM_PLUGIN_NAME)
FAILED_CHANNELS         = _("You were unable to be subscribed to the following "
                            "software channels because there were insufficient "
                            "subscriptions available in your account:")
NO_BASE_CHANNEL            = _(
"This system was unable to subscribe to any software channels. Your system "
"will not receive any software updates to keep it secure and supported. "
"Contact your Satellite administrator about this problem. Once you make the "
"appropriate active subscriptions available in your account, you may browse "
"to this system's profile in the CLN web interface and subscribe this system "
"to software channels via the software > software channels tab.")
SLOTS_TITLE             = _("Service Level:")
OK_SLOTS                = _("Depending on what CloudLinux Network modules are associated with a system, you'll "
                            "enjoy different benefits. The following are the "
                            "CloudLinux Network modules associated with this system:")
SLOTS                   =  SLOTS_TITLE + "\n" + OK_SLOTS + "\n%s"
FAILED_SLOTS            = _("This system was unable to be associated with the "
                            "following CLN module(s) because there were "
                            "insufficient subscriptions available in your account:")
MANAGEMENT              = _("Management module: automatic updates, systems "
                            "grouping, systems permissions, system package profiling, "
                            "bare-metal provisioning, existing state provisioning, "
                            "rollbacks, configuration management")

VIRT = _("Virtualization module: software updates for a limited number of "
        "virtual guests on this system.")


VIRT_FAILED = _("<b>Warning:</b> Any guest systems you create on this system "
        "and register to RHN will consume CloudLinux "
        "subscriptions beyond this host system's subscription. You will need "
        "to: (1) make a virtualization system entitlement available and "
        "(2) apply that system entitlement to this "
        "system in CLN's web interface if you do not want virtual guests of "
        "this system to consume additional subscriptions.")

NO_SYS_ENTITLEMENT         = _("This system was unable to be associated with "
"any CLN service level modules. This system will not receive any software "
"updates to keep it secure and supported. Contace your Satellite administrator "
"about this problem. Once you make the "
"appropriate active subscriptions available in your account, you may browse "
"to this system's profile in the CLN web interface, delete the profile, and "
"re-connect this system to CloudLinux Network.")
ACTIVATION_KEY          = _("Universal default activation key detected\n"
                            "A universal default activation key was detected in your account. "
                            "This means that a set of properties (software channel subscriptions, "
                            "package installations, system group memberships, etc.) "
                            "for your system's connection to CloudLinux Network or CloudLinux Network Proxy"
                            "have been determined by the activation key rather than your "
                            "installation number.  "
                            "You may also refer to the RHN Reference Guide, section 6.4.6 for more details "
                            "about activation keys (http://access.redhat.com/knowledge/docs/Red_Hat_Network/)\n"
                            "Universal Default activation key: %s")

# Error Messages.
FATAL_ERROR                = _("Fatal Error")
WARNING                    = _("Warning")
HOSTED_CONNECTION_ERROR    = _("We can't contact the CloudLinux Network.\n\n"
                               "Double check the location provided - is '%s' correct?\n"
                               "If not, you can correct it and try again.\n\n"
                               "Make sure that the network connection on this system is operational.\n\n"
                               "This system will not be able to successfully receive software updates "
                               "from CloudLinux without connecting to a CloudLinux Network server")

BASECHANNELERROR           = _("Architecture: %s, OS Release: %s, OS "
                               "Version: %s")
SERVER_TOO_OLD             = _("This server doesn't support functionality "
                               "needed by this version of the software update"
                               " setup client. Please try again with a newer "
                               "server.")


SSL_CERT_ERROR_MSG         = _("<b><span size=\"16000\">Incompatible Certificate File</span></b>\n\n"
                               "The certificate you provided, <b>%s</b>, is not compatible with "
                               " the CloudLinux Network server at <b>%s</b>. You may want to double-check"
                               " that you have provided a valid certificate file."
                               " Are you sure you have provided the correct certificate, and that"
                               " the certificate file has not been corrupted?\n\n"
                               "Please try again with a different certificate file.")

SSL_CERT_EXPIRED           = _("<b><span size=\"12000\">Incompatible Certificate File</span></b>\n\n"
                               " The certificate is expired. Please ensure you have the correct "
                               " certificate and your system time is correct.")

SSL_CERT_FILE_NOT_FOUND_ERRER = _("Please verify the values of sslCACert and serverURL in "
                                  "/etc/sysconfig/rhn/up2date. You can either make the "
                                  "serverURL use http instead of https, or you can "
                                  "download the SSL cert from your Satellite, place it "
                                  "in /usr/share/rhn, and ensure sslCACert points to it.")

ACT_KEY_USAGE_LIMIT_ERROR = _("Problem registering system.\n\n"
                              "A universal default activation key limits the "
                              "number of systems which can connect to "
                              "the CLN organization associated with your "
                              "login. To allow this system to connect, "
                              "please contact your CLN organization "
                              "administrator to increase the number of "
                              "systems allowed to connect or to disable "
                              "this universal default activation key. "
                              "More details can be found in CloudLinux "
                              "Knowledgebase Article #7924 at "
                              "http://kbase.redhat.com/faq/FAQ_61_7924.shtm ")

CHANNEL_PAGE_TIP       = _("\n Tip: Minor releases with a '*' are currently"
                           " supported by CloudLinux.\n\n")

CHANNEL_PAGE_WARNING = _("Warning:You will not be able to limit this"
                          " system to minor release that is older than"
                          " the recent minor release if you select this"
                          " option.\n")

CONFIRM_OS_WARNING      = _("Your system will be subscribed to %s \n"
                            "base software channel. You will not be\n"
                            "able to move this system to an earlier release\n"
                            "(you will be able to move to a newer release).\n"
                            "Are you sure you would like to continue?")



# Navigation
OK        = _("OK")
ERROR     = _("Error")
NEXT      = _("Next")
BACK      = _("Back")
CANCEL    = _("Cancel")
NO_CANCEL = _("No, Cancel")
YES_CONT  = _("Yes, Continue")
DESELECT  = _("Press <space> to deselect the option.")


hardware_udev.py000064400000031764150516774040007762 0ustar00# Copyright (c) 2010--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 pyudev
import os
import re

from hwdata import PCI, USB

def get_devices():
    """ Returns list of dictionaries with keys for every device in system
        (values are provide as example):
        'bus' : 'pci'
        'driver' : 'pcieport-driver'
        'pciType' : '1'
        'detached' : '0'
        'class' : 'OTHER'
        'desc' : 'Intel Corporation|5000 Series Chipset PCI Express x4 Port 2'
    """
    # listen to uevents on all subsystems
    context = pyudev.Context()
    devices = context.list_devices()

    result = []
    for device in devices.match_subsystem("pci").match_subsystem("usb").match_subsystem("block").match_subsystem("ccw").match_subsystem("scsi"):
        subsystem = device.subsystem
        result_item = {
            'bus':      subsystem,
            'driver':   device.driver,
            'pciType':  _clasify_pci_type(subsystem),
            'detached': '0', # always zero?
            'class':    _clasify_class(device),
            'desc':     _get_device_desc(device),
        }
        if result_item['class'] is None:
            result_item['class'] = 'OTHER'
        if result_item['driver'] is None:
            result_item['driver'] = 'unknown'
        if subsystem == 'block':
            if _get_device_property(device, 'ID_BUS'):
                result_item['bus'] = _get_device_property(device, 'ID_BUS')
            result_item['device'] = device.sys_name
            if device.device_type == 'partition':
                # do not report partitions, just whole disks
                continue
            if _get_device_property(device, 'DM_NAME'):
                # LVM device
                continue
            if _get_device_property(device, 'MAJOR') == '1':
                # ram device
                continue
            if _get_device_property(device, 'MAJOR') == '7':
                # character devices for virtual console terminals
                continue
            # This is interpreted as Physical. But what to do with it?
            # result_item['prop1'] = ''
            # This is interpreted as Logical. But what to do with it?
            # result_item['prop2'] = ''
        elif subsystem == 'pci':
            pci_class = _get_device_property(device, 'PCI_ID')
            if pci_class:
                (result_item['prop1'], result_item['prop2']) = pci_class.split(':')
            pci_subsys = _get_device_property(device, 'PCI_SUBSYS_ID')
            if pci_subsys:
                (result_item['prop3'], result_item['prop4']) = pci_subsys.split(':')
        elif subsystem == 'usb':
           if _get_device_property(device, 'ID_VENDOR_ID'):
                result_item['prop1'] = _get_device_property(device, 'ID_VENDOR_ID')
           if _get_device_property(device, 'ID_MODEL_ID'):
                result_item['prop2'] = _get_device_property(device, 'ID_MODEL_ID')
        if _get_device_property(device, 'ID_BUS') and _get_device_property(device, 'ID_BUS') == 'scsi':
            if _get_device_property(device, 'ID_PATH') or _get_device_property(device, 'DEVPATH'):
                if _get_device_property(device, 'ID_PATH'):
                    path = _get_device_property(device, 'ID_PATH')
                    m = re.search('.*scsi-(\d+):(\d+):(\d+):(\d+)', path)
                else: # device.has_property('DEVPATH')
                    path = _get_device_property(device, 'DEVPATH')
                    m = re.search('.*/(\d+):(\d+):(\d+):(\d+)/block/', path)
                if m: # do not fail, if regexp did not match
                    result_item['prop1'] = m.group(1) # DEV_HOST
                    result_item['prop2'] = m.group(2) # DEV_ID
                    result_item['prop3'] = m.group(3) # DEV_CHANNEL
                    result_item['prop4'] = m.group(4) # DEV_LUN
        result.append(result_item)
    return result

def get_computer_info():
    """ Return dictionaries with keys (values are provided as example):
        'system.formfactor': 'unknown'
        'system.kernel.version': '2.6.18-128.1.6.el5xen'
            'system.kernel.machine': 'i686'
        'system.kernel.name': 'Linux'
    """
    uname = os.uname()
    result = {
        'system.kernel.name': uname[0],
        'system.kernel.version': uname[2],
        'system.kernel.machine': uname[4],
    }
    return result

#PCI DEVICE DEFINES
# These are taken from pci_ids.h in the linux kernel source and used to
# properly identify the hardware
PCI_BASE_CLASS_STORAGE =        '1'
PCI_CLASS_STORAGE_SCSI =        '00'
PCI_CLASS_STORAGE_IDE =         '01'
PCI_CLASS_STORAGE_FLOPPY =      '02'
PCI_CLASS_STORAGE_IPI =         '03'
PCI_CLASS_STORAGE_RAID =        '04'
PCI_CLASS_STORAGE_OTHER =       '80'

PCI_BASE_CLASS_NETWORK =        '2'
PCI_CLASS_NETWORK_ETHERNET =    '00'
PCI_CLASS_NETWORK_TOKEN_RING =  '01'
PCI_CLASS_NETWORK_FDDI =        '02'
PCI_CLASS_NETWORK_ATM =         '03'
PCI_CLASS_NETWORK_OTHER =       '80'

PCI_BASE_CLASS_DISPLAY =        '3'
PCI_CLASS_DISPLAY_VGA =         '00'
PCI_CLASS_DISPLAY_XGA =         '01'
PCI_CLASS_DISPLAY_3D =          '02'
PCI_CLASS_DISPLAY_OTHER =       '80'

PCI_BASE_CLASS_MULTIMEDIA =     '4'
PCI_CLASS_MULTIMEDIA_VIDEO =    '00'
PCI_CLASS_MULTIMEDIA_AUDIO =    '01'
PCI_CLASS_MULTIMEDIA_PHONE =    '02'
PCI_CLASS_MULTIMEDIA_OTHER =    '80'

PCI_BASE_CLASS_BRIDGE =         '6'
PCI_CLASS_BRIDGE_HOST =         '00'
PCI_CLASS_BRIDGE_ISA =          '01'
PCI_CLASS_BRIDGE_EISA =         '02'
PCI_CLASS_BRIDGE_MC =           '03'
PCI_CLASS_BRIDGE_PCI =          '04'
PCI_CLASS_BRIDGE_PCMCIA =       '05'
PCI_CLASS_BRIDGE_NUBUS =        '06'
PCI_CLASS_BRIDGE_CARDBUS =      '07'
PCI_CLASS_BRIDGE_RACEWAY =      '08'
PCI_CLASS_BRIDGE_OTHER =        '80'

PCI_BASE_CLASS_COMMUNICATION =  '7'
PCI_CLASS_COMMUNICATION_SERIAL = '00'
PCI_CLASS_COMMUNICATION_PARALLEL = '01'
PCI_CLASS_COMMUNICATION_MULTISERIAL = '02'
PCI_CLASS_COMMUNICATION_MODEM = '03'
PCI_CLASS_COMMUNICATION_OTHER = '80'

PCI_BASE_CLASS_INPUT =          '9'
PCI_CLASS_INPUT_KEYBOARD =      '00'
PCI_CLASS_INPUT_PEN =           '01'
PCI_CLASS_INPUT_MOUSE =         '02'
PCI_CLASS_INPUT_SCANNER =       '03'
PCI_CLASS_INPUT_GAMEPORT =      '04'
PCI_CLASS_INPUT_OTHER =         '80'

PCI_BASE_CLASS_SERIAL =         'C'
PCI_CLASS_SERIAL_FIREWIRE =     '00'
PCI_CLASS_SERIAL_ACCESS =       '01'
PCI_CLASS_SERIAL_SSA =          '02'
PCI_CLASS_SERIAL_USB =          '03'
PCI_CLASS_SERIAL_FIBER =        '04'
PCI_CLASS_SERIAL_SMBUS =        '05'

def _clasify_pci_type(subsystem):
    """ return 1 if device is PCI, otherwise -1 """
    if subsystem == 'pci':
        return '1'
    else:
        return '-1'

def _get_device_property(device, prop):
    """ return the property of the given device independent of the implementation version """
    try:
        return device.properties.get(prop)
    except AttributeError:
        return device.get(prop)

def _clasify_class(device):
    """ Clasify type of device. Returned value is one of following string:
        NETWORK, KEYBOARD, MOUSE, VIDEO, USB, IDE, SCSI, RAID, MODEM, SCANNER
        CAPTURE, AUDIO, FIREWIRE, SOCKET, CDROM, HD, FLOPPY, TAPE, PRINTER, OTHER
        or None if it is neither PCI nor USB device.
    """
    (base_class, sub_class) = _parse_pci_class(_get_device_property(device, 'PCI_CLASS'))
    subsystem = device.subsystem

    # network devices
    if base_class == PCI_BASE_CLASS_NETWORK:
        return 'OTHER' # if set as 'NETWORK' it will not display in HW tab

    # input devices
    # pci
    if base_class == PCI_BASE_CLASS_INPUT:
        if sub_class == PCI_CLASS_INPUT_KEYBOARD:
            return 'KEYBOARD'
        elif sub_class == PCI_CLASS_INPUT_MOUSE:
            return 'MOUSE'
    # usb
    id_serial = _get_device_property(device, 'ID_SERIAL')
    if id_serial:
        id_serial = id_serial.lower()
        # KEYBOARD <-- do this before mouse, some keyboards have built-in mice
        if 'keyboard' in id_serial:
            return 'KEYBOARD'
        # MOUSE
        if 'mouse' in id_serial:
            return 'MOUSE'

    if base_class:      # PCI Devices
        if base_class == PCI_BASE_CLASS_DISPLAY:
            return 'VIDEO'
        elif base_class == PCI_BASE_CLASS_SERIAL:
            if sub_class == PCI_CLASS_SERIAL_USB:
                return 'USB'
            elif sub_class == PCI_CLASS_SERIAL_FIREWIRE:
                return 'FIREWIRE'
        elif base_class == PCI_BASE_CLASS_STORAGE:
            if sub_class == PCI_CLASS_STORAGE_IDE:
                return 'IDE'
            elif sub_class == PCI_CLASS_STORAGE_SCSI:
                return 'SCSI'
            elif sub_class == PCI_CLASS_STORAGE_RAID:
                return 'RAID'
            elif sub_class == PCI_CLASS_STORAGE_FLOPPY:
                return 'FLOPPY'
        elif base_class == PCI_BASE_CLASS_COMMUNICATION and sub_class == PCI_CLASS_COMMUNICATION_MODEM:
            return 'MODEM'
        elif base_class == PCI_BASE_CLASS_INPUT and sub_class == PCI_CLASS_INPUT_SCANNER:
            return 'SCANNER'
        elif base_class == PCI_BASE_CLASS_MULTIMEDIA:
            if sub_class == PCI_CLASS_MULTIMEDIA_VIDEO:
                return 'CAPTURE'
            elif sub_class == PCI_CLASS_MULTIMEDIA_AUDIO:
                return 'AUDIO'
        elif base_class == PCI_BASE_CLASS_BRIDGE and (
            sub_class == PCI_CLASS_BRIDGE_PCMCIA or sub_class == PCI_CLASS_BRIDGE_CARDBUS ):
            return 'SOCKET'

    if subsystem == 'block':
        if _get_device_property(device, 'ID_CDROM') or (
            _get_device_property(device, 'ID_TYPE') and _get_device_property(device, 'ID_TYPE') == 'cd'):
            return 'CDROM'
        else:
            return 'HD'
    elif subsystem == 'sound':
        return 'AUDIO'

    if subsystem =='scsi':
        if device.device_type =='scsi_device':
            dev_type = _get_scsi_dev_type(device)
            if dev_type == 0 or dev_type == 14:
                return 'HD'
            elif dev_type == 1:
                return 'TAPE'
            elif dev_type == 5:
                return 'CDROM'
            else:
                return 'OTHER'
    # PRINTER
    m = re.search('.*/lp\d+$', device.sys_path)
    if m:
        return 'PRINTER'

    if subsystem == 'scsi':
        return 'SCSI'

    # Catchall for specific devices, only do this after all the others
    if subsystem == 'pci' or subsystem == 'usb':
        return 'OTHER'

    # No class found
    return None

def _get_device_desc(device):
    """ Return human readable description of device. """
    subsystem = device.subsystem
    command = None
    result = None
    if subsystem == 'pci':
        (vendor_id, device_id) = _get_device_property(device, 'PCI_ID').split(':')
        pci = PCI()
        result = "%s|%s" % (pci.get_vendor(vendor_id), pci.get_device(vendor_id, device_id))
    elif subsystem == 'usb':
        vendor_id = _get_device_property(device, 'ID_VENDOR_ID')
        usb = USB()
        if vendor_id:
            result = "%s|%s" % (usb.get_vendor(vendor_id), usb.get_device(vendor_id, _get_device_property(device, 'ID_MODEL_ID')))
        elif device.device_type == 'usb_interface':
            if device.driver == 'usbhid':
                result = 'USB HID Interface'
            elif device.driver == 'hub':
                result = 'USB Hub Interface'
            else:
                result = 'USB Interface'
        elif device.device_type == 'usb_device' and _get_device_property(device, 'PRODUCT'):
            (vendor_id, model_id) = _get_device_property(device, 'PRODUCT').split('/')[:2]
            # left pad it with 0 to 4 digits
            vendor_id = '%.4x' % int(vendor_id, 16)
            model_id = '%.4x' % int(model_id, 16)
            result = "%s|%s" % (usb.get_vendor(vendor_id), usb.get_device(vendor_id, model_id))
    elif subsystem == 'block':
        result = _get_device_property(device, 'ID_MODEL')
    if result:
        return result
    else:
        return ''

def _parse_pci_class(pci_class):
    """ Parse Class Code. Return touple of
        [base class code, sub-class code]
        You are usually interested to only first two.
        The third - "specific register-level programming interface" is ignored.
        For details, see the PCI Local Bus Specification 2.1/2.2 Section 6.2.1 Device Identification
    """
    if pci_class is None:
        return (None, None)
    else:
        return (pci_class[-6:-4], pci_class[-4:-2])

def _get_scsi_dev_type(device):
    """ Return SCSI type of device in raw format as presented in /sys/...devpath../type """
    try:
        f = open("%s/type" % device.sys_path, 'r')
    except IOError:
        return -1
    result = f.readline()
    f.close()
    return result
rhnreg.py000064400000076545150516774040006435 0ustar00#
# RHN Registration Client
# Copyright (c) 2000--2016 Red Hat, Inc.
#
# Authors:
#     Adrian Likins <alikins@redhat.com>
#     Preston Brown <pbrown@redhat.com>
#     Daniel Benamy <dbenamy@redhat.com>
import os
import sys
import dbus
import base64
import libxml2

from up2date_client import up2dateUtils
from up2date_client import up2dateErrors
from up2date_client import up2dateAuth
from up2date_client import rhnserver
from up2date_client import pkgUtils
from up2date_client import up2dateLog
from up2date_client import rhnreg_constants
from up2date_client import hardware
from up2date_client.rhnPackageInfo import convertPackagesFromHashToList
from up2date_client.pkgplatform import getPlatform
from rhn.i18n import ustr, sstr
from rhn.tb import raise_with_tb

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

try:
    from virtualization import support
except ImportError:
    support = None

import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

# global variables
#SYSID_DIR = /tmp
SYSID_DIR = "/etc/sysconfig/rhn"
REMIND_FILE = "%s/rhn_register_remind" % SYSID_DIR

HW_CODE_FILE = "%s/hw-activation-code" % SYSID_DIR
RHSM_FILE = "/etc/pki/consumer/cert.pem"

JWT_TOKEN = '/etc/sysconfig/rhn/jwt.token'

_human_readable_to_product = {
    'CloudLinux OS Shared Pro': 'shared_pro',
    'CloudLinux OS Shared': 'shared',
    'CloudLinux OS Solo': 'solo',
    'CloudLinux OS Admin': 'admin',
}
_product_to_human_readable = {
    v: k for k, v in _human_readable_to_product.items()}

from up2date_client import config
cfg = config.initUp2dateConfig()
log = up2dateLog.initLog()


def startRhnsd():
    # successful registration.  Try to start rhnsd if it isn't running.
    if os.access("/usr/sbin/rhnsd", os.R_OK|os.X_OK):
        # test for UsrMerge systemd environment
        systemd_system_unitdir = "/usr/lib/systemd/system"
        systemd_systemctl = "/usr/bin/systemctl"
        if not os.access(systemd_systemctl, os.R_OK|os.X_OK):
            if os.access("/bin/systemctl", os.R_OK|os.X_OK):
                systemd_systemctl = "/bin/systemctl"
                systemd_system_unitdir = "/lib/systemd/system"
        if os.access("%s/rhnsd.service" % systemd_system_unitdir, os.R_OK):
            # systemd
            if os.access(systemd_systemctl, os.R_OK|os.X_OK):
                os.system("%s enable rhnsd > /dev/null" % systemd_systemctl);
                os.system("%s start rhnsd > /dev/null" % systemd_systemctl);
            else:
                print(_("Warning: unable to enable rhnsd with systemd"))
        else:
            # SysV init scripts
            if os.access("/sbin/chkconfig", os.R_OK|os.X_OK):
                os.system("/sbin/chkconfig rhnsd on > /dev/null");
            else:
                print(_("Warning: unable to enable rhnsd with chkconfig"))

            service_path = "/sbin/service"
            if not os.access(service_path, os.R_OK|os.X_OK):
                if os.access("/usr/sbin/service", os.R_OK|os.X_OK):
                    service_path = "/usr/sbin/service"

            rc = os.system("%s rhnsd status > /dev/null" % service_path)
            if rc:
                os.system("%s rhnsd start > /dev/null" % service_path)

def getOemInfo():
    configFile = cfg["oemInfoFile"] or "/etc/sysconfig/rhn/oeminfo"

    if not os.access(configFile, os.R_OK):
        return {}

    fd = open(configFile, "r")
    L = fd.readlines()

    info = {}
    for i in L:
        i = i.strip()
        if i == "":
            continue
        try:
            (key, value) = i.split(':')
        except ValueError:
            raise_with_tb(up2dateErrors.OemInfoFileError(i))

        info[key] = value.strip()

    return info

def rhsm_registered():
    """ Returns true if system is registred using subscription manager """
    if os.access(RHSM_FILE, os.R_OK):
        statinfo = os.stat(RHSM_FILE)
        return statinfo.st_size > 0
    else:
        return False

def registered():
    return os.access(cfg['systemIdPath'], os.R_OK)

def createSystemRegisterRemindFile():
    if not os.access(REMIND_FILE, os.R_OK):
        # touch the file to tell the applet it needs to remind
        # the user to register
        fd = open(REMIND_FILE, "w+")
        fd.close()

def removeSystemRegisterRemindFile():
    if os.access(REMIND_FILE, os.R_OK):
        os.unlink(REMIND_FILE)

def _write_secure_file(secure_file, file_contents):
    """ Write a file to disk that is not readable by other users. """
    dir_name = os.path.dirname(secure_file)
    if not os.access(dir_name, os.W_OK):
        return False

    if os.access(secure_file, os.F_OK):
        # already have file there; let's back it up
        try:
            os.rename(secure_file, secure_file + '.save')
        except:
            return False

    fd = os.open(secure_file, os.O_WRONLY | os.O_CREAT, int('0600', 8))
    fd_file = os.fdopen(fd, 'w')
    try:
        fd_file.write(sstr(file_contents))
    finally:
        fd_file.close()

    return True

def writeSystemId(systemId):
    res = _write_secure_file(cfg['systemIdPath'], systemId)

    # newer registratio  clients will create a file indicating that
    # we need to remind the user to register, this removes it
    if res:
        removeSystemRegisterRemindFile()

    updateRhsmStatus()

    return res


def extract_system_id():
    xpath_str = "//member[name='system_id']/value/string"

    systemId = up2dateAuth.getSystemId()
    if systemId is None:
        return
    try:
        result = libxml2.parseDoc(systemId)
        context = result.xpathNewContext()
        system_id = context.xpathEval(xpath_str)[0].content
        # remove `ID-` and convert to integer
        system_id = int(system_id[3:])
    except (IndexError, libxml2.parserError):
        log.log_me('systemID file doesn\'t have system_id field or the file is broken')
        return

    return system_id


def _execute_pre_jwt_update_hook(token: str, allowTransition: bool):
    """
    Execute binary file which we use as hook for jwt token updates
    """
    import subprocess, os
    # during cldeploy we don't have python or any other packages, so just exit
    if not os.path.exists('/opt/cloudlinux/venv/bin/python3'):
        return

    cmd = ['/usr/sbin/cl-pre-jwt-update', '--new-token', token]
    if allowTransition:
        cmd.append('--allow-transition')

    p = subprocess.Popen(cmd)
    stdout, stderr = p.communicate()
    if p.returncode != 0:
        log.log_me("Pre jwt update hook failed with stdout=%s and stderr=%s" % (stdout, stderr))


def _execute_post_jwt_update_hook(allowTransition: bool):
    """
    Execute binary file which we use as hook for jwt token updates
    """
    import subprocess, os
    # during cldeploy we don't have python or any other packages, so just exit
    if not os.path.exists('/opt/cloudlinux/venv/bin/python3'):
        return

    cmd = ['/usr/sbin/cl-post-jwt-update']
    if allowTransition:
        cmd.append('--allow-transition')

    p = subprocess.Popen(cmd)
    stdout, stderr = p.communicate()
    if p.returncode != 0:
        log.log_me("Post jwt update hook failed with stdout=%s and stderr=%s" % (stdout, stderr))


def getAndWriteJWTTokenToFile(systemId, allowTransition = False):
    """
    Get a JWT token from CLN and save it to the file
    :param systemId: content of file `/etc/sysconfig/rhn/systemid`
    :return: None
    """

    xmlrpm_server = rhnserver.RhnServer()
    try:
        result = xmlrpm_server.up2date.getJWTToken(systemId)

    except up2dateErrors.UnknownMethodException:
        # if CLN doesn't have this method we do nothing
        return
    except (up2dateErrors.AuthenticationTicketError,
            up2dateErrors.RhnUuidUniquenessError,
            up2dateErrors.CommunicationError,
            up2dateErrors.AuthenticationOrAccountCreationError):
        log.log_exception(*sys.exc_info())
        return

    _execute_pre_jwt_update_hook(result, allowTransition)
    _write_secure_file(JWT_TOKEN, result)
    _execute_post_jwt_update_hook(allowTransition)


def writeHWCode(hw_activation_code):
    """Returns True if the write is successful or False if it fails."""
    return _write_secure_file(HW_CODE_FILE, hw_activation_code + '\n')

def get_virt_info():
    """
    This function returns the UUID and virtualization type of this system, if
    it is a guest.  Otherwise, it returns None.  To figure this out, we'll
    use a number of heuristics (list in order of precedence):

       1.  Check /proc/xen/xsd_port.  If exists, we know the system is a
           host; exit.
       2.  Check SMBIOS.  If vendor='Xen' and UUID is non-zero, we know the
           system is a fully-virt guest; exit.
       3.  Check /sys/hypervisor/uuid.  If exists and is non-zero, we know
           the system is a para-virt guest; exit.
       4.  If non of the above checks worked; we know we have a
           non-xen-enabled system; exit.
    """

    # First, check whether /proc/xen/xsd_port exists.  If so, we know this is
    # a host system.
    try:
        if os.path.exists("/proc/xen/xsd_port"):
            # Ok, we know this is *at least* a host system.  However, it may
            # also be a fully-virt guest.  Check for that next.  If it is, we'll
            # just report that instead since we only support one level of
            # virtualization.
            (uuid, virt_type) = get_fully_virt_info()
            return (uuid, virt_type)
    except IOError:
        # Failed.  Move on to next strategy.
        pass

    # This is not a virt host system. Check if it's a fully-virt guest.
    (uuid, virt_type) = get_fully_virt_info()
    if uuid is not None:
        return (uuid, virt_type)

    # This is not a fully virt guest system. Check if it's a para-virt guest.
    (uuid, virt_type) = get_para_virt_info()
    if uuid is not None:
        return (uuid, virt_type)

    # If we got here, we have a system that does not have virtualization
    # enabled.
    return (None, None)

def get_para_virt_info():
    """
    This function checks /sys/hypervisor/uuid to see if the system is a
    para-virt guest.  It returns a (uuid, virt_type) tuple.
    """
    try:
        uuid_file = open('/sys/hypervisor/uuid', 'r')
        uuid = uuid_file.read()
        uuid_file.close()
        uuid = uuid.lower().replace('-', '').rstrip("\r\n")
        virt_type = "para"
        return (uuid, virt_type)
    except IOError:
        # Failed; must not be para-virt.
        pass

    return (None, None)

def get_fully_virt_info():
    """
    This function looks in the SMBIOS area to determine if this is a
    fully-virt guest.  It returns a (uuid, virt_type) tuple.
    """
    vendor = hardware.dmi_vendor()
    uuid = hardware.dmi_system_uuid()
    if vendor.lower() == "xen":
        uuid = uuid.lower().replace('-', '')
        virt_type = "fully"
        return (uuid, virt_type)
    else:
        return (None, None)

def _is_host_uuid(uuid):
    uuid = eval('0x%s' % uuid)
    return long(uuid) == long(0)

def welcomeText():
    s = rhnserver.RegistrationRhnServer()

    return s.registration.welcome_message()


def getCaps():
    s = rhnserver.RegistrationRhnServer()
    # figure out if were missing any needed caps
    s.capabilities.validate()

def reserveUser(username, password):
    s = rhnserver.RegistrationRhnServer()
    return s.registration.reserve_user(username, password)


class RegistrationResult:
    def __init__(self, systemId, channels, failedChannels, systemSlots,
                 failedSystemSlots, universalActivationKey, rawDict=None):
        # TODO Get rid of rawDict
        self._systemId = systemId
        self._channels = channels
        self._failedChannels = failedChannels
        self._systemSlots = systemSlots
        self._failedSystemSlots = failedSystemSlots
        if len(universalActivationKey) > 0:
            self._universalActivationKey = universalActivationKey
        else:
            self._universalActivationKey = None
        self.rawDict = rawDict

    def getSystemId(self):
        return self._systemId

    def getChannels(self):
        return self._channels

    def getFailedChannels(self):
        return self._failedChannels

    def getSystemSlots(self):
        return self._systemSlots

    def getSystemSlotDescriptions(self):
        return [self._getSlotDescription(s) for s in self._systemSlots]

    def getFailedSystemSlotDescriptions(self):
        return [self._getFailedSlotDescription(s) for s in self._failedSystemSlots]

    def getUniversalActivationKey(self):
        """Returns None if no universal activation key was used."""
        return self._universalActivationKey

    def hasBaseAndUpdates(self):
        """Returns True if the system was subscribed to at least one channel
        and was given any type of system slot so it will get updates. In other
        words, returns True if the system will be getting at least basic
        updates.

        """
        # If it was subscribed to at least one channel, that must include a
        # base channel.
        return len(self._channels) > 0 and len(self._systemSlots) > 0

    def _getFailedSlotDescription(self, slot):
        if slot == 'virtualization_host':
            return rhnreg_constants.VIRT + " " + rhnreg_constants.VIRT_FAILED
        else:
            return self._getSlotDescription(slot)

    def _getSlotDescription(self, slot):
        if slot == 'enterprise_entitled':
            return rhnreg_constants.MANAGEMENT
        elif slot == 'virtualization_host':
            return rhnreg_constants.VIRT
        else:
            return slot


def getServerEdition(human_readable: bool = False):
    edition_cache_file = '/opt/cloudlinux/cl_edition'

    # edition cache does not exist only in the case when
    # we did not register server yet
    if not os.path.exists(edition_cache_file):
        return 'shared'

    with open(edition_cache_file) as f:
        raw_edition = f.read().strip('\n')
        if human_readable:
            return raw_edition
        return _human_readable_to_product[raw_edition]


def get_users_count_from_cllib():
    from subprocess import Popen, PIPE
    if not os.path.exists('/opt/cloudlinux/venv/bin'):
        raise ValueError()
    cmd = '/opt/cloudlinux/venv/bin/python3 -c "from clcommon.cpapi import cpusers; print(cpusers())"'
    process = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
    output, errors = [result.decode().strip() for result in process.communicate()]
    if errors:
        raise ValueError()
    return len(output[1:-1].split(', '))


def get_users_count_generic():
    from up2date_client.clpwd import ClPwd
    pwd = ClPwd()
    return len(pwd.get_uid_dict())


def countServerUsers():
    try:
        users_count = get_users_count_from_cllib()
    except Exception:
        users_count = get_users_count_generic()
    return users_count


def checkLicenseKey(activationKey, strictEdition, silentMigration):
    try:
        licenseInformation = checkKey(activationKey)
    except up2dateErrors.CommunicationError as e:
        print("%s" % e.errmsg)
        sys.exit(1)
    except up2dateErrors.UnknownMethodException:
        return

    currentEdition = getServerEdition()
    licenseEdition = licenseInformation['edition']

    if licenseEdition == currentEdition:
        return

    if strictEdition:
        print(
            "WARNING: Automatic registration in yum transactions is "
            "only available when edition matches the provided license. "
            "Your current edition is {current_edition} and your license is {new_edition}.".format(
                current_edition=_product_to_human_readable[currentEdition],
                new_edition=_product_to_human_readable[licenseEdition]
            )
        )
        print("Run clnreg_ks manually to complete registration.")
        sys.exit(1)

    if not silentMigration:
        if not sys.stdin.isatty():
            print('Error: interactive input required for edition migration, but tool '
                  'is running in non-interactive mode. Please try running the tool again '
                  'in interactive shell or add `--migrate-silently` flag to accept all'
                  'questions and perform the edition migration silently.')
            exit(1)

        message = (f"{_product_to_human_readable[currentEdition]} edition installed on your server "
                   f"does not match license you are trying to register server with: "
                   f"{_product_to_human_readable[licenseEdition]}. Migration is required. "
                   f"You may lose access to the services which are not supported by the new edition.")

        edition_to_users_limit = {
            'admin': 5,
            'solo': 1
        }
        license_users_limit = edition_to_users_limit.get(licenseEdition)
        if license_users_limit is not None:
            users_on_server = countServerUsers()

            if users_on_server > license_users_limit:
                print(f"The license you are trying to register with allows a maximum of "
                      f"{edition_to_users_limit[licenseEdition]} hosting accounts which is less "
                      f"than {users_on_server} users detected on this server. Aborting.")
                sys.exit(1)
            else:
                message = (f"{message} Also, the license you are trying to register with allows a maximum of "
                           f"{edition_to_users_limit[licenseEdition]} hosting accounts. "
                           f"Make sure that your system complies with this requirement.")

        _askConfirmation(message)



def _askConfirmation(confirmationMessage: str):
    """
    Prints message and makes sure that client is ready for edition migration.
    """
    print(confirmationMessage)

    response = input("Do you want to continue? [N/y]: ", )
    if response.lower() != 'y':
        print('Aborted.')
        sys.exit(1)


def registerSystem(username = None, password = None,
                   profileName = None,
                   token = None, other = None, edition=None):
    """Wrapper for the old xmlrpc to register a system. Activates subscriptions
    if a reg num is given.

    """
    assert username is None and password is None, \
        "username and password usage is deprecated"

    auth_dict = { "profile_name" : profileName,
                  "os_release" : up2dateUtils.getVersion(),
                  "release_name" : up2dateUtils.getOSRelease(),
                  "architecture" : up2dateUtils.getArch()
                }

    # send information about previous registration
    system_id_xml = up2dateAuth.getSystemId()
    if system_id_xml is not None:
        auth_dict["system_id"] = system_id_xml

    # dict of other bits to send
    if other:
        for (key, item) in other.items():
            auth_dict[key] = item
    if token:
        auth_dict["token"] = token
    else:
        auth_dict["username"] = username
        auth_dict["password"] = password

    if edition is not None:
        auth_dict['edition'] = edition
    else:
        auth_dict['edition'] = 'solo' \
            if os.path.exists('/etc/cloudlinux-edition-solo') \
            else 'admin' if os.path.exists('/etc/cloudlinux-edition-admin') else 'shared'

    if cfg['supportsSMBIOS']:
        auth_dict["smbios"] = _encode_characters(hardware.get_smbios())

    s = rhnserver.RegistrationRhnServer()
    ret = s.registration.new_system(auth_dict)

    return ret


def checkKey(activationKey):
    """
    Check the activation key and return it's edition and customer
    """
    s = rhnserver.RegistrationRhnServer()
    ret = s.registration.license_check(activationKey)

    # {'customerId': 10000327, 'edition': 'solo'}
    return ret


def updateRhsmStatus():
    try:
        bus = dbus.SystemBus()
        validity_obj = bus.ProxyObjectClass(bus, 'com.redhat.SubscriptionManager',
              '/EntitlementStatus', introspect=False)
        validity_iface = dbus.Interface(validity_obj,
              dbus_interface='com.redhat.SubscriptionManager.EntitlementStatus')
    except dbus.DBusException:
        # we can't connect to dbus. it's not running, likely from a minimal
        # install. we can't do anything here, so just ignore it.
        return

    try:
        validity_iface.check_status()
    except dbus.DBusException:
        # the call timed out, or something similar. we don't really care
        # about a timely reply or what the result might be, we just want
        # the method to run. So we can safely ignore this.
        pass


def getAvailableChannels(username, password):
    s = rhnserver.RegistrationRhnServer()
    server_arch = up2dateUtils.getArch()
    server_version = up2dateUtils.getVersion()
    server_release = up2dateUtils.getRelease()

    availableChannels = None

    try:
        availableChannels = s.registration.available_eus_channels(
                                                 username, password,
                                                 server_arch, server_version,
                                                 server_release)
    except xmlrpclib.Fault:
        f = sys.exc_info()[1]
        if f.faultCode == 99:
            raise_with_tb(up2dateErrors.DelayError(f.faultString))
        else:
            raise

    return availableChannels




def registerSystem2(username = None, password = None,
                   profileName = None, packages = None,
                   activationKey = None, other = {}):
    """Uses the new xmlrpcs to register a system. Returns a dict instead of just
    system id.

    The main differences between this and registerSystem and that this doesn't
    do activation and does child channel subscriptions if possible. See the
    documentation for the xmlrpc handlers in backend for more detail.

    If nothing is going to be in other, it can be {} or None.

    New in RHEL 5.

    """
    if other is None:
        other = {}

    if activationKey:
        assert username is None
        assert password is None
        assert activationKey is not None
    else:
        assert username is not None
        assert password is not None
        assert activationKey is None
    for key in other.keys():
        assert key in ['registration_number',
                       'org_id',
                       'virt_uuid',
                       'virt_type',
                       'channel']

    if cfg['supportsSMBIOS']:
        other["smbios"] = _encode_characters(hardware.get_smbios())

    s = rhnserver.RegistrationRhnServer()

    if activationKey:
        info = s.registration.new_system_activation_key(profileName,
                                                        up2dateUtils.getOSRelease(),
                                                        up2dateUtils.getVersion(),
                                                        up2dateUtils.getArch(),
                                                        activationKey,
                                                        other)
    else:
        info = s.registration.new_system_user_pass(profileName,
                                                   up2dateUtils.getOSRelease(),
                                                   up2dateUtils.getVersion(),
                                                   up2dateUtils.getArch(),
                                                   username,
                                                   password,
                                                   other)
    log.log_debug("Returned:\n%s" % info)
    result = RegistrationResult(info['system_id'],
                                info['channels'], info['failed_channels'],
                                info['system_slots'], info['failed_system_slots'],
                                info['universal_activation_key'],
                                rawDict=info)
    return result

def server_supports_eus():
    return cfg["supportsEUS"]

# pylint: disable=unused-argument
def sendHardware(systemId, hardwareList):
    # The endpoint that is called in this function (registration.add_hw_profile)
    # is disabled on the CLN side, and does not do anything.
    # Therefore, we can safely disable this function.
    return

    # Original code preserved below in case we ever need to re-enable this function.
    # def remove_ip6addr(x):
    #     if x['class'] == 'NETINFO' and 'ip6addr' in x:
    #         del x['ip6addr']
    #     return x
    # s = rhnserver.RegistrationRhnServer()
    # if not s.capabilities.hasCapability('ipv6', 1):
    #     hardwareList = [remove_ip6addr(i) for i in hardwareList]
    # s.registration.add_hw_profile(systemId, _encode_characters(hardwareList))

# pylint: disable=unused-argument
def sendPackages(systemId, packageList):
    # The endpoint that is called in this function (registration.add_packages)
    # is disabled on the CLN side, and does not do anything.
    # Therefore, we can safely disable this function.
    return

    # Original code preserved below in case we ever need to re-enable this function.
    # s = rhnserver.RegistrationRhnServer()
    # if not s.capabilities.hasCapability('xmlrpc.packages.extended_profile', 2):
    #     # for older satellites and hosted - convert to old format
    #     packageList = convertPackagesFromHashToList(packageList)
    # s.registration.add_packages(systemId, packageList)

def sendVirtInfo(systemId):
    if support is not None:
        support.refresh()

def listPackages(systemId):
    s = rhnserver.RegistrationRhnServer()
    print(s.registration.list_packages, systemId())

def makeNiceServerUrl(server):
    """Raises up2dateErrors.InvalidProtocolError if the server url has a
    protocol specified and it's not http or https.

    """
    protocol, host, path, parameters, query, fragmentIdentifier = urlparse.urlparse(server)
    if protocol is None or protocol == '':
        server = 'https://' + server
        # We must call it again because if there wasn't a protocol the
        # host will be in path
        protocol, host, path, parameters, query, fragmentIdentifier = urlparse.urlparse(server)
    if protocol not in ['https', 'http']:
        raise up2dateErrors.InvalidProtocolError("You specified an invalid "
                                                 "protocol. Only https and "
                                                 "http are allowed.")
    if path is None or path == '' or path == '/':
        path = '/XMLRPC'
    server = urlparse.urlunparse((protocol, host, path, parameters, query,
                                  fragmentIdentifier))
    # TODO Raise an exception if url isn't valid
    return server

def getServerType(serverUrl=None):
    """Returns 'hosted' if the url points to a known hosted server. Otherwise
    returns 'satellite'.
    """
    return 'satellite'


class ActivationResult:
    ACTIVATED_NOW = 0
    ALREADY_USED = 1

    def __init__(self, status, registrationNumber, channels={}, systemSlots={}):
        """channels and systemSlots are dicts where the key/value pairs are
        label (string) / quantity (int).

        """
        self._status = status
        # TODO Validate reg num
        self._regNum = registrationNumber
        self._channels = channels
        self._systemSlots = systemSlots

    def getStatus(self):
        return self._status

    def getRegistrationNumber(self):
        return self._regNum

    def getChannelsActivated(self):
        """Returns a dict- the key/value pairs are label/quantity."""
        return self._channels

    def getSystemSlotsActivated(self):
        """Returns a dict- the key/value pairs are label/quantity."""
        return self._systemSlots

def _encode_characters(*args):
        """ All the data we gathered from dmi, bios, gudev are in utf-8,
            we need to convert characters beyond ord(127) - e.g \xae to unicode.
        """
        result=[]
        for item in args:
            item_type = type(item)
            if item_type == StringType:
                item = ustr(item)
            elif item_type == TupleType:
                item = tuple(_encode_characters(i) for i in item)
            elif item_type == ListType:
                item = [_encode_characters(i) for i in item]
            elif item_type == DictType or item_type == DictionaryType:
                item = dict([(_encode_characters(name, val)) for name, val in item.items()])
            # else: numbers or UnicodeType - are safe
            result.append(item)
        if len(result) == 1:
            return result[0]
        else:
            return tuple(result)

def _activate_hardware(login, password):

    # Read the asset code from the hardware.
    activateHWResult = None
    hardwareInfo = None
    hw_activation_code = None
    try:
        hardwareInfo = hardware.get_hal_system_and_smbios()
        hardwareInfo = _encode_characters(hardwareInfo)
    except:
        log.log_me("There was an error while reading the hardware "
                   "info from the bios. Traceback:\n")
        log.log_exception(*sys.exc_info())

    if hardwareInfo is not None:
        try:
            activateHWResult = activateHardwareInfo(
                                       login, password, hardwareInfo)
            if activateHWResult.getStatus() == ActivationResult.ACTIVATED_NOW:
                hw_activation_code = activateHWResult.getRegistrationNumber()
                writeHWCode(hw_activation_code)
        except up2dateErrors.NotEntitlingError:
            log.log_debug('There are are no entitlements associated '
                          'with this hardware.')
        except up2dateErrors.InvalidRegistrationNumberError:
            log.log_debug('The hardware id was not recognized as valid.')
    return hw_activation_code

def activateHardwareInfo(username, password, hardwareInfo, orgId=None):
    """Tries to activate an entitlement linked to the hardware info that we
    read from the bios.

    Returns an ActivationResult.
    Can raise:
        Invalid number.
        Hardware info is not entitling.
        Communication errors, etc

    """
##    import pprint
##    pprint.pprint(hardwareInfo)

    other = {}
    if orgId:
        other = {'org_id': orgId}

    server = rhnserver.RegistrationRhnServer()
    result = server.registration.activate_hardware_info(username, password,
                                                        hardwareInfo, other)
    statusCode = result['status_code']
    regNum = result['registration_number']
    log.log_debug('Server returned status code %s' % statusCode)
    if statusCode == 0:
        return ActivationResult(ActivationResult.ACTIVATED_NOW, regNum)
    elif statusCode == 1:
        return ActivationResult(ActivationResult.ALREADY_USED, regNum)
    else:
        message = "The server returned unknown status code %s while activating" \
                   " the hardware info." % statusCode
        raise up2dateErrors.CommunicationError(message)


def spawnRhnCheckForUI():
    if os.access("/usr/sbin/rhn_check", os.R_OK|os.X_OK):
        from subprocess import Popen, PIPE
        p = Popen(["/usr/sbin/rhn_check"], stdin=PIPE, stdout=PIPE, \
                  stderr=PIPE)
        map(lambda x:log.log_me(x), p.stdout.readlines() + \
                  p.stderr.readlines())
    else:
        log.log_me("Warning: unable to run rhn_check")

if getPlatform() == 'deb':
    def pluginEnable():
        """On Debian no extra action for plugin is needed"""
        return 1, 0
else:
    from up2date_client.pmPlugin import pluginEnable
capabilities.py000064400000016434150516774040007570 0ustar00
from up2date_client import config
from up2date_client import up2dateErrors

try: # python2
    import UserDict
except ImportError: # python3
    import collections as UserDict

import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

# a dict with "capability name" as the key, and the version
# as the value.
neededCaps = {"caneatCheese": {'version':"21"},
              "supportsAutoUp2dateOption": {'version': "1"},
              "registration.finish_message": {'version': "1"},
              "xmlrpc.packages.extended_profile": {'version':"1"},
              "registration.delta_packages": {'version':"1"},
              "registration.update_contact_info": {'version': "1"},
              "registration.extended_update_support": {"version" : "1"},
              "registration.smbios": {"version" : "1"}}

def parseCap(capstring):
    value = None
    caps = capstring.split(',')

    capslist = []
    for cap in caps:
        try:
            (key_version, value) = [i.strip() for i in cap.split("=", 1)]
        except ValueError:
            # Bad directive: not in 'a = b' format
            continue

        # parse out the version
        # lets give it a shot sans regex's first...
        (key,version) = key_version.split("(", 1)

        # just to be paranoid
        if version[-1] != ")":
            print("something broke in parsing the capabilited headers")
        #FIXME: raise an approriate exception here...

        # trim off the trailing paren
        version = version[:-1]
        data = {'version': version, 'value': value}

        capslist.append((key, data))

    return capslist

class Capabilities(UserDict.UserDict):
    def __init__(self):
        UserDict.UserDict.__init__(self)
        self.missingCaps = {}
        #self.populate()
#        self.validate()
        self.neededCaps = neededCaps
        self.cfg = config.initUp2dateConfig()


    def populate(self, headers):
        for key, val in headers.items():
            if key.lower() == "x-rhn-server-capability":
                capslist = parseCap(val)

                for (cap,data) in capslist:
                    self.data[cap] = data

    def parseCapVersion(self, versionString):
        index = versionString.find('-')
        # version of "-" is bogus, ditto for "1-"
        if index > 0:
            rng = versionString.split("-")
            start = rng[0]
            end = rng[1]
            versions = range(int(start), int(end)+1)
            return versions

        vers = versionString.split(':')
        if len(vers) > 1:
            versions = [int(a) for a in vers]
            return versions

        return [int(versionString)]

    def validateCap(self, cap, capvalue):
        if not cap in self.data:
            errstr = _("This client requires the server to support %s, which the current " \
                       "server does not support") % cap
            self.missingCaps[cap] = None
        else:
            data = self.data[cap]
            # DOES the server have the version we need
            if int(capvalue['version']) not in self.parseCapVersion(data['version']):
                self.missingCaps[cap] =  self.neededCaps[cap]


    def validate(self):
        for key in self.neededCaps.keys():
            self.validateCap(key, self.neededCaps[key])

        self.workaroundMissingCaps()

    def setConfig(self, key, configItem):
        if key in self.tmpCaps:
            self.cfg[configItem] = 0
            del self.tmpCaps[key]
        else:
            self.cfg[configItem] = 1

    def workaroundMissingCaps(self):
        # if we have caps that we know we want, but we can
        # can work around, setup config variables here so
        # that we know to do just that
        self.tmpCaps = self.missingCaps

        # this is an example of how to work around it
        key = 'caneatCheese'
        if key in self.tmpCaps:
            # do whatevers needed to workaround
            del self.tmpCaps[key]
        else:
            # we support this, set a config option to
            # indicate that possibly
            pass

        # dict of key to configItem, and the config item that
        # corresponds with it

        capsConfigMap = {'supportsAutoUp2dateOption': 'supportsAutoUp2dateOption',
                         'registration.finish_message': 'supportsFinishMessage',
                         "registration.update_contact_info" : 'supportsUpdateContactInfo',
                         "registration.delta_packages" : 'supportsDeltaPackages',
                         "xmlrpc.packages.extended_profile" : 'supportsExtendedPackageProfile',
                         "registration.extended_update_support" : "supportsEUS",
                         "registration.smbios" : "supportsSMBIOS"}

        for key in capsConfigMap.keys():
            self.setConfig(key, capsConfigMap[key])

        # if we want to blow up on missing caps we cant eat around
        missingCaps = []
        wrongVersionCaps = []

        if len(self.tmpCaps):
            for cap in self.tmpCaps:
                capInfo = self.tmpCaps[cap]
                if capInfo == None:
                    # it's completly mssing
                    missingCaps.append((cap, capInfo))
                else:
                    wrongVersionCaps.append((cap, capInfo))

        errString = ""
        errorList = []
        if len(wrongVersionCaps):
            for (cap, capInfo) in wrongVersionCaps:
                errString = errString + "Needs %s of version: %s but server has version: %s\n" % (cap,
                                                                                    capInfo['version'],
                                                                                    self.data[cap]['version'])
                errorList.append({"capName":cap, "capInfo":capInfo, "serverVersion":self.data[cap]})

        if len(missingCaps):
            for (cap, capInfo) in missingCaps:
                errString = errString + "Needs %s but server does not support that capability\n" % (cap)
                errorList.append({"capName":cap, "capInfo":capInfo, "serverVersion":""})

        if len(errString):
            raise up2dateErrors.ServerCapabilityError(errString, errorList)

    def hasCapability(self, capability, version=None):
        """Checks if the server supports a capability and optionally a version.
        Returns True or False.

        This complements the neededCaps mechanism provided by this module.
        Using hasCapability makes it easier to do something only if the server
        supports it or to put workaround code in the user of this class. The
        neededCaps mechanism makes it easier to put workaround code in this
        module, which makes sense if it is to be shared.

        'capability' should be a string such as 'registration.foobar'. It can
        be a capability in 'neededCaps' above or one that isn't there. 'version'
        can be a string (where isdigit() is True) or an int.

        """
        assert version is None or str(version).isdigit()

        if not capability in self.data:
            return False
        if version:
            data = self.data[capability]
            if int(version) not in self.parseCapVersion(data['version']):
                return False
        return True
tui.py000064400000127315150516774040005741 0ustar00#
# TUI for RHN Registration
# Copyright (c) 2000--2020 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 os import geteuid
import sys

import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

import snack
import signal

from up2date_client import rhnreg, hardware
from up2date_client import up2dateErrors
from up2date_client import up2dateUtils
from up2date_client import pkgUtils
from up2date_client import up2dateLog
from up2date_client import config
from up2date_client.config import convert_url_from_puny
from up2date_client import up2dateAuth
from rhn import rpclib
from rhn.connections import idn_puny_to_unicode
from rhn.i18n import sstr
from up2date_client.pmPlugin import PM_PLUGIN_NAME, PM_PLUGIN_CONF
from up2date_client.rhnreg_constants import *

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

def ErrorWindow(screen, errmsg):
    snack.ButtonChoiceWindow(screen, sstr(ERROR), sstr(u"%s" % errmsg),
                             [sstr(BACK)])

def FatalErrorWindow(screen, errmsg):
    snack.ButtonChoiceWindow(screen, sstr(FATAL_ERROR), sstr(u"%s" % errmsg),
                             [sstr(OK)])
    screen.finish()
    sys.exit(1)

def WarningWindow(screen, errmsg):
    snack.ButtonChoiceWindow(screen, sstr(WARNING), sstr("%s" % errmsg),
                             [sstr(OK)])
    screen.finish()


def ConfirmQuitWindow(screen):
    button = snack.ButtonChoiceWindow(screen, sstr(CONFIRM_QUIT),
                             sstr(CONFIRM_QUIT_SURE) + "\n" + \
                             sstr(WHY_REGISTER_SEC)  + "\n" + \
                             sstr(WHY_REGISTER_SEC_TXT) + "\n\n" + \
                             sstr(WHY_REGISTER_DLD) + "\n" + \
                             sstr(WHY_REGISTER_DLD_TXT) + "\n\n" + \
                             sstr(WHY_REGISTER_SUPP) + "\n" + \
                             sstr(WHY_REGISTER_SUPP_TXT) + "\n\n" + \
                             sstr(WHY_REGISTER_COMP) + "\n" + \
                             sstr(WHY_REGISTER_COMP_TXT) + "\n\n" + \
                             sstr(CONFIRM_QUIT_WILLNOT) + "\n" + \
                             sstr(WHY_REGISTER_TIP),
                             [sstr(CONTINUE_REGISTERING), sstr(REGISTER_LATER2)],
                             width = 70)

    if button == sstr(REGISTER_LATER2).lower():
        screen.finish()
        return 1
    else:
        return 0


def tui_call_wrapper(screen, func, *params):

    try:
        results = func(*params)
    except up2dateErrors.CommunicationError:
        ErrorWindow(screen, HOSTED_CONNECTION_ERROR % config.getServerURL()[0])
        raise sys.exc_info()[1]
    except up2dateErrors.SSLCertificateVerifyFailedError:
        ErrorWindow(screen, e.errmsg)
        raise sys.exc_info()[1]
    except up2dateErrors.NoBaseChannelError:
        e = sys.exc_info()[1]
        FatalErrorWindow(screen, e.errmsg + '\n' +
                         BASECHANNELERROR % (up2dateUtils.getArch(),
                                             up2dateUtils.getOSRelease(),
                                             up2dateUtils.getVersion()))
    except up2dateErrors.SSLCertificateFileNotFound:
        e = sys.exc_info()[1]
        ErrorWindow(screen, e.errmsg + '\n\n' +
                         SSL_CERT_FILE_NOT_FOUND_ERRER)
        raise e

    return results

class WindowSkipException(Exception):
        pass

class AlreadyRegisteredWindow:
    name = "AlreadyRegisteredWindow"

    def __init__(self, screen, tui):

        if not rhnreg.registered() or tui.test:
            raise WindowSkipException()

        self.screen = screen
        self.tui = tui
        size = snack._snack.size()

        systemIdXml = rpclib.xmlrpclib.loads(up2dateAuth.getSystemId())
        oldUsername = systemIdXml[0][0]['username']
        oldsystemId = systemIdXml[0][0]['system_id']

        toplevel = snack.GridForm(self.screen, sstr(SYSTEM_ALREADY_SETUP), 1, 2)
        self.bb = snack.ButtonBar(self.screen,
                                  [(sstr(YES_CONT), "next"),
                                   (sstr(NO_CANCEL), "exit")])
        toplevel.add(self.bb, 0, 1, growx = 1)

        tb = snack.Textbox(size[0]-30, size[1]-20,
                            sstr(SYSTEM_ALREADY_REGISTERED + "\n\n"
                            + _("Spacewalk Location:") + " " + convert_url_from_puny(self.tui.serverURL) + "\n"
                            + _("Login:") + " " + oldUsername + "\n"
                            + _("System ID:") + " " + oldsystemId + "\n\n"
                            + SYSTEM_ALREADY_REGISTERED_CONT + "\n"),
                            1, 1)
        toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))

        self.g = toplevel

    def saveResults(self):
            pass

    def run(self):
        log.log_debug("Running %s" % self.name)

        result = self.g.runOnce()
        button = self.bb.buttonPressed(result)

        if result == "F12":
            return "next"

        return button

class SatelliteUrlWindow:
    name = "SatelliteUrlWindow"

    def __init__(self, screen, tui):
        self.screen = screen
        self.tui = tui
        self.tui.alreadyRegistered = 0

        self.server = convert_url_from_puny(self.tui.serverURL)
        fixed_server_url = rhnreg.makeNiceServerUrl(self.server)

        #Save the config only if the url is different
        if fixed_server_url != self.server:
            self.server = fixed_server_url
            config.setServerURL(self.server)
            cfg.save()

        size = snack._snack.size()

        toplevel = snack.GridForm(screen, sstr(SATELLITE_URL_WINDOW),
                1, 4)

        prompt_text = SATELLITE_URL_TEXT
        url_label = SATELLITE_URL_PROMPT
        ssl_label = SATELLITE_URL_PROMPT2

        label = snack.Textbox(size[0]-10, 3,
                                  sstr(prompt_text),
                                  scroll = 0, wrap = 1)

        toplevel.add(label, 0, 0, anchorLeft = 1)

        # spacer
        label = snack.Label(sstr(""))
        toplevel.add(label, 0, 1)

        grid = snack.Grid(2, 3)

        label = snack.Label(sstr(url_label))
        grid.setField(label, 0, 0, padding = (0, 0, 1, 0),
                          anchorRight = 1)

        self.urlEntry = snack.Entry(40)
        self.urlEntry.set(self.server)
        grid.setField(self.urlEntry, 1, 0, anchorLeft = 1)

        label = snack.Label(sstr(ssl_label))
        grid.setField(label, 0, 1, padding = (0, 0, 1, 0),
                          anchorRight = 1)

        self.sslEntry = snack.Entry(40)
        self.sslEntry.set(tui.sslCACert)
        grid.setField(self.sslEntry, 1, 1, anchorLeft = 1)

        toplevel.add(grid, 0, 2)

        # BUTTON BAR
        self.bb = snack.ButtonBar(screen,
                                   [(sstr(NEXT), "next"),
                                   (sstr(BACK), "back"),
                                   (sstr(CANCEL), "cancel")])

        toplevel.add(self.bb, 0, 3, padding = (0, 1, 0, 0),
                 growx = 1)


        self.g = toplevel

    def validateFields(self):
        if self.urlEntry.value() == "":
            snack.ButtonChoiceWindow(self.screen, sstr(ERROR),
                                     sstr(SATELLITE_REQUIRED),
                                     buttons = [sstr(OK)])
            self.g.setCurrent(self.urlEntry)
            return 0

        if (self.urlEntry.value()[:5] == 'https' and
                self.sslEntry.value() == ""):
            snack.ButtonChoiceWindow(self.screen, sstr(ERROR),
                                     sstr(SSL_REQUIRED),
                                     buttons = [sstr(OK)])
            self.g.setCurrent(self.sslEntry)
            return 0
        return 1

    def saveResults(self):
        serverEntry = self.urlEntry.value()
        # fix up the server url, E.G. if someone left off /XMLRPC
        fixed_server_url = rhnreg.makeNiceServerUrl(serverEntry)
        if fixed_server_url != serverEntry:
            serverEntry = fixed_server_url

        self.tui.serverURL = serverEntry
        self.tui.sslCACert = self.sslEntry.value()
        config.setServerURL(serverEntry)
        config.setSSLCACert(self.sslEntry.value())
        cfg.save()

    def run(self):
        log.log_debug("Running %s" % self.name)
        self.screen.refresh()
        valid = 0
        while not valid:
            result = self.g.run()
            button = self.bb.buttonPressed(result)

            if result == "F12":
                button = "next"

            if button == "next":
                valid = self.validateFields()

            else:
                break

        self.screen.popWindow()

        return button

class AlreadyRegisteredSubscriptionManagerWindow:
    name = "AlreadyRegisteredSubscriptionManagerWindow"

    def __init__(self, screen, tui):

        if not rhnreg.rhsm_registered() or tui.test:
            raise WindowSkipException()

        self.screen = screen
        self.tui = tui
        size = snack._snack.size()

        toplevel = snack.GridForm(self.screen, sstr(SYSTEM_ALREADY_SETUP), 1, 2)
        self.bb = snack.ButtonBar(self.screen,
                                  [(sstr(YES_CONT), "next"),
                                   (sstr(NO_CANCEL), "exit")])
        toplevel.add(self.bb, 0, 1, growx = 1)

        tb = snack.Textbox(size[0]-30, size[1]-20,
                            sstr(WARNING + "\n\n"
                            + RHSM_SYSTEM_ALREADY_REGISTERED + "\n\n"
                            + SYSTEM_ALREADY_REGISTERED_CONT + "\n"),
                            1, 1)
        toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))

        self.g = toplevel

    def saveResults(self):
            pass

    def run(self):
        log.log_debug("Running %s" % self.name)

        result = self.g.runOnce()
        button = self.bb.buttonPressed(result)

        if result == "F12":
            return "next"

        return button

class ConnectWindow:
    name = "ConnectWindow"

    def __init__(self, screen, tui):
        self.screen = screen
        self.tui = tui
        size = snack._snack.size()

        self.server = convert_url_from_puny(self.tui.serverURL)

        self.proxy = cfg['httpProxy']

        toplevel = snack.GridForm(self.screen, sstr(CONNECT_WINDOW), 1, 1)

        text = CONNECT_WINDOW_TEXT % self.server + "\n\n"

        if self.proxy:
            text += CONNECT_WINDOW_TEXT2 % self.proxy

        tb = snack.Textbox(size[0]-30, size[1]-20,
                           sstr(text),
                           1, 1)

        toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))

        self.g = toplevel


    def run(self):
        log.log_debug("Running %s" % self.name)

        # We draw and display the window.  The window gets displayed as
        # long as we are attempting to connect to the server.  Once we
        # connect the window is gone.
        result = self.g.draw()
        self.screen.refresh()
        # try to connect given the server url and ssl cert provided. If
        # unsuccessful, return to previous screen to allow user to fix.
        try:
            tui_call_wrapper(self.screen, rhnreg.getCaps)
        except:
            return "back"

        self.screen.popWindow()

        # Just return next, although the user wouldn't have actually pressed
        # anything.
        return "next"

    def saveResults(self):
        pass

class StartWindow:
    name = "StartWindow"

    def __init__(self, screen, tui):
        self.screen = screen
        self.tui = tui
        size = snack._snack.size()
        toplevel = snack.GridForm(self.screen, sstr(START_REGISTER_WINDOW),
                                  1, 2)

        start_register_text = sstr(START_REGISTER_TEXT)

        tb = snack.Textbox(size[0]-10, size[1]-14, start_register_text, 1, 1)
        toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))

        self.bb = snack.ButtonBar(self.screen,
                                  [(sstr(WHY_REGISTER), "why_register"),
                                   (sstr(NEXT), "next"),
                                   (sstr(CANCEL), "cancel")])
        toplevel.add(self.bb, 0, 1, growx = 1)

        self.g = toplevel

    def saveResults(self):
        pass


    def run(self):
        log.log_debug("Running %s" % self.name)
        result = self.g.runOnce()
        button = self.bb.buttonPressed(result)

        if result == "F12":
            return "next"
        elif button == "why_register":
            why_reg_win = WhyRegisterWindow(self.screen, self.tui)
            why_reg_win.run()
            return button

        return button

class WhyRegisterWindow:
    name = "WhyRegisterWindow"

    def __init__(self, screen, tui):
        self.screen = screen
        self.tui = tui
        size = snack._snack.size()
        toplevel = snack.GridForm(self.screen, sstr(WHY_REGISTER_WINDOW),
                                  1, 2)


        why_register_text = WHY_REGISTER_TEXT + "\n\n" + \
                            WHY_REGISTER_SEC  + "\n" + \
                            WHY_REGISTER_SEC_TXT + "\n\n" + \
                            WHY_REGISTER_DLD + "\n" + \
                            WHY_REGISTER_DLD_TXT + "\n\n" + \
                            WHY_REGISTER_SUPP + "\n" + \
                            WHY_REGISTER_SUPP_TXT + "\n\n" + \
                            WHY_REGISTER_COMP + "\n" + \
                            WHY_REGISTER_COMP_TXT + "\n\n" + \
                            WHY_REGISTER_TIP

        tb = snack.Textbox(size[0]-10, size[1]-14, sstr(why_register_text), 1, 1)

        toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))


        self.bb = snack.ButtonBar(self.screen,
                                  [(sstr(BACK_REGISTER), "back")])
        toplevel.add(self.bb, 0, 1, growx = 1)

        self.g = toplevel

    def run(self):
        log.log_debug("Running %s" % self.name)
        result = self.g.runOnce()
        button = self.bb.buttonPressed(result)

        return button


class InfoWindow:
    name = "InfoWindow"

    def __init__(self, screen, tui):
        self.screen = screen
        self.tui = tui
        self.tui.alreadyRegistered = 0

        self.server = self.tui.serverURL

        size = snack._snack.size()

        toplevel = snack.GridForm(screen, sstr(REGISTER_WINDOW), 1, 4)

        decoded_server = convert_url_from_puny(self.server)
        url = self.server
        if decoded_server != self.server:
            url += " (%s)" % decoded_server
        login_prompt = LOGIN_PROMPT % url
        login_label = LOGIN
        login_tip = LOGIN_TIP

        label = snack.Textbox(size[0]-10, 3,
                                  sstr(login_prompt),
                                  scroll = 0, wrap = 1)

        toplevel.add(label, 0, 0, anchorLeft = 1)

        grid = snack.Grid(2, 3)

        label = snack.Label(sstr(login_label))
        grid.setField(label, 0, 0, padding = (0, 0, 1, 0),
                          anchorRight = 1)

        self.userNameEntry = snack.Entry(20)
        self.userNameEntry.set(tui.userName)
        grid.setField(self.userNameEntry, 1, 0, anchorLeft = 1)

        label = snack.Label(sstr(PASSWORD))
        grid.setField(label, 0, 1, padding = (0, 0, 1, 0),
                          anchorRight = 1)

        try:
            self.passwordEntry = snack.Entry(20, password = 1)
        except TypeError:
            self.passwordEntry = snack.Entry(20, hidden = 1)
        self.passwordEntry.set(tui.password)
        grid.setField(self.passwordEntry, 1, 1, anchorLeft = 1)

        toplevel.add(grid, 0, 1)

        label = snack.TextboxReflowed(size[0]-10, sstr(login_tip))
        toplevel.add(label, 0, 2, anchorLeft=1)

        # BUTTON BAR
        self.bb = snack.ButtonBar(screen,
                                   [(sstr(NEXT), "next"),
                                   (sstr(BACK), "back"),
                                   (sstr(CANCEL), "cancel")])

        toplevel.add(self.bb, 0, 3, padding = (0, 1, 0, 0),
                 growx = 1)


        self.g = toplevel


    def validateFields(self):
        if self.userNameEntry.value() == "":
            snack.ButtonChoiceWindow(self.screen, sstr(ERROR),
                                     sstr(USER_REQUIRED),
                                     buttons = [sstr(OK)])
            self.g.setCurrent(self.userNameEntry)
            return 0
        if self.passwordEntry.value() == "":
            snack.ButtonChoiceWindow(self.screen, sstr(ERROR),
                                     sstr(PASSWORD_REQUIRED),
                                     buttons = [sstr(OK)])
            self.g.setCurrent(self.passwordEntry)
            return 0


        try:
            self.tui.alreadyRegistered = rhnreg.reserveUser(self.userNameEntry.value(), self.passwordEntry.value())
        except up2dateErrors.ValidationError:
            e = sys.exc_info()[1]
            snack.ButtonChoiceWindow(self.screen, sstr(_("Error")), sstr(_("The server indicated an error:\n")) + sstr(e.errmsg), buttons = [sstr(_("OK"))])
            self.g.setCurrent(self.userNameEntry)
            return 0
        except up2dateErrors.CommunicationError:
            e = sys.exc_info()[1]
            FatalErrorWindow(self.screen, _("There was an error communicating with the registration server:\n") + e.errmsg)
        return 1


    def saveResults(self):
        self.tui.userName = self.userNameEntry.value()
        self.tui.password = self.passwordEntry.value()

    def run(self):
        log.log_debug("Running %s" % self.name)
        self.screen.refresh()
        valid = 0
        while not valid:
            result = self.g.run()
            button = self.bb.buttonPressed(result)

            if result == "F12":
                button = "next"

            if button == "next":
                valid = self.validateFields()

            else:
                break

        self.screen.popWindow()
        return button

class OSReleaseWindow:
    name = "OSReleaseWindow"

    def __init__(self, screen, tui):

        self.tui = tui
        if not rhnreg.server_supports_eus():
            log.log_debug("Server does not support EUS, skipping OSReleaseWindow")
            raise WindowSkipException()

        self.available_channels = rhnreg.getAvailableChannels(
                        tui.userName, tui.password)
        if len(self.available_channels['channels']) < 1:
            log.log_debug("No available EUS channels, skipping OSReleaseWindow")
            raise WindowSkipException()

        self.screen = screen
        self.size = snack._snack.size()

        self.selectChannel = False

        toplevel = snack.GridForm(self.screen, sstr(SELECT_OSRELEASE), 1, 7)
        self.g = toplevel

        self.ostext = snack.TextboxReflowed(self.size[0]-10, sstr(OS_VERSION))
        toplevel.add(self.ostext, 0, 0, anchorLeft = 1)
        optiontext1 = sstr(LIMITED_UPDATES)

        if self.tui.limited_updates_button:
            self.limited_updates_button = snack.SingleRadioButton(optiontext1,
                                                None, isOn = 1)
        else:
            self.limited_updates_button = snack.SingleRadioButton(optiontext1,
                                                None)

        toplevel.add(self.limited_updates_button, 0, 1, padding = (0, 1, 0, 1),
                     anchorLeft = 1)

        self.sublabel = snack.Label(sstr(MINOR_RELEASE))
        toplevel.add(self.sublabel, 0, 2, anchorLeft = 1)

        self.channelList = snack.Listbox(self.size[1]-22, 1,
                                 width = self.size[0]-10)
        toplevel.add(self.channelList, 0, 3)

        for key, value in sorted(self.available_channels['channels'].items(), key=lambda a:a[0]):
            if key in self.available_channels['receiving_updates']:
                value = value + "*"
            self.channelList.append(" " + value, key)

        self.tip = snack.TextboxReflowed(self.size[0]-10, sstr(CHANNEL_PAGE_TIP))
        toplevel.add(self.tip, 0, 4, anchorLeft = 1)

        optiontext2 = sstr(ALL_UPDATES)

        if self.tui.all_updates_button:
            self.all_updates_button = snack.SingleRadioButton(optiontext2,
                                            self.limited_updates_button, isOn=1)
        else:
            self.all_updates_button = snack.SingleRadioButton(optiontext2,
                                            self.limited_updates_button)

        toplevel.add(self.all_updates_button, 0, 5, padding = (0, 0, 0, 1),
                     anchorLeft = 1)

        #self.warning = snack.TextboxReflowed(self.size[0]-10,
        #                     sstr(CHANNEL_PAGE_WARNING))
        #toplevel.add(self.warning, 0, 9, anchorLeft = 1)


        self.bb = snack.ButtonBar(screen,
                          [(sstr(NEXT), "next"),
                           (sstr(BACK), "back"),
                           (sstr(CANCEL), "cancel")])
        toplevel.add(self.bb, 0, 6, growx = 1)

        self.screen.refresh()



    def run(self):
        log.log_debug("Running %s" % self.name)
        self.screen.refresh()
        valid = "cancel"
        while valid == "cancel":
            result = self.g.run()
            button = self.bb.buttonPressed(result)

            if result == "F12":
                button = "next"

            if button == "next":
                valid = self.validateFields()
            else:
                break

        self.screen.popWindow()
        return button

    def validateFields(self):
        msgbox = "ok"
        later_release = False
        if self.limited_updates_button.selected():
            later_release = self.channelList.current() != \
                                 self.available_channels['default_channel']

        title = sstr(CONFIRM_OS_RELEASE_SELECTION)
        if later_release:
            msgbox = snack.ButtonChoiceWindow(self.screen, title,
                           sstr(CONFIRM_OS_WARNING) % self.channelList.current(),
                           buttons =[sstr(OK), sstr(CANCEL)])
            return msgbox

        if self.all_updates_button.selected() or later_release:
            msgbox = snack.ButtonChoiceWindow(self.screen, title,
                                  sstr(CONFIRM_OS_ALL), buttons =[sstr(OK), sstr(CANCEL)])
            return msgbox
        return msgbox

    def saveResults(self):
        # if limited updates save the channel and selction
        # for future use
        self.tui.other.pop('channel', None)
        if self.limited_updates_button.selected():
            log.log_debug("Selected Channel %s" % self.channelList.current())
            self.tui.other['channel'] = self.channelList.current()
            self.tui.limited_updates_button = self.limited_updates_button.selected()
            self.tui.all_updates_button = 0

        # saving data for all updates button
        if self.all_updates_button.selected():
            self.tui.all_updates_button = self.all_updates_button.selected()
            self.tui.limited_updates_button = 0


class HardwareWindow:
    name = "HardwareWindow"

    def __init__(self, screen, tui):
        self.screen = screen
        self.tui = tui
        size = snack._snack.size()

        #get the virtualization uuid and set it to other.
        (virt_uuid, virt_type) = rhnreg.get_virt_info()
        if not virt_uuid is None:
            self.tui.other['virt_uuid'] = virt_uuid
            self.tui.other['virt_type'] = virt_type

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

        toplevel = snack.GridForm(screen, sstr(HARDWARE_WINDOW), 1, 7)

        text = snack.TextboxReflowed(70, sstr(HARDWARE_WINDOW_DESC1))

        toplevel.add(text, 0, 0, anchorLeft = 1)

        grid = snack.Grid(2, 2)

        label = snack.Label(sstr(_("Profile name:")))
        grid.setField(label, 0, 0, padding = (0, 0, 1, 0), anchorRight = 1)

        self.profileEntry = snack.Entry(40)
        grid.setField(self.profileEntry, 1, 0, anchorLeft = 1)

        toplevel.add(grid, 0, 1, anchorLeft = 1)

        if tui.includeHardware:
            self.hardwareButton = snack.Checkbox(sstr(HARDWARE_WINDOW_CHECKBOX), isOn = 1)
        else:
            self.hardwareButton = snack.Checkbox(sstr(HARDWARE_WINDOW_CHECKBOX))

        toplevel.add(self.hardwareButton, 0, 2, padding = (0, 1, 0, 0),
                     anchorLeft = 1)

        label = snack.Label(sstr(DESELECT))
        toplevel.add(label, 0, 3, anchorLeft = 1, padding = (0, 0, 0, 1))

        grid = snack.Grid(4, 3)
        hardware_text = ''

        hardware_text += _("Version: ") + sstr(up2dateUtils.getVersion()) + "  "
        self.versionLabel = snack.Label(sstr(_("Version: ")))
        grid.setField(self.versionLabel, 0, 0, padding = (0, 0, 1, 0), anchorLeft = 1)

        self.versionLabel2 = snack.Label(sstr(up2dateUtils.getVersion()))
        grid.setField(self.versionLabel2, 1, 0, anchorLeft = 1)

        hardware_text += _("CPU model: ")

        for hw in tui.hardware:
            if hw['class'] == 'CPU':
                hardware_text += hw['model'] +"\n"

        hardware_text += _("Hostname: ")

        for hw in tui.hardware:
            if hw['class'] == 'NETINFO':
                unicode_hostname = idn_puny_to_unicode(hw['hostname'])
                hardware_text += unicode_hostname + "\n"

                if tui.profileName != "":
                    self.profileEntry.set(tui.profileName)
                else:
                    self.profileEntry.set(sstr(unicode_hostname))

        hardware_text += _("CPU speed: ")

        for hw in tui.hardware:
            if hw['class'] == 'CPU':
                hardware_text += _("%d MHz") % hw['speed'] + "  "

        hardware_text += _("IP Address: ")

        for hw in tui.hardware:
            if hw['class'] == 'NETINFO':
                if hw['ipaddr']:
                    hardware_text += hw['ipaddr'] + "  "
                elif hw['ip6addr']:
                    hardware_text += hw['ip6addr'] + "  "

        hardware_text += _("Memory: ")

        for hw in tui.hardware:
            if hw['class'] == 'MEMORY':
                hardware_text += _("%s megabytes") % hw['ram']

        tb = snack.TextboxReflowed(80, sstr(hardware_text))
        toplevel.add(tb, 0, 4)

        self.additionalHWLabel = snack.TextboxReflowed(size[0]-10, sstr(HARDWARE_WINDOW_DESC2))

        toplevel.add(self.additionalHWLabel, 0, 5, padding = (0, 1, 0, 0),
                     anchorLeft = 1)

        # BUTTON BAR
        self.bb = snack.ButtonBar(screen,
                                  [(sstr(NEXT), "next"),
                                   (sstr(BACK), "back"),
                                   (sstr(CANCEL), "cancel")])
        toplevel.add(self.bb, 0, 6, padding = (0, 1, 0, 0),
                     growx = 1)

        self.g = toplevel

        # self.screen.gridWrappedWindow(toplevel, 'HardwareWindow', 80, 14)

    def saveResults(self):
        self.tui.profileName = self.profileEntry.value()
        self.tui.includeHardware = self.hardwareButton.selected()

    def run(self):
        log.log_debug("Running %s" % self.name)
        result = self.g.runOnce()
        button = self.bb.buttonPressed(result)

        if result == "F12":
            return "next"
        return button

class PackagesWindow:
    name = "PackagesWindow"

    def __init__(self, screen, tui):
        self.screen = screen
        self.tui = tui
        size = snack._snack.size()
        toplevel = snack.GridForm(screen, sstr(PACKAGES_WINDOW), 1, 5)
        self.g = toplevel


        text = snack.TextboxReflowed(size[0]-10, sstr(PACKAGES_WINDOW_DESC1))

        toplevel.add(text, 0, 0, anchorLeft = 1)

        self.packagesButton = snack.Checkbox(sstr(PACKAGES_WINDOW_DESC2), 1)
        toplevel.add(self.packagesButton, 0, 1, padding = (0, 1, 0, 1),
                     anchorLeft = 1)

        label = snack.Label(sstr(PACKAGES_WINDOW_UNCHECK))
        toplevel.add(label, 0, 2, anchorLeft = 1)

        #self.packageList = snack.Listbox(size[1]-18, 1, width = size[0]-10)
        self.packageList = snack.CheckboxTree(size[1]-18, 1)
        toplevel.add(self.packageList, 0, 3)

        # do we need to read the packages from disk?
        if tui.packageList == []:
            self.pwin = snack.GridForm(screen, sstr(PACKAGES_WINDOW_PKGLIST), 1, 1)

            self.scale = snack.Scale(40, 100)
            self.pwin.add(self.scale, 0, 0)
            self.pwin.draw()
            self.screen.refresh()
            getArch = 0
            if rhnreg.cfg['supportsExtendedPackageProfile']:
                getArch = 1
            tui.packageList = pkgUtils.getInstalledPackageList(getArch=getArch)
            self.screen.popWindow()

        for package in tui.packageList:
            self.packageList.append("%s-%s-%s" % (sstr(package['name']),
                                                  sstr(package['version']),
                                                  sstr(package['release'])),
                                                  item = sstr(package['name']),
                                                  selected = 1)

        # BUTTON BAR
        self.bb = snack.ButtonBar(screen,
                                  [(sstr(NEXT), "next"),
                                   (sstr(BACK), "back"),
                                   (sstr(CANCEL), "cancel")])
        toplevel.add(self.bb, 0, 4, padding = (0, 1, 0, 0),
                     growx = 1)



    def setScale(self, amount, total):
        self.scale.set(int(((amount * 1.0)/ total) * 100))
        self.pwin.draw()
        self.screen.refresh()


    def saveResults(self):
        self.tui.includePackages = self.packagesButton.selected()
        selection = self.packageList.getSelection()
        for pkg in self.tui.packageList:
            if pkg['name'] in selection:
                self.tui.selectedPackages.append(pkg)


    def run(self):
        log.log_debug("Running %s" % self.name)
        result = self.g.runOnce()
        button = self.bb.buttonPressed(result)

        if result == "F12":
            return "next"
        return button

class SendWindow:
    name = "SendWindow"

    def __init__(self, screen, tui):
        self.screen = screen
        self.tui = tui
        size = snack._snack.size()

        toplevel = snack.GridForm(screen, sstr(SEND_WINDOW), 1, 2)

        text = snack.TextboxReflowed(size[0]-15, sstr(SEND_WINDOW_DESC))
        toplevel.add(text, 0, 0)

        # BUTTON BAR
        self.bb = snack.ButtonBar(screen,
                                  [(sstr(NEXT), "next"),
                                   (sstr(BACK), "back"),
                                   (sstr(CANCEL), "cancel")])
        toplevel.add(self.bb, 0, 1, padding = (0, 1, 0, 0),
                     growx = 1)

        self.g = toplevel

    def saveResults(self):
        pass


    def run(self):
        log.log_debug("Running %s" % self.name)
        result = self.g.runOnce()
        button = self.bb.buttonPressed(result)

        if result == "F12":
            return "next"
        return button

class SendingWindow:
    name = "SendingWindow"

    def __init__(self, screen, tui):
        self.screen = screen
        self.tui = tui
        size = snack._snack.size()

        self.pwin = snack.GridForm(screen, sstr(SENDING_WINDOW), 1, 1)

        self.scale = snack.Scale(40, 100)
        self.pwin.add(self.scale, 0, 0)

    def run(self):
        log.log_debug("Running %s" % self.name)

        self.pwin.draw()
        self.screen.refresh()

        reg_info = None
        try:
            # reg_info dict contains: 'system_id', 'channels',
            # 'failed_channels', 'slots', 'failed_slots'
            log.log_debug('other is %s' % str(self.tui.other))

            reg_info = rhnreg.registerSystem2(self.tui.userName, self.tui.password,
                                             self.tui.profileName,
                                             other = self.tui.other)
            reg_info = reg_info.rawDict

            systemId = sstr(reg_info['system_id'])

        except up2dateErrors.CommunicationError:
            e = sys.exc_info()[1]
            FatalErrorWindow(self.screen,
                             _("Problem registering system:\n") + e.errmsg)
        except up2dateErrors.RhnUuidUniquenessError:
            e = sys.exc_info()[1]
            FatalErrorWindow(self.screen,
                             _("Problem registering system:\n") + e.errmsg)
        except up2dateErrors.InsuffMgmntEntsError:
            e = sys.exc_info()[1]
            FatalErrorWindow(self.screen,
                             _("Problem registering system:\n") + e.errmsg)
        except up2dateErrors.RegistrationDeniedError:
            e = sys.exc_info()[1]
            FatalErrorWindow(self.screen,
                             _("Problem registering system:\n") + e.errmsg)
        except up2dateErrors.ActivationKeyUsageLimitError:
            FatalErrorWindow(self.screen,
                             ACT_KEY_USAGE_LIMIT_ERROR)
        except:
            log.log_exception(*sys.exc_info())
            FatalErrorWindow(self.screen, _("Problem registering system."))

        # write the system id out.
        if not rhnreg.writeSystemId(systemId):
            FatalErrorWindow(self.screen,
                             _("Problem writing out system id to disk."))

        self.setScale(1, 4)

        # include the info from the oeminfo file as well
        self.oemInfo = rhnreg.getOemInfo()

        self.setScale(2, 4)

        # maybe upload hardware profile
        if self.tui.includeHardware:
            try:
                rhnreg.sendHardware(systemId, self.tui.hardware)
            except up2dateErrors.CommunicationError:
                e = sys.exc_info()[1]
                FatalErrorWindow(self.screen,
                                 _("Problem sending hardware profile:\n") + e.errmsg)
            except:
                log.log_exception(*sys.exc_info())
                FatalErrorWindow(self.screen,
                                 _("Problem sending hardware profile."))

        self.setScale(3, 4)

        # build up package list if necessary
        if self.tui.includePackages:
            try:
                rhnreg.sendPackages(systemId, self.tui.selectedPackages)
            except up2dateErrors.CommunicationError:
                e = sys.exc_info()[1]
                FatalErrorWindow(self.screen, _("Problem sending package list:\n") + e.errmsg)
            except:
                log.log_exception(*sys.exc_info())
                FatalErrorWindow(self.screen, _("Problem sending package list."))

        li = None
        try:
            li = up2dateAuth.updateLoginInfo()
        except up2dateErrors.InsuffMgmntEntsError:
            FatalErrorWindow(self.screen, sys.exc_info()[1])

        # Send virtualization information to the server.
        rhnreg.sendVirtInfo(systemId)

        # enable yum-rhn-plugin / dnf-plugin-spacewalk
        try:
            self.tui.pm_plugin_present, self.tui.pm_plugin_conf_changed = rhnreg.pluginEnable()
        except IOError:
            e = sys.exc_info()[1]
            WarningWindow(self.screen, _("Could not open %s\n%s is not enabled.\n") % (PM_PLUGIN_CONF, PM_PLUGIN_NAME) + e.errmsg)
            self.tui.pm_plugin_conf_error = 1

        rhnreg.spawnRhnCheckForUI()
        self.setScale(4, 4)

        # Pop the pwin (Progress bar window)
        self.screen.popWindow()

        self.tui.reg_info = reg_info

        return "next"

    def saveResults(self):
        pass

    def setScale(self, amount, total):
        self.scale.set(int(((amount * 1.0)/ total) * 100))
        self.pwin.draw()
        self.screen.refresh()


class FinishWindow:
    name = "FinishWindow"

    def __init__(self, screen, tui):
        self.screen = screen
        self.tui = tui
        size = snack._snack.size()

        toplevel = snack.GridForm(screen, sstr(FINISH_WINDOW),
                                  1, 2)

        text = snack.TextboxReflowed(size[0]-11, sstr(FINISH_WINDOW_TEXT_TUI))
        toplevel.add(text, 0, 0)

        # BUTTON BAR
        self.bb = snack.ButtonBar(screen,
                                  [(sstr(_("Finish")), "next")])
        toplevel.add(self.bb, 0, 1, padding = (0, 1, 0, 0),
                     growx = 1)

        self.g = toplevel

    def saveResults(self):
        pass


    def run(self):
        log.log_debug("Running %s" % self.name)
        result = self.g.runOnce()
        button = self.bb.buttonPressed(result)

        if result == "F12":
            return "next"
        return button

class ReviewWindow:
    name = "ReviewWindow"

    def __init__(self, screen, tui):
        self.screen = screen
        self.tui = tui
        self.reg_info = tui.reg_info
        size = snack._snack.size()

        toplevel = snack.GridForm(screen, sstr(REVIEW_WINDOW), 1, 2)
        review_window_text = ''

        if not self.tui.pm_plugin_present:
            review_window_text += PM_PLUGIN_WARNING + "\n\n"
        if self.tui.pm_plugin_conf_error:
            review_window_text += PM_PLUGIN_CONF_ERROR + "\n\n"
        if self.tui.pm_plugin_conf_changed:
            review_window_text += PM_PLUGIN_CONF_CHANGED + "\n\n"

        # Build up the review_window_text based on the data in self.reg_info
        review_window_text += REVIEW_WINDOW_PROMPT + "\n\n"

        # Create and add the text for what channels the system was
        # subscribed to.
        if len(self.reg_info['channels']) > 0:
            channel_list = ""
            for channel in self.reg_info['channels']:
                channel_list += channel + "\n"

            channels = CHANNELS_TITLE + "\n" + \
                       OK_CHANNELS + "\n" + \
                       "%s\n"

            log.log_debug("server type is %s " % self.tui.serverType)
            channels += CHANNELS_SAT_WARNING

            review_window_text += channels % channel_list + "\n\n"

        if len(self.reg_info['system_slots']) > 0:
            slot_list = ""
            for slot in self.reg_info['system_slots']:
                if slot == 'enterprise_entitled':
                    slot_list += MANAGEMENT + "\n"
                elif slot == 'virtualization_host':
                    slot_list += VIRT + "\n"
                else:
                    slot_list += slot + "\n"
            review_window_text += SLOTS % slot_list + "\n\n"

        if len(self.reg_info['universal_activation_key']) > 0:
            act_key_list = ""
            for act_key in self.reg_info['universal_activation_key']:
                act_key_list += act_key
            review_window_text += ACTIVATION_KEY % (act_key_list)

        self.review_window = snack.Textbox(size[0]-10, size[1]-14, sstr(review_window_text), 1, 1)

        toplevel.add(self.review_window, 0, 0, padding = (0, 1, 0, 0))

        # BUTTON BAR
        self.bb = snack.ButtonBar(screen, [(sstr(OK), "next")])
        toplevel.add(self.bb, 0, 1, padding = (0, 1, 0, 0),
                     growx = 1)

        self.g = toplevel

    def saveResults(self):
        return 1

    def run(self):
        log.log_debug("Running %s" % self.name)
        result = self.g.runOnce()
        button = self.bb.buttonPressed(result)

        if result == "F12":
            button = "next"
        if not self.tui.pm_plugin_present:
            button = "exit"
        if self.tui.pm_plugin_conf_error:
            button = "exit"

        return button

class Tui:
    name = "RHN_REGISTER_TUI"

    def __init__(self, screen, test):
        self.screen = screen
        self.test = test
        self.size = snack._snack.size()
        self.drawFrame()
        self.alreadyRegistered = 0
        try:
            self.serverType = rhnreg.getServerType()
        except up2dateErrors.InvalidProtocolError:
            FatalErrorWindow(screen, _("You specified an invalid protocol." +
                                     "Only https and http are allowed."))

        self.windows = [
            AlreadyRegisteredSubscriptionManagerWindow,
            AlreadyRegisteredWindow,
            StartWindow,
            SatelliteUrlWindow,
            ConnectWindow,
            InfoWindow,
            OSReleaseWindow,
            HardwareWindow,
            PackagesWindow,
            SendWindow,
            SendingWindow,
            ReviewWindow,
            FinishWindow
            ]
        self.serverURL = config.getServerURL()[0]

        if not cfg['sslCACert']:
            cfg.set('sslCACert', '/usr/share/rhn/CLN-ORG-TRUSTED-SSL-CERT')
        self.sslCACert = cfg['sslCACert']

    def __del__(self):
        self.screen.finish()


    def drawFrame(self):
        self.welcomeText = COPYRIGHT_TEXT
        self.screen.drawRootText(0, 0, sstr(self.welcomeText))
        self.screen.pushHelpLine(sstr(_("  <Tab>/<Alt-Tab> between elements  |  <Space> selects  |  <F12> next screen")))


    def initResults(self):
        self.userName = ""
        self.password = ""

        self.oemInfo = {}
        self.productInfo = {
            "entitlement_num" : "",
            "registration_num" : "",
            "first_name" : "",
            "last_name" : "",
            "company" : "",
            "address" : "",
            "city" : "",
            "state" : "",
            "zip" : "",
            "country" : "",
           }

        self.other = {}
        self.other['registration_number'] = ''

        self.profileName = ""
        self.includeHardware = 1

        self.limited_updates_button = 1
        self.all_updates_button = 0
        self.includePackages = 0
        self.packageList = []
        self.selectedPackages = []
        self.pm_plugin_present = 1
        self.pm_plugin_conf_error = 0
        self.pm_plugin_conf_changed = 0

    def run(self):
        log.log_debug("Running %s" % self.name)
        self.initResults()

        direction = "forward"

        try:
            index = 0
            while index < len(self.windows):

                win = None
                try:
                    win = self.windows[index](self.screen, self)
                except WindowSkipException:
                    if direction == "forward":
                        index = index + 1
                    else:
                        index = index - 1
                    continue

                log.log_debug("index is %s" % index)

                result = win.run()
                log.log_debug("Result %s" % result)

                if result == "back":
                    if index > 0:
                        index = index - 1

                    # If we're on the info window, "back" means go back
                    # to the satellite url window, not back to the
                    # temporary connection test window.
                    if (index > 0 and
                            self.windows[index].name == ConnectWindow.name):
                        index -= 1

                    direction = "backward"

                elif result == "exit":
                    return

                elif result == "cancel":
                    log.log_debug("Caught a cancel request")

                    # Show the confirm quit window
                    if ConfirmQuitWindow(self.screen) == 1:
                        return

                elif result == "next":
                    index = index + 1
                    win.saveResults()
                    direction = "forward"

        finally:
            self.screen.finish()


def main():
    test = 0
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    if len(sys.argv) > 1:
        if sys.argv[1] == "-t" or sys.argv[1] == "--test":
            test = 1

    screen = snack.SnackScreen()

    if geteuid() != 0 and not test:
        FatalErrorWindow(screen, _("You must run the RHN registration program as root."))

    tui = Tui(screen, test)
    tui.run()


if __name__ == "__main__":
    main()
__pycache__/hardware.cpython-36.pyc000064400000044657150516774040013230 0ustar003

c8h��D@sJdZddlmZmZmZmZddlZddlZddlZddlZddl	m
Z
ddl	mZddl	mZddl
mZyeWnek
r�eZYnXyddlZdZWnek
r�d	ZYnXyddlZddlZdZWnek
r�d	ZYnXddlZejd
dd�Zeed��seje_ejZddlZejd
dg��ddl Z WdQRXddl	m!Z!yddl"m#Z#m$Z$dZ%Wn^ek
�r�yddl&m#Z#m$Z$dZ%Wn.ek
�r�ddl'm(Z(m)Z)m*Z*dZ%YnXYnXyddl+Z+Wnek
�r�dZ+YnXej,j-d�yddl.m/Z0dZ1Wnek
�r*d	Z1YnXda2da3dd�Z4e4�Z5e5�rfe j6�e!j7�Z8e8j9de5�dd�Z:dd�Z;dd�Z<dd�Z=d d!�Z>d"d#�Z?d$d%�Z@d&d'�ZAd(d)�ZBd*d+�ZCd,d-�ZDd.d/�ZEd0d1�ZFd2d3�ZGd4d5�ZHd6d7�ZId8d9�ZJd:d;�ZKd<d=�Z/eLd>k�rFx<e/�D]2ZMx&eMjN�D]ZOePd?eOeMeOf��qWeP�qWdS)@z1Used to read hardware info from kudzu, /proc, etc�)�gethostname�getaddrinfo�AF_INET�AF_INET6N)�config)�	rhnserver)�up2dateUtils)�ustrTFzrhn-client-tools)Zfallback�ugettextzFailed to save log entryzSMBIOS.*: entry point at)�
up2dateLog)�get_devices�get_computer_info�)�check_hal_dbus_status�get_hal_computer�read_halz/usr/share/rhsm)�HardwarecCsttd�sdStj�S)N�get_warnings)�hasattr�	dmidecoder�rr�/usr/lib/python3.6/hardware.py�dmi_warnings[s
rz.Warnings collected during dmidecode import: %sc	Cs�tdkr�trdStj�}|jtj�y6|jd�}t�}|rXtj�t	j
�}|jd|�Wn dat�}|rxtj�dS|j�atS)z= Initialize _dmi_data unless it already exist and returns it N�allzdmidecode warnings: %sr)
�	_dmi_data�_dmi_not_availablerZdmidecodeXMLZ
SetResultTypeZ
DMIXML_DOCZQuerySectionr�clear_warningsr�initLog�	log_debugZxpathNewContext)Zdmixml�data�dmi_warn�logrrr�_initialize_dmi_datags(
r"cCs6t�}|dkrdS|j|�}|gkr.|djSdSdS)z� Fetch DMI data from given section using given path.
        If data could not be retrieved, returns empty string.
        General method and should not be used outside of this module.
    N�r)r"Z	xpathEvalZcontent)�pathZdmi_datarrrr�get_dmi_data�s

r%cCstd�S)zt Return Vendor from dmidecode bios information.
        If this value could not be fetch, returns empty string.
    z/dmidecode/BIOSinfo/Vendor)r%rrrr�
dmi_vendor�sr&cCstd�}|sd}|S)zt Return UUID from dmidecode system information.
        If this value could not be fetch, returns empty string.
    z7/dmidecode/SystemInfo/SystemUUID[not(@unavailable='1')]r#)r%)Zuuidrrr�dmi_system_uuid�sr'cCs�tjdtj�siStdd�j�}i}d|d<x`|D]X}t|�s@q2|jd�}t|�dkrXq2|dj�}||d<dj|dd��j�||d<q2W|S)	Nz/etc/sysconfig/installinfo�rZINSTALLINFO�class�=rrr#)	�os�access�R_OK�open�	readlines�len�split�strip�join)ZinstallinfoZinstalldict�info�valsZstrippedstringrrr�read_installinfo�s

"r6csHytjd�}Wntk
r&g}YnXtjd��t�fdd�|D��S)z� returns number of CPU in system

    Beware that it can be different from number of active CPU (e.g. on s390x architecture
    z/sys/devices/system/cpu/z^cpu[0-9]+$csg|]}�j|�r|�qSr)�match)�.0�i)�re_cpurr�
<listcomp>�szcpu_count.<locals>.<listcomp>)r+�listdir�OSError�re�compiler0)Zcpu_dirr)r:r�	cpu_count�s

r@cCs�ytrt�j�dSWnYnXd}tjdtj�r�y^tjd�j�}d}x6|D].}|jd�r`qPt	|j
d�d�}||krP|}qPW|dkr�d|SWnYnXtjd	tj��r$ydtd	d
�j�}t
�}x4|D],}d|kr�t	|j
d�dj��}|j|�q�Wt|�dk�rt|�SWnYnXtjd
tj��r�yFtjd�j�}d}x |D]}d|k�rN|d7}�qNW|dk�rx|SWnYnXdS)Nzcpu.cpu_socket(s)rz/usr/bin/lscpuz/usr/bin/lscpu -pr�#�,�z
/proc/cpuinfor(zphysical id�:z/usr/sbin/dmidecodez /usr/sbin/dmidecode -t processorzProcessor Information���rE)�subscription_manager_available�SubManHardwareZ
getCpuInfor+r,�X_OK�popenr/�
startswith�intr1r-r.�setr2�addr0)�number_sockets�linesZmax_socket_index�lineZsocket_indexZ
socket_ids�countrrr�__get_number_sockets�sX





rRc
Csxdd�}dd�}tjdtj�s"iStr4tjtjd�tdd�j�}tj�dj	�}t
�}d	d
d�}|dd
kr~|dFd�dks�|dk�rz||�}|dkr�d|d<nd|d<||d<||d�|d<||d�|d<||d�|d<||d�|d<||d�|d<||d�|d<||d�|d<||d �|d!<||d"�}|d#k�r:d$}yttt
|��d%�|d&<Wntk
�rtdG|d&<YnX�n||dHk�rp||�}d'|d<||d)�|d<||d*�|d<||d+�|d<||d,�|d<d-||d.�||d/�f|d0<||d1�|d<d#|d<||d�|d<||d2�|d!<||d3�}|j�}y ttt
|d���d4|d&<Wntk
�rjdI|d&<YnX�n�|dJk�r.||�}||d<||d<||d6�|d<||d7�|d<||d8�|d<||d9�|d<||d�|d<|d"}yttt
|��d%�|d&<Wntk
�rdK|d&<YnX||d:�|d!<�n�|dLk�r�||�}||d<||d<||d*�|d<||d9�|d<||d�|d<||d<�|d<||d=�ddM�}yttt
|��d%�|d&<Wntk
�r�dN|d&<YnX�n|dOk�r�i}xH|jdA�D]:}	|	jdB�}
t|
�dk�r�q�|
d%j�||
dj�<�q�W||d<||d�|d<||d<||d<||dC�|d<d#|d<d#|d<d#|d<d#|d<||d:�|d!<d|d&<nX||d<||d<||d<||d<d#|d<d#|d<d#|d<d#|d<d#|d<d#|d!<d|d&<|d�s
d%|d<n@yt|d�|d<Wnd%|d<YnX|ddk�rJd%|d<tj�}|jjdD��rtt�}|�rt||dE<|S)PNcSs|j�}||krdS||S)Nr#)�lower)�a�entry�errr�	get_entry�szread_cpuinfo.<locals>.get_entrycSs�d}i}x�|jd�D]|}t|�s"q|d}|dkr4PxZ|jd�D]L}t|�sNq@|jd�}t|�dkrfq@|dj�|dj�}}|||j�<q@WqW|S)Nrz

r�
rDrC)r1r0r2rS)�cpulistrQ�tmpdict�cpuZcpu_attrr5�name�valuerrr�get_cpulist_as_dicts"
z)read_cpuinfo.<locals>.get_cpulist_as_dictz
/proc/cpuinfo�Cr(�ZCPUZ	Processor)r)Zdescrr9rC�86�x86_64�platformZi386rQZ	vendor_id�typez
model nameZmodelz
cpu familyZmodel_numberZ	model_verZsteppingZ	model_revz
cache size�cacheZbogomips�flags�otherzcpu mhzr#z-1rZspeed�alpha�alphaev6z
cpus detectedr[z	cpu modelz
cpu variationz%s/%szsystem typezsystem variationZ
model_versionzcpu revisionzplatform stringzcycle frequency [Hz]i@B�ia64�vendor�familyZarchrevZrevisionZfeatures�ppc64�machineZclock��s390�s390xrXz: zbogomips per cpuZcpu_socketsZsocket_count���rE)rhrirE)rjrE)rm���rE)rprq)r+r,r-�locale�	setlocale�
LC_NUMERICr.�read�unamerSr@rK�round�float�
ValueErrorr1r0r2rZ	RhnServerZcapabilitiesZ
hasCapabilityrR)
rWr^rYrxrQZhwdictrZZ	mhz_speedZhz_speedr[r5�srNrrr�read_cpuinfo�s�	&





 






r}cCs@tj�}|d}|dd�dkr&t�S|dd�dkr<t�SdS)NrCroz2.6z2.4)r+rx�read_memory_2_6�read_memory_2_4)ZunZkernelrrr�read_memory�sr�cCs�tjdtj�siStdd�j�}|jd�}|d}|j�}i}d|d<tt|d�d�}|dkrt|d	|d	}n|d
|d
}t|�|d<|d}|j�}tt|d�d�}t|�|d
<|S)Nz
/proc/meminfor(rXr�MEMORYr)i� r`��ramrC�swapii)	r+r,r-r.rwr1rK�long�str)�meminforOZcurlineZmemlist�memdict�megsrrrr�s$
rcCs�tjdtj�siStdd�j�}|jd�}i}xB|D]:}|jdd�}|d}t|�dkrZq4|dj�}|||<q4Wi}d|d<|d	}|jd
�}	t|	d�}
t|
d�}|d}|jd
�}	t|	d�}
t|
d�}t	|�|d
<t	|�|d<|S)Nz
/proc/meminfor(rXrDrrr�r)ZMemTotal� iZ	SwapTotalr�r�)
r+r,r-r.rwr1r0r2r�r�)r�rOZmeminfo_dictrPZblobs�keyr]r�Z	total_strZblipsZtotal_kr�Zswap_strZswap_kZ	swap_megsrrrr~�s2



r~cCsBtj�}tj�}ddd�}d}d}d}�x|D�]}|jd�d}|jd�d}||}	x�ttfD]�}
ytj|
�}Wntjk
r�wbYnX|d	r�tj�}|jd�\}}	t	|	�}	yR|j
d
�|j||	f�|j�d}
|
tkr�|
}n|
}tj
|
�}||
k�r|}Wn"tjk
�r(|j�wbYnX|j�qbWq.Wtjjd��r�tjdtj��r�tdd�j�}x�|D]}t|��s~�ql|j�}�qlWn�tjjd
��r tjd
tj��r td
d�j�}xd|D]\}t|��sҐq�|jd�}t|�dk�r�q�|dj�dk�r�dj|dd��jd�}P�q�W|dk�s4|dk�r8d}|||fS)z� returns [hostname, intf, intf6]

        Where hostname is you FQDN of this machine.
        And intf is numeric IPv4 address. And intf6 is IPv6 address.
    i��P)ZhttpsZhttpN�/rCrDrZenableProxy�z
/etc/hostnamer(z/etc/sysconfig/networkr*rZHOSTNAMEr#z"' 	
zlocalhost.localdomain�unknown)r�initUp2dateConfigZgetServerURLr1rr�socket�errorZgetProxySettingrKZ
settimeoutZconnectZgetsockname�getfqdn�closer+r$�isfiler,r-r.r/r0r2r3)�cfgZsl�st�hostnameZintfZintf6Z	serverUrlZserverZ
servertypeZportrlr|Zserver_portZintf_tmpZhostname_tmpZhostnameinfor4Znetworkinfor5rrr�findHostByRoute�sj








r�c	Cs�d}ytd|d�}Wn
|Sd}xV|j�D]J}|rT|jd�dkrT|j�d}P|jd�dkr0|j�d	}||kr0d
}q0W|j�|S)
Nr#z/proc/net/bonding/%sr(FzPermanent HW addr: rrozSlave Interface: rCTrErE)r.r/�findr1r�)�masterZslave�hwaddrZbondingZslave_foundrPZifnamerrr�get_slave_hwaddrFs r�cCs.i}d|d<t�\|d<|d<|d<|ddkrRt�|d<d|dkrRtj�|d<|ddkr�y4t|dd�}tdd	�|�}|d
dd
|d<Wnd|d<YnX|ddkr�y4t|dd�}td
d	�|�}|d
dd
|d<Wnd|d<YnX|ddk�rd|d<|ddk�r*d|d<|S)NZNETINFOr)r��ipaddrZip6addrr��.cSs|dtjkS)Nr)r�r)�xrrr�<lambda>iszread_network.<locals>.<lambda>rr`z	127.0.0.1cSs|dtjkS)Nr)r�r)r�rrrr�rsz::1r#)r�rr�r�r�filter)ZnetdictZ
list_of_addrsZ
ipv4_addrsZ
ipv6_addrsrrr�read_network[s4
r�c4Cs�i}d|d<tr(tr(tjjd�|StrFtttj�tj	���}nt
j�}�x6|D�],}y,trntj|�}nt
j
|�t
jdd}Wnd}YnXytjd|�}Wnd}YnX|r�tjj|�}t||�}y@tr�tj|�}n,td|d	�}|j�jd
�dj�}|j�Wn |dk�r0d
}nd}YnXy.t�rNtj|�}nt
j
|�t
jdd}Wnd}YnXy.t�r�tj|�}	nt
j
|�t
jdd}	Wnd}	YnXy.t�r�tj|�}
nt
j
|�t
jdd}
Wnd}
YnXg}t�r`tj|�}xL|D]D}
x<|
j�D]0}|j }|dk�r:d}|j!||j"|j#d���q"W�qW�ny�x�t
j
|�t
j$D]�}|djd�d}t%j&|�}|j'�r�d}n(|j(�r�d}n|j)�r�d}n|j*�r�d}|d}d}xd|jd�D]V}|�s�PnF|j+�dk�r|d7}n.|dt,t-|jd�dd��dd�j.d�7}�q�W|j!|||d���qtWWnt/k
�rlYnX|||	|
||d�||<qVW|S)NZ
NETINTERFACESr)zWWarning: information about network interfaces could not be retrieved on this platform.
r�addrr#z/sys/class/net/%s/masterz/sys/class/net/%s/device/ueventr(r*r�loZloopbackZUnknown�netmask�	broadcast�globalZuniverse)�scoper�r��%�link�hostZsiterDZffffr�r�rC�1)r�r�r�r��moduleZipv6)0�ethtool_present�netifaces_present�sys�stderr�write�listrL�ethtoolrZget_active_devices�	netifaces�
interfacesZ
get_hwaddrZifaddressesZAF_LINKr+�readlinkr$�basenamer�Z
get_moduler.�readliner1r2r�Z
get_ipaddrrZget_netmaskZ
get_broadcastZget_interfaces_infoZget_ipv6_addressesr��appendZaddressr�r�	ipaddressZIPv6AddressZ	is_globalZ
is_link_localZis_loopbackZ
is_site_localrS�binrK�rindex�KeyError)ZintDictr�Z	interfacer�r�Zmaster_interfacer�Zdriver_filer�r�r�Zip6_listZdev_infor4Zip6r�Zip6_addrZ
scope_infoZip6_netmaskZnetmask_bitsZ
two_octetsrrr�read_network_interfaces~s�












4r�c	CsBi}d|d<tj�dj�}|ddko6|dd�dkrH|dkrH|St�}|rZ||d	<td
�}|rn||d<td�}|r�|d
|}||d<td�|d<td�}|r�||d<td�}|r�||d<td�}|r�||d<td�}td�}td�}	td�}
dd|d|d|	d|
f|d<x*t|j��D]}||dk�r ||=�q W|S)NZDMIr)r`rr9rCrarbrkz!/dmidecode/SystemInfo/ProductName�productz/dmidecode/SystemInfo/Versionr��systemz%/dmidecode/BaseBoardInfo/ManufacturerZboardz/dmidecode/BIOSinfo/VendorZbios_vendorz/dmidecode/BIOSinfo/VersionZbios_versionz/dmidecode/BIOSinfo/ReleaseDateZbios_releasez#/dmidecode/ChassisInfo/SerialNumberz/dmidecode/ChassisInfo/AssetTagz%/dmidecode/BaseBoardInfo/SerialNumberz"/dmidecode/SystemInfo/SerialNumberz#(%s: %s) (%s: %s) (%s: %s) (%s: %s)ZchassisZassetrr)r+rxrSr&r%r��keys)Zdmidictrxrkr��versionr��releaseZchassis_serialZchassis_tagZboard_serialZ
system_serial�krrr�read_dmisJ(r�c
Cs�ytrt�}nt�}|j�}Wn6tk
rTtj�}dtj�d}|j	|�iSXi}x*|D]"}|j
d�r`t||�|t|�<q`W|jt
��|S)Nz0Error reading system and smbios information: %s
rr�)�using_gudevr
rZGetAllProperties�	Exceptionrrr��exc_inforrJr	�update�
get_smbios)ZpropsZcomputerr!�msgZsystem_and_smbiosr�rrr�get_hal_system_and_smbios;s 


r�c	CsDt�triSt�t�td�td�td�td�td�td�d�SdS)	a
 Returns dictionary with values we are interested for.
        For historical reason it is in format, which use HAL.
        Currently in dictionary are keys:
        smbios.system.uuid, smbios.bios.vendor, smbios.system.serial,
        smbios.system.manufacturer.
    z"/dmidecode/SystemInfo/SerialNumberz"/dmidecode/SystemInfo/Manufacturerz!/dmidecode/SystemInfo/ProductNamez/dmidecode/SystemInfo/SKUnumberz/dmidecode/SystemInfo/Familyz/dmidecode/SystemInfo/Version)zsmbios.system.uuidzsmbios.bios.vendorzsmbios.system.serialzsmbios.system.manufacturerzsmbios.system.productzsmbios.system.skunumberzsmbios.system.familyzsmbios.system.versionN)r"rr'r&r%rrrrr�Psr�c.Cs"trt�}nzt�\}}d}|s"|r<tj�}d}|j|�d}g}|r�yt�}|rT|}Wn.tj�}dtj�d}|j|�YnXyt	�}|r�|j
|�Wn"ttd�tj�d�YnXyt
�}|r�|j
|�Wn"ttd�tj�d�YnXtj�}|d�sNyt�}|�r(|j
|�Wn"ttd�tj�d�YnXyt�}|�rf|j
|�Wn.tj�}d	tj�d}|j|�YnXyt�}|�r�|j
|�Wn"ttd
�tj�d�YnX|d�syt�}|�r�|j
|�Wn"ttd�tj�d�YnX|S)NrzaWarning: haldaemon or messagebus service not running. Cannot probe hardware and DMI information.
rz'Error reading hardware information: %s
zError reading cpu information:z(Error reading system memory information:ZskipNetworkz%Error reading networking information:z"Error reading DMI information: %s
z)Error reading install method information:z,Error reading network interface information:)r�rrrrZlog_merr�r�r}r��print�_r�rr�r�r�r6r�)ZallhwZ
hal_statusZdbus_statusZhwdaemonr!r��retr�rrrrgsz



r�__main__z'%s' : '%s')Q�__doc__r�rrrrr>r+r�Zup2date_clientrrrZrhn.i18nr	r��	NameErrorrKr�r��ImportErrorr�r�r��gettextZtranslation�trr
r�ZdbusZsuppress_errorsrrZup2date_client.hardware_udevrr
r�Zup2date_client.hardware_gudevZup2date_client.hardware_halrrrrtr$r�Zsubscription_manager.hwproberrGrFrrrr rrr!rr"r%r&r'r6r@rRr}r�rr~r�r�r�r�r�r�r��__name__Zhwr�r�r�rrrr�<module>s�





7B!K#:]
__pycache__/up2dateErrors.cpython-36.pyc000064400000032511150516774040014156 0ustar003

c8h)�!@s�ddlZejddd�Zeed�s(eje_ejZddlZddlmZddl	m
Z
ddl	mZdd	lm
Z
ddlZejd
d�ejdd
�e_yddlmZWnJek
r�yddlmZWn$ek
r�Gd
d�de�ZYnXYnXGdd�de�ZGdd�de�ZyddlmZWnBek
�rZyddlmZWnek
�rTeZYnXYnXGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGd d!�d!e�ZGd"d#�d#e�Z Gd$d%�d%e�Z!Gd&d'�d'e�Z"Gd(d)�d)e!e�Z#Gd*d+�d+e!�Z$Gd,d-�d-e!e�Z%Gd.d/�d/e%�Z&Gd0d1�d1e�Z'Gd2d3�d3e!�Z(Gd4d5�d5e!�Z)Gd6d7�d7e!e�Z*Gd8d9�d9e!e�Z+Gd:d;�d;e!e�Z,Gd<d=�d=e�Z-Gd>d?�d?e!�Z.Gd@dA�dAe�Z/GdBdC�dCee�Z0GdDdE�dEe�Z1GdFdG�dGe%�Z2GdHdI�dIe�Z3GdJdK�dKe�Z4GdLdM�dMe!�Z5GdNdO�dOe!�Z6GdPdQ�dQe!�Z7GdRdS�dSe!�Z8GdTdU�dUe!�Z9GdVdW�dWe�Z:GdXdY�dYe!�Z;GdZd[�d[e!�Z<dS)\�Nzrhn-client-toolsT)Zfallback�ugettext)�ustr)�config)�
up2dateLog)�getPlatform�)�YumBaseError)�Errorc@s$eZdZdd�Zdd�Zdd�ZdS)�PmBaseErrorcCs
||_dS)N)�value)�self�errmsg�r�#/usr/lib/python3.6/up2dateErrors.py�__init__-szPmBaseError.__init__cCsttd�|jj|f��dS)Nzclass %s has no attribute '%s')�AttributeError�_�	__class__�__name__)r�namerrr�__getattr__/szPmBaseError.__getattr__cCs"|dkr||jd<n
||j|<dS)Nr
r)r
r)�__dict__)rrrrrr�__setattr__1szPmBaseError.__setattr__N)r�
__module__�__qualname__rrrrrrrr
,sr
c@s4eZdZdZdZdd�Zdd�Zdd�Zd	d
�ZdS)r	zbase class for errors�cCs2t|�}tj||�d|j||_tj�|_dS)Nzrhn-plugin: )rr
r�premsgrrZinitLog�log)rr
rrrr;szError.__init__cCs|jj|j�|jS)N)rZlog_mer)rrrr�__repr__AszError.__repr__cCsT|dkr|jSttd�r$tj||�S||jkr8|j|Sttd�|jj|f��dS)zG Spacewalk backend still use errmsg, let have errmsg as alias to value r
rzclass %s has no attribute '%s'N)	r�hasattrr
rrrrrr)rrrrrrEs


zError.__getattr__cCs<|dkr||jd<n$ttd�r.tj|||�n
||j|<dS)zG Spacewalk backend still use errmsg, let have errmsg as alias to value r
rrN)rrr
r)rrrrrrrSs

zError.__setattr__N)	rrr�__doc__rrrrrrrrrr	8sr	c@seZdZdS)�DebAndSuseRepoErrorN)rrrrrrrr!^sr!)�	RepoErrorc@seZdZdZed�ZdS)�RpmErrorz$rpm itself raised an error conditionzRPM error.  The message was:
N)rrrr rrrrrrr#jsr#c@seZdZdS)�RhnServerExceptionN)rrrrrrrr$nsr$c@seZdZdZed�ZdS)�
PasswordErrorz@Raise when the server responds with that a password is incorrectz!Password error. The message was:
N)rrrr rrrrrrr%qsr%c@s"eZdZdZed�Zddd�ZdS)�DependencyErrorz7Raise when a rpm transaction set has a dependency errorz'RPM dependency error. The message was:
NcCstj||�||_dS)N)r	r�deps)r�msgr'rrrrxszDependencyError.__init__)N)rrrr rrrrrrrr&usr&c@seZdZdZed�ZdS)�CommunicationErrorzDIndicates a problem doing xml-rpc http communication with the serverz2Error communicating with server. The message was:
N)rrrr rrrrrrr)sr)c@seZdZdZed�ZdS)�FileNotFoundErrorzR
    Raise when a package or header that is requested returns
    a 404 error codezFile Not Found: 
N)rrrr rrrrrrr*�sr*c@seZdZdZed�ZdS)�
DelayErrorzO
    Raise when the expected response from a xml-rpc call
    exceeds a timeoutz+Delay error from server.  The message was:
N)rrrr rrrrrrr+�sr+c@s eZdZdZdd�Zdd�ZdS)�RpmRemoveErrorzP
    Raise when we can't remove a package for some reason
    (failed deps, etc)cCs`tj|d�||_x@|jj�D]2}t|j|�|j|<|jd||j|f|_qW|j|_dS)Nrz%s failed because of %s
)r	r�args�keysrr�data)rr-�keyrrrr�szRpmRemoveError.__init__cCs|jS)N)r)rrrrr�szRpmRemoveError.__repr__N)rrrr rrrrrrr,�sr,c@seZdZdd�Zdd�ZdS)�
NoLogErrorcCst|�}|j||_dS)N)rrr)rr(rrrr�szNoLogError.__init__cCs|jS)N)r)rrrrr�szNoLogError.__repr__N)rrrrrrrrrr1�sr1c@seZdZdS)�
AbuseErrorN)rrrrrrrr2�sr2c@seZdZdS)�AuthenticationTicketErrorN)rrrrrrrr3�sr3c@seZdZdS)�AuthenticationErrorN)rrrrrrrr4�sr4c@seZdZdZed�ZdS)�ValidationErrorz1indicates an error during server input validationz!Error validating data at server:
N)rrrr rrrrrrr5�sr5c@seZdZdS)�InvalidRegistrationNumberErrorN)rrrrrrrr6�sr6c@s$eZdZdd�Zdd�Zdd�ZdS)�RegistrationDeniedErrorcCstj||j��dS)N)r$r�changeExplanation)rrrrr�sz RegistrationDeniedError.__init__cCs|jS)N)r)rrrrr�sz RegistrationDeniedError.__repr__cCstd�S)Nz�
CloudLinux Network Classic is not supported.
To register with CloudLinux Subscription Management please run:

    subscription-manager register --auto-attach

Get more information at www.cloudlinux.com
    )r)rrrrr8�sz)RegistrationDeniedError.changeExplanationN)rrrrrr8rrrrr7�sr7c@seZdZdZed�ZdS)�InvalidProductRegistrationErrorz1indicates an error during server input validationz"The installation number is invalidN)rrrr rrrrrrr9�sr9c@seZdZed�ZdS)�OemInfoFileErrorz)Error parsing the oemInfo file at field:
N)rrrrrrrrrr:�sr:c@seZdZdZdS)�NoBaseChannelErrorz/No valid base channel was found for this systemN)rrrr rrrrr;�sr;c@seZdZdS)�UnknownMethodExceptionN)rrrrrrrr<�sr<c@seZdZdS)�RhnUuidUniquenessErrorN)rrrrrrrr=�sr=c@seZdZddd�Zdd�ZdS)�ServerCapabilityErrorNcCs tj||�g|_|r||_dS)N)r	r�	errorlist)rr(r?rrrr�szServerCapabilityError.__init__cCs|jS)N)r)rrrrr�szServerCapabilityError.__repr__)N)rrrrrrrrrr>�s
r>c@seZdZdS)�NoChannelsErrorN)rrrrrrrr@�sr@c@seZdZdZed�ZdS)�NetworkErrorzD some generic network error occurred, e.g. connection reset by peer zNetwork error: N)rrrr rrrrrrrA�srAc@seZdZdd�ZejZdS)�SSLCertificateVerifyFailedErrorcCsftj�}|d}t|d�}|j�}|j�tjjtjj|�}|j	�rVt
j|d|�nt
j|d�dS)NZ	sslCACert�rznThe certificate %s is expired. Please ensure you have the correct certificate and your system time is correct.z(The SSL certificate failed verification.)rZinitUp2dateConfig�open�read�close�OpenSSLZcryptoZload_certificateZFILETYPE_PEMZhas_expiredr"r)rZ
up2dateConfigZcertFile�fZbufZtempCertrrrr�s

z(SSLCertificateVerifyFailedError.__init__N)rrrrr	rrrrrrB�srBc@seZdZdS)�SSLCertificateFileNotFoundN)rrrrrrrrI�srIc@seZdZdZdS)�$AuthenticationOrAccountCreationErrora%Class that can represent different things depending on context:
    While logging in with an existing user it represents a username or password
    being incorrect.
    While creating a new account, it represents the username already being
    taken or the user not being allowed to create an account.
    Optimally these different things would be different exceptions, but there
    are single fault codes the server can return to the client that can mean
    more than one of them so we have no way of knowing which is actually
    intended.

    N)rrrr rrrrrJsrJc@seZdZdS)�NotEntitlingErrorN)rrrrrrrrKsrKc@seZdZdS)�InvalidProtocolErrorN)rrrrrrrrLsrLc@seZdZdS)�UnableToCreateUserN)rrrrrrrrMsrMc@seZdZdS)�ActivationKeyUsageLimitErrorN)rrrrrrrrNsrNc@seZdZdS)�LoginMinLengthErrorN)rrrrrrrrOsrOc@seZdZdS)�PasswordMinLengthErrorN)rrrrrrrrPsrPc@seZdZdS)�PasswordMaxLengthErrorN)rrrrrrrrQ!srQc@s$eZdZdd�Zdd�Zdd�ZdS)�InsuffMgmntEntsErrorcCstj||j|��dS)N)r$rr8)rr(rrrr&szInsuffMgmntEntsError.__init__cCs|jS)N)r)rrrrr)szInsuffMgmntEntsError.__repr__cCs.td�}d}|j|�t|�}|d|�|S)Na�
    Your organization does not have enough Management entitlements to register this
    system to CloudLinux Network. Please notify your organization administrator of this error.
    You should be able to register this system after your organization frees existing
    or purchases additional entitlements. Additional entitlements may be purchased by your
    organization administrator by logging into CloudLinux Network and visiting

    A common cause of this error code is due to having mistakenly setup an
    Activation Key which is set as the universal default.  If an activation key is set
    on the account as a universal default, you can disable this key and retry to avoid
    requiring a Management entitlement.zExplanation:)r�rindex�len)rr(ZnewExplnZterm�locrrrr8,s

z&InsuffMgmntEntsError.changeExplanationN)rrrrrr8rrrrrR%srRc@seZdZdS)�NoSystemIdErrorN)rrrrrrrrV<srVc@seZdZdZdS)�InvalidRedirectionErrorz7 Raise when redirect requests could'nt return a packageN)rrrr rrrrrW?srW)=�gettextZtranslation�trrrrGZrhn.i18nrZup2date_clientrrZup2date_client.pkgplatformr�sys�pathZ
yum.Errorsrr
�ImportErrorZdnf.exceptionsr	�	Exceptionr!r"r#r$r%r&r)r*r+r,r1r2r3r4r5r6r7r9r:r;r<r=r>r@rArBrIrJrKrLrMrNrOrPrQrRrVrWrrrr�<module>s~
&

__pycache__/pkgplatform.cpython-36.opt-1.pyc000064400000000440150516774040014676 0ustar003

ge8h5�@sdZdd�ZdS)�rpmcCstdkrtSdSdS)Nz@PLATzFORM@rz
@PLATFORM@)�	_platform�rr�!/usr/lib/python3.6/pkgplatform.py�getPlatform	srN)rrrrrr�<module>s__pycache__/capabilities.cpython-36.opt-1.pyc000064400000012440150516774040015004 0ustar003

c8h�@s�ddlmZddlmZyddlZWnek
r@ddlZYnXddlZejddd�Ze	ed�sjeje_
ej
Zdd	idd
idd
idd
idd
idd
idd
idd
id�Zdd
�Z
Gdd�dej�ZdS)�)�config)�
up2dateErrorsNzrhn-client-toolsT)Zfallback�ugettext�versionZ21�1)�caneatCheese�supportsAutoUp2dateOptionzregistration.finish_messagez xmlrpc.packages.extended_profilezregistration.delta_packagesz registration.update_contact_infoz$registration.extended_update_supportzregistration.smbiosc	Cs�d}|jd�}g}x�|D]�}ydd�|jdd�D�\}}Wntk
rPwYnX|jdd�\}}|d
dkrvtd�|dd�}||d	�}|j||f�qW|S)N�,cSsg|]}|j��qS�)�strip)�.0�ir
r
�"/usr/lib/python3.6/capabilities.py�
<listcomp>#szparseCap.<locals>.<listcomp>�=��(�)z2something broke in parsing the capabilited headers)r�value���r)�split�
ValueError�print�append)	Z	capstringrZcaps�capslist�capZkey_version�keyr�datar
r
r�parseCaps


rc@sNeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	ddd�Z
dS)�CapabilitiescCs&tjj|�i|_t|_tj�|_dS)N)�UserDict�__init__�missingCaps�
neededCapsrZinitUp2dateConfig�cfg)�selfr
r
rr!:szCapabilities.__init__cCsJxD|j�D]8\}}|j�dkr
t|�}x|D]\}}||j|<q,Wq
WdS)Nzx-rhn-server-capability)�items�lowerrr)r%Zheadersr�valrrrr
r
r�populateCs
zCapabilities.populatecCsx|jd�}|dkrF|jd�}|d}|d}tt|�t|�d�}|S|jd�}t|�dkrndd�|D�}|St|�gS)N�-rr�:cSsg|]}t|��qSr
)�int)r�ar
r
rrWsz0Capabilities.parseCapVersion.<locals>.<listcomp>)�findr�ranger,�len)r%Z
versionString�index�rng�start�endZversionsZversr
r
r�parseCapVersionKs


zCapabilities.parseCapVersioncCsZ||jkr"td�|}d|j|<n4|j|}t|d�|j|d�krV|j||j|<dS)NzXThis client requires the server to support %s, which the current server does not supportr)r�_r"r,r5r#)r%rZcapvalueZerrstrrr
r
r�validateCap\s

zCapabilities.validateCapcCs2x$|jj�D]}|j||j|�qW|j�dS)N)r#�keysr7�workaroundMissingCaps)r%rr
r
r�validatehszCapabilities.validatecCs,||jkrd|j|<|j|=n
d|j|<dS)Nrr)�tmpCapsr$)r%rZ
configItemr
r
r�	setConfigns


zCapabilities.setConfigc	CsZ|j|_d}||jkr |j|=ndddddddd	�}x |j�D]}|j|||�q>Wg}g}t|j�r�x>|jD]4}|j|}|dkr�|j||f�qp|j||f�qpWd
}g}t|��rxH|D]@\}}|d||d|j|df}|j|||j|d
��q�Wt|��r@x0|D](\}}|d|}|j||d
d
���qWt|��rVtj||��dS)NrrZsupportsFinishMessageZsupportsUpdateContactInfoZsupportsDeltaPackagesZsupportsExtendedPackageProfileZsupportsEUSZsupportsSMBIOS)rzregistration.finish_messagez registration.update_contact_infozregistration.delta_packagesz xmlrpc.packages.extended_profilez$registration.extended_update_supportzregistration.smbios�z3Needs %s of version: %s but server has version: %s
r)ZcapName�capInfoZ
serverVersionz5Needs %s but server does not support that capability
)	r"r;r8r<r0rrrZServerCapabilityError)	r%rZ
capsConfigMapr"ZwrongVersionCapsrr>Z	errStringZ	errorListr
r
rr9usF

	




z"Capabilities.workaroundMissingCapsNcCs:||jkrdS|r6|j|}t|�|j|d�kr6dSdS)a�Checks if the server supports a capability and optionally a version.
        Returns True or False.

        This complements the neededCaps mechanism provided by this module.
        Using hasCapability makes it easier to do something only if the server
        supports it or to put workaround code in the user of this class. The
        neededCaps mechanism makes it easier to put workaround code in this
        module, which makes sense if it is to be shared.

        'capability' should be a string such as 'registration.foobar'. It can
        be a capability in 'neededCaps' above or one that isn't there. 'version'
        can be a string (where isdigit() is True) or an int.

        FrT)rr,r5)r%Z
capabilityrrr
r
r�
hasCapability�s

zCapabilities.hasCapability)N)�__name__�
__module__�__qualname__r!r)r5r7r:r<r9r?r
r
r
rr9s	<r)Zup2date_clientrrr �ImportError�collections�gettextZtranslation�t�hasattrrr6r#rrr
r
r
r�<module>s(
__pycache__/capabilities.cpython-36.pyc000064400000012531150516774040014046 0ustar003

c8h�@s�ddlmZddlmZyddlZWnek
r@ddlZYnXddlZejddd�Ze	ed�sjeje_
ej
Zdd	idd
idd
idd
idd
idd
idd
idd
id�Zdd
�Z
Gdd�dej�ZdS)�)�config)�
up2dateErrorsNzrhn-client-toolsT)Zfallback�ugettext�versionZ21�1)�caneatCheese�supportsAutoUp2dateOptionzregistration.finish_messagez xmlrpc.packages.extended_profilezregistration.delta_packagesz registration.update_contact_infoz$registration.extended_update_supportzregistration.smbiosc	Cs�d}|jd�}g}x�|D]�}ydd�|jdd�D�\}}Wntk
rPwYnX|jdd�\}}|d
dkrvtd�|dd�}||d	�}|j||f�qW|S)N�,cSsg|]}|j��qS�)�strip)�.0�ir
r
�"/usr/lib/python3.6/capabilities.py�
<listcomp>#szparseCap.<locals>.<listcomp>�=��(�)z2something broke in parsing the capabilited headers)r�value���r)�split�
ValueError�print�append)	Z	capstringrZcaps�capslist�capZkey_version�keyr�datar
r
r�parseCaps


rc@sNeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	ddd�Z
dS)�CapabilitiescCs&tjj|�i|_t|_tj�|_dS)N)�UserDict�__init__�missingCaps�
neededCapsrZinitUp2dateConfig�cfg)�selfr
r
rr!:szCapabilities.__init__cCsJxD|j�D]8\}}|j�dkr
t|�}x|D]\}}||j|<q,Wq
WdS)Nzx-rhn-server-capability)�items�lowerrr)r%Zheadersr�valrrrr
r
r�populateCs
zCapabilities.populatecCsx|jd�}|dkrF|jd�}|d}|d}tt|�t|�d�}|S|jd�}t|�dkrndd�|D�}|St|�gS)N�-rr�:cSsg|]}t|��qSr
)�int)r�ar
r
rrWsz0Capabilities.parseCapVersion.<locals>.<listcomp>)�findr�ranger,�len)r%Z
versionString�index�rng�start�endZversionsZversr
r
r�parseCapVersionKs


zCapabilities.parseCapVersioncCsZ||jkr"td�|}d|j|<n4|j|}t|d�|j|d�krV|j||j|<dS)NzXThis client requires the server to support %s, which the current server does not supportr)r�_r"r,r5r#)r%rZcapvalueZerrstrrr
r
r�validateCap\s

zCapabilities.validateCapcCs2x$|jj�D]}|j||j|�qW|j�dS)N)r#�keysr7�workaroundMissingCaps)r%rr
r
r�validatehszCapabilities.validatecCs,||jkrd|j|<|j|=n
d|j|<dS)Nrr)�tmpCapsr$)r%rZ
configItemr
r
r�	setConfigns


zCapabilities.setConfigc	CsZ|j|_d}||jkr |j|=ndddddddd	�}x |j�D]}|j|||�q>Wg}g}t|j�r�x>|jD]4}|j|}|dkr�|j||f�qp|j||f�qpWd
}g}t|��rxH|D]@\}}|d||d|j|df}|j|||j|d
��q�Wt|��r@x0|D](\}}|d|}|j||d
d
���qWt|��rVtj||��dS)NrrZsupportsFinishMessageZsupportsUpdateContactInfoZsupportsDeltaPackagesZsupportsExtendedPackageProfileZsupportsEUSZsupportsSMBIOS)rzregistration.finish_messagez registration.update_contact_infozregistration.delta_packagesz xmlrpc.packages.extended_profilez$registration.extended_update_supportzregistration.smbios�z3Needs %s of version: %s but server has version: %s
r)ZcapName�capInfoZ
serverVersionz5Needs %s but server does not support that capability
)	r"r;r8r<r0rrrZServerCapabilityError)	r%rZ
capsConfigMapr"ZwrongVersionCapsrr>Z	errStringZ	errorListr
r
rr9usF

	




z"Capabilities.workaroundMissingCapsNcCsR|dkst|�j�st�||jkr&dS|rN|j|}t|�|j|d�krNdSdS)a�Checks if the server supports a capability and optionally a version.
        Returns True or False.

        This complements the neededCaps mechanism provided by this module.
        Using hasCapability makes it easier to do something only if the server
        supports it or to put workaround code in the user of this class. The
        neededCaps mechanism makes it easier to put workaround code in this
        module, which makes sense if it is to be shared.

        'capability' should be a string such as 'registration.foobar'. It can
        be a capability in 'neededCaps' above or one that isn't there. 'version'
        can be a string (where isdigit() is True) or an int.

        NFrT)�str�isdigit�AssertionErrorrr,r5)r%Z
capabilityrrr
r
r�
hasCapability�s

zCapabilities.hasCapability)N)�__name__�
__module__�__qualname__r!r)r5r7r:r<r9rBr
r
r
rr9s	<r)Zup2date_clientrrr �ImportError�collections�gettextZtranslation�t�hasattrrr6r#rrr
r
r
r�<module>s(
__pycache__/pkgUtils.cpython-36.opt-1.pyc000064400000000415150516774040014154 0ustar003

c8h'�@s,ddlmZe�dkr ddlTnddlTdS)�)�getPlatformZdeb)�*N)Zup2date_client.pkgplatformrZup2date_client.debUtilsZup2date_client.rpmUtils�rr�/usr/lib/python3.6/pkgUtils.py�<module>s

__pycache__/clientCaps.cpython-36.opt-1.pyc000064400000003752150516774040014446 0ustar003

c8h��
@s�ddlZddlZddlmZyddlZWnek
rDddlZYnXGdd�dej�Ze�Zddd�Z	e	�dd	�Z
e
d
ddd��e
d
ddd��e
dddd��e
dddd��e
dddd��e
dddd��dS)�N)�parseCapc@s&eZdZdd�Zddd�Zdd�ZdS)	�ClientCapabilitiescCstjj|�|j�dS)N)�UserDict�__init__�populate)�self�r� /usr/lib/python3.6/clientCaps.pyrszClientCapabilities.__init__NcCs dddd�i}|r|}||_dS)NZcaneatCheese�)�version�value)�data)rZcapsToPopulateZ	localcapsrrr	rszClientCapabilities.populatecCsPg}xF|jj�D]8}d}d||j|d|j|df}|j||f�qW|S)NzX-RHN-Client-Capabilityz	%s(%s)=%srr)r
�keys�append)rZ
headerList�keyZ
headerNamerrrr	�headerFormatszClientCapabilities.headerFormat)N)�__name__�
__module__�__qualname__rrrrrrr	rs

r�/etc/sysconfig/rhn/clientCaps.dcCs�tjd|�}x�|D]~}tjj|�r&qtj|tj�s6qt|d�}xP|j�D]D}|j�}|sJ|ddkrjqJt	|�}x|D]\}}|t
j|<qxWqJWqWdS)Nz%s/*�rr�#)�glob�os�path�isdir�access�R_OK�open�	readlines�stripr�capsr
)ZcapsDirZ	capsFilesZcapsFile�fd�lineZcaplist�capr
rrr	�
loadLocalCaps*s

r%cCs|tj|<dS)N)r!r
)r$r
rrr	�registerCapCsr&zpackages.runTransaction�1)rrzpackages.rollBackzpackages.verifyzpackages.extended_profile�2z
reboot.rebootzpackages.update)r)rrZup2date_client.capabilitiesrr�ImportError�collectionsrr!r%r&rrrr	�<module>s"
__pycache__/rhnreg_constants.cpython-36.opt-1.pyc000064400000033300150516774040015732 0ustar003

c8h�H�@s�ddlmZmZddlZejddd�Zeed�s8eje_ejZed�Z	ed�Z
ed	�Zed
�Zed�Z
ed�Zed
�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Z ed�Z!ed �Z"ed!�Z#ed"�Z$ed#�Z%ed$�Z&ed%�Z'ed&�Z(ed'�Z)ed(�Z*ed)�Z+ed*�Z,ed+�Z-ed,�Z.ed-�Z/ed.�Z0ed/�Z1ed0�Z2ed1�Z3ed2�Z4ed3�Z5ed4�Z6ed5�Z7ed6�Z8ed7�Z9ed8�Z:ed9�Z;ed:�Z<ed;�Z=ed<�Z>ed=�Z?ed>�Z@ed?�ZAed@�ZBedA�ZCedB�ZDedC�ZEedD�ZFedE�ZGedF�eZHedG�ZIedH�ZJedI�ZKedJ�ZLedK�ZMedL�ZNedM�ZOedN�eZPedO�eZQedP�eefZRedQ�ZSedR�ZTedS�ZUedT�ZVeUdUeVdVZWedW�ZXedX�ZYedY�ZZedZ�Z[ed[�Z\ed\�Z]ed]�Z^ed^�Z_ed_�Z`ed`�Zaeda�Zbedb�Zcedc�Zdedd�Zeede�Zfedf�Zgedg�Zhedh�Ziedi�Zjedj�Zkedk�Zledl�Zmedm�Znedn�Zoedo�Zpedp�ZqdS)q�)�PM_PLUGIN_NAME�PM_NAMENzrhn-client-toolsT)Zfallback�ugettextu:Copyright © 2006--2014 Red Hat, Inc. All rights reserved.z"Enter your CloudLinux Network URL.z�Please enter the location of your CloudLinux Network server and of its SSL certificate. The SSL certificate is only required if you will be connecting over https (recommended).zSatellite URL:zSSL certificate:z%You must enter a valid Satellite URL.zNIf you are using https you must enter the location of a valid SSL certificate.z+Attempting to contact the Spacewalk server.zIWe are attempting to contact the CloudLinux Network Network server at %s.zA proxy was specified at %s.zSystem RegistrationaSThis assistant will guide you through connecting your system to CloudLinux Network to receive software updates, including security updates, to keep your system supported and compliant.  You will need the following at this time:

 * A network connection
 * Your CloudLinux Login & password
 * The location of a CloudLinux Network or Proxy

z Why Should I Connect to CLN? ...zWhy Registerz�Connecting your system to CloudLinux Network allows you to take full advantage of the benefits of a paid subscription, including:zSecurity & Updates:zDownloads & Upgrades:zSupport:zCompliance:zsReceive the latest software updates, including security updates, keeping this CloudLinux system updated and secure.zMDownload installation images for CloudLinux releases, including new releases.ztAccess to the technical support experts at CloudLinux for help with any issues you might encounter with this system.zsStay in compliance with your subscription agreement and manage subscriptions for systems connected to your account.zOTip: CloudLinux values your privacy: http://www.cloudlinux.com/company/privacy/z Take me back to the registrationzSoftware Update Not Set Upz�Are you sure you don't want to connect your system to CloudLinux Network? You'll miss out on the benefits of a CloudLinux subscription:
z~You will not be able to take advantage of these subscription privileges without connecting your system to CloudLinux Network.
z"Take me back to the setup process.zI'll register later.zCloudLinux AccountzDPlease enter your login information for the %s CloudLinux Network:

zCloudLinux Login:zLogin:z	Password:zYTip: Forgot your login or password?  Contact your Satellite's Organization Administrator.zPlease enter a desired login.z#Please enter and verify a password.z Operating System Release VersionzOperating System version:z Minor Release: zLimited Updates OnlyzAll available updatesz*Confirm operating system release selectionz]Your system will be subscribed to the base software channel to receive all available updates.zCreate Profile - Hardwarez�A Profile Name is a descriptive name that you choose to identify this System Profile on the CloudLinux Network web pages. Optionally, include a computer serial or identification number.zsAdditional hardware information including PCI devices, disk sizes and mount points will be included in the profile.z=Include the following information about hardware and network:zCreate Profile - PackageszeRPM information is important to determine what updated software packages are relevant to this system.zBInclude RPM packages installed on this system in my System Profilez>You may deselect individual packages by unchecking them below.zBuilding Package Listz*Email Address:zSystem Already RegisteredzDIt appears this system has already been set up for software updates:z(Are you sure you would like to continue?a�This system has already been registered using CloudLinux Subscription Management.

Your system is being registered again using CloudLinux Network or CloudLinux Network Proxy technology. CloudLinux recommends that customers only register once.

To learn more about RHN Classic/CloudLinux Network registration and technologies please consult this Knowledge Base Article: https://access.redhat.com/kb/docs/DOC-45563z.Send Profile Information to CloudLinux Networka
We are finished collecting information for the System Profile.

Press "Next" to send this System Profile to CloudLinux Network.  Click "Cancel" and no information will be sent.  You can run the registration program later by typing `rhn_register` at the command line.z%Sending Profile to CloudLinux NetworkzUpdates Configureda�You may now run '%s update' from this system's command line to get the latest software updates from CloudLinux Network. You will need to run this periodically to get the latest updates. Alternatively, you may configure this system for automatic software updates (also known as 'auto errata update') via the CloudLinux Network web interface.  (Instructions for this are in chapter 6 of the CLN Reference Guide, available from the 'Help' button in the main Red Hat Network Satellite web interface.)zReview Subscriptionz-Please review the subscription details below:zgThe installation number %s was activated during this system's initial connection to CloudLinux Network.zQSubscriptions have been activated for the following CloudLinux products/services:zSoftware Channel Subscriptions:zFThis system will receive updates from the following software channels:aJWarning: Only installed product listed above will receive updates and support. If you would like to receive updates for additional products, please login to your satellite web interface and subscribe this system to the appropriate software channels. See Kbase article for more details. (http://kbase.redhat.com/faq/docs/DOC-11313)zQWarning: %s is not present, could not enable it.
Automatic updates will not work.zNote: %s has been enabled.zbWarning: An error occurred during enabling %s.
%s is not enabled.
Automatic updates will not work.z�You were unable to be subscribed to the following software channels because there were insufficient subscriptions available in your account:a�This system was unable to subscribe to any software channels. Your system will not receive any software updates to keep it secure and supported. Contact your Satellite administrator about this problem. Once you make the appropriate active subscriptions available in your account, you may browse to this system's profile in the CLN web interface and subscribe this system to software channels via the software > software channels tab.zService Level:z�Depending on what CloudLinux Network modules are associated with a system, you'll enjoy different benefits. The following are the CloudLinux Network modules associated with this system:�
z
%sz�This system was unable to be associated with the following CLN module(s) because there were insufficient subscriptions available in your account:z�Management module: automatic updates, systems grouping, systems permissions, system package profiling, bare-metal provisioning, existing state provisioning, rollbacks, configuration managementz^Virtualization module: software updates for a limited number of virtual guests on this system.a�<b>Warning:</b> Any guest systems you create on this system and register to RHN will consume CloudLinux subscriptions beyond this host system's subscription. You will need to: (1) make a virtualization system entitlement available and (2) apply that system entitlement to this system in CLN's web interface if you do not want virtual guests of this system to consume additional subscriptions.a�This system was unable to be associated with any CLN service level modules. This system will not receive any software updates to keep it secure and supported. Contace your Satellite administrator about this problem. Once you make the appropriate active subscriptions available in your account, you may browse to this system's profile in the CLN web interface, delete the profile, and re-connect this system to CloudLinux Network.aJUniversal default activation key detected
A universal default activation key was detected in your account. This means that a set of properties (software channel subscriptions, package installations, system group memberships, etc.) for your system's connection to CloudLinux Network or CloudLinux Network Proxyhave been determined by the activation key rather than your installation number.  You may also refer to the RHN Reference Guide, section 6.4.6 for more details about activation keys (http://access.redhat.com/knowledge/docs/Red_Hat_Network/)
Universal Default activation key: %szFatal Error�WarningaXWe can't contact the CloudLinux Network.

Double check the location provided - is '%s' correct?
If not, you can correct it and try again.

Make sure that the network connection on this system is operational.

This system will not be able to successfully receive software updates from CloudLinux without connecting to a CloudLinux Network serverz0Architecture: %s, OS Release: %s, OS Version: %sz�This server doesn't support functionality needed by this version of the software update setup client. Please try again with a newer server.a�<b><span size="16000">Incompatible Certificate File</span></b>

The certificate you provided, <b>%s</b>, is not compatible with  the CloudLinux Network server at <b>%s</b>. You may want to double-check that you have provided a valid certificate file. Are you sure you have provided the correct certificate, and that the certificate file has not been corrupted?

Please try again with a different certificate file.z�<b><span size="12000">Incompatible Certificate File</span></b>

 The certificate is expired. Please ensure you have the correct  certificate and your system time is correct.aPlease verify the values of sslCACert and serverURL in /etc/sysconfig/rhn/up2date. You can either make the serverURL use http instead of https, or you can download the SSL cert from your Satellite, place it in /usr/share/rhn, and ensure sslCACert points to it.a�Problem registering system.

A universal default activation key limits the number of systems which can connect to the CLN organization associated with your login. To allow this system to connect, please contact your CLN organization administrator to increase the number of systems allowed to connect or to disable this universal default activation key. More details can be found in CloudLinux Knowledgebase Article #7924 at http://kbase.redhat.com/faq/FAQ_61_7924.shtm zI
 Tip: Minor releases with a '*' are currently supported by CloudLinux.

z�Warning:You will not be able to limit this system to minor release that is older than the recent minor release if you select this option.
z�Your system will be subscribed to %s 
base software channel. You will not be
able to move this system to an earlier release
(you will be able to move to a newer release).
Are you sure you would like to continue?�OK�ErrorZNextZBackZCancelz
No, Cancelz
Yes, Continuez%Press <space> to deselect the option.)rZup2date_client.pmPluginrr�gettextZtranslation�t�hasattrr�_ZCOPYRIGHT_TEXTZSATELLITE_URL_WINDOWZSATELLITE_URL_TEXTZSATELLITE_URL_PROMPTZSATELLITE_URL_PROMPT2ZSATELLITE_REQUIREDZSSL_REQUIREDZCONNECT_WINDOWZCONNECT_WINDOW_TEXTZCONNECT_WINDOW_TEXT2ZSTART_REGISTER_WINDOWZSTART_REGISTER_TEXTZWHY_REGISTERZWHY_REGISTER_WINDOWZWHY_REGISTER_TEXTZWHY_REGISTER_SECZWHY_REGISTER_DLDZWHY_REGISTER_SUPPZWHY_REGISTER_COMPZWHY_REGISTER_SEC_TXTZWHY_REGISTER_DLD_TXTZWHY_REGISTER_SUPP_TXTZWHY_REGISTER_COMP_TXTZWHY_REGISTER_TIPZ
BACK_REGISTERZCONFIRM_QUITZCONFIRM_QUIT_SUREZCONFIRM_QUIT_WILLNOTZCONTINUE_REGISTERINGZREGISTER_LATER2ZREGISTER_WINDOWZLOGIN_PROMPTZHOSTED_LOGINZLOGINZPASSWORDZ	LOGIN_TIPZ
USER_REQUIREDZPASSWORD_REQUIREDZSELECT_OSRELEASEZ
OS_VERSIONZ
MINOR_RELEASEZLIMITED_UPDATESZALL_UPDATESZCONFIRM_OS_RELEASE_SELECTIONZCONFIRM_OS_ALLZHARDWARE_WINDOWZHARDWARE_WINDOW_DESC1ZHARDWARE_WINDOW_DESC2ZHARDWARE_WINDOW_CHECKBOXZPACKAGES_WINDOWZPACKAGES_WINDOW_DESC1ZPACKAGES_WINDOW_DESC2ZPACKAGES_WINDOW_UNCHECKZPACKAGES_WINDOW_PKGLISTZEMAILZSYSTEM_ALREADY_SETUPZSYSTEM_ALREADY_REGISTEREDZSYSTEM_ALREADY_REGISTERED_CONTZRHSM_SYSTEM_ALREADY_REGISTEREDZSEND_WINDOWZSEND_WINDOW_DESCZSENDING_WINDOWZ
FINISH_WINDOWZFINISH_WINDOW_TEXT_TUIZ
REVIEW_WINDOWZREVIEW_WINDOW_PROMPTZSUB_NUMZSUB_NUM_RESULTZCHANNELS_TITLEZOK_CHANNELSZCHANNELS_SAT_WARNINGZPM_PLUGIN_WARNINGZPM_PLUGIN_CONF_CHANGEDZPM_PLUGIN_CONF_ERRORZFAILED_CHANNELSZNO_BASE_CHANNELZSLOTS_TITLEZOK_SLOTSZSLOTSZFAILED_SLOTSZ
MANAGEMENTZVIRTZVIRT_FAILEDZNO_SYS_ENTITLEMENTZACTIVATION_KEYZFATAL_ERRORZWARNINGZHOSTED_CONNECTION_ERRORZBASECHANNELERRORZSERVER_TOO_OLDZSSL_CERT_ERROR_MSGZSSL_CERT_EXPIREDZSSL_CERT_FILE_NOT_FOUND_ERRERZACT_KEY_USAGE_LIMIT_ERRORZCHANNEL_PAGE_TIPZCHANNEL_PAGE_WARNINGZCONFIRM_OS_WARNINGrZERRORZNEXTZBACKZCANCELZ	NO_CANCELZYES_CONTZDESELECT�r
r
�&/usr/lib/python3.6/rhnreg_constants.py�<module>
s�



	__pycache__/config.cpython-36.opt-1.pyc000064400000030767150516774040013634 0ustar003

c8h�9�@sndZddlZddlZddlZddlZddlmZmZddlm	Z	m
Z
yddlmZm
Z
Wn$ek
r|ddlmZm
Z
YnXddlZejddd�Zeed	�s�eje_ejZdEdFdGdHdIdJdKdLdMdNdOdPdQdRdd d!d"d#gfd$�Zd%d d&gZGd'd(�d(�ZGd)d*�d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�ZdSd6d7�ZdTd8d9�Z dUd:d;�Z!d<d=�Z"d>d?�Z#d@dA�Z$dVdCdD�Z%dS)Wzj
This module includes the Config and Up2date Config classes use by the
up2date agent to hold config info.
�N)�idn_ascii_to_puny�idn_puny_to_unicode)�ustr�sstr)�urlsplit�
urlunsplitzrhn-client-toolsT)Zfallback�ugettext�Use a HTTP Proxy�Remote server URL�)https://xmlrpc.cln.cloudlinux.com/XMLRPC/�&Remote server URL for access over IPv6�.https://ipv6.xmlrpc.cln.cloudlinux.com/XMLRPC/�Mirror list URL�>https://repo.cloudlinux.com/cloudlinux/mirrorlists/cln-mirrors�#Whether or not debugging is enabled�Location of system id�/etc/sysconfig/rhn/systemid�4Override the automatically determined system version��;HTTP proxy in host:port format, e.g. squid.example.com:3128�'The username for an authenticated proxy�.The password to use for an authenticated proxy�$To use an authenticated proxy or not�BNumber of attempts to make at network connections before giving up��)The CA cert used to verify the ssl server�'/usr/share/rhn/CLN-ORG-TRUSTED-SSL-CERT�Disable the reboot actionzDConfig options that can not be overwritten by a config update action�	sslCACert�	serverURL�disallowConfChanges�noReboot)ZenableProxyr�
serverURLipv6�	mirrorURL�debug�systemIdPathZversionOverride�	httpProxy�	proxyUser�
proxyPasswordZenableProxyAuthZnetworkRetriesrr!r r%ZtmpDirc@sleZdZdZddd�Zddd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)�
ConfigFilez;class for handling persistent config options for the clientNcCsi|_||_|jr|j�dS)N)�dict�fileName�load)�self�filename�r/�/usr/lib/python3.6/config.py�__init__CszConfigFile.__init__cCs�|r
||_|jdkrdStj|jtj�s,dSt|jd�}d}�x�|j�D�]�}|jd�dkr^qH||j�}|spqH|ddkr�|dd�j�}qHnd}|jdd�}t	|�dkr�qH|dj�}t
|dj��}d}|jd	�}	|	dkr�|d|	�}|}d}|�rx|jd
�}
|dk�r"t|jt
j���}nVt	|
�dk�rVyt|�}Wntk
�rRYnXn"|
ddk�rjg}nd
d�|
D�}||f}||jk�r�|j|}|dk	�r�||df}|dk	�r�|d|f}||j|<qHW|j�dS)N�rr�#rr�\�=�z	[comment]�;r'r(cSsg|]}|j�r|j��qSr/)�strip)�.0�valr/r/r0�
<listcomp>�sz#ConfigFile.load.<locals>.<listcomp>���r<r<)r'r()r+�os�access�R_OK�open�	readlines�findr8�split�lenrr�encode�locale�getpreferredencoding�int�
ValueErrorr*�close)r-r.�fZ	multiline�linerC�key�value�comment�pos�valuesZnewvalr/r/r0r,Isd






zConfigFile.loadc	CsJ|jdkrdStj|jtj�sTtjtjj|j�tj�sTttdtjj|j���dSt|jdd�}tj	|jdt
dd��|jd�|jd�|jd�x�|jj
�D]�}|j|\}}|jtd	||f��t|�tg�kr�|g}|tkr�ttjj|�}|jtd
|djtt|��f��|jd�q�W|j�tj|jd|j�dS)
Nz%s was not foundz.new�wZ0644�zI# Automatically generated Red Hat Update Agent config file, do not edit.
z# Format: 1.0
rz%s[comment]=%s
z%s=%s
r7�
)r+r=r>r?�path�dirname�print�_r@�chmodrH�writer*�keysr�type�FileOptions�map�abspath�join�strrJ�rename)r-rKrMrOrNr/r/r0�save�s,
	


"zConfigFile.savecCs
||jkS)N)r*)r-�namer/r/r0�__contains__�szConfigFile.__contains__cCs||kS)Nr/)r-rdr/r/r0�has_key�szConfigFile.has_keycCs
|jj�S)N)r*r[)r-r/r/r0r[�szConfigFile.keyscCsdd�|jj�D�S)NcSsg|]}|d�qS)rr/)r9�ar/r/r0r;�sz%ConfigFile.values.<locals>.<listcomp>)r*rQ)r-r/r/r0rQ�szConfigFile.valuescCs|jj|�dS)N)r*�update)r-r*r/r/r0rh�szConfigFile.updatecCs||jkr|j|dSdS)Nr)r*)r-rdr/r/r0�__getitem__�s
zConfigFile.__getitem__cCs0||jkr|j|}nd}|d|f|j|<dS)Nr)NN)r*)r-rdrNr:r/r/r0�__setitem__�s
zConfigFile.__setitem__cCs||jkr|j|dSdS)Nrr)r*)r-rdr/r/r0�info�s
zConfigFile.info)N)N)�__name__�
__module__�__qualname__�__doc__r1r,rcrerfr[rQrhrirjrkr/r/r/r0r)@s

H#r)c@sveZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�ZdS)�ConfigNcCs.t�|_|jjt�|r$|jj|�i|_dS)N)r)�storedrh�Defaultsr,�runtime)r-r.r/r/r0r1�s
zConfig.__init__cCs ||jkrdS||jkrdSdS)NTF)rsrq)r-rdr/r/r0re�s


zConfig.__contains__cCs||kS)Nr/)r-rdr/r/r0rf�szConfig.has_keycCs8t|jj��}x$|jj�D]}||kr|j|�qW|S)N)�listrsr[rq�append)r-�ret�kr/r/r0r[�s
zConfig.keyscCs*g}x |j�D]}|j|j|��qW|S)N)r[ruri)r-rvrwr/r/r0rQ�sz
Config.valuescCs.g}x$|j�D]}|j||j|�f�qW|S)N)r[ruri)r-rvrwr/r/r0�items�szConfig.itemscCst|j��S)N)rDr[)r-r/r/r0�__len__szConfig.__len__cCs||j|<dS)N)rs)r-rdrNr/r/r0rjszConfig.__setitem__cCs,||jkr|j|S||jkr(|j|SdS)N)rsrq)r-rdr/r/r0ri
s




zConfig.__getitem__cCs|jj|�S)N)rqrk)r-rdr/r/r0rkszConfig.infocCs|jj�dS)N)rqrc)r-r/r/r0rcszConfig.savecCs8|jj|�x&|jj�D]}||jkr(q|j|=qWdS)N)rqr,r[rs)r-r.rwr/r/r0r,s

zConfig.loadcCs ||j|<||jkr|j|=dS)N)rqrs)r-rdrNr/r/r0�set#s

z
Config.set)N)rlrmrnr1rerfr[rQrxryrjrirkrcr,rzr/r/r/r0rp�s
		
rpcCs^t�}d}|d}|rZ|dd�dkr2|dd�}|jd�}tt|d��|d<dj|�}|S)zkreturns proxy string in format hostname:port
    hostname is converted to Punycode (RFC3492) if needed
    Nr&�zhttp://�:r)�initUp2dateConfigrCrarr`)�cfg�proxyZ	proxyHost�partsr/r/r0�getProxySetting*s

r�cCs:t|�}tt|dtt|d��|d|d|df��S)z=returns url where hostname is converted to Punycode (RFC3492)rrr6��)rrrrr)�url�sr/r/r0�convert_url_to_puny<sr�cCs6t|�}tt|dt|d�|d|d|df��S)zXreturns url where hostname is converted from Punycode (RFC3492). Returns unicode string.rrr6r�r�)rrrr)r�r�r/r/r0�convert_url_from_punyBsr�c
Csvtd}|dkrd}|jd�rVt|jdd�d�� }ttj|j��}dd�|D�SQRXtj	|�}dd�|j
jd	�D�S)
Nr#z>https://repo.cloudlinux.com/cloudlinux/mirrorlists/cln-mirrorszfile://rr2cSsg|]}|rt|��qSr/)r�)r9�mirrorr/r/r0r;Osz+getServerlURLFromMirror.<locals>.<listcomp>cSsg|]}|rt|��qSr/)r�)r9r�r/r/r0r;QsrT)r~�
startswithr@�replacer^rar8rA�requests�get�textrC)r�Z
mirrorlistZmirrorsZrequestr/r/r0�getServerlURLFromMirrorHs

r�cCs&t|t�rdd�|D�St|�gSdS)z�
    Internal function to process server URL to Punycode format.

    Processes both single URLs and lists of URLs.

    :param serverUrl: URL or list of URLs to process.
    :return: List of processed URLs in Punycode format.
    cSsg|]}t|��qSr/)r�)r9�ir/r/r0r;^sz$processServerURL.<locals>.<listcomp>N)�
isinstancertr�)Z	serverUrlr/r/r0�processServerURLTs	
r�FcCs^t�}t|d�}t|d�}||f}||f}|r6|Sddlm}|j�}|dkrZ|rZ|S|S)a�
    Return a pair of server URLs (primary and fallback) based on the preferred interface.

    :param registration: If True, it indicates that the URLs are being fetched for registration purposes.
    If that is the case, the function will always use IPv4 URLs with IPv6 as fallback,
    regardless of the preferred_interface setting.
    Assumed false by default, expected to be specified explicitly when needed.

    :return: Pair of server URL configs, first is the primary, second is the fallback.
    rr"r)�up2dateAuthZIPv6)r}r�Zup2date_clientr�ZgetPreferredInterface)�registrationr~Zipv4_urlZipv6_urlZipv4_primary_pairZipv6_primary_pairr�Zpreferred_interfacer/r/r0�getServerURLPaircsr�cCst|d�dS)az
    Return the primary server URL from config based on preferred_interface.

    If preferred_interface=IPv6 in system_id, returns serverURLipv6 if available.
    Otherwise returns normal serverURL.
    Note: the config may have one value or a list of values, but this function always returns a list.

    :return: List of server URLs with hostnames converted to Punycode.
    )r�r)r�)r�r/r/r0�getServerURL�s
r�cCst|d�dS)z�
    Determine the fallback server URL from system_id.

    The fallback server URL is the one that is *not* set as preferred_interface.
    If preferred_interface is IPv6, it returns serverURL (i.e. IPv4 host), otherwise serverURLipv6.
    )r�r)r�)r�r/r/r0�getFallbackServerURL�sr�cCst�}|jd|�dS)zSet serverURL in configrN)r}rz)rr~r/r/r0�setServerURL�sr�cCst�}|jd|�dS)zSet serverURLipv6 in configr"N)r}rz)rr~r/r/r0�setServerURLipv6�sr�cCst�}|jd|�dS)zSet sslCACert in configrN)r}rz)rr~r/r/r0�setSSLCACert�sr��/etc/sysconfig/rhn/up2datecCsPytWntk
r daYnXtdkrLt|�adtd<tjj�rLdtd<tS)z<This function is the right way to get at the up2date config.NF�isattyT)r~�	NameErrorrp�sys�stdoutr�)Zcfg_filer/r/r0r}�s

r})r	r)r
r)rr
)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)F)F)F)r�)&ror=r�rFr�Zrhn.connectionsrrZrhn.i18nrrZurlparserr�ImportErrorZurllib.parse�gettextZtranslation�t�hasattrrrXrrr]r)rpr�r�r�r�r�r�r�r�r�r�r�r}r/r/r/r0�<module>sb
O
'


__pycache__/pkgUtils.cpython-36.pyc000064400000000415150516774040013215 0ustar003

c8h'�@s,ddlmZe�dkr ddlTnddlTdS)�)�getPlatformZdeb)�*N)Zup2date_client.pkgplatformrZup2date_client.debUtilsZup2date_client.rpmUtils�rr�/usr/lib/python3.6/pkgUtils.py�<module>s

__pycache__/rpmUtils.cpython-36.pyc000064400000006160150516774040013235 0ustar003

c8h��@s|ddlZddlZddlmZddlmZddlZejddd�Ze	ed�sPeje_
ej
Zdd	�Zd
d�Z
ddd
�Zdd�ZdS)�N)�sstr)�transactionzrhn-client-toolsT)Zfallback�ugettextcKsVtj�}|j�}x$|j�D]}|j|tj||�qWg}x|D]}|j|�q@W|S)z@ just cause this is such a potentially useful looking method... )r�initReadOnlyTransaction�dbMatch�keys�pattern�rpmZRPMMIRE_GLOB�append)�kwargs�_tsZmi�keywordZ
headerList�h�r�/usr/lib/python3.6/rpmUtils.py�installedHeaderByKeywords
rcCs~i}g}g}�xf|D�]\}|d|d|d|dd�}x.|j�D]"}||dks^||dkrB||=qBWtf|�}t|�dkr�|j|�x�|D]�}|d}	|	dkr�d}	|d	}
|
dkr�d}
|d
|d|d|	|
f}|d	dkr�d
|d|d|df}n d|d|d|d|df}d|}
tj|
�}|j�}|j�g}x|D]}|j|j���qHW|j||g�q�WqW||fS)zf given a list of package labels, run rpm -V on them
        and return a dict keyed off that data
    r���)�name�version�release�archN��epochrrrrz%s-%s-%sz%s-%s-%s.%sz/usr/bin/rpmverify -V %s)	rr�lenr
�os�popen�	readlines�close�strip)Zpackages�dataZmissing_packagesZretlist�package�keywords�keyZheaders�headerrrZpkgZpackageLabelZverifystring�fd�resZreslist�linerrr�verifyPackages*sH



 

r)c
Cs~g}|dkr|td��tj�}d}d}x"|j�D]}|dkr@P|d}q2W|}d}�x|j�D�]}|dkrpPt|d�|dt|d�t|d�|d	d
�}	|	ddkr�d|	d<nd|	d|	d<|r�|d
|	d
<|	d
r�t|	d
�|	d
<|j|	�nP|�r@|d
�rt|d
�|	d
<|d�r4t|d�|	d<|j|	�n
|j|	�|dk�r^|||�|d}q`W|jdd�d�|S)z| Return list of packages. Package is hash with keys name, epoch,
        version, release and optionaly arch and cookie
    Nz0Getting list of packages installed on the systemrrrrrr�installtime)rrrrr*rz%srZcookiecSs|d|d|d|dfS)Nrrrrr)�xrrr�<lambda>�sz)getInstalledPackageList.<locals>.<lambda>)r$)�_rrrrr
�sort)
ZmsgCallbackZprogressCallbackZgetArchZgetInfoZpkg_listr�countZtotalrr"rrr�getInstalledPackageListlsP








r0cCs2ytjtj�Wntk
r,td�YnXdS)zSet rpm's verbosity mode
    z4extra verbosity not supported in this version of rpmN)r	ZsetVerbosityZRPMLOG_DEBUG�AttributeError�printrrrr�setDebugVerbosity�sr3)NNNN)rr	Zrhn.i18nrZup2date_clientr�gettextZtranslation�t�hasattrrr-rr)r0r3rrrr�<module>s

B
9__pycache__/rhnHardware.cpython-36.opt-1.pyc000064400000000724150516774040014622 0ustar003

c8hH�@s0ddlmZddlmZddlmZdd�ZdS)�)�up2dateAuth)�	rpcServer)�hardwarecCs&tj�}tj�}|jjtj�|�dS)N)rZ	getServerrZHardwareZregistrationZrefresh_hw_profilerZgetSystemId)�sZhardwareList�r�!/usr/lib/python3.6/rhnHardware.py�updateHardwaresrN)Zup2date_clientrrrrrrrr�<module>s__pycache__/clpwd.cpython-36.pyc000064400000007626150516774040012537 0ustar003

c8h;�@s"ddlZddlZGdd�d�ZdS)�Nc@s�eZdZGdd�de�Zddd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zddd�ZdS)�ClPwdc@seZdZdd�ZdS)zClPwd.NoSuchUserExceptioncCstj|d|f�dS)NzNo such user (%s))�	Exception�__init__)�self�user�r�/usr/lib/python3.6/clpwd.pyrsz"ClPwd.NoSuchUserException.__init__N)�__name__�
__module__�__qualname__rrrrr�NoSuchUserExceptionsrNcCs8i|_i|_i|_i|_|dkr.|jd�|_n||_dS)Ni�)�
_user_key_map�_uid_key_map�_user_full_map�
_uid_full_map�get_sys_min_uid�_min_uid)rZmin_uidrrrr	szClPwd.__init__cCs|j�|jS)N)�_load_passwd_databaser
)rrrr�
get_user_dictszClPwd.get_user_dictcCs|j�|jS)N)rr)rrrr�get_uid_dictszClPwd.get_uid_dictcCs|j�|jS)N)rr)rrrr�get_user_full_dictszClPwd.get_user_full_dictcCs|j�|jS)N)rr)rrrr�get_uid_full_dictszClPwd.get_uid_full_dictcCs0y|j�|Stk
r*tj|��YnXdS)z*
        Return pw_entry for user
        N)r�KeyErrorrr)rrrrr�get_pw_by_name#szClPwd.get_pw_by_namecCs0y|j�|Stk
r*tj|��YnXdS)z7
        Return list of passwd entries for uid
        N)rrrr)r�uidrrr�
get_pw_by_uid,szClPwd.get_pw_by_uidcCs2y|j�|jStk
r,tj|��YnXdS)z&
        Returns uid for user
        N)r�pw_uidrrr)rrrrr�get_uid5sz
ClPwd.get_uidcCs2y|j�|jStk
r,tj|��YnXdS)z`
        Returns homedir for a user
        @param user: string
        @return: string
        N)r�pw_dirrrr)rrrrr�get_homedir>szClPwd.get_homedircCs�|js�x�tj�D]|}||j|j<|j|jkr8g|j|j<|j|jj|�|j|jkr||j|j<|j|j	krzg|j	|j<|j	|jj|�qWdS)zZ
        Loads the passwd database and fills user_to_uid and user_to_homedir maps
        N)
r�pwdZgetpwallr�pw_namer�appendrr
r)r�entryrrrrIszClPwd._load_passwd_databasecCs>y|j�|}Wntk
r.tj|��YnXdd�|D�S)zs
        Return names of users with uid specified
        @param uid: int
        @return: list of strings
        cSsg|]
}|j�qSr)r!)�.0r#rrr�
<listcomp>dsz#ClPwd.get_names.<locals>.<listcomp>)rrrr)rrZentriesrrr�	get_namesYs
zClPwd.get_names��cCsnd}tjj|�rjt|d��J}xB|D]:}|jd�r"yt|jd�dj��Stk
rZYq"Xq"WWdQRX|S)z�
        Return system defined MIN_UID from /etc/login.def or def_min_uid
        @param def_min_uid: int
        @return: MIN_UID: int
        z/etc/login.defs�rZUID_MIN�N)	�os�path�exists�open�
startswith�int�split�strip�
ValueError)rZdef_min_uidZLOGIN_DEF_FILE�lines�linerrrrgs

zClPwd.get_sys_min_uid)N)r')r	r
rrrrrrrrrrrrrr&rrrrrrs

			r)r r*rrrrr�<module>s__pycache__/pmPlugin.cpython-36.opt-1.pyc000064400000004714150516774040014153 0ustar003

c8h+�@s�ddlZddlZddlZyddlmZdZdZdZWn ek
rTdZdZdZYnXd	d
�Z	dd�Z
d
d�Zdd�Zdd�Z
dd�ZdS)�N)�__version__z/etc/dnf/plugins/spacewalk.confzdnf-plugin-spacewalk�dnfz$/etc/yum/pluginconf.d/rhnplugin.confzyum-rhn-pluginZyumcCsNd}d}t�r6d}t�r*t�s4t�d}qFt�d}ntjjd�rFd}||fS)z!Enables plugin, may throw IOErrorr�z(/usr/lib/zypp/plugins/services/spacewalk)�PluginPackagePresent�PluginConfPresent�
PluginEnabled�enablePlugin�createDefaultPluginConf�os�path�exists)Zconf_changedZplugin_present�r
�/usr/lib/python3.6/pmPlugin.py�pluginEnablesrcCstj�}|jdt�}|j�S)zO Returns positive number if plugin package is installed, otherwise it return 0 Zprovidename)�rpmZTransactionSetZdbMatch�PM_PLUGIN_NAME�count)ZtsZheadersr
r
rr%srcCs(ytjt�dStk
r"dSXdS)z- Returns true if PM_PLUGIN_CONF is presented TFN)r
�stat�PM_PLUGIN_CONF�OSErrorr
r
r
rr+s

rcCs ttd�}|jd�|j�dS)z1 Create file PM_PLUGIN_CONF, with default values �wz[main]
enabled = 1
gpgcheck = 1N)�openr�write�close)�fr
r
rr	3s
r	cCs�ttd�}|j�}|j�d}d}xZ|D]R}tjd|�rNtjd|�rJd}nd}|r(tjd|�}|r(t|jd��rvd}q(d}q(W|S)zM Returns True if plugin is enabled
        Can thrown IOError exception.
    �rFz^\[.*]z^\[main]Tz^\s*enabled\s*=\s*([0-9])r)rr�	readlinesr�re�match�int�group)r�lines�main_section�result�line�mr
r
rr;s"

rcCs�ttd�}|j�}|j�d}ttd�}xJ|D]B}tjd|�rTtjd|�rPd}nd}|rftjdd|�}|j|�q.W|j�d	S)
ze enable plugin by setting enabled=1 in file PM_PLUGIN_CONF
        Can thrown IOError exception.
    rFrz^\[.*]z^\[main]Tz^(\s*)enabled\s*=.+z
\1enabled = 1N)rrrrrr�subr)rr!r"r$r
r
rrSs


r)r
rrrrrrZPM_NAME�ImportErrorrrrr	rrr
r
r
r�<module>s"
__pycache__/config.cpython-36.pyc000064400000030767150516774040012675 0ustar003

c8h�9�@sndZddlZddlZddlZddlZddlmZmZddlm	Z	m
Z
yddlmZm
Z
Wn$ek
r|ddlmZm
Z
YnXddlZejddd�Zeed	�s�eje_ejZdEdFdGdHdIdJdKdLdMdNdOdPdQdRdd d!d"d#gfd$�Zd%d d&gZGd'd(�d(�ZGd)d*�d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�ZdSd6d7�ZdTd8d9�Z dUd:d;�Z!d<d=�Z"d>d?�Z#d@dA�Z$dVdCdD�Z%dS)Wzj
This module includes the Config and Up2date Config classes use by the
up2date agent to hold config info.
�N)�idn_ascii_to_puny�idn_puny_to_unicode)�ustr�sstr)�urlsplit�
urlunsplitzrhn-client-toolsT)Zfallback�ugettext�Use a HTTP Proxy�Remote server URL�)https://xmlrpc.cln.cloudlinux.com/XMLRPC/�&Remote server URL for access over IPv6�.https://ipv6.xmlrpc.cln.cloudlinux.com/XMLRPC/�Mirror list URL�>https://repo.cloudlinux.com/cloudlinux/mirrorlists/cln-mirrors�#Whether or not debugging is enabled�Location of system id�/etc/sysconfig/rhn/systemid�4Override the automatically determined system version��;HTTP proxy in host:port format, e.g. squid.example.com:3128�'The username for an authenticated proxy�.The password to use for an authenticated proxy�$To use an authenticated proxy or not�BNumber of attempts to make at network connections before giving up��)The CA cert used to verify the ssl server�'/usr/share/rhn/CLN-ORG-TRUSTED-SSL-CERT�Disable the reboot actionzDConfig options that can not be overwritten by a config update action�	sslCACert�	serverURL�disallowConfChanges�noReboot)ZenableProxyr�
serverURLipv6�	mirrorURL�debug�systemIdPathZversionOverride�	httpProxy�	proxyUser�
proxyPasswordZenableProxyAuthZnetworkRetriesrr!r r%ZtmpDirc@sleZdZdZddd�Zddd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)�
ConfigFilez;class for handling persistent config options for the clientNcCsi|_||_|jr|j�dS)N)�dict�fileName�load)�self�filename�r/�/usr/lib/python3.6/config.py�__init__CszConfigFile.__init__cCs�|r
||_|jdkrdStj|jtj�s,dSt|jd�}d}�x�|j�D�]�}|jd�dkr^qH||j�}|spqH|ddkr�|dd�j�}qHnd}|jdd�}t	|�dkr�qH|dj�}t
|dj��}d}|jd	�}	|	dkr�|d|	�}|}d}|�rx|jd
�}
|dk�r"t|jt
j���}nVt	|
�dk�rVyt|�}Wntk
�rRYnXn"|
ddk�rjg}nd
d�|
D�}||f}||jk�r�|j|}|dk	�r�||df}|dk	�r�|d|f}||j|<qHW|j�dS)N�rr�#rr�\�=�z	[comment]�;r'r(cSsg|]}|j�r|j��qSr/)�strip)�.0�valr/r/r0�
<listcomp>�sz#ConfigFile.load.<locals>.<listcomp>���r<r<)r'r()r+�os�access�R_OK�open�	readlines�findr8�split�lenrr�encode�locale�getpreferredencoding�int�
ValueErrorr*�close)r-r.�fZ	multiline�linerC�key�value�comment�pos�valuesZnewvalr/r/r0r,Isd






zConfigFile.loadc	CsJ|jdkrdStj|jtj�sTtjtjj|j�tj�sTttdtjj|j���dSt|jdd�}tj	|jdt
dd��|jd�|jd�|jd�x�|jj
�D]�}|j|\}}|jtd	||f��t|�tg�kr�|g}|tkr�ttjj|�}|jtd
|djtt|��f��|jd�q�W|j�tj|jd|j�dS)
Nz%s was not foundz.new�wZ0644�zI# Automatically generated Red Hat Update Agent config file, do not edit.
z# Format: 1.0
rz%s[comment]=%s
z%s=%s
r7�
)r+r=r>r?�path�dirname�print�_r@�chmodrH�writer*�keysr�type�FileOptions�map�abspath�join�strrJ�rename)r-rKrMrOrNr/r/r0�save�s,
	


"zConfigFile.savecCs
||jkS)N)r*)r-�namer/r/r0�__contains__�szConfigFile.__contains__cCs||kS)Nr/)r-rdr/r/r0�has_key�szConfigFile.has_keycCs
|jj�S)N)r*r[)r-r/r/r0r[�szConfigFile.keyscCsdd�|jj�D�S)NcSsg|]}|d�qS)rr/)r9�ar/r/r0r;�sz%ConfigFile.values.<locals>.<listcomp>)r*rQ)r-r/r/r0rQ�szConfigFile.valuescCs|jj|�dS)N)r*�update)r-r*r/r/r0rh�szConfigFile.updatecCs||jkr|j|dSdS)Nr)r*)r-rdr/r/r0�__getitem__�s
zConfigFile.__getitem__cCs0||jkr|j|}nd}|d|f|j|<dS)Nr)NN)r*)r-rdrNr:r/r/r0�__setitem__�s
zConfigFile.__setitem__cCs||jkr|j|dSdS)Nrr)r*)r-rdr/r/r0�info�s
zConfigFile.info)N)N)�__name__�
__module__�__qualname__�__doc__r1r,rcrerfr[rQrhrirjrkr/r/r/r0r)@s

H#r)c@sveZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�ZdS)�ConfigNcCs.t�|_|jjt�|r$|jj|�i|_dS)N)r)�storedrh�Defaultsr,�runtime)r-r.r/r/r0r1�s
zConfig.__init__cCs ||jkrdS||jkrdSdS)NTF)rsrq)r-rdr/r/r0re�s


zConfig.__contains__cCs||kS)Nr/)r-rdr/r/r0rf�szConfig.has_keycCs8t|jj��}x$|jj�D]}||kr|j|�qW|S)N)�listrsr[rq�append)r-�ret�kr/r/r0r[�s
zConfig.keyscCs*g}x |j�D]}|j|j|��qW|S)N)r[ruri)r-rvrwr/r/r0rQ�sz
Config.valuescCs.g}x$|j�D]}|j||j|�f�qW|S)N)r[ruri)r-rvrwr/r/r0�items�szConfig.itemscCst|j��S)N)rDr[)r-r/r/r0�__len__szConfig.__len__cCs||j|<dS)N)rs)r-rdrNr/r/r0rjszConfig.__setitem__cCs,||jkr|j|S||jkr(|j|SdS)N)rsrq)r-rdr/r/r0ri
s




zConfig.__getitem__cCs|jj|�S)N)rqrk)r-rdr/r/r0rkszConfig.infocCs|jj�dS)N)rqrc)r-r/r/r0rcszConfig.savecCs8|jj|�x&|jj�D]}||jkr(q|j|=qWdS)N)rqr,r[rs)r-r.rwr/r/r0r,s

zConfig.loadcCs ||j|<||jkr|j|=dS)N)rqrs)r-rdrNr/r/r0�set#s

z
Config.set)N)rlrmrnr1rerfr[rQrxryrjrirkrcr,rzr/r/r/r0rp�s
		
rpcCs^t�}d}|d}|rZ|dd�dkr2|dd�}|jd�}tt|d��|d<dj|�}|S)zkreturns proxy string in format hostname:port
    hostname is converted to Punycode (RFC3492) if needed
    Nr&�zhttp://�:r)�initUp2dateConfigrCrarr`)�cfg�proxyZ	proxyHost�partsr/r/r0�getProxySetting*s

r�cCs:t|�}tt|dtt|d��|d|d|df��S)z=returns url where hostname is converted to Punycode (RFC3492)rrr6��)rrrrr)�url�sr/r/r0�convert_url_to_puny<sr�cCs6t|�}tt|dt|d�|d|d|df��S)zXreturns url where hostname is converted from Punycode (RFC3492). Returns unicode string.rrr6r�r�)rrrr)r�r�r/r/r0�convert_url_from_punyBsr�c
Csvtd}|dkrd}|jd�rVt|jdd�d�� }ttj|j��}dd�|D�SQRXtj	|�}dd�|j
jd	�D�S)
Nr#z>https://repo.cloudlinux.com/cloudlinux/mirrorlists/cln-mirrorszfile://rr2cSsg|]}|rt|��qSr/)r�)r9�mirrorr/r/r0r;Osz+getServerlURLFromMirror.<locals>.<listcomp>cSsg|]}|rt|��qSr/)r�)r9r�r/r/r0r;QsrT)r~�
startswithr@�replacer^rar8rA�requests�get�textrC)r�Z
mirrorlistZmirrorsZrequestr/r/r0�getServerlURLFromMirrorHs

r�cCs&t|t�rdd�|D�St|�gSdS)z�
    Internal function to process server URL to Punycode format.

    Processes both single URLs and lists of URLs.

    :param serverUrl: URL or list of URLs to process.
    :return: List of processed URLs in Punycode format.
    cSsg|]}t|��qSr/)r�)r9�ir/r/r0r;^sz$processServerURL.<locals>.<listcomp>N)�
isinstancertr�)Z	serverUrlr/r/r0�processServerURLTs	
r�FcCs^t�}t|d�}t|d�}||f}||f}|r6|Sddlm}|j�}|dkrZ|rZ|S|S)a�
    Return a pair of server URLs (primary and fallback) based on the preferred interface.

    :param registration: If True, it indicates that the URLs are being fetched for registration purposes.
    If that is the case, the function will always use IPv4 URLs with IPv6 as fallback,
    regardless of the preferred_interface setting.
    Assumed false by default, expected to be specified explicitly when needed.

    :return: Pair of server URL configs, first is the primary, second is the fallback.
    rr"r)�up2dateAuthZIPv6)r}r�Zup2date_clientr�ZgetPreferredInterface)�registrationr~Zipv4_urlZipv6_urlZipv4_primary_pairZipv6_primary_pairr�Zpreferred_interfacer/r/r0�getServerURLPaircsr�cCst|d�dS)az
    Return the primary server URL from config based on preferred_interface.

    If preferred_interface=IPv6 in system_id, returns serverURLipv6 if available.
    Otherwise returns normal serverURL.
    Note: the config may have one value or a list of values, but this function always returns a list.

    :return: List of server URLs with hostnames converted to Punycode.
    )r�r)r�)r�r/r/r0�getServerURL�s
r�cCst|d�dS)z�
    Determine the fallback server URL from system_id.

    The fallback server URL is the one that is *not* set as preferred_interface.
    If preferred_interface is IPv6, it returns serverURL (i.e. IPv4 host), otherwise serverURLipv6.
    )r�r)r�)r�r/r/r0�getFallbackServerURL�sr�cCst�}|jd|�dS)zSet serverURL in configrN)r}rz)rr~r/r/r0�setServerURL�sr�cCst�}|jd|�dS)zSet serverURLipv6 in configr"N)r}rz)rr~r/r/r0�setServerURLipv6�sr�cCst�}|jd|�dS)zSet sslCACert in configrN)r}rz)rr~r/r/r0�setSSLCACert�sr��/etc/sysconfig/rhn/up2datecCsPytWntk
r daYnXtdkrLt|�adtd<tjj�rLdtd<tS)z<This function is the right way to get at the up2date config.NF�isattyT)r~�	NameErrorrp�sys�stdoutr�)Zcfg_filer/r/r0r}�s

r})r	r)r
r)rr
)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)F)F)F)r�)&ror=r�rFr�Zrhn.connectionsrrZrhn.i18nrrZurlparserr�ImportErrorZurllib.parse�gettextZtranslation�t�hasattrrrXrrr]r)rpr�r�r�r�r�r�r�r�r�r�r�r}r/r/r/r0�<module>sb
O
'


__pycache__/up2dateAuth.cpython-36.opt-1.pyc000064400000017574150516774040014556 0ustar003

c8h�*�@sDddlZddlZddlZddlZddlZddlZddlmZyddlm	Z	Wne
k
rdeZ	YnXddlm
Z
ddlmZddlmZddlmZddlmZdd	lmZdd
lmZdadZdd
�Zdd�Zdd�Zdd�Zdd�Zdd�Zd)dd�Zd*dd�Zd+dd�ZGdd �d e�Z d!d"�Z!d#d$�Z"d%d&�Z#d'd(�Z$dS),�N)�	rpcServer)�DictType)�rpclib)�
clientCaps)�config)�	rhnserver)�
up2dateErrors)�
up2dateLog)�up2dateUtilsz /var/spool/up2date/loginAuth.pklcCs@tj�}|d}tj|tj�s"dSt|d�}|j�}|j�|S)N�systemIdPath�r)r�initUp2dateConfig�os�access�R_OK�open�read�close)�cfg�path�f�ret�r�!/usr/lib/python3.6/up2dateAuth.py�getSystemIds
rcCs�tj�}t�}d}|dkr|SyDtjj|�dd}|jdd�}|dkrN|}n|jd||f�|Stk
r�|jd�|j	t
j��YnX|S)	z�
    Extract the preferred_interface parameter from system_id XML
    Returns 'IPv4' or 'IPv6' if specified, otherwise 'IPv4' as default
    �IPv4Nr�preferred_interface�IPv6zGInvalid preferred_interface value '%s' in system_id, defaulting to '%s'zGFailed to parse system_id XML, preferred_interface defaulting to 'IPv4')rr)r	�initLogrr�	xmlrpclib�loads�get�log_me�	Exception�
log_exception�sys�exc_info)�log�systemIdrZparamsZ
cfg_interfacerrr�getPreferredInterface(s$
r)c	CsBtjjd�rdStj�}ytjjt��ddd}Wn
dSt	j
�}|doZ||k�r>tj�}|j
jt�|�}|d}|d|jd��}tj|tj�s�ytj|�Wn
dStj|tj�s�dStj|tj��r�|d}ytj||�Wn
dSt|d�}|j|�|j�ytj|td	d
��WnYnXdS)NZLEAPP_IPU_IN_PROGRESSrZ
os_releaseZchannelOverrider�/z.save�w�0600�)r�environr!rr
rrr rr
Z
getVersionrZRegistrationRhnServerZregistrationZupgrade_version�rfindr�W_OK�mkdir�F_OK�renamer�writer�chmod�int)	r�idVerZ	systemVer�sZnewSystemIdr�dirZsavePathrrrr�maybeUpdateVersionLsB

r:cCs�tj�}|jd�ts$|jd�dStj�td�}tjjt�}tj	|tj
�s�y tj|�tj|t
dd��Wn|jd|�dSttd�}tjtt
d	d��tj||�|j�|d
ttd�}|jd|d
d
|d�dS)z�
    Pickle loginInfo to a file
    Returns:
    True    -- wrote loginInfo to a pickle file
    False   -- did _not_ write loginInfo to a pickle file
    zwriteCachedLogin() invokedz1writeCachedLogin() loginInfo is None, so bailing.F)�time�	loginInfoZ0700r-z'Unable to write pickled loginInfo to %s�wbr,r;zX-RHN-Auth-Expire-OffsetzWrote pickled loginInfo at z with expiration of z	 seconds.T)r	r�	log_debugr<r;rr�dirname�pcklAuthFileNamerr0r1r5r6r"r�pickle�dumpr�float)r'�dataZpcklDir�pcklAuth�
expireTimerrr�writeCachedLoginzs.



rGc	CsTtj�}|jd�tjttj�s2|jdt�dSttd�}ytj	|�}Wn*t
tfk
rt|jd�|j�dSX|j�yLt
jjt��ddd}d|d	d
}||kr�|jd||f�dSWnYnX|d}|d	}tj�}|t|d
�}|jd|d|dt|d
��||k�r<|jd||f�dSt|�|jd|�dS)zb
    Read pickle info from a file
    Caches authorization info for connecting to the server.
    zreadCachedLogin invokedz'Unable to read pickled loginInfo at: %sF�rbzSUnexpected EOF. Probably an empty file,                        regenerate auth filerZ	system_idzID-%sr<zX-RHN-Server-Idz#system id version changed: %s vs %sr;zX-RHN-Auth-Expire-Offsetz(Checking pickled loginInfo, currentTime=z
, createTime=z, expire-offset=z9Pickled loginInfo has expired, created = %s, expire = %s.z<readCachedLogin(): using pickled loginInfo set to expire at T)r	rr>rrr@rrrA�load�EOFError�
ValueErrorrrrr rr;rC�_updateLoginInfo)	r'rErDr7ZcidVerZcreatedTime�liZcurrentTimerFrrr�readCachedLogin�sH


rNcCs2t|�tkr*tt�tkr$tj|�q.|andadS)z,
    Update the global var, "loginInfo"
    N)�typerr<�update)rMrrrrL�s
rLFc	Cs�tj�}|jd|�|r,tr,t�r,tStj|d�}tjj	�}x|D]\}}|j
||�qHW|dkrnt�}|svdSt�|j
d�|jj|tj�t|��}|jj�t|�t�tr�|j
d�|jdt�tS)Nzlogin(forceUpdate=%s) invoked)�timeoutzlogging into up2date serverz?successfully retrieved authentication token from up2date serverz
logininfo:)r	rr>r<rNrZ	RhnServerrZcapsZheaderFormatZ
add_headerrr:r"Zup2date�login�socketZgetfqdn�_get_panel_nameZcapabilitiesZvalidaterLrG)	r(�forceUpdaterQr'ZserverZ
headerlistZ
headerName�valuerMrrrrR�s.



rRcCs0tj�}|jd�td|d�ts,tjd��tS)NzupdateLoginInfo() login infoT)rUrQzUnable to authenticate)r	rr"rRr<rZAuthenticationError)rQr'rrr�updateLoginInfo�s

rWcCs8ytaWntk
r daYnXtr*tSt|d�tS)N)rQ)r<�	NameErrorrR)rQrrr�getLoginInfos

rYc@seZdZdS)�_FailedToGetPanelNameN)�__name__�
__module__�__qualname__rrrrrZsrZcCsLy
t�}Wn8tk
rBt�s8|jtj��|jd�t�}YnX|j�S)Nz?Failed to get panel name via cldetect, using fallback mechanism)	�_get_panel_name_via_cldetectrZ�_is_cldeploy_runningr$r%r&r"�_fallback_get_panel_name�lower)r'Z
panel_namerrrrTs

rTcCstd}d}d}tjj|�r8t|��}|j�j�}WdQRX|rpd|}tjj|�rpt|��}d|j�k}WdQRX|S)Nz/var/lock/cldeploy.lckFz/proc/%s/cmdlineZcldeploy)rr�existsrr�strip)Zlock_file_pathZcldeploy_running�pidrZpid_cmdline_pathrrrr_$s

r_cCsrddg\}}}tjj|�s(td|��tj|tjtjdd�}|j�\}}|jdkrjtddj	|�|f��|j
�S)	Nz/usr/bin/cldetectz--detect-cp-nameonlyz7Failed to obtain panel name because '%s' does not existT)�stdout�stderrZuniversal_newlinesrz:Failed to obtain panel name using '%s' command; stderr: %s� )rrrbrZ�
subprocess�Popen�PIPEZcommunicate�
returncode�joinrc)Zbinary�_�cmdZprocessrerfrrrr^5s
r^cCsdtjjd�rdStjjd�r dStjjd�r0dStjjd�r@dStjjd	�rPd
Stjjd�r`dSd
S)Nz/usr/local/psa/admin/Zpleskz/usr/local/interworx/Z	interworxz#/usr/local/cpanel/whostmgr/docroot/Zcpanelz/usr/local/ispmgr/Zispmgrz/usr/local/directadmin/Zdirectadminz/usr/local/mgr5/sbin/mgrctlZispmgr5�unknown)rr�isdir�isfilerrrrr`Hsr`)NFN)N)N)%rrAr%r;rSrhZup2date_clientr�typesr�ImportError�dictZrhnrrrrrr	r
r<r@rr)r:rGrNrLrRrWrYr#rZrTr_r^r`rrrr�<module>sB

$. ,
%




__pycache__/rpmUtils.cpython-36.opt-1.pyc000064400000006160150516774040014174 0ustar003

c8h��@s|ddlZddlZddlmZddlmZddlZejddd�Ze	ed�sPeje_
ej
Zdd	�Zd
d�Z
ddd
�Zdd�ZdS)�N)�sstr)�transactionzrhn-client-toolsT)Zfallback�ugettextcKsVtj�}|j�}x$|j�D]}|j|tj||�qWg}x|D]}|j|�q@W|S)z@ just cause this is such a potentially useful looking method... )r�initReadOnlyTransaction�dbMatch�keys�pattern�rpmZRPMMIRE_GLOB�append)�kwargs�_tsZmi�keywordZ
headerList�h�r�/usr/lib/python3.6/rpmUtils.py�installedHeaderByKeywords
rcCs~i}g}g}�xf|D�]\}|d|d|d|dd�}x.|j�D]"}||dks^||dkrB||=qBWtf|�}t|�dkr�|j|�x�|D]�}|d}	|	dkr�d}	|d	}
|
dkr�d}
|d
|d|d|	|
f}|d	dkr�d
|d|d|df}n d|d|d|d|df}d|}
tj|
�}|j�}|j�g}x|D]}|j|j���qHW|j||g�q�WqW||fS)zf given a list of package labels, run rpm -V on them
        and return a dict keyed off that data
    r���)�name�version�release�archN��epochrrrrz%s-%s-%sz%s-%s-%s.%sz/usr/bin/rpmverify -V %s)	rr�lenr
�os�popen�	readlines�close�strip)Zpackages�dataZmissing_packagesZretlist�package�keywords�keyZheaders�headerrrZpkgZpackageLabelZverifystring�fd�resZreslist�linerrr�verifyPackages*sH



 

r)c
Cs~g}|dkr|td��tj�}d}d}x"|j�D]}|dkr@P|d}q2W|}d}�x|j�D�]}|dkrpPt|d�|dt|d�t|d�|d	d
�}	|	ddkr�d|	d<nd|	d|	d<|r�|d
|	d
<|	d
r�t|	d
�|	d
<|j|	�nP|�r@|d
�rt|d
�|	d
<|d�r4t|d�|	d<|j|	�n
|j|	�|dk�r^|||�|d}q`W|jdd�d�|S)z| Return list of packages. Package is hash with keys name, epoch,
        version, release and optionaly arch and cookie
    Nz0Getting list of packages installed on the systemrrrrrr�installtime)rrrrr*rz%srZcookiecSs|d|d|d|dfS)Nrrrrr)�xrrr�<lambda>�sz)getInstalledPackageList.<locals>.<lambda>)r$)�_rrrrr
�sort)
ZmsgCallbackZprogressCallbackZgetArchZgetInfoZpkg_listr�countZtotalrr"rrr�getInstalledPackageListlsP








r0cCs2ytjtj�Wntk
r,td�YnXdS)zSet rpm's verbosity mode
    z4extra verbosity not supported in this version of rpmN)r	ZsetVerbosityZRPMLOG_DEBUG�AttributeError�printrrrr�setDebugVerbosity�sr3)NNNN)rr	Zrhn.i18nrZup2date_clientr�gettextZtranslation�t�hasattrrr-rr)r0r3rrrr�<module>s

B
9__pycache__/clientCaps.cpython-36.pyc000064400000003752150516774040013507 0ustar003

c8h��
@s�ddlZddlZddlmZyddlZWnek
rDddlZYnXGdd�dej�Ze�Zddd�Z	e	�dd	�Z
e
d
ddd��e
d
ddd��e
dddd��e
dddd��e
dddd��e
dddd��dS)�N)�parseCapc@s&eZdZdd�Zddd�Zdd�ZdS)	�ClientCapabilitiescCstjj|�|j�dS)N)�UserDict�__init__�populate)�self�r� /usr/lib/python3.6/clientCaps.pyrszClientCapabilities.__init__NcCs dddd�i}|r|}||_dS)NZcaneatCheese�)�version�value)�data)rZcapsToPopulateZ	localcapsrrr	rszClientCapabilities.populatecCsPg}xF|jj�D]8}d}d||j|d|j|df}|j||f�qW|S)NzX-RHN-Client-Capabilityz	%s(%s)=%srr)r
�keys�append)rZ
headerList�keyZ
headerNamerrrr	�headerFormatszClientCapabilities.headerFormat)N)�__name__�
__module__�__qualname__rrrrrrr	rs

r�/etc/sysconfig/rhn/clientCaps.dcCs�tjd|�}x�|D]~}tjj|�r&qtj|tj�s6qt|d�}xP|j�D]D}|j�}|sJ|ddkrjqJt	|�}x|D]\}}|t
j|<qxWqJWqWdS)Nz%s/*�rr�#)�glob�os�path�isdir�access�R_OK�open�	readlines�stripr�capsr
)ZcapsDirZ	capsFilesZcapsFile�fd�lineZcaplist�capr
rrr	�
loadLocalCaps*s

r%cCs|tj|<dS)N)r!r
)r$r
rrr	�registerCapCsr&zpackages.runTransaction�1)rrzpackages.rollBackzpackages.verifyzpackages.extended_profile�2z
reboot.rebootzpackages.update)r)rrZup2date_client.capabilitiesrr�ImportError�collectionsrr!r%r&rrrr	�<module>s"
__pycache__/rpcServer.cpython-36.pyc000064400000016762150516774040013402 0ustar003

c8h�.�@sPddlZddlZddlZddlZddlmZddlmZddlmZddlmZddlm	Z	ddl
mZddl
mZdd	l
mZy$ddlZddlZddlZddlZWn<ek
r�ddljZddljZddljZddljZYnXddlZejd
dd�Zeed
��seje_ejZ dd�Z!Gdd�dej"�Z#Gdd�d�Z$ddd�Z%dd�Z&dS)�N)�config)�
clientCaps)�
up2dateLog)�
up2dateErrors)�up2dateUtils)�SSL)�rpclib)�
raise_with_tbzrhn-client-toolsT)Zfallback�ugettextcCst|�dS)N)�print)�msg�r
�/usr/lib/python3.6/rpcServer.py�stdoutMsgCallback&src@s(eZdZiZdd�Zdd�Zdd�ZdS)�RetryServercCs
||_dS)N)�
serverList)�selfrr
r
r�
addServerList.szRetryServer.addServerListc
Cs�tj�|_�x�y|j||�}W�n�tjk
r:�Y�n�tjk
rR�Y�nntj	k
r�|jj
d�ttd��t
jd�Y�n6|jj�}|dkr�|jj�|jr�djdd�|jj�D��}ttd��t|��d|j}dt
j�d	t
j�df}||j|j<||}|d
|jj�}|jj
|�tj|jj��}|d	}	|d|_|d|_|	j�}	|	dk�r�ttjd|	��|j|_|	|_|jj�|_|j�s�d|_d|_ wYnXPqW|S)Nz,Error: Server Unavailable. Please try later.��
cSsg|]\}}d||f�qS)z%s:
%sr
)�.0�host�errorr
r
r�
<listcomp>Lsz)RetryServer._request1.<locals>.<listcomp>z>Errors occurred while trying to connect to the remote servers.z!An error occurred talking to %s:
z%s
%s
rzTrying the next serverURL: %s
��http�httpsz%Redirected to unsupported protocol %sz/RPC2���)rr)!r�initLog�logZ_requestrZInvalidRedirectionError�	xmlrpclibZFault�httplibZ
BadStatusLine�log_mer�_�sys�exitr�next�resetServerIndex�_error_messages�join�itemsZ_host�exc_info�server�urlparseZurlsplitZ_handler�lowerr	Z
_orig_handlerZ_typeZ_uriZ_allow_redirect)
rZ
methodnameZparams�retr,Zerror_combined_msgrZ
exception_msgZ	parse_res�typr
r
r�	_request11sX






zRetryServer._request1cCstjj|j|�S)N)rr Z_Methodr1)r�namer
r
r�__getattr__sszRetryServer.__getattr__N)�__name__�
__module__�__qualname__r(rr1r3r
r
r
rr*sBrc@s0eZdZgfdd�Zdd�Zdd�Zdd�Zd	S)
�
ServerListcCs||_d|_dS)Nr)r�index)rZ
serverlistr
r
r�__init__zszServerList.__init__cCs|j|j|_|jS)N)rr8Z	serverurl)rr
r
rr,~szServerList.servercCs(|jd|_|jt|j�kr dS|j�S)Nr)r8�lenrr,)rr
r
rr&�szServerList.nextcCs
d|_dS)Nr)r8)rr
r
rr'�szServerList.resetServerIndexN)r4r5r6r9r,r&r'r
r
r
rr7ysr7FcCs�tj�}tj�}|d}t|t�s(|g}|p0dg}|drDtj�}nd}|s�tj|d�}	tj|d�}
|
r�x$|
D]}||	krn|	j	|�qnWn|}	t
|	�}d}
d}|dr�|dp�d}
|dp�d}d}xFdD]>}|tjkr�tj|s�q�tj|j
d�d
}|j
d�d
}Pq�Wt|j�|||
||d�}|j|�|jdtj��|�rL|j|�dd�|jjD�}|�r�xP|D]H}tj|tj��s�dtd�|f}|jd|�tj|��|j|��qjWtj�tjj �}x|D]\}}|j||��q�W|S)NZ	sslCACertz'/usr/share/rhn/CLN-ORG-TRUSTED-SSL-CERTZenableProxy)�registrationZenableProxyAuth�	proxyUser�
proxyPassword�LANGUAGE�LC_ALL�LC_MESSAGES�LANG�:r�.)�refreshCallback�proxyZusernameZpassword�timeoutzX-Up2date-VersioncSs"g|]}tj|�ddkrd�qS)rrT)r-)r�ir
r
rr�szgetServer.<locals>.<listcomp>z%s: %sz ERROR: can not find RHNS CA filez%s)r>r?r@rA)!rrr�initUp2dateConfig�
isinstance�listZgetProxySettingZgetServerURLZgetFallbackServerURL�appendr7�os�environ�splitrr,rZ
add_headerr�versionZsetlangr�access�R_OKr#r"rZSSLCertificateFileNotFoundZadd_trusted_certrZ
loadLocalCapsZcapsZheaderFormat)rDZserverOverriderFr;r�cfgZcaZ
rhns_ca_certsZ	proxyHostZ
serverUrlsZfallbackURL�urlrr<r=Zlang�env�sZneed_caZrhns_ca_certrZ
headerlistZ
headerName�valuer
r
r�	getServer�sn











rWcOs�tj�}|jd|jd�tj�}d}d}yt|d�}Wntk
rTd}YnX|dkrbd}�xPd}d}y|||�}W�n�tk
r�t	t
jtd���Y�n�t
jtjfk
�r4|jdtj�d|f�||k�r*tj�d}	t|	j�dk�rt	t
j|	jd��nt	t
j|	jd��nd}Y�nBtjk
�rbtd�t	t
jd��Y�ntjk
�r�tj�d}	d	}
|
d
|	j}
|
d|	j}
|
d|	j}
|j|
�t	t
j|
��Y�n�tjk
�rPtj�d}	|jd
|	j |f�|	j!dk�r$|jd|	j"�|jd�t#j$|	j%�\}}d}
t&|�dk�rh|jd|�ddl'm(}|j)�t&|�dk�r�|jtd��t	t
j|	j ��t&|�dk�r&t*|d�t*g�k�r�|d}n|d}t*|�t*g�k�r�d|d|d|d|df}n|}d||f}
|j|
�t	t
j+|
��|
�sL||k�rHt	t
j|	j ��nd}Yn&tj,k
�rtt	t
jd��YnX|dk�r�Pnd}|�r�t-j.d�|d}||krft
jd��qfW|S)NzrpcServer: Calling XMLRPC %sZ
_Method__namerZnetworkRetriesrzConnection aborted by the userz(A socket error occurred: %s, attempt #%szhttplib.IncompleteReadz
An HTTP error occurred:
zURL: %s
zStatus Code: %s
zError Message: %s
z,A protocol error occurred: %s , attempt #%s,i�zCould not find URL, %sz)Check server name and/or URL, then retry
�"z'Auth token timeout occurred
 errmsg: %s)�up2dateAuth�3z.Server has refused connection due to high load�z%s-%s-%s.%sr�zFile Not Found: %s
%sz Broken response from the server.�z0The data returned from the server was incomplete)/rrZ	log_debug�__dict__rrH�int�
ValueError�KeyboardInterruptr	rZCommunicationErrorr#�socketrrZsocket_errorr"r$r+r:�argsr!ZIncompleteReadr�urllib2Z	HTTPError�filename�coderr Z
ProtocolError�errmsgZerrcoderSrZreportErrorZheaders�abs�up2date_clientrYZupdateLoginInfo�type�FileNotFoundErrorZ
ResponseError�timeZsleep)�methodrc�kwargsrrRr/Z
attempt_countZattemptsZfailure�erZerrCodeZerrMsg�resetrYZpkgZpkgNamer
r
r�doCall�s�





"



rq)NNNF)'rLr$rbrlrirrrrrZrhnrrZrhn.tbr	r!rdr-r �ImportErrorZhttp.clientZclientZurllib.requestZrequestZurllib.parse�parseZ
xmlrpc.client�gettextZtranslation�t�hasattrr
r#rZServerrr7rWrqr
r
r
r�<module>sD


O
T__pycache__/up2dateLog.cpython-36.opt-1.pyc000064400000004755150516774040014373 0ustar003

c8h<�@sFddlZddlZddlmZmZddlmZGdd�d�Zdd�ZdS)�N)�ustr�sstr)�configc@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)�Logz�
    attempt to log all interesting stuff, namely, anything that hits
    the network any error messages, package installs, etc
    cCsd|_tj�|_d|_dS)NZup2date�)�apprZinitUp2dateConfig�cfg�log_info)�self�r� /usr/lib/python3.6/up2dateLog.py�__init__
s
zLog.__init__cCst|�|_dS)N)�strr)r
�namerrr�set_app_nameszLog.set_app_namecGs |jddkr|jd|��dS)N�debug��D: )r)r�log_me)r
�argsrrr�	log_debugsz
Log.log_debugcGsddtjtj��|jf|_d}x |D]}tt|��}||7}q$W|jddkrVt|�|j|�dS)zHGeneral logging function.
        Eg: log_me("I am a banana.")

        z[%s] %srrrN)	�time�ctimerr	rrr�print�	write_log)r
r�s�irrrrs
z
Log.log_mecCs@dtjtj��|jf|_tj�}djtj|��}|j|�dS)Nz[%s] %sr)	rrrr	�	traceback�
extract_stack�join�format_listr)r
�x�msgrrr�trace_me)szLog.trace_mecCsddtjtj��|jf|_dg}|jd�|tjtj|��}|jd||f�|jdj	|��dS)Nz[%s] %s�
z#Traceback (most recent call last):
z%s: %s
r)
rrrr	�appendrr �
extract_tbrr)r
Zlogtype�value�tb�outputrrr�
log_exception/s
zLog.log_exceptioncCsP|jdpd}t|d�}dt|j�t|�f}|jt|��|j�|j�dS)NZlogFilez/var/log/up2date�az%s %s
)r�openrr	�writer�flush�close)r
rZlog_nameZlog_filer"rrrr7s
z
Log.write_logN)�__name__�
__module__�__qualname__�__doc__r
rrrr#r*rrrrrrsrcCs4ytaWntk
r daYnXtdkr0t�atS)N)�log�	NameErrorrrrrr�initLog@s
r6)	rrZrhn.i18nrrZup2date_clientrrr6rrrr�<module>s
8__pycache__/transaction.cpython-36.pyc000064400000005135150516774040013744 0ustar003

c8ha�@s8ddlZdadZGdd�d�ZGdd�d�Zdd�ZdS)�Nc@seZdZdd�Zdd�ZdS)�TransactionDatacCs2i|_g|jd<g|jd<g|jd<g|jd<dS)N�packages�flagsZvsflagsZprobFilterFlags)�data)�self�r�!/usr/lib/python3.6/transaction.py�__init__!s



zTransactionData.__init__c	CsFd}g}g}g}g}x\|jdD]N\}}|dkr<|j|�q |dkrP|j|�q |dkrd|j|�q |j|�q Wx0|D](}|d|d|d|d	|d
f}qxWx0|D](}|d|d|d|d	|d
f}q�Wx0|D](}|d|d|d|d	|d
f}q�Wx8|D]0}|d
|d|d|d|d	|d
f}�qW|S)N�r�u�i�ez		[e] %s-%s-%s:%s
r���z		[i] %s-%s-%s:%s
z		[u] %s-%s-%s:%s
z		[%s] %s-%s-%s:%s
�)r�append)r�outZremovedZ	installed�updatedZmiscZpkgInfo�moderrr�display/s.
(
(
(
zTransactionData.displayN)�__name__�
__module__�__qualname__r	rrrrrrsrc@s4eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZdS)�Up2dateTransactioncCs:tj�|_ddddddddd	d
ddd
dddg|_g|_dS)NZdbMatchZcheck�orderZaddEraseZ
addInstallZrunZIDTXloadZIDTXglobZrollbackZpgpImportPubkeyZ
pgpPrtPktsZDebugZsetFlags�
setVSFlagsZ
setProbFilterZhdrFromFdno)�rpmZTransactionSet�ts�_methods�tsflags)rrrrr	Ms$
zUp2dateTransaction.__init__cCs ||jkr|j|�St|��dS)N)r�	getMethod�AttributeError)r�attrrrr�__getattr__as

zUp2dateTransaction.__getattr__cCst|j|�S)N)�getattrr)r�methodrrrr!gszUp2dateTransaction.getMethodcCs"|jj|�|jj|jd�dS)Nr���)r rrr)rrrrr�pushVSFlagsoszUp2dateTransaction.pushVSFlagscCs|jd=|jj|jd�dS)Nrr'r')r rr)rrrr�
popVSFlagssszUp2dateTransaction.popVSFlagsN)rrrr	r$r!r(r)rrrrrLs
rcCstdkrt�atjd�tS)Nrr')�read_tsrr(rrrr�initReadOnlyTransactionws
r+)rr*rrrr+rrrr�<module>
s
.+__pycache__/rhncli.cpython-36.opt-1.pyc000064400000016256150516774040013643 0ustar003

c8hw$�@svddlZddlZddlZddlmZddlmZddlmZddlmZddl	m
Z
ddlmZyddl
Z
Wnek
r�ddljZ
YnXddlZejdd	d
�Zeed�s�eje_ejZddlmZdd
lmZddlmZddlmZddlmZddlmZedddded�d�edded�d�edded�d�edded�d�edd ed!�d�gZGd"d#�d#e�Z d$d%�Z!dS)&�N)�Option)�OptionParser)�SSL)�crypto)�rpclib)�sstrzrhn-client-toolsT)Zfallback�ugettext)�config)�up2dateAuth)�
up2dateErrors)�
up2dateLog)�up2dateUtils)�pkgUtilsz-vz	--verbose�countzShow additional output)�action�default�helpz--proxyZstorezSpecify an http proxy to use)rrz--proxyUserz:Specify a username to use with an authenticated http proxyz--proxyPasswordz:Specify a password to use with an authenticated http proxyz--debug�
store_truez&Enable debug output (network requests)c@steZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Ze
dd��Ze
dd��ZdS)�RhnClicCs(tttj�d�|_d|_d|_d|_dS)N)Zoption_list�versionF)r�
_optionsTabler�_RhnCli__versionString�	optparser�options�args�hasGui)�self�r�/usr/lib/python3.6/rhncli.py�__init__Qs
zRhnCli.__init__cCs�tt_y |j�tj|j�pd�W�n�tk
rZtjjt	t
d���tjd�Y�n�tk
r�tjjt	t
d�tj�d��tjd�Y�nRt
jk
�rtj�d}|dks�tt|��dkr�tjjt	t
d���ntjjt	t
d�|��Y�n�tk
�rBtjjt	t
d�tj�d��tjd�Y�n�tjk
�r�tjjt	t
d�tj�d��tjjt	t
d	���tjd�Y�nRtjtjfk
�r�tjjt	d
ttj�d���tjd�Y�n
tjk
�rtjjt	t
d�tj�d��Yn�tk
�r,�Yn�tjk
�rltjjt	t
d
�tj�d��tjd�Yn~tjk
�r�tjjt	dtj�d��tjd�YnBtjk
�r�tjjt	dttj�d���tjd�YnXdS)Nrz

Aborted.
�z$An unexpected OS error occurred: %s
z1A connection was attempted with a malformed URI.
z5A connection was attempted with a malformed URI: %s.
z%There was some sort of I/O error: %s
zThere was an SSL error: %s
zqA common cause of this error is the system time being incorrect. Verify that the time on this system is correct.
zOpenSSL.SSL.SysCallError: %s
�z!There was a SSL crypto error: %s
z&There was an authentication error: %s
z%s
zXMLRPC ProtocolError: %s
�)�exceptionHandler�sys�
excepthook�
initialize�exit�main�KeyboardInterrupt�stderr�writer�_�OSError�exc_inforZMalformedURIError�len�str�IOErrorr�ErrorZSysCallError�socket�errorr�
SystemExitr�AuthenticationErrorZRpmError�	xmlrpclibZ
ProtocolError)r�errr�runZsL    $  z
RhnCli.runcCsn|jj�\|_|_tj|jj�tj�dkrRt	d�t
jd}|j|�t
j
d�|jjrb|j�|j�dS)NrzYou must be root to run %sr )r�
parse_argsrrr�_RhnCli__setDebugLevel�verbose�os�geteuidr,r$�argv�_warning_dialogr'�debug�_initialize_debug_network_logs�_RhnCli__updateProxyConfig)rZrootWarningMsgrrrr&�s

zRhnCli.initializecCst�dS)N)�NotImplementedError)rrrrr(�szRhnCli.maincCsxddl}yddlm}Wn tk
r8ddlm}YnXd|_|j�|j�j|j	�|jd�}|j|j	�d|_
dS)zF
        Enables logging of all all https requests to console
        rN)�HTTPConnectionr zrequests.packages.urllib3T)�loggingZhttp.clientrE�ImportErrorZhttplibZ
debuglevelZbasicConfigZ	getLoggerZsetLevel�DEBUGZ	propagate)rrFrEZrequests_logrrrrB�s
z%RhnCli._initialize_debug_network_logscCs�ytj�dStjk
r2ttj�d�dStjk
rFdStjk
rzt	j
�}|jd�|jtj��dSXdS)NTr Fz4There was a RhnServerException while testing login:
)
r
ZupdateLoginInforZServerCapabilityError�printr$r.r6ZRhnServerExceptionr�initLogZlog_me�
log_exception)r�logrrr�
_testRhnLogin�s
zRhnCli._testRhnLoginc	CsP|jrDyddlm}|j|�WqLttd��t|�YqLXnt|�dS)Nr)�guiz'Unable to open gui. Try `up2date --nox`)r�up2date_clientrN�errorWindowrIr,)r�messagerNrrrr@�szRhnCli._warning_dialogcCsxtj�}|jjr,|jd|jj�|jdd�|jjrP|jd|jj�|jdd�|jjrt|jd|jj�|jdd�dS)z�Update potential proxy configuration.
        Note: this will _not_ save the info to up2date's configuration file
        A separate call to config.initUp2dateConfig.save() is needed.
        Z	httpProxyZenableProxyr �	proxyUserZenableProxyAuth�
proxyPasswordN)r	�initUp2dateConfigr�proxy�setrRrS)r�cfgrrrZ__updateProxyConfig�szRhnCli.__updateProxyConfigcCstj�}|j�dS)zM
        Saves the current up2date configuration being used to disk.
        N)r	rTZsave)rrWrrr�
saveConfig�szRhnCli.saveConfigc	CsP|jrDyddlm}|j|�WqLttd��t|�YqLXnt|�dS)Nr)rNz'Unable to open gui. Try `up2date --nox`)rrOrNrPrIr,)rZerrMsgrNrrrZ__faultError�szRhnCli.__faultErrorcCstd�tj�}|S)Nzp%%prog (Spacewalk Client Tools) %s
Copyright (C) 1999--2014 Red Hat, Inc.
Licensed under the terms of the GPLv2.)r,r
r)Z
versionStringrrrZ__versionString�s
zRhnCli.__versionStringcCs0tj�}|d||d<|ddkr,tj�dS)NrAr!)r	rTrZsetDebugVerbosity)�levelrWrrrZ__setDebugLevel�szRhnCli.__setDebugLevelN)�__name__�
__module__�__qualname__rr9r&r(rBrMr@rCrXZ_RhnCli__faultError�staticmethodrr;rrrrrOs	,rcCs�tj�}tjjttd�d��t|d�rPtjjt|j�d�|j	|||�n&tjjtt
|�d��|j	|||�tjjttd�d��dS)NzAn error has occurred:�
�errmsgz)See /var/log/up2date for more information)rrJr$r*r+rr,�hasattrr_rKr0)�type�value�tbrLrrrr#�s
r#)"r$r=r3ZoptparserrZOpenSSLrrZrhnrZrhn.i18nrr7rGZ
xmlrpc.clientZclient�gettextZtranslation�tr`rr,rOr	r
rrr
rr�objectrr#rrrr�<module>"sH





)__pycache__/up2dateLog.cpython-36.pyc000064400000004755150516774040013434 0ustar003

c8h<�@sFddlZddlZddlmZmZddlmZGdd�d�Zdd�ZdS)�N)�ustr�sstr)�configc@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)�Logz�
    attempt to log all interesting stuff, namely, anything that hits
    the network any error messages, package installs, etc
    cCsd|_tj�|_d|_dS)NZup2date�)�apprZinitUp2dateConfig�cfg�log_info)�self�r� /usr/lib/python3.6/up2dateLog.py�__init__
s
zLog.__init__cCst|�|_dS)N)�strr)r
�namerrr�set_app_nameszLog.set_app_namecGs |jddkr|jd|��dS)N�debug��D: )r)r�log_me)r
�argsrrr�	log_debugsz
Log.log_debugcGsddtjtj��|jf|_d}x |D]}tt|��}||7}q$W|jddkrVt|�|j|�dS)zHGeneral logging function.
        Eg: log_me("I am a banana.")

        z[%s] %srrrN)	�time�ctimerr	rrr�print�	write_log)r
r�s�irrrrs
z
Log.log_mecCs@dtjtj��|jf|_tj�}djtj|��}|j|�dS)Nz[%s] %sr)	rrrr	�	traceback�
extract_stack�join�format_listr)r
�x�msgrrr�trace_me)szLog.trace_mecCsddtjtj��|jf|_dg}|jd�|tjtj|��}|jd||f�|jdj	|��dS)Nz[%s] %s�
z#Traceback (most recent call last):
z%s: %s
r)
rrrr	�appendrr �
extract_tbrr)r
Zlogtype�value�tb�outputrrr�
log_exception/s
zLog.log_exceptioncCsP|jdpd}t|d�}dt|j�t|�f}|jt|��|j�|j�dS)NZlogFilez/var/log/up2date�az%s %s
)r�openrr	�writer�flush�close)r
rZlog_nameZlog_filer"rrrr7s
z
Log.write_logN)�__name__�
__module__�__qualname__�__doc__r
rrrr#r*rrrrrrsrcCs4ytaWntk
r daYnXtdkr0t�atS)N)�log�	NameErrorrrrrr�initLog@s
r6)	rrZrhn.i18nrrZup2date_clientrrr6rrrr�<module>s
8__pycache__/hardware_gudev.cpython-36.pyc000064400000017325150516774040014412 0ustar003

c8h�3�@s�y(ddlZejdd�ddlmZdZWn,eefk
rTddlZddlZdZYnXddl	Z	ddl
Z
ddlmZm
Z
dd	�Zd
d�ZdZd
ZdZdZdZdZdZdZd
ZdZdZdZdZdZd
ZdZdZ dZ!dZ"d
Z#dZ$dZ%dZ&dZ'd
Z(dZ)dZ*dZ+dZ,dZ-dZ.dZ/dZ0dZ1dZ2d
Z3dZ4dZ5dZ6dZ7dZ8d
Z9dZ:dZ;dZ<dZ=dZ>dZ?d
Z@dZAdZBdZCdZDdZEdd�ZFd d!�ZGd"d#�ZHd$d%�ZId&d'�ZJdS)(�N�GUdevz1.0)rTF)�PCI�USBc
Csrtrtj�}ntjdg�}|jd�|jd�|jd�|jd�|jd�}g}�x|D�]}|j�}||j�t|�dt|�t	|�d�}|d	d
kr�d|d	<|dd
kr�d
|d<|dk�r|j
d�r�|jd�|d<|j�|d<|j
�dkr�qX|jd�r�qX|jd�dk�r
qX|jd�dk�r�qXn�|dk�rv|jd�}|�rN|jd�\|d<|d<|jd�}|�r�|jd�\|d<|d<n>|dk�r�|j
d��r�|jd�|d<|j
d��r�|jd�|d<|j
d��r`|jd�dk�r`|j
d��s�|j
d ��r`|j
d��r|jd�}tjd!|�}	n|jd �}tjd"|�}	|	�r`|	jd#�|d<|	jd$�|d<|	jd%�|d<|	jd&�|d<|j|�qXW|S)'aE Returns list of dictionaries with keys for every device in system
        (values are provide as example):
        'bus' : 'pci'
        'driver' : 'pcieport-driver'
        'pciType' : '1'
        'detached' : '0'
        'class' : 'OTHER'
        'desc' : 'Intel Corporation|5000 Series Chipset PCI Express x4 Port 2'
    ��pci�usb�blockZccw�scsi�0)�bus�driverZpciTypeZdetached�classZdescr
N�OTHERr�unknownZID_BUSr�device�	partitionZDM_NAMEZMAJOR�1�7�PCI_ID�:Zprop1Zprop2Z
PCI_SUBSYS_IDZprop3Zprop4�ID_VENDOR_ID�ID_MODEL_IDZID_PATHZDEVPATHz.*scsi-(\d+):(\d+):(\d+):(\d+)z!.*/(\d+):(\d+):(\d+):(\d+)/block/����)�gi_gudevrZClient�gudevZquery_by_subsystem�
get_subsystem�
get_driver�_clasify_pci_type�_clasify_class�_get_device_desc�has_property�get_propertyZget_name�get_devtype�split�re�search�group�append)
ZclientZdevices�resultr�	subsystemZresult_item�	pci_classZ
pci_subsys�path�m�r0�$/usr/lib/python3.6/hardware_gudev.py�get_devicessn
2








r2cCs$tj�}|d|d|dd�}|S)z� Return dictionaries with keys (values are provided as example):
        'system.formfactor': 'unknown'
        'system.kernel.version': '2.6.18-128.1.6.el5xen'
            'system.kernel.machine': 'i686'
        'system.kernel.name': 'Linux'
    rrr)zsystem.kernel.namezsystem.kernel.versionzsystem.kernel.machine)�os�uname)r4r+r0r0r1�get_computer_infons
r5rZ00Z01Z02Z03Z04Z80�2�3�4�6Z05Z06Z07Z08r�9�CcCs|dkrdSdSdS)z) return 1 if device is PCI, otherwise -1 rrz-1Nr0)r,r0r0r1r �sr cCs>t|jd��\}}|j�}|tkr&dS|tkrF|tkr:dS|tkrFdS|jd�}|rt|j�}d|krhdSd|krtdS|�rZ|tkr�dS|t	kr�|t
kr�d	S|tkr�d
Sn�|tkr�|t
kr�dS|tkr�dS|tkr�d
S|tkr�dSnx|tko�|tk�r�dS|tk�r|tk�rdS|tk�r8|tk�r(dS|tk�rZdSn"|tk�rZ|tk�sV|tk�rZdS|dk�r�|jd��s�|jd��r�|jd�dk�r�dSdSn|dk�r�dS|dk�r�|jdk�r�t|�}|dk�s�|dk�r�dS|dk�r�d S|d!k�r�dSdStjd"|j��}|�rd#S|dk�r"dS|d$k�s6|d%k�r:dSd&S)'a Clasify type of device. Returned value is one of following string:
        NETWORK, KEYBOARD, MOUSE, VIDEO, USB, IDE, SCSI, RAID, MODEM, SCANNER
        CAPTURE, AUDIO, FIREWIRE, SOCKET, CDROM, HD, FLOPPY, TAPE, PRINTER, OTHER
        or None if it is neither PCI nor USB device.
    Z	PCI_CLASSrZKEYBOARDZMOUSEZ	ID_SERIALZkeyboardZmouseZVIDEOrZFIREWIREZIDEZSCSIZRAIDZFLOPPYZMODEMZSCANNERZCAPTUREZAUDIOZSOCKETrZID_CDROMZID_TYPEZcdZCDROMZHDZsoundr	Zscsi_devicer�rZTAPE�z	.*/lp\d+$ZPRINTERrrN) �_parse_pci_classr$r�PCI_BASE_CLASS_NETWORK�PCI_BASE_CLASS_INPUT�PCI_CLASS_INPUT_KEYBOARD�PCI_CLASS_INPUT_MOUSE�lower�PCI_BASE_CLASS_DISPLAY�PCI_BASE_CLASS_SERIAL�PCI_CLASS_SERIAL_USB�PCI_CLASS_SERIAL_FIREWIRE�PCI_BASE_CLASS_STORAGE�PCI_CLASS_STORAGE_IDE�PCI_CLASS_STORAGE_SCSI�PCI_CLASS_STORAGE_RAID�PCI_CLASS_STORAGE_FLOPPY�PCI_BASE_CLASS_COMMUNICATION�PCI_CLASS_COMMUNICATION_MODEM�PCI_CLASS_INPUT_SCANNER�PCI_BASE_CLASS_MULTIMEDIA�PCI_CLASS_MULTIMEDIA_VIDEO�PCI_CLASS_MULTIMEDIA_AUDIO�PCI_BASE_CLASS_BRIDGE�PCI_CLASS_BRIDGE_PCMCIA�PCI_CLASS_BRIDGE_CARDBUSr#r%�_get_scsi_dev_typer'r(�get_sysfs_path)rZ
base_classZ	sub_classr,Z	id_serialZdev_typer/r0r0r1r!�s�










r!c	CsV|j�}d}d}|dkrN|jd�jd�\}}t�}d|j|�|j||�f}n�|dk�r0|jd�}t�}|r�d|j|�|j||jd��f}n�|j�d	kr�|j�d
kr�d}n|j�dkr�d
}nd}nj|j�dko�|jd��rD|jd�jd�dd�\}}dt	|d�}dt	|d�}d|j|�|j||�f}n|dk�rD|jd�}|�rN|SdSdS)z. Return human readable description of device. Nrrrz%s|%srrrZ
usb_interfaceZusbhidzUSB HID InterfaceZhubzUSB Hub Interfacez
USB InterfaceZ
usb_deviceZPRODUCT�/rz%.4x�rZID_MODELr)
rr$r&rZ
get_vendorZ
get_devicerr%r�int)	rr,Zcommandr+Z	vendor_idZ	device_idrrZmodel_idr0r0r1r"%s8

"

r"cCs(|dkrdS|dd�|dd	�fSdS)
a= Parse Class Code. Return touple of
        [base class code, sub-class code]
        You are usually interested to only first two.
        The third - "specific register-level programming interface" is ignored.
        For details, see the PCI Local Bus Specification 2.1/2.2 Section 6.2.1 Device Identification
    N�rr)NNi�������r\���r0)r-r0r0r1r>Gsr>cCs@ytd|j�d�}Wntk
r*dSX|j�}|j�|S)zQ Return SCSI type of device in raw format as presented in /sys/...devpath../type z%s/type�rr���)�openrW�IOError�readline�close)r�fr+r0r0r1rVSsrV)KZgiZrequire_versionZ
gi.repositoryrr�ImportError�
ValueErrorrZglibr3r'Zhwdatarrr2r5rHrJrIrLZPCI_CLASS_STORAGE_IPIrKZPCI_CLASS_STORAGE_OTHERr?ZPCI_CLASS_NETWORK_ETHERNETZPCI_CLASS_NETWORK_TOKEN_RINGZPCI_CLASS_NETWORK_FDDIZPCI_CLASS_NETWORK_ATMZPCI_CLASS_NETWORK_OTHERrDZPCI_CLASS_DISPLAY_VGAZPCI_CLASS_DISPLAY_XGAZPCI_CLASS_DISPLAY_3DZPCI_CLASS_DISPLAY_OTHERrPrQrRZPCI_CLASS_MULTIMEDIA_PHONEZPCI_CLASS_MULTIMEDIA_OTHERrSZPCI_CLASS_BRIDGE_HOSTZPCI_CLASS_BRIDGE_ISAZPCI_CLASS_BRIDGE_EISAZPCI_CLASS_BRIDGE_MCZPCI_CLASS_BRIDGE_PCIrTZPCI_CLASS_BRIDGE_NUBUSrUZPCI_CLASS_BRIDGE_RACEWAYZPCI_CLASS_BRIDGE_OTHERrMZPCI_CLASS_COMMUNICATION_SERIALZ PCI_CLASS_COMMUNICATION_PARALLELZ#PCI_CLASS_COMMUNICATION_MULTISERIALrNZPCI_CLASS_COMMUNICATION_OTHERr@rAZPCI_CLASS_INPUT_PENrBrOZPCI_CLASS_INPUT_GAMEPORTZPCI_CLASS_INPUT_OTHERrErGZPCI_CLASS_SERIAL_ACCESSZPCI_CLASS_SERIAL_SSArFZPCI_CLASS_SERIAL_FIBERZPCI_CLASS_SERIAL_SMBUSr r!r"r>rVr0r0r0r1�<module>s�
P`"__pycache__/rhnChannel.cpython-36.opt-1.pyc000064400000011355150516774040014437 0ustar003

c8h��@s�ddlmZddlmZddlmZddlmZddlmZddlZejddd	�Ze	ed
�sdeje_
ej
ZGdd�d�ZGd
d�d�Z
ddd�ZgZdaddd�Zdd�Zdd�Zdd�ZdS)�)�up2dateAuth)�
up2dateLog)�
up2dateErrors)�config)�	rhnserverNzrhn-client-toolsT)Zfallback�ugettextc@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�
rhnChannelcKs*i|_x|j�D]}|||j|<qWdS)N)�dict�keys)�self�kwargs�kw�r� /usr/lib/python3.6/rhnChannel.py�__init__szrhnChannel.__init__cCs
|j|S)N)r	)r�itemrrr�__getitem__szrhnChannel.__getitem__cCs||j|<dS)N)r	)rr�valuerrr�__setitem__szrhnChannel.__setitem__cCs|jd|jdkS)N�name)r	)r�otherrrr�__lt__!szrhnChannel.__lt__cCs
|jj�S)N)r	r
)rrrrr
$szrhnChannel.keyscCs
|jj�S)N)r	�values)rrrrr'szrhnChannel.valuescCs
|jj�S)N)r	�items)rrrrr*szrhnChannel.itemsN)
�__name__�
__module__�__qualname__rrrrr
rrrrrrrsrc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)�rhnChannelListcCs
g|_dS)N)�list)rrrrr.szrhnChannelList.__init__cCs|jj|�dS)N)r�append)r�channelrrr�
addChannel3szrhnChannelList.addChannelcCs|jS)N)r)rrrr�channels7szrhnChannelList.channelscCs$x|jD]}|d|kr|SqWdS)N�label)r)r�channelnamer rrr�
getByLabel:szrhnChannelList.getByLabelcCs
|j|�S)N)r%)rr$rrr�	getByName>szrhnChannelList.getByNamecCs.g}x$|jD]}|d|kr|j|�qW|S)N�type)rr)rr'r"r rrr�	getByTypeAs
zrhnChannelList.getByTypeN)	rrrrr!r"r%r&r(rrrrr-srcCsdg}t|d�}xP|j�D]D}|ddkrR|d|d<d|d|d|df|d<|j|�qW|S)	N)�timeoutr'�up2dater#rz%s channel %s from  %s�url�description)�getChannelsr"r)r)r"ZsourceChannelsZ
sourceChannelrrr�getChannelDetailsKs
r.c
Cs:tj�}tj�}to|�rt�atj|d�}tj	�sFt
jtd���|j
jtj	��}x�|D]�}|rr|d|krrq\tdtj�d�}x2|j�D]&}	|	dkr�|d|d<q�||	||	<q�W|d�r
|d|d	<|d<|d
<|d<|jd|d	�|jd
�|jd�tj|�q\Wttj�dk�r6t
jtd���tS)zG return rhnChannelList containing list of channel we are subscribed to )r)zUnable to Locate SystemIdr#r*)r'r+Z
last_modified�versionZchannelOverriderr,Zsummaryz'WARNING: Channel overridden locally: %sz=-------: If you see this warning outside of the leapp processz$-------: contact CloudLinux support.rzEThis system may not be updated until it is associated with a channel.)rZinitUp2dateConfigrZinitLog�selected_channelsrr�	RhnServerr�getSystemIdrZNoSystemIdError�_r*ZlistChannelsrZgetServerlURLFromMirrorr
Zlog_mer!�lenrZNoChannelsError)
�force�label_whitelistr)Zcfg�log�sZup2dateChannelsZchanr �keyrrrr-^s2

$

r-cCs dattdd�|��}t|d�S)NcSs|dfS)N�r)�xrrr�<lambda>�szsetChannels.<locals>.<lambda>)r6)r0r	�mapr-)ZtempchannelsZ	whitelistrrr�setChannels�sr>cCstj�}|jjtj�|||�S)N)rr1r*�subscribeChannelsrr2)r"�username�passwdr8rrrr?�sr?cCstj�}|jjtj�|||�S)N)rr1r*�unsubscribeChannelsrr2)r"r@rAr8rrrrB�srB)N)NNN)Zup2date_clientrrrrr�gettextZtranslation�t�hasattrrr3rrr.Zcmdline_pkgsr0r-r>r?rBrrrr�<module>s$


(__pycache__/tui.cpython-36.opt-1.pyc000064400000076402150516774040013164 0ustar003

c8hͮ�@s(ddlmZddlZddlZejddd�Zeed�s<eje_ejZddl	Z	ddl
Z
ddlmZm
Z
ddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZmZddlTej �Z!ej"�Z#dd�Z$dd�Z%dd�Z&dd�Z'dd�Z(Gdd�de)�Z*Gd d!�d!�Z+Gd"d#�d#�Z,Gd$d%�d%�Z-Gd&d'�d'�Z.Gd(d)�d)�Z/Gd*d+�d+�Z0Gd,d-�d-�Z1Gd.d/�d/�Z2Gd0d1�d1�Z3Gd2d3�d3�Z4Gd4d5�d5�Z5Gd6d7�d7�Z6Gd8d9�d9�Z7Gd:d;�d;�Z8Gd<d=�d=�Z9d>d?�Z:e;d@k�r$e:�dS)A�)�geteuidNzrhn-client-toolsT)Zfallback�ugettext)�rhnreg�hardware)�
up2dateErrors)�up2dateUtils)�pkgUtils)�
up2dateLog)�config)�convert_url_from_puny)�up2dateAuth)�rpclib)�idn_puny_to_unicode)�sstr)�PM_PLUGIN_NAME�PM_PLUGIN_CONF)�*cCs&tj|tt�td|�tt�g�dS)Nz%s)�snack�ButtonChoiceWindowr�ERROR�BACK)�screen�errmsg�r�/usr/lib/python3.6/tui.py�ErrorWindow/srcCs8tj|tt�td|�tt�g�|j�tjd�dS)Nz%s�)rrrZFATAL_ERROR�OK�finish�sys�exit)rrrrr�FatalErrorWindow3sr!cCs.tj|tt�td|�tt�g�|j�dS)Nz%s)rrr�WARNINGrr)rrrrr�
WarningWindow9sr#cCs�tj|tt�tt�dtt�dtt�dtt�dtt�dtt	�dtt
�dtt�dtt�dtt
�dtt�tt�tt�gdd�}|tt�j�kr�|j�dSdSdS)N�
z

�F)�widthrr)rrrZCONFIRM_QUITZCONFIRM_QUIT_SURE�WHY_REGISTER_SEC�WHY_REGISTER_SEC_TXT�WHY_REGISTER_DLD�WHY_REGISTER_DLD_TXT�WHY_REGISTER_SUPP�WHY_REGISTER_SUPP_TXT�WHY_REGISTER_COMP�WHY_REGISTER_COMP_TXTZCONFIRM_QUIT_WILLNOT�WHY_REGISTER_TIPZCONTINUE_REGISTERINGZREGISTER_LATER2�lowerr)r�buttonrrr�ConfirmQuitWindow?s
vr2c
Gs�y||�}Wn�tjk
rDt|ttj�d�tj�d�Yn�tjk
rpt||j	�tj�d�Yn�tj
k
r�tj�d}t||j	dtt
j�t
j�t
j�f�Yn:tjk
r�tj�d}t||j	dt�|�YnX|S)Nrrr$z

)r�CommunicationErrorrZHOSTED_CONNECTION_ERRORr
�getServerURLr�exc_infoZSSLCertificateVerifyFailedErrorrZNoBaseChannelErrorr!ZBASECHANNELERRORr�getArchZgetOSRelease�
getVersionZSSLCertificateFileNotFoundZSSL_CERT_FILE_NOT_FOUND_ERRER)r�funcZparams�results�errr�tui_call_wrapperVs(
r;c@seZdZdS)�WindowSkipExceptionN)�__name__�
__module__�__qualname__rrrrr<nsr<c@s(eZdZdZdd�Zdd�Zdd�ZdS)�AlreadyRegisteredWindowc	Cs<tj�s|jrt��||_||_tjj�}t	j
jtj
��}|ddd}|ddd}tj|jtt�dd�}tj|jtt�dftt�dfg�|_|j|jdddd�tj|dd	|dd
ttdtd�d
t|jj�dtd�d
|dtd�d
|dtd�dd�}|j|dddd�||_dS)NrZusername�	system_idr��nextr )�growx��z

zSpacewalk Location:� r$zLogin:z
System ID:)�padding)rrrr)rZ
registered�testr<r�tuir�_snack�sizer
Z	xmlrpclib�loadsrZgetSystemId�GridFormr�SYSTEM_ALREADY_SETUP�	ButtonBar�YES_CONT�	NO_CANCEL�bb�add�TextboxZSYSTEM_ALREADY_REGISTERED�_r�	serverURL�SYSTEM_ALREADY_REGISTERED_CONT�g)	�selfrrJrLZsystemIdXmlZoldUsernameZoldsystemId�toplevel�tbrrr�__init__ts&

Tz AlreadyRegisteredWindow.__init__cCsdS)Nr)rZrrr�saveResults�sz#AlreadyRegisteredWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %s�F12rC)�log�	log_debug�namerY�runOncerS�
buttonPressed)rZ�resultr1rrr�run�s
zAlreadyRegisteredWindow.runN)r=r>r?rbr]r^rfrrrrr@qsr@c@s0eZdZdZdd�Zdd�Zdd�Zdd�Zd	S)
�SatelliteUrlWindowcCs�||_||_d|j_t|jj�|_tj|j�}||jkrR||_tj	|j�t
j�tj
j�}tj|tt�dd�}t}t}t}tj|dddt|�ddd�}	|j|	dddd�tjtd��}	|j|	dd�tjd	d�}
tjt|��}	|
j|	ddddd
�tjd�|_|jj|j�|
j|jdddd�tjt|��}	|
j|	ddddd
�tjd�|_|jj|j�|
j|jdddd�|j|
dd	�tj|tt �dftt!�d
ftt"�dfg�|_#|j|j#ddddd�||_$dS)Nrr��
�)�scroll�wrap)�
anchorLeft�rB)rH�anchorRight�(rC�back�cancel)rHrD)rrrr)rrrr)rrrr)%rrJ�alreadyRegisteredrrW�serverr�makeNiceServerUrlr
�setServerURL�cfg�saverrKrLrNrZSATELLITE_URL_WINDOWZSATELLITE_URL_TEXTZSATELLITE_URL_PROMPTZSATELLITE_URL_PROMPT2rUrT�Label�Grid�setField�Entry�urlEntry�set�sslEntry�	sslCACertrP�NEXTr�CANCELrSrY)rZrrJ�fixed_server_urlrLr[Zprompt_textZ	url_labelZ	ssl_label�label�gridrrrr]�sT




zSatelliteUrlWindow.__init__cCs�|jj�dkrBtj|jtt�tt�tt�gd�|j	j
|j�dS|jj�dd�dkr�|jj�dkr�tj|jtt�tt�tt�gd�|j	j
|j�dSdS)Nrn)�buttonsr�Zhttpsr)
r}�valuerrrrrZSATELLITE_REQUIREDrrY�
setCurrentrZSSL_REQUIRED)rZrrr�validateFields�sz!SatelliteUrlWindow.validateFieldscCs\|jj�}tj|�}||kr |}||j_|jj�|j_tj	|�tj
|jj��tj�dS)N)
r}r�rrurJrWrr�r
rvZsetSSLCACertrwrx)rZZserverEntryr�rrrr^�s


zSatelliteUrlWindow.saveResultscCsltjd|j�|jj�d}x>|s\|jj�}|jj|�}|dkrFd}|dkrX|j	�}q Pq W|jj
�|S)Nz
Running %srr_rC)r`rarbr�refreshrYrfrSrdr��	popWindow)rZ�validrer1rrrrfs



zSatelliteUrlWindow.runN)r=r>r?rbr]r�r^rfrrrrrg�s
A
rgc@s(eZdZdZdd�Zdd�Zdd�ZdS)�*AlreadyRegisteredSubscriptionManagerWindowcCs�tj�s|jrt��||_||_tjj�}tj	|jt
t�dd�}tj|jt
t
�dft
t�dfg�|_|j|jdddd�tj|dd|ddt
td	td	td
�dd�}|j|dddd�||_dS)
NrrBrCr r)rDrErFz

r$)rH)rrrr)rZrhsm_registeredrIr<rrJrrKrLrNrrOrPrQrRrSrTrUr"ZRHSM_SYSTEM_ALREADY_REGISTEREDrXrY)rZrrJrLr[r\rrrr]s 

z3AlreadyRegisteredSubscriptionManagerWindow.__init__cCsdS)Nr)rZrrrr^2sz6AlreadyRegisteredSubscriptionManagerWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %sr_rC)r`rarbrYrcrSrd)rZrer1rrrrf5s
z.AlreadyRegisteredSubscriptionManagerWindow.runN)r=r>r?rbr]r^rfrrrrr�sr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�
ConnectWindowcCs�||_||_tjj�}t|jj�|_td|_	tj
|jtt�dd�}t
|jd}|j	rf|t|j	7}tj|dd|ddt|�dd�}|j|dddd�||_dS)	NZ	httpProxyrz

rrErF)rH)rrrr)rrJrrKrLrrWrtrw�proxyrNrZCONNECT_WINDOWZCONNECT_WINDOW_TEXTZCONNECT_WINDOW_TEXT2rUrTrY)rZrrJrLr[�textr\rrrr]Cs

zConnectWindow.__init__c	CsPtjd|j�|jj�}|jj�yt|jtj	�Wn
dS|jj
�dS)Nz
Running %srqrC)r`rarbrY�drawrr�r;rZgetCapsr�)rZrerrrrf\s


zConnectWindow.runcCsdS)Nr)rZrrrr^qszConnectWindow.saveResultsN)r=r>r?rbr]rfr^rrrrr�@sr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�StartWindowcCs�||_||_tjj�}tj|jtt�dd�}tt�}tj	|dd|dd|dd�}|j
|dddd�tj|jtt�dftt
�dftt�d	fg�|_|j
|jdddd
�||_dS)NrrBrri�)rH�why_registerrCrr)rD)rrrr)rrJrrKrLrNrZSTART_REGISTER_WINDOWZSTART_REGISTER_TEXTrUrTrPZWHY_REGISTERr�r�rSrY)rZrrJrLr[Zstart_register_textr\rrrr]ws
"

zStartWindow.__init__cCsdS)Nr)rZrrrr^�szStartWindow.saveResultscCsXtjd|j�|jj�}|jj|�}|dkr2dS|dkrTt|j|j	�}|j
�|S|S)Nz
Running %sr_rCr�)r`rarbrYrcrSrd�WhyRegisterWindowrrJrf)rZrer1Zwhy_reg_winrrrrf�s
zStartWindow.runN)r=r>r?rbr]r^rfrrrrr�tsr�c@s eZdZdZdd�Zdd�ZdS)r�cCs�||_||_tjj�}tj|jtt�dd�}tdt	dt
dtdtdt
dtdtdtdt}tj|dd|ddt|�dd�}|j|dddd�tj|jtt�d	fg�|_|j|jdddd
�||_dS)NrrBz

r$rrir�)rHrq)rD)rrrr)rrJrrKrLrNrZWHY_REGISTER_WINDOWZWHY_REGISTER_TEXTr'r(r)r*r+r,r-r.r/rUrTrPZ
BACK_REGISTERrSrY)rZrrJrLr[Zwhy_register_textr\rrrr]�s
F&zWhyRegisterWindow.__init__cCs*tjd|j�|jj�}|jj|�}|S)Nz
Running %s)r`rarbrYrcrSrd)rZrer1rrrrf�s
zWhyRegisterWindow.runN)r=r>r?rbr]rfrrrrr��sr�c@s0eZdZdZdd�Zdd�Zdd�Zdd�Zd	S)
�
InfoWindowcCs||_||_d|j_|jj|_tjj�}tj|t	t
�dd�}t|j�}|j}||jkrb|d|7}t|}t
}t}	tj|dddt	|�ddd�}
|j|
dddd�tjd	d�}tjt	|��}
|j|
ddddd
�tjd�|_|jj|j�|j|jdddd�tjt	t��}
|j|
ddddd
�ytjddd�|_Wn&tk
�r\tjddd
�|_YnX|jj|j�|j|jdddd�|j|dd�tj|ddt	|	��}
|j|
dd	dd�tj|t	t�dft	t�dft	t �dfg�|_!|j|j!ddddd�||_"dS)Nrrrhz (%s)rirj)rkrl)rmrB)rHrorF)�password)ZhiddenrCrqrr)rHrD)rrrr)rrrr)rrrr)#rrJrsrWrtrrKrLrNrZREGISTER_WINDOWrZLOGIN_PROMPTZLOGINZ	LOGIN_TIPrUrTrzryr{r|�
userNameEntryr~�userNameZPASSWORD�
passwordEntry�	TypeErrorr��TextboxReflowedrPr�rr�rSrY)rZrrJrLr[Zdecoded_serverZurlZlogin_promptZlogin_labelZ	login_tipr�r�rrrr]�sV






zInfoWindow.__init__c
CsL|jj�dkrBtj|jtt�tt�tt�gd�|j	j
|j�dS|jj�dkr�tj|jtt�tt�tt�gd�|j	j
|j�dSy t
j|jj�|jj��|j_Wn�tjk
�rtj�d}tj|jttd��ttd��t|j�ttd��gd�|j	j
|j�dStjk
�rFtj�d}t|jtd�|j�YnXdS)	Nrn)r�rr�ErrorzThe server indicated an error:
rz?There was an error communicating with the registration server:
)r�r�rrrrrZ
USER_REQUIREDrrYr�r�ZPASSWORD_REQUIREDrZreserveUserrJrsrZValidationErrorrr5rVrr3r!)rZr:rrrr�	s. 8zInfoWindow.validateFieldscCs |jj�|j_|jj�|j_dS)N)r�r�rJr�r�r�)rZrrrr^%szInfoWindow.saveResultscCsltjd|j�|jj�d}x>|s\|jj�}|jj|�}|dkrFd}|dkrX|j	�}q Pq W|jj
�|S)Nz
Running %srr_rC)r`rarbrr�rYrfrSrdr�r�)rZr�rer1rrrrf)s



zInfoWindow.runN)r=r>r?rbr]r�r^rfrrrrr��s
@r�c@s0eZdZdZdd�Zdd�Zdd�Zdd�Zd	S)
�OSReleaseWindowcCsx||_tj�stjd�t��tj|j|j�|_	t
|j	d�dkrRtjd�t��||_tj
j�|_d|_tj|jtt�dd�}||_tj|jddtt��|_|j|jdddd	�tt�}|jjr�tj|ddd
�|_ntj|d�|_|j|jddddd�tjtt��|_|j|jdddd	�tj|jdd
d|jddd�|_|j|jdd�xRt |j	dj!�dd�d�D]4\}}||j	dk�r�|d}|jj"d||��qtWtj|jddtt#��|_$|j|j$dddd	�tt%�}|jj&�rtj||jdd
�|_&ntj||j�|_&|j|j&ddddd�tj'|tt(�dftt)�dftt*�dfg�|_+|j|j+dddd�|jj,�dS)Nz5Server does not support EUS, skipping OSReleaseWindow�channelsrz3No available EUS channels, skipping OSReleaseWindowF�rri)rm)�isOn)rHrmrB�)r&rjcSs|dS)Nrr)�arrr�<lambda>jsz*OSReleaseWindow.__init__.<locals>.<lambda>)�keyZreceiving_updatesrrGrhr�rCrqrr�)rD)rrrr)rrrr)-rJrZserver_supports_eusr`rar<ZgetAvailableChannelsr�r��available_channels�lenrrrKrLZ
selectChannelrNrZSELECT_OSRELEASErYr�Z
OS_VERSIONZostextrTZLIMITED_UPDATES�limited_updates_buttonZSingleRadioButtonryZ
MINOR_RELEASEZsublabelZListbox�channelList�sorted�items�appendZCHANNEL_PAGE_TIPZtipZALL_UPDATES�all_updates_buttonrPr�rr�rSr�)rZrrJr[Zoptiontext1r�r�Zoptiontext2rrrr]@sb

$



zOSReleaseWindow.__init__cCsptjd|j�|jj�d}xB|dkr`|jj�}|jj|�}|dkrJd}|dkr\|j	�}q Pq W|jj
�|S)Nz
Running %srrr_rC)r`rarbrr�rYrfrSrdr�r�)rZr�rer1rrrrf�s




zOSReleaseWindow.runcCs�d}d}|jj�r&|jj�|jdk}tt�}|rdtj|j	|tt
�|jj�tt�tt�gd�}|S|j
j�sr|r�tj|j	|tt�tt�tt�gd�}|S|S)N�okFZdefault_channel)r�)r��selectedr��currentr�rZCONFIRM_OS_RELEASE_SELECTIONrrrZCONFIRM_OS_WARNINGrr�r�ZCONFIRM_OS_ALL)rZZmsgboxZ
later_release�titlerrrr��s 


zOSReleaseWindow.validateFieldscCsz|jjjdd�|jj�rVtjd|jj��|jj�|jjd<|jj�|j_d|j_	|j	j�rv|j	j�|j_	d|j_dS)N�channelzSelected Channel %sr)
rJ�other�popr�r�r`rar�r�r�)rZrrrr^�s

zOSReleaseWindow.saveResultsN)r=r>r?rbr]rfr�r^rrrrr�=s
Mr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�HardwareWindowc	Cs�||_||_tjj�}tj�\}}|dk	rB||jjd<||jjd<tj	�|_tj
|tt�dd�}tj
dtt��}|j|dddd�tjdd�}tjttd	���}	|j|	ddd.dd
�tjd�|_|j|jdddd�|j|dddd�|j�rtjtt�dd�|_ntjtt��|_|j|jddd/dd
�tjtt��}	|j|	dddd0d�tjdd�}d}
|
td�ttj��d7}
tjttd���|_|j|jddd1dd
�tjttj���|_|j|jdddd�|
td�7}
x.|jD]$}|ddk�r�|
|dd7}
�q�W|
td�7}
xb|jD]X}|ddk�rt|d�}|
|d7}
|j dk�r`|jj!|j �n|jj!t|���qW|
td�7}
x6|jD],}|ddk�r�|
td�|dd7}
�q�W|
td�7}
xT|jD]J}|ddk�r�|d �r�|
|d d7}
n|d!�r�|
|d!d7}
�q�W|
td"�7}
x2|jD](}|dd#k�r0|
td$�|d%7}
�q0Wtj
d&t|
��}
|j|
dd�tj
|dd'tt"��|_#|j|j#dd(d2dd
�tj$|tt%�d)ftt&�d*ftt'�d+fg�|_(|j|j(dd,d3dd-�||_)dS)4N�	virt_uuid�	virt_typerr�r%r)rmrBz
Profile name:)rHrorp)r�)rHrmrj)rmrHrhrnz	Version: z  zCPU model: �classZCPUZmodelr$z
Hostname: ZNETINFOZhostnamezCPU speed: z%d MHzZspeedzIP Address: ZipaddrZip6addrzMemory: ZMEMORYz%s megabytesZram�Prir�rCrqrrr�)rHrD)rrrr)rrrr)rrrr)rrrr)rrrr)rrrr)*rrJrrKrLrZ
get_virt_infor�rZHardwarerNrZHARDWARE_WINDOWr�ZHARDWARE_WINDOW_DESC1rTrzryrVr{r|�profileEntry�includeHardware�CheckboxZHARDWARE_WINDOW_CHECKBOX�hardwareButtonZDESELECTrr7ZversionLabelZ
versionLabel2r�profileNamer~ZHARDWARE_WINDOW_DESC2ZadditionalHWLabelrPr�rr�rSrY)rZrrJrLr�r�r[r�r�r�Z
hardware_textZhwZunicode_hostnamer\rrrr]�s�





zHardwareWindow.__init__cCs |jj�|j_|jj�|j_dS)N)r�r�rJr�r�r�r�)rZrrrr^5szHardwareWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %sr_rC)r`rarbrYrcrSrd)rZrer1rrrrf9s
zHardwareWindow.runN)r=r>r?rbr]r^rfrrrrr��snr�c@s0eZdZdZdd�Zdd�Zdd�Zdd�Zd	S)
�PackagesWindowc	Cs�||_||_tjj�}tj|tt�dd�}||_tj	|ddtt
��}|j|dddd�tjtt
�d�|_|j|jddddd�tjtt��}|j|dddd�tj|ddd�|_|j|jdd	�|jgk�rJtj|tt�dd�|_tjd
d�|_|jj|jdd�|jj�|jj�d}tjd�r2d}tj|d
�|_|jj�xL|jD]B}|jjdt|d�t|d�t|d�ft|d�dd��qRWtj|tt �dftt!�dftt"�dfg�|_#|j|j#ddddd�dS)Nrr�rri)rm)rHrmrB�rjrp�dZsupportsExtendedPackageProfile)r6z%s-%s-%srb�version�release)�itemr�rCrqrrrh)rHrD)rrrr)rrrr)$rrJrrKrLrNrZPACKAGES_WINDOWrYr�ZPACKAGES_WINDOW_DESC1rTr�ZPACKAGES_WINDOW_DESC2�packagesButtonryZPACKAGES_WINDOW_UNCHECKZCheckboxTree�packageListZPACKAGES_WINDOW_PKGLIST�pwin�Scale�scaler�r�rrwrZgetInstalledPackageListr�r�rPr�rr�rS)	rZrrJrLr[r�r�r6�packagerrrr]EsJ







zPackagesWindow.__init__cCs4|jjt|d|d��|jj�|jj�dS)Ng�?r�)r�r~�intr�r�rr�)rZ�amount�totalrrr�setScale{s
zPackagesWindow.setScalecCsH|jj�|j_|jj�}x*|jjD]}|d|kr"|jjj|�q"WdS)Nrb)r�r�rJ�includePackagesr�ZgetSelection�selectedPackagesr�)rZZ	selectionZpkgrrrr^�s

zPackagesWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %sr_rC)r`rarbrYrcrSrd)rZrer1rrrrf�s
zPackagesWindow.runN)r=r>r?rbr]r�r^rfrrrrr�Bs
6r�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�
SendWindowcCs�||_||_tjj�}tj|tt�dd�}tj|ddtt	��}|j
|dd�tj|tt�dftt
�dftt�dfg�|_|j
|jddd	dd�||_dS)
NrrBr�rCrqrr)rHrD)rrrr)rrJrrKrLrNrZSEND_WINDOWr�ZSEND_WINDOW_DESCrTrPr�rr�rSrY)rZrrJrLr[r�rrrr]�s


zSendWindow.__init__cCsdS)Nr)rZrrrr^�szSendWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %sr_rC)r`rarbrYrcrSrd)rZrer1rrrrf�s
zSendWindow.runN)r=r>r?rbr]r^rfrrrrr��sr�c@s0eZdZdZdd�Zdd�Zdd�Zdd�Zd	S)
�
SendingWindowcCsP||_||_tjj�}tj|tt�dd�|_tj	dd�|_
|jj|j
dd�dS)Nrrpr�r)rrJrrKrLrNrZSENDING_WINDOWr�r�r�rT)rZrrJrLrrrr]�s
zSendingWindow.__init__c%Cs�tjd|j�|jj�|jj�d}yPtjdt|jj	��t
j|jj|jj
|jj|jj	d�}|j}t|d�}W�n(tjk
r�tj�d}t|jtd�|j�Yn�tjk
r�tj�d}t|jtd�|j�Yn�tjk
�rtj�d}t|jtd�|j�Yn�tjk
�rVtj�d}t|jtd�|j�YnLtjk
�rxt|jt�Yn*tjtj��t|jtd��YnXt
j|��s�t|jtd��|jdd	�t
j �|_!|jd
d	�|jj"�rbyt
j#||jj$�Wnbtjk
�r8tj�d}t|jtd�|j�Yn*tjtj��t|jtd��YnX|jd
d	�|jj%�r�yt
j&||jj'�Wnbtjk
�r�tj�d}t|jtd�|j�Yn*tjtj��t|jtd��YnXd}yt(j)�}Wn,tjk
�r,t|jtj�d�YnXt
j*|�yt
j+�\|j_,|j_-WnHt.k
�r�tj�d}t/|jtd�t0t1f|j�d|j_2YnXt
j3�|jd	d	�|jj4�||j_5dS)Nz
Running %szother is %s)r�rArzProblem registering system:
zProblem registering system.z&Problem writing out system id to disk.rhrBz"Problem sending hardware profile:
z!Problem sending hardware profile.rjzProblem sending package list:
zProblem sending package list.z%Could not open %s
%s is not enabled.
rC)6r`rarbr�r�rr��strrJr�rZregisterSystem2r�r�r�ZrawDictrrr3rr5r!rVrZRhnUuidUniquenessErrorZInsuffMgmntEntsErrorZRegistrationDeniedErrorZActivationKeyUsageLimitErrorZACT_KEY_USAGE_LIMIT_ERRORZ
log_exceptionZ
writeSystemIdr�Z
getOemInfo�oemInfor�ZsendHardwarerr�ZsendPackagesr�rZupdateLoginInfoZsendVirtInfoZpluginEnable�pm_plugin_present�pm_plugin_conf_changed�IOErrorr#rr�pm_plugin_conf_errorZspawnRhnCheckForUIr��reg_info)rZr�ZsystemIdr:Zlirrrrf�s�








zSendingWindow.runcCsdS)Nr)rZrrrr^.szSendingWindow.saveResultscCs4|jjt|d|d��|jj�|jj�dS)Ng�?r�)r�r~r�r�r�rr�)rZr�r�rrrr�1s
zSendingWindow.setScaleN)r=r>r?rbr]rfr^r�rrrrr��s

kr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�FinishWindowcCs�||_||_tjj�}tj|tt�dd�}tj|ddtt	��}|j
|dd�tj|ttd��dfg�|_
|j
|j
ddddd�||_dS)	NrrBr�ZFinishrC)rHrD)rrrr)rrJrrKrLrNrZ
FINISH_WINDOWr�ZFINISH_WINDOW_TEXT_TUIrTrPrVrSrY)rZrrJrLr[r�rrrr]:s
zFinishWindow.__init__cCsdS)Nr)rZrrrr^MszFinishWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %sr_rC)r`rarbrYrcrSrd)rZrer1rrrrfQs
zFinishWindow.runN)r=r>r?rbr]r^rfrrrrr�7sr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�ReviewWindowc
Cs"||_||_|j|_tjj�}tj|tt�dd�}d}|jj	sJ|t
d7}|jjr^|td7}|jj
rr|td7}|td7}t|jd�dkr�d}x|jdD]}||d7}q�Wtdtdd}tjd	|jj�|t7}|||d7}t|jd
�dk�rld}	xP|jd
D]B}
|
dk�r2|	td7}	n$|
dk�rJ|	td7}	n|	|
d7}	�qW|t|	d7}t|jd
�dk�r�d}x|jd
D]}||7}�q�W|t|7}tj|dd|ddt|�dd�|_|j|jdddd�tj|tt�dfg�|_ |j|j ddddd�||_!dS)NrrBrnz

r�rr$z%s
zserver type is %s Zsystem_slotsZenterprise_entitledZvirtualization_hostZuniversal_activation_keyrir�)rHrC)rHrD)rrrr)rrrr)"rrJr�rrKrLrNrZ
REVIEW_WINDOWr�ZPM_PLUGIN_WARNINGr�ZPM_PLUGIN_CONF_ERRORr�ZPM_PLUGIN_CONF_CHANGEDZREVIEW_WINDOW_PROMPTr�ZCHANNELS_TITLEZOK_CHANNELSr`ra�
serverTypeZCHANNELS_SAT_WARNINGZ
MANAGEMENTZVIRTZSLOTSZACTIVATION_KEYrUZ
review_windowrTrPrrSrY)
rZrrJrLr[Zreview_window_textZchannel_listr�r�Z	slot_listZslotZact_key_listZact_keyrrrr]]sT


(zReviewWindow.__init__cCsdS)Nrr)rZrrrr^�szReviewWindow.saveResultscCsNtjd|j�|jj�}|jj|�}|dkr2d}|jjs>d}|jj	rJd}|S)Nz
Running %sr_rCr )
r`rarbrYrcrSrdrJr�r�)rZrer1rrrrf�s
zReviewWindow.runN)r=r>r?rbr]r^rfrrrrr�Zs?r�c@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
�TuiZRHN_REGISTER_TUIcCs�||_||_tjj�|_|j�d|_ytj�|_	Wn$t
jk
rXt|t
d��YnXtttttttttttttg
|_tj�d|_tds�tj dd�td|_!dS)Nrz"You specified an invalid protocol.z Only https and http are allowed.r�z'/usr/share/rhn/CLN-ORG-TRUSTED-SSL-CERTzBYou specified an invalid protocol.Only https and http are allowed.)"rrIrrKrL�	drawFramersrZ
getServerTyper�rZInvalidProtocolErrorr!rVr�r@r�rgr�r�r�r�r�r�r�r�r��windowsr
r4rWrwr~r�)rZrrIrrrr]�s6zTui.__init__cCs|jj�dS)N)rr)rZrrr�__del__�szTui.__del__cCs4t|_|jjddt|j��|jjttd���dS)NrzL  <Tab>/<Alt-Tab> between elements  |  <Space> selects  |  <F12> next screen)ZCOPYRIGHT_TEXTZwelcomeTextrZdrawRootTextrZpushHelpLinerV)rZrrrr��sz
Tui.drawFramecCs~d|_d|_i|_ddddddddddd�
|_i|_d|jd<d|_d|_d|_d|_d|_	g|_
g|_d|_d|_
d|_dS)Nrn)
Zentitlement_numZregistration_numZ
first_name�	last_nameZcompanyZaddressZcity�state�zipZcountryZregistration_numberrr)r�r�r�ZproductInfor�r�r�r�r�r�r�r�r�r�r�)rZrrr�initResults�s2

zTui.initResultscCsRtjd|j�|j�d}�z"d}�x|t|j�k�r<d}y|j||j|�}Wn0tk
r�|dkrt|d}n|d}w(YnXtjd|�|j�}tjd|�|dkr�|dkr�|d}|dkr�|j|jt	jkr�|d8}d}q(|d	kr�dS|d
k�rtjd�t
|j�dk�r:dSq(|dkr(|d}|j�d}q(WWd|jj�XdS)
Nz
Running %sZforwardrrzindex is %sz	Result %srqZbackwardr rrzCaught a cancel requestrC)
r`rarbr�r�r�rr<rfr�r2r^r)rZ�	direction�index�winrerrrrf�sF


zTui.runN)	r=r>r?rbr]r�r�r�rfrrrrr��s!!r�cCs~d}tjtjtj�ttj�dkrBtjddks>tjddkrBd}tj�}t�dkrh|rht	|t
d��t||�}|j�dS)Nrrz-tz--testz2You must run the RHN registration program as root.)
�signal�SIGINT�SIG_IGNr�r�argvrZSnackScreenrr!rVr�rf)rIrrJrrr�main5s
r��__main__)<�osrr�gettextZtranslation�t�hasattrrrVrr�Zup2date_clientrrrrrr	r
Zup2date_client.configrrZrhnr
Zrhn.connectionsrZrhn.i18nrZup2date_client.pmPluginrrZup2date_client.rhnreg_constantsZinitLogr`ZinitUp2dateConfigrwrr!r#r2r;�	Exceptionr<r@rgr�r�r�r�r�r�r�r�r�r�r�r�r�r�r=rrrr�<module>sd
/w)4))w~P$#S	
__pycache__/getMethod.cpython-36.pyc000064400000004401150516774040013332 0ustar003

c8h��@s�ddlZddlZddlZddlmZyddlmZWnek
rLeZYnXGdd�de	�Z
dd�Zdd	�Ze
d
kr�ddd
dddddgZxleD]dZede�yeed�ZWn>e
k
r�ej�dZededjeeej��f�Yq�Xe�q�WdS)�N)�
raise_with_tb)�	ClassTypec@seZdZdZdS)�GetMethodExceptionzException classN)�__name__�
__module__�__qualname__�__doc__�r	r	�/usr/lib/python3.6/getMethod.pyrsrcCsrtjtj}|tjd}xR|D]J}t|�s4td��x |D]}||kr:td|��q:W|d|kr td��q WdS)N�_zEmpty method componentz)Invalid character '%s' in the method namerz6Method names should start with an alphabetic character)�stringZascii_lowercaseZascii_uppercaseZdigits�lenr)�methodNameCompsZalphaZallowedChars�comp�cr	r	r
�sanitys

rc
Csz|jd�|jd�}t|�x~tt|�dd
�D]^}dj|d|��}yt|�}Wn8tk
rfw.Yn$tk
r�tt	d|��YnXPq.Wt	d|��|}|}x�tdt|��D]�}||}||k�r�t
||�s�t	ddj|d|��|f��t||�}q�t
|d��s$t	ddj|d|����t|d�}	||	k�rVt	d	dj|d|��|f��t||�}t|�t
kr�|�}q�W|S)N�.r�zCould not import module %szAction %s could not be importedzClass %s has no attribute %sZ
__rhnexport__zClass %s is not RHN-compliantzClass %s does not export '%s'���)�splitr�ranger
�join�
__import__�ImportError�	Exceptionrr�hasattr�getattr�typer)
Z
methodNameZ	baseClassr�indexZ
modulenameZactionsZfIndexZ	classNamerZexportr	r	r
�	getMethod.sB






r�__main__za.b.c.d.e.fza.b.c.d.e.foo.hz
a.b.c.d.e.g.hz
a.b.d.d.e.g.hza.b.d.d._e.g.hza.b.d.d.e_.g.hza.b.d.d.e-.g.hza.b.d.d..g.hz----Running method %s: ZActionsrzError getting the method %s: %s�)�osr�sysZrhn.tbr�typesrrrrrrrr�methods�m�print�method�exc_info�er�map�str�argsr	r	r	r
�<module>
s8
=
__pycache__/up2dateErrors.cpython-36.opt-1.pyc000064400000032511150516774040015115 0ustar003

c8h)�!@s�ddlZejddd�Zeed�s(eje_ejZddlZddlmZddl	m
Z
ddl	mZdd	lm
Z
ddlZejd
d�ejdd
�e_yddlmZWnJek
r�yddlmZWn$ek
r�Gd
d�de�ZYnXYnXGdd�de�ZGdd�de�ZyddlmZWnBek
�rZyddlmZWnek
�rTeZYnXYnXGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGd d!�d!e�ZGd"d#�d#e�Z Gd$d%�d%e�Z!Gd&d'�d'e�Z"Gd(d)�d)e!e�Z#Gd*d+�d+e!�Z$Gd,d-�d-e!e�Z%Gd.d/�d/e%�Z&Gd0d1�d1e�Z'Gd2d3�d3e!�Z(Gd4d5�d5e!�Z)Gd6d7�d7e!e�Z*Gd8d9�d9e!e�Z+Gd:d;�d;e!e�Z,Gd<d=�d=e�Z-Gd>d?�d?e!�Z.Gd@dA�dAe�Z/GdBdC�dCee�Z0GdDdE�dEe�Z1GdFdG�dGe%�Z2GdHdI�dIe�Z3GdJdK�dKe�Z4GdLdM�dMe!�Z5GdNdO�dOe!�Z6GdPdQ�dQe!�Z7GdRdS�dSe!�Z8GdTdU�dUe!�Z9GdVdW�dWe�Z:GdXdY�dYe!�Z;GdZd[�d[e!�Z<dS)\�Nzrhn-client-toolsT)Zfallback�ugettext)�ustr)�config)�
up2dateLog)�getPlatform�)�YumBaseError)�Errorc@s$eZdZdd�Zdd�Zdd�ZdS)�PmBaseErrorcCs
||_dS)N)�value)�self�errmsg�r�#/usr/lib/python3.6/up2dateErrors.py�__init__-szPmBaseError.__init__cCsttd�|jj|f��dS)Nzclass %s has no attribute '%s')�AttributeError�_�	__class__�__name__)r�namerrr�__getattr__/szPmBaseError.__getattr__cCs"|dkr||jd<n
||j|<dS)Nr
r)r
r)�__dict__)rrrrrr�__setattr__1szPmBaseError.__setattr__N)r�
__module__�__qualname__rrrrrrrr
,sr
c@s4eZdZdZdZdd�Zdd�Zdd�Zd	d
�ZdS)r	zbase class for errors�cCs2t|�}tj||�d|j||_tj�|_dS)Nzrhn-plugin: )rr
r�premsgrrZinitLog�log)rr
rrrr;szError.__init__cCs|jj|j�|jS)N)rZlog_mer)rrrr�__repr__AszError.__repr__cCsT|dkr|jSttd�r$tj||�S||jkr8|j|Sttd�|jj|f��dS)zG Spacewalk backend still use errmsg, let have errmsg as alias to value r
rzclass %s has no attribute '%s'N)	r�hasattrr
rrrrrr)rrrrrrEs


zError.__getattr__cCs<|dkr||jd<n$ttd�r.tj|||�n
||j|<dS)zG Spacewalk backend still use errmsg, let have errmsg as alias to value r
rrN)rrr
r)rrrrrrrSs

zError.__setattr__N)	rrr�__doc__rrrrrrrrrr	8sr	c@seZdZdS)�DebAndSuseRepoErrorN)rrrrrrrr!^sr!)�	RepoErrorc@seZdZdZed�ZdS)�RpmErrorz$rpm itself raised an error conditionzRPM error.  The message was:
N)rrrr rrrrrrr#jsr#c@seZdZdS)�RhnServerExceptionN)rrrrrrrr$nsr$c@seZdZdZed�ZdS)�
PasswordErrorz@Raise when the server responds with that a password is incorrectz!Password error. The message was:
N)rrrr rrrrrrr%qsr%c@s"eZdZdZed�Zddd�ZdS)�DependencyErrorz7Raise when a rpm transaction set has a dependency errorz'RPM dependency error. The message was:
NcCstj||�||_dS)N)r	r�deps)r�msgr'rrrrxszDependencyError.__init__)N)rrrr rrrrrrrr&usr&c@seZdZdZed�ZdS)�CommunicationErrorzDIndicates a problem doing xml-rpc http communication with the serverz2Error communicating with server. The message was:
N)rrrr rrrrrrr)sr)c@seZdZdZed�ZdS)�FileNotFoundErrorzR
    Raise when a package or header that is requested returns
    a 404 error codezFile Not Found: 
N)rrrr rrrrrrr*�sr*c@seZdZdZed�ZdS)�
DelayErrorzO
    Raise when the expected response from a xml-rpc call
    exceeds a timeoutz+Delay error from server.  The message was:
N)rrrr rrrrrrr+�sr+c@s eZdZdZdd�Zdd�ZdS)�RpmRemoveErrorzP
    Raise when we can't remove a package for some reason
    (failed deps, etc)cCs`tj|d�||_x@|jj�D]2}t|j|�|j|<|jd||j|f|_qW|j|_dS)Nrz%s failed because of %s
)r	r�args�keysrr�data)rr-�keyrrrr�szRpmRemoveError.__init__cCs|jS)N)r)rrrrr�szRpmRemoveError.__repr__N)rrrr rrrrrrr,�sr,c@seZdZdd�Zdd�ZdS)�
NoLogErrorcCst|�}|j||_dS)N)rrr)rr(rrrr�szNoLogError.__init__cCs|jS)N)r)rrrrr�szNoLogError.__repr__N)rrrrrrrrrr1�sr1c@seZdZdS)�
AbuseErrorN)rrrrrrrr2�sr2c@seZdZdS)�AuthenticationTicketErrorN)rrrrrrrr3�sr3c@seZdZdS)�AuthenticationErrorN)rrrrrrrr4�sr4c@seZdZdZed�ZdS)�ValidationErrorz1indicates an error during server input validationz!Error validating data at server:
N)rrrr rrrrrrr5�sr5c@seZdZdS)�InvalidRegistrationNumberErrorN)rrrrrrrr6�sr6c@s$eZdZdd�Zdd�Zdd�ZdS)�RegistrationDeniedErrorcCstj||j��dS)N)r$r�changeExplanation)rrrrr�sz RegistrationDeniedError.__init__cCs|jS)N)r)rrrrr�sz RegistrationDeniedError.__repr__cCstd�S)Nz�
CloudLinux Network Classic is not supported.
To register with CloudLinux Subscription Management please run:

    subscription-manager register --auto-attach

Get more information at www.cloudlinux.com
    )r)rrrrr8�sz)RegistrationDeniedError.changeExplanationN)rrrrrr8rrrrr7�sr7c@seZdZdZed�ZdS)�InvalidProductRegistrationErrorz1indicates an error during server input validationz"The installation number is invalidN)rrrr rrrrrrr9�sr9c@seZdZed�ZdS)�OemInfoFileErrorz)Error parsing the oemInfo file at field:
N)rrrrrrrrrr:�sr:c@seZdZdZdS)�NoBaseChannelErrorz/No valid base channel was found for this systemN)rrrr rrrrr;�sr;c@seZdZdS)�UnknownMethodExceptionN)rrrrrrrr<�sr<c@seZdZdS)�RhnUuidUniquenessErrorN)rrrrrrrr=�sr=c@seZdZddd�Zdd�ZdS)�ServerCapabilityErrorNcCs tj||�g|_|r||_dS)N)r	r�	errorlist)rr(r?rrrr�szServerCapabilityError.__init__cCs|jS)N)r)rrrrr�szServerCapabilityError.__repr__)N)rrrrrrrrrr>�s
r>c@seZdZdS)�NoChannelsErrorN)rrrrrrrr@�sr@c@seZdZdZed�ZdS)�NetworkErrorzD some generic network error occurred, e.g. connection reset by peer zNetwork error: N)rrrr rrrrrrrA�srAc@seZdZdd�ZejZdS)�SSLCertificateVerifyFailedErrorcCsftj�}|d}t|d�}|j�}|j�tjjtjj|�}|j	�rVt
j|d|�nt
j|d�dS)NZ	sslCACert�rznThe certificate %s is expired. Please ensure you have the correct certificate and your system time is correct.z(The SSL certificate failed verification.)rZinitUp2dateConfig�open�read�close�OpenSSLZcryptoZload_certificateZFILETYPE_PEMZhas_expiredr"r)rZ
up2dateConfigZcertFile�fZbufZtempCertrrrr�s

z(SSLCertificateVerifyFailedError.__init__N)rrrrr	rrrrrrB�srBc@seZdZdS)�SSLCertificateFileNotFoundN)rrrrrrrrI�srIc@seZdZdZdS)�$AuthenticationOrAccountCreationErrora%Class that can represent different things depending on context:
    While logging in with an existing user it represents a username or password
    being incorrect.
    While creating a new account, it represents the username already being
    taken or the user not being allowed to create an account.
    Optimally these different things would be different exceptions, but there
    are single fault codes the server can return to the client that can mean
    more than one of them so we have no way of knowing which is actually
    intended.

    N)rrrr rrrrrJsrJc@seZdZdS)�NotEntitlingErrorN)rrrrrrrrKsrKc@seZdZdS)�InvalidProtocolErrorN)rrrrrrrrLsrLc@seZdZdS)�UnableToCreateUserN)rrrrrrrrMsrMc@seZdZdS)�ActivationKeyUsageLimitErrorN)rrrrrrrrNsrNc@seZdZdS)�LoginMinLengthErrorN)rrrrrrrrOsrOc@seZdZdS)�PasswordMinLengthErrorN)rrrrrrrrPsrPc@seZdZdS)�PasswordMaxLengthErrorN)rrrrrrrrQ!srQc@s$eZdZdd�Zdd�Zdd�ZdS)�InsuffMgmntEntsErrorcCstj||j|��dS)N)r$rr8)rr(rrrr&szInsuffMgmntEntsError.__init__cCs|jS)N)r)rrrrr)szInsuffMgmntEntsError.__repr__cCs.td�}d}|j|�t|�}|d|�|S)Na�
    Your organization does not have enough Management entitlements to register this
    system to CloudLinux Network. Please notify your organization administrator of this error.
    You should be able to register this system after your organization frees existing
    or purchases additional entitlements. Additional entitlements may be purchased by your
    organization administrator by logging into CloudLinux Network and visiting

    A common cause of this error code is due to having mistakenly setup an
    Activation Key which is set as the universal default.  If an activation key is set
    on the account as a universal default, you can disable this key and retry to avoid
    requiring a Management entitlement.zExplanation:)r�rindex�len)rr(ZnewExplnZterm�locrrrr8,s

z&InsuffMgmntEntsError.changeExplanationN)rrrrrr8rrrrrR%srRc@seZdZdS)�NoSystemIdErrorN)rrrrrrrrV<srVc@seZdZdZdS)�InvalidRedirectionErrorz7 Raise when redirect requests could'nt return a packageN)rrrr rrrrrW?srW)=�gettextZtranslation�trrrrGZrhn.i18nrZup2date_clientrrZup2date_client.pkgplatformr�sys�pathZ
yum.Errorsrr
�ImportErrorZdnf.exceptionsr	�	Exceptionr!r"r#r$r%r&r)r*r+r,r1r2r3r4r5r6r7r9r:r;r<r=r>r@rArBrIrJrKrLrMrNrOrPrQrRrVrWrrrr�<module>s~
&

__pycache__/rhnPackageInfo.cpython-36.pyc000064400000003202150516774040014267 0ustar003

c8h\	�@sVddlmZddlmZddlmZddlmZdd�Zddd	�Zd
d�Zdd
�ZdS)�)�up2dateAuth)�
up2dateLog)�	rhnserver)�pkgUtilscCs8tj�}|jdt|d��|jdt|d��dS)Nz&Adding packages to package profile: %sZaddedz*Removing packages from package profile: %sZremoved)rZinitLogZlog_me�pprint_pkglist)Zpkgs�log�r�$/usr/lib/python3.6/rhnPackageInfo.py�logDeltaPackagess
r
NcCsdS)z; get a list of installed packages and send it to rhnServer Nr)Ztimeoutrrr	�updatePackageProfilesrcCs>t|�tg�kr dd�|D�}nd|d|d|df}|S)NcSs&g|]}d|d|d|df�qS)z%s-%s-%sr��r)�.0�arrr	�
<listcomp>'sz"pprint_pkglist.<locals>.<listcomp>z%s-%s-%srrr
)�type)Zpkglist�outputrrr	r%src	Cs�g}x�|D]�}d|krNd|krN|j|d|d|d|d|d|dg�q
d|kr�|j|d|d|d|d|dg�q
|j|d|d|d|dg�q
W|S)z� takes list of hashes and covert it to list of lists
        resulting strucure is:
        [[name, version, release, epoch, arch, cookie], ... ]
    ZarchZcookie�name�version�releaseZepoch)�append)Zpackages�result�packagerrr	�convertPackagesFromHashToList,s
&r)N)	Zup2date_clientrrrrr
rrrrrrr	�<module>s
__pycache__/haltree.cpython-36.pyc000064400000006104150516774040013040 0ustar003

c8h"�@sRyddlmZmZWnek
r0eZeZYnXGdd�d�ZGdd�d�ZdS)�)�
StringType�IntTypec@s eZdZdZdd�Zdd�ZdS)�	HalDevicez5An object containing its udi, properties and childrencCs@|d|_||_g|_d|_d|kr0|d|_nd|_d|_dS)Nzinfo.udizinfo.parent)�udi�
properties�children�classification�
parent_udi�parent)�selfr�r�/usr/lib/python3.6/haltree.py�__init__"s
zHalDevice.__init__cCs6t|jd�x$|jj�D]\}}td|d|�qWdS)N�:z    z ==> )�printrr�items)r�property�valuerrr
�print_properties0szHalDevice.print_propertiesN)�__name__�
__module__�__qualname__�__doc__rrrrrr
r src@sHeZdZdd�Zdd�Zdd�Zdd�Zed	d
��Zdd�Z	d
d�Z
dS)�HalTreecCsd|_g|_dS)N)�head�
no_parent_yet)rrrr
r9szHalTree.__init__cCsL|jr8|j|j�}|r*|jj|�||_q>|jj|�n||_|j|�dS)N)r	�_HalTree__find_noder�appendr
rr�_HalTree__get_lost_children)r�
hal_devicer
rrr
�add>szHalTree.addcCsRg}g}|jdd�}x6|D].}|j|jkr||_|jj|�|jj|�qWdS)N)rr	rr
rr�remove)rrZ
found_listZindexesZno_parent_yet_copyZdevrrr
Z__get_lost_childrenMs
zHalTree.__get_lost_childrencCsD|jrtj|j|�}|r|Sx"|jD]}tj||�}|r$|Sq$WdS)zo
        This takes a node in the HalDevice tree and returns the HalDevice with
        the given udi.
        N)rr�_HalTree__find_node_workerr)rr�nodeZ
found_noderrr
Z__find_nodeWszHalTree.__find_nodecCs6|j|kr|Sx"|jD]}tj||�}|r|SqWdS)N)rrrr")r#rZdevice�resrrr
Z__find_node_workergs
zHalTree.__find_node_workercCs|j|jd�dS)N�)�_HalTree__print_dev_treer)rrrr
�
print_treeqszHalTree.print_treecCs�t||j�t|d|j�x�|jj�D]�\}}t|�tkrz|j�rbt|dd|tt	|��f�q�t|dd||f�q&t|�t
kr�t|dd|tt	|��f�q&t|dd||f�q&Wtx|jD]}|j||d�q�WdS)NzCLASS:z    z%-20s ==> %s)
rrrrr�typer�isdigit�hex�intrrr&)rr#�indent�namerZchildrrr
Z__print_dev_treets  zHalTree.__print_dev_treeN)rrrrr rr�staticmethodr"r'r&rrrr
r8s

rN)�typesrr�ImportError�bytesr+rrrrrr
�<module>s
__pycache__/hardware_udev.cpython-36.pyc000064400000017263150516774040014244 0ustar003

c8h�3�@sDddlZddlZddlZddlmZmZdd�Zdd�ZdZdZ	d	Z
d
ZdZdZ
d
ZdZdZd	Zd
ZdZd
ZdZdZd	Zd
Zd
ZdZdZd	Zd
Zd
ZdZdZ d	Z!d
Z"dZ#dZ$dZ%dZ&dZ'dZ(d
Z)dZ*dZ+d	Z,d
Z-dZ.d
Z/dZ0dZ1d	Z2d
Z3dZ4dZ5d
Z6dZ7dZ8d	Z9d
Z:dZ;dZ<dZ=dd�Z>dd�Z?dd�Z@dd �ZAd!d"�ZBd#d$�ZCdS)%�N)�PCI�USBc
CsFtj�}|j�}g}�x*|jd�jd�jd�jd�jd�D�]}|j}||jt|�dt|�t|�d�}|dd	krzd
|d<|dd	kr�d|d<|dkr�t	|d
�r�t	|d
�|d<|j
|d<|jdkr�q:t	|d�r�q:t	|d�dkr�q:t	|d�dkr�q:n�|dk�rJt	|d�}|�r"|jd�\|d<|d<t	|d�}|�r�|jd�\|d<|d<n>|dk�r�t	|d��rnt	|d�|d<t	|d��r�t	|d�|d<t	|d
��r4t	|d
�dk�r4t	|d��s�t	|d��r4t	|d��r�t	|d�}t
jd |�}	nt	|d�}t
jd!|�}	|	�r4|	jd"�|d<|	jd#�|d<|	jd$�|d<|	jd%�|d<|j|�q:W|S)&aE Returns list of dictionaries with keys for every device in system
        (values are provide as example):
        'bus' : 'pci'
        'driver' : 'pcieport-driver'
        'pciType' : '1'
        'detached' : '0'
        'class' : 'OTHER'
        'desc' : 'Intel Corporation|5000 Series Chipset PCI Express x4 Port 2'
    �pci�usb�blockZccw�scsi�0)�bus�driverZpciTypeZdetached�classZdescrN�OTHERr
�unknownZID_BUSr	�device�	partitionZDM_NAMEZMAJOR�1�7�PCI_ID�:Zprop1Zprop2Z
PCI_SUBSYS_IDZprop3Zprop4�ID_VENDOR_ID�ID_MODEL_IDZID_PATHZDEVPATHz.*scsi-(\d+):(\d+):(\d+):(\d+)z!.*/(\d+):(\d+):(\d+):(\d+)/block/����)�pyudevZContextZlist_devicesZmatch_subsystem�	subsystemr
�_clasify_pci_type�_clasify_class�_get_device_desc�_get_device_propertyZsys_name�device_type�split�re�search�group�append)
�contextZdevices�resultrrZresult_item�	pci_classZ
pci_subsys�path�m�r+�#/usr/lib/python3.6/hardware_udev.py�get_devicessj,









r-cCs$tj�}|d|d|dd�}|S)z� Return dictionaries with keys (values are provided as example):
        'system.formfactor': 'unknown'
        'system.kernel.version': '2.6.18-128.1.6.el5xen'
            'system.kernel.machine': 'i686'
        'system.kernel.name': 'Linux'
    rrr)zsystem.kernel.namezsystem.kernel.versionzsystem.kernel.machine)�os�uname)r/r'r+r+r,�get_computer_infobs
r0rZ00Z01Z02Z03Z04Z80�2�3�4�6Z05Z06Z07Z08r�9�CcCs|dkrdSdSdS)z) return 1 if device is PCI, otherwise -1 rrz-1Nr+)rr+r+r,r�srcCs,y|jj|�Stk
r&|j|�SXdS)zS return the property of the given device independent of the implementation version N)Z
properties�get�AttributeError)rZpropr+r+r,r�srcCs:tt|d��\}}|j}|tkr$dS|tkrD|tkr8dS|tkrDdSt|d�}|rr|j�}d|krfdSd|krrdS|�rX|tkr�dS|t	kr�|t
kr�d	S|tkr�d
Sn�|tkr�|t
kr�dS|tkr�dS|tkr�d
S|tkr�dSnx|tko�|tk�r�dS|tk�r|tk�rdS|tk�r6|tk�r&dS|tk�rXdSn"|tk�rX|tk�sT|tk�rXdS|dk�r�t|d��s�t|d��r�t|d�dk�r�dSdSn|dk�r�dS|dk�r�|jdk�r�t|�}|dk�s�|dk�r�dS|dk�r�d S|d!k�r�dSdStjd"|j�}|�rd#S|dk�rdS|d$k�s2|d%k�r6dSd&S)'a Clasify type of device. Returned value is one of following string:
        NETWORK, KEYBOARD, MOUSE, VIDEO, USB, IDE, SCSI, RAID, MODEM, SCANNER
        CAPTURE, AUDIO, FIREWIRE, SOCKET, CDROM, HD, FLOPPY, TAPE, PRINTER, OTHER
        or None if it is neither PCI nor USB device.
    Z	PCI_CLASSrZKEYBOARDZMOUSEZ	ID_SERIALZkeyboardZmouseZVIDEOrZFIREWIREZIDEZSCSIZRAIDZFLOPPYZMODEMZSCANNERZCAPTUREZAUDIOZSOCKETrZID_CDROMZID_TYPEZcdZCDROMZHDZsoundrZscsi_devicer�rZTAPE�z	.*/lp\d+$ZPRINTERrrN)�_parse_pci_classrr�PCI_BASE_CLASS_NETWORK�PCI_BASE_CLASS_INPUT�PCI_CLASS_INPUT_KEYBOARD�PCI_CLASS_INPUT_MOUSE�lower�PCI_BASE_CLASS_DISPLAY�PCI_BASE_CLASS_SERIAL�PCI_CLASS_SERIAL_USB�PCI_CLASS_SERIAL_FIREWIRE�PCI_BASE_CLASS_STORAGE�PCI_CLASS_STORAGE_IDE�PCI_CLASS_STORAGE_SCSI�PCI_CLASS_STORAGE_RAID�PCI_CLASS_STORAGE_FLOPPY�PCI_BASE_CLASS_COMMUNICATION�PCI_CLASS_COMMUNICATION_MODEM�PCI_CLASS_INPUT_SCANNER�PCI_BASE_CLASS_MULTIMEDIA�PCI_CLASS_MULTIMEDIA_VIDEO�PCI_CLASS_MULTIMEDIA_AUDIO�PCI_BASE_CLASS_BRIDGE�PCI_CLASS_BRIDGE_PCMCIA�PCI_CLASS_BRIDGE_CARDBUSr �_get_scsi_dev_typer"r#�sys_path)rZ
base_classZ	sub_classrZ	id_serialZdev_typer*r+r+r,r�s�










rc	CsL|j}d}d}|dkrLt|d�jd�\}}t�}d|j|�|j||�f}n�|dk�r&t|d�}t�}|r�d|j|�|j|t|d��f}n�|jd	kr�|jd
kr�d}n|jdkr�d
}nd}nh|jdko�t|d��r:t|d�jd�dd�\}}dt	|d�}dt	|d�}d|j|�|j||�f}n|dk�r:t|d�}|�rD|SdSdS)z. Return human readable description of device. Nrrrz%s|%srrrZ
usb_interfaceZusbhidzUSB HID InterfaceZhubzUSB Hub Interfacez
USB InterfaceZ
usb_deviceZPRODUCT�/rz%.4x�rZID_MODEL�)
rrr!rZ
get_vendorZ
get_devicerr r
�int)	rrZcommandr'Z	vendor_idZ	device_idrrZmodel_idr+r+r,r s8

"




rcCs(|dkrdS|dd�|dd	�fSdS)
a= Parse Class Code. Return touple of
        [base class code, sub-class code]
        You are usually interested to only first two.
        The third - "specific register-level programming interface" is ignored.
        For details, see the PCI Local Bus Specification 2.1/2.2 Section 6.2.1 Device Identification
    N�rr)NNi�������rZ���r+)r(r+r+r,r;Bsr;cCs>ytd|jd�}Wntk
r(dSX|j�}|j�|S)zQ Return SCSI type of device in raw format as presented in /sys/...devpath../type z%s/type�rr���)�openrT�IOError�readline�close)r�fr'r+r+r,rSNsrS)Drr.r"Zhwdatarrr-r0rErGrFrIZPCI_CLASS_STORAGE_IPIrHZPCI_CLASS_STORAGE_OTHERr<ZPCI_CLASS_NETWORK_ETHERNETZPCI_CLASS_NETWORK_TOKEN_RINGZPCI_CLASS_NETWORK_FDDIZPCI_CLASS_NETWORK_ATMZPCI_CLASS_NETWORK_OTHERrAZPCI_CLASS_DISPLAY_VGAZPCI_CLASS_DISPLAY_XGAZPCI_CLASS_DISPLAY_3DZPCI_CLASS_DISPLAY_OTHERrMrNrOZPCI_CLASS_MULTIMEDIA_PHONEZPCI_CLASS_MULTIMEDIA_OTHERrPZPCI_CLASS_BRIDGE_HOSTZPCI_CLASS_BRIDGE_ISAZPCI_CLASS_BRIDGE_EISAZPCI_CLASS_BRIDGE_MCZPCI_CLASS_BRIDGE_PCIrQZPCI_CLASS_BRIDGE_NUBUSrRZPCI_CLASS_BRIDGE_RACEWAYZPCI_CLASS_BRIDGE_OTHERrJZPCI_CLASS_COMMUNICATION_SERIALZ PCI_CLASS_COMMUNICATION_PARALLELZ#PCI_CLASS_COMMUNICATION_MULTISERIALrKZPCI_CLASS_COMMUNICATION_OTHERr=r>ZPCI_CLASS_INPUT_PENr?rLZPCI_CLASS_INPUT_GAMEPORTZPCI_CLASS_INPUT_OTHERrBrDZPCI_CLASS_SERIAL_ACCESSZPCI_CLASS_SERIAL_SSArCZPCI_CLASS_SERIAL_FIBERZPCI_CLASS_SERIAL_SMBUSrrrrr;rSr+r+r+r,�<module>s�M`"__pycache__/haltree.cpython-36.opt-1.pyc000064400000006104150516774040013777 0ustar003

c8h"�@sRyddlmZmZWnek
r0eZeZYnXGdd�d�ZGdd�d�ZdS)�)�
StringType�IntTypec@s eZdZdZdd�Zdd�ZdS)�	HalDevicez5An object containing its udi, properties and childrencCs@|d|_||_g|_d|_d|kr0|d|_nd|_d|_dS)Nzinfo.udizinfo.parent)�udi�
properties�children�classification�
parent_udi�parent)�selfr�r�/usr/lib/python3.6/haltree.py�__init__"s
zHalDevice.__init__cCs6t|jd�x$|jj�D]\}}td|d|�qWdS)N�:z    z ==> )�printrr�items)r�property�valuerrr
�print_properties0szHalDevice.print_propertiesN)�__name__�
__module__�__qualname__�__doc__rrrrrr
r src@sHeZdZdd�Zdd�Zdd�Zdd�Zed	d
��Zdd�Z	d
d�Z
dS)�HalTreecCsd|_g|_dS)N)�head�
no_parent_yet)rrrr
r9szHalTree.__init__cCsL|jr8|j|j�}|r*|jj|�||_q>|jj|�n||_|j|�dS)N)r	�_HalTree__find_noder�appendr
rr�_HalTree__get_lost_children)r�
hal_devicer
rrr
�add>szHalTree.addcCsRg}g}|jdd�}x6|D].}|j|jkr||_|jj|�|jj|�qWdS)N)rr	rr
rr�remove)rrZ
found_listZindexesZno_parent_yet_copyZdevrrr
Z__get_lost_childrenMs
zHalTree.__get_lost_childrencCsD|jrtj|j|�}|r|Sx"|jD]}tj||�}|r$|Sq$WdS)zo
        This takes a node in the HalDevice tree and returns the HalDevice with
        the given udi.
        N)rr�_HalTree__find_node_workerr)rr�nodeZ
found_noderrr
Z__find_nodeWszHalTree.__find_nodecCs6|j|kr|Sx"|jD]}tj||�}|r|SqWdS)N)rrrr")r#rZdevice�resrrr
Z__find_node_workergs
zHalTree.__find_node_workercCs|j|jd�dS)N�)�_HalTree__print_dev_treer)rrrr
�
print_treeqszHalTree.print_treecCs�t||j�t|d|j�x�|jj�D]�\}}t|�tkrz|j�rbt|dd|tt	|��f�q�t|dd||f�q&t|�t
kr�t|dd|tt	|��f�q&t|dd||f�q&Wtx|jD]}|j||d�q�WdS)NzCLASS:z    z%-20s ==> %s)
rrrrr�typer�isdigit�hex�intrrr&)rr#�indent�namerZchildrrr
Z__print_dev_treets  zHalTree.__print_dev_treeN)rrrrr rr�staticmethodr"r'r&rrrr
r8s

rN)�typesrr�ImportError�bytesr+rrrrrr
�<module>s
__pycache__/rhnChannel.cpython-36.pyc000064400000011355150516774040013500 0ustar003

c8h��@s�ddlmZddlmZddlmZddlmZddlmZddlZejddd	�Ze	ed
�sdeje_
ej
ZGdd�d�ZGd
d�d�Z
ddd�ZgZdaddd�Zdd�Zdd�Zdd�ZdS)�)�up2dateAuth)�
up2dateLog)�
up2dateErrors)�config)�	rhnserverNzrhn-client-toolsT)Zfallback�ugettextc@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�
rhnChannelcKs*i|_x|j�D]}|||j|<qWdS)N)�dict�keys)�self�kwargs�kw�r� /usr/lib/python3.6/rhnChannel.py�__init__szrhnChannel.__init__cCs
|j|S)N)r	)r�itemrrr�__getitem__szrhnChannel.__getitem__cCs||j|<dS)N)r	)rr�valuerrr�__setitem__szrhnChannel.__setitem__cCs|jd|jdkS)N�name)r	)r�otherrrr�__lt__!szrhnChannel.__lt__cCs
|jj�S)N)r	r
)rrrrr
$szrhnChannel.keyscCs
|jj�S)N)r	�values)rrrrr'szrhnChannel.valuescCs
|jj�S)N)r	�items)rrrrr*szrhnChannel.itemsN)
�__name__�
__module__�__qualname__rrrrr
rrrrrrrsrc@s<eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
S)�rhnChannelListcCs
g|_dS)N)�list)rrrrr.szrhnChannelList.__init__cCs|jj|�dS)N)r�append)r�channelrrr�
addChannel3szrhnChannelList.addChannelcCs|jS)N)r)rrrr�channels7szrhnChannelList.channelscCs$x|jD]}|d|kr|SqWdS)N�label)r)r�channelnamer rrr�
getByLabel:szrhnChannelList.getByLabelcCs
|j|�S)N)r%)rr$rrr�	getByName>szrhnChannelList.getByNamecCs.g}x$|jD]}|d|kr|j|�qW|S)N�type)rr)rr'r"r rrr�	getByTypeAs
zrhnChannelList.getByTypeN)	rrrrr!r"r%r&r(rrrrr-srcCsdg}t|d�}xP|j�D]D}|ddkrR|d|d<d|d|d|df|d<|j|�qW|S)	N)�timeoutr'�up2dater#rz%s channel %s from  %s�url�description)�getChannelsr"r)r)r"ZsourceChannelsZ
sourceChannelrrr�getChannelDetailsKs
r.c
Cs:tj�}tj�}to|�rt�atj|d�}tj	�sFt
jtd���|j
jtj	��}x�|D]�}|rr|d|krrq\tdtj�d�}x2|j�D]&}	|	dkr�|d|d<q�||	||	<q�W|d�r
|d|d	<|d<|d
<|d<|jd|d	�|jd
�|jd�tj|�q\Wttj�dk�r6t
jtd���tS)zG return rhnChannelList containing list of channel we are subscribed to )r)zUnable to Locate SystemIdr#r*)r'r+Z
last_modified�versionZchannelOverriderr,Zsummaryz'WARNING: Channel overridden locally: %sz=-------: If you see this warning outside of the leapp processz$-------: contact CloudLinux support.rzEThis system may not be updated until it is associated with a channel.)rZinitUp2dateConfigrZinitLog�selected_channelsrr�	RhnServerr�getSystemIdrZNoSystemIdError�_r*ZlistChannelsrZgetServerlURLFromMirrorr
Zlog_mer!�lenrZNoChannelsError)
�force�label_whitelistr)Zcfg�log�sZup2dateChannelsZchanr �keyrrrr-^s2

$

r-cCs dattdd�|��}t|d�S)NcSs|dfS)N�r)�xrrr�<lambda>�szsetChannels.<locals>.<lambda>)r6)r0r	�mapr-)ZtempchannelsZ	whitelistrrr�setChannels�sr>cCstj�}|jjtj�|||�S)N)rr1r*�subscribeChannelsrr2)r"�username�passwdr8rrrr?�sr?cCstj�}|jjtj�|||�S)N)rr1r*�unsubscribeChannelsrr2)r"r@rAr8rrrrB�srB)N)NNN)Zup2date_clientrrrrr�gettextZtranslation�t�hasattrrr3rrr.Zcmdline_pkgsr0r-r>r?rBrrrr�<module>s$


(__pycache__/up2dateUtils.cpython-36.opt-1.pyc000064400000010102150516774040014731 0ustar003

ge8h<�@s�dZddlZddlZddlZddlZddlZddlmZddlmZddl	m
Z
ddlmZej
ddd	�Zeed
�s|eje_ejZe
�dkr�ddlZdd
�ZnddlmZdd
�Zdd�Zdd�Zdd�Zdd�Zdd�Zejdd��ZdS)zutility functions for up2date�N)�
up2dateErrors)�config)�getPlatform)�sstrzrhn-client-toolsT)Zfallback�ugettext�debcCs6tj�}|d}d}d|kr$|d}|d}|||fS)NZIDzn/aZCODENAMEZRELEASE)�lsb_releaseZget_distro_information)Z	dist_infoZos_nameZ
os_version�
os_release�r
�"/usr/lib/python3.6/up2dateUtils.py�_getOSVersionAndReleasesr)�transactioncCs~tj�}�xn|jdd�D]~}d}t|d�}t|d�}|dd�|dD�kr�td	d�t|d|d
�D��}d||f}||}t|d�||f}|SWx�|jdd
�D]�}d}t|d�}t|d�}|dd�|dD�k�rtdd�t|d|d
�D��}d||f}||}t|d�||f}|SWxL|jdd�D]2}t|d�t|d�t|d�f}|jj�|SWtj	d��dS)NZProvidenamezoraclelinux-releasezsystem-release(releasever)�version�releasecss|]}t|�VqdS)N)r)�.0�provider
r
r�	<genexpr>,sz*_getOSVersionAndRelease.<locals>.<genexpr>Zprovidenamecss"|]\}}t|�t|�fVqdS)N)r)r�n�vr
r
rr-sZprovideversionz%s-%s�namezredhat-releasecss|]}t|�VqdS)N)r)rrr
r
rr8scss"|]\}}t|�t|�fVqdS)N)r)rrrr
r
rr9szdistribution-releasezxCould not determine what version of CloudLinux you are running.
If you get this error, try running 

		rpm --rebuilddb

)
r
ZinitReadOnlyTransactionZdbMatchr�dict�zip�tsZcloseDBrZRpmError)r�hZ	SYSRELVERrrZprovidesZosVersionReleaser
r
rr&s:"
cCs,tj�}|drt|d�St�\}}}|S)z3
    Returns the version of redhat-release rpm
    ZversionOverride)rZinitUp2dateConfig�strr)Zcfgr	rrr
r
r�
getVersionLs
rcCst�\}}}|S)z4
    Returns the name of the redhat-release rpm
    )r)r	rrr
r
r�getOSReleaseVsrcCst�\}}}|S)z7
    Returns the release of the redhat-release rpm
    )r)r	rrr
r
r�
getRelease]srcCsztjdtj�r@tdd�}|j�j�}ddi}||kr<||}|Stj�d}t�dkrv|dkrbd
}|dkrnd}|d
7}|S)Nz/etc/rpm/platform�rzia32e-redhat-linuxzx86_64-redhat-linux�r�i486�i586�i686Zi386Zx86_64�amd64z
-debian-linux)r r!r")�os�access�R_OK�open�read�strip�unamer)�fd�platform�replaceZarchr
r
r�getArchds

r.cCsdS)Nz12.12.5-1.module_el8.10.0+6935+f9aadf00.cloudlinuxr
r
r
r
rrysrccs�tj�\}}tjd�}tjd�}tj|d�tj|d�z
dVWdtj|d�tj|d�Xtj|�tj|��<}tjdj|��}x$|D]}|j	|�s�t
|tjd�q�WWdQRXdS)zP
    Context manager to suppress errors
    matching the specified patterns
    ��N�|)�file)
r$�pipe�dup�dup2�close�fdopen�re�compile�join�search�print�sys�stderr)Zerror_patternsZread_endZ	write_endZ
old_stdoutZ
old_stderr�fZcombined_pattern�liner
r
r�suppress_errors~s





rA)�__doc__�
contextlibr$r=r8�gettextZup2date_clientrrZup2date_client.pkgplatformrZrhn.i18nrZtranslation�t�hasattrr�_rrr
rrrr.r�contextmanagerrAr
r
r
r�<module>s0



&
__pycache__/transaction.cpython-36.opt-1.pyc000064400000005135150516774040014703 0ustar003

c8ha�@s8ddlZdadZGdd�d�ZGdd�d�Zdd�ZdS)�Nc@seZdZdd�Zdd�ZdS)�TransactionDatacCs2i|_g|jd<g|jd<g|jd<g|jd<dS)N�packages�flagsZvsflagsZprobFilterFlags)�data)�self�r�!/usr/lib/python3.6/transaction.py�__init__!s



zTransactionData.__init__c	CsFd}g}g}g}g}x\|jdD]N\}}|dkr<|j|�q |dkrP|j|�q |dkrd|j|�q |j|�q Wx0|D](}|d|d|d|d	|d
f}qxWx0|D](}|d|d|d|d	|d
f}q�Wx0|D](}|d|d|d|d	|d
f}q�Wx8|D]0}|d
|d|d|d|d	|d
f}�qW|S)N�r�u�i�ez		[e] %s-%s-%s:%s
r���z		[i] %s-%s-%s:%s
z		[u] %s-%s-%s:%s
z		[%s] %s-%s-%s:%s
�)r�append)r�outZremovedZ	installed�updatedZmiscZpkgInfo�moderrr�display/s.
(
(
(
zTransactionData.displayN)�__name__�
__module__�__qualname__r	rrrrrrsrc@s4eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZdS)�Up2dateTransactioncCs:tj�|_ddddddddd	d
ddd
dddg|_g|_dS)NZdbMatchZcheck�orderZaddEraseZ
addInstallZrunZIDTXloadZIDTXglobZrollbackZpgpImportPubkeyZ
pgpPrtPktsZDebugZsetFlags�
setVSFlagsZ
setProbFilterZhdrFromFdno)�rpmZTransactionSet�ts�_methods�tsflags)rrrrr	Ms$
zUp2dateTransaction.__init__cCs ||jkr|j|�St|��dS)N)r�	getMethod�AttributeError)r�attrrrr�__getattr__as

zUp2dateTransaction.__getattr__cCst|j|�S)N)�getattrr)r�methodrrrr!gszUp2dateTransaction.getMethodcCs"|jj|�|jj|jd�dS)Nr���)r rrr)rrrrr�pushVSFlagsoszUp2dateTransaction.pushVSFlagscCs|jd=|jj|jd�dS)Nrr'r')r rr)rrrr�
popVSFlagssszUp2dateTransaction.popVSFlagsN)rrrr	r$r!r(r)rrrrrLs
rcCstdkrt�atjd�tS)Nrr')�read_tsrr(rrrr�initReadOnlyTransactionws
r+)rr*rrrr+rrrr�<module>
s
.+__pycache__/pmPlugin.cpython-36.pyc000064400000004714150516774040013214 0ustar003

c8h+�@s�ddlZddlZddlZyddlmZdZdZdZWn ek
rTdZdZdZYnXd	d
�Z	dd�Z
d
d�Zdd�Zdd�Z
dd�ZdS)�N)�__version__z/etc/dnf/plugins/spacewalk.confzdnf-plugin-spacewalk�dnfz$/etc/yum/pluginconf.d/rhnplugin.confzyum-rhn-pluginZyumcCsNd}d}t�r6d}t�r*t�s4t�d}qFt�d}ntjjd�rFd}||fS)z!Enables plugin, may throw IOErrorr�z(/usr/lib/zypp/plugins/services/spacewalk)�PluginPackagePresent�PluginConfPresent�
PluginEnabled�enablePlugin�createDefaultPluginConf�os�path�exists)Zconf_changedZplugin_present�r
�/usr/lib/python3.6/pmPlugin.py�pluginEnablesrcCstj�}|jdt�}|j�S)zO Returns positive number if plugin package is installed, otherwise it return 0 Zprovidename)�rpmZTransactionSetZdbMatch�PM_PLUGIN_NAME�count)ZtsZheadersr
r
rr%srcCs(ytjt�dStk
r"dSXdS)z- Returns true if PM_PLUGIN_CONF is presented TFN)r
�stat�PM_PLUGIN_CONF�OSErrorr
r
r
rr+s

rcCs ttd�}|jd�|j�dS)z1 Create file PM_PLUGIN_CONF, with default values �wz[main]
enabled = 1
gpgcheck = 1N)�openr�write�close)�fr
r
rr	3s
r	cCs�ttd�}|j�}|j�d}d}xZ|D]R}tjd|�rNtjd|�rJd}nd}|r(tjd|�}|r(t|jd��rvd}q(d}q(W|S)zM Returns True if plugin is enabled
        Can thrown IOError exception.
    �rFz^\[.*]z^\[main]Tz^\s*enabled\s*=\s*([0-9])r)rr�	readlinesr�re�match�int�group)r�lines�main_section�result�line�mr
r
rr;s"

rcCs�ttd�}|j�}|j�d}ttd�}xJ|D]B}tjd|�rTtjd|�rPd}nd}|rftjdd|�}|j|�q.W|j�d	S)
ze enable plugin by setting enabled=1 in file PM_PLUGIN_CONF
        Can thrown IOError exception.
    rFrz^\[.*]z^\[main]Tz^(\s*)enabled\s*=.+z
\1enabled = 1N)rrrrrr�subr)rr!r"r$r
r
rrSs


r)r
rrrrrrZPM_NAME�ImportErrorrrrr	rrr
r
r
r�<module>s"
__pycache__/rhnPackageInfo.cpython-36.opt-1.pyc000064400000003202150516774050015227 0ustar003

c8h\	�@sVddlmZddlmZddlmZddlmZdd�Zddd	�Zd
d�Zdd
�ZdS)�)�up2dateAuth)�
up2dateLog)�	rhnserver)�pkgUtilscCs8tj�}|jdt|d��|jdt|d��dS)Nz&Adding packages to package profile: %sZaddedz*Removing packages from package profile: %sZremoved)rZinitLogZlog_me�pprint_pkglist)Zpkgs�log�r�$/usr/lib/python3.6/rhnPackageInfo.py�logDeltaPackagess
r
NcCsdS)z; get a list of installed packages and send it to rhnServer Nr)Ztimeoutrrr	�updatePackageProfilesrcCs>t|�tg�kr dd�|D�}nd|d|d|df}|S)NcSs&g|]}d|d|d|df�qS)z%s-%s-%sr��r)�.0�arrr	�
<listcomp>'sz"pprint_pkglist.<locals>.<listcomp>z%s-%s-%srrr
)�type)Zpkglist�outputrrr	r%src	Cs�g}x�|D]�}d|krNd|krN|j|d|d|d|d|d|dg�q
d|kr�|j|d|d|d|d|dg�q
|j|d|d|d|dg�q
W|S)z� takes list of hashes and covert it to list of lists
        resulting strucure is:
        [[name, version, release, epoch, arch, cookie], ... ]
    ZarchZcookie�name�version�releaseZepoch)�append)Zpackages�result�packagerrr	�convertPackagesFromHashToList,s
&r)N)	Zup2date_clientrrrrr
rrrrrrr	�<module>s
__pycache__/hardware.cpython-36.opt-1.pyc000064400000044657150516774050014170 0ustar003

c8h��D@sJdZddlmZmZmZmZddlZddlZddlZddlZddl	m
Z
ddl	mZddl	mZddl
mZyeWnek
r�eZYnXyddlZdZWnek
r�d	ZYnXyddlZddlZdZWnek
r�d	ZYnXddlZejd
dd�Zeed��seje_ejZddlZejd
dg��ddl Z WdQRXddl	m!Z!yddl"m#Z#m$Z$dZ%Wn^ek
�r�yddl&m#Z#m$Z$dZ%Wn.ek
�r�ddl'm(Z(m)Z)m*Z*dZ%YnXYnXyddl+Z+Wnek
�r�dZ+YnXej,j-d�yddl.m/Z0dZ1Wnek
�r*d	Z1YnXda2da3dd�Z4e4�Z5e5�rfe j6�e!j7�Z8e8j9de5�dd�Z:dd�Z;dd�Z<dd�Z=d d!�Z>d"d#�Z?d$d%�Z@d&d'�ZAd(d)�ZBd*d+�ZCd,d-�ZDd.d/�ZEd0d1�ZFd2d3�ZGd4d5�ZHd6d7�ZId8d9�ZJd:d;�ZKd<d=�Z/eLd>k�rFx<e/�D]2ZMx&eMjN�D]ZOePd?eOeMeOf��qWeP�qWdS)@z1Used to read hardware info from kudzu, /proc, etc�)�gethostname�getaddrinfo�AF_INET�AF_INET6N)�config)�	rhnserver)�up2dateUtils)�ustrTFzrhn-client-tools)Zfallback�ugettextzFailed to save log entryzSMBIOS.*: entry point at)�
up2dateLog)�get_devices�get_computer_info�)�check_hal_dbus_status�get_hal_computer�read_halz/usr/share/rhsm)�HardwarecCsttd�sdStj�S)N�get_warnings)�hasattr�	dmidecoder�rr�/usr/lib/python3.6/hardware.py�dmi_warnings[s
rz.Warnings collected during dmidecode import: %sc	Cs�tdkr�trdStj�}|jtj�y6|jd�}t�}|rXtj�t	j
�}|jd|�Wn dat�}|rxtj�dS|j�atS)z= Initialize _dmi_data unless it already exist and returns it N�allzdmidecode warnings: %sr)
�	_dmi_data�_dmi_not_availablerZdmidecodeXMLZ
SetResultTypeZ
DMIXML_DOCZQuerySectionr�clear_warningsr�initLog�	log_debugZxpathNewContext)Zdmixml�data�dmi_warn�logrrr�_initialize_dmi_datags(
r"cCs6t�}|dkrdS|j|�}|gkr.|djSdSdS)z� Fetch DMI data from given section using given path.
        If data could not be retrieved, returns empty string.
        General method and should not be used outside of this module.
    N�r)r"Z	xpathEvalZcontent)�pathZdmi_datarrrr�get_dmi_data�s

r%cCstd�S)zt Return Vendor from dmidecode bios information.
        If this value could not be fetch, returns empty string.
    z/dmidecode/BIOSinfo/Vendor)r%rrrr�
dmi_vendor�sr&cCstd�}|sd}|S)zt Return UUID from dmidecode system information.
        If this value could not be fetch, returns empty string.
    z7/dmidecode/SystemInfo/SystemUUID[not(@unavailable='1')]r#)r%)Zuuidrrr�dmi_system_uuid�sr'cCs�tjdtj�siStdd�j�}i}d|d<x`|D]X}t|�s@q2|jd�}t|�dkrXq2|dj�}||d<dj|dd��j�||d<q2W|S)	Nz/etc/sysconfig/installinfo�rZINSTALLINFO�class�=rrr#)	�os�access�R_OK�open�	readlines�len�split�strip�join)ZinstallinfoZinstalldict�info�valsZstrippedstringrrr�read_installinfo�s

"r6csHytjd�}Wntk
r&g}YnXtjd��t�fdd�|D��S)z� returns number of CPU in system

    Beware that it can be different from number of active CPU (e.g. on s390x architecture
    z/sys/devices/system/cpu/z^cpu[0-9]+$csg|]}�j|�r|�qSr)�match)�.0�i)�re_cpurr�
<listcomp>�szcpu_count.<locals>.<listcomp>)r+�listdir�OSError�re�compiler0)Zcpu_dirr)r:r�	cpu_count�s

r@cCs�ytrt�j�dSWnYnXd}tjdtj�r�y^tjd�j�}d}x6|D].}|jd�r`qPt	|j
d�d�}||krP|}qPW|dkr�d|SWnYnXtjd	tj��r$ydtd	d
�j�}t
�}x4|D],}d|kr�t	|j
d�dj��}|j|�q�Wt|�dk�rt|�SWnYnXtjd
tj��r�yFtjd�j�}d}x |D]}d|k�rN|d7}�qNW|dk�rx|SWnYnXdS)Nzcpu.cpu_socket(s)rz/usr/bin/lscpuz/usr/bin/lscpu -pr�#�,�z
/proc/cpuinfor(zphysical id�:z/usr/sbin/dmidecodez /usr/sbin/dmidecode -t processorzProcessor Information���rE)�subscription_manager_available�SubManHardwareZ
getCpuInfor+r,�X_OK�popenr/�
startswith�intr1r-r.�setr2�addr0)�number_sockets�linesZmax_socket_index�lineZsocket_indexZ
socket_ids�countrrr�__get_number_sockets�sX





rRc
Csxdd�}dd�}tjdtj�s"iStr4tjtjd�tdd�j�}tj�dj	�}t
�}d	d
d�}|dd
kr~|dFd�dks�|dk�rz||�}|dkr�d|d<nd|d<||d<||d�|d<||d�|d<||d�|d<||d�|d<||d�|d<||d�|d<||d�|d<||d �|d!<||d"�}|d#k�r:d$}yttt
|��d%�|d&<Wntk
�rtdG|d&<YnX�n||dHk�rp||�}d'|d<||d)�|d<||d*�|d<||d+�|d<||d,�|d<d-||d.�||d/�f|d0<||d1�|d<d#|d<||d�|d<||d2�|d!<||d3�}|j�}y ttt
|d���d4|d&<Wntk
�rjdI|d&<YnX�n�|dJk�r.||�}||d<||d<||d6�|d<||d7�|d<||d8�|d<||d9�|d<||d�|d<|d"}yttt
|��d%�|d&<Wntk
�rdK|d&<YnX||d:�|d!<�n�|dLk�r�||�}||d<||d<||d*�|d<||d9�|d<||d�|d<||d<�|d<||d=�ddM�}yttt
|��d%�|d&<Wntk
�r�dN|d&<YnX�n|dOk�r�i}xH|jdA�D]:}	|	jdB�}
t|
�dk�r�q�|
d%j�||
dj�<�q�W||d<||d�|d<||d<||d<||dC�|d<d#|d<d#|d<d#|d<d#|d<||d:�|d!<d|d&<nX||d<||d<||d<||d<d#|d<d#|d<d#|d<d#|d<d#|d<d#|d!<d|d&<|d�s
d%|d<n@yt|d�|d<Wnd%|d<YnX|ddk�rJd%|d<tj�}|jjdD��rtt�}|�rt||dE<|S)PNcSs|j�}||krdS||S)Nr#)�lower)�a�entry�errr�	get_entry�szread_cpuinfo.<locals>.get_entrycSs�d}i}x�|jd�D]|}t|�s"q|d}|dkr4PxZ|jd�D]L}t|�sNq@|jd�}t|�dkrfq@|dj�|dj�}}|||j�<q@WqW|S)Nrz

r�
rDrC)r1r0r2rS)�cpulistrQ�tmpdict�cpuZcpu_attrr5�name�valuerrr�get_cpulist_as_dicts"
z)read_cpuinfo.<locals>.get_cpulist_as_dictz
/proc/cpuinfo�Cr(�ZCPUZ	Processor)r)Zdescrr9rC�86�x86_64�platformZi386rQZ	vendor_id�typez
model nameZmodelz
cpu familyZmodel_numberZ	model_verZsteppingZ	model_revz
cache size�cacheZbogomips�flags�otherzcpu mhzr#z-1rZspeed�alpha�alphaev6z
cpus detectedr[z	cpu modelz
cpu variationz%s/%szsystem typezsystem variationZ
model_versionzcpu revisionzplatform stringzcycle frequency [Hz]i@B�ia64�vendor�familyZarchrevZrevisionZfeatures�ppc64�machineZclock��s390�s390xrXz: zbogomips per cpuZcpu_socketsZsocket_count���rE)rhrirE)rjrE)rm���rE)rprq)r+r,r-�locale�	setlocale�
LC_NUMERICr.�read�unamerSr@rK�round�float�
ValueErrorr1r0r2rZ	RhnServerZcapabilitiesZ
hasCapabilityrR)
rWr^rYrxrQZhwdictrZZ	mhz_speedZhz_speedr[r5�srNrrr�read_cpuinfo�s�	&





 






r}cCs@tj�}|d}|dd�dkr&t�S|dd�dkr<t�SdS)NrCroz2.6z2.4)r+rx�read_memory_2_6�read_memory_2_4)ZunZkernelrrr�read_memory�sr�cCs�tjdtj�siStdd�j�}|jd�}|d}|j�}i}d|d<tt|d�d�}|dkrt|d	|d	}n|d
|d
}t|�|d<|d}|j�}tt|d�d�}t|�|d
<|S)Nz
/proc/meminfor(rXr�MEMORYr)i� r`��ramrC�swapii)	r+r,r-r.rwr1rK�long�str)�meminforOZcurlineZmemlist�memdict�megsrrrr�s$
rcCs�tjdtj�siStdd�j�}|jd�}i}xB|D]:}|jdd�}|d}t|�dkrZq4|dj�}|||<q4Wi}d|d<|d	}|jd
�}	t|	d�}
t|
d�}|d}|jd
�}	t|	d�}
t|
d�}t	|�|d
<t	|�|d<|S)Nz
/proc/meminfor(rXrDrrr�r)ZMemTotal� iZ	SwapTotalr�r�)
r+r,r-r.rwr1r0r2r�r�)r�rOZmeminfo_dictrPZblobs�keyr]r�Z	total_strZblipsZtotal_kr�Zswap_strZswap_kZ	swap_megsrrrr~�s2



r~cCsBtj�}tj�}ddd�}d}d}d}�x|D�]}|jd�d}|jd�d}||}	x�ttfD]�}
ytj|
�}Wntjk
r�wbYnX|d	r�tj�}|jd�\}}	t	|	�}	yR|j
d
�|j||	f�|j�d}
|
tkr�|
}n|
}tj
|
�}||
k�r|}Wn"tjk
�r(|j�wbYnX|j�qbWq.Wtjjd��r�tjdtj��r�tdd�j�}x�|D]}t|��s~�ql|j�}�qlWn�tjjd
��r tjd
tj��r td
d�j�}xd|D]\}t|��sҐq�|jd�}t|�dk�r�q�|dj�dk�r�dj|dd��jd�}P�q�W|dk�s4|dk�r8d}|||fS)z� returns [hostname, intf, intf6]

        Where hostname is you FQDN of this machine.
        And intf is numeric IPv4 address. And intf6 is IPv6 address.
    i��P)ZhttpsZhttpN�/rCrDrZenableProxy�z
/etc/hostnamer(z/etc/sysconfig/networkr*rZHOSTNAMEr#z"' 	
zlocalhost.localdomain�unknown)r�initUp2dateConfigZgetServerURLr1rr�socket�errorZgetProxySettingrKZ
settimeoutZconnectZgetsockname�getfqdn�closer+r$�isfiler,r-r.r/r0r2r3)�cfgZsl�st�hostnameZintfZintf6Z	serverUrlZserverZ
servertypeZportrlr|Zserver_portZintf_tmpZhostname_tmpZhostnameinfor4Znetworkinfor5rrr�findHostByRoute�sj








r�c	Cs�d}ytd|d�}Wn
|Sd}xV|j�D]J}|rT|jd�dkrT|j�d}P|jd�dkr0|j�d	}||kr0d
}q0W|j�|S)
Nr#z/proc/net/bonding/%sr(FzPermanent HW addr: rrozSlave Interface: rCTrErE)r.r/�findr1r�)�masterZslave�hwaddrZbondingZslave_foundrPZifnamerrr�get_slave_hwaddrFs r�cCs.i}d|d<t�\|d<|d<|d<|ddkrRt�|d<d|dkrRtj�|d<|ddkr�y4t|dd�}tdd	�|�}|d
dd
|d<Wnd|d<YnX|ddkr�y4t|dd�}td
d	�|�}|d
dd
|d<Wnd|d<YnX|ddk�rd|d<|ddk�r*d|d<|S)NZNETINFOr)r��ipaddrZip6addrr��.cSs|dtjkS)Nr)r�r)�xrrr�<lambda>iszread_network.<locals>.<lambda>rr`z	127.0.0.1cSs|dtjkS)Nr)r�r)r�rrrr�rsz::1r#)r�rr�r�r�filter)ZnetdictZ
list_of_addrsZ
ipv4_addrsZ
ipv6_addrsrrr�read_network[s4
r�c4Cs�i}d|d<tr(tr(tjjd�|StrFtttj�tj	���}nt
j�}�x6|D�],}y,trntj|�}nt
j
|�t
jdd}Wnd}YnXytjd|�}Wnd}YnX|r�tjj|�}t||�}y@tr�tj|�}n,td|d	�}|j�jd
�dj�}|j�Wn |dk�r0d
}nd}YnXy.t�rNtj|�}nt
j
|�t
jdd}Wnd}YnXy.t�r�tj|�}	nt
j
|�t
jdd}	Wnd}	YnXy.t�r�tj|�}
nt
j
|�t
jdd}
Wnd}
YnXg}t�r`tj|�}xL|D]D}
x<|
j�D]0}|j }|dk�r:d}|j!||j"|j#d���q"W�qW�ny�x�t
j
|�t
j$D]�}|djd�d}t%j&|�}|j'�r�d}n(|j(�r�d}n|j)�r�d}n|j*�r�d}|d}d}xd|jd�D]V}|�s�PnF|j+�dk�r|d7}n.|dt,t-|jd�dd��dd�j.d�7}�q�W|j!|||d���qtWWnt/k
�rlYnX|||	|
||d�||<qVW|S)NZ
NETINTERFACESr)zWWarning: information about network interfaces could not be retrieved on this platform.
r�addrr#z/sys/class/net/%s/masterz/sys/class/net/%s/device/ueventr(r*r�loZloopbackZUnknown�netmask�	broadcast�globalZuniverse)�scoper�r��%�link�hostZsiterDZffffr�r�rC�1)r�r�r�r��moduleZipv6)0�ethtool_present�netifaces_present�sys�stderr�write�listrL�ethtoolrZget_active_devices�	netifaces�
interfacesZ
get_hwaddrZifaddressesZAF_LINKr+�readlinkr$�basenamer�Z
get_moduler.�readliner1r2r�Z
get_ipaddrrZget_netmaskZ
get_broadcastZget_interfaces_infoZget_ipv6_addressesr��appendZaddressr�r�	ipaddressZIPv6AddressZ	is_globalZ
is_link_localZis_loopbackZ
is_site_localrS�binrK�rindex�KeyError)ZintDictr�Z	interfacer�r�Zmaster_interfacer�Zdriver_filer�r�r�Zip6_listZdev_infor4Zip6r�Zip6_addrZ
scope_infoZip6_netmaskZnetmask_bitsZ
two_octetsrrr�read_network_interfaces~s�












4r�c	CsBi}d|d<tj�dj�}|ddko6|dd�dkrH|dkrH|St�}|rZ||d	<td
�}|rn||d<td�}|r�|d
|}||d<td�|d<td�}|r�||d<td�}|r�||d<td�}|r�||d<td�}td�}td�}	td�}
dd|d|d|	d|
f|d<x*t|j��D]}||dk�r ||=�q W|S)NZDMIr)r`rr9rCrarbrkz!/dmidecode/SystemInfo/ProductName�productz/dmidecode/SystemInfo/Versionr��systemz%/dmidecode/BaseBoardInfo/ManufacturerZboardz/dmidecode/BIOSinfo/VendorZbios_vendorz/dmidecode/BIOSinfo/VersionZbios_versionz/dmidecode/BIOSinfo/ReleaseDateZbios_releasez#/dmidecode/ChassisInfo/SerialNumberz/dmidecode/ChassisInfo/AssetTagz%/dmidecode/BaseBoardInfo/SerialNumberz"/dmidecode/SystemInfo/SerialNumberz#(%s: %s) (%s: %s) (%s: %s) (%s: %s)ZchassisZassetrr)r+rxrSr&r%r��keys)Zdmidictrxrkr��versionr��releaseZchassis_serialZchassis_tagZboard_serialZ
system_serial�krrr�read_dmisJ(r�c
Cs�ytrt�}nt�}|j�}Wn6tk
rTtj�}dtj�d}|j	|�iSXi}x*|D]"}|j
d�r`t||�|t|�<q`W|jt
��|S)Nz0Error reading system and smbios information: %s
rr�)�using_gudevr
rZGetAllProperties�	Exceptionrrr��exc_inforrJr	�update�
get_smbios)ZpropsZcomputerr!�msgZsystem_and_smbiosr�rrr�get_hal_system_and_smbios;s 


r�c	CsDt�triSt�t�td�td�td�td�td�td�d�SdS)	a
 Returns dictionary with values we are interested for.
        For historical reason it is in format, which use HAL.
        Currently in dictionary are keys:
        smbios.system.uuid, smbios.bios.vendor, smbios.system.serial,
        smbios.system.manufacturer.
    z"/dmidecode/SystemInfo/SerialNumberz"/dmidecode/SystemInfo/Manufacturerz!/dmidecode/SystemInfo/ProductNamez/dmidecode/SystemInfo/SKUnumberz/dmidecode/SystemInfo/Familyz/dmidecode/SystemInfo/Version)zsmbios.system.uuidzsmbios.bios.vendorzsmbios.system.serialzsmbios.system.manufacturerzsmbios.system.productzsmbios.system.skunumberzsmbios.system.familyzsmbios.system.versionN)r"rr'r&r%rrrrr�Psr�c.Cs"trt�}nzt�\}}d}|s"|r<tj�}d}|j|�d}g}|r�yt�}|rT|}Wn.tj�}dtj�d}|j|�YnXyt	�}|r�|j
|�Wn"ttd�tj�d�YnXyt
�}|r�|j
|�Wn"ttd�tj�d�YnXtj�}|d�sNyt�}|�r(|j
|�Wn"ttd�tj�d�YnXyt�}|�rf|j
|�Wn.tj�}d	tj�d}|j|�YnXyt�}|�r�|j
|�Wn"ttd
�tj�d�YnX|d�syt�}|�r�|j
|�Wn"ttd�tj�d�YnX|S)NrzaWarning: haldaemon or messagebus service not running. Cannot probe hardware and DMI information.
rz'Error reading hardware information: %s
zError reading cpu information:z(Error reading system memory information:ZskipNetworkz%Error reading networking information:z"Error reading DMI information: %s
z)Error reading install method information:z,Error reading network interface information:)r�rrrrZlog_merr�r�r}r��print�_r�rr�r�r�r6r�)ZallhwZ
hal_statusZdbus_statusZhwdaemonr!r��retr�rrrrgsz



r�__main__z'%s' : '%s')Q�__doc__r�rrrrr>r+r�Zup2date_clientrrrZrhn.i18nr	r��	NameErrorrKr�r��ImportErrorr�r�r��gettextZtranslation�trr
r�ZdbusZsuppress_errorsrrZup2date_client.hardware_udevrr
r�Zup2date_client.hardware_gudevZup2date_client.hardware_halrrrrtr$r�Zsubscription_manager.hwproberrGrFrrrr rrr!rr"r%r&r'r6r@rRr}r�rr~r�r�r�r�r�r�r��__name__Zhwr�r�r�rrrr�<module>s�





7B!K#:]
__pycache__/hardware_gudev.cpython-36.opt-1.pyc000064400000017325150516774050015352 0ustar003

c8h�3�@s�y(ddlZejdd�ddlmZdZWn,eefk
rTddlZddlZdZYnXddl	Z	ddl
Z
ddlmZm
Z
dd	�Zd
d�ZdZd
ZdZdZdZdZdZdZd
ZdZdZdZdZdZd
ZdZdZ dZ!dZ"d
Z#dZ$dZ%dZ&dZ'd
Z(dZ)dZ*dZ+dZ,dZ-dZ.dZ/dZ0dZ1dZ2d
Z3dZ4dZ5dZ6dZ7dZ8d
Z9dZ:dZ;dZ<dZ=dZ>dZ?d
Z@dZAdZBdZCdZDdZEdd�ZFd d!�ZGd"d#�ZHd$d%�ZId&d'�ZJdS)(�N�GUdevz1.0)rTF)�PCI�USBc
Csrtrtj�}ntjdg�}|jd�|jd�|jd�|jd�|jd�}g}�x|D�]}|j�}||j�t|�dt|�t	|�d�}|d	d
kr�d|d	<|dd
kr�d
|d<|dk�r|j
d�r�|jd�|d<|j�|d<|j
�dkr�qX|jd�r�qX|jd�dk�r
qX|jd�dk�r�qXn�|dk�rv|jd�}|�rN|jd�\|d<|d<|jd�}|�r�|jd�\|d<|d<n>|dk�r�|j
d��r�|jd�|d<|j
d��r�|jd�|d<|j
d��r`|jd�dk�r`|j
d��s�|j
d ��r`|j
d��r|jd�}tjd!|�}	n|jd �}tjd"|�}	|	�r`|	jd#�|d<|	jd$�|d<|	jd%�|d<|	jd&�|d<|j|�qXW|S)'aE Returns list of dictionaries with keys for every device in system
        (values are provide as example):
        'bus' : 'pci'
        'driver' : 'pcieport-driver'
        'pciType' : '1'
        'detached' : '0'
        'class' : 'OTHER'
        'desc' : 'Intel Corporation|5000 Series Chipset PCI Express x4 Port 2'
    ��pci�usb�blockZccw�scsi�0)�bus�driverZpciTypeZdetached�classZdescr
N�OTHERr�unknownZID_BUSr�device�	partitionZDM_NAMEZMAJOR�1�7�PCI_ID�:Zprop1Zprop2Z
PCI_SUBSYS_IDZprop3Zprop4�ID_VENDOR_ID�ID_MODEL_IDZID_PATHZDEVPATHz.*scsi-(\d+):(\d+):(\d+):(\d+)z!.*/(\d+):(\d+):(\d+):(\d+)/block/����)�gi_gudevrZClient�gudevZquery_by_subsystem�
get_subsystem�
get_driver�_clasify_pci_type�_clasify_class�_get_device_desc�has_property�get_propertyZget_name�get_devtype�split�re�search�group�append)
ZclientZdevices�resultr�	subsystemZresult_item�	pci_classZ
pci_subsys�path�m�r0�$/usr/lib/python3.6/hardware_gudev.py�get_devicessn
2








r2cCs$tj�}|d|d|dd�}|S)z� Return dictionaries with keys (values are provided as example):
        'system.formfactor': 'unknown'
        'system.kernel.version': '2.6.18-128.1.6.el5xen'
            'system.kernel.machine': 'i686'
        'system.kernel.name': 'Linux'
    rrr)zsystem.kernel.namezsystem.kernel.versionzsystem.kernel.machine)�os�uname)r4r+r0r0r1�get_computer_infons
r5rZ00Z01Z02Z03Z04Z80�2�3�4�6Z05Z06Z07Z08r�9�CcCs|dkrdSdSdS)z) return 1 if device is PCI, otherwise -1 rrz-1Nr0)r,r0r0r1r �sr cCs>t|jd��\}}|j�}|tkr&dS|tkrF|tkr:dS|tkrFdS|jd�}|rt|j�}d|krhdSd|krtdS|�rZ|tkr�dS|t	kr�|t
kr�d	S|tkr�d
Sn�|tkr�|t
kr�dS|tkr�dS|tkr�d
S|tkr�dSnx|tko�|tk�r�dS|tk�r|tk�rdS|tk�r8|tk�r(dS|tk�rZdSn"|tk�rZ|tk�sV|tk�rZdS|dk�r�|jd��s�|jd��r�|jd�dk�r�dSdSn|dk�r�dS|dk�r�|jdk�r�t|�}|dk�s�|dk�r�dS|dk�r�d S|d!k�r�dSdStjd"|j��}|�rd#S|dk�r"dS|d$k�s6|d%k�r:dSd&S)'a Clasify type of device. Returned value is one of following string:
        NETWORK, KEYBOARD, MOUSE, VIDEO, USB, IDE, SCSI, RAID, MODEM, SCANNER
        CAPTURE, AUDIO, FIREWIRE, SOCKET, CDROM, HD, FLOPPY, TAPE, PRINTER, OTHER
        or None if it is neither PCI nor USB device.
    Z	PCI_CLASSrZKEYBOARDZMOUSEZ	ID_SERIALZkeyboardZmouseZVIDEOrZFIREWIREZIDEZSCSIZRAIDZFLOPPYZMODEMZSCANNERZCAPTUREZAUDIOZSOCKETrZID_CDROMZID_TYPEZcdZCDROMZHDZsoundr	Zscsi_devicer�rZTAPE�z	.*/lp\d+$ZPRINTERrrN) �_parse_pci_classr$r�PCI_BASE_CLASS_NETWORK�PCI_BASE_CLASS_INPUT�PCI_CLASS_INPUT_KEYBOARD�PCI_CLASS_INPUT_MOUSE�lower�PCI_BASE_CLASS_DISPLAY�PCI_BASE_CLASS_SERIAL�PCI_CLASS_SERIAL_USB�PCI_CLASS_SERIAL_FIREWIRE�PCI_BASE_CLASS_STORAGE�PCI_CLASS_STORAGE_IDE�PCI_CLASS_STORAGE_SCSI�PCI_CLASS_STORAGE_RAID�PCI_CLASS_STORAGE_FLOPPY�PCI_BASE_CLASS_COMMUNICATION�PCI_CLASS_COMMUNICATION_MODEM�PCI_CLASS_INPUT_SCANNER�PCI_BASE_CLASS_MULTIMEDIA�PCI_CLASS_MULTIMEDIA_VIDEO�PCI_CLASS_MULTIMEDIA_AUDIO�PCI_BASE_CLASS_BRIDGE�PCI_CLASS_BRIDGE_PCMCIA�PCI_CLASS_BRIDGE_CARDBUSr#r%�_get_scsi_dev_typer'r(�get_sysfs_path)rZ
base_classZ	sub_classr,Z	id_serialZdev_typer/r0r0r1r!�s�










r!c	CsV|j�}d}d}|dkrN|jd�jd�\}}t�}d|j|�|j||�f}n�|dk�r0|jd�}t�}|r�d|j|�|j||jd��f}n�|j�d	kr�|j�d
kr�d}n|j�dkr�d
}nd}nj|j�dko�|jd��rD|jd�jd�dd�\}}dt	|d�}dt	|d�}d|j|�|j||�f}n|dk�rD|jd�}|�rN|SdSdS)z. Return human readable description of device. Nrrrz%s|%srrrZ
usb_interfaceZusbhidzUSB HID InterfaceZhubzUSB Hub Interfacez
USB InterfaceZ
usb_deviceZPRODUCT�/rz%.4x�rZID_MODELr)
rr$r&rZ
get_vendorZ
get_devicerr%r�int)	rr,Zcommandr+Z	vendor_idZ	device_idrrZmodel_idr0r0r1r"%s8

"

r"cCs(|dkrdS|dd�|dd	�fSdS)
a= Parse Class Code. Return touple of
        [base class code, sub-class code]
        You are usually interested to only first two.
        The third - "specific register-level programming interface" is ignored.
        For details, see the PCI Local Bus Specification 2.1/2.2 Section 6.2.1 Device Identification
    N�rr)NNi�������r\���r0)r-r0r0r1r>Gsr>cCs@ytd|j�d�}Wntk
r*dSX|j�}|j�|S)zQ Return SCSI type of device in raw format as presented in /sys/...devpath../type z%s/type�rr���)�openrW�IOError�readline�close)r�fr+r0r0r1rVSsrV)KZgiZrequire_versionZ
gi.repositoryrr�ImportError�
ValueErrorrZglibr3r'Zhwdatarrr2r5rHrJrIrLZPCI_CLASS_STORAGE_IPIrKZPCI_CLASS_STORAGE_OTHERr?ZPCI_CLASS_NETWORK_ETHERNETZPCI_CLASS_NETWORK_TOKEN_RINGZPCI_CLASS_NETWORK_FDDIZPCI_CLASS_NETWORK_ATMZPCI_CLASS_NETWORK_OTHERrDZPCI_CLASS_DISPLAY_VGAZPCI_CLASS_DISPLAY_XGAZPCI_CLASS_DISPLAY_3DZPCI_CLASS_DISPLAY_OTHERrPrQrRZPCI_CLASS_MULTIMEDIA_PHONEZPCI_CLASS_MULTIMEDIA_OTHERrSZPCI_CLASS_BRIDGE_HOSTZPCI_CLASS_BRIDGE_ISAZPCI_CLASS_BRIDGE_EISAZPCI_CLASS_BRIDGE_MCZPCI_CLASS_BRIDGE_PCIrTZPCI_CLASS_BRIDGE_NUBUSrUZPCI_CLASS_BRIDGE_RACEWAYZPCI_CLASS_BRIDGE_OTHERrMZPCI_CLASS_COMMUNICATION_SERIALZ PCI_CLASS_COMMUNICATION_PARALLELZ#PCI_CLASS_COMMUNICATION_MULTISERIALrNZPCI_CLASS_COMMUNICATION_OTHERr@rAZPCI_CLASS_INPUT_PENrBrOZPCI_CLASS_INPUT_GAMEPORTZPCI_CLASS_INPUT_OTHERrErGZPCI_CLASS_SERIAL_ACCESSZPCI_CLASS_SERIAL_SSArFZPCI_CLASS_SERIAL_FIBERZPCI_CLASS_SERIAL_SMBUSr r!r"r>rVr0r0r0r1�<module>s�
P`"__pycache__/hardware_hal.cpython-36.pyc000064400000015366150516774050014050 0ustar003

c8hT-�@sHdZddlmZmZddlZdZdZdZdZdZ	dZ
dZdZdZ
dZdZdZdZdZdZdZdZdZdZdZdZdZdZd	ZdZdZdZdZ dZ!d
Z"d	Z#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dZ+dZ,d
Z-dZ.dZ/dZ0dZ1dZ2dZ3dZ4dZ5dZ6dZ7dZ8dZ9d
Z:dd�Z;dd�Z<dd�Z=dd�Z>dd�Z?dd�Z@dd�ZAdd�ZBdd �ZCd!d"�ZDdS)#z Get hardware info using HAL �)�HalTree�	HalDevice�N����P�����	�cCs�g}tj�}|jdd�}tj|d�}|j�}t�}x>|D]6}|jd|�}tj|d�}|j�}	t|	�}
|j|
�q8Wt	|j
�}|S)Nzorg.freedesktop.Halz/org/freedesktop/Hal/Managerzorg.freedesktop.Hal.Managerzorg.freedesktop.Hal.Device)�dbus�	SystemBus�
get_object�	InterfaceZ
GetAllDevicesrZGetAllPropertiesr�add�process_hal_nodes�head)�ret�busZhal_manager_objZhal_managerZdevice_listZhal_treeZudiZ
device_obj�device�
propertiesZhaldev�
kudzu_list�r�"/usr/lib/python3.6/hardware_hal.py�read_hal\s 

rcCs&g}t|�|_|jr�|j}i}|j|d<tt|��|d<|ddkr�d|jkr\|jd|d<d|jkrt|jd|d<d|jkr�|jd|d	<d
|jkr�|jd
|d<tt|��|d<t|�}|r�t|�|d
<tt|��|d<tt	|��|d<d|d<|j
|�x"|jD]}t|�}|j
|��qW|S)N�classrZscsiz	scsi.hostZprop1zscsi.targetZprop2zscsi.busZprop3zscsi.lunZprop4�driverr�descZpciTyperZdetached)�classify_hal�classification�parent�str�get_device_busr�get_device_driver�get_device_path�get_device_description�get_device_pcitype�appendZchildrenr�extend)�noderr#�devZdevice_pathZchildZ
child_listrrrrts8






rcCs^d|jkrdSd|jkr\d|jkr\|jddkr\d|jdj�krFdSd|jdj�kr\d	Sd
|jk�r�|jd
tkrzdS|jd
tkr�|jdtkr�d
S|jd
tkr�|jdtkr�dS|jdtkr�dS|jdtkr�dS|jd
t	kr�|jdt
kr�dS|jd
tk�r"|jdtk�r"dS|jd
t
k�rZ|jdtk�rFdS|jdtk�rZdS|jd
tk�r~|jdtk�r~dS|jd
tk�r�|jdtk�s�|jdtk�r�dSd|jk�r|jddk�r�dS|jddk�r�dS|jddk�r�dS|jddk�rdSd |jk�r.|jd d!k�r.dSd"|jk�r>d#Sd$|jk�sVd%|jk�rZd&SdS)'Nz
net.interface�NETWORKzinfo.productz
info.category�inputZkeyboardZKEYBOARDZmouseZMOUSEzpci.device_classZVIDEOzpci.device_subclassZUSBZIDEZSCSIZRAIDZMODEMZSCANNERZCAPTUREZAUDIOZFIREWIREZSOCKETzstorage.drive_typeZcdromZCDROMZdiskZHDZfloppyZFLOPPYZtapeZTAPEzxen.typeZvbdzprinter.productZPRINTERzpci.product_idzusb.product_idZOTHER)r�lower�PCI_BASE_CLASS_DISPLAY�PCI_BASE_CLASS_SERIAL�PCI_CLASS_SERIAL_USB�PCI_BASE_CLASS_STORAGE�PCI_CLASS_STORAGE_IDE�PCI_CLASS_STORAGE_SCSI�PCI_CLASS_STORAGE_RAID�PCI_BASE_CLASS_COMMUNICATION�PCI_CLASS_COMMUNICATION_MODEM�PCI_BASE_CLASS_INPUT�PCI_CLASS_INPUT_SCANNER�PCI_BASE_CLASS_MULTIMEDIA�PCI_CLASS_MULTIMEDIA_VIDEO�PCI_CLASS_MULTIMEDIA_AUDIO�PCI_CLASS_SERIAL_FIREWIRE�PCI_BASE_CLASS_BRIDGE�PCI_CLASS_BRIDGE_PCMCIA�PCI_CLASS_BRIDGE_CARDBUS)r,rrrr!�sr
r!cCsHd|jkr|jd}n.d|jkr@|jddkr4d}qD|jd}nd}|S)Nzstorage.buszinfo.bus�platformZMISC)r)r,rrrrr%�s

r%cCs4d|jkr|jd}nd|jkr,|jd}nd}|S)Nzinfo.linux.driverznet.linux.driver�unknown)r)r,rrrrr&s

r&cCs|d}d|jkr|jd}n4d|jkr0|jd}n|jdkrNd|jkrN|jd}|rx|jd�rh|dd�}t|�dkrxd}|S)	a%
    Return the device file path.

    As kudzu did not return a string with the /dev/ prefix,
    this function will not, either.
    RHN's DB has a limit of 16 characters for the device path.
    If the path is longer than that, return None.
    If no device path is found, return None.
    Nzblock.devicezlinux.device_filer.z
net.interfacez/dev/r
�)rr"�
startswith�len)r,r-rrrr's






r'cCsbd|jkr.d|jkr.|jdd|jd}n0d|jkrD|jd}nd|jkrZ|jd}nd}|S)Nzinfo.vendorzinfo.product�|�)r)r,r rrrr(*s



r(cCsrd}d}d
}d|jo |jddkkrj|j}d|jkrd|jddkrd|jddks^|jdd	krd|}qn|}n|}|S)Nrrzinfo.busZpcizpci.device_classr	zpci.device_subclassr
r���)rr#)r,ZPCI_TYPE_PCMCIAZPCI_TYPE_PCIZPCI_TYPE_NOT_PCIr#Zpcityperrrr)7s
r)cCs$tj�}|jdd�}tj|d�}|S)Nzorg.freedesktop.Halz%/org/freedesktop/Hal/devices/computerzorg.freedesktop.Hal.Device)rrrr)rZcomputer_objZcomputerrrr�get_hal_computerKs
rKcCs,ddl}|jd�\}}|jd�\}}||fS)Nrz/etc/init.d/haldaemon statusz/etc/init.d/messagebus status)�
subprocessZgetstatusoutput)ZcommandsZ
hal_status�msgZdbus_statusrrr�check_hal_dbus_statusSsrN)E�__doc__Zhaltreerrrr4r6r5ZPCI_CLASS_STORAGE_FLOPPYZPCI_CLASS_STORAGE_IPIr7ZPCI_CLASS_STORAGE_OTHERZPCI_BASE_CLASS_NETWORKZPCI_CLASS_NETWORK_ETHERNETZPCI_CLASS_NETWORK_TOKEN_RINGZPCI_CLASS_NETWORK_FDDIZPCI_CLASS_NETWORK_ATMZPCI_CLASS_NETWORK_OTHERr1ZPCI_CLASS_DISPLAY_VGAZPCI_CLASS_DISPLAY_XGAZPCI_CLASS_DISPLAY_3DZPCI_CLASS_DISPLAY_OTHERr<r=r>ZPCI_CLASS_MULTIMEDIA_PHONEZPCI_CLASS_MULTIMEDIA_OTHERr@ZPCI_CLASS_BRIDGE_HOSTZPCI_CLASS_BRIDGE_ISAZPCI_CLASS_BRIDGE_EISAZPCI_CLASS_BRIDGE_MCZPCI_CLASS_BRIDGE_PCIrAZPCI_CLASS_BRIDGE_NUBUSrBZPCI_CLASS_BRIDGE_RACEWAYZPCI_CLASS_BRIDGE_OTHERr8ZPCI_CLASS_COMMUNICATION_SERIALZ PCI_CLASS_COMMUNICATION_PARALLELZ#PCI_CLASS_COMMUNICATION_MULTISERIALr9ZPCI_CLASS_COMMUNICATION_OTHERr:ZPCI_CLASS_INPUT_KEYBOARDZPCI_CLASS_INPUT_PENZPCI_CLASS_INPUT_MOUSEr;ZPCI_CLASS_INPUT_GAMEPORTZPCI_CLASS_INPUT_OTHERr2r?ZPCI_CLASS_SERIAL_ACCESSZPCI_CLASS_SERIAL_SSAr3ZPCI_CLASS_SERIAL_FIBERZPCI_CLASS_SERIAL_SMBUSrrr!r%r&r'r(r)rKrNrrrr�<module>s�)Z


__pycache__/hardware_udev.cpython-36.opt-1.pyc000064400000017263150516774050015204 0ustar003

c8h�3�@sDddlZddlZddlZddlmZmZdd�Zdd�ZdZdZ	d	Z
d
ZdZdZ
d
ZdZdZd	Zd
ZdZd
ZdZdZd	Zd
Zd
ZdZdZd	Zd
Zd
ZdZdZ d	Z!d
Z"dZ#dZ$dZ%dZ&dZ'dZ(d
Z)dZ*dZ+d	Z,d
Z-dZ.d
Z/dZ0dZ1d	Z2d
Z3dZ4dZ5d
Z6dZ7dZ8d	Z9d
Z:dZ;dZ<dZ=dd�Z>dd�Z?dd�Z@dd �ZAd!d"�ZBd#d$�ZCdS)%�N)�PCI�USBc
CsFtj�}|j�}g}�x*|jd�jd�jd�jd�jd�D�]}|j}||jt|�dt|�t|�d�}|dd	krzd
|d<|dd	kr�d|d<|dkr�t	|d
�r�t	|d
�|d<|j
|d<|jdkr�q:t	|d�r�q:t	|d�dkr�q:t	|d�dkr�q:n�|dk�rJt	|d�}|�r"|jd�\|d<|d<t	|d�}|�r�|jd�\|d<|d<n>|dk�r�t	|d��rnt	|d�|d<t	|d��r�t	|d�|d<t	|d
��r4t	|d
�dk�r4t	|d��s�t	|d��r4t	|d��r�t	|d�}t
jd |�}	nt	|d�}t
jd!|�}	|	�r4|	jd"�|d<|	jd#�|d<|	jd$�|d<|	jd%�|d<|j|�q:W|S)&aE Returns list of dictionaries with keys for every device in system
        (values are provide as example):
        'bus' : 'pci'
        'driver' : 'pcieport-driver'
        'pciType' : '1'
        'detached' : '0'
        'class' : 'OTHER'
        'desc' : 'Intel Corporation|5000 Series Chipset PCI Express x4 Port 2'
    �pci�usb�blockZccw�scsi�0)�bus�driverZpciTypeZdetached�classZdescrN�OTHERr
�unknownZID_BUSr	�device�	partitionZDM_NAMEZMAJOR�1�7�PCI_ID�:Zprop1Zprop2Z
PCI_SUBSYS_IDZprop3Zprop4�ID_VENDOR_ID�ID_MODEL_IDZID_PATHZDEVPATHz.*scsi-(\d+):(\d+):(\d+):(\d+)z!.*/(\d+):(\d+):(\d+):(\d+)/block/����)�pyudevZContextZlist_devicesZmatch_subsystem�	subsystemr
�_clasify_pci_type�_clasify_class�_get_device_desc�_get_device_propertyZsys_name�device_type�split�re�search�group�append)
�contextZdevices�resultrrZresult_item�	pci_classZ
pci_subsys�path�m�r+�#/usr/lib/python3.6/hardware_udev.py�get_devicessj,









r-cCs$tj�}|d|d|dd�}|S)z� Return dictionaries with keys (values are provided as example):
        'system.formfactor': 'unknown'
        'system.kernel.version': '2.6.18-128.1.6.el5xen'
            'system.kernel.machine': 'i686'
        'system.kernel.name': 'Linux'
    rrr)zsystem.kernel.namezsystem.kernel.versionzsystem.kernel.machine)�os�uname)r/r'r+r+r,�get_computer_infobs
r0rZ00Z01Z02Z03Z04Z80�2�3�4�6Z05Z06Z07Z08r�9�CcCs|dkrdSdSdS)z) return 1 if device is PCI, otherwise -1 rrz-1Nr+)rr+r+r,r�srcCs,y|jj|�Stk
r&|j|�SXdS)zS return the property of the given device independent of the implementation version N)Z
properties�get�AttributeError)rZpropr+r+r,r�srcCs:tt|d��\}}|j}|tkr$dS|tkrD|tkr8dS|tkrDdSt|d�}|rr|j�}d|krfdSd|krrdS|�rX|tkr�dS|t	kr�|t
kr�d	S|tkr�d
Sn�|tkr�|t
kr�dS|tkr�dS|tkr�d
S|tkr�dSnx|tko�|tk�r�dS|tk�r|tk�rdS|tk�r6|tk�r&dS|tk�rXdSn"|tk�rX|tk�sT|tk�rXdS|dk�r�t|d��s�t|d��r�t|d�dk�r�dSdSn|dk�r�dS|dk�r�|jdk�r�t|�}|dk�s�|dk�r�dS|dk�r�d S|d!k�r�dSdStjd"|j�}|�rd#S|dk�rdS|d$k�s2|d%k�r6dSd&S)'a Clasify type of device. Returned value is one of following string:
        NETWORK, KEYBOARD, MOUSE, VIDEO, USB, IDE, SCSI, RAID, MODEM, SCANNER
        CAPTURE, AUDIO, FIREWIRE, SOCKET, CDROM, HD, FLOPPY, TAPE, PRINTER, OTHER
        or None if it is neither PCI nor USB device.
    Z	PCI_CLASSrZKEYBOARDZMOUSEZ	ID_SERIALZkeyboardZmouseZVIDEOrZFIREWIREZIDEZSCSIZRAIDZFLOPPYZMODEMZSCANNERZCAPTUREZAUDIOZSOCKETrZID_CDROMZID_TYPEZcdZCDROMZHDZsoundrZscsi_devicer�rZTAPE�z	.*/lp\d+$ZPRINTERrrN)�_parse_pci_classrr�PCI_BASE_CLASS_NETWORK�PCI_BASE_CLASS_INPUT�PCI_CLASS_INPUT_KEYBOARD�PCI_CLASS_INPUT_MOUSE�lower�PCI_BASE_CLASS_DISPLAY�PCI_BASE_CLASS_SERIAL�PCI_CLASS_SERIAL_USB�PCI_CLASS_SERIAL_FIREWIRE�PCI_BASE_CLASS_STORAGE�PCI_CLASS_STORAGE_IDE�PCI_CLASS_STORAGE_SCSI�PCI_CLASS_STORAGE_RAID�PCI_CLASS_STORAGE_FLOPPY�PCI_BASE_CLASS_COMMUNICATION�PCI_CLASS_COMMUNICATION_MODEM�PCI_CLASS_INPUT_SCANNER�PCI_BASE_CLASS_MULTIMEDIA�PCI_CLASS_MULTIMEDIA_VIDEO�PCI_CLASS_MULTIMEDIA_AUDIO�PCI_BASE_CLASS_BRIDGE�PCI_CLASS_BRIDGE_PCMCIA�PCI_CLASS_BRIDGE_CARDBUSr �_get_scsi_dev_typer"r#�sys_path)rZ
base_classZ	sub_classrZ	id_serialZdev_typer*r+r+r,r�s�










rc	CsL|j}d}d}|dkrLt|d�jd�\}}t�}d|j|�|j||�f}n�|dk�r&t|d�}t�}|r�d|j|�|j|t|d��f}n�|jd	kr�|jd
kr�d}n|jdkr�d
}nd}nh|jdko�t|d��r:t|d�jd�dd�\}}dt	|d�}dt	|d�}d|j|�|j||�f}n|dk�r:t|d�}|�rD|SdSdS)z. Return human readable description of device. Nrrrz%s|%srrrZ
usb_interfaceZusbhidzUSB HID InterfaceZhubzUSB Hub Interfacez
USB InterfaceZ
usb_deviceZPRODUCT�/rz%.4x�rZID_MODEL�)
rrr!rZ
get_vendorZ
get_devicerr r
�int)	rrZcommandr'Z	vendor_idZ	device_idrrZmodel_idr+r+r,r s8

"




rcCs(|dkrdS|dd�|dd	�fSdS)
a= Parse Class Code. Return touple of
        [base class code, sub-class code]
        You are usually interested to only first two.
        The third - "specific register-level programming interface" is ignored.
        For details, see the PCI Local Bus Specification 2.1/2.2 Section 6.2.1 Device Identification
    N�rr)NNi�������rZ���r+)r(r+r+r,r;Bsr;cCs>ytd|jd�}Wntk
r(dSX|j�}|j�|S)zQ Return SCSI type of device in raw format as presented in /sys/...devpath../type z%s/type�rr���)�openrT�IOError�readline�close)r�fr'r+r+r,rSNsrS)Drr.r"Zhwdatarrr-r0rErGrFrIZPCI_CLASS_STORAGE_IPIrHZPCI_CLASS_STORAGE_OTHERr<ZPCI_CLASS_NETWORK_ETHERNETZPCI_CLASS_NETWORK_TOKEN_RINGZPCI_CLASS_NETWORK_FDDIZPCI_CLASS_NETWORK_ATMZPCI_CLASS_NETWORK_OTHERrAZPCI_CLASS_DISPLAY_VGAZPCI_CLASS_DISPLAY_XGAZPCI_CLASS_DISPLAY_3DZPCI_CLASS_DISPLAY_OTHERrMrNrOZPCI_CLASS_MULTIMEDIA_PHONEZPCI_CLASS_MULTIMEDIA_OTHERrPZPCI_CLASS_BRIDGE_HOSTZPCI_CLASS_BRIDGE_ISAZPCI_CLASS_BRIDGE_EISAZPCI_CLASS_BRIDGE_MCZPCI_CLASS_BRIDGE_PCIrQZPCI_CLASS_BRIDGE_NUBUSrRZPCI_CLASS_BRIDGE_RACEWAYZPCI_CLASS_BRIDGE_OTHERrJZPCI_CLASS_COMMUNICATION_SERIALZ PCI_CLASS_COMMUNICATION_PARALLELZ#PCI_CLASS_COMMUNICATION_MULTISERIALrKZPCI_CLASS_COMMUNICATION_OTHERr=r>ZPCI_CLASS_INPUT_PENr?rLZPCI_CLASS_INPUT_GAMEPORTZPCI_CLASS_INPUT_OTHERrBrDZPCI_CLASS_SERIAL_ACCESSZPCI_CLASS_SERIAL_SSArCZPCI_CLASS_SERIAL_FIBERZPCI_CLASS_SERIAL_SMBUSrrrrr;rSr+r+r+r,�<module>s�M`"__pycache__/up2dateAuth.cpython-36.pyc000064400000017574150516774050013620 0ustar003

c8h�*�@sDddlZddlZddlZddlZddlZddlZddlmZyddlm	Z	Wne
k
rdeZ	YnXddlm
Z
ddlmZddlmZddlmZddlmZdd	lmZdd
lmZdadZdd
�Zdd�Zdd�Zdd�Zdd�Zdd�Zd)dd�Zd*dd�Zd+dd�ZGdd �d e�Z d!d"�Z!d#d$�Z"d%d&�Z#d'd(�Z$dS),�N)�	rpcServer)�DictType)�rpclib)�
clientCaps)�config)�	rhnserver)�
up2dateErrors)�
up2dateLog)�up2dateUtilsz /var/spool/up2date/loginAuth.pklcCs@tj�}|d}tj|tj�s"dSt|d�}|j�}|j�|S)N�systemIdPath�r)r�initUp2dateConfig�os�access�R_OK�open�read�close)�cfg�path�f�ret�r�!/usr/lib/python3.6/up2dateAuth.py�getSystemIds
rcCs�tj�}t�}d}|dkr|SyDtjj|�dd}|jdd�}|dkrN|}n|jd||f�|Stk
r�|jd�|j	t
j��YnX|S)	z�
    Extract the preferred_interface parameter from system_id XML
    Returns 'IPv4' or 'IPv6' if specified, otherwise 'IPv4' as default
    �IPv4Nr�preferred_interface�IPv6zGInvalid preferred_interface value '%s' in system_id, defaulting to '%s'zGFailed to parse system_id XML, preferred_interface defaulting to 'IPv4')rr)r	�initLogrr�	xmlrpclib�loads�get�log_me�	Exception�
log_exception�sys�exc_info)�log�systemIdrZparamsZ
cfg_interfacerrr�getPreferredInterface(s$
r)c	CsBtjjd�rdStj�}ytjjt��ddd}Wn
dSt	j
�}|doZ||k�r>tj�}|j
jt�|�}|d}|d|jd��}tj|tj�s�ytj|�Wn
dStj|tj�s�dStj|tj��r�|d}ytj||�Wn
dSt|d�}|j|�|j�ytj|td	d
��WnYnXdS)NZLEAPP_IPU_IN_PROGRESSrZ
os_releaseZchannelOverrider�/z.save�w�0600�)r�environr!rr
rrr rr
Z
getVersionrZRegistrationRhnServerZregistrationZupgrade_version�rfindr�W_OK�mkdir�F_OK�renamer�writer�chmod�int)	r�idVerZ	systemVer�sZnewSystemIdr�dirZsavePathrrrr�maybeUpdateVersionLsB

r:cCs�tj�}|jd�ts$|jd�dStj�td�}tjjt�}tj	|tj
�s�y tj|�tj|t
dd��Wn|jd|�dSttd�}tjtt
d	d��tj||�|j�|d
ttd�}|jd|d
d
|d�dS)z�
    Pickle loginInfo to a file
    Returns:
    True    -- wrote loginInfo to a pickle file
    False   -- did _not_ write loginInfo to a pickle file
    zwriteCachedLogin() invokedz1writeCachedLogin() loginInfo is None, so bailing.F)�time�	loginInfoZ0700r-z'Unable to write pickled loginInfo to %s�wbr,r;zX-RHN-Auth-Expire-OffsetzWrote pickled loginInfo at z with expiration of z	 seconds.T)r	r�	log_debugr<r;rr�dirname�pcklAuthFileNamerr0r1r5r6r"r�pickle�dumpr�float)r'�dataZpcklDir�pcklAuth�
expireTimerrr�writeCachedLoginzs.



rGc	CsTtj�}|jd�tjttj�s2|jdt�dSttd�}ytj	|�}Wn*t
tfk
rt|jd�|j�dSX|j�yLt
jjt��ddd}d|d	d
}||kr�|jd||f�dSWnYnX|d}|d	}tj�}|t|d
�}|jd|d|dt|d
��||k�r<|jd||f�dSt|�|jd|�dS)zb
    Read pickle info from a file
    Caches authorization info for connecting to the server.
    zreadCachedLogin invokedz'Unable to read pickled loginInfo at: %sF�rbzSUnexpected EOF. Probably an empty file,                        regenerate auth filerZ	system_idzID-%sr<zX-RHN-Server-Idz#system id version changed: %s vs %sr;zX-RHN-Auth-Expire-Offsetz(Checking pickled loginInfo, currentTime=z
, createTime=z, expire-offset=z9Pickled loginInfo has expired, created = %s, expire = %s.z<readCachedLogin(): using pickled loginInfo set to expire at T)r	rr>rrr@rrrA�load�EOFError�
ValueErrorrrrr rr;rC�_updateLoginInfo)	r'rErDr7ZcidVerZcreatedTime�liZcurrentTimerFrrr�readCachedLogin�sH


rNcCs2t|�tkr*tt�tkr$tj|�q.|andadS)z,
    Update the global var, "loginInfo"
    N)�typerr<�update)rMrrrrL�s
rLFc	Cs�tj�}|jd|�|r,tr,t�r,tStj|d�}tjj	�}x|D]\}}|j
||�qHW|dkrnt�}|svdSt�|j
d�|jj|tj�t|��}|jj�t|�t�tr�|j
d�|jdt�tS)Nzlogin(forceUpdate=%s) invoked)�timeoutzlogging into up2date serverz?successfully retrieved authentication token from up2date serverz
logininfo:)r	rr>r<rNrZ	RhnServerrZcapsZheaderFormatZ
add_headerrr:r"Zup2date�login�socketZgetfqdn�_get_panel_nameZcapabilitiesZvalidaterLrG)	r(�forceUpdaterQr'ZserverZ
headerlistZ
headerName�valuerMrrrrR�s.



rRcCs0tj�}|jd�td|d�ts,tjd��tS)NzupdateLoginInfo() login infoT)rUrQzUnable to authenticate)r	rr"rRr<rZAuthenticationError)rQr'rrr�updateLoginInfo�s

rWcCs8ytaWntk
r daYnXtr*tSt|d�tS)N)rQ)r<�	NameErrorrR)rQrrr�getLoginInfos

rYc@seZdZdS)�_FailedToGetPanelNameN)�__name__�
__module__�__qualname__rrrrrZsrZcCsLy
t�}Wn8tk
rBt�s8|jtj��|jd�t�}YnX|j�S)Nz?Failed to get panel name via cldetect, using fallback mechanism)	�_get_panel_name_via_cldetectrZ�_is_cldeploy_runningr$r%r&r"�_fallback_get_panel_name�lower)r'Z
panel_namerrrrTs

rTcCstd}d}d}tjj|�r8t|��}|j�j�}WdQRX|rpd|}tjj|�rpt|��}d|j�k}WdQRX|S)Nz/var/lock/cldeploy.lckFz/proc/%s/cmdlineZcldeploy)rr�existsrr�strip)Zlock_file_pathZcldeploy_running�pidrZpid_cmdline_pathrrrr_$s

r_cCsrddg\}}}tjj|�s(td|��tj|tjtjdd�}|j�\}}|jdkrjtddj	|�|f��|j
�S)	Nz/usr/bin/cldetectz--detect-cp-nameonlyz7Failed to obtain panel name because '%s' does not existT)�stdout�stderrZuniversal_newlinesrz:Failed to obtain panel name using '%s' command; stderr: %s� )rrrbrZ�
subprocess�Popen�PIPEZcommunicate�
returncode�joinrc)Zbinary�_�cmdZprocessrerfrrrr^5s
r^cCsdtjjd�rdStjjd�r dStjjd�r0dStjjd�r@dStjjd	�rPd
Stjjd�r`dSd
S)Nz/usr/local/psa/admin/Zpleskz/usr/local/interworx/Z	interworxz#/usr/local/cpanel/whostmgr/docroot/Zcpanelz/usr/local/ispmgr/Zispmgrz/usr/local/directadmin/Zdirectadminz/usr/local/mgr5/sbin/mgrctlZispmgr5�unknown)rr�isdir�isfilerrrrr`Hsr`)NFN)N)N)%rrAr%r;rSrhZup2date_clientr�typesr�ImportError�dictZrhnrrrrrr	r
r<r@rr)r:rGrNrLrRrWrYr#rZrTr_r^r`rrrr�<module>sB

$. ,
%




__pycache__/rhnreg.cpython-36.pyc000064400000062362150516774050012712 0ustar003

c8he}�@s�ddlZddlZddlZddlZddlZddlmZddlmZddlmZddlm	Z	ddlm
Z
ddlmZddlmZdd	lm
Z
dd
lmZddlmZddlmZmZdd
lmZy4ddlZddlZddlmZmZmZmZmZmZWnFe k
�r6ddl!j"Zddl#j$Ze%Ze&Ze'Ze(Ze)Ze)Ze*Z+YnXyddl,m-Z-Wne k
�rbdZ-YnXddl.Z.e.j/ddd�Z0e1e0d��s�e0j.e0_2e0j2Z3dZ4de4Z5de4Z6dZ7dZ8ddddd�Z9dd�e9j:�D�Z;dd lm<Z<e<j=�Z>ej?�Z@d!d"�ZAd#d$�ZBd%d&�ZCd'd(�ZDd)d*�ZEd+d,�ZFd-d.�ZGd/d0�ZHd1d2�ZIe(eJd3�d4d5�ZKeJd6�d7d8�ZLd�d:d;�ZMd<d=�ZNd>d?�ZOd@dA�ZPdBdC�ZQdDdE�ZRdFdG�ZSdHdI�ZTdJdK�ZUGdLdM�dM�ZVd�eJdN�dOdP�ZWdQdR�ZXdSdT�ZYdUdV�ZZdWdX�Z[e(dY�dZd[�Z\d�d\d]�Z]d^d_�Z^d`da�Z_dbdc�Z`dddddifddde�Zadfdg�Zbdhdi�Zcdjdk�Zddldm�Zedndo�Zfdpdq�Zgd�drds�ZhGdtdu�du�Zidvdw�Zjdxdy�Zkd�dzd{�Zld|d}�Zme�d~k�r�dd��Znndd�lomnZndS)��N)�up2dateUtils)�
up2dateErrors)�up2dateAuth)�	rhnserver)�pkgUtils)�
up2dateLog)�rhnreg_constants)�hardware)�convertPackagesFromHashToList)�getPlatform)�ustr�sstr)�
raise_with_tb)�ListType�	TupleType�
StringType�UnicodeType�DictType�DictionaryType)�supportzrhn-client-toolsT)Zfallback�ugettextz/etc/sysconfig/rhnz%s/rhn_register_remindz%s/hw-activation-codez/etc/pki/consumer/cert.pemz/etc/sysconfig/rhn/jwt.tokenZ
shared_pro�shared�solo�admin)zCloudLinux OS Shared ProzCloudLinux OS SharedzCloudLinux OS SolozCloudLinux OS AdmincCsi|]\}}||�qS�r)�.0�k�vrr�/usr/lib/python3.6/rhnreg.py�
<dictcomp>Gsr)�configcCs&tjdtjtjB��r"d}d}tj|tjtjB�sNtjdtjtjB�rNd}d}tjd|tj�r�tj|tjtjB�r�tjd|�tjd|�nttd	��n�tjd
tjtjB�r�tjd�nttd��d
}tj|tjtjB��stjdtjtjB��rd}tjd|�}|�r"tjd|�dS)Nz/usr/sbin/rhnsdz/usr/lib/systemd/systemz/usr/bin/systemctlz/bin/systemctlz/lib/systemd/systemz%s/rhnsd.servicez%s enable rhnsd > /dev/nullz%s start rhnsd > /dev/nullz,Warning: unable to enable rhnsd with systemdz/sbin/chkconfigz$/sbin/chkconfig rhnsd on > /dev/nullz.Warning: unable to enable rhnsd with chkconfigz
/sbin/servicez/usr/sbin/servicez%s rhnsd status > /dev/nullz%s rhnsd start > /dev/null)�os�access�R_OK�X_OK�system�print�_)Zsystemd_system_unitdirZsystemd_systemctlZservice_pathZrcrrr�
startRhnsdOs,r(cCs�tdp
d}tj|tj�siSt|d�}|j�}i}x`|D]X}|j�}|dkrPq:y|jd�\}}Wn"tk
r�t	t
j|��YnX|j�||<q:W|S)NZoemInfoFilez/etc/sysconfig/rhn/oeminfo�r��:)�cfgr!r"r#�open�	readlines�strip�split�
ValueErrorrrZOemInfoFileError)Z
configFile�fd�L�info�i�key�valuerrr�
getOemInfops 

r8cCs*tjttj�r"tjt�}|jdkSdSdS)z@ Returns true if system is registred using subscription manager rFN)r!r"�	RHSM_FILEr#�stat�st_size)Zstatinforrr�rhsm_registered�s

r<cCstjtdtj�S)N�systemIdPath)r!r"r,r#rrrr�
registered�sr>cCs$tjttj�s ttd�}|j�dS)Nzw+)r!r"�REMIND_FILEr#r-�close)r2rrr�createSystemRegisterRemindFile�s
rAcCstjttj�rtjt�dS)N)r!r"r?r#�unlinkrrrr�removeSystemRegisterRemindFile�srCcCs�tjj|�}tj|tj�sdStj|tj�rLytj||d�Wn
dStj|tjtj	Bt
dd��}tj|d�}z|jt
|��Wd|j�XdS)z; Write a file to disk that is not readable by other users. Fz.saveZ0600��wNT)r!�path�dirnamer"�W_OK�F_OK�renamer-�O_WRONLY�O_CREAT�int�fdopen�writer
r@)Zsecure_fileZ
file_contentsZdir_namer2Zfd_filerrr�_write_secure_file�s
rPcCs"ttd|�}|rt�t�|S)Nr=)rPr,rC�updateRhsmStatus)�systemId�resrrr�
writeSystemId�s
rTcCsxd}tj�}|dkrdSy6tj|�}|j�}|j|�dj}t|dd��}Wn$ttj	fk
rrt
jd�dSX|S)Nz'//member[name='system_id']/value/stringr�z@systemID file doesn't have system_id field or the file is broken)r�getSystemId�libxml2ZparseDocZxpathNewContextZ	xpathEvalZcontentrM�
IndexErrorZparserError�log�log_me)Z	xpath_strrR�result�context�	system_idrrr�extract_system_id�s

r^)�token�allowTransitioncCsnddl}ddl}|jjd�s dSdd|g}|r8|jd�|j|�}|j�\}}|jdkrjtj	d||f�dS)zH
    Execute binary file which we use as hook for jwt token updates
    rNz /opt/cloudlinux/venv/bin/python3z/usr/sbin/cl-pre-jwt-updatez--new-tokenz--allow-transitionz7Pre jwt update hook failed with stdout=%s and stderr=%s)
�
subprocessr!rF�exists�append�Popen�communicate�
returncoderYrZ)r_r`rar!�cmd�p�stdout�stderrrrr�_execute_pre_jwt_update_hook�s



rk)r`cCsjddl}ddl}|jjd�s dSdg}|r4|jd�|j|�}|j�\}}|jdkrftj	d||f�dS)zH
    Execute binary file which we use as hook for jwt token updates
    rNz /opt/cloudlinux/venv/bin/python3z/usr/sbin/cl-post-jwt-updatez--allow-transitionz8Post jwt update hook failed with stdout=%s and stderr=%s)
rar!rFrbrcrdrerfrYrZ)r`rar!rgrhrirjrrr�_execute_post_jwt_update_hook�s


rlFcCs�tj�}y|jj|�}WnFtjk
r.dStjtjtjtj	fk
r^t
jtj
��dSXt||�tt|�t|�dS)z�
    Get a JWT token from CLN and save it to the file
    :param systemId: content of file `/etc/sysconfig/rhn/systemid`
    :return: None
    N)rZ	RhnServerZup2dateZgetJWTTokenr�UnknownMethodExceptionZAuthenticationTicketErrorZRhnUuidUniquenessError�CommunicationErrorZ$AuthenticationOrAccountCreationErrorrY�
log_exception�sys�exc_inforkrP�	JWT_TOKENrl)rRr`Z
xmlrpm_serverr[rrr�getAndWriteJWTTokenToFile�s

rscCstt|d�S)z=Returns True if the write is successful or False if it fails.�
)rP�HW_CODE_FILE)�hw_activation_coderrr�writeHWCodesrwcCspy"tjjd�r t�\}}||fSWntk
r6YnXt�\}}|dk	rR||fSt�\}}|dk	rl||fSdS)a�
    This function returns the UUID and virtualization type of this system, if
    it is a guest.  Otherwise, it returns None.  To figure this out, we'll
    use a number of heuristics (list in order of precedence):

       1.  Check /proc/xen/xsd_port.  If exists, we know the system is a
           host; exit.
       2.  Check SMBIOS.  If vendor='Xen' and UUID is non-zero, we know the
           system is a fully-virt guest; exit.
       3.  Check /sys/hypervisor/uuid.  If exists and is non-zero, we know
           the system is a para-virt guest; exit.
       4.  If non of the above checks worked; we know we have a
           non-xen-enabled system; exit.
    z/proc/xen/xsd_portN)NN)r!rFrb�get_fully_virt_info�IOError�get_para_virt_info)�uuid�	virt_typerrr�
get_virt_infos


r}cCsVy<tdd�}|j�}|j�|j�jdd�jd�}d}||fStk
rPYnXdS)	z�
    This function checks /sys/hypervisor/uuid to see if the system is a
    para-virt guest.  It returns a (uuid, virt_type) tuple.
    z/sys/hypervisor/uuidr)�-r*z
ZparaN)NN)r-�readr@�lower�replace�rstripry)Z	uuid_filer{r|rrrrzCs
rzcCs@tj�}tj�}|j�dkr8|j�jdd�}d}||fSdSdS)z�
    This function looks in the SMBIOS area to determine if this is a
    fully-virt guest.  It returns a (uuid, virt_type) tuple.
    Zxenr~r*ZfullyN)NN)r	Z
dmi_vendorZdmi_system_uuidr�r�)Zvendorr{r|rrrrxUsrxcCstd|�}t|�td�kS)Nz0x%sr)�eval�long)r{rrr�
_is_host_uuidcsr�cCstj�}|jj�S)N)r�RegistrationRhnServer�registrationZwelcome_message)�srrr�welcomeTextgsr�cCstj�}|jj�dS)N)rr�ZcapabilitiesZvalidate)r�rrr�getCapsmsr�cCstj�}|jj||�S)N)rr�r�Zreserve_user)�username�passwordr�rrr�reserveUserrsr�c@sfeZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dS)�RegistrationResultNcCsB||_||_||_||_||_t|�dkr2||_nd|_||_dS)Nr)�	_systemId�	_channels�_failedChannels�_systemSlots�_failedSystemSlots�len�_universalActivationKey�rawDict)�selfrR�channelsZfailedChannels�systemSlotsZfailedSystemSlotsZuniversalActivationKeyr�rrr�__init__xszRegistrationResult.__init__cCs|jS)N)r�)r�rrrrV�szRegistrationResult.getSystemIdcCs|jS)N)r�)r�rrr�getChannels�szRegistrationResult.getChannelscCs|jS)N)r�)r�rrr�getFailedChannels�sz$RegistrationResult.getFailedChannelscCs|jS)N)r�)r�rrr�getSystemSlots�sz!RegistrationResult.getSystemSlotscs�fdd��jD�S)Ncsg|]}�j|��qSr)�_getSlotDescription)rr�)r�rr�
<listcomp>�sz@RegistrationResult.getSystemSlotDescriptions.<locals>.<listcomp>)r�)r�r)r�r�getSystemSlotDescriptions�sz,RegistrationResult.getSystemSlotDescriptionscs�fdd��jD�S)Ncsg|]}�j|��qSr)�_getFailedSlotDescription)rr�)r�rrr��szFRegistrationResult.getFailedSystemSlotDescriptions.<locals>.<listcomp>)r�)r�r)r�r�getFailedSystemSlotDescriptions�sz2RegistrationResult.getFailedSystemSlotDescriptionscCs|jS)z5Returns None if no universal activation key was used.)r�)r�rrr�getUniversalActivationKey�sz,RegistrationResult.getUniversalActivationKeycCst|j�dkot|j�dkS)z�Returns True if the system was subscribed to at least one channel
        and was given any type of system slot so it will get updates. In other
        words, returns True if the system will be getting at least basic
        updates.

        r)r�r�r�)r�rrr�hasBaseAndUpdates�s	z$RegistrationResult.hasBaseAndUpdatescCs&|dkrtjdtjS|j|�SdS)N�virtualization_host� )r�VIRTZVIRT_FAILEDr�)r��slotrrrr��sz,RegistrationResult._getFailedSlotDescriptioncCs$|dkrtjS|dkrtjS|SdS)NZenterprise_entitledr�)rZ
MANAGEMENTr�)r�r�rrrr��s
z&RegistrationResult._getSlotDescription)N)�__name__�
__module__�__qualname__r�rVr�r�r�r�r�r�r�r�r�rrrrr�ws

r�)�human_readablec	CsFd}tjj|�sdSt|�� }|j�jd�}|r4|St|SQRXdS)Nz/opt/cloudlinux/cl_editionrrt)r!rFrbr-rr/�_human_readable_to_product)r�Zedition_cache_file�fZraw_editionrrr�getServerEdition�s
r�cCslddlm}m}tjjd�s"t��d}||d||d�}dd�|j�D�\}}|rVt��t|d	d�j	d
��S)Nr)rd�PIPEz/opt/cloudlinux/venv/binzZ/opt/cloudlinux/venv/bin/python3 -c "from clcommon.cpapi import cpusers; print(cpusers())"T)�shellrirjcSsg|]}|j�j��qSr)�decoder/)rr[rrrr��sz.get_users_count_from_cllib.<locals>.<listcomp>�z, ���)
rardr�r!rFrbr1rer�r0)rdr�rgZprocess�output�errorsrrr�get_users_count_from_cllib�sr�cCsddlm}|�}t|j��S)Nr)�ClPwd)Zup2date_client.clpwdr�r�Zget_uid_dict)r��pwdrrr�get_users_count_generic�sr�cCs*y
t�}Wntk
r$t�}YnX|S)N)r��	Exceptionr�)Zusers_countrrr�countServerUsers�s

r�cCsTyt|�}WnPtjk
rH}ztd|j�tjd�WYdd}~Xntjk
r\dSXt�}|d}||krxdS|r�tdj	t
|t
|d��td�tjd�|�sPtjj�s�td�td�t
|�dt
|�d	�}d
dd�}|j
|�}	|	dk	�rHt�}
|
|	k�r4td||�d
|
�d��tjd�n|�d||�d�}t|�dS)Nz%sr��editionz�WARNING: Automatic registration in yum transactions is only available when edition matches the provided license. Your current edition is {current_edition} and your license is {new_edition}.)Zcurrent_editionZnew_editionz0Run clnreg_ks manually to complete registration.aError: interactive input required for edition migration, but tool is running in non-interactive mode. Please try running the tool again in interactive shell or add `--migrate-silently` flag to accept allquestions and perform the edition migration silently.za edition installed on your server does not match license you are trying to register server with: zh. Migration is required. You may lose access to the services which are not supported by the new edition.�)rrz@The license you are trying to register with allows a maximum of z% hosting accounts which is less than z) users detected on this server. Aborting.zG Also, the license you are trying to register with allows a maximum of zM hosting accounts. Make sure that your system complies with this requirement.)�checkKeyrrnr&�errmsgrp�exitrmr��format�_product_to_human_readable�stdin�isatty�getr��_askConfirmation)�
activationKeyZ
strictEditionZsilentMigrationZlicenseInformation�eZcurrentEditionZlicenseEdition�messageZedition_to_users_limitZlicense_users_limitZusers_on_serverrrr�checkLicenseKey�sB




r�)�confirmationMessagecCs2t|�td�}|j�dkr.td�tjd�dS)zS
    Prints message and makes sure that client is ready for edition migration.
    z Do you want to continue? [N/y]: �yzAborted.r�N)r&�inputr�rpr�)r�Zresponserrrr�s
r�cCs�|dkr|dkstd��|tj�tj�tj�d�}tj�}|dk	rJ||d<|rlx|j�D]\}}	|	||<qXW|rz||d<n||d<||d<|dk	r�||d<n(tj	j
d	�r�d
ntj	j
d�r�dnd
|d<tdr�tt
j��|d<tj�}
|
jj|�}|S)ziWrapper for the old xmlrpc to register a system. Activates subscriptions
    if a reg num is given.

    Nz)username and password usage is deprecated)Zprofile_nameZ
os_releaseZrelease_nameZarchitecturer]r_r�r�r�z/etc/cloudlinux-edition-solorz/etc/cloudlinux-edition-adminrr�supportsSMBIOS�smbios)�AssertionErrorr�
getVersion�getOSRelease�getArchrrV�itemsr!rFrbr,�_encode_charactersr	�
get_smbiosrr�r�Z
new_system)r�r��profileNamer_�otherr�Z	auth_dictZ
system_id_xmlr6�itemr��retrrr�registerSystem)s2

r�cCstj�}|jj|�}|S)zG
    Check the activation key and return it's edition and customer
    )rr�r�Z
license_check)r�r�r�rrrr�Xsr�cCsly,tj�}|j|dddd�}tj|dd�}Wntjk
rBdSXy|j�Wntjk
rfYnXdS)Nzcom.redhat.SubscriptionManagerz/EntitlementStatusF)Z
introspectz0com.redhat.SubscriptionManager.EntitlementStatus)Zdbus_interface)�dbusZ	SystemBusZProxyObjectClassZ	InterfaceZ
DBusExceptionZcheck_status)ZbusZvalidity_objZvalidity_ifacerrrrQcs
rQcCs�tj�}tj�}tj�}tj�}d}y|jj|||||�}Wn@tj	k
r|t
j�d}|jdkrvt
tj|j��n�YnX|S)Nr��c)rr�rr�r�Z
getReleaser�Zavailable_eus_channels�	xmlrpclibZFaultrprqZ	faultCoderrZ
DelayErrorZfaultString)r�r�r�Zserver_archZserver_versionZserver_releaseZavailableChannelsr�rrr�getAvailableChannelsxs 

r�c
	Cs$|dkri}|r6|dkst�|dks(t�|dk	sZt�n$|dk	sBt�|dk	sNt�|dksZt�x|j�D]}|dksdt�qdWtdr�ttj��|d<tj�}|r�|jj	|t
j�t
j�t
j
�||�}n$|jj|t
j�t
j�t
j
�|||�}tjd	|�t|d
|d|d|d
|d|d|d�}	|	S)a�Uses the new xmlrpcs to register a system. Returns a dict instead of just
    system id.

    The main differences between this and registerSystem and that this doesn't
    do activation and does child channel subscriptions if possible. See the
    documentation for the xmlrpc handlers in backend for more detail.

    If nothing is going to be in other, it can be {} or None.

    New in RHEL 5.

    N�registration_number�org_id�	virt_uuidr|�channelr�r�zReturned:
%sr]r�Zfailed_channelsZsystem_slotsZfailed_system_slotsZuniversal_activation_key)r�)r�r�r�r|r�)r��keysr,r�r	r�rr�r�Znew_system_activation_keyrr�r�r�Znew_system_user_passrY�	log_debugr�)
r�r�r�Zpackagesr�r�r6r�r4r[rrr�registerSystem2�sNr�cCstdS)NZsupportsEUS)r,rrrr�server_supports_eus�sr�cCsdS)Nr)rRZhardwareListrrr�sendHardware�sr�cCsdS)Nr)rRZpackageListrrr�sendPackages�sr�cCstdk	rtj�dS)N)rZrefresh)rRrrr�sendVirtInfo�sr�cCstj�}t|jj|��dS)N)rr�r&r�Z
list_packages)rRr�rrr�listPackages�sr�cCs�tj|�\}}}}}}|dks&|dkrDd|}tj|�\}}}}}}|d	krVtjd��|dksn|dksn|dkrrd}tj||||||f�}|S)
zzRaises up2dateErrors.InvalidProtocolError if the server url has a
    protocol specified and it's not http or https.

    Nr*zhttps://�https�httpzCYou specified an invalid protocol. Only https and http are allowed.�/z/XMLRPC)r�r�)�urlparserZInvalidProtocolErrorZ
urlunparse)�serverZprotocol�hostrFZ
parametersZqueryZfragmentIdentifierrrr�makeNiceServerUrl�s
r�cCsdS)zdReturns 'hosted' if the url points to a known hosted server. Otherwise
    returns 'satellite'.
    Z	satelliter)Z	serverUrlrrr�
getServerTypesr�c@sBeZdZdZdZiifdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
S)�ActivationResultrr�cCs||_||_||_||_dS)zschannels and systemSlots are dicts where the key/value pairs are
        label (string) / quantity (int).

        N)�_status�_regNumr�r�)r�ZstatusZregistrationNumberr�r�rrrr�szActivationResult.__init__cCs|jS)N)r�)r�rrr�	getStatus$szActivationResult.getStatuscCs|jS)N)r�)r�rrr�getRegistrationNumber'sz&ActivationResult.getRegistrationNumbercCs|jS)z7Returns a dict- the key/value pairs are label/quantity.)r�)r�rrr�getChannelsActivated*sz%ActivationResult.getChannelsActivatedcCs|jS)z7Returns a dict- the key/value pairs are label/quantity.)r�)r�rrr�getSystemSlotsActivated.sz(ActivationResult.getSystemSlotsActivatedN)
r�r�r��
ACTIVATED_NOW�ALREADY_USEDr�r�r�r�r�rrrrr�sr�cGs�g}x�|D]�}t|�}|tkr(t|�}nZ|tkrDtdd�|D��}n>|tkr\dd�|D�}n&|tksl|tkr�tdd�|j	�D��}|j
|�q
Wt|�dkr�|dSt|�SdS)	u� All the data we gathered from dmi, bios, gudev are in utf-8,
            we need to convert characters beyond ord(127) - e.g ® to unicode.
        css|]}t|�VqdS)N)r�)rr5rrr�	<genexpr><sz%_encode_characters.<locals>.<genexpr>cSsg|]}t|��qSr)r�)rr5rrrr�>sz&_encode_characters.<locals>.<listcomp>cSsg|]\}}t||��qSr)r�)r�name�valrrrr�@sr�rN)�typerrr�tuplerrr�dictr�rcr�)�argsr[r�Z	item_typerrrr�2s

r�cCs�d}d}d}ytj�}t|�}Wn$tjd�tjtj��YnX|dk	r�y.t|||�}|j	�t
jkrz|j�}t
|�Wn>tjk
r�tjd�Yn tjk
r�tjd�YnX|S)NzMThere was an error while reading the hardware info from the bios. Traceback:
z<There are are no entitlements associated with this hardware.z,The hardware id was not recognized as valid.)r	Zget_hal_system_and_smbiosr�rYrZrorprq�activateHardwareInfor�r�r�r�rwrZNotEntitlingErrorr�ZInvalidRegistrationNumberError)Zloginr�ZactivateHWResult�hardwareInforvrrr�_activate_hardwareHs*

rc
Cs�i}|rd|i}tj�}|jj||||�}|d}|d}tjd|�|dkr\ttj|�S|dkrpttj|�Sd|}	t	j
|	��dS)	z�Tries to activate an entitlement linked to the hardware info that we
    read from the bios.

    Returns an ActivationResult.
    Can raise:
        Invalid number.
        Hardware info is not entitling.
        Communication errors, etc

    r�Zstatus_coder�zServer returned status code %srr�zNThe server returned unknown status code %s while activating the hardware info.N)rr�r�Zactivate_hardware_inforYr�r�r�r�rrn)
r�r�rZorgIdr�r�r[Z
statusCodeZregNumr�rrrrds 
rcCsdtjdtjtjB�rVddlm}m}|dg|||d�}tdd�|jj	�|j
j	��n
tjd�dS)Nz/usr/sbin/rhn_checkr)rdr�)r�rirjcSs
tj|�S)N)rYrZ)�xrrr�<lambda>�sz$spawnRhnCheckForUI.<locals>.<lambda>z Warning: unable to run rhn_check)
r!r"r#r$rardr��maprir.rjrYrZ)rdr�rhrrr�spawnRhnCheckForUI�s
rZdebcCsdS)z.On Debian no extra action for plugin is neededr�r)r�rrrrrr�pluginEnable�sr)r)F)F)NNNNNN)N)N)pr!rpr��base64rWZup2date_clientrrrrrrrr	Zup2date_client.rhnPackageInfor
Zup2date_client.pkgplatformrZrhn.i18nrr
Zrhn.tbrr�r��typesrrrrrr�ImportErrorZurllib.parse�parseZ
xmlrpc.clientZclient�listr�bytes�strrrMr�Zvirtualizationr�gettextZtranslation�t�hasattrrr'Z	SYSID_DIRr?rur9rrr�r�r�r ZinitUp2dateConfigr,ZinitLogrYr(r8r<r>rArCrPrTr^�boolrkrlrsrwr}rzrxr�r�r�r�r�r�r�r�r�r�r�r�r�rQr�r�r�r�r�r�r�r�r�r�r�rrrrZup2date_client.pmPluginrrrr�<module>	s�$



!

,?>
-;


"

__pycache__/clpwd.cpython-36.opt-1.pyc000064400000007626150516774050013477 0ustar003

c8h;�@s"ddlZddlZGdd�d�ZdS)�Nc@s�eZdZGdd�de�Zddd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zddd�ZdS)�ClPwdc@seZdZdd�ZdS)zClPwd.NoSuchUserExceptioncCstj|d|f�dS)NzNo such user (%s))�	Exception�__init__)�self�user�r�/usr/lib/python3.6/clpwd.pyrsz"ClPwd.NoSuchUserException.__init__N)�__name__�
__module__�__qualname__rrrrr�NoSuchUserExceptionsrNcCs8i|_i|_i|_i|_|dkr.|jd�|_n||_dS)Ni�)�
_user_key_map�_uid_key_map�_user_full_map�
_uid_full_map�get_sys_min_uid�_min_uid)rZmin_uidrrrr	szClPwd.__init__cCs|j�|jS)N)�_load_passwd_databaser
)rrrr�
get_user_dictszClPwd.get_user_dictcCs|j�|jS)N)rr)rrrr�get_uid_dictszClPwd.get_uid_dictcCs|j�|jS)N)rr)rrrr�get_user_full_dictszClPwd.get_user_full_dictcCs|j�|jS)N)rr)rrrr�get_uid_full_dictszClPwd.get_uid_full_dictcCs0y|j�|Stk
r*tj|��YnXdS)z*
        Return pw_entry for user
        N)r�KeyErrorrr)rrrrr�get_pw_by_name#szClPwd.get_pw_by_namecCs0y|j�|Stk
r*tj|��YnXdS)z7
        Return list of passwd entries for uid
        N)rrrr)r�uidrrr�
get_pw_by_uid,szClPwd.get_pw_by_uidcCs2y|j�|jStk
r,tj|��YnXdS)z&
        Returns uid for user
        N)r�pw_uidrrr)rrrrr�get_uid5sz
ClPwd.get_uidcCs2y|j�|jStk
r,tj|��YnXdS)z`
        Returns homedir for a user
        @param user: string
        @return: string
        N)r�pw_dirrrr)rrrrr�get_homedir>szClPwd.get_homedircCs�|js�x�tj�D]|}||j|j<|j|jkr8g|j|j<|j|jj|�|j|jkr||j|j<|j|j	krzg|j	|j<|j	|jj|�qWdS)zZ
        Loads the passwd database and fills user_to_uid and user_to_homedir maps
        N)
r�pwdZgetpwallr�pw_namer�appendrr
r)r�entryrrrrIszClPwd._load_passwd_databasecCs>y|j�|}Wntk
r.tj|��YnXdd�|D�S)zs
        Return names of users with uid specified
        @param uid: int
        @return: list of strings
        cSsg|]
}|j�qSr)r!)�.0r#rrr�
<listcomp>dsz#ClPwd.get_names.<locals>.<listcomp>)rrrr)rrZentriesrrr�	get_namesYs
zClPwd.get_names��cCsnd}tjj|�rjt|d��J}xB|D]:}|jd�r"yt|jd�dj��Stk
rZYq"Xq"WWdQRX|S)z�
        Return system defined MIN_UID from /etc/login.def or def_min_uid
        @param def_min_uid: int
        @return: MIN_UID: int
        z/etc/login.defs�rZUID_MIN�N)	�os�path�exists�open�
startswith�int�split�strip�
ValueError)rZdef_min_uidZLOGIN_DEF_FILE�lines�linerrrrgs

zClPwd.get_sys_min_uid)N)r')r	r
rrrrrrrrrrrrrr&rrrrrrs

			r)r r*rrrrr�<module>s__pycache__/debUtils.cpython-36.opt-1.pyc000064400000004262150516774050014132 0ustar003

c8h�@slddlZddlZddlZejddd�Zeed�s8eje_ejZdd�Zdd	�Z	d
d�Z
ddd
�Zdd�ZdS)�Nzrhn-client-toolsT)Zfallback�ugettextcCsHtj�}g}x2|D]*}||d}|dks2|jr|j|�qWg|fS)Nr)�apt�CacheZis_installed�append)Zpackages�cacheZmissing_packages�package�pkg�r	�/usr/lib/python3.6/debUtils.py�verifyPackagess
rcCs`d}d}|jd�dkr$|jd�\}}|jd�dkrV|jd�}dj|dd��}|d	}|||fS)
N��X�:��-���rrr)�find�split�join)�version�epoch�releaseZtmpr	r	r
�parseVREs
rcCstd}d|d||fg}d|kr<|jd|d|jd���x2|D]*}tjj||�}tjj|�rBtjj|�SqBWdS)Nz/var/lib/dpkg/infoz%s.listz
%s:%s.listrr)r�index�os�pathr�isfile�getmtime)Zpkg_nameZpkg_arch�dir�files�frr	r	r
�installTime(s
r!c
	Cs�|dkr|td��tj�}d}x|D]}|jdkr&|d7}q&Wd}g}xv|D]n}|jdkr^qNt|jj�\}	}
}|j||	|
|jjdt|j|jj�d�}|j	|�|dkr�|||�|d}qNW|j
dd�d	�|S)
z} Return list of packages. Package is dict with following keys:
        name, epoch, version, release and optionaly arch.
    Nz0Getting list of packages installed on the systemrrz-deb)�namerrrZarchZinstalltimecSs|dS)Nrr	)rr	r	r
�<lambda>Zsz)getInstalledPackageList.<locals>.<lambda>)�key)�_rrZ	installedrrr"Zarchitecturer!r�sort)
ZmsgCallbackZprogressCallbackZgetArchZgetInforZtotalr�countZpkg_listrrrrr	r	r
�getInstalledPackageList8s2






r(cCsdS)Nr	r	r	r	r
�setDebugVerbosity]sr))NNNN)
rr�gettextZtranslation�t�hasattrrr%rrr!r(r)r	r	r	r
�<module>s


$__pycache__/rhnserver.cpython-36.opt-1.pyc000064400000012301150516774050014366 0ustar003

c8h;%�@s�ddlmZddlmZddlmZddlmZddlZddlZyddlZWne	k
rjddl
jZYnXGdd�de�Z
Gdd	�d	e�ZGd
d�de�ZdS)�)�
raise_with_tb)�	rpcServer)�
up2dateErrors)�capabilitiesNc@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�_DoCallWrapperze
    A callable object that will handle multiple levels of attributes,
    and catch exceptions.
    cCs||_||_dS)N)�_server�_method_name)�selfZserver�method_name�r�/usr/lib/python3.6/rhnserver.py�__init__5sz_DoCallWrapper.__init__cCst|jd|j|f�S)z= Recursively build up the method name to pass to the server. z%s.%s)rrr)r	r
rrr�__getattr__9sz_DoCallWrapper.__getattr__cOs�t|j|j�}ytj|f|�|�Stjk
rLt|jt	j
�d��Yn�tjj
k
r�tt	j
�d�}|jd�}|jd�}d}t|�dkr�|d}nt|�dkr�|d}|jd�}|dkr�ttj��nttj|��YnXdS)	z3 Call the method. Catch faults and translate them. �z[()]�,��z 'zcertificate verify failedN)�getattrrrrZdoCall�	xmlrpclibZFaultr�$_DoCallWrapper__exception_from_fault�sys�exc_info�OpenSSLZSSL�Error�str�strip�split�lenrZSSLCertificateVerifyFailedErrorZNetworkError)r	�args�kwargs�method�error�pieces�messagerrr�__call__>s$



z_DoCallWrapper.__call__cCs�|jdkrtj|j�}�n�|jdkr4tj|j�}�n�|jdkrNtj|j�}�nr|jdkrhtj|j�}�nX|jdkr�tj|j�}�n>|jd kr�tj|j�}�n$|jd!kr�tj|j�}�n
|jd"kr�tj|j�}�n�|jd#kr�tj|j�}�n�|jd$k�rtj	|j�}�n�|jd%k�r"tj
|j�}�n�t|j�dk�rBtj|j�}�n~t|j�d
k�rbtj
|j�}�n^t|j�dk�r~tj�}�nBt|j�dk�r�tj|j�}�n"|jdk�r�tj|j�}�nt|j�dk�r�tj	|j�}n�|jd&k�r�tj|j�}n�|jd'k�rtj|j�}n�|jd(k�r&tj|j�}n�|jd)k�r@tj|j�}n�|jd*k�sX|jd+k�rftj|j�}nZ|jd,k�r�tj|j�}n@|jd-k�r�tj|j�}n&|jd.k�r�tj|j�}ntj|j�}|S)/N�r�nr�
������$�1�<�J�i�c�[�jiXiYiZi�i�i��=�������i�������i�i�i�i�i��i��i���i����i����i����i����i/���iD���iC���i������)Z	faultCoderZ$AuthenticationOrAccountCreationErrorZfaultStringZUnknownMethodExceptionZLoginMinLengthErrorZPasswordMinLengthErrorZValidationErrorZNoBaseChannelErrorZInsuffMgmntEntsErrorZ
PasswordError�absZ
AbuseErrorZAuthenticationTicketErrorZRegistrationDeniedErrorZRhnUuidUniquenessErrorZ
DelayErrorZInvalidRegistrationNumberErrorZNotEntitlingErrorZPasswordMaxLengthErrorZActivationKeyUsageLimitErrorZUnableToCreateUserZCommunicationError)r	ZfaultZ	exceptionrrrZ__exception_from_faultXsr












z%_DoCallWrapper.__exception_from_faultN)�__name__�
__module__�__qualname__�__doc__r
rr$rrrrrr.s
rc@s:eZdZdZddd�Zdd�Zee�Zdd	�Zd
d�Z	dS)
�	RhnServerz`
    An rpc server object that calls doCall for you, and catches lower
    level exceptions
    NFcCs,|dkrtj|||d�|_n||_d|_dS)N)�serverOverride�timeout�registration)rZ	getServerr�
_capabilities)r	rArB�rpcServerOverriderCrrrr
�szRhnServer.__init__cCsL|jdkrF|jj�}|dkr0|jj�|jj�}tj�|_|jj|�|jS)N)rDrZget_response_headersrCZwelcome_messagerZCapabilitiesZpopulate)r	ZheadersrrrZ__get_capabilities�s




zRhnServer.__get_capabilitiescCs|jj||�dS)N)r�
add_header)r	�key�valuerrrrF�szRhnServer.add_headercCst|j|�S)z6Return a callable object that will do the work for us.)rr)r	r
rrrr�szRhnServer.__getattr__)NNNF)
r<r=r>r?r
Z_RhnServer__get_capabilities�propertyrrFrrrrrr@�s

r@cs"eZdZdZd�fdd�	Z�ZS)�RegistrationRhnServerz�
    A specialized RhnServer subclass for handling registration-related calls.

    Intended to be used as a shorthand for registration tasks instead of
    the plain RhnServer.
    Ncstt|�j|||dd�dS)NT)rArBrErC)�superrJr
)r	rArBrE)�	__class__rrr
�s

zRegistrationRhnServer.__init__)NNN)r<r=r>r?r
�
__classcell__rr)rLrrJ�srJ)Zrhn.tbrZup2date_clientrrrrrr�ImportErrorZ
xmlrpc.clientZclient�objectrr@rJrrrr�<module>"sx+__pycache__/rhnserver.cpython-36.pyc000064400000012301150516774050013427 0ustar003

c8h;%�@s�ddlmZddlmZddlmZddlmZddlZddlZyddlZWne	k
rjddl
jZYnXGdd�de�Z
Gdd	�d	e�ZGd
d�de�ZdS)�)�
raise_with_tb)�	rpcServer)�
up2dateErrors)�capabilitiesNc@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�_DoCallWrapperze
    A callable object that will handle multiple levels of attributes,
    and catch exceptions.
    cCs||_||_dS)N)�_server�_method_name)�selfZserver�method_name�r�/usr/lib/python3.6/rhnserver.py�__init__5sz_DoCallWrapper.__init__cCst|jd|j|f�S)z= Recursively build up the method name to pass to the server. z%s.%s)rrr)r	r
rrr�__getattr__9sz_DoCallWrapper.__getattr__cOs�t|j|j�}ytj|f|�|�Stjk
rLt|jt	j
�d��Yn�tjj
k
r�tt	j
�d�}|jd�}|jd�}d}t|�dkr�|d}nt|�dkr�|d}|jd�}|dkr�ttj��nttj|��YnXdS)	z3 Call the method. Catch faults and translate them. �z[()]�,��z 'zcertificate verify failedN)�getattrrrrZdoCall�	xmlrpclibZFaultr�$_DoCallWrapper__exception_from_fault�sys�exc_info�OpenSSLZSSL�Error�str�strip�split�lenrZSSLCertificateVerifyFailedErrorZNetworkError)r	�args�kwargs�method�error�pieces�messagerrr�__call__>s$



z_DoCallWrapper.__call__cCs�|jdkrtj|j�}�n�|jdkr4tj|j�}�n�|jdkrNtj|j�}�nr|jdkrhtj|j�}�nX|jdkr�tj|j�}�n>|jd kr�tj|j�}�n$|jd!kr�tj|j�}�n
|jd"kr�tj|j�}�n�|jd#kr�tj|j�}�n�|jd$k�rtj	|j�}�n�|jd%k�r"tj
|j�}�n�t|j�dk�rBtj|j�}�n~t|j�d
k�rbtj
|j�}�n^t|j�dk�r~tj�}�nBt|j�dk�r�tj|j�}�n"|jdk�r�tj|j�}�nt|j�dk�r�tj	|j�}n�|jd&k�r�tj|j�}n�|jd'k�rtj|j�}n�|jd(k�r&tj|j�}n�|jd)k�r@tj|j�}n�|jd*k�sX|jd+k�rftj|j�}nZ|jd,k�r�tj|j�}n@|jd-k�r�tj|j�}n&|jd.k�r�tj|j�}ntj|j�}|S)/N�r�nr�
������$�1�<�J�i�c�[�jiXiYiZi�i�i��=�������i�������i�i�i�i�i��i��i���i����i����i����i����i/���iD���iC���i������)Z	faultCoderZ$AuthenticationOrAccountCreationErrorZfaultStringZUnknownMethodExceptionZLoginMinLengthErrorZPasswordMinLengthErrorZValidationErrorZNoBaseChannelErrorZInsuffMgmntEntsErrorZ
PasswordError�absZ
AbuseErrorZAuthenticationTicketErrorZRegistrationDeniedErrorZRhnUuidUniquenessErrorZ
DelayErrorZInvalidRegistrationNumberErrorZNotEntitlingErrorZPasswordMaxLengthErrorZActivationKeyUsageLimitErrorZUnableToCreateUserZCommunicationError)r	ZfaultZ	exceptionrrrZ__exception_from_faultXsr












z%_DoCallWrapper.__exception_from_faultN)�__name__�
__module__�__qualname__�__doc__r
rr$rrrrrr.s
rc@s:eZdZdZddd�Zdd�Zee�Zdd	�Zd
d�Z	dS)
�	RhnServerz`
    An rpc server object that calls doCall for you, and catches lower
    level exceptions
    NFcCs,|dkrtj|||d�|_n||_d|_dS)N)�serverOverride�timeout�registration)rZ	getServerr�
_capabilities)r	rArB�rpcServerOverriderCrrrr
�szRhnServer.__init__cCsL|jdkrF|jj�}|dkr0|jj�|jj�}tj�|_|jj|�|jS)N)rDrZget_response_headersrCZwelcome_messagerZCapabilitiesZpopulate)r	ZheadersrrrZ__get_capabilities�s




zRhnServer.__get_capabilitiescCs|jj||�dS)N)r�
add_header)r	�key�valuerrrrF�szRhnServer.add_headercCst|j|�S)z6Return a callable object that will do the work for us.)rr)r	r
rrrr�szRhnServer.__getattr__)NNNF)
r<r=r>r?r
Z_RhnServer__get_capabilities�propertyrrFrrrrrr@�s

r@cs"eZdZdZd�fdd�	Z�ZS)�RegistrationRhnServerz�
    A specialized RhnServer subclass for handling registration-related calls.

    Intended to be used as a shorthand for registration tasks instead of
    the plain RhnServer.
    Ncstt|�j|||dd�dS)NT)rArBrErC)�superrJr
)r	rArBrE)�	__class__rrr
�s

zRegistrationRhnServer.__init__)NNN)r<r=r>r?r
�
__classcell__rr)rLrrJ�srJ)Zrhn.tbrZup2date_clientrrrrrr�ImportErrorZ
xmlrpc.clientZclient�objectrr@rJrrrr�<module>"sx+__pycache__/getMethod.cpython-36.opt-1.pyc000064400000004401150516774050014272 0ustar003

c8h��@s�ddlZddlZddlZddlmZyddlmZWnek
rLeZYnXGdd�de	�Z
dd�Zdd	�Ze
d
kr�ddd
dddddgZxleD]dZede�yeed�ZWn>e
k
r�ej�dZededjeeej��f�Yq�Xe�q�WdS)�N)�
raise_with_tb)�	ClassTypec@seZdZdZdS)�GetMethodExceptionzException classN)�__name__�
__module__�__qualname__�__doc__�r	r	�/usr/lib/python3.6/getMethod.pyrsrcCsrtjtj}|tjd}xR|D]J}t|�s4td��x |D]}||kr:td|��q:W|d|kr td��q WdS)N�_zEmpty method componentz)Invalid character '%s' in the method namerz6Method names should start with an alphabetic character)�stringZascii_lowercaseZascii_uppercaseZdigits�lenr)�methodNameCompsZalphaZallowedChars�comp�cr	r	r
�sanitys

rc
Csz|jd�|jd�}t|�x~tt|�dd
�D]^}dj|d|��}yt|�}Wn8tk
rfw.Yn$tk
r�tt	d|��YnXPq.Wt	d|��|}|}x�tdt|��D]�}||}||k�r�t
||�s�t	ddj|d|��|f��t||�}q�t
|d��s$t	ddj|d|����t|d�}	||	k�rVt	d	dj|d|��|f��t||�}t|�t
kr�|�}q�W|S)N�.r�zCould not import module %szAction %s could not be importedzClass %s has no attribute %sZ
__rhnexport__zClass %s is not RHN-compliantzClass %s does not export '%s'���)�splitr�ranger
�join�
__import__�ImportError�	Exceptionrr�hasattr�getattr�typer)
Z
methodNameZ	baseClassr�indexZ
modulenameZactionsZfIndexZ	classNamerZexportr	r	r
�	getMethod.sB






r�__main__za.b.c.d.e.fza.b.c.d.e.foo.hz
a.b.c.d.e.g.hz
a.b.d.d.e.g.hza.b.d.d._e.g.hza.b.d.d.e_.g.hza.b.d.d.e-.g.hza.b.d.d..g.hz----Running method %s: ZActionsrzError getting the method %s: %s�)�osr�sysZrhn.tbr�typesrrrrrrrr�methods�m�print�method�exc_info�er�map�str�argsr	r	r	r
�<module>
s8
=
__pycache__/rhnreg_constants.cpython-36.pyc000064400000033300150516774050014774 0ustar003

c8h�H�@s�ddlmZmZddlZejddd�Zeed�s8eje_ejZed�Z	ed�Z
ed	�Zed
�Zed�Z
ed�Zed
�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Zed�Z ed�Z!ed �Z"ed!�Z#ed"�Z$ed#�Z%ed$�Z&ed%�Z'ed&�Z(ed'�Z)ed(�Z*ed)�Z+ed*�Z,ed+�Z-ed,�Z.ed-�Z/ed.�Z0ed/�Z1ed0�Z2ed1�Z3ed2�Z4ed3�Z5ed4�Z6ed5�Z7ed6�Z8ed7�Z9ed8�Z:ed9�Z;ed:�Z<ed;�Z=ed<�Z>ed=�Z?ed>�Z@ed?�ZAed@�ZBedA�ZCedB�ZDedC�ZEedD�ZFedE�ZGedF�eZHedG�ZIedH�ZJedI�ZKedJ�ZLedK�ZMedL�ZNedM�ZOedN�eZPedO�eZQedP�eefZRedQ�ZSedR�ZTedS�ZUedT�ZVeUdUeVdVZWedW�ZXedX�ZYedY�ZZedZ�Z[ed[�Z\ed\�Z]ed]�Z^ed^�Z_ed_�Z`ed`�Zaeda�Zbedb�Zcedc�Zdedd�Zeede�Zfedf�Zgedg�Zhedh�Ziedi�Zjedj�Zkedk�Zledl�Zmedm�Znedn�Zoedo�Zpedp�ZqdS)q�)�PM_PLUGIN_NAME�PM_NAMENzrhn-client-toolsT)Zfallback�ugettextu:Copyright © 2006--2014 Red Hat, Inc. All rights reserved.z"Enter your CloudLinux Network URL.z�Please enter the location of your CloudLinux Network server and of its SSL certificate. The SSL certificate is only required if you will be connecting over https (recommended).zSatellite URL:zSSL certificate:z%You must enter a valid Satellite URL.zNIf you are using https you must enter the location of a valid SSL certificate.z+Attempting to contact the Spacewalk server.zIWe are attempting to contact the CloudLinux Network Network server at %s.zA proxy was specified at %s.zSystem RegistrationaSThis assistant will guide you through connecting your system to CloudLinux Network to receive software updates, including security updates, to keep your system supported and compliant.  You will need the following at this time:

 * A network connection
 * Your CloudLinux Login & password
 * The location of a CloudLinux Network or Proxy

z Why Should I Connect to CLN? ...zWhy Registerz�Connecting your system to CloudLinux Network allows you to take full advantage of the benefits of a paid subscription, including:zSecurity & Updates:zDownloads & Upgrades:zSupport:zCompliance:zsReceive the latest software updates, including security updates, keeping this CloudLinux system updated and secure.zMDownload installation images for CloudLinux releases, including new releases.ztAccess to the technical support experts at CloudLinux for help with any issues you might encounter with this system.zsStay in compliance with your subscription agreement and manage subscriptions for systems connected to your account.zOTip: CloudLinux values your privacy: http://www.cloudlinux.com/company/privacy/z Take me back to the registrationzSoftware Update Not Set Upz�Are you sure you don't want to connect your system to CloudLinux Network? You'll miss out on the benefits of a CloudLinux subscription:
z~You will not be able to take advantage of these subscription privileges without connecting your system to CloudLinux Network.
z"Take me back to the setup process.zI'll register later.zCloudLinux AccountzDPlease enter your login information for the %s CloudLinux Network:

zCloudLinux Login:zLogin:z	Password:zYTip: Forgot your login or password?  Contact your Satellite's Organization Administrator.zPlease enter a desired login.z#Please enter and verify a password.z Operating System Release VersionzOperating System version:z Minor Release: zLimited Updates OnlyzAll available updatesz*Confirm operating system release selectionz]Your system will be subscribed to the base software channel to receive all available updates.zCreate Profile - Hardwarez�A Profile Name is a descriptive name that you choose to identify this System Profile on the CloudLinux Network web pages. Optionally, include a computer serial or identification number.zsAdditional hardware information including PCI devices, disk sizes and mount points will be included in the profile.z=Include the following information about hardware and network:zCreate Profile - PackageszeRPM information is important to determine what updated software packages are relevant to this system.zBInclude RPM packages installed on this system in my System Profilez>You may deselect individual packages by unchecking them below.zBuilding Package Listz*Email Address:zSystem Already RegisteredzDIt appears this system has already been set up for software updates:z(Are you sure you would like to continue?a�This system has already been registered using CloudLinux Subscription Management.

Your system is being registered again using CloudLinux Network or CloudLinux Network Proxy technology. CloudLinux recommends that customers only register once.

To learn more about RHN Classic/CloudLinux Network registration and technologies please consult this Knowledge Base Article: https://access.redhat.com/kb/docs/DOC-45563z.Send Profile Information to CloudLinux Networka
We are finished collecting information for the System Profile.

Press "Next" to send this System Profile to CloudLinux Network.  Click "Cancel" and no information will be sent.  You can run the registration program later by typing `rhn_register` at the command line.z%Sending Profile to CloudLinux NetworkzUpdates Configureda�You may now run '%s update' from this system's command line to get the latest software updates from CloudLinux Network. You will need to run this periodically to get the latest updates. Alternatively, you may configure this system for automatic software updates (also known as 'auto errata update') via the CloudLinux Network web interface.  (Instructions for this are in chapter 6 of the CLN Reference Guide, available from the 'Help' button in the main Red Hat Network Satellite web interface.)zReview Subscriptionz-Please review the subscription details below:zgThe installation number %s was activated during this system's initial connection to CloudLinux Network.zQSubscriptions have been activated for the following CloudLinux products/services:zSoftware Channel Subscriptions:zFThis system will receive updates from the following software channels:aJWarning: Only installed product listed above will receive updates and support. If you would like to receive updates for additional products, please login to your satellite web interface and subscribe this system to the appropriate software channels. See Kbase article for more details. (http://kbase.redhat.com/faq/docs/DOC-11313)zQWarning: %s is not present, could not enable it.
Automatic updates will not work.zNote: %s has been enabled.zbWarning: An error occurred during enabling %s.
%s is not enabled.
Automatic updates will not work.z�You were unable to be subscribed to the following software channels because there were insufficient subscriptions available in your account:a�This system was unable to subscribe to any software channels. Your system will not receive any software updates to keep it secure and supported. Contact your Satellite administrator about this problem. Once you make the appropriate active subscriptions available in your account, you may browse to this system's profile in the CLN web interface and subscribe this system to software channels via the software > software channels tab.zService Level:z�Depending on what CloudLinux Network modules are associated with a system, you'll enjoy different benefits. The following are the CloudLinux Network modules associated with this system:�
z
%sz�This system was unable to be associated with the following CLN module(s) because there were insufficient subscriptions available in your account:z�Management module: automatic updates, systems grouping, systems permissions, system package profiling, bare-metal provisioning, existing state provisioning, rollbacks, configuration managementz^Virtualization module: software updates for a limited number of virtual guests on this system.a�<b>Warning:</b> Any guest systems you create on this system and register to RHN will consume CloudLinux subscriptions beyond this host system's subscription. You will need to: (1) make a virtualization system entitlement available and (2) apply that system entitlement to this system in CLN's web interface if you do not want virtual guests of this system to consume additional subscriptions.a�This system was unable to be associated with any CLN service level modules. This system will not receive any software updates to keep it secure and supported. Contace your Satellite administrator about this problem. Once you make the appropriate active subscriptions available in your account, you may browse to this system's profile in the CLN web interface, delete the profile, and re-connect this system to CloudLinux Network.aJUniversal default activation key detected
A universal default activation key was detected in your account. This means that a set of properties (software channel subscriptions, package installations, system group memberships, etc.) for your system's connection to CloudLinux Network or CloudLinux Network Proxyhave been determined by the activation key rather than your installation number.  You may also refer to the RHN Reference Guide, section 6.4.6 for more details about activation keys (http://access.redhat.com/knowledge/docs/Red_Hat_Network/)
Universal Default activation key: %szFatal Error�WarningaXWe can't contact the CloudLinux Network.

Double check the location provided - is '%s' correct?
If not, you can correct it and try again.

Make sure that the network connection on this system is operational.

This system will not be able to successfully receive software updates from CloudLinux without connecting to a CloudLinux Network serverz0Architecture: %s, OS Release: %s, OS Version: %sz�This server doesn't support functionality needed by this version of the software update setup client. Please try again with a newer server.a�<b><span size="16000">Incompatible Certificate File</span></b>

The certificate you provided, <b>%s</b>, is not compatible with  the CloudLinux Network server at <b>%s</b>. You may want to double-check that you have provided a valid certificate file. Are you sure you have provided the correct certificate, and that the certificate file has not been corrupted?

Please try again with a different certificate file.z�<b><span size="12000">Incompatible Certificate File</span></b>

 The certificate is expired. Please ensure you have the correct  certificate and your system time is correct.aPlease verify the values of sslCACert and serverURL in /etc/sysconfig/rhn/up2date. You can either make the serverURL use http instead of https, or you can download the SSL cert from your Satellite, place it in /usr/share/rhn, and ensure sslCACert points to it.a�Problem registering system.

A universal default activation key limits the number of systems which can connect to the CLN organization associated with your login. To allow this system to connect, please contact your CLN organization administrator to increase the number of systems allowed to connect or to disable this universal default activation key. More details can be found in CloudLinux Knowledgebase Article #7924 at http://kbase.redhat.com/faq/FAQ_61_7924.shtm zI
 Tip: Minor releases with a '*' are currently supported by CloudLinux.

z�Warning:You will not be able to limit this system to minor release that is older than the recent minor release if you select this option.
z�Your system will be subscribed to %s 
base software channel. You will not be
able to move this system to an earlier release
(you will be able to move to a newer release).
Are you sure you would like to continue?�OK�ErrorZNextZBackZCancelz
No, Cancelz
Yes, Continuez%Press <space> to deselect the option.)rZup2date_client.pmPluginrr�gettextZtranslation�t�hasattrr�_ZCOPYRIGHT_TEXTZSATELLITE_URL_WINDOWZSATELLITE_URL_TEXTZSATELLITE_URL_PROMPTZSATELLITE_URL_PROMPT2ZSATELLITE_REQUIREDZSSL_REQUIREDZCONNECT_WINDOWZCONNECT_WINDOW_TEXTZCONNECT_WINDOW_TEXT2ZSTART_REGISTER_WINDOWZSTART_REGISTER_TEXTZWHY_REGISTERZWHY_REGISTER_WINDOWZWHY_REGISTER_TEXTZWHY_REGISTER_SECZWHY_REGISTER_DLDZWHY_REGISTER_SUPPZWHY_REGISTER_COMPZWHY_REGISTER_SEC_TXTZWHY_REGISTER_DLD_TXTZWHY_REGISTER_SUPP_TXTZWHY_REGISTER_COMP_TXTZWHY_REGISTER_TIPZ
BACK_REGISTERZCONFIRM_QUITZCONFIRM_QUIT_SUREZCONFIRM_QUIT_WILLNOTZCONTINUE_REGISTERINGZREGISTER_LATER2ZREGISTER_WINDOWZLOGIN_PROMPTZHOSTED_LOGINZLOGINZPASSWORDZ	LOGIN_TIPZ
USER_REQUIREDZPASSWORD_REQUIREDZSELECT_OSRELEASEZ
OS_VERSIONZ
MINOR_RELEASEZLIMITED_UPDATESZALL_UPDATESZCONFIRM_OS_RELEASE_SELECTIONZCONFIRM_OS_ALLZHARDWARE_WINDOWZHARDWARE_WINDOW_DESC1ZHARDWARE_WINDOW_DESC2ZHARDWARE_WINDOW_CHECKBOXZPACKAGES_WINDOWZPACKAGES_WINDOW_DESC1ZPACKAGES_WINDOW_DESC2ZPACKAGES_WINDOW_UNCHECKZPACKAGES_WINDOW_PKGLISTZEMAILZSYSTEM_ALREADY_SETUPZSYSTEM_ALREADY_REGISTEREDZSYSTEM_ALREADY_REGISTERED_CONTZRHSM_SYSTEM_ALREADY_REGISTEREDZSEND_WINDOWZSEND_WINDOW_DESCZSENDING_WINDOWZ
FINISH_WINDOWZFINISH_WINDOW_TEXT_TUIZ
REVIEW_WINDOWZREVIEW_WINDOW_PROMPTZSUB_NUMZSUB_NUM_RESULTZCHANNELS_TITLEZOK_CHANNELSZCHANNELS_SAT_WARNINGZPM_PLUGIN_WARNINGZPM_PLUGIN_CONF_CHANGEDZPM_PLUGIN_CONF_ERRORZFAILED_CHANNELSZNO_BASE_CHANNELZSLOTS_TITLEZOK_SLOTSZSLOTSZFAILED_SLOTSZ
MANAGEMENTZVIRTZVIRT_FAILEDZNO_SYS_ENTITLEMENTZACTIVATION_KEYZFATAL_ERRORZWARNINGZHOSTED_CONNECTION_ERRORZBASECHANNELERRORZSERVER_TOO_OLDZSSL_CERT_ERROR_MSGZSSL_CERT_EXPIREDZSSL_CERT_FILE_NOT_FOUND_ERRERZACT_KEY_USAGE_LIMIT_ERRORZCHANNEL_PAGE_TIPZCHANNEL_PAGE_WARNINGZCONFIRM_OS_WARNINGrZERRORZNEXTZBACKZCANCELZ	NO_CANCELZYES_CONTZDESELECT�r
r
�&/usr/lib/python3.6/rhnreg_constants.py�<module>
s�



	__pycache__/debUtils.cpython-36.pyc000064400000004262150516774050013173 0ustar003

c8h�@slddlZddlZddlZejddd�Zeed�s8eje_ejZdd�Zdd	�Z	d
d�Z
ddd
�Zdd�ZdS)�Nzrhn-client-toolsT)Zfallback�ugettextcCsHtj�}g}x2|D]*}||d}|dks2|jr|j|�qWg|fS)Nr)�apt�CacheZis_installed�append)Zpackages�cacheZmissing_packages�package�pkg�r	�/usr/lib/python3.6/debUtils.py�verifyPackagess
rcCs`d}d}|jd�dkr$|jd�\}}|jd�dkrV|jd�}dj|dd��}|d	}|||fS)
N��X�:��-���rrr)�find�split�join)�version�epoch�releaseZtmpr	r	r
�parseVREs
rcCstd}d|d||fg}d|kr<|jd|d|jd���x2|D]*}tjj||�}tjj|�rBtjj|�SqBWdS)Nz/var/lib/dpkg/infoz%s.listz
%s:%s.listrr)r�index�os�pathr�isfile�getmtime)Zpkg_nameZpkg_arch�dir�files�frr	r	r
�installTime(s
r!c
	Cs�|dkr|td��tj�}d}x|D]}|jdkr&|d7}q&Wd}g}xv|D]n}|jdkr^qNt|jj�\}	}
}|j||	|
|jjdt|j|jj�d�}|j	|�|dkr�|||�|d}qNW|j
dd�d	�|S)
z} Return list of packages. Package is dict with following keys:
        name, epoch, version, release and optionaly arch.
    Nz0Getting list of packages installed on the systemrrz-deb)�namerrrZarchZinstalltimecSs|dS)Nrr	)rr	r	r
�<lambda>Zsz)getInstalledPackageList.<locals>.<lambda>)�key)�_rrZ	installedrrr"Zarchitecturer!r�sort)
ZmsgCallbackZprogressCallbackZgetArchZgetInforZtotalr�countZpkg_listrrrrr	r	r
�getInstalledPackageList8s2






r(cCsdS)Nr	r	r	r	r
�setDebugVerbosity]sr))NNNN)
rr�gettextZtranslation�t�hasattrrr%rrr!r(r)r	r	r	r
�<module>s


$__pycache__/pkgplatform.cpython-36.pyc000064400000000440150516774050013740 0ustar003

ge8h5�@sdZdd�ZdS)�rpmcCstdkrtSdSdS)Nz@PLATzFORM@rz
@PLATFORM@)�	_platform�rr�!/usr/lib/python3.6/pkgplatform.py�getPlatform	srN)rrrrrr�<module>s__pycache__/rpcServer.cpython-36.opt-1.pyc000064400000016762150516774050014342 0ustar003

c8h�.�@sPddlZddlZddlZddlZddlmZddlmZddlmZddlmZddlm	Z	ddl
mZddl
mZdd	l
mZy$ddlZddlZddlZddlZWn<ek
r�ddljZddljZddljZddljZYnXddlZejd
dd�Zeed
��seje_ejZ dd�Z!Gdd�dej"�Z#Gdd�d�Z$ddd�Z%dd�Z&dS)�N)�config)�
clientCaps)�
up2dateLog)�
up2dateErrors)�up2dateUtils)�SSL)�rpclib)�
raise_with_tbzrhn-client-toolsT)Zfallback�ugettextcCst|�dS)N)�print)�msg�r
�/usr/lib/python3.6/rpcServer.py�stdoutMsgCallback&src@s(eZdZiZdd�Zdd�Zdd�ZdS)�RetryServercCs
||_dS)N)�
serverList)�selfrr
r
r�
addServerList.szRetryServer.addServerListc
Cs�tj�|_�x�y|j||�}W�n�tjk
r:�Y�n�tjk
rR�Y�nntj	k
r�|jj
d�ttd��t
jd�Y�n6|jj�}|dkr�|jj�|jr�djdd�|jj�D��}ttd��t|��d|j}dt
j�d	t
j�df}||j|j<||}|d
|jj�}|jj
|�tj|jj��}|d	}	|d|_|d|_|	j�}	|	dk�r�ttjd|	��|j|_|	|_|jj�|_|j�s�d|_d|_ wYnXPqW|S)Nz,Error: Server Unavailable. Please try later.��
cSsg|]\}}d||f�qS)z%s:
%sr
)�.0�host�errorr
r
r�
<listcomp>Lsz)RetryServer._request1.<locals>.<listcomp>z>Errors occurred while trying to connect to the remote servers.z!An error occurred talking to %s:
z%s
%s
rzTrying the next serverURL: %s
��http�httpsz%Redirected to unsupported protocol %sz/RPC2���)rr)!r�initLog�logZ_requestrZInvalidRedirectionError�	xmlrpclibZFault�httplibZ
BadStatusLine�log_mer�_�sys�exitr�next�resetServerIndex�_error_messages�join�itemsZ_host�exc_info�server�urlparseZurlsplitZ_handler�lowerr	Z
_orig_handlerZ_typeZ_uriZ_allow_redirect)
rZ
methodnameZparams�retr,Zerror_combined_msgrZ
exception_msgZ	parse_res�typr
r
r�	_request11sX






zRetryServer._request1cCstjj|j|�S)N)rr Z_Methodr1)r�namer
r
r�__getattr__sszRetryServer.__getattr__N)�__name__�
__module__�__qualname__r(rr1r3r
r
r
rr*sBrc@s0eZdZgfdd�Zdd�Zdd�Zdd�Zd	S)
�
ServerListcCs||_d|_dS)Nr)r�index)rZ
serverlistr
r
r�__init__zszServerList.__init__cCs|j|j|_|jS)N)rr8Z	serverurl)rr
r
rr,~szServerList.servercCs(|jd|_|jt|j�kr dS|j�S)Nr)r8�lenrr,)rr
r
rr&�szServerList.nextcCs
d|_dS)Nr)r8)rr
r
rr'�szServerList.resetServerIndexN)r4r5r6r9r,r&r'r
r
r
rr7ysr7FcCs�tj�}tj�}|d}t|t�s(|g}|p0dg}|drDtj�}nd}|s�tj|d�}	tj|d�}
|
r�x$|
D]}||	krn|	j	|�qnWn|}	t
|	�}d}
d}|dr�|dp�d}
|dp�d}d}xFdD]>}|tjkr�tj|s�q�tj|j
d�d
}|j
d�d
}Pq�Wt|j�|||
||d�}|j|�|jdtj��|�rL|j|�dd�|jjD�}|�r�xP|D]H}tj|tj��s�dtd�|f}|jd|�tj|��|j|��qjWtj�tjj �}x|D]\}}|j||��q�W|S)NZ	sslCACertz'/usr/share/rhn/CLN-ORG-TRUSTED-SSL-CERTZenableProxy)�registrationZenableProxyAuth�	proxyUser�
proxyPassword�LANGUAGE�LC_ALL�LC_MESSAGES�LANG�:r�.)�refreshCallback�proxyZusernameZpassword�timeoutzX-Up2date-VersioncSs"g|]}tj|�ddkrd�qS)rrT)r-)r�ir
r
rr�szgetServer.<locals>.<listcomp>z%s: %sz ERROR: can not find RHNS CA filez%s)r>r?r@rA)!rrr�initUp2dateConfig�
isinstance�listZgetProxySettingZgetServerURLZgetFallbackServerURL�appendr7�os�environ�splitrr,rZ
add_headerr�versionZsetlangr�access�R_OKr#r"rZSSLCertificateFileNotFoundZadd_trusted_certrZ
loadLocalCapsZcapsZheaderFormat)rDZserverOverriderFr;r�cfgZcaZ
rhns_ca_certsZ	proxyHostZ
serverUrlsZfallbackURL�urlrr<r=Zlang�env�sZneed_caZrhns_ca_certrZ
headerlistZ
headerName�valuer
r
r�	getServer�sn











rWcOs�tj�}|jd|jd�tj�}d}d}yt|d�}Wntk
rTd}YnX|dkrbd}�xPd}d}y|||�}W�n�tk
r�t	t
jtd���Y�n�t
jtjfk
�r4|jdtj�d|f�||k�r*tj�d}	t|	j�dk�rt	t
j|	jd��nt	t
j|	jd��nd}Y�nBtjk
�rbtd�t	t
jd��Y�ntjk
�r�tj�d}	d	}
|
d
|	j}
|
d|	j}
|
d|	j}
|j|
�t	t
j|
��Y�n�tjk
�rPtj�d}	|jd
|	j |f�|	j!dk�r$|jd|	j"�|jd�t#j$|	j%�\}}d}
t&|�dk�rh|jd|�ddl'm(}|j)�t&|�dk�r�|jtd��t	t
j|	j ��t&|�dk�r&t*|d�t*g�k�r�|d}n|d}t*|�t*g�k�r�d|d|d|d|df}n|}d||f}
|j|
�t	t
j+|
��|
�sL||k�rHt	t
j|	j ��nd}Yn&tj,k
�rtt	t
jd��YnX|dk�r�Pnd}|�r�t-j.d�|d}||krft
jd��qfW|S)NzrpcServer: Calling XMLRPC %sZ
_Method__namerZnetworkRetriesrzConnection aborted by the userz(A socket error occurred: %s, attempt #%szhttplib.IncompleteReadz
An HTTP error occurred:
zURL: %s
zStatus Code: %s
zError Message: %s
z,A protocol error occurred: %s , attempt #%s,i�zCould not find URL, %sz)Check server name and/or URL, then retry
�"z'Auth token timeout occurred
 errmsg: %s)�up2dateAuth�3z.Server has refused connection due to high load�z%s-%s-%s.%sr�zFile Not Found: %s
%sz Broken response from the server.�z0The data returned from the server was incomplete)/rrZ	log_debug�__dict__rrH�int�
ValueError�KeyboardInterruptr	rZCommunicationErrorr#�socketrrZsocket_errorr"r$r+r:�argsr!ZIncompleteReadr�urllib2Z	HTTPError�filename�coderr Z
ProtocolError�errmsgZerrcoderSrZreportErrorZheaders�abs�up2date_clientrYZupdateLoginInfo�type�FileNotFoundErrorZ
ResponseError�timeZsleep)�methodrc�kwargsrrRr/Z
attempt_countZattemptsZfailure�erZerrCodeZerrMsg�resetrYZpkgZpkgNamer
r
r�doCall�s�





"



rq)NNNF)'rLr$rbrlrirrrrrZrhnrrZrhn.tbr	r!rdr-r �ImportErrorZhttp.clientZclientZurllib.requestZrequestZurllib.parse�parseZ
xmlrpc.client�gettextZtranslation�t�hasattrr
r#rZServerrr7rWrqr
r
r
r�<module>sD


O
T__pycache__/rhncli.cpython-36.pyc000064400000016256150516774050012705 0ustar003

c8hw$�@svddlZddlZddlZddlmZddlmZddlmZddlmZddl	m
Z
ddlmZyddl
Z
Wnek
r�ddljZ
YnXddlZejdd	d
�Zeed�s�eje_ejZddlmZdd
lmZddlmZddlmZddlmZddlmZedddded�d�edded�d�edded�d�edded�d�edd ed!�d�gZGd"d#�d#e�Z d$d%�Z!dS)&�N)�Option)�OptionParser)�SSL)�crypto)�rpclib)�sstrzrhn-client-toolsT)Zfallback�ugettext)�config)�up2dateAuth)�
up2dateErrors)�
up2dateLog)�up2dateUtils)�pkgUtilsz-vz	--verbose�countzShow additional output)�action�default�helpz--proxyZstorezSpecify an http proxy to use)rrz--proxyUserz:Specify a username to use with an authenticated http proxyz--proxyPasswordz:Specify a password to use with an authenticated http proxyz--debug�
store_truez&Enable debug output (network requests)c@steZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Ze
dd��Ze
dd��ZdS)�RhnClicCs(tttj�d�|_d|_d|_d|_dS)N)Zoption_list�versionF)r�
_optionsTabler�_RhnCli__versionString�	optparser�options�args�hasGui)�self�r�/usr/lib/python3.6/rhncli.py�__init__Qs
zRhnCli.__init__cCs�tt_y |j�tj|j�pd�W�n�tk
rZtjjt	t
d���tjd�Y�n�tk
r�tjjt	t
d�tj�d��tjd�Y�nRt
jk
�rtj�d}|dks�tt|��dkr�tjjt	t
d���ntjjt	t
d�|��Y�n�tk
�rBtjjt	t
d�tj�d��tjd�Y�n�tjk
�r�tjjt	t
d�tj�d��tjjt	t
d	���tjd�Y�nRtjtjfk
�r�tjjt	d
ttj�d���tjd�Y�n
tjk
�rtjjt	t
d�tj�d��Yn�tk
�r,�Yn�tjk
�rltjjt	t
d
�tj�d��tjd�Yn~tjk
�r�tjjt	dtj�d��tjd�YnBtjk
�r�tjjt	dttj�d���tjd�YnXdS)Nrz

Aborted.
�z$An unexpected OS error occurred: %s
z1A connection was attempted with a malformed URI.
z5A connection was attempted with a malformed URI: %s.
z%There was some sort of I/O error: %s
zThere was an SSL error: %s
zqA common cause of this error is the system time being incorrect. Verify that the time on this system is correct.
zOpenSSL.SSL.SysCallError: %s
�z!There was a SSL crypto error: %s
z&There was an authentication error: %s
z%s
zXMLRPC ProtocolError: %s
�)�exceptionHandler�sys�
excepthook�
initialize�exit�main�KeyboardInterrupt�stderr�writer�_�OSError�exc_inforZMalformedURIError�len�str�IOErrorr�ErrorZSysCallError�socket�errorr�
SystemExitr�AuthenticationErrorZRpmError�	xmlrpclibZ
ProtocolError)r�errr�runZsL    $  z
RhnCli.runcCsn|jj�\|_|_tj|jj�tj�dkrRt	d�t
jd}|j|�t
j
d�|jjrb|j�|j�dS)NrzYou must be root to run %sr )r�
parse_argsrrr�_RhnCli__setDebugLevel�verbose�os�geteuidr,r$�argv�_warning_dialogr'�debug�_initialize_debug_network_logs�_RhnCli__updateProxyConfig)rZrootWarningMsgrrrr&�s

zRhnCli.initializecCst�dS)N)�NotImplementedError)rrrrr(�szRhnCli.maincCsxddl}yddlm}Wn tk
r8ddlm}YnXd|_|j�|j�j|j	�|jd�}|j|j	�d|_
dS)zF
        Enables logging of all all https requests to console
        rN)�HTTPConnectionr zrequests.packages.urllib3T)�loggingZhttp.clientrE�ImportErrorZhttplibZ
debuglevelZbasicConfigZ	getLoggerZsetLevel�DEBUGZ	propagate)rrFrEZrequests_logrrrrB�s
z%RhnCli._initialize_debug_network_logscCs�ytj�dStjk
r2ttj�d�dStjk
rFdStjk
rzt	j
�}|jd�|jtj��dSXdS)NTr Fz4There was a RhnServerException while testing login:
)
r
ZupdateLoginInforZServerCapabilityError�printr$r.r6ZRhnServerExceptionr�initLogZlog_me�
log_exception)r�logrrr�
_testRhnLogin�s
zRhnCli._testRhnLoginc	CsP|jrDyddlm}|j|�WqLttd��t|�YqLXnt|�dS)Nr)�guiz'Unable to open gui. Try `up2date --nox`)r�up2date_clientrN�errorWindowrIr,)r�messagerNrrrr@�szRhnCli._warning_dialogcCsxtj�}|jjr,|jd|jj�|jdd�|jjrP|jd|jj�|jdd�|jjrt|jd|jj�|jdd�dS)z�Update potential proxy configuration.
        Note: this will _not_ save the info to up2date's configuration file
        A separate call to config.initUp2dateConfig.save() is needed.
        Z	httpProxyZenableProxyr �	proxyUserZenableProxyAuth�
proxyPasswordN)r	�initUp2dateConfigr�proxy�setrRrS)r�cfgrrrZ__updateProxyConfig�szRhnCli.__updateProxyConfigcCstj�}|j�dS)zM
        Saves the current up2date configuration being used to disk.
        N)r	rTZsave)rrWrrr�
saveConfig�szRhnCli.saveConfigc	CsP|jrDyddlm}|j|�WqLttd��t|�YqLXnt|�dS)Nr)rNz'Unable to open gui. Try `up2date --nox`)rrOrNrPrIr,)rZerrMsgrNrrrZ__faultError�szRhnCli.__faultErrorcCstd�tj�}|S)Nzp%%prog (Spacewalk Client Tools) %s
Copyright (C) 1999--2014 Red Hat, Inc.
Licensed under the terms of the GPLv2.)r,r
r)Z
versionStringrrrZ__versionString�s
zRhnCli.__versionStringcCs0tj�}|d||d<|ddkr,tj�dS)NrAr!)r	rTrZsetDebugVerbosity)�levelrWrrrZ__setDebugLevel�szRhnCli.__setDebugLevelN)�__name__�
__module__�__qualname__rr9r&r(rBrMr@rCrXZ_RhnCli__faultError�staticmethodrr;rrrrrOs	,rcCs�tj�}tjjttd�d��t|d�rPtjjt|j�d�|j	|||�n&tjjtt
|�d��|j	|||�tjjttd�d��dS)NzAn error has occurred:�
�errmsgz)See /var/log/up2date for more information)rrJr$r*r+rr,�hasattrr_rKr0)�type�value�tbrLrrrr#�s
r#)"r$r=r3ZoptparserrZOpenSSLrrZrhnrZrhn.i18nrr7rGZ
xmlrpc.clientZclient�gettextZtranslation�tr`rr,rOr	r
rrr
rr�objectrr#rrrr�<module>"sH





)__pycache__/__init__.cpython-36.pyc000064400000000161150516774050013151 0ustar003

c8h�@sdS)N�rrr�/usr/lib/python3.6/__init__.py�<module>s__pycache__/__init__.cpython-36.opt-1.pyc000064400000000161150516774050014110 0ustar003

c8h�@sdS)N�rrr�/usr/lib/python3.6/__init__.py�<module>s__pycache__/rhnHardware.cpython-36.pyc000064400000000724150516774050013664 0ustar003

c8hH�@s0ddlmZddlmZddlmZdd�ZdS)�)�up2dateAuth)�	rpcServer)�hardwarecCs&tj�}tj�}|jjtj�|�dS)N)rZ	getServerrZHardwareZregistrationZrefresh_hw_profilerZgetSystemId)�sZhardwareList�r�!/usr/lib/python3.6/rhnHardware.py�updateHardwaresrN)Zup2date_clientrrrrrrrr�<module>s__pycache__/tui.cpython-36.pyc000064400000076402150516774050012226 0ustar003

c8hͮ�@s(ddlmZddlZddlZejddd�Zeed�s<eje_ejZddl	Z	ddl
Z
ddlmZm
Z
ddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZmZddlTej �Z!ej"�Z#dd�Z$dd�Z%dd�Z&dd�Z'dd�Z(Gdd�de)�Z*Gd d!�d!�Z+Gd"d#�d#�Z,Gd$d%�d%�Z-Gd&d'�d'�Z.Gd(d)�d)�Z/Gd*d+�d+�Z0Gd,d-�d-�Z1Gd.d/�d/�Z2Gd0d1�d1�Z3Gd2d3�d3�Z4Gd4d5�d5�Z5Gd6d7�d7�Z6Gd8d9�d9�Z7Gd:d;�d;�Z8Gd<d=�d=�Z9d>d?�Z:e;d@k�r$e:�dS)A�)�geteuidNzrhn-client-toolsT)Zfallback�ugettext)�rhnreg�hardware)�
up2dateErrors)�up2dateUtils)�pkgUtils)�
up2dateLog)�config)�convert_url_from_puny)�up2dateAuth)�rpclib)�idn_puny_to_unicode)�sstr)�PM_PLUGIN_NAME�PM_PLUGIN_CONF)�*cCs&tj|tt�td|�tt�g�dS)Nz%s)�snack�ButtonChoiceWindowr�ERROR�BACK)�screen�errmsg�r�/usr/lib/python3.6/tui.py�ErrorWindow/srcCs8tj|tt�td|�tt�g�|j�tjd�dS)Nz%s�)rrrZFATAL_ERROR�OK�finish�sys�exit)rrrrr�FatalErrorWindow3sr!cCs.tj|tt�td|�tt�g�|j�dS)Nz%s)rrr�WARNINGrr)rrrrr�
WarningWindow9sr#cCs�tj|tt�tt�dtt�dtt�dtt�dtt�dtt	�dtt
�dtt�dtt�dtt
�dtt�tt�tt�gdd�}|tt�j�kr�|j�dSdSdS)N�
z

�F)�widthrr)rrrZCONFIRM_QUITZCONFIRM_QUIT_SURE�WHY_REGISTER_SEC�WHY_REGISTER_SEC_TXT�WHY_REGISTER_DLD�WHY_REGISTER_DLD_TXT�WHY_REGISTER_SUPP�WHY_REGISTER_SUPP_TXT�WHY_REGISTER_COMP�WHY_REGISTER_COMP_TXTZCONFIRM_QUIT_WILLNOT�WHY_REGISTER_TIPZCONTINUE_REGISTERINGZREGISTER_LATER2�lowerr)r�buttonrrr�ConfirmQuitWindow?s
vr2c
Gs�y||�}Wn�tjk
rDt|ttj�d�tj�d�Yn�tjk
rpt||j	�tj�d�Yn�tj
k
r�tj�d}t||j	dtt
j�t
j�t
j�f�Yn:tjk
r�tj�d}t||j	dt�|�YnX|S)Nrrr$z

)r�CommunicationErrorrZHOSTED_CONNECTION_ERRORr
�getServerURLr�exc_infoZSSLCertificateVerifyFailedErrorrZNoBaseChannelErrorr!ZBASECHANNELERRORr�getArchZgetOSRelease�
getVersionZSSLCertificateFileNotFoundZSSL_CERT_FILE_NOT_FOUND_ERRER)r�funcZparams�results�errr�tui_call_wrapperVs(
r;c@seZdZdS)�WindowSkipExceptionN)�__name__�
__module__�__qualname__rrrrr<nsr<c@s(eZdZdZdd�Zdd�Zdd�ZdS)�AlreadyRegisteredWindowc	Cs<tj�s|jrt��||_||_tjj�}t	j
jtj
��}|ddd}|ddd}tj|jtt�dd�}tj|jtt�dftt�dfg�|_|j|jdddd�tj|dd	|dd
ttdtd�d
t|jj�dtd�d
|dtd�d
|dtd�dd�}|j|dddd�||_dS)NrZusername�	system_idr��nextr )�growx��z

zSpacewalk Location:� r$zLogin:z
System ID:)�padding)rrrr)rZ
registered�testr<r�tuir�_snack�sizer
Z	xmlrpclib�loadsrZgetSystemId�GridFormr�SYSTEM_ALREADY_SETUP�	ButtonBar�YES_CONT�	NO_CANCEL�bb�add�TextboxZSYSTEM_ALREADY_REGISTERED�_r�	serverURL�SYSTEM_ALREADY_REGISTERED_CONT�g)	�selfrrJrLZsystemIdXmlZoldUsernameZoldsystemId�toplevel�tbrrr�__init__ts&

Tz AlreadyRegisteredWindow.__init__cCsdS)Nr)rZrrr�saveResults�sz#AlreadyRegisteredWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %s�F12rC)�log�	log_debug�namerY�runOncerS�
buttonPressed)rZ�resultr1rrr�run�s
zAlreadyRegisteredWindow.runN)r=r>r?rbr]r^rfrrrrr@qsr@c@s0eZdZdZdd�Zdd�Zdd�Zdd�Zd	S)
�SatelliteUrlWindowcCs�||_||_d|j_t|jj�|_tj|j�}||jkrR||_tj	|j�t
j�tj
j�}tj|tt�dd�}t}t}t}tj|dddt|�ddd�}	|j|	dddd�tjtd��}	|j|	dd�tjd	d�}
tjt|��}	|
j|	ddddd
�tjd�|_|jj|j�|
j|jdddd�tjt|��}	|
j|	ddddd
�tjd�|_|jj|j�|
j|jdddd�|j|
dd	�tj|tt �dftt!�d
ftt"�dfg�|_#|j|j#ddddd�||_$dS)Nrr��
�)�scroll�wrap)�
anchorLeft�rB)rH�anchorRight�(rC�back�cancel)rHrD)rrrr)rrrr)rrrr)%rrJ�alreadyRegisteredrrW�serverr�makeNiceServerUrlr
�setServerURL�cfg�saverrKrLrNrZSATELLITE_URL_WINDOWZSATELLITE_URL_TEXTZSATELLITE_URL_PROMPTZSATELLITE_URL_PROMPT2rUrT�Label�Grid�setField�Entry�urlEntry�set�sslEntry�	sslCACertrP�NEXTr�CANCELrSrY)rZrrJ�fixed_server_urlrLr[Zprompt_textZ	url_labelZ	ssl_label�label�gridrrrr]�sT




zSatelliteUrlWindow.__init__cCs�|jj�dkrBtj|jtt�tt�tt�gd�|j	j
|j�dS|jj�dd�dkr�|jj�dkr�tj|jtt�tt�tt�gd�|j	j
|j�dSdS)Nrn)�buttonsr�Zhttpsr)
r}�valuerrrrrZSATELLITE_REQUIREDrrY�
setCurrentrZSSL_REQUIRED)rZrrr�validateFields�sz!SatelliteUrlWindow.validateFieldscCs\|jj�}tj|�}||kr |}||j_|jj�|j_tj	|�tj
|jj��tj�dS)N)
r}r�rrurJrWrr�r
rvZsetSSLCACertrwrx)rZZserverEntryr�rrrr^�s


zSatelliteUrlWindow.saveResultscCsltjd|j�|jj�d}x>|s\|jj�}|jj|�}|dkrFd}|dkrX|j	�}q Pq W|jj
�|S)Nz
Running %srr_rC)r`rarbr�refreshrYrfrSrdr��	popWindow)rZ�validrer1rrrrfs



zSatelliteUrlWindow.runN)r=r>r?rbr]r�r^rfrrrrrg�s
A
rgc@s(eZdZdZdd�Zdd�Zdd�ZdS)�*AlreadyRegisteredSubscriptionManagerWindowcCs�tj�s|jrt��||_||_tjj�}tj	|jt
t�dd�}tj|jt
t
�dft
t�dfg�|_|j|jdddd�tj|dd|ddt
td	td	td
�dd�}|j|dddd�||_dS)
NrrBrCr r)rDrErFz

r$)rH)rrrr)rZrhsm_registeredrIr<rrJrrKrLrNrrOrPrQrRrSrTrUr"ZRHSM_SYSTEM_ALREADY_REGISTEREDrXrY)rZrrJrLr[r\rrrr]s 

z3AlreadyRegisteredSubscriptionManagerWindow.__init__cCsdS)Nr)rZrrrr^2sz6AlreadyRegisteredSubscriptionManagerWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %sr_rC)r`rarbrYrcrSrd)rZrer1rrrrf5s
z.AlreadyRegisteredSubscriptionManagerWindow.runN)r=r>r?rbr]r^rfrrrrr�sr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�
ConnectWindowcCs�||_||_tjj�}t|jj�|_td|_	tj
|jtt�dd�}t
|jd}|j	rf|t|j	7}tj|dd|ddt|�dd�}|j|dddd�||_dS)	NZ	httpProxyrz

rrErF)rH)rrrr)rrJrrKrLrrWrtrw�proxyrNrZCONNECT_WINDOWZCONNECT_WINDOW_TEXTZCONNECT_WINDOW_TEXT2rUrTrY)rZrrJrLr[�textr\rrrr]Cs

zConnectWindow.__init__c	CsPtjd|j�|jj�}|jj�yt|jtj	�Wn
dS|jj
�dS)Nz
Running %srqrC)r`rarbrY�drawrr�r;rZgetCapsr�)rZrerrrrf\s


zConnectWindow.runcCsdS)Nr)rZrrrr^qszConnectWindow.saveResultsN)r=r>r?rbr]rfr^rrrrr�@sr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�StartWindowcCs�||_||_tjj�}tj|jtt�dd�}tt�}tj	|dd|dd|dd�}|j
|dddd�tj|jtt�dftt
�dftt�d	fg�|_|j
|jdddd
�||_dS)NrrBrri�)rH�why_registerrCrr)rD)rrrr)rrJrrKrLrNrZSTART_REGISTER_WINDOWZSTART_REGISTER_TEXTrUrTrPZWHY_REGISTERr�r�rSrY)rZrrJrLr[Zstart_register_textr\rrrr]ws
"

zStartWindow.__init__cCsdS)Nr)rZrrrr^�szStartWindow.saveResultscCsXtjd|j�|jj�}|jj|�}|dkr2dS|dkrTt|j|j	�}|j
�|S|S)Nz
Running %sr_rCr�)r`rarbrYrcrSrd�WhyRegisterWindowrrJrf)rZrer1Zwhy_reg_winrrrrf�s
zStartWindow.runN)r=r>r?rbr]r^rfrrrrr�tsr�c@s eZdZdZdd�Zdd�ZdS)r�cCs�||_||_tjj�}tj|jtt�dd�}tdt	dt
dtdtdt
dtdtdtdt}tj|dd|ddt|�dd�}|j|dddd�tj|jtt�d	fg�|_|j|jdddd
�||_dS)NrrBz

r$rrir�)rHrq)rD)rrrr)rrJrrKrLrNrZWHY_REGISTER_WINDOWZWHY_REGISTER_TEXTr'r(r)r*r+r,r-r.r/rUrTrPZ
BACK_REGISTERrSrY)rZrrJrLr[Zwhy_register_textr\rrrr]�s
F&zWhyRegisterWindow.__init__cCs*tjd|j�|jj�}|jj|�}|S)Nz
Running %s)r`rarbrYrcrSrd)rZrer1rrrrf�s
zWhyRegisterWindow.runN)r=r>r?rbr]rfrrrrr��sr�c@s0eZdZdZdd�Zdd�Zdd�Zdd�Zd	S)
�
InfoWindowcCs||_||_d|j_|jj|_tjj�}tj|t	t
�dd�}t|j�}|j}||jkrb|d|7}t|}t
}t}	tj|dddt	|�ddd�}
|j|
dddd�tjd	d�}tjt	|��}
|j|
ddddd
�tjd�|_|jj|j�|j|jdddd�tjt	t��}
|j|
ddddd
�ytjddd�|_Wn&tk
�r\tjddd
�|_YnX|jj|j�|j|jdddd�|j|dd�tj|ddt	|	��}
|j|
dd	dd�tj|t	t�dft	t�dft	t �dfg�|_!|j|j!ddddd�||_"dS)Nrrrhz (%s)rirj)rkrl)rmrB)rHrorF)�password)ZhiddenrCrqrr)rHrD)rrrr)rrrr)rrrr)#rrJrsrWrtrrKrLrNrZREGISTER_WINDOWrZLOGIN_PROMPTZLOGINZ	LOGIN_TIPrUrTrzryr{r|�
userNameEntryr~�userNameZPASSWORD�
passwordEntry�	TypeErrorr��TextboxReflowedrPr�rr�rSrY)rZrrJrLr[Zdecoded_serverZurlZlogin_promptZlogin_labelZ	login_tipr�r�rrrr]�sV






zInfoWindow.__init__c
CsL|jj�dkrBtj|jtt�tt�tt�gd�|j	j
|j�dS|jj�dkr�tj|jtt�tt�tt�gd�|j	j
|j�dSy t
j|jj�|jj��|j_Wn�tjk
�rtj�d}tj|jttd��ttd��t|j�ttd��gd�|j	j
|j�dStjk
�rFtj�d}t|jtd�|j�YnXdS)	Nrn)r�rr�ErrorzThe server indicated an error:
rz?There was an error communicating with the registration server:
)r�r�rrrrrZ
USER_REQUIREDrrYr�r�ZPASSWORD_REQUIREDrZreserveUserrJrsrZValidationErrorrr5rVrr3r!)rZr:rrrr�	s. 8zInfoWindow.validateFieldscCs |jj�|j_|jj�|j_dS)N)r�r�rJr�r�r�)rZrrrr^%szInfoWindow.saveResultscCsltjd|j�|jj�d}x>|s\|jj�}|jj|�}|dkrFd}|dkrX|j	�}q Pq W|jj
�|S)Nz
Running %srr_rC)r`rarbrr�rYrfrSrdr�r�)rZr�rer1rrrrf)s



zInfoWindow.runN)r=r>r?rbr]r�r^rfrrrrr��s
@r�c@s0eZdZdZdd�Zdd�Zdd�Zdd�Zd	S)
�OSReleaseWindowcCsx||_tj�stjd�t��tj|j|j�|_	t
|j	d�dkrRtjd�t��||_tj
j�|_d|_tj|jtt�dd�}||_tj|jddtt��|_|j|jdddd	�tt�}|jjr�tj|ddd
�|_ntj|d�|_|j|jddddd�tjtt��|_|j|jdddd	�tj|jdd
d|jddd�|_|j|jdd�xRt |j	dj!�dd�d�D]4\}}||j	dk�r�|d}|jj"d||��qtWtj|jddtt#��|_$|j|j$dddd	�tt%�}|jj&�rtj||jdd
�|_&ntj||j�|_&|j|j&ddddd�tj'|tt(�dftt)�dftt*�dfg�|_+|j|j+dddd�|jj,�dS)Nz5Server does not support EUS, skipping OSReleaseWindow�channelsrz3No available EUS channels, skipping OSReleaseWindowF�rri)rm)�isOn)rHrmrB�)r&rjcSs|dS)Nrr)�arrr�<lambda>jsz*OSReleaseWindow.__init__.<locals>.<lambda>)�keyZreceiving_updatesrrGrhr�rCrqrr�)rD)rrrr)rrrr)-rJrZserver_supports_eusr`rar<ZgetAvailableChannelsr�r��available_channels�lenrrrKrLZ
selectChannelrNrZSELECT_OSRELEASErYr�Z
OS_VERSIONZostextrTZLIMITED_UPDATES�limited_updates_buttonZSingleRadioButtonryZ
MINOR_RELEASEZsublabelZListbox�channelList�sorted�items�appendZCHANNEL_PAGE_TIPZtipZALL_UPDATES�all_updates_buttonrPr�rr�rSr�)rZrrJr[Zoptiontext1r�r�Zoptiontext2rrrr]@sb

$



zOSReleaseWindow.__init__cCsptjd|j�|jj�d}xB|dkr`|jj�}|jj|�}|dkrJd}|dkr\|j	�}q Pq W|jj
�|S)Nz
Running %srrr_rC)r`rarbrr�rYrfrSrdr�r�)rZr�rer1rrrrf�s




zOSReleaseWindow.runcCs�d}d}|jj�r&|jj�|jdk}tt�}|rdtj|j	|tt
�|jj�tt�tt�gd�}|S|j
j�sr|r�tj|j	|tt�tt�tt�gd�}|S|S)N�okFZdefault_channel)r�)r��selectedr��currentr�rZCONFIRM_OS_RELEASE_SELECTIONrrrZCONFIRM_OS_WARNINGrr�r�ZCONFIRM_OS_ALL)rZZmsgboxZ
later_release�titlerrrr��s 


zOSReleaseWindow.validateFieldscCsz|jjjdd�|jj�rVtjd|jj��|jj�|jjd<|jj�|j_d|j_	|j	j�rv|j	j�|j_	d|j_dS)N�channelzSelected Channel %sr)
rJ�other�popr�r�r`rar�r�r�)rZrrrr^�s

zOSReleaseWindow.saveResultsN)r=r>r?rbr]rfr�r^rrrrr�=s
Mr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�HardwareWindowc	Cs�||_||_tjj�}tj�\}}|dk	rB||jjd<||jjd<tj	�|_tj
|tt�dd�}tj
dtt��}|j|dddd�tjdd�}tjttd	���}	|j|	ddd.dd
�tjd�|_|j|jdddd�|j|dddd�|j�rtjtt�dd�|_ntjtt��|_|j|jddd/dd
�tjtt��}	|j|	dddd0d�tjdd�}d}
|
td�ttj��d7}
tjttd���|_|j|jddd1dd
�tjttj���|_|j|jdddd�|
td�7}
x.|jD]$}|ddk�r�|
|dd7}
�q�W|
td�7}
xb|jD]X}|ddk�rt|d�}|
|d7}
|j dk�r`|jj!|j �n|jj!t|���qW|
td�7}
x6|jD],}|ddk�r�|
td�|dd7}
�q�W|
td�7}
xT|jD]J}|ddk�r�|d �r�|
|d d7}
n|d!�r�|
|d!d7}
�q�W|
td"�7}
x2|jD](}|dd#k�r0|
td$�|d%7}
�q0Wtj
d&t|
��}
|j|
dd�tj
|dd'tt"��|_#|j|j#dd(d2dd
�tj$|tt%�d)ftt&�d*ftt'�d+fg�|_(|j|j(dd,d3dd-�||_)dS)4N�	virt_uuid�	virt_typerr�r%r)rmrBz
Profile name:)rHrorp)r�)rHrmrj)rmrHrhrnz	Version: z  zCPU model: �classZCPUZmodelr$z
Hostname: ZNETINFOZhostnamezCPU speed: z%d MHzZspeedzIP Address: ZipaddrZip6addrzMemory: ZMEMORYz%s megabytesZram�Prir�rCrqrrr�)rHrD)rrrr)rrrr)rrrr)rrrr)rrrr)rrrr)*rrJrrKrLrZ
get_virt_infor�rZHardwarerNrZHARDWARE_WINDOWr�ZHARDWARE_WINDOW_DESC1rTrzryrVr{r|�profileEntry�includeHardware�CheckboxZHARDWARE_WINDOW_CHECKBOX�hardwareButtonZDESELECTrr7ZversionLabelZ
versionLabel2r�profileNamer~ZHARDWARE_WINDOW_DESC2ZadditionalHWLabelrPr�rr�rSrY)rZrrJrLr�r�r[r�r�r�Z
hardware_textZhwZunicode_hostnamer\rrrr]�s�





zHardwareWindow.__init__cCs |jj�|j_|jj�|j_dS)N)r�r�rJr�r�r�r�)rZrrrr^5szHardwareWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %sr_rC)r`rarbrYrcrSrd)rZrer1rrrrf9s
zHardwareWindow.runN)r=r>r?rbr]r^rfrrrrr��snr�c@s0eZdZdZdd�Zdd�Zdd�Zdd�Zd	S)
�PackagesWindowc	Cs�||_||_tjj�}tj|tt�dd�}||_tj	|ddtt
��}|j|dddd�tjtt
�d�|_|j|jddddd�tjtt��}|j|dddd�tj|ddd�|_|j|jdd	�|jgk�rJtj|tt�dd�|_tjd
d�|_|jj|jdd�|jj�|jj�d}tjd�r2d}tj|d
�|_|jj�xL|jD]B}|jjdt|d�t|d�t|d�ft|d�dd��qRWtj|tt �dftt!�dftt"�dfg�|_#|j|j#ddddd�dS)Nrr�rri)rm)rHrmrB�rjrp�dZsupportsExtendedPackageProfile)r6z%s-%s-%srb�version�release)�itemr�rCrqrrrh)rHrD)rrrr)rrrr)$rrJrrKrLrNrZPACKAGES_WINDOWrYr�ZPACKAGES_WINDOW_DESC1rTr�ZPACKAGES_WINDOW_DESC2�packagesButtonryZPACKAGES_WINDOW_UNCHECKZCheckboxTree�packageListZPACKAGES_WINDOW_PKGLIST�pwin�Scale�scaler�r�rrwrZgetInstalledPackageListr�r�rPr�rr�rS)	rZrrJrLr[r�r�r6�packagerrrr]EsJ







zPackagesWindow.__init__cCs4|jjt|d|d��|jj�|jj�dS)Ng�?r�)r�r~�intr�r�rr�)rZ�amount�totalrrr�setScale{s
zPackagesWindow.setScalecCsH|jj�|j_|jj�}x*|jjD]}|d|kr"|jjj|�q"WdS)Nrb)r�r�rJ�includePackagesr�ZgetSelection�selectedPackagesr�)rZZ	selectionZpkgrrrr^�s

zPackagesWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %sr_rC)r`rarbrYrcrSrd)rZrer1rrrrf�s
zPackagesWindow.runN)r=r>r?rbr]r�r^rfrrrrr�Bs
6r�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�
SendWindowcCs�||_||_tjj�}tj|tt�dd�}tj|ddtt	��}|j
|dd�tj|tt�dftt
�dftt�dfg�|_|j
|jddd	dd�||_dS)
NrrBr�rCrqrr)rHrD)rrrr)rrJrrKrLrNrZSEND_WINDOWr�ZSEND_WINDOW_DESCrTrPr�rr�rSrY)rZrrJrLr[r�rrrr]�s


zSendWindow.__init__cCsdS)Nr)rZrrrr^�szSendWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %sr_rC)r`rarbrYrcrSrd)rZrer1rrrrf�s
zSendWindow.runN)r=r>r?rbr]r^rfrrrrr��sr�c@s0eZdZdZdd�Zdd�Zdd�Zdd�Zd	S)
�
SendingWindowcCsP||_||_tjj�}tj|tt�dd�|_tj	dd�|_
|jj|j
dd�dS)Nrrpr�r)rrJrrKrLrNrZSENDING_WINDOWr�r�r�rT)rZrrJrLrrrr]�s
zSendingWindow.__init__c%Cs�tjd|j�|jj�|jj�d}yPtjdt|jj	��t
j|jj|jj
|jj|jj	d�}|j}t|d�}W�n(tjk
r�tj�d}t|jtd�|j�Yn�tjk
r�tj�d}t|jtd�|j�Yn�tjk
�rtj�d}t|jtd�|j�Yn�tjk
�rVtj�d}t|jtd�|j�YnLtjk
�rxt|jt�Yn*tjtj��t|jtd��YnXt
j|��s�t|jtd��|jdd	�t
j �|_!|jd
d	�|jj"�rbyt
j#||jj$�Wnbtjk
�r8tj�d}t|jtd�|j�Yn*tjtj��t|jtd��YnX|jd
d	�|jj%�r�yt
j&||jj'�Wnbtjk
�r�tj�d}t|jtd�|j�Yn*tjtj��t|jtd��YnXd}yt(j)�}Wn,tjk
�r,t|jtj�d�YnXt
j*|�yt
j+�\|j_,|j_-WnHt.k
�r�tj�d}t/|jtd�t0t1f|j�d|j_2YnXt
j3�|jd	d	�|jj4�||j_5dS)Nz
Running %szother is %s)r�rArzProblem registering system:
zProblem registering system.z&Problem writing out system id to disk.rhrBz"Problem sending hardware profile:
z!Problem sending hardware profile.rjzProblem sending package list:
zProblem sending package list.z%Could not open %s
%s is not enabled.
rC)6r`rarbr�r�rr��strrJr�rZregisterSystem2r�r�r�ZrawDictrrr3rr5r!rVrZRhnUuidUniquenessErrorZInsuffMgmntEntsErrorZRegistrationDeniedErrorZActivationKeyUsageLimitErrorZACT_KEY_USAGE_LIMIT_ERRORZ
log_exceptionZ
writeSystemIdr�Z
getOemInfo�oemInfor�ZsendHardwarerr�ZsendPackagesr�rZupdateLoginInfoZsendVirtInfoZpluginEnable�pm_plugin_present�pm_plugin_conf_changed�IOErrorr#rr�pm_plugin_conf_errorZspawnRhnCheckForUIr��reg_info)rZr�ZsystemIdr:Zlirrrrf�s�








zSendingWindow.runcCsdS)Nr)rZrrrr^.szSendingWindow.saveResultscCs4|jjt|d|d��|jj�|jj�dS)Ng�?r�)r�r~r�r�r�rr�)rZr�r�rrrr�1s
zSendingWindow.setScaleN)r=r>r?rbr]rfr^r�rrrrr��s

kr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�FinishWindowcCs�||_||_tjj�}tj|tt�dd�}tj|ddtt	��}|j
|dd�tj|ttd��dfg�|_
|j
|j
ddddd�||_dS)	NrrBr�ZFinishrC)rHrD)rrrr)rrJrrKrLrNrZ
FINISH_WINDOWr�ZFINISH_WINDOW_TEXT_TUIrTrPrVrSrY)rZrrJrLr[r�rrrr]:s
zFinishWindow.__init__cCsdS)Nr)rZrrrr^MszFinishWindow.saveResultscCs6tjd|j�|jj�}|jj|�}|dkr2dS|S)Nz
Running %sr_rC)r`rarbrYrcrSrd)rZrer1rrrrfQs
zFinishWindow.runN)r=r>r?rbr]r^rfrrrrr�7sr�c@s(eZdZdZdd�Zdd�Zdd�ZdS)�ReviewWindowc
Cs"||_||_|j|_tjj�}tj|tt�dd�}d}|jj	sJ|t
d7}|jjr^|td7}|jj
rr|td7}|td7}t|jd�dkr�d}x|jdD]}||d7}q�Wtdtdd}tjd	|jj�|t7}|||d7}t|jd
�dk�rld}	xP|jd
D]B}
|
dk�r2|	td7}	n$|
dk�rJ|	td7}	n|	|
d7}	�qW|t|	d7}t|jd
�dk�r�d}x|jd
D]}||7}�q�W|t|7}tj|dd|ddt|�dd�|_|j|jdddd�tj|tt�dfg�|_ |j|j ddddd�||_!dS)NrrBrnz

r�rr$z%s
zserver type is %s Zsystem_slotsZenterprise_entitledZvirtualization_hostZuniversal_activation_keyrir�)rHrC)rHrD)rrrr)rrrr)"rrJr�rrKrLrNrZ
REVIEW_WINDOWr�ZPM_PLUGIN_WARNINGr�ZPM_PLUGIN_CONF_ERRORr�ZPM_PLUGIN_CONF_CHANGEDZREVIEW_WINDOW_PROMPTr�ZCHANNELS_TITLEZOK_CHANNELSr`ra�
serverTypeZCHANNELS_SAT_WARNINGZ
MANAGEMENTZVIRTZSLOTSZACTIVATION_KEYrUZ
review_windowrTrPrrSrY)
rZrrJrLr[Zreview_window_textZchannel_listr�r�Z	slot_listZslotZact_key_listZact_keyrrrr]]sT


(zReviewWindow.__init__cCsdS)Nrr)rZrrrr^�szReviewWindow.saveResultscCsNtjd|j�|jj�}|jj|�}|dkr2d}|jjs>d}|jj	rJd}|S)Nz
Running %sr_rCr )
r`rarbrYrcrSrdrJr�r�)rZrer1rrrrf�s
zReviewWindow.runN)r=r>r?rbr]r^rfrrrrr�Zs?r�c@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
�TuiZRHN_REGISTER_TUIcCs�||_||_tjj�|_|j�d|_ytj�|_	Wn$t
jk
rXt|t
d��YnXtttttttttttttg
|_tj�d|_tds�tj dd�td|_!dS)Nrz"You specified an invalid protocol.z Only https and http are allowed.r�z'/usr/share/rhn/CLN-ORG-TRUSTED-SSL-CERTzBYou specified an invalid protocol.Only https and http are allowed.)"rrIrrKrL�	drawFramersrZ
getServerTyper�rZInvalidProtocolErrorr!rVr�r@r�rgr�r�r�r�r�r�r�r�r��windowsr
r4rWrwr~r�)rZrrIrrrr]�s6zTui.__init__cCs|jj�dS)N)rr)rZrrr�__del__�szTui.__del__cCs4t|_|jjddt|j��|jjttd���dS)NrzL  <Tab>/<Alt-Tab> between elements  |  <Space> selects  |  <F12> next screen)ZCOPYRIGHT_TEXTZwelcomeTextrZdrawRootTextrZpushHelpLinerV)rZrrrr��sz
Tui.drawFramecCs~d|_d|_i|_ddddddddddd�
|_i|_d|jd<d|_d|_d|_d|_d|_	g|_
g|_d|_d|_
d|_dS)Nrn)
Zentitlement_numZregistration_numZ
first_name�	last_nameZcompanyZaddressZcity�state�zipZcountryZregistration_numberrr)r�r�r�ZproductInfor�r�r�r�r�r�r�r�r�r�r�)rZrrr�initResults�s2

zTui.initResultscCsRtjd|j�|j�d}�z"d}�x|t|j�k�r<d}y|j||j|�}Wn0tk
r�|dkrt|d}n|d}w(YnXtjd|�|j�}tjd|�|dkr�|dkr�|d}|dkr�|j|jt	jkr�|d8}d}q(|d	kr�dS|d
k�rtjd�t
|j�dk�r:dSq(|dkr(|d}|j�d}q(WWd|jj�XdS)
Nz
Running %sZforwardrrzindex is %sz	Result %srqZbackwardr rrzCaught a cancel requestrC)
r`rarbr�r�r�rr<rfr�r2r^r)rZ�	direction�index�winrerrrrf�sF


zTui.runN)	r=r>r?rbr]r�r�r�rfrrrrr��s!!r�cCs~d}tjtjtj�ttj�dkrBtjddks>tjddkrBd}tj�}t�dkrh|rht	|t
d��t||�}|j�dS)Nrrz-tz--testz2You must run the RHN registration program as root.)
�signal�SIGINT�SIG_IGNr�r�argvrZSnackScreenrr!rVr�rf)rIrrJrrr�main5s
r��__main__)<�osrr�gettextZtranslation�t�hasattrrrVrr�Zup2date_clientrrrrrr	r
Zup2date_client.configrrZrhnr
Zrhn.connectionsrZrhn.i18nrZup2date_client.pmPluginrrZup2date_client.rhnreg_constantsZinitLogr`ZinitUp2dateConfigrwrr!r#r2r;�	Exceptionr<r@rgr�r�r�r�r�r�r�r�r�r�r�r�r�r�r=rrrr�<module>sd
/w)4))w~P$#S	
__pycache__/hardware_hal.cpython-36.opt-1.pyc000064400000015366150516774050015007 0ustar003

c8hT-�@sHdZddlmZmZddlZdZdZdZdZdZ	dZ
dZdZdZ
dZdZdZdZdZdZdZdZdZdZdZdZdZdZd	ZdZdZdZdZ dZ!d
Z"d	Z#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dZ+dZ,d
Z-dZ.dZ/dZ0dZ1dZ2dZ3dZ4dZ5dZ6dZ7dZ8dZ9d
Z:dd�Z;dd�Z<dd�Z=dd�Z>dd�Z?dd�Z@dd�ZAdd�ZBdd �ZCd!d"�ZDdS)#z Get hardware info using HAL �)�HalTree�	HalDevice�N����P�����	�cCs�g}tj�}|jdd�}tj|d�}|j�}t�}x>|D]6}|jd|�}tj|d�}|j�}	t|	�}
|j|
�q8Wt	|j
�}|S)Nzorg.freedesktop.Halz/org/freedesktop/Hal/Managerzorg.freedesktop.Hal.Managerzorg.freedesktop.Hal.Device)�dbus�	SystemBus�
get_object�	InterfaceZ
GetAllDevicesrZGetAllPropertiesr�add�process_hal_nodes�head)�ret�busZhal_manager_objZhal_managerZdevice_listZhal_treeZudiZ
device_obj�device�
propertiesZhaldev�
kudzu_list�r�"/usr/lib/python3.6/hardware_hal.py�read_hal\s 

rcCs&g}t|�|_|jr�|j}i}|j|d<tt|��|d<|ddkr�d|jkr\|jd|d<d|jkrt|jd|d<d|jkr�|jd|d	<d
|jkr�|jd
|d<tt|��|d<t|�}|r�t|�|d
<tt|��|d<tt	|��|d<d|d<|j
|�x"|jD]}t|�}|j
|��qW|S)N�classrZscsiz	scsi.hostZprop1zscsi.targetZprop2zscsi.busZprop3zscsi.lunZprop4�driverr�descZpciTyperZdetached)�classify_hal�classification�parent�str�get_device_busr�get_device_driver�get_device_path�get_device_description�get_device_pcitype�appendZchildrenr�extend)�noderr#�devZdevice_pathZchildZ
child_listrrrrts8






rcCs^d|jkrdSd|jkr\d|jkr\|jddkr\d|jdj�krFdSd|jdj�kr\d	Sd
|jk�r�|jd
tkrzdS|jd
tkr�|jdtkr�d
S|jd
tkr�|jdtkr�dS|jdtkr�dS|jdtkr�dS|jd
t	kr�|jdt
kr�dS|jd
tk�r"|jdtk�r"dS|jd
t
k�rZ|jdtk�rFdS|jdtk�rZdS|jd
tk�r~|jdtk�r~dS|jd
tk�r�|jdtk�s�|jdtk�r�dSd|jk�r|jddk�r�dS|jddk�r�dS|jddk�r�dS|jddk�rdSd |jk�r.|jd d!k�r.dSd"|jk�r>d#Sd$|jk�sVd%|jk�rZd&SdS)'Nz
net.interface�NETWORKzinfo.productz
info.category�inputZkeyboardZKEYBOARDZmouseZMOUSEzpci.device_classZVIDEOzpci.device_subclassZUSBZIDEZSCSIZRAIDZMODEMZSCANNERZCAPTUREZAUDIOZFIREWIREZSOCKETzstorage.drive_typeZcdromZCDROMZdiskZHDZfloppyZFLOPPYZtapeZTAPEzxen.typeZvbdzprinter.productZPRINTERzpci.product_idzusb.product_idZOTHER)r�lower�PCI_BASE_CLASS_DISPLAY�PCI_BASE_CLASS_SERIAL�PCI_CLASS_SERIAL_USB�PCI_BASE_CLASS_STORAGE�PCI_CLASS_STORAGE_IDE�PCI_CLASS_STORAGE_SCSI�PCI_CLASS_STORAGE_RAID�PCI_BASE_CLASS_COMMUNICATION�PCI_CLASS_COMMUNICATION_MODEM�PCI_BASE_CLASS_INPUT�PCI_CLASS_INPUT_SCANNER�PCI_BASE_CLASS_MULTIMEDIA�PCI_CLASS_MULTIMEDIA_VIDEO�PCI_CLASS_MULTIMEDIA_AUDIO�PCI_CLASS_SERIAL_FIREWIRE�PCI_BASE_CLASS_BRIDGE�PCI_CLASS_BRIDGE_PCMCIA�PCI_CLASS_BRIDGE_CARDBUS)r,rrrr!�sr
r!cCsHd|jkr|jd}n.d|jkr@|jddkr4d}qD|jd}nd}|S)Nzstorage.buszinfo.bus�platformZMISC)r)r,rrrrr%�s

r%cCs4d|jkr|jd}nd|jkr,|jd}nd}|S)Nzinfo.linux.driverznet.linux.driver�unknown)r)r,rrrrr&s

r&cCs|d}d|jkr|jd}n4d|jkr0|jd}n|jdkrNd|jkrN|jd}|rx|jd�rh|dd�}t|�dkrxd}|S)	a%
    Return the device file path.

    As kudzu did not return a string with the /dev/ prefix,
    this function will not, either.
    RHN's DB has a limit of 16 characters for the device path.
    If the path is longer than that, return None.
    If no device path is found, return None.
    Nzblock.devicezlinux.device_filer.z
net.interfacez/dev/r
�)rr"�
startswith�len)r,r-rrrr's






r'cCsbd|jkr.d|jkr.|jdd|jd}n0d|jkrD|jd}nd|jkrZ|jd}nd}|S)Nzinfo.vendorzinfo.product�|�)r)r,r rrrr(*s



r(cCsrd}d}d
}d|jo |jddkkrj|j}d|jkrd|jddkrd|jddks^|jdd	krd|}qn|}n|}|S)Nrrzinfo.busZpcizpci.device_classr	zpci.device_subclassr
r���)rr#)r,ZPCI_TYPE_PCMCIAZPCI_TYPE_PCIZPCI_TYPE_NOT_PCIr#Zpcityperrrr)7s
r)cCs$tj�}|jdd�}tj|d�}|S)Nzorg.freedesktop.Halz%/org/freedesktop/Hal/devices/computerzorg.freedesktop.Hal.Device)rrrr)rZcomputer_objZcomputerrrr�get_hal_computerKs
rKcCs,ddl}|jd�\}}|jd�\}}||fS)Nrz/etc/init.d/haldaemon statusz/etc/init.d/messagebus status)�
subprocessZgetstatusoutput)ZcommandsZ
hal_status�msgZdbus_statusrrr�check_hal_dbus_statusSsrN)E�__doc__Zhaltreerrrr4r6r5ZPCI_CLASS_STORAGE_FLOPPYZPCI_CLASS_STORAGE_IPIr7ZPCI_CLASS_STORAGE_OTHERZPCI_BASE_CLASS_NETWORKZPCI_CLASS_NETWORK_ETHERNETZPCI_CLASS_NETWORK_TOKEN_RINGZPCI_CLASS_NETWORK_FDDIZPCI_CLASS_NETWORK_ATMZPCI_CLASS_NETWORK_OTHERr1ZPCI_CLASS_DISPLAY_VGAZPCI_CLASS_DISPLAY_XGAZPCI_CLASS_DISPLAY_3DZPCI_CLASS_DISPLAY_OTHERr<r=r>ZPCI_CLASS_MULTIMEDIA_PHONEZPCI_CLASS_MULTIMEDIA_OTHERr@ZPCI_CLASS_BRIDGE_HOSTZPCI_CLASS_BRIDGE_ISAZPCI_CLASS_BRIDGE_EISAZPCI_CLASS_BRIDGE_MCZPCI_CLASS_BRIDGE_PCIrAZPCI_CLASS_BRIDGE_NUBUSrBZPCI_CLASS_BRIDGE_RACEWAYZPCI_CLASS_BRIDGE_OTHERr8ZPCI_CLASS_COMMUNICATION_SERIALZ PCI_CLASS_COMMUNICATION_PARALLELZ#PCI_CLASS_COMMUNICATION_MULTISERIALr9ZPCI_CLASS_COMMUNICATION_OTHERr:ZPCI_CLASS_INPUT_KEYBOARDZPCI_CLASS_INPUT_PENZPCI_CLASS_INPUT_MOUSEr;ZPCI_CLASS_INPUT_GAMEPORTZPCI_CLASS_INPUT_OTHERr2r?ZPCI_CLASS_SERIAL_ACCESSZPCI_CLASS_SERIAL_SSAr3ZPCI_CLASS_SERIAL_FIBERZPCI_CLASS_SERIAL_SMBUSrrr!r%r&r'r(r)rKrNrrrr�<module>s�)Z


__pycache__/rhnreg.cpython-36.opt-1.pyc000064400000061762150516774050013654 0ustar003

c8he}�@s�ddlZddlZddlZddlZddlZddlmZddlmZddlmZddlm	Z	ddlm
Z
ddlmZddlmZdd	lm
Z
dd
lmZddlmZddlmZmZdd
lmZy4ddlZddlZddlmZmZmZmZmZmZWnFe k
�r6ddl!j"Zddl#j$Ze%Ze&Ze'Ze(Ze)Ze)Ze*Z+YnXyddl,m-Z-Wne k
�rbdZ-YnXddl.Z.e.j/ddd�Z0e1e0d��s�e0j.e0_2e0j2Z3dZ4de4Z5de4Z6dZ7dZ8ddddd�Z9dd�e9j:�D�Z;dd lm<Z<e<j=�Z>ej?�Z@d!d"�ZAd#d$�ZBd%d&�ZCd'd(�ZDd)d*�ZEd+d,�ZFd-d.�ZGd/d0�ZHd1d2�ZIe(eJd3�d4d5�ZKeJd6�d7d8�ZLd�d:d;�ZMd<d=�ZNd>d?�ZOd@dA�ZPdBdC�ZQdDdE�ZRdFdG�ZSdHdI�ZTdJdK�ZUGdLdM�dM�ZVd�eJdN�dOdP�ZWdQdR�ZXdSdT�ZYdUdV�ZZdWdX�Z[e(dY�dZd[�Z\d�d\d]�Z]d^d_�Z^d`da�Z_dbdc�Z`dddddifddde�Zadfdg�Zbdhdi�Zcdjdk�Zddldm�Zedndo�Zfdpdq�Zgd�drds�ZhGdtdu�du�Zidvdw�Zjdxdy�Zkd�dzd{�Zld|d}�Zme�d~k�r�dd��Znndd�lomnZndS)��N)�up2dateUtils)�
up2dateErrors)�up2dateAuth)�	rhnserver)�pkgUtils)�
up2dateLog)�rhnreg_constants)�hardware)�convertPackagesFromHashToList)�getPlatform)�ustr�sstr)�
raise_with_tb)�ListType�	TupleType�
StringType�UnicodeType�DictType�DictionaryType)�supportzrhn-client-toolsT)Zfallback�ugettextz/etc/sysconfig/rhnz%s/rhn_register_remindz%s/hw-activation-codez/etc/pki/consumer/cert.pemz/etc/sysconfig/rhn/jwt.tokenZ
shared_pro�shared�solo�admin)zCloudLinux OS Shared ProzCloudLinux OS SharedzCloudLinux OS SolozCloudLinux OS AdmincCsi|]\}}||�qS�r)�.0�k�vrr�/usr/lib/python3.6/rhnreg.py�
<dictcomp>Gsr)�configcCs&tjdtjtjB��r"d}d}tj|tjtjB�sNtjdtjtjB�rNd}d}tjd|tj�r�tj|tjtjB�r�tjd|�tjd|�nttd	��n�tjd
tjtjB�r�tjd�nttd��d
}tj|tjtjB��stjdtjtjB��rd}tjd|�}|�r"tjd|�dS)Nz/usr/sbin/rhnsdz/usr/lib/systemd/systemz/usr/bin/systemctlz/bin/systemctlz/lib/systemd/systemz%s/rhnsd.servicez%s enable rhnsd > /dev/nullz%s start rhnsd > /dev/nullz,Warning: unable to enable rhnsd with systemdz/sbin/chkconfigz$/sbin/chkconfig rhnsd on > /dev/nullz.Warning: unable to enable rhnsd with chkconfigz
/sbin/servicez/usr/sbin/servicez%s rhnsd status > /dev/nullz%s rhnsd start > /dev/null)�os�access�R_OK�X_OK�system�print�_)Zsystemd_system_unitdirZsystemd_systemctlZservice_pathZrcrrr�
startRhnsdOs,r(cCs�tdp
d}tj|tj�siSt|d�}|j�}i}x`|D]X}|j�}|dkrPq:y|jd�\}}Wn"tk
r�t	t
j|��YnX|j�||<q:W|S)NZoemInfoFilez/etc/sysconfig/rhn/oeminfo�r��:)�cfgr!r"r#�open�	readlines�strip�split�
ValueErrorrrZOemInfoFileError)Z
configFile�fd�L�info�i�key�valuerrr�
getOemInfops 

r8cCs*tjttj�r"tjt�}|jdkSdSdS)z@ Returns true if system is registred using subscription manager rFN)r!r"�	RHSM_FILEr#�stat�st_size)Zstatinforrr�rhsm_registered�s

r<cCstjtdtj�S)N�systemIdPath)r!r"r,r#rrrr�
registered�sr>cCs$tjttj�s ttd�}|j�dS)Nzw+)r!r"�REMIND_FILEr#r-�close)r2rrr�createSystemRegisterRemindFile�s
rAcCstjttj�rtjt�dS)N)r!r"r?r#�unlinkrrrr�removeSystemRegisterRemindFile�srCcCs�tjj|�}tj|tj�sdStj|tj�rLytj||d�Wn
dStj|tjtj	Bt
dd��}tj|d�}z|jt
|��Wd|j�XdS)z; Write a file to disk that is not readable by other users. Fz.saveZ0600��wNT)r!�path�dirnamer"�W_OK�F_OK�renamer-�O_WRONLY�O_CREAT�int�fdopen�writer
r@)Zsecure_fileZ
file_contentsZdir_namer2Zfd_filerrr�_write_secure_file�s
rPcCs"ttd|�}|rt�t�|S)Nr=)rPr,rC�updateRhsmStatus)�systemId�resrrr�
writeSystemId�s
rTcCsxd}tj�}|dkrdSy6tj|�}|j�}|j|�dj}t|dd��}Wn$ttj	fk
rrt
jd�dSX|S)Nz'//member[name='system_id']/value/stringr�z@systemID file doesn't have system_id field or the file is broken)r�getSystemId�libxml2ZparseDocZxpathNewContextZ	xpathEvalZcontentrM�
IndexErrorZparserError�log�log_me)Z	xpath_strrR�result�context�	system_idrrr�extract_system_id�s

r^)�token�allowTransitioncCsnddl}ddl}|jjd�s dSdd|g}|r8|jd�|j|�}|j�\}}|jdkrjtj	d||f�dS)zH
    Execute binary file which we use as hook for jwt token updates
    rNz /opt/cloudlinux/venv/bin/python3z/usr/sbin/cl-pre-jwt-updatez--new-tokenz--allow-transitionz7Pre jwt update hook failed with stdout=%s and stderr=%s)
�
subprocessr!rF�exists�append�Popen�communicate�
returncoderYrZ)r_r`rar!�cmd�p�stdout�stderrrrr�_execute_pre_jwt_update_hook�s



rk)r`cCsjddl}ddl}|jjd�s dSdg}|r4|jd�|j|�}|j�\}}|jdkrftj	d||f�dS)zH
    Execute binary file which we use as hook for jwt token updates
    rNz /opt/cloudlinux/venv/bin/python3z/usr/sbin/cl-post-jwt-updatez--allow-transitionz8Post jwt update hook failed with stdout=%s and stderr=%s)
rar!rFrbrcrdrerfrYrZ)r`rar!rgrhrirjrrr�_execute_post_jwt_update_hook�s


rlFcCs�tj�}y|jj|�}WnFtjk
r.dStjtjtjtj	fk
r^t
jtj
��dSXt||�tt|�t|�dS)z�
    Get a JWT token from CLN and save it to the file
    :param systemId: content of file `/etc/sysconfig/rhn/systemid`
    :return: None
    N)rZ	RhnServerZup2dateZgetJWTTokenr�UnknownMethodExceptionZAuthenticationTicketErrorZRhnUuidUniquenessError�CommunicationErrorZ$AuthenticationOrAccountCreationErrorrY�
log_exception�sys�exc_inforkrP�	JWT_TOKENrl)rRr`Z
xmlrpm_serverr[rrr�getAndWriteJWTTokenToFile�s

rscCstt|d�S)z=Returns True if the write is successful or False if it fails.�
)rP�HW_CODE_FILE)�hw_activation_coderrr�writeHWCodesrwcCspy"tjjd�r t�\}}||fSWntk
r6YnXt�\}}|dk	rR||fSt�\}}|dk	rl||fSdS)a�
    This function returns the UUID and virtualization type of this system, if
    it is a guest.  Otherwise, it returns None.  To figure this out, we'll
    use a number of heuristics (list in order of precedence):

       1.  Check /proc/xen/xsd_port.  If exists, we know the system is a
           host; exit.
       2.  Check SMBIOS.  If vendor='Xen' and UUID is non-zero, we know the
           system is a fully-virt guest; exit.
       3.  Check /sys/hypervisor/uuid.  If exists and is non-zero, we know
           the system is a para-virt guest; exit.
       4.  If non of the above checks worked; we know we have a
           non-xen-enabled system; exit.
    z/proc/xen/xsd_portN)NN)r!rFrb�get_fully_virt_info�IOError�get_para_virt_info)�uuid�	virt_typerrr�
get_virt_infos


r}cCsVy<tdd�}|j�}|j�|j�jdd�jd�}d}||fStk
rPYnXdS)	z�
    This function checks /sys/hypervisor/uuid to see if the system is a
    para-virt guest.  It returns a (uuid, virt_type) tuple.
    z/sys/hypervisor/uuidr)�-r*z
ZparaN)NN)r-�readr@�lower�replace�rstripry)Z	uuid_filer{r|rrrrzCs
rzcCs@tj�}tj�}|j�dkr8|j�jdd�}d}||fSdSdS)z�
    This function looks in the SMBIOS area to determine if this is a
    fully-virt guest.  It returns a (uuid, virt_type) tuple.
    Zxenr~r*ZfullyN)NN)r	Z
dmi_vendorZdmi_system_uuidr�r�)Zvendorr{r|rrrrxUsrxcCstd|�}t|�td�kS)Nz0x%sr)�eval�long)r{rrr�
_is_host_uuidcsr�cCstj�}|jj�S)N)r�RegistrationRhnServer�registrationZwelcome_message)�srrr�welcomeTextgsr�cCstj�}|jj�dS)N)rr�ZcapabilitiesZvalidate)r�rrr�getCapsmsr�cCstj�}|jj||�S)N)rr�r�Zreserve_user)�username�passwordr�rrr�reserveUserrsr�c@sfeZdZddd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dS)�RegistrationResultNcCsB||_||_||_||_||_t|�dkr2||_nd|_||_dS)Nr)�	_systemId�	_channels�_failedChannels�_systemSlots�_failedSystemSlots�len�_universalActivationKey�rawDict)�selfrR�channelsZfailedChannels�systemSlotsZfailedSystemSlotsZuniversalActivationKeyr�rrr�__init__xszRegistrationResult.__init__cCs|jS)N)r�)r�rrrrV�szRegistrationResult.getSystemIdcCs|jS)N)r�)r�rrr�getChannels�szRegistrationResult.getChannelscCs|jS)N)r�)r�rrr�getFailedChannels�sz$RegistrationResult.getFailedChannelscCs|jS)N)r�)r�rrr�getSystemSlots�sz!RegistrationResult.getSystemSlotscs�fdd��jD�S)Ncsg|]}�j|��qSr)�_getSlotDescription)rr�)r�rr�
<listcomp>�sz@RegistrationResult.getSystemSlotDescriptions.<locals>.<listcomp>)r�)r�r)r�r�getSystemSlotDescriptions�sz,RegistrationResult.getSystemSlotDescriptionscs�fdd��jD�S)Ncsg|]}�j|��qSr)�_getFailedSlotDescription)rr�)r�rrr��szFRegistrationResult.getFailedSystemSlotDescriptions.<locals>.<listcomp>)r�)r�r)r�r�getFailedSystemSlotDescriptions�sz2RegistrationResult.getFailedSystemSlotDescriptionscCs|jS)z5Returns None if no universal activation key was used.)r�)r�rrr�getUniversalActivationKey�sz,RegistrationResult.getUniversalActivationKeycCst|j�dkot|j�dkS)z�Returns True if the system was subscribed to at least one channel
        and was given any type of system slot so it will get updates. In other
        words, returns True if the system will be getting at least basic
        updates.

        r)r�r�r�)r�rrr�hasBaseAndUpdates�s	z$RegistrationResult.hasBaseAndUpdatescCs&|dkrtjdtjS|j|�SdS)N�virtualization_host� )r�VIRTZVIRT_FAILEDr�)r��slotrrrr��sz,RegistrationResult._getFailedSlotDescriptioncCs$|dkrtjS|dkrtjS|SdS)NZenterprise_entitledr�)rZ
MANAGEMENTr�)r�r�rrrr��s
z&RegistrationResult._getSlotDescription)N)�__name__�
__module__�__qualname__r�rVr�r�r�r�r�r�r�r�r�rrrrr�ws

r�)�human_readablec	CsFd}tjj|�sdSt|�� }|j�jd�}|r4|St|SQRXdS)Nz/opt/cloudlinux/cl_editionrrt)r!rFrbr-rr/�_human_readable_to_product)r�Zedition_cache_file�fZraw_editionrrr�getServerEdition�s
r�cCslddlm}m}tjjd�s"t��d}||d||d�}dd�|j�D�\}}|rVt��t|d	d�j	d
��S)Nr)rd�PIPEz/opt/cloudlinux/venv/binzZ/opt/cloudlinux/venv/bin/python3 -c "from clcommon.cpapi import cpusers; print(cpusers())"T)�shellrirjcSsg|]}|j�j��qSr)�decoder/)rr[rrrr��sz.get_users_count_from_cllib.<locals>.<listcomp>�z, ���)
rardr�r!rFrbr1rer�r0)rdr�rgZprocess�output�errorsrrr�get_users_count_from_cllib�sr�cCsddlm}|�}t|j��S)Nr)�ClPwd)Zup2date_client.clpwdr�r�Zget_uid_dict)r��pwdrrr�get_users_count_generic�sr�cCs*y
t�}Wntk
r$t�}YnX|S)N)r��	Exceptionr�)Zusers_countrrr�countServerUsers�s

r�cCsTyt|�}WnPtjk
rH}ztd|j�tjd�WYdd}~Xntjk
r\dSXt�}|d}||krxdS|r�tdj	t
|t
|d��td�tjd�|�sPtjj�s�td�td�t
|�dt
|�d	�}d
dd�}|j
|�}	|	dk	�rHt�}
|
|	k�r4td||�d
|
�d��tjd�n|�d||�d�}t|�dS)Nz%sr��editionz�WARNING: Automatic registration in yum transactions is only available when edition matches the provided license. Your current edition is {current_edition} and your license is {new_edition}.)Zcurrent_editionZnew_editionz0Run clnreg_ks manually to complete registration.aError: interactive input required for edition migration, but tool is running in non-interactive mode. Please try running the tool again in interactive shell or add `--migrate-silently` flag to accept allquestions and perform the edition migration silently.za edition installed on your server does not match license you are trying to register server with: zh. Migration is required. You may lose access to the services which are not supported by the new edition.�)rrz@The license you are trying to register with allows a maximum of z% hosting accounts which is less than z) users detected on this server. Aborting.zG Also, the license you are trying to register with allows a maximum of zM hosting accounts. Make sure that your system complies with this requirement.)�checkKeyrrnr&�errmsgrp�exitrmr��format�_product_to_human_readable�stdin�isatty�getr��_askConfirmation)�
activationKeyZ
strictEditionZsilentMigrationZlicenseInformation�eZcurrentEditionZlicenseEdition�messageZedition_to_users_limitZlicense_users_limitZusers_on_serverrrr�checkLicenseKey�sB




r�)�confirmationMessagecCs2t|�td�}|j�dkr.td�tjd�dS)zS
    Prints message and makes sure that client is ready for edition migration.
    z Do you want to continue? [N/y]: �yzAborted.r�N)r&�inputr�rpr�)r�Zresponserrrr�s
r�cCs�|tj�tj�tj�d�}tj�}|dk	r2||d<|rTx|j�D]\}}	|	||<q@W|rb||d<n||d<||d<|dk	r�||d<n(tjj	d�r�d	ntjj	d
�r�dnd|d<t
d
r�ttj
��|d<tj�}
|
jj|�}|S)ziWrapper for the old xmlrpc to register a system. Activates subscriptions
    if a reg num is given.

    )Zprofile_nameZ
os_releaseZrelease_nameZarchitectureNr]r_r�r�r�z/etc/cloudlinux-edition-solorz/etc/cloudlinux-edition-adminrr�supportsSMBIOS�smbios)r�
getVersion�getOSRelease�getArchrrV�itemsr!rFrbr,�_encode_charactersr	�
get_smbiosrr�r�Z
new_system)r�r��profileNamer_�otherr�Z	auth_dictZ
system_id_xmlr6�itemr��retrrr�registerSystem)s.


r�cCstj�}|jj|�}|S)zG
    Check the activation key and return it's edition and customer
    )rr�r�Z
license_check)r�r�r�rrrr�Xsr�cCsly,tj�}|j|dddd�}tj|dd�}Wntjk
rBdSXy|j�Wntjk
rfYnXdS)Nzcom.redhat.SubscriptionManagerz/EntitlementStatusF)Z
introspectz0com.redhat.SubscriptionManager.EntitlementStatus)Zdbus_interface)�dbusZ	SystemBusZProxyObjectClassZ	InterfaceZ
DBusExceptionZcheck_status)ZbusZvalidity_objZvalidity_ifacerrrrQcs
rQcCs�tj�}tj�}tj�}tj�}d}y|jj|||||�}Wn@tj	k
r|t
j�d}|jdkrvt
tj|j��n�YnX|S)Nr��c)rr�rr�r�Z
getReleaser�Zavailable_eus_channels�	xmlrpclibZFaultrprqZ	faultCoderrZ
DelayErrorZfaultString)r�r�r�Zserver_archZserver_versionZserver_releaseZavailableChannelsr�rrr�getAvailableChannelsxs 

r�c
	Cs�|dkri}|rnx|j�D]}qWtdr<ttj��|d<tj�}|rl|jj|t	j
�t	j�t	j�||�}n$|jj
|t	j
�t	j�t	j�|||�}tjd|�t|d|d|d|d|d	|d
|d�}	|	S)a�Uses the new xmlrpcs to register a system. Returns a dict instead of just
    system id.

    The main differences between this and registerSystem and that this doesn't
    do activation and does child channel subscriptions if possible. See the
    documentation for the xmlrpc handlers in backend for more detail.

    If nothing is going to be in other, it can be {} or None.

    New in RHEL 5.

    Nr�r�zReturned:
%sr]r�Zfailed_channelsZsystem_slotsZfailed_system_slotsZuniversal_activation_key)r�)�keysr,r�r	r�rr�r�Znew_system_activation_keyrr�r�r�Znew_system_user_passrY�	log_debugr�)
r�r�r�Zpackagesr�r�r6r�r4r[rrr�registerSystem2�s<r�cCstdS)NZsupportsEUS)r,rrrr�server_supports_eus�sr�cCsdS)Nr)rRZhardwareListrrr�sendHardware�sr�cCsdS)Nr)rRZpackageListrrr�sendPackages�sr�cCstdk	rtj�dS)N)rZrefresh)rRrrr�sendVirtInfo�sr�cCstj�}t|jj|��dS)N)rr�r&r�Z
list_packages)rRr�rrr�listPackages�sr�cCs�tj|�\}}}}}}|dks&|dkrDd|}tj|�\}}}}}}|d	krVtjd��|dksn|dksn|dkrrd}tj||||||f�}|S)
zzRaises up2dateErrors.InvalidProtocolError if the server url has a
    protocol specified and it's not http or https.

    Nr*zhttps://�https�httpzCYou specified an invalid protocol. Only https and http are allowed.�/z/XMLRPC)r�r�)�urlparserZInvalidProtocolErrorZ
urlunparse)�serverZprotocol�hostrFZ
parametersZqueryZfragmentIdentifierrrr�makeNiceServerUrl�s
r�cCsdS)zdReturns 'hosted' if the url points to a known hosted server. Otherwise
    returns 'satellite'.
    Z	satelliter)Z	serverUrlrrr�
getServerTypesr�c@sBeZdZdZdZiifdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
S)�ActivationResultrr�cCs||_||_||_||_dS)zschannels and systemSlots are dicts where the key/value pairs are
        label (string) / quantity (int).

        N)�_status�_regNumr�r�)r�ZstatusZregistrationNumberr�r�rrrr�szActivationResult.__init__cCs|jS)N)r�)r�rrr�	getStatus$szActivationResult.getStatuscCs|jS)N)r�)r�rrr�getRegistrationNumber'sz&ActivationResult.getRegistrationNumbercCs|jS)z7Returns a dict- the key/value pairs are label/quantity.)r�)r�rrr�getChannelsActivated*sz%ActivationResult.getChannelsActivatedcCs|jS)z7Returns a dict- the key/value pairs are label/quantity.)r�)r�rrr�getSystemSlotsActivated.sz(ActivationResult.getSystemSlotsActivatedN)
r�r�r��
ACTIVATED_NOW�ALREADY_USEDr�r�r�r�r�rrrrr�sr�cGs�g}x�|D]�}t|�}|tkr(t|�}nZ|tkrDtdd�|D��}n>|tkr\dd�|D�}n&|tksl|tkr�tdd�|j	�D��}|j
|�q
Wt|�dkr�|dSt|�SdS)	u� All the data we gathered from dmi, bios, gudev are in utf-8,
            we need to convert characters beyond ord(127) - e.g ® to unicode.
        css|]}t|�VqdS)N)r�)rr5rrr�	<genexpr><sz%_encode_characters.<locals>.<genexpr>cSsg|]}t|��qSr)r�)rr5rrrr�>sz&_encode_characters.<locals>.<listcomp>cSsg|]\}}t||��qSr)r�)r�name�valrrrr�@sr�rN)�typerrr�tuplerrr�dictr�rcr�)�argsr[r�Z	item_typerrrr�2s

r�cCs�d}d}d}ytj�}t|�}Wn$tjd�tjtj��YnX|dk	r�y.t|||�}|j	�t
jkrz|j�}t
|�Wn>tjk
r�tjd�Yn tjk
r�tjd�YnX|S)NzMThere was an error while reading the hardware info from the bios. Traceback:
z<There are are no entitlements associated with this hardware.z,The hardware id was not recognized as valid.)r	Zget_hal_system_and_smbiosr�rYrZrorprq�activateHardwareInfor�r�r�r�rwrZNotEntitlingErrorr�ZInvalidRegistrationNumberError)Zloginr�ZactivateHWResult�hardwareInforvrrr�_activate_hardwareHs*

rc
Cs�i}|rd|i}tj�}|jj||||�}|d}|d}tjd|�|dkr\ttj|�S|dkrpttj|�Sd|}	t	j
|	��dS)	z�Tries to activate an entitlement linked to the hardware info that we
    read from the bios.

    Returns an ActivationResult.
    Can raise:
        Invalid number.
        Hardware info is not entitling.
        Communication errors, etc

    Zorg_idZstatus_codeZregistration_numberzServer returned status code %srr�zNThe server returned unknown status code %s while activating the hardware info.N)rr�r�Zactivate_hardware_inforYr�r�r�r�rrn)
r�r�rZorgIdr�r�r[Z
statusCodeZregNumr�rrrrds 
rcCsdtjdtjtjB�rVddlm}m}|dg|||d�}tdd�|jj	�|j
j	��n
tjd�dS)Nz/usr/sbin/rhn_checkr)rdr�)r�rirjcSs
tj|�S)N)rYrZ)�xrrr�<lambda>�sz$spawnRhnCheckForUI.<locals>.<lambda>z Warning: unable to run rhn_check)
r!r"r#r$rardr��maprir.rjrYrZ)rdr�rhrrr�spawnRhnCheckForUI�s
rZdebcCsdS)z.On Debian no extra action for plugin is neededr�r)r�rrrrrr�pluginEnable�sr)r)F)F)NNNNNN)N)N)pr!rpr��base64rWZup2date_clientrrrrrrrr	Zup2date_client.rhnPackageInfor
Zup2date_client.pkgplatformrZrhn.i18nrr
Zrhn.tbrr�r��typesrrrrrr�ImportErrorZurllib.parse�parseZ
xmlrpc.clientZclient�listr��bytes�strr�rMr�Zvirtualizationr�gettextZtranslation�t�hasattrrr'Z	SYSID_DIRr?rur9rrr�r�r�r ZinitUp2dateConfigr,ZinitLogrYr(r8r<r>rArCrPrTr^�boolrkrlrsrwr}rzrxr�r�r�r�r�r�r�r�r�r�r�r�r�rQr�r�r�r�r�r�r�r�r�r�r�rrrrZup2date_client.pmPluginrrrr�<module>	s�$



!

,?>
-;


"

__pycache__/up2dateUtils.cpython-36.pyc000064400000010102150516774050013773 0ustar003

ge8h<�@s�dZddlZddlZddlZddlZddlZddlmZddlmZddl	m
Z
ddlmZej
ddd	�Zeed
�s|eje_ejZe
�dkr�ddlZdd
�ZnddlmZdd
�Zdd�Zdd�Zdd�Zdd�Zdd�Zejdd��ZdS)zutility functions for up2date�N)�
up2dateErrors)�config)�getPlatform)�sstrzrhn-client-toolsT)Zfallback�ugettext�debcCs6tj�}|d}d}d|kr$|d}|d}|||fS)NZIDzn/aZCODENAMEZRELEASE)�lsb_releaseZget_distro_information)Z	dist_infoZos_nameZ
os_version�
os_release�r
�"/usr/lib/python3.6/up2dateUtils.py�_getOSVersionAndReleasesr)�transactioncCs~tj�}�xn|jdd�D]~}d}t|d�}t|d�}|dd�|dD�kr�td	d�t|d|d
�D��}d||f}||}t|d�||f}|SWx�|jdd
�D]�}d}t|d�}t|d�}|dd�|dD�k�rtdd�t|d|d
�D��}d||f}||}t|d�||f}|SWxL|jdd�D]2}t|d�t|d�t|d�f}|jj�|SWtj	d��dS)NZProvidenamezoraclelinux-releasezsystem-release(releasever)�version�releasecss|]}t|�VqdS)N)r)�.0�provider
r
r�	<genexpr>,sz*_getOSVersionAndRelease.<locals>.<genexpr>Zprovidenamecss"|]\}}t|�t|�fVqdS)N)r)r�n�vr
r
rr-sZprovideversionz%s-%s�namezredhat-releasecss|]}t|�VqdS)N)r)rrr
r
rr8scss"|]\}}t|�t|�fVqdS)N)r)rrrr
r
rr9szdistribution-releasezxCould not determine what version of CloudLinux you are running.
If you get this error, try running 

		rpm --rebuilddb

)
r
ZinitReadOnlyTransactionZdbMatchr�dict�zip�tsZcloseDBrZRpmError)r�hZ	SYSRELVERrrZprovidesZosVersionReleaser
r
rr&s:"
cCs,tj�}|drt|d�St�\}}}|S)z3
    Returns the version of redhat-release rpm
    ZversionOverride)rZinitUp2dateConfig�strr)Zcfgr	rrr
r
r�
getVersionLs
rcCst�\}}}|S)z4
    Returns the name of the redhat-release rpm
    )r)r	rrr
r
r�getOSReleaseVsrcCst�\}}}|S)z7
    Returns the release of the redhat-release rpm
    )r)r	rrr
r
r�
getRelease]srcCsztjdtj�r@tdd�}|j�j�}ddi}||kr<||}|Stj�d}t�dkrv|dkrbd
}|dkrnd}|d
7}|S)Nz/etc/rpm/platform�rzia32e-redhat-linuxzx86_64-redhat-linux�r�i486�i586�i686Zi386Zx86_64�amd64z
-debian-linux)r r!r")�os�access�R_OK�open�read�strip�unamer)�fd�platform�replaceZarchr
r
r�getArchds

r.cCsdS)Nz12.12.5-1.module_el8.10.0+6935+f9aadf00.cloudlinuxr
r
r
r
rrysrccs�tj�\}}tjd�}tjd�}tj|d�tj|d�z
dVWdtj|d�tj|d�Xtj|�tj|��<}tjdj|��}x$|D]}|j	|�s�t
|tjd�q�WWdQRXdS)zP
    Context manager to suppress errors
    matching the specified patterns
    ��N�|)�file)
r$�pipe�dup�dup2�close�fdopen�re�compile�join�search�print�sys�stderr)Zerror_patternsZread_endZ	write_endZ
old_stdoutZ
old_stderr�fZcombined_pattern�liner
r
r�suppress_errors~s





rA)�__doc__�
contextlibr$r=r8�gettextZup2date_clientrrZup2date_client.pkgplatformrZrhn.i18nrZtranslation�t�hasattrr�_rrr
rrrr.r�contextmanagerrAr
r
r
r�<module>s0



&
rhnHardware.py000064400000000510150516774050007371 0ustar00
from up2date_client import up2dateAuth
from up2date_client import rpcServer
from up2date_client import hardware

def updateHardware():
    s = rpcServer.getServer()


    hardwareList = hardware.Hardware()
    s.registration.refresh_hw_profile(up2dateAuth.getSystemId(),
                                          hardwareList)
hardware_hal.py000064400000026524150516774050007562 0ustar00#
# Copyright (c) 1999--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.
#

""" Get hardware info using HAL """

from .haltree import HalTree, HalDevice
import dbus

#PCI DEVICE DEFINES
# These are taken from pci_ids.h in the linux kernel source and used to
# properly identify the hardware
PCI_BASE_CLASS_STORAGE =        1
PCI_CLASS_STORAGE_SCSI =        0
PCI_CLASS_STORAGE_IDE =         1
PCI_CLASS_STORAGE_FLOPPY =      2
PCI_CLASS_STORAGE_IPI =         3
PCI_CLASS_STORAGE_RAID =        4
PCI_CLASS_STORAGE_OTHER =       80

PCI_BASE_CLASS_NETWORK =        2
PCI_CLASS_NETWORK_ETHERNET =    0
PCI_CLASS_NETWORK_TOKEN_RING =  1
PCI_CLASS_NETWORK_FDDI =        2
PCI_CLASS_NETWORK_ATM =         3
PCI_CLASS_NETWORK_OTHER =       80

PCI_BASE_CLASS_DISPLAY =        3
PCI_CLASS_DISPLAY_VGA =         0
PCI_CLASS_DISPLAY_XGA =         1
PCI_CLASS_DISPLAY_3D =          2
PCI_CLASS_DISPLAY_OTHER =       80

PCI_BASE_CLASS_MULTIMEDIA =     4
PCI_CLASS_MULTIMEDIA_VIDEO =    0
PCI_CLASS_MULTIMEDIA_AUDIO =    1
PCI_CLASS_MULTIMEDIA_PHONE =    2
PCI_CLASS_MULTIMEDIA_OTHER =    80

PCI_BASE_CLASS_BRIDGE =         6
PCI_CLASS_BRIDGE_HOST =         0
PCI_CLASS_BRIDGE_ISA =          1
PCI_CLASS_BRIDGE_EISA =         2
PCI_CLASS_BRIDGE_MC =           3
PCI_CLASS_BRIDGE_PCI =          4
PCI_CLASS_BRIDGE_PCMCIA =       5
PCI_CLASS_BRIDGE_NUBUS =        6
PCI_CLASS_BRIDGE_CARDBUS =      7
PCI_CLASS_BRIDGE_RACEWAY =      8
PCI_CLASS_BRIDGE_OTHER =        80

PCI_BASE_CLASS_COMMUNICATION =  7
PCI_CLASS_COMMUNICATION_SERIAL = 0
PCI_CLASS_COMMUNICATION_PARALLEL = 1
PCI_CLASS_COMMUNICATION_MULTISERIAL = 2
PCI_CLASS_COMMUNICATION_MODEM = 3
PCI_CLASS_COMMUNICATION_OTHER = 80

PCI_BASE_CLASS_INPUT =          9
PCI_CLASS_INPUT_KEYBOARD =      0
PCI_CLASS_INPUT_PEN =           1
PCI_CLASS_INPUT_MOUSE =         2
PCI_CLASS_INPUT_SCANNER =       3
PCI_CLASS_INPUT_GAMEPORT =      4
PCI_CLASS_INPUT_OTHER =         80

PCI_BASE_CLASS_SERIAL =         12
PCI_CLASS_SERIAL_FIREWIRE =     0
PCI_CLASS_SERIAL_ACCESS =       1
PCI_CLASS_SERIAL_SSA =          2
PCI_CLASS_SERIAL_USB =          3
PCI_CLASS_SERIAL_FIBER =        4
PCI_CLASS_SERIAL_SMBUS =        5

# read_hal()
#
# This reads in all the properties for each device from HAL, storing the
# property names & values into a dict.  A list of dicts is returned.
#
# This only works on newer versions of dbus & HAL (as found in RHEL5)
def read_hal():
    ret = []
    bus = dbus.SystemBus()

    hal_manager_obj = bus.get_object('org.freedesktop.Hal',
        '/org/freedesktop/Hal/Manager')
    hal_manager = dbus.Interface(hal_manager_obj,
        'org.freedesktop.Hal.Manager')

    device_list = hal_manager.GetAllDevices()
    hal_tree = HalTree()
    for udi in device_list:
        device_obj = bus.get_object ('org.freedesktop.Hal', udi)
        device = dbus.Interface(device_obj, 'org.freedesktop.Hal.Device')

        properties = device.GetAllProperties()

        haldev = HalDevice(properties)
        hal_tree.add(haldev)

    kudzu_list = process_hal_nodes(hal_tree.head)
    return kudzu_list

    # Recursive function, does all the dirty work for add_hal_hardware
def process_hal_nodes(node):
    kudzu_list = []
    node.classification = classify_hal(node)
    if node.classification:
        parent = node.parent
        dev = {}
        dev['class'] = node.classification
        #get bus
        dev['bus'] = str(get_device_bus(node))

        #get scsi info
        if dev['bus'] == 'scsi':
            if 'scsi.host' in parent.properties:
                dev['prop1'] = parent.properties['scsi.host']
            if 'scsi.target' in parent.properties:
                dev['prop2'] = parent.properties['scsi.target']
            if 'scsi.bus' in parent.properties:
                dev['prop3'] = parent.properties['scsi.bus']
            if 'scsi.lun' in parent.properties:
                dev['prop4'] = parent.properties['scsi.lun']


        dev['driver'] = str(get_device_driver(node))

        device_path = get_device_path(node)
        if device_path:
            dev['device'] = str(device_path)

        dev['desc'] = str(get_device_description(node))

        dev['pciType'] = str(get_device_pcitype(node))

        dev['detached'] = 0
        kudzu_list.append(dev)

    for child in node.children:
        child_list = process_hal_nodes(child)
        kudzu_list.extend(child_list)

    return kudzu_list

def classify_hal(node):
    # NETWORK
    if 'net.interface' in node.properties:
        return 'NETWORK'

    if 'info.product' in node.properties and 'info.category' in node.properties:
        if node.properties['info.category'] == 'input':
            # KEYBOARD <-- do this before mouse, some keyboards have built-in mice
            if 'keyboard' in node.properties['info.product'].lower():
                return 'KEYBOARD'
            # MOUSE
            if 'mouse' in node.properties['info.product'].lower():
                return 'MOUSE'

    if 'pci.device_class' in node.properties:
        #VIDEO
        if node.properties['pci.device_class'] == PCI_BASE_CLASS_DISPLAY:
            return 'VIDEO'
        #USB
        if (node.properties['pci.device_class'] ==  PCI_BASE_CLASS_SERIAL
                and node.properties['pci.device_subclass'] == PCI_CLASS_SERIAL_USB):
            return 'USB'

        if node.properties['pci.device_class'] == PCI_BASE_CLASS_STORAGE:
            #IDE
            if node.properties['pci.device_subclass'] == PCI_CLASS_STORAGE_IDE:
                return 'IDE'
            #SCSI
            if node.properties['pci.device_subclass'] == PCI_CLASS_STORAGE_SCSI:
                return 'SCSI'
            #RAID
            if node.properties['pci.device_subclass'] == PCI_CLASS_STORAGE_RAID:
                return 'RAID'
        #MODEM
        if (node.properties['pci.device_class'] == PCI_BASE_CLASS_COMMUNICATION
                and node.properties['pci.device_subclass'] == PCI_CLASS_COMMUNICATION_MODEM):
            return 'MODEM'
        #SCANNER
        if (node.properties['pci.device_class'] == PCI_BASE_CLASS_INPUT
                and node.properties['pci.device_subclass'] == PCI_CLASS_INPUT_SCANNER):
            return 'SCANNER'

        if node.properties['pci.device_class'] == PCI_BASE_CLASS_MULTIMEDIA:
            #CAPTURE -- video capture card
            if node.properties['pci.device_subclass'] == PCI_CLASS_MULTIMEDIA_VIDEO:
                return 'CAPTURE'
            #AUDIO
            if node.properties['pci.device_subclass'] == PCI_CLASS_MULTIMEDIA_AUDIO:
                return 'AUDIO'

        #FIREWIRE
        if (node.properties['pci.device_class'] == PCI_BASE_CLASS_SERIAL
                and node.properties['pci.device_subclass'] == PCI_CLASS_SERIAL_FIREWIRE):
            return 'FIREWIRE'
        #SOCKET -- PCMCIA yenta socket stuff
        if (node.properties['pci.device_class'] == PCI_BASE_CLASS_BRIDGE
                and (node.properties['pci.device_subclass'] == PCI_CLASS_BRIDGE_PCMCIA
                or node.properties['pci.device_subclass'] == PCI_CLASS_BRIDGE_CARDBUS)):
            return 'SOCKET'

    if 'storage.drive_type' in node.properties:
        #CDROM
        if node.properties['storage.drive_type'] == 'cdrom':
            return 'CDROM'
        #HD
        if node.properties['storage.drive_type'] == 'disk':
            return 'HD'
         #FLOPPY
        if node.properties['storage.drive_type'] == 'floppy':
            return 'FLOPPY'
        #TAPE
        if node.properties['storage.drive_type'] == 'tape':
            return 'TAPE'

    if 'xen.type' in node.properties:
        if node.properties['xen.type'] == 'vbd':
            return 'HD'

    #PRINTER
    if 'printer.product' in node.properties:
        return 'PRINTER'

    #Catchall for specific devices, only do this after all the others
    if ('pci.product_id' in node.properties or
            'usb.product_id' in node.properties):
        return 'OTHER'

    # No class found
    return None

def get_device_bus(node):
    if 'storage.bus' in node.properties:
        bus = node.properties['storage.bus']
    elif 'info.bus' in node.properties:
        if node.properties['info.bus'] == 'platform':
            bus = 'MISC'
        else:
            bus = node.properties['info.bus']
    else:
        bus = 'MISC'

    return bus

def get_device_driver(node):
    if 'info.linux.driver' in node.properties:
        driver = node.properties['info.linux.driver']
    elif 'net.linux.driver' in node.properties:
        driver = node.properties['net.linux.driver']
    else:
        driver = 'unknown'

    return driver

def get_device_path(node):
    """
    Return the device file path.

    As kudzu did not return a string with the /dev/ prefix,
    this function will not, either.
    RHN's DB has a limit of 16 characters for the device path.
    If the path is longer than that, return None.
    If no device path is found, return None.
    """
    dev = None

    if 'block.device' in node.properties:
        dev = node.properties['block.device']
    elif 'linux.device_file' in node.properties:
        dev = node.properties['linux.device_file']
    elif (node.classification == 'NETWORK'
            and 'net.interface' in node.properties):
        dev = node.properties['net.interface']

    if dev:
        if dev.startswith('/dev/'):
            dev = dev[5:]
        if len(dev) > 16:
            dev = None

    return dev

def get_device_description(node):
    if ('info.vendor' in node.properties
            and 'info.product' in node.properties):
        desc = node.properties['info.vendor'] + '|' +  node.properties['info.product']
    elif ('info.vendor' in node.properties):
        desc = node.properties['info.vendor']
    elif 'info.product' in node.properties:
        desc =  node.properties['info.product']
    else:
        desc = ""

    return desc

def get_device_pcitype(node):
    PCI_TYPE_PCMCIA = 2
    PCI_TYPE_PCI = 1
    PCI_TYPE_NOT_PCI = -1

    if 'info.bus' in (node.properties
            and node.properties['info.bus'] == 'pci'):
        parent = node.parent
        if ('pci.device_class' in parent.properties
                and (parent.properties['pci.device_class'] == 6
                and (parent.properties['pci.device_subclass'] == 5
                or parent.properties['pci.device_subclass'] == 7))):
            pcitype = PCI_TYPE_PCMCIA
        else:
            pcitype = PCI_TYPE_PCI
    else:
        pcitype = PCI_TYPE_NOT_PCI

    return pcitype

def get_hal_computer():
    bus = dbus.SystemBus()
    computer_obj = bus.get_object("org.freedesktop.Hal",
        "/org/freedesktop/Hal/devices/computer")
    computer = dbus.Interface(computer_obj, "org.freedesktop.Hal.Device")

    return computer

def check_hal_dbus_status():
    # check if hal and messagebus are running, if not warn the user
    import subprocess as commands
    hal_status, msg = commands.getstatusoutput('/etc/init.d/haldaemon status')
    dbus_status, msg = commands.getstatusoutput('/etc/init.d/messagebus status')
    return hal_status, dbus_status


up2dateAuth.py000064400000025300150516774050007316 0ustar00#

import os
import pickle
import sys
import time
import socket
import subprocess
from up2date_client import rpcServer

try: # python2
    from types import DictType
except ImportError: # python3
    DictType = dict

from rhn import rpclib
from up2date_client import clientCaps
from up2date_client import config
from up2date_client import rhnserver
from up2date_client import up2dateErrors
from up2date_client import up2dateLog
from up2date_client import up2dateUtils

loginInfo = None
pcklAuthFileName = "/var/spool/up2date/loginAuth.pkl"

def getSystemId():
    cfg = config.initUp2dateConfig()
    path = cfg["systemIdPath"]
    if not os.access(path, os.R_OK):
        return None

    f = open(path, "r")
    ret = f.read()

    f.close()
    return ret


def getPreferredInterface():
    """
    Extract the preferred_interface parameter from system_id XML
    Returns 'IPv4' or 'IPv6' if specified, otherwise 'IPv4' as default
    """
    log = up2dateLog.initLog()
    systemId = getSystemId()
    preferred_interface = "IPv4"

    if systemId is None:
        return preferred_interface

    try:
        # Read the system ID XML and parse it
        # rpclib.xmlrpclib is the standard way to do this across the project
        params = rpclib.xmlrpclib.loads(systemId)[0][0]
        cfg_interface = params.get("preferred_interface", "IPv4")
        # Only 'IPv4' and 'IPv6' are valid options
        if preferred_interface in ("IPv4", "IPv6"):
            preferred_interface = cfg_interface
        else:
            log.log_me(
                "Invalid preferred_interface value '%s' in system_id, "
                "defaulting to '%s'" % (cfg_interface, preferred_interface)
            )
        return preferred_interface
    except Exception:
        # If there's any error parsing the XML, default to IPv4
        log.log_me("Failed to parse system_id XML, preferred_interface defaulting to 'IPv4'")
        log.log_exception(*sys.exc_info())
    return preferred_interface


# if a user has upgraded to a newer release of Red Hat but still
# has a systemid from their older release, they need to get an updated
# systemid from the RHN servers.  This takes care of that.
def maybeUpdateVersion():
    # if process is in the middle of system upgrade, do not switch channel automatically
    if os.environ.get('LEAPP_IPU_IN_PROGRESS'):
        return

    cfg = config.initUp2dateConfig()
    try:
        idVer = rpclib.xmlrpclib.loads(getSystemId())[0][0]['os_release']
    except:
        # they may not even have a system id yet.
        return 0

    systemVer = up2dateUtils.getVersion()

    if not cfg['channelOverride'] and idVer != systemVer:
      s = rhnserver.RegistrationRhnServer()

      newSystemId = s.registration.upgrade_version(getSystemId(), systemVer)

      path = cfg["systemIdPath"]
      dir = path[:path.rfind("/")]
      if not os.access(dir, os.W_OK):
          try:
              os.mkdir(dir)
          except:
              return 0
      if not os.access(dir, os.W_OK):
          return 0

      if os.access(path, os.F_OK):
          # already have systemid file there; let's back it up
          savePath = path + ".save"
          try:
              os.rename(path, savePath)
          except:
              return 0

      f = open(path, "w")
      f.write(newSystemId)
      f.close()
      try:
          os.chmod(path, int('0600', 8))
      except:
          pass


def writeCachedLogin():
    """
    Pickle loginInfo to a file
    Returns:
    True    -- wrote loginInfo to a pickle file
    False   -- did _not_ write loginInfo to a pickle file
    """
    log = up2dateLog.initLog()
    log.log_debug("writeCachedLogin() invoked")
    if not loginInfo:
        log.log_debug("writeCachedLogin() loginInfo is None, so bailing.")
        return False
    data = {'time': time.time(),
            'loginInfo': loginInfo}

    pcklDir = os.path.dirname(pcklAuthFileName)
    if not os.access(pcklDir, os.W_OK):
        try:
            os.mkdir(pcklDir)
            os.chmod(pcklDir, int('0700', 8))
        except:
            log.log_me("Unable to write pickled loginInfo to %s" % pcklDir)
            return False
    pcklAuth = open(pcklAuthFileName, 'wb')
    os.chmod(pcklAuthFileName, int('0600', 8))
    pickle.dump(data, pcklAuth)
    pcklAuth.close()
    expireTime = data['time'] + float(loginInfo['X-RHN-Auth-Expire-Offset'])
    log.log_debug("Wrote pickled loginInfo at ", data['time'], " with expiration of ",
            expireTime, " seconds.")
    return True

def readCachedLogin():
    """
    Read pickle info from a file
    Caches authorization info for connecting to the server.
    """
    log = up2dateLog.initLog()
    log.log_debug("readCachedLogin invoked")
    if not os.access(pcklAuthFileName, os.R_OK):
        log.log_debug("Unable to read pickled loginInfo at: %s" % pcklAuthFileName)
        return False
    pcklAuth = open(pcklAuthFileName, 'rb')
    try:
        data = pickle.load(pcklAuth)
    except (EOFError, ValueError):
        log.log_debug("Unexpected EOF. Probably an empty file, \
                       regenerate auth file")
        pcklAuth.close()
        return False
    pcklAuth.close()
    # Check if system_id has changed
    try:
        idVer = rpclib.xmlrpclib.loads(getSystemId())[0][0]['system_id']
        cidVer = "ID-%s" % data['loginInfo']['X-RHN-Server-Id']
        if idVer != cidVer:
            log.log_debug("system id version changed: %s vs %s" % (idVer, cidVer))
            return False
    except:
        pass
    createdTime = data['time']
    li = data['loginInfo']
    currentTime = time.time()
    expireTime = createdTime + float(li['X-RHN-Auth-Expire-Offset'])
    #Check if expired, offset is stored in "X-RHN-Auth-Expire-Offset"
    log.log_debug("Checking pickled loginInfo, currentTime=", currentTime,
            ", createTime=", createdTime, ", expire-offset=",
            float(li['X-RHN-Auth-Expire-Offset']))
    if (currentTime > expireTime):
        log.log_debug("Pickled loginInfo has expired, created = %s, expire = %s." \
                %(createdTime, expireTime))
        return False
    _updateLoginInfo(li)
    log.log_debug("readCachedLogin(): using pickled loginInfo set to expire at ", expireTime)
    return True

def _updateLoginInfo(li):
    """
    Update the global var, "loginInfo"
    """
    global loginInfo
    if type(li) == DictType:
        if type(loginInfo) == DictType:
            # must retain the reference.
            loginInfo.update(li)
        else:
            # this had better be the initial login or we lose the reference.
            loginInfo = li
    else:
        loginInfo = None

# allow to pass in a system id for use in rhnreg
# a bit of a kluge to make caps work correctly
def login(systemId=None, forceUpdate=False, timeout=None):
    log = up2dateLog.initLog()
    log.log_debug("login(forceUpdate=%s) invoked" % (forceUpdate))
    if not forceUpdate and not loginInfo:
        if readCachedLogin():
            return loginInfo

    server = rhnserver.RhnServer(timeout=timeout)

    # send up the capabality info
    headerlist = clientCaps.caps.headerFormat()
    for (headerName, value) in headerlist:
        server.add_header(headerName, value)

    if systemId == None:
        systemId = getSystemId()

    if not systemId:
        return None

    maybeUpdateVersion()
    log.log_me("logging into up2date server")

    li = server.up2date.login(systemId, socket.getfqdn(), _get_panel_name(log))

    # figure out if were missing any needed caps
    server.capabilities.validate()
    _updateLoginInfo(li) #update global var, loginInfo
    writeCachedLogin() #pickle global loginInfo

    if loginInfo:
        log.log_me("successfully retrieved authentication token "
                   "from up2date server")

    log.log_debug("logininfo:", loginInfo)
    return loginInfo

def updateLoginInfo(timeout=None):
    log = up2dateLog.initLog()
    log.log_me("updateLoginInfo() login info")
    # NOTE: login() updates the loginInfo object
    login(forceUpdate=True, timeout=timeout)
    if not loginInfo:
        raise up2dateErrors.AuthenticationError("Unable to authenticate")
    return loginInfo


def getLoginInfo(timeout=None):
    global loginInfo
    try:
        loginInfo = loginInfo
    except NameError:
        loginInfo = None
    if loginInfo:
        return loginInfo
    # NOTE: login() updates the loginInfo object
    login(timeout=timeout)
    return loginInfo


class _FailedToGetPanelName(Exception):
    pass


def _get_panel_name(log):
    try:
        panel_name = _get_panel_name_via_cldetect()
    except _FailedToGetPanelName:
        # Do not spam logs when we're executed from under cldeploy script
        # and no cloudlinux packages are yet installed.
        if not _is_cldeploy_running():
            log.log_exception(*sys.exc_info())
            log.log_me("Failed to get panel name via cldetect, using fallback mechanism")
        panel_name = _fallback_get_panel_name()
    return panel_name.lower()


def _is_cldeploy_running():
    # NOTE(vlebedev): This is more or less a direct port of shell code from cldeploy script.
    lock_file_path = '/var/lock/cldeploy.lck'
    cldeploy_running = False
    pid = None

    if os.path.exists(lock_file_path):
        with open(lock_file_path) as f:
            pid = f.read().strip()
    if pid:
        pid_cmdline_path = "/proc/%s/cmdline" % pid
        if os.path.exists(pid_cmdline_path):
            with open(pid_cmdline_path) as f:
                cldeploy_running = 'cldeploy' in f.read()
    return cldeploy_running


def _get_panel_name_via_cldetect():
    binary, _ = cmd = ["/usr/bin/cldetect", "--detect-cp-nameonly"]
    if not os.path.exists(binary):
        raise _FailedToGetPanelName(
            "Failed to obtain panel name because '%s' does not exist"
            % binary
        )

    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
    stdout, stderr = process.communicate()
    if process.returncode != 0:
        raise _FailedToGetPanelName(
            "Failed to obtain panel name using '%s' command; stderr: %s"
            % (" ".join(cmd), stderr)
        )

    return stdout.strip()


def _fallback_get_panel_name():
    # NOTE(vlebedev): This is more or less a direct port of shell code from cldeploy script.
    # TODO(vlebedev): Pass $PANEL from cldeploy instead of duplication?
    if os.path.isdir("/usr/local/psa/admin/"):
        return "plesk"
    if os.path.isdir("/usr/local/interworx/"):
        return "interworx"
    if os.path.isdir("/usr/local/cpanel/whostmgr/docroot/"):
        return "cpanel"
    if os.path.isdir("/usr/local/ispmgr/"):
        return "ispmgr"
    if os.path.isdir("/usr/local/directadmin/"):
        return "directadmin"
    if os.path.isfile("/usr/local/mgr5/sbin/mgrctl"):
        return "ispmgr5"
    return "unknown"
rpcServer.py000064400000027337150516774050007117 0ustar00#

import os
import sys
import socket
import time

from up2date_client import config
from up2date_client import clientCaps
from up2date_client import up2dateLog
from up2date_client import up2dateErrors
from up2date_client import up2dateUtils

from rhn import SSL
from rhn import rpclib
from rhn.tb import raise_with_tb

try:  # python2
    import httplib
    import urllib2
    import urlparse
    import xmlrpclib
except ImportError:  # python3
    import http.client as httplib
    import urllib.request as urllib2
    import urllib.parse as urlparse
    import xmlrpc.client as xmlrpclib

import gettext

t = gettext.translation("rhn-client-tools", fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, "ugettext"):
    t.ugettext = t.gettext
_ = t.ugettext


def stdoutMsgCallback(msg):
    print(msg)


class RetryServer(rpclib.Server):
    # Dict of server: error_message pairs to keep track of failure messages and display them if needed
    _error_messages = {}

    def addServerList(self, serverList):
        self.serverList = serverList

    def _request1(self, methodname, params):
        self.log = up2dateLog.initLog()

        while 1:
            try:
                ret = self._request(methodname, params)
            except rpclib.InvalidRedirectionError:
                raise
            except xmlrpclib.Fault:
                raise
            except httplib.BadStatusLine:
                self.log.log_me("Error: Server Unavailable. Please try later.")
                stdoutMsgCallback(_("Error: Server Unavailable. Please try later."))
                sys.exit(-1)
            except:
                server = self.serverList.next()

                if server is None:
                    # since just because we failed, the server list could
                    # change (aka, firstboot, they get an option to reset the
                    # the server configuration) so reset the serverList
                    self.serverList.resetServerIndex()

                    # Display the error messages for all servers to stdout
                    # This only happens if all servers in the list fail
                    if self._error_messages:
                        error_combined_msg = "\n".join(
                            ["%s:\n%s" % (host, error) for host, error in self._error_messages.items()]
                        )
                        # No need to log this, these are already logged at the same point where the error occurred
                        stdoutMsgCallback(_("Errors occurred while trying to connect to the remote servers."))
                        stdoutMsgCallback(error_combined_msg)

                    raise

                msg = "An error occurred talking to %s:\n" % self._host
                exception_msg = "%s\n%s\n" % (sys.exc_info()[0], sys.exc_info()[1])

                # Store the error message for the failed server
                self._error_messages[self._host] = exception_msg

                msg = msg + exception_msg
                msg = msg + "Trying the next serverURL: %s\n" % self.serverList.server()

                self.log.log_me(msg)
                # try a different url

                # use the next serverURL
                parse_res = urlparse.urlsplit(self.serverList.server())
                typ = parse_res[0]  # scheme
                self._host = parse_res[1]  # netloc
                self._handler = parse_res[2]  # path
                typ = typ.lower()
                if typ not in ("http", "https"):
                    raise_with_tb(rpclib.InvalidRedirectionError("Redirected to unsupported protocol %s" % typ))
                self._orig_handler = self._handler
                self._type = typ
                self._uri = self.serverList.server()
                if not self._handler:
                    self._handler = "/RPC2"
                self._allow_redirect = 1
                continue
            # if we get this far, we succedded
            break
        return ret

    def __getattr__(self, name):
        # magic method dispatcher
        return rpclib.xmlrpclib._Method(self._request1, name)


# uh, yeah, this could be an iterator, but we need it to work on 1.5 as well
class ServerList:
    def __init__(self, serverlist=[]):
        self.serverList = serverlist
        self.index = 0

    def server(self):
        self.serverurl = self.serverList[self.index]
        return self.serverurl

    def next(self):
        self.index = self.index + 1
        if self.index >= len(self.serverList):
            return None
        return self.server()

    def resetServerIndex(self):
        self.index = 0


def getServer(
    refreshCallback=None,
    serverOverride=None,
    timeout=None,
    registration=False,
):
    log = up2dateLog.initLog()
    cfg = config.initUp2dateConfig()

    # Where do we keep the CA certificate for RHNS?
    # The servers we're talking to need to have their certs
    # signed by one of these CA.
    ca = cfg["sslCACert"]
    if not isinstance(ca, list):
        ca = [ca]

    rhns_ca_certs = ca or ["/usr/share/rhn/CLN-ORG-TRUSTED-SSL-CERT"]
    if cfg["enableProxy"]:
        proxyHost = config.getProxySetting()
    else:
        proxyHost = None

    if not serverOverride:
        serverUrls = config.getServerURL(registration=registration)

        # Check for a fallback server URL and add it to the list if available
        fallbackURL = config.getFallbackServerURL(registration=registration)
        # Ensure that none of the URLs from the fallback list are already in the serverUrls list
        if fallbackURL:
            for url in fallbackURL:
                if url not in serverUrls:
                    serverUrls.append(url)
    else:
        serverUrls = serverOverride
    serverList = ServerList(serverUrls)

    proxyUser = None
    proxyPassword = None
    if cfg["enableProxyAuth"]:
        proxyUser = cfg["proxyUser"] or None
        proxyPassword = cfg["proxyPassword"] or None

    lang = None
    for env in "LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG":
        if env in os.environ:
            if not os.environ[env]:
                # sometimes unset
                continue
            lang = os.environ[env].split(":")[0]
            lang = lang.split(".")[0]
            break

    s = RetryServer(
        serverList.server(),
        refreshCallback=refreshCallback,
        proxy=proxyHost,
        username=proxyUser,
        password=proxyPassword,
        timeout=timeout,
    )
    s.addServerList(serverList)

    s.add_header("X-Up2date-Version", up2dateUtils.version())

    if lang:
        s.setlang(lang)

    # require CLN-ORG-TRUSTED-SSL-CERT file to be able to authenticate the SSL connections
    need_ca = [True for i in s.serverList.serverList if urlparse.urlparse(i)[0] == "https"]
    if need_ca:
        for rhns_ca_cert in rhns_ca_certs:
            if not os.access(rhns_ca_cert, os.R_OK):
                msg = "%s: %s" % (_("ERROR: can not find RHNS CA file"), rhns_ca_cert)
                log.log_me("%s" % msg)
                raise up2dateErrors.SSLCertificateFileNotFound(msg)

            # force the validation of the SSL cert
            s.add_trusted_cert(rhns_ca_cert)

    clientCaps.loadLocalCaps()

    # send up the capabality info
    headerlist = clientCaps.caps.headerFormat()
    for headerName, value in headerlist:
        s.add_header(headerName, value)
    return s


def doCall(method, *args, **kwargs):
    log = up2dateLog.initLog()
    log.log_debug("rpcServer: Calling XMLRPC %s" % method.__dict__["_Method__name"])
    cfg = config.initUp2dateConfig()
    ret = None

    attempt_count = 1
    try:
        attempts = int(cfg["networkRetries"])
    except ValueError:
        attempts = 1
    if attempts <= 0:
        attempts = 1

    while 1:
        failure = 0
        ret = None
        try:
            ret = method(*args, **kwargs)
        except KeyboardInterrupt:
            raise_with_tb(up2dateErrors.CommunicationError(_("Connection aborted by the user")))
        # if we get a socket error, keep tryingx2
        except (socket.error, SSL.socket_error):
            log.log_me("A socket error occurred: %s, attempt #%s" % (sys.exc_info()[1], attempt_count))
            if attempt_count >= attempts:
                e = sys.exc_info()[1]
                if len(e.args) > 1:
                    raise_with_tb(up2dateErrors.CommunicationError(e.args[1]))
                else:
                    raise_with_tb(up2dateErrors.CommunicationError(e.args[0]))
            else:
                failure = 1
        except httplib.IncompleteRead:
            print("httplib.IncompleteRead")
            raise_with_tb(up2dateErrors.CommunicationError("httplib.IncompleteRead"))

        except urllib2.HTTPError:
            e = sys.exc_info()[1]
            msg = "\nAn HTTP error occurred:\n"
            msg = msg + "URL: %s\n" % e.filename
            msg = msg + "Status Code: %s\n" % e.code
            msg = msg + "Error Message: %s\n" % e.msg
            log.log_me(msg)
            raise_with_tb(up2dateErrors.CommunicationError(msg))

        except xmlrpclib.ProtocolError:
            e = sys.exc_info()[1]
            log.log_me("A protocol error occurred: %s , attempt #%s," % (e.errmsg, attempt_count))
            if e.errcode == 404:
                log.log_me("Could not find URL, %s" % (e.url))
                log.log_me("Check server name and/or URL, then retry\n")

            (errCode, errMsg) = rpclib.reportError(e.headers)
            reset = 0
            if abs(errCode) == 34:
                log.log_me("Auth token timeout occurred\n errmsg: %s" % errMsg)
                # this calls login, which in tern calls doCall (ie,
                # this function) but login should never get a 34, so
                # should be safe from recursion

                from up2date_client import up2dateAuth

                up2dateAuth.updateLoginInfo()

            # the servers are being throttle to pay users only, catch the
            # exceptions and display a nice error message
            if abs(errCode) == 51:
                log.log_me(_("Server has refused connection due to high load"))
                raise_with_tb(up2dateErrors.CommunicationError(e.errmsg))
            # if we get a 404 from our server, thats pretty
            # fatal... no point in retrying over and over. Note that
            # errCode == 17 is specific to our servers, if the
            # serverURL is just pointing somewhere random they will
            # get a 0 for errcode and will raise a CommunicationError
            if abs(errCode) == 17:
                # in this case, the args are the package string, so lets try to
                # build a useful error message
                if type(args[0]) == type([]):
                    pkg = args[0]
                else:
                    pkg = args[1]

                if type(pkg) == type([]):
                    pkgName = "%s-%s-%s.%s" % (pkg[0], pkg[1], pkg[2], pkg[4])
                else:
                    pkgName = pkg
                msg = "File Not Found: %s\n%s" % (pkgName, errMsg)
                log.log_me(msg)
                raise_with_tb(up2dateErrors.FileNotFoundError(msg))

            if not reset:
                if attempt_count >= attempts:
                    raise_with_tb(up2dateErrors.CommunicationError(e.errmsg))
                else:
                    failure = 1

        except xmlrpclib.ResponseError:
            raise_with_tb(up2dateErrors.CommunicationError("Broken response from the server."))

        if ret != None:
            break
        else:
            failure = 1

        if failure:
            # rest for five seconds before trying again
            time.sleep(5)
            attempt_count = attempt_count + 1

        if attempt_count > attempts:
            raise up2dateErrors.CommunicationError("The data returned from the server was incomplete")

    return ret
rhnserver.py000064400000022473150516774050007156 0ustar00
#   rhn-client-tools
#
# Copyright (c) 2006--2016 Red Hat, Inc.
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; version 2 of the License.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
#   02110-1301  USA
#
# 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.


from rhn.tb import raise_with_tb
from up2date_client import rpcServer
from up2date_client import up2dateErrors
from up2date_client import capabilities
import sys
import OpenSSL

try: # python2
    import xmlrpclib
except ImportError: # python3
    import xmlrpc.client as xmlrpclib

class _DoCallWrapper(object):

    """
    A callable object that will handle multiple levels of attributes,
    and catch exceptions.
    """

    def __init__(self, server, method_name):
        self._server = server
        self._method_name = method_name

    def __getattr__(self, method_name):
        """ Recursively build up the method name to pass to the server. """
        return _DoCallWrapper(self._server,
            "%s.%s" % (self._method_name, method_name))

    def __call__(self, *args, **kwargs):
        """ Call the method. Catch faults and translate them. """
        method = getattr(self._server, self._method_name)

        try:
            return rpcServer.doCall(method, *args, **kwargs)
        except xmlrpclib.Fault:
            raise_with_tb(self.__exception_from_fault(sys.exc_info()[1]))
        except OpenSSL.SSL.Error:
            # TODO This should probably be moved to rhnlib and raise an
            # exception that subclasses OpenSSL.SSL.Error
            # TODO Is there a better way to detect cert failures?
            error = str(sys.exc_info()[1])
            error = error.strip("[()]")
            pieces = error.split(',')
            message = ""
            if len(pieces) > 2:
                message = pieces[2]
            elif len(pieces) == 2:
                message = pieces[1]
            message = message.strip(" '")
            if message == 'certificate verify failed':
                raise_with_tb(up2dateErrors.SSLCertificateVerifyFailedError())
            else:
                raise_with_tb(up2dateErrors.NetworkError(message))

    def __exception_from_fault(self, fault):
            if fault.faultCode == -3:
                # This username is already taken, or the password is incorrect.
                exception = up2dateErrors.AuthenticationOrAccountCreationError(fault.faultString)
            elif fault.faultCode == -2:
                # Invalid username and password combination.
                exception = up2dateErrors.AuthenticationOrAccountCreationError(fault.faultString)
            elif fault.faultCode == -110:
                # Account is disabled
                exception = up2dateErrors.AuthenticationOrAccountCreationError(fault.faultString)
            elif fault.faultCode == -1:
                exception = up2dateErrors.UnknownMethodException(fault.faultString)
            elif fault.faultCode == -13:
                # Username is too short.
                exception = up2dateErrors.LoginMinLengthError(fault.faultString)
            elif fault.faultCode == -14:
                # too short password
                exception = up2dateErrors.PasswordMinLengthError(
                                          fault.faultString)
            elif fault.faultCode == -15:
                # bad chars in username
                exception = up2dateErrors.ValidationError(fault.faultString)
            elif fault.faultCode == -16:
                # Invalid product registration code.
                # TODO Should this really be a validation error?
                exception = up2dateErrors.ValidationError(fault.faultString)
            elif fault.faultCode == -19:
                # invalid
                exception = up2dateErrors.NoBaseChannelError(fault.faultString)
            elif fault.faultCode == -31:
                # No entitlement
                exception = up2dateErrors.InsuffMgmntEntsError(fault.faultString)
            elif fault.faultCode == -36:
                # rhnException.py says this means "Invalid action."
                # TODO find out which is right
                exception = up2dateErrors.PasswordError(fault.faultString)
            elif abs(fault.faultCode) == 49:
                exception = up2dateErrors.AbuseError(fault.faultString)
            elif abs(fault.faultCode) == 60:
                exception = up2dateErrors.AuthenticationTicketError(fault.faultString)
            elif abs(fault.faultCode) == 74:
                exception = up2dateErrors.RegistrationDeniedError()
            elif abs(fault.faultCode) == 105:
                exception = up2dateErrors.RhnUuidUniquenessError(fault.faultString)
            elif fault.faultCode == 99:
                exception = up2dateErrors.DelayError(fault.faultString)
            elif abs(fault.faultCode) == 91:
                exception = up2dateErrors.InsuffMgmntEntsError(fault.faultString)
            elif fault.faultCode == -106:
                # Invalid username.
                exception = up2dateErrors.ValidationError(fault.faultString)
            elif fault.faultCode == -600:
                # Invalid username.
                exception = up2dateErrors.InvalidRegistrationNumberError(fault.faultString)
            elif fault.faultCode == -601:
                # No entitlements associated with given hardware info
                exception = up2dateErrors.NotEntitlingError(fault.faultString)
            elif fault.faultCode == -602:
                # No entitlements associated with reg num
                exception = up2dateErrors.NotEntitlingError(fault.faultString)
            elif fault.faultCode == -2001 or fault.faultCode == -700:
                exception = up2dateErrors.AuthenticationOrAccountCreationError(
                                          fault.faultString)
            elif fault.faultCode == -701:
                exception = up2dateErrors.PasswordMaxLengthError(
                                          fault.faultString)
            elif fault.faultCode == -61:
                exception = up2dateErrors.ActivationKeyUsageLimitError(
                                          fault.faultString)
            elif fault.faultCode == -5:
                exception = up2dateErrors.UnableToCreateUser(
                            fault.faultString)
            else:
                exception = up2dateErrors.CommunicationError(fault.faultString)

            return exception


class RhnServer(object):
    """
    An rpc server object that calls doCall for you, and catches lower
    level exceptions
    """

    def __init__(
        self,
        serverOverride=None,
        timeout=None,
        rpcServerOverride=None,
        registration=False,
    ):
        if rpcServerOverride is None:
            self._server = rpcServer.getServer(
                serverOverride=serverOverride,
                timeout=timeout,
                registration=registration,
            )
        else:
            self._server = rpcServerOverride
        self._capabilities = None

    def __get_capabilities(self):
        if self._capabilities is None:
            headers = self._server.get_response_headers()
            if headers is None:
                self.registration.welcome_message()
                headers = self._server.get_response_headers()
            self._capabilities = capabilities.Capabilities()
            self._capabilities.populate(headers)
        return self._capabilities

    capabilities = property(__get_capabilities)

    def add_header(self, key, value):
        self._server.add_header(key, value)

    def __getattr__(self, method_name):
        """Return a callable object that will do the work for us."""
        return _DoCallWrapper(self._server, method_name)


class RegistrationRhnServer(RhnServer):
    """
    A specialized RhnServer subclass for handling registration-related calls.

    Intended to be used as a shorthand for registration tasks instead of
    the plain RhnServer.
    """

    def __init__(self, serverOverride=None, timeout=None, rpcServerOverride=None):
        super(RegistrationRhnServer, self).__init__(
            serverOverride=serverOverride,
            timeout=timeout,
            rpcServerOverride=rpcServerOverride,
            registration=True,
        )
up2dateErrors.py000064400000024406150516774050007677 0ustar00#
# Client code for Update Agent
# Copyright (c) 1999--2016 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Preston Brown <pbrown@redhat.com>
#         Adrian Likins <alikins@redhat.com
#         Cristian Gafton <gafton@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.

import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext
import OpenSSL
from rhn.i18n import ustr
from up2date_client import config
from up2date_client import up2dateLog
from up2date_client.pkgplatform import getPlatform

import sys
sys.path = sys.path[1:] + sys.path[:1]

try:
    from yum.Errors import YumBaseError as PmBaseError
except ImportError:
    try:
        from dnf.exceptions import Error as PmBaseError
    except ImportError:
        class PmBaseError(Exception):
            def __init__(self, errmsg):
                self.value = errmsg
            def __getattr__(self, name):
                raise AttributeError(_("class %s has no attribute '%s'") % (self.__class__.__name__, name))
            def __setattr__(self, name, value):
                if name in ['errmsg', 'value']:
                    self.__dict__['value'] = value
                else:
                    self.__dict__[name] = value


class Error(PmBaseError):
    """base class for errors"""
    premsg = ''
    def __init__(self, errmsg):
        errmsg = ustr(errmsg)
        PmBaseError.__init__(self, errmsg)
        self.value = 'rhn-plugin: ' + self.premsg + errmsg
        self.log = up2dateLog.initLog()

    def __repr__(self):
        self.log.log_me(self.value)
        return self.value

    def __getattr__(self, name):
        """ Spacewalk backend still use errmsg, let have errmsg as alias to value """
        if name == 'errmsg':
            return self.value
        else:
            if hasattr(PmBaseError, '__getattr__'):
                # rhel5 has no __getattribute__()
                return PmBaseError.__getattr__(self, name)
            else:
                if name in self.__dict__:
                    return self.__dict__[name]
                else:
                    raise AttributeError(_("class %s has no attribute '%s'") % (self.__class__.__name__, name))

    def __setattr__(self, name, value):
        """ Spacewalk backend still use errmsg, let have errmsg as alias to value """
        if name == 'errmsg':
            self.__dict__['value'] = value
        else:
            if hasattr(PmBaseError, '__setattr__'):
                # rhel5 has no __setattr__()
                PmBaseError.__setattr__(self, name, value)
            else:
                self.__dict__[name] = value

class DebAndSuseRepoError(Error):
   pass

try:
    from yum.Errors import RepoError
except ImportError:
    try:
        from dnf.exceptions import RepoError
    except ImportError:
        RepoError = DebAndSuseRepoError


class RpmError(Error):
    """rpm itself raised an error condition"""
    premsg = _("RPM error.  The message was:\n")

class RhnServerException(Error):
    pass

class PasswordError(RhnServerException):
    """Raise when the server responds with that a password is incorrect"""
    premsg = _("Password error. The message was:\n")

class DependencyError(Error):
    """Raise when a rpm transaction set has a dependency error"""
    premsg = _("RPM dependency error. The message was:\n")
    def __init__(self, msg, deps=None):
        Error.__init__(self, msg)
        # just tag on the whole deps tuple, so we have plenty of info
        # to play with
        self.deps = deps


class CommunicationError(RhnServerException):
    """Indicates a problem doing xml-rpc http communication with the server"""
    premsg = _("Error communicating with server. "\
                 "The message was:\n")

class FileNotFoundError(Error):
    """
    Raise when a package or header that is requested returns
    a 404 error code"""
    premsg =  _("File Not Found: \n")


class DelayError(RhnServerException):
    """
    Raise when the expected response from a xml-rpc call
    exceeds a timeout"""
    premsg =  _("Delay error from server.  The message was:\n")

class RpmRemoveError(Error):
    """
    Raise when we can't remove a package for some reason
    (failed deps, etc)"""
    def __init__(self, args):
        Error.__init__(self, "")
        self.args = args
        for key in self.args.keys():
            self.args[key] = ustr(self.args[key])
            self.value = self.value + "%s failed because of %s\n" % (
                key, self.args[key])
        self.data = self.args
    def __repr__(self):
        return self.value

class NoLogError(Error):
    def __init__(self, msg):
        msg = ustr(msg)
        self.value = self.premsg + msg

    def __repr__(self):
        return self.value

class AbuseError(Error):
    pass

class AuthenticationTicketError(NoLogError, RhnServerException):
    pass

class AuthenticationError(NoLogError):
    pass

class ValidationError(NoLogError, RhnServerException):
    """indicates an error during server input validation"""
    premsg = _("Error validating data at server:\n")

class InvalidRegistrationNumberError(ValidationError):
    pass

class RegistrationDeniedError(RhnServerException):
    def __init__(self):
        RhnServerException.__init__(self, self.changeExplanation())

    def __repr__(self):
        return self.value

    def changeExplanation(self):
        return _("""
CloudLinux Network Classic is not supported.
To register with CloudLinux Subscription Management please run:

    subscription-manager register --auto-attach

Get more information at www.cloudlinux.com
    """)

class InvalidProductRegistrationError(NoLogError):
    """indicates an error during server input validation"""
    premsg = _("The installation number is invalid")

class OemInfoFileError(NoLogError):
    premsg = _("Error parsing the oemInfo file at field:\n")

class NoBaseChannelError(NoLogError, RhnServerException):
    """No valid base channel was found for this system"""
    pass

class UnknownMethodException(NoLogError, RhnServerException):
    pass

class RhnUuidUniquenessError(NoLogError, RhnServerException):
    pass

class ServerCapabilityError(Error):
    def __init__(self, msg, errorlist=None):
        Error.__init__(self, msg)
        self.errorlist = []
        if errorlist:
            self.errorlist=errorlist

    def __repr__(self):
        return self.value

class NoChannelsError(NoLogError):
    pass

class NetworkError(Error):
    """ some generic network error occurred, e.g. connection reset by peer """
    premsg = _("Network error: ")

class SSLCertificateVerifyFailedError(RepoError, Error):
    def __init__(self):
        # Need to override __init__ because the base class requires a message arg
        # and this exception shouldn't.
        up2dateConfig = config.initUp2dateConfig()
        certFile = up2dateConfig['sslCACert']
        f = open(certFile, "r")
        buf = f.read()
        f.close()
        tempCert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, buf)
        if tempCert.has_expired():
            RepoError.__init__(self ,"The certificate %s is expired. Please ensure you have the correct"
                           " certificate and your system time is correct." % certFile)
        else:
            RepoError.__init__(self, "The SSL certificate failed verification.")

    __getattr__ = Error.__getattr__

class SSLCertificateFileNotFound(Error):
    pass


class AuthenticationOrAccountCreationError(ValidationError):
    """Class that can represent different things depending on context:
    While logging in with an existing user it represents a username or password
    being incorrect.
    While creating a new account, it represents the username already being
    taken or the user not being allowed to create an account.
    Optimally these different things would be different exceptions, but there
    are single fault codes the server can return to the client that can mean
    more than one of them so we have no way of knowing which is actually
    intended.

    """
    pass

class NotEntitlingError(Error):
    pass

class InvalidProtocolError(Error):
    pass

class UnableToCreateUser(NoLogError):
     pass

class ActivationKeyUsageLimitError(NoLogError):
    pass

class LoginMinLengthError(NoLogError):
    pass

class PasswordMinLengthError(NoLogError):
    pass

class PasswordMaxLengthError(NoLogError):
    pass


class InsuffMgmntEntsError(RhnServerException):
    def __init__(self, msg ):
        RhnServerException.__init__(self, self.changeExplanation(msg))

    def __repr__(self):
        return self.value

    def changeExplanation(self, msg):
        newExpln = _("""
    Your organization does not have enough Management entitlements to register this
    system to CloudLinux Network. Please notify your organization administrator of this error.
    You should be able to register this system after your organization frees existing
    or purchases additional entitlements. Additional entitlements may be purchased by your
    organization administrator by logging into CloudLinux Network and visiting

    A common cause of this error code is due to having mistakenly setup an
    Activation Key which is set as the universal default.  If an activation key is set
    on the account as a universal default, you can disable this key and retry to avoid
    requiring a Management entitlement.""")
        term = "Explanation:"
        loc = msg.rindex(term) + len(term)
        return msg[:loc] + newExpln

class NoSystemIdError(NoLogError):
    pass

class InvalidRedirectionError(NoLogError):
    """ Raise when redirect requests could'nt return a package"""
    pass
haltree.py000064400000011042150516774050006552 0ustar00
# HalTree Purpose:
#
# HalTree is a way to organize the mess of data you get from hal.  In general,
# if you want to get all the information about every device in the system, you
# end up with a list of dicts, where each dict contains the property name/values
# for a device.  This list isn't very useful as the hal data is actually
# organized into a tree.  For example, you have the computer as the head, then
# there may be a scsi card plugged in.  That in turn will have scsi channels
# and luns, which scsi devices may be connected to.  So this module will help
# you reorganize your hal data back to the way they were intended.
#
# HalTree Usage:
#
# The tree gets built one device at a time.  Once you've created a HalTree
# object, devices get added to the tree with HalTree.add(hw_dev_dict).  The
# devices can be added in any particular order, and the tree gets properly
# structured as the devices get added.  But the tree structure isn't likely
# to be ready until all the devices have been added.  Those devices without a
# parent get stuck in the no_parent_yet list.
#
# When a device gets added, it is no longer a plain dict.  It is stored in a
# HalDevice.  The original dict can be found in HalDevice.properties.

try: # python2
    from types import StringType, IntType
except ImportError: # python3
    StringType = bytes
    IntType = int


class HalDevice:
    "An object containing its udi, properties and children"
    def __init__ (self, properties):
        self.udi = properties['info.udi']

        self.properties = properties
        self.children = []
        self.classification = None

        if 'info.parent' in properties:
            self.parent_udi = properties['info.parent']
        else:
            self.parent_udi = None

        self.parent = None

    def print_properties(self):
        print(self.udi, ":")
        for property, value in self.properties.items():
            print("    ", property," ==> ",  value)




class HalTree:
    def __init__ (self):
        self.head = None
        self.no_parent_yet = []


    def add(self, hal_device):
        if hal_device.parent_udi:
            parent = self.__find_node(hal_device.parent_udi)
            if parent:
                parent.children.append(hal_device)
                hal_device.parent = parent
            else:  #parent isn't in the main tree yet, stick it in waiting
                self.no_parent_yet.append(hal_device)
        else: #if it doesn't have a parent, it must be the head 'computer'
            self.head = hal_device

        #check to see if there are any children waiting for this dev
        self.__get_lost_children(hal_device)


    def __get_lost_children(self, hal_device):
        found_list = []
        indexes = []
        no_parent_yet_copy = self.no_parent_yet[:]
        for dev in no_parent_yet_copy:
            if dev.parent_udi == hal_device.udi:
                dev.parent = hal_device
                hal_device.children.append(dev)
                self.no_parent_yet.remove(dev)

    def __find_node(self, udi):
        """
        This takes a node in the HalDevice tree and returns the HalDevice with
        the given udi.
        """
        if self.head:
            node = HalTree.__find_node_worker(self.head, udi)
            if node:
                return node

        for node in self.no_parent_yet:
            found_node = HalTree.__find_node_worker(node, udi)
            if found_node:
                return found_node
        return None

    @staticmethod
    def __find_node_worker(node, udi):
        if node.udi == udi:
            return node
        for device in node.children:
            res = HalTree.__find_node_worker(device, udi)
            if res:
                return res
        return None

    def print_tree(self):
        self.__print_dev_tree(self.head, "")

    def __print_dev_tree(self, node, indent):
        print(indent, node.udi)
        print(indent, "CLASS:", node.classification)
        for name, property in node.properties.items():
            if (type(property) == StringType):
                if property.isdigit():
                    print(indent + "    ", "%-20s ==> %s" % (name, hex(int(property))))
                else:
                    print(indent + "    ", "%-20s ==> %s" % (name, property))
            elif (type(property) == IntType):
                print(indent + "    ", "%-20s ==> %s" % (name, hex(int(property))))
            else:
                print(indent + "    ", "%-20s ==> %s" % (name, property))
        print
        for child in node.children:
            self.__print_dev_tree(child, indent + "    ")
config.py000064400000034723150516774050006406 0ustar00# This file is a portion of the Red Hat Update Agent
# Copyright (c) 1999--2020 Red Hat, Inc.  Distributed under GPL
#
# Authors:
#       Cristian Gafton <gafton@redhat.com>
#       Adrian Likins   <alikins@redhat.com>
#
"""
This module includes the Config and Up2date Config classes use by the
up2date agent to hold config info.
"""

import os
import sys
import locale
import requests
from rhn.connections import idn_ascii_to_puny, idn_puny_to_unicode
from rhn.i18n import ustr, sstr

try:  # python2
    from urlparse import urlsplit, urlunsplit
except ImportError:  # python3
    from urllib.parse import urlsplit, urlunsplit

import gettext

t = gettext.translation("rhn-client-tools", fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, "ugettext"):
    t.ugettext = t.gettext
_ = t.ugettext

# XXX: This could be moved in a more "static" location if it is too
# much of an eye sore
Defaults = {
    "enableProxy": ("Use a HTTP Proxy", 0),
    "serverURL": ("Remote server URL", "https://xmlrpc.cln.cloudlinux.com/XMLRPC/"),
    "serverURLipv6": ("Remote server URL for access over IPv6", "https://ipv6.xmlrpc.cln.cloudlinux.com/XMLRPC/"),
    "mirrorURL": ("Mirror list URL", "https://repo.cloudlinux.com/cloudlinux/mirrorlists/cln-mirrors"),
    "debug": ("Whether or not debugging is enabled", 0),
    "systemIdPath": ("Location of system id", "/etc/sysconfig/rhn/systemid"),
    "versionOverride": ("Override the automatically determined system version", ""),
    "httpProxy": ("HTTP proxy in host:port format, e.g. squid.example.com:3128", ""),
    "proxyUser": ("The username for an authenticated proxy", ""),
    "proxyPassword": ("The password to use for an authenticated proxy", ""),
    "enableProxyAuth": ("To use an authenticated proxy or not", 0),
    "networkRetries": ("Number of attempts to make at network connections before giving up", 1),
    "sslCACert": ("The CA cert used to verify the ssl server", "/usr/share/rhn/CLN-ORG-TRUSTED-SSL-CERT"),
    "noReboot": ("Disable the reboot action", 0),
    "disallowConfChanges": (
        "Config options that can not be overwritten by a config update action",
        ["sslCACert", "serverURL", "disallowConfChanges", "noReboot"],
    ),
}

FileOptions = [
    "systemIdPath",
    "sslCACert",
    "tmpDir",
]


# a peristent configuration storage class
class ConfigFile:
    "class for handling persistent config options for the client"

    def __init__(self, filename=None):
        self.dict = {}
        self.fileName = filename
        if self.fileName:
            self.load()

    def load(self, filename=None):
        if filename:
            self.fileName = filename
        if self.fileName is None:
            return
        if not os.access(self.fileName, os.R_OK):
            #            print("warning: can't access %s" % self.fileName)
            return

        f = open(self.fileName, "r")

        multiline = ""
        for line in f.readlines():
            # strip comments
            if line.find("#") == 0:
                continue
            line = multiline + line.strip()
            if not line:
                continue

            # if line ends in '\', append the next line before parsing
            if line[-1] == "\\":
                multiline = line[:-1].strip()
                continue
            else:
                multiline = ""

            split = line.split("=", 1)
            if len(split) != 2:
                # not in 'a = b' format. we should log this
                # or maybe error.
                continue
            key = split[0].strip()
            value = ustr(split[1].strip())

            # decode a comment line
            comment = None
            pos = key.find("[comment]")
            if pos != -1:
                key = key[:pos]
                comment = value
                value = None

            # figure out if we need to parse the value further
            if value:
                # possibly split value into a list
                values = value.split(";")
                if key in ["proxyUser", "proxyPassword"]:
                    value = sstr(value.encode(locale.getpreferredencoding()))
                elif len(values) == 1:
                    try:
                        value = int(value)
                    except ValueError:
                        pass
                elif values[0] == "":
                    value = []
                else:
                    # there could be whitespace between the values on
                    # one line, let's strip it out
                    value = [val.strip() for val in values if val.strip()]

            # now insert the (comment, value) in the dictionary
            newval = (comment, value)
            if key in self.dict:  # do we need to update
                newval = self.dict[key]
                if comment is not None:  # override comment
                    newval = (comment, newval[1])
                if value is not None:  # override value
                    newval = (newval[0], value)
            self.dict[key] = newval
        f.close()

    def save(self):
        if self.fileName is None:
            return

        # this really shouldn't happen, since it means that the
        # /etc/sysconfig/rhn directory doesn't exist, which is way broken

        # and note the attempted fix breaks useage of this by the applet
        # since it reuses this code to create its config file, and therefore
        # tries to makedirs() the users home dir again (with a specific perms)
        # and fails (see #130391)
        if not os.access(self.fileName, os.R_OK):
            if not os.access(os.path.dirname(self.fileName), os.R_OK):
                print(_("%s was not found" % os.path.dirname(self.fileName)))
                return

        f = open(self.fileName + ".new", "w")
        os.chmod(self.fileName + ".new", int("0644", 8))

        f.write("# Automatically generated Red Hat Update Agent config file, do not edit.\n")
        f.write("# Format: 1.0\n")
        f.write("")
        for key in self.dict.keys():
            (comment, value) = self.dict[key]
            f.write(sstr("%s[comment]=%s\n" % (key, comment)))
            if type(value) != type([]):
                value = [value]
            if key in FileOptions:
                value = map(os.path.abspath, value)
            f.write(sstr("%s=%s\n" % (key, ";".join(map(str, value)))))
            f.write("\n")
        f.close()
        os.rename(self.fileName + ".new", self.fileName)

    # dictionary interface
    def __contains__(self, name):
        return name in self.dict

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

    def keys(self):
        return self.dict.keys()

    def values(self):
        return [a[1] for a in self.dict.values()]

    def update(self, dict):
        self.dict.update(dict)

    # we return None when we reference an invalid key instead of
    # raising an exception
    def __getitem__(self, name):
        if name in self.dict:
            return self.dict[name][1]
        return None

    def __setitem__(self, name, value):
        if name in self.dict:
            val = self.dict[name]
        else:
            val = (None, None)
        self.dict[name] = (val[0], value)

    # we might need to expose the comments...
    def info(self, name):
        if name in self.dict:
            return self.dict[name][0]
        return ""


# a superclass for the ConfigFile that also handles runtime-only
# config values
class Config:
    def __init__(self, filename=None):
        self.stored = ConfigFile()
        self.stored.update(Defaults)
        if filename:
            self.stored.load(filename)
        self.runtime = {}

    # classic dictionary interface: we prefer values from the runtime
    # dictionary over the ones from the stored config
    def __contains__(self, name):
        if name in self.runtime:
            return True
        if name in self.stored:
            return True
        return False

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

    def keys(self):
        ret = list(self.runtime.keys())
        for k in self.stored.keys():
            if k not in ret:
                ret.append(k)
        return ret

    def values(self):
        ret = []
        for k in self.keys():
            ret.append(self.__getitem__(k))
        return ret

    def items(self):
        ret = []
        for k in self.keys():
            ret.append((k, self.__getitem__(k)))
        return ret

    def __len__(self):
        return len(self.keys())

    def __setitem__(self, name, value):
        self.runtime[name] = value

    # we return None when nothing is found instead of raising and exception
    def __getitem__(self, name):
        if name in self.runtime:
            return self.runtime[name]
        if name in self.stored:
            return self.stored[name]
        return None

    # These function expose access to the peristent storage for
    # updates and saves
    def info(self, name):  # retrieve comments
        return self.stored.info(name)

    def save(self):
        self.stored.save()

    def load(self, filename):
        self.stored.load(filename)
        # make sure the runtime cache is not polluted
        for k in self.stored.keys():
            if k not in self.runtime:
                continue
            # allow this one to pass through
            del self.runtime[k]

    # save straight in the persistent storage
    def set(self, name, value):
        self.stored[name] = value
        # clean up the runtime cache
        if name in self.runtime:
            del self.runtime[name]


def getProxySetting():
    """returns proxy string in format hostname:port
    hostname is converted to Punycode (RFC3492) if needed
    """
    cfg = initUp2dateConfig()
    proxy = None
    proxyHost = cfg["httpProxy"]

    if proxyHost:
        if proxyHost[:7] == "http://":
            proxyHost = proxyHost[7:]
        parts = proxyHost.split(":")
        parts[0] = str(idn_ascii_to_puny(parts[0]))
        proxy = ":".join(parts)

    return proxy


def convert_url_to_puny(url):
    """returns url where hostname is converted to Punycode (RFC3492)"""
    s = urlsplit(url)
    return sstr(urlunsplit((s[0], ustr(idn_ascii_to_puny(s[1])), s[2], s[3], s[4])))


def convert_url_from_puny(url):
    """returns url where hostname is converted from Punycode (RFC3492). Returns unicode string."""
    s = urlsplit(url)
    return ustr(urlunsplit((s[0], idn_puny_to_unicode(s[1]), s[2], s[3], s[4])))


def getServerlURLFromMirror():
    url = cfg["mirrorURL"]
    if url is None:
        url = "https://repo.cloudlinux.com/cloudlinux/mirrorlists/cln-mirrors"
    if url.startswith("file://"):
        with open(url.replace("file://", ""), "r") as mirrorlist:
            mirrors = map(str.strip, mirrorlist.readlines())
            return [convert_url_to_puny(mirror) for mirror in mirrors if mirror]
    request = requests.get(url)
    return [convert_url_to_puny(mirror) for mirror in request.text.split("\n") if mirror]


def processServerURL(serverUrl):
    """
    Internal function to process server URL to Punycode format.

    Processes both single URLs and lists of URLs.

    :param serverUrl: URL or list of URLs to process.
    :return: List of processed URLs in Punycode format.
    """
    if isinstance(serverUrl, list):
        return [convert_url_to_puny(i) for i in serverUrl]
    else:
        return [convert_url_to_puny(serverUrl)]


def getServerURLPair(registration=False):
    """
    Return a pair of server URLs (primary and fallback) based on the preferred interface.

    :param registration: If True, it indicates that the URLs are being fetched for registration purposes.
    If that is the case, the function will always use IPv4 URLs with IPv6 as fallback,
    regardless of the preferred_interface setting.
    Assumed false by default, expected to be specified explicitly when needed.

    :return: Pair of server URL configs, first is the primary, second is the fallback.
    """
    cfg = initUp2dateConfig()

    ipv4_url = processServerURL(cfg["serverURL"])
    ipv6_url = processServerURL(cfg["serverURLipv6"])

    # Note that we don't consider the case where there's no IPv6 URL configured,
    # we expect that the configuration will always have both URLs set.
    ipv4_primary_pair = (ipv4_url, ipv6_url)
    ipv6_primary_pair = (ipv6_url, ipv4_url)

    # If registration is True, we always use IPv4 URLs with IPv6 as fallback
    if registration:
        return ipv4_primary_pair

    # Import here to avoid circular import
    from up2date_client import up2dateAuth

    # Check if preferred_interface is set to IPv6
    preferred_interface = up2dateAuth.getPreferredInterface()

    # If IPv6 is preferred, use it
    if preferred_interface == "IPv6" and ipv6_url:
        return ipv6_primary_pair

    # Otherwise use the normal URL
    return ipv4_primary_pair


def getServerURL(registration=False):
    """
    Return the primary server URL from config based on preferred_interface.

    If preferred_interface=IPv6 in system_id, returns serverURLipv6 if available.
    Otherwise returns normal serverURL.
    Note: the config may have one value or a list of values, but this function always returns a list.

    :return: List of server URLs with hostnames converted to Punycode.
    """
    return getServerURLPair(registration=registration)[0]  # Return the primary URL


def getFallbackServerURL(registration=False):
    """
    Determine the fallback server URL from system_id.

    The fallback server URL is the one that is *not* set as preferred_interface.
    If preferred_interface is IPv6, it returns serverURL (i.e. IPv4 host), otherwise serverURLipv6.
    """
    return getServerURLPair(registration=registration)[1]  # Return the fallback URL


def setServerURL(serverURL):
    """Set serverURL in config"""
    cfg = initUp2dateConfig()
    cfg.set("serverURL", serverURL)


def setServerURLipv6(serverURL):
    """Set serverURLipv6 in config"""
    cfg = initUp2dateConfig()
    cfg.set("serverURLipv6", serverURL)


def setSSLCACert(sslCACert):
    """Set sslCACert in config"""
    cfg = initUp2dateConfig()
    cfg.set("sslCACert", sslCACert)


def initUp2dateConfig(cfg_file="/etc/sysconfig/rhn/up2date"):
    """This function is the right way to get at the up2date config."""
    global cfg
    try:
        cfg
    except NameError:
        cfg = None

    if cfg == None:
        cfg = Config(cfg_file)
        cfg["isatty"] = False
        if sys.stdout.isatty():
            cfg["isatty"] = True

    return cfg
up2dateUtils.py000064400000012074150516774050007521 0ustar00# Client code for Update Agent
# Copyright (c) 1999--2018 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Preston Brown <pbrown@redhat.com>
#         Adrian Likins <alikins@redhat.com>
#
"""utility functions for up2date"""

import contextlib
import os
import sys
import re
import gettext
from up2date_client import up2dateErrors
from up2date_client import config
from up2date_client.pkgplatform import getPlatform
from rhn.i18n import sstr

t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

if getPlatform() == 'deb':
    import lsb_release
    def _getOSVersionAndRelease():
        dist_info = lsb_release.get_distro_information()
        os_name = dist_info['ID']
        os_version = 'n/a'
        if 'CODENAME' in dist_info:
            os_version = dist_info['CODENAME']
        os_release = dist_info['RELEASE']
        return os_name, os_version, os_release

else:
    from up2date_client import transaction
    def _getOSVersionAndRelease():
        ts = transaction.initReadOnlyTransaction()
        for h in ts.dbMatch('Providename', "oraclelinux-release"):
            SYSRELVER = 'system-release(releasever)'
            version = sstr(h['version'])
            release = sstr(h['release'])
            if SYSRELVER in (sstr(provide) for provide in h['providename']):
                provides = dict((sstr(n), sstr(v))
                                for n,v in zip(h['providename'], h['provideversion']))
                release = '%s-%s' % (version, release)
                version = provides[SYSRELVER]
            osVersionRelease = (sstr(h['name']), version, release)
            return osVersionRelease
        else:
            for h in ts.dbMatch('Providename', "redhat-release"):
                SYSRELVER = 'system-release(releasever)'
                version = sstr(h['version'])
                release = sstr(h['release'])
                if SYSRELVER in (sstr(provide) for provide in h['providename']):
                    provides = dict((sstr(n), sstr(v))
                                    for n,v in zip(h['providename'], h['provideversion']))
                    release = '%s-%s' % (version, release)
                    version = provides[SYSRELVER]
                osVersionRelease = (sstr(h['name']), version, release)
                return osVersionRelease
            else:
                for h in ts.dbMatch('Providename', "distribution-release"):
                    osVersionRelease = (sstr(h['name']), sstr(h['version']), sstr(h['release']))
                    # zypper requires a exclusive lock on the rpmdb. So we need
                    # to close it here.
                    ts.ts.closeDB()
                    return osVersionRelease
                else:
                    raise up2dateErrors.RpmError(
                        "Could not determine what version of CloudLinux you "\
                        "are running.\nIf you get this error, try running \n\n"\
                        "\t\trpm --rebuilddb\n\n")

def getVersion():
    '''
    Returns the version of redhat-release rpm
    '''
    cfg = config.initUp2dateConfig()
    if cfg["versionOverride"]:
        return str(cfg["versionOverride"])
    os_release, version, release = _getOSVersionAndRelease()
    return version

def getOSRelease():
    '''
    Returns the name of the redhat-release rpm
    '''
    os_release, version, release = _getOSVersionAndRelease()
    return os_release

def getRelease():
    '''
    Returns the release of the redhat-release rpm
    '''
    os_release, version, release = _getOSVersionAndRelease()
    return release

def getArch():
    if os.access("/etc/rpm/platform", os.R_OK):
        fd = open("/etc/rpm/platform", "r")
        platform = fd.read().strip()

        #bz 216225
        #handle some replacements..
        replace = {"ia32e-redhat-linux": "x86_64-redhat-linux"}
        if platform in replace:
            platform = replace[platform]
        return platform
    arch = os.uname()[4]
    if getPlatform() == 'deb':
        # On debian we only support i386
        if arch in ['i486', 'i586', 'i686']:
            arch = 'i386'
        if arch == 'x86_64':
            arch = 'amd64'
        arch += '-debian-linux'
    return arch

def version():
    # substituted to the real version by the Makefile at installation time.
    return "2.12.5-1.module_el8.10.0+6935+f9aadf00.cloudlinux"


@contextlib.contextmanager
def suppress_errors(error_patterns):
    '''
    Context manager to suppress errors
    matching the specified patterns
    '''
    read_end, write_end = os.pipe()
    old_stdout = os.dup(1)
    old_stderr = os.dup(2)
    os.dup2(write_end, 1)
    os.dup2(write_end, 2)

    try:
        yield
    finally:
        # Restore stdout and stderr
        os.dup2(old_stdout, 1)
        os.dup2(old_stderr, 2)

    os.close(write_end)
    with os.fdopen(read_end) as f:
        combined_pattern = re.compile('|'.join(error_patterns))
        for line in f:
            if not combined_pattern.search(line):
                print(line, file=sys.stderr)
clpwd.py000064400000007073150516774050006250 0ustar00import pwd
import os

class ClPwd:
    class NoSuchUserException(Exception):
        def __init__(self, user):
            Exception.__init__(self, "No such user (%s)" % (user,))

    def __init__(self, min_uid = None):
        self._user_key_map = {}
        self._uid_key_map = {}
        self._user_full_map = {}
        self._uid_full_map = {}
        if min_uid is None:
            self._min_uid = self.get_sys_min_uid(500)
        else:
            self._min_uid = min_uid

    def get_user_dict(self):
        self._load_passwd_database()
        return self._user_key_map

    def get_uid_dict(self):
        self._load_passwd_database()
        return self._uid_key_map

    def get_user_full_dict(self):
        self._load_passwd_database()
        return self._user_full_map

    def get_uid_full_dict(self):
        self._load_passwd_database()
        return self._uid_full_map

    def get_pw_by_name(self, user):
        """
        Return pw_entry for user
        """
        try:
            return self.get_user_full_dict()[user]
        except KeyError:
            raise ClPwd.NoSuchUserException(user)

    def get_pw_by_uid(self, uid):
        """
        Return list of passwd entries for uid
        """
        try:
            return self.get_uid_full_dict()[uid]
        except KeyError:
            raise ClPwd.NoSuchUserException(uid)

    def get_uid(self, user):
        """
        Returns uid for user
        """
        try:
            return self.get_user_full_dict()[user].pw_uid
        except KeyError:
            raise ClPwd.NoSuchUserException(user)

    def get_homedir(self, user):
        """
        Returns homedir for a user
        @param user: string
        @return: string
        """
        try:
            return self.get_user_full_dict()[user].pw_dir
        except KeyError:
            raise ClPwd.NoSuchUserException(user)

    def _load_passwd_database(self):
        """
        Loads the passwd database and fills user_to_uid and user_to_homedir maps
        """
        if not self._uid_full_map:
            for entry in pwd.getpwall():
                self._user_full_map[entry.pw_name] = entry
                if entry.pw_uid not in self._uid_full_map:
                    self._uid_full_map[entry.pw_uid] = []
                self._uid_full_map[entry.pw_uid].append(entry)
                if entry.pw_uid >= self._min_uid:
                    self._user_key_map[entry.pw_name] = entry
                    if entry.pw_uid not in self._uid_key_map:
                        self._uid_key_map[entry.pw_uid] = []
                    self._uid_key_map[entry.pw_uid].append(entry)

    def get_names(self, uid):
        """
        Return names of users with uid specified
        @param uid: int
        @return: list of strings
        """
        try:
            entries = self.get_uid_full_dict()[uid]
        except KeyError:
            raise ClPwd.NoSuchUserException(uid)

        return [entry.pw_name for entry in entries]


    def get_sys_min_uid(self, def_min_uid = 500):
        """
        Return system defined MIN_UID from /etc/login.def or def_min_uid
        @param def_min_uid: int
        @return: MIN_UID: int
        """

        LOGIN_DEF_FILE = '/etc/login.defs'
        if (os.path.exists(LOGIN_DEF_FILE)):
            with open(LOGIN_DEF_FILE, 'r') as lines:
                for line in lines:
                    if line.startswith('UID_MIN'):
                        try:
                            return int(line.split('UID_MIN')[1].strip())
                        except ValueError:
                            pass

        return def_min_uid
up2dateLog.py000064400000004074150516774050007143 0ustar00#

import time
import traceback
from rhn.i18n import ustr, sstr
from up2date_client import config

class Log:
    """
    attempt to log all interesting stuff, namely, anything that hits
    the network any error messages, package installs, etc
    """ # " emacs sucks
    def __init__(self):
        self.app = "up2date"
        self.cfg = config.initUp2dateConfig()
        self.log_info = ''

    def set_app_name(self, name):
        self.app = str(name)

    def log_debug(self, *args):
        if self.cfg["debug"] > 1:
            self.log_me("D: ", *args)

    def log_me(self, *args):
        """General logging function.
        Eg: log_me("I am a banana.")

        """
        self.log_info = "[%s] %s" % (time.ctime(time.time()), self.app)
        s = u""
        for i in args:
            # we really need unicode(str(i)) here, because i can be anything
            # from string or int to list, dict or even class
            i = ustr(str(i))
            s += i
        if self.cfg["debug"] > 1:
            print(s)
        self.write_log(s)

    def trace_me(self):
        self.log_info = "[%s] %s" % (time.ctime(time.time()), self.app)
        x = traceback.extract_stack()
        msg = ''.join(traceback.format_list(x))
        self.write_log(msg)

    def log_exception(self, logtype, value, tb):
        self.log_info = "[%s] %s" % (time.ctime(time.time()), self.app)
        output = ["\n"] # Accumulate the strings in a list
        output.append("Traceback (most recent call last):\n")
        output = output + traceback.format_list(traceback.extract_tb(tb))
        output.append("%s: %s\n" % (logtype, value))
        self.write_log("".join(output))

    def write_log(self, s):

        log_name = self.cfg["logFile"] or "/var/log/up2date"
        log_file = open(log_name, 'a')
        msg = u"%s %s\n" % (ustr(self.log_info), ustr(s))
        log_file.write(sstr(msg))
        log_file.flush()
        log_file.close()

def initLog():
    global log
    try:
        log = log
    except NameError:
        log = None

    if log == None:
        log = Log()

    return log
getMethod.py000064400000010316150516774050007051 0ustar00# Retrieve action method name given queued action information.
#
# Client code for Update Agent
# Copyright (c) 1999--2016 Red Hat, Inc.  Distributed under GPLv2.
#
# An allowable xmlrpc method is retrieved given a base location, a
# hierarchical route to the class/module, and method name.
#

import os
import string
import sys

from rhn.tb import raise_with_tb

try: # python2
    from types import ClassType
except ImportError: # python3
    ClassType = type

class GetMethodException(Exception):
    """Exception class"""
    pass


def sanity(methodNameComps):
    #"""
    # Verifies if all the components have proper names
    #"""
    # Allowed characters in each string
    alpha = string.ascii_lowercase + string.ascii_uppercase
    allowedChars = alpha + string.digits + '_'
    for comp in methodNameComps:
        if not len(comp):
            raise GetMethodException("Empty method component")
        for c in comp:
            if c not in allowedChars:
                raise GetMethodException(
                    "Invalid character '%s' in the method name" % c)
        # Can only begin with a letter
        if comp[0] not in alpha:
            raise GetMethodException(
                "Method names should start with an alphabetic character")


def getMethod(methodName, baseClass):
    #"""
    #Retreive method given methodName, path to base of tree, and class/module
    #route/label.
    #"""
    # First split the method name
    methodNameComps = baseClass.split('.') + methodName.split('.')
    # Sanity checks
    sanity(methodNameComps)
    # Look for the module, start with the most specific
    for index in range(len(methodNameComps), 0, -1):
        modulename = '.'.join(methodNameComps[:index])
        try:
            actions = __import__(modulename)
        except ImportError:
            # does not exist, try next one
            continue
        except Exception:
            raise_with_tb(GetMethodException("Could not import module %s" % modulename))
        # found one, skip the rest
        break
    else:
        # no module found. die
        raise GetMethodException("Action %s could not be imported" % methodName)

    # The position of the file
    fIndex = index

    className = actions
    # Iterate through the list of components and try to load that specific
    # module/method
    for index in range(1, len(methodNameComps)):
        comp = methodNameComps[index]
        if index < fIndex:
            # This is a directory or a file we have to load
            if not hasattr(className, comp):
                # Hmmm... Not there
                raise GetMethodException("Class %s has no attribute %s" % (
                    '.'.join(methodNameComps[:index]), comp))
            className = getattr(className, comp)
            #print(type(className))
            continue
        # A file or method
        # We look for the special __rhnexport__ array
        if not hasattr(className, '__rhnexport__'):
            raise GetMethodException("Class %s is not RHN-compliant" % \
                '.'.join(methodNameComps[:index]))
        export = getattr(className, '__rhnexport__')
        if comp not in export:
            raise GetMethodException("Class %s does not export '%s'" % (
                '.'.join(methodNameComps[:index]), comp))
        className = getattr(className, comp)
        if type(className) is ClassType:
            # Try to instantiate it
            className = className()
        #print(type(className))

    return className


#-----------------------------------------------------------------------------
if __name__ == '__main__':
    # Two valid ones and a bogus one
    methods = [
        'a.b.c.d.e.f',
        'a.b.c.d.e.foo.h',
        'a.b.c.d.e.g.h',
        'a.b.d.d.e.g.h',
        'a.b.d.d._e.g.h',
        'a.b.d.d.e_.g.h',
        'a.b.d.d.e-.g.h',
        'a.b.d.d..g.h',
    ]

    for m in methods:
        print("----Running method %s: " % m)
        try:
            method = getMethod(m, 'Actions')
        except GetMethodException:
            e = sys.exc_info()[1]
            print("Error getting the method %s: %s" % (m,
                ''.join(map(str, e.args))))
        else:
            method()
#-----------------------------------------------------------------------------

pkgplatform.py000064400000000465150516774050007463 0ustar00# Client code for Update Agent
# Copyright (c) 2011--2012 Red Hat, Inc.  Distributed under GPLv2.
#
# Author: Simon Lukasik
#

# substituted to the prefered platfrom by Makefile
_platform='rpm'
def getPlatform():
    if _platform != '@PLAT' + 'FORM@':
        return _platform
    else:
        return 'rpm'

hardware_gudev.py000064400000031640150516774050010123 0ustar00# Copyright (c) 2010--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.
#

try:
    import gi
    gi.require_version('GUdev', '1.0')
    from gi.repository import GUdev
    gi_gudev = True
except (ImportError, ValueError):
    import gudev
    import glib
    gi_gudev = False

import os
import re

from hwdata import PCI, USB

def get_devices():
    """ Returns list of dictionaries with keys for every device in system
        (values are provide as example):
        'bus' : 'pci'
        'driver' : 'pcieport-driver'
        'pciType' : '1'
        'detached' : '0'
        'class' : 'OTHER'
        'desc' : 'Intel Corporation|5000 Series Chipset PCI Express x4 Port 2'
    """
    # listen to uevents on all subsystems
    if gi_gudev:
        client = GUdev.Client()
    else:
        client = gudev.Client([""])
    # FIX ME - change to None to list all devices once it is fixed in gudev
    devices = client.query_by_subsystem("pci") + client.query_by_subsystem("usb") + client.query_by_subsystem("block") + client.query_by_subsystem("ccw") + client.query_by_subsystem("scsi")
    result = []
    for device in devices:
        subsystem = device.get_subsystem()
        result_item = {
            'bus':      subsystem,
            'driver':   device.get_driver(),
            'pciType':  _clasify_pci_type(subsystem),
            'detached': '0', # always zero?
            'class':    _clasify_class(device),
            'desc':     _get_device_desc(device),
        }
        if result_item['class'] is None:
            result_item['class'] = 'OTHER'
        if result_item['driver'] is None:
            result_item['driver'] = 'unknown'
        if subsystem == 'block':
            if device.has_property('ID_BUS'):
                result_item['bus'] = device.get_property('ID_BUS')
            result_item['device'] = device.get_name()
            if device.get_devtype() == 'partition':
                # do not report partitions, just whole disks
                continue
            if device.get_property('DM_NAME'):
                # LVM device
                continue
            if device.get_property('MAJOR') == '1':
                # ram device
                continue
            if device.get_property('MAJOR') == '7':
                # character devices for virtual console terminals
                continue
            # This is interpreted as Physical. But what to do with it?
            # result_item['prop1'] = ''
            # This is interpreted as Logical. But what to do with it?
            # result_item['prop2'] = ''
        elif subsystem == 'pci':
            pci_class = device.get_property('PCI_ID')
            if pci_class:
                (result_item['prop1'], result_item['prop2']) = pci_class.split(':')
            pci_subsys = device.get_property('PCI_SUBSYS_ID')
            if pci_subsys:
                (result_item['prop3'], result_item['prop4']) = pci_subsys.split(':')
        elif subsystem == 'usb':
           if device.has_property('ID_VENDOR_ID'):
                result_item['prop1'] = device.get_property('ID_VENDOR_ID')
           if device.has_property('ID_MODEL_ID'):
                result_item['prop2'] = device.get_property('ID_MODEL_ID')
        if device.has_property('ID_BUS') and device.get_property('ID_BUS') == 'scsi':
            if device.has_property('ID_PATH') or device.has_property('DEVPATH'):
                if device.has_property('ID_PATH'):
                    path = device.get_property('ID_PATH')
                    m = re.search('.*scsi-(\d+):(\d+):(\d+):(\d+)', path)
                else: # device.has_property('DEVPATH')
                    path = device.get_property('DEVPATH')
                    m = re.search('.*/(\d+):(\d+):(\d+):(\d+)/block/', path)
                if m: # do not fail, if regexp did not match
                    result_item['prop1'] = m.group(1) # DEV_HOST
                    result_item['prop2'] = m.group(2) # DEV_ID
                    result_item['prop3'] = m.group(3) # DEV_CHANNEL
                    result_item['prop4'] = m.group(4) # DEV_LUN
        result.append(result_item)
    return result

def get_computer_info():
    """ Return dictionaries with keys (values are provided as example):
        'system.formfactor': 'unknown'
        'system.kernel.version': '2.6.18-128.1.6.el5xen'
            'system.kernel.machine': 'i686'
        'system.kernel.name': 'Linux'
    """
    uname = os.uname()
    result = {
        'system.kernel.name': uname[0],
        'system.kernel.version': uname[2],
        'system.kernel.machine': uname[4],
    }
    return result

#PCI DEVICE DEFINES
# These are taken from pci_ids.h in the linux kernel source and used to
# properly identify the hardware
PCI_BASE_CLASS_STORAGE =        '1'
PCI_CLASS_STORAGE_SCSI =        '00'
PCI_CLASS_STORAGE_IDE =         '01'
PCI_CLASS_STORAGE_FLOPPY =      '02'
PCI_CLASS_STORAGE_IPI =         '03'
PCI_CLASS_STORAGE_RAID =        '04'
PCI_CLASS_STORAGE_OTHER =       '80'

PCI_BASE_CLASS_NETWORK =        '2'
PCI_CLASS_NETWORK_ETHERNET =    '00'
PCI_CLASS_NETWORK_TOKEN_RING =  '01'
PCI_CLASS_NETWORK_FDDI =        '02'
PCI_CLASS_NETWORK_ATM =         '03'
PCI_CLASS_NETWORK_OTHER =       '80'

PCI_BASE_CLASS_DISPLAY =        '3'
PCI_CLASS_DISPLAY_VGA =         '00'
PCI_CLASS_DISPLAY_XGA =         '01'
PCI_CLASS_DISPLAY_3D =          '02'
PCI_CLASS_DISPLAY_OTHER =       '80'

PCI_BASE_CLASS_MULTIMEDIA =     '4'
PCI_CLASS_MULTIMEDIA_VIDEO =    '00'
PCI_CLASS_MULTIMEDIA_AUDIO =    '01'
PCI_CLASS_MULTIMEDIA_PHONE =    '02'
PCI_CLASS_MULTIMEDIA_OTHER =    '80'

PCI_BASE_CLASS_BRIDGE =         '6'
PCI_CLASS_BRIDGE_HOST =         '00'
PCI_CLASS_BRIDGE_ISA =          '01'
PCI_CLASS_BRIDGE_EISA =         '02'
PCI_CLASS_BRIDGE_MC =           '03'
PCI_CLASS_BRIDGE_PCI =          '04'
PCI_CLASS_BRIDGE_PCMCIA =       '05'
PCI_CLASS_BRIDGE_NUBUS =        '06'
PCI_CLASS_BRIDGE_CARDBUS =      '07'
PCI_CLASS_BRIDGE_RACEWAY =      '08'
PCI_CLASS_BRIDGE_OTHER =        '80'

PCI_BASE_CLASS_COMMUNICATION =  '7'
PCI_CLASS_COMMUNICATION_SERIAL = '00'
PCI_CLASS_COMMUNICATION_PARALLEL = '01'
PCI_CLASS_COMMUNICATION_MULTISERIAL = '02'
PCI_CLASS_COMMUNICATION_MODEM = '03'
PCI_CLASS_COMMUNICATION_OTHER = '80'

PCI_BASE_CLASS_INPUT =          '9'
PCI_CLASS_INPUT_KEYBOARD =      '00'
PCI_CLASS_INPUT_PEN =           '01'
PCI_CLASS_INPUT_MOUSE =         '02'
PCI_CLASS_INPUT_SCANNER =       '03'
PCI_CLASS_INPUT_GAMEPORT =      '04'
PCI_CLASS_INPUT_OTHER =         '80'

PCI_BASE_CLASS_SERIAL =         'C'
PCI_CLASS_SERIAL_FIREWIRE =     '00'
PCI_CLASS_SERIAL_ACCESS =       '01'
PCI_CLASS_SERIAL_SSA =          '02'
PCI_CLASS_SERIAL_USB =          '03'
PCI_CLASS_SERIAL_FIBER =        '04'
PCI_CLASS_SERIAL_SMBUS =        '05'

def _clasify_pci_type(subsystem):
    """ return 1 if device is PCI, otherwise -1 """
    if subsystem == 'pci':
        return '1'
    else:
        return '-1'

def _clasify_class(device):
    """ Clasify type of device. Returned value is one of following string:
        NETWORK, KEYBOARD, MOUSE, VIDEO, USB, IDE, SCSI, RAID, MODEM, SCANNER
        CAPTURE, AUDIO, FIREWIRE, SOCKET, CDROM, HD, FLOPPY, TAPE, PRINTER, OTHER
        or None if it is neither PCI nor USB device.
    """
    (base_class, sub_class) = _parse_pci_class(device.get_property('PCI_CLASS'))
    subsystem = device.get_subsystem()

    # network devices
    if base_class == PCI_BASE_CLASS_NETWORK:
        return 'OTHER' # if set as 'NETWORK' it will not display in HW tab

    # input devices
    # pci
    if base_class == PCI_BASE_CLASS_INPUT:
        if sub_class == PCI_CLASS_INPUT_KEYBOARD:
            return 'KEYBOARD'
        elif sub_class == PCI_CLASS_INPUT_MOUSE:
            return 'MOUSE'
    # usb
    id_serial = device.get_property('ID_SERIAL')
    if id_serial:
        id_serial = id_serial.lower()
        # KEYBOARD <-- do this before mouse, some keyboards have built-in mice
        if 'keyboard' in id_serial:
            return 'KEYBOARD'
        # MOUSE
        if 'mouse' in id_serial:
            return 'MOUSE'

    if base_class:      # PCI Devices
        if base_class == PCI_BASE_CLASS_DISPLAY:
            return 'VIDEO'
        elif base_class == PCI_BASE_CLASS_SERIAL:
            if sub_class == PCI_CLASS_SERIAL_USB:
                return 'USB'
            elif sub_class == PCI_CLASS_SERIAL_FIREWIRE:
                return 'FIREWIRE'
        elif base_class == PCI_BASE_CLASS_STORAGE:
            if sub_class == PCI_CLASS_STORAGE_IDE:
                return 'IDE'
            elif sub_class == PCI_CLASS_STORAGE_SCSI:
                return 'SCSI'
            elif sub_class == PCI_CLASS_STORAGE_RAID:
                return 'RAID'
            elif sub_class == PCI_CLASS_STORAGE_FLOPPY:
                return 'FLOPPY'
        elif base_class == PCI_BASE_CLASS_COMMUNICATION and sub_class == PCI_CLASS_COMMUNICATION_MODEM:
            return 'MODEM'
        elif base_class == PCI_BASE_CLASS_INPUT and sub_class == PCI_CLASS_INPUT_SCANNER:
            return 'SCANNER'
        elif base_class == PCI_BASE_CLASS_MULTIMEDIA:
            if sub_class == PCI_CLASS_MULTIMEDIA_VIDEO:
                return 'CAPTURE'
            elif sub_class == PCI_CLASS_MULTIMEDIA_AUDIO:
                return 'AUDIO'
        elif base_class == PCI_BASE_CLASS_BRIDGE and (
            sub_class == PCI_CLASS_BRIDGE_PCMCIA or sub_class == PCI_CLASS_BRIDGE_CARDBUS ):
            return 'SOCKET'

    if subsystem == 'block':
        if device.has_property('ID_CDROM') or (
            device.has_property('ID_TYPE') and device.get_property('ID_TYPE') == 'cd'):
            return 'CDROM'
        else:
            return 'HD'
    elif subsystem == 'sound':
        return 'AUDIO'

    if subsystem =='scsi':
        if device.get_devtype =='scsi_device':
            dev_type = _get_scsi_dev_type(device)
            if dev_type == 0 or dev_type == 14:
                return 'HD'
            elif dev_type == 1:
                return 'TAPE'
            elif dev_type == 5:
                return 'CDROM'
            else:
                return 'OTHER'
    # PRINTER
    m = re.search('.*/lp\d+$', device.get_sysfs_path())
    if m:
        return 'PRINTER'

    if subsystem == 'scsi':
        return 'SCSI'

    # Catchall for specific devices, only do this after all the others
    if subsystem == 'pci' or subsystem == 'usb':
        return 'OTHER'

    # No class found
    return None

def _get_device_desc(device):
    """ Return human readable description of device. """
    subsystem = device.get_subsystem()
    command = None
    result = None
    if subsystem == 'pci':
        (vendor_id, device_id) = device.get_property('PCI_ID').split(':')
        pci = PCI()
        result = "%s|%s" % (pci.get_vendor(vendor_id), pci.get_device(vendor_id, device_id))
    elif subsystem == 'usb':
        vendor_id = device.get_property('ID_VENDOR_ID')
        usb = USB()
        if vendor_id:
            result = "%s|%s" % (usb.get_vendor(vendor_id), usb.get_device(vendor_id, device.get_property('ID_MODEL_ID')))
        elif device.get_devtype() == 'usb_interface':
            if device.get_driver() == 'usbhid':
                result = 'USB HID Interface'
            elif device.get_driver() == 'hub':
                result = 'USB Hub Interface'
            else:
                result = 'USB Interface'
        elif device.get_devtype() == 'usb_device' and device.get_property('PRODUCT'):
            (vendor_id, model_id) = device.get_property('PRODUCT').split('/')[:2]
            # left pad it with 0 to 4 digits
            vendor_id = '%.4x' % int(vendor_id, 16)
            model_id = '%.4x' % int(model_id, 16)
            result = "%s|%s" % (usb.get_vendor(vendor_id), usb.get_device(vendor_id, model_id))
    elif subsystem == 'block':
        result = device.get_property('ID_MODEL')
    if result:
        return result
    else:
        return ''

def _parse_pci_class(pci_class):
    """ Parse Class Code. Return touple of
        [base class code, sub-class code]
        You are usually interested to only first two.
        The third - "specific register-level programming interface" is ignored.
        For details, see the PCI Local Bus Specification 2.1/2.2 Section 6.2.1 Device Identification
    """
    if pci_class is None:
        return (None, None)
    else:
        return (pci_class[-6:-4], pci_class[-4:-2])

def _get_scsi_dev_type(device):
    """ Return SCSI type of device in raw format as presented in /sys/...devpath../type """
    try:
        f = open("%s/type" % device.get_sysfs_path(), 'r')
    except IOError:
        return -1
    result = f.readline()
    f.close()
    return result
hardware.py000064400000077643150516774050006746 0ustar00#
# Copyright (c) 1999--2018 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 thing gets the hardware configuraion out of a system
"""Used to read hardware info from kudzu, /proc, etc"""
from socket import gethostname, getaddrinfo, AF_INET, AF_INET6
import socket
import re
import os
import sys
from up2date_client import config
from up2date_client import rhnserver
from up2date_client import up2dateUtils

from rhn.i18n import ustr

try:
    long
except NameError: # long is not defined in python3
    long = int


# network module for python 2
try:
    import ethtool
    ethtool_present = True
except ImportError:
    ethtool_present = False

# network module for python3 (Fedora >= 23)
try:
    import netifaces
    import ipaddress
    netifaces_present = True
except ImportError:
    netifaces_present = False

import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

import dbus
with up2dateUtils.suppress_errors(['Failed to save log entry',
                                   'SMBIOS.*: entry point at']):
    import dmidecode
from up2date_client import up2dateLog

try:
    from up2date_client.hardware_udev import get_devices, get_computer_info
    using_gudev = 1
except ImportError:
    try: # F13 and EL6
        from up2date_client.hardware_gudev import get_devices, get_computer_info
        using_gudev = 1
    except ImportError:
        from up2date_client.hardware_hal import check_hal_dbus_status, get_hal_computer, read_hal
        using_gudev = 0

# Some systems don't have the _locale module installed
try:
    import locale
except ImportError:
    locale = None

sys.path.append("/usr/share/rhsm")
try:
    from subscription_manager.hwprobe import Hardware as SubManHardware
    subscription_manager_available = True
except ImportError:
    subscription_manager_available = False

# this does not change, we can cache it
_dmi_data           = None
_dmi_not_available  = 0

def dmi_warnings():
    if not hasattr(dmidecode, 'get_warnings'):
        return None

    return dmidecode.get_warnings()

dmi_warn = dmi_warnings()
if dmi_warn:
    dmidecode.clear_warnings()
    log = up2dateLog.initLog()
    log.log_debug("Warnings collected during dmidecode import: %s" % dmi_warn)

def _initialize_dmi_data():
    """ Initialize _dmi_data unless it already exist and returns it """
    global _dmi_data, _dmi_not_available
    if _dmi_data is None:
        if _dmi_not_available:
            # do not try to initialize it again and again if not available
            return None
        else :
            dmixml = dmidecode.dmidecodeXML()
            dmixml.SetResultType(dmidecode.DMIXML_DOC)
            # Get all the DMI data and prepare a XPath context
            try:
                data = dmixml.QuerySection('all')
                dmi_warn = dmi_warnings()
                if dmi_warn:
                    dmidecode.clear_warnings()
                    log = up2dateLog.initLog()
                    log.log_debug("dmidecode warnings: %s" % dmi_warn)
            except:
                # DMI decode FAIL, this can happend e.g in PV guest
                _dmi_not_available = 1
                dmi_warn = dmi_warnings()
                if dmi_warn:
                    dmidecode.clear_warnings()
                return None
            _dmi_data = data.xpathNewContext()
    return _dmi_data

def get_dmi_data(path):
    """ Fetch DMI data from given section using given path.
        If data could not be retrieved, returns empty string.
        General method and should not be used outside of this module.
    """
    dmi_data = _initialize_dmi_data()
    if dmi_data is None:
        return ''
    data = dmi_data.xpathEval(path)
    if data != []:
        return data[0].content
    else:
        # The path do not exist
        return ''

def dmi_vendor():
    """ Return Vendor from dmidecode bios information.
        If this value could not be fetch, returns empty string.
    """
    return get_dmi_data('/dmidecode/BIOSinfo/Vendor')

def dmi_system_uuid():
    """ Return UUID from dmidecode system information.
        If this value could not be fetch, returns empty string.
    """
    # if guest was created manualy it can have empty UUID, in this
    # case dmidecode set attribute unavailable to 1
    uuid = get_dmi_data("/dmidecode/SystemInfo/SystemUUID[not(@unavailable='1')]")
    if not uuid:
        uuid = ''
    return uuid

def read_installinfo():
    if not os.access("/etc/sysconfig/installinfo", os.R_OK):
        return {}
    installinfo = open("/etc/sysconfig/installinfo", "r").readlines()
    installdict = {}
    installdict['class'] = "INSTALLINFO"
    for info in installinfo:
        if not len(info):
            continue
        vals = info.split('=')
        if len(vals) <= 1:
            continue
        strippedstring = vals[0].strip()
        vals[0] = strippedstring

        installdict[vals[0]] = ''.join(vals[1:]).strip()
    return installdict

def cpu_count():
    """ returns number of CPU in system

    Beware that it can be different from number of active CPU (e.g. on s390x architecture
    """
    try:
        cpu_dir = os.listdir('/sys/devices/system/cpu/')
    except OSError:
        cpu_dir = []

    re_cpu = re.compile(r"^cpu[0-9]+$")
    return len([i for i in cpu_dir if re_cpu.match(i)])

# get the number of sockets available on this machine
def __get_number_sockets():
    try:
        if subscription_manager_available:
            return SubManHardware().getCpuInfo()['cpu.cpu_socket(s)']
    except:
        pass # something went wrong, let's figure it out ourselves

    number_sockets = 0
    # Try lscpu command if available
    if os.access("/usr/bin/lscpu", os.X_OK):
        try:
            lines = os.popen("/usr/bin/lscpu -p").readlines()
            max_socket_index = -1
            for line in lines:
                if line.startswith('#'):
                    continue
                # get the socket index from the output
                socket_index = int(line.split(',')[2])
                if socket_index > max_socket_index:
                    max_socket_index = socket_index
            if max_socket_index > -1:
                return 1 + max_socket_index
        except:
            pass

    # Next try parsing /proc/cpuinfo
    if os.access("/proc/cpuinfo", os.R_OK):
        try:
            lines = open("/proc/cpuinfo", 'r').readlines()
            socket_ids = set()
            for line in lines:
                if 'physical id' in line:
                    socket_index = int(line.split(':')[1].strip())
                    socket_ids.add(socket_index)
            if len(socket_ids) > 0:
                return len(socket_ids)
        except:
            pass

    # Next try dmidecode
    if os.access("/usr/sbin/dmidecode", os.X_OK):
        try:
            lines = os.popen("/usr/sbin/dmidecode -t processor").readlines()
            count = 0
            for line in lines:
                if 'Processor Information' in line:
                    count += 1
            if count > 0:
                return count
        except:
            pass

    return None

# This has got to be one of the ugliest fucntions alive
def read_cpuinfo():
    def get_entry(a, entry):
        e = entry.lower()
        if not e in a:
            return ""
        return a[e]

    # read cpu list and return number of cpus and list as dictionary
    def get_cpulist_as_dict(cpulist):
        count = 0
        tmpdict = {}
        for cpu in cpulist.split("\n\n"):
            if not len(cpu):
                continue
            count = count + 1
            if count > 1:
                break # no need to parse rest
            for cpu_attr in cpu.split("\n"):
                if not len(cpu_attr):
                    continue
                vals = cpu_attr.split(":")
                if len(vals) != 2:
                    # XXX: make at least some effort to recover this data...
                    continue
                name, value = vals[0].strip(), vals[1].strip()
                tmpdict[name.lower()] = value
        return tmpdict

    if not os.access("/proc/cpuinfo", os.R_OK):
        return {}

    # Okay, the kernel likes to give us the information we need in the
    # standard "C" locale.
    if locale:
        # not really needed if you don't plan on using atof()
        locale.setlocale(locale.LC_NUMERIC, "C")

    cpulist = open("/proc/cpuinfo", "r").read()
    uname = os.uname()[4].lower()
    count = cpu_count()

    # This thing should return a hwdict that has the following
    # members:
    #
    # class, desc (required to identify the hardware device)
    # count, type, model, model_number, model_ver, model_rev
    # bogomips, platform, speed, cache

    hwdict = { 'class': "CPU",
               "desc" : "Processor",
               }
    if uname[0] == "i" and uname[-2:] == "86" or (uname == "x86_64"):
        # IA32 compatible enough
        tmpdict = get_cpulist_as_dict(cpulist)

        if uname == "x86_64":
            hwdict['platform'] = 'x86_64'
        else:
            hwdict['platform'] = "i386"

        hwdict['count']         = count
        hwdict['type']          = get_entry(tmpdict, 'vendor_id')
        hwdict['model']         = get_entry(tmpdict, 'model name')
        hwdict['model_number']  = get_entry(tmpdict, 'cpu family')
        hwdict['model_ver']     = get_entry(tmpdict, 'model')
        hwdict['model_rev']     = get_entry(tmpdict, 'stepping')
        hwdict['cache']         = get_entry(tmpdict, 'cache size')
        hwdict['bogomips']      = get_entry(tmpdict, 'bogomips')
        hwdict['other']         = get_entry(tmpdict, 'flags')
        mhz_speed               = get_entry(tmpdict, 'cpu mhz')
        if mhz_speed == "":
            # damn, some machines don't report this
            mhz_speed = "-1"
        try:
            hwdict['speed']         = int(round(float(mhz_speed)) - 1)
        except ValueError:
            hwdict['speed'] = -1
    elif uname in["alpha", "alphaev6"]:
        # Treat it as an an Alpha
        tmpdict = get_cpulist_as_dict(cpulist)

        hwdict['platform']      = "alpha"
        hwdict['count']         = get_entry(tmpdict, 'cpus detected')
        hwdict['type']          = get_entry(tmpdict, 'cpu')
        hwdict['model']         = get_entry(tmpdict, 'cpu model')
        hwdict['model_number']  = get_entry(tmpdict, 'cpu variation')
        hwdict['model_version'] = "%s/%s" % (get_entry(tmpdict, 'system type'),
                                             get_entry(tmpdict,'system variation'))
        hwdict['model_rev']     = get_entry(tmpdict, 'cpu revision')
        hwdict['cache']         = "" # pitty the kernel doesn't tell us this.
        hwdict['bogomips']      = get_entry(tmpdict, 'bogomips')
        hwdict['other']         = get_entry(tmpdict, 'platform string')
        hz_speed                = get_entry(tmpdict, 'cycle frequency [Hz]')
        # some funky alphas actually report in the form "462375000 est."
        hz_speed = hz_speed.split()
        try:
            hwdict['speed']         = int(round(float(hz_speed[0]))) / 1000000
        except ValueError:
            hwdict['speed'] = -1
    elif uname in ["ia64"]:
        tmpdict = get_cpulist_as_dict(cpulist)

        hwdict['platform']      = uname
        hwdict['count']         = count
        hwdict['type']          = get_entry(tmpdict, 'vendor')
        hwdict['model']         = get_entry(tmpdict, 'family')
        hwdict['model_ver']     = get_entry(tmpdict, 'archrev')
        hwdict['model_rev']     = get_entry(tmpdict, 'revision')
        hwdict['bogomips']      = get_entry(tmpdict, 'bogomips')
        mhz_speed = tmpdict['cpu mhz']
        try:
            hwdict['speed'] = int(round(float(mhz_speed)) - 1)
        except ValueError:
            hwdict['speed'] = -1
        hwdict['other']         = get_entry(tmpdict, 'features')

    elif uname in ['ppc64']:
        tmpdict = get_cpulist_as_dict(cpulist)

        hwdict['platform'] = uname
        hwdict['count'] = count
        hwdict['model'] = get_entry(tmpdict, "cpu")
        hwdict['model_ver'] = get_entry(tmpdict, 'revision')
        hwdict['bogomips'] = get_entry(tmpdict, 'bogomips')
        hwdict['type'] = get_entry(tmpdict, 'machine')
        # strings are postpended with "mhz"
        mhz_speed = get_entry(tmpdict, 'clock')[:-3]
        try:
            hwdict['speed'] = int(round(float(mhz_speed)) - 1)
        except ValueError:
            hwdict['speed'] = -1

    elif uname in ['s390', 's390x']:
        tmpdict = {}
        for cpu in cpulist.split("\n"):
            vals = cpu.split(": ")
            if len(vals) != 2:
                continue
            tmpdict[vals[0].strip()] = vals[1].strip()

        hwdict['platform']      = uname
        hwdict['type']          = get_entry(tmpdict,'vendor_id')
        hwdict['model']         = uname
        hwdict['count']         = count
        hwdict['bogomips']      = get_entry(tmpdict, 'bogomips per cpu')
        hwdict['model_number']  = ""
        hwdict['model_ver']     = ""
        hwdict['model_rev']     = ""
        hwdict['cache']         = ""
        hwdict['other']         = get_entry(tmpdict, 'features')
        hwdict['speed']         = 0


    else:
        # XXX: expand me. Be nice to others
        hwdict['platform']      = uname
        hwdict['count']         = count
        hwdict['type']          = uname
        hwdict['model']         = uname
        hwdict['model_number']  = ""
        hwdict['model_ver']     = ""
        hwdict['model_rev']     = ""
        hwdict['cache']         = ""
        hwdict['bogomips']      = ""
        hwdict['other']         = ""
        hwdict['speed']         = 0

    # make sure we get the right number here
    if not hwdict["count"]:
        hwdict["count"] = 1
    else:
        try:
            hwdict["count"] = int(hwdict["count"])
        except:
            hwdict["count"] = 1
        else:
            if hwdict["count"] == 0: # we have at least one
                hwdict["count"] = 1

    # Network communication doesn't really belong in here. Sadly though
    # this is the only single place we can put this check. If it's not
    # here then it would need to be in five or six other places, which
    # is not good from a DRY and quality-assurance perspective.
    s = rhnserver.RhnServer()
    if s.capabilities.hasCapability('cpu_sockets'):
        # If we know it add in the number of sockets
        number_sockets = __get_number_sockets()
        if number_sockets:
            hwdict['socket_count'] = number_sockets

    # This whole things hurts a lot.
    return hwdict

def read_memory():
    un = os.uname()
    kernel = un[2]
    if kernel[:3] >= "2.6":
        return read_memory_2_6()
    if kernel[:3] == "2.4":
        return read_memory_2_4()

def read_memory_2_4():
    if not os.access("/proc/meminfo", os.R_OK):
        return {}

    meminfo = open("/proc/meminfo", "r").read()
    lines = meminfo.split("\n")
    curline = lines[1]
    memlist = curline.split()
    memdict = {}
    memdict['class'] = "MEMORY"
    megs = int(long(memlist[1])/(1024*1024))
    if megs < 32:
        megs = megs + (4 - (megs % 4))
    else:
        megs = megs + (16 - (megs % 16))
    memdict['ram'] = str(megs)
    curline = lines[2]
    memlist = curline.split()
    # otherwise, it breaks on > ~4gigs of swap
    megs = int(long(memlist[1])/(1024*1024))
    memdict['swap'] = str(megs)
    return memdict

def read_memory_2_6():
    if not os.access("/proc/meminfo", os.R_OK):
        return {}
    meminfo = open("/proc/meminfo", "r").read()
    lines = meminfo.split("\n")
    meminfo_dict = {}
    for line in lines:
        blobs = line.split(":", 1)
        key = blobs[0]
        if len(blobs) == 1:
            continue
        #print(blobs)
        value = blobs[1].strip()
        meminfo_dict[key] = value

    memdict = {}
    memdict["class"] = "MEMORY"

    total_str = meminfo_dict['MemTotal']
    blips = total_str.split(" ")
    total_k = long(blips[0])
    megs = long(total_k/(1024))

    swap_str = meminfo_dict['SwapTotal']
    blips = swap_str.split(' ')
    swap_k = long(blips[0])
    swap_megs = long(swap_k/(1024))

    memdict['ram'] = str(megs)
    memdict['swap'] = str(swap_megs)
    return memdict


def findHostByRoute():
    """ returns [hostname, intf, intf6]

        Where hostname is you FQDN of this machine.
        And intf is numeric IPv4 address. And intf6 is IPv6 address.
    """
    cfg = config.initUp2dateConfig()
    sl = config.getServerURL()

    st = {'https':443, 'http':80}
    hostname = None
    intf = None
    intf6 = None
    for serverUrl in sl:
        server = serverUrl.split('/')[2]
        servertype = serverUrl.split(':')[0]
        port = st[servertype]

        for family in (AF_INET6, AF_INET):
            try:
                s = socket.socket(family)
            except socket.error:
                continue

            if cfg['enableProxy']:
                server_port = config.getProxySetting()
                (server, port) = server_port.split(':')
                port = int(port)

            try:
                s.settimeout(5)
                s.connect((server, port))
                intf_tmp = s.getsockname()[0]
                if family == AF_INET:
                    intf = intf_tmp
                else:
                    intf6 = intf_tmp
                hostname_tmp = socket.getfqdn(intf_tmp)
                if hostname_tmp != intf_tmp:
                    hostname = hostname_tmp
            except socket.error:
                s.close()
                continue
            s.close()

    # Override hostname with the value from /etc/hostname
    if os.path.isfile("/etc/hostname") and os.access("/etc/hostname", os.R_OK):
        hostnameinfo = open("/etc/hostname", "r").readlines()

        for info in hostnameinfo:
            if not len(info):
                continue
            hostname = info.strip()

    # Override hostname with the one in /etc/sysconfig/network
    # for bz# 457953
    elif os.path.isfile("/etc/sysconfig/network") and os.access("/etc/sysconfig/network", os.R_OK):
        networkinfo = open("/etc/sysconfig/network", "r").readlines()

        for info in networkinfo:
            if not len(info):
                continue
            vals = info.split('=')
            if len(vals) <= 1:
                continue
            if vals[0].strip() == "HOSTNAME":
                # /etc/sysconfig/network is of shell syntax,
                # so values can be quoted
                hostname = ''.join(vals[1:]).strip('"\' \t\n')
                break

    if hostname == None or hostname == 'localhost.localdomain':
        hostname = "unknown"
    return hostname, intf, intf6

def get_slave_hwaddr(master, slave):
    hwaddr = ""
    try:
        bonding = open('/proc/net/bonding/%s' % master, "r")
    except:
        return hwaddr

    slave_found = False
    for line in bonding.readlines():
        if slave_found and line.find("Permanent HW addr: ") != -1:
            hwaddr = line.split()[3]
            break

        if line.find("Slave Interface: ") != -1:
            ifname = line.split()[2]
            if ifname == slave:
                slave_found = True

    bonding.close()
    return hwaddr

def read_network():
    netdict = {}
    netdict['class'] = "NETINFO"

    netdict['hostname'], netdict['ipaddr'], netdict['ip6addr'] = findHostByRoute()

    if netdict['hostname'] == "unknown":
        netdict['hostname'] = gethostname()
        if "." not in netdict['hostname']:
            netdict['hostname'] = socket.getfqdn()

    if netdict['ipaddr'] is None:
        try:
            list_of_addrs = getaddrinfo(netdict['hostname'], None)
            ipv4_addrs = filter(lambda x:x[0]==socket.AF_INET, list_of_addrs)
            # take first ipv4 addr
            netdict['ipaddr'] = ipv4_addrs[0][4][0]
        except:
            netdict['ipaddr'] = "127.0.0.1"

    if netdict['ip6addr'] is None:
        try:
            list_of_addrs = getaddrinfo(netdict['hostname'], None)
            ipv6_addrs = filter(lambda x:x[0]==socket.AF_INET6, list_of_addrs)
            # take first ipv6 addr
            netdict['ip6addr'] = ipv6_addrs[0][4][0]
        except:
            netdict['ip6addr'] = "::1"

    if netdict['ipaddr'] is None:
        netdict['ipaddr'] = ''
    if netdict['ip6addr'] is None:
        netdict['ip6addr'] = ''
    return netdict

def read_network_interfaces():
    intDict = {}
    intDict['class'] = "NETINTERFACES"

    if not ethtool_present and not netifaces_present:
        # ethtool is not available on non-linux platforms (as kfreebsd), skip it
        sys.stderr.write("Warning: information about network interfaces could not be retrieved on this platform.\n")
        return intDict

    if ethtool_present:
        interfaces = list(set(ethtool.get_devices() + ethtool.get_active_devices()))
    else:
        interfaces = netifaces.interfaces()

    for interface in interfaces:
        try:
            if ethtool_present:
                hwaddr = ethtool.get_hwaddr(interface)
            else:
                hwaddr = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]['addr']
        except:
            hwaddr = ""

        # slave devices can have their hwaddr changed
        try:
            master = os.readlink('/sys/class/net/%s/master' % interface)
        except:
            master = None

        if master:
            master_interface = os.path.basename(master)
            hwaddr = get_slave_hwaddr(master_interface, interface)

        try:
            if ethtool_present:
                module = ethtool.get_module(interface)
            else:
                driver_file = open('/sys/class/net/%s/device/uevent' % interface, 'r')
                module = driver_file.readline().split('=')[1].strip()
                driver_file.close()
        except:
            if interface == 'lo':
                module = "loopback"
            else:
                module = "Unknown"

        try:
            if ethtool_present:
                ipaddr = ethtool.get_ipaddr(interface)
            else:
                ipaddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
        except:
            ipaddr = ""

        try:
            if ethtool_present:
                netmask = ethtool.get_netmask(interface)
            else:
                netmask = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['netmask']
        except:
            netmask = ""

        try:
            if ethtool_present:
                broadcast = ethtool.get_broadcast(interface)
            else:
                broadcast = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['broadcast']
        except:
            broadcast = ""

        ip6_list = []
        if ethtool_present:
            dev_info = ethtool.get_interfaces_info(interface)
            for info in dev_info:
                # one interface may have more IPv6 addresses
                for ip6 in info.get_ipv6_addresses():
                    scope = ip6.scope
                    if scope == 'global':
                        scope = 'universe'
                    ip6_list.append({
                        'scope':   scope,
                        'addr':    ip6.address,
                        'netmask': ip6.netmask
                    })

        else:
            try:
                for dev_info in netifaces.ifaddresses(interface)[netifaces.AF_INET6]:
                    ip6_addr = dev_info['addr'].split('%')[0]

                    scope_info = ipaddress.IPv6Address(ip6_addr)
                    if scope_info.is_global:
                        scope = 'universe'
                    elif scope_info.is_link_local:
                        scope = 'link'
                    elif scope_info.is_loopback:
                        scope = 'host'
                    elif scope_info.is_site_local:
                        scope = 'site'

                    # count number of '1' bits in netmask returned by netifaces
                    ip6_netmask = dev_info['netmask']
                    netmask_bits = 0
                    for two_octets in ip6_netmask.split(':'):
                        if not two_octets:
                            break
                        elif two_octets.lower() == 'ffff':
                            netmask_bits += 16
                        else:
                            # remove '0b' from begin and find last '1' in the string
                            netmask_bits += 1 + bin(int(two_octets.split('/')[0], 16))[2:].rindex('1')

                    ip6_list.append({
                            'scope':   scope,
                            'addr':    ip6_addr,
                            'netmask': netmask_bits
                    })
            except KeyError:
                pass  # no ipv6 for this interface

        intDict[interface] = {'hwaddr': hwaddr,
                              'ipaddr': ipaddr,
                              'netmask': netmask,
                              'broadcast': broadcast,
                              'module': module,
                              'ipv6': ip6_list}

    return intDict


# Read DMI information via hal.
def read_dmi():
    dmidict = {}
    dmidict["class"] = "DMI"

    # Try to obtain DMI info if architecture is i386, x86_64 or ia64
    uname = os.uname()[4].lower()
    if not (uname[0] == "i"  and  uname[-2:] == "86") and not (uname == "x86_64"):
        return dmidict

    # System Information
    vendor = dmi_vendor()
    if vendor:
        dmidict["vendor"] = vendor

    product = get_dmi_data('/dmidecode/SystemInfo/ProductName')
    if product:
        dmidict["product"] = product

    version = get_dmi_data('/dmidecode/SystemInfo/Version')
    if version:
        system = product + " " + version
        dmidict["system"] = system

    # BaseBoard Information
    dmidict["board"] = get_dmi_data('/dmidecode/BaseBoardInfo/Manufacturer')

    # Bios Information
    vendor = get_dmi_data('/dmidecode/BIOSinfo/Vendor')
    if vendor:
        dmidict["bios_vendor"] = vendor
    version = get_dmi_data('/dmidecode/BIOSinfo/Version')
    if version:
        dmidict["bios_version"] = version
    release = get_dmi_data('/dmidecode/BIOSinfo/ReleaseDate')
    if release:
        dmidict["bios_release"] = release

    # Chassis Information
    # The hairy part is figuring out if there is an asset tag/serial number of importance
    chassis_serial = get_dmi_data('/dmidecode/ChassisInfo/SerialNumber')
    chassis_tag = get_dmi_data('/dmidecode/ChassisInfo/AssetTag')
    board_serial = get_dmi_data('/dmidecode/BaseBoardInfo/SerialNumber')

    system_serial = get_dmi_data('/dmidecode/SystemInfo/SerialNumber')

    dmidict["asset"] = "(%s: %s) (%s: %s) (%s: %s) (%s: %s)" % ("chassis", chassis_serial,
                                                     "chassis", chassis_tag,
                                                     "board", board_serial,
                                                     "system", system_serial)

    # Clean up empty entries
    for k in list(dmidict.keys()):
        if dmidict[k] is None:
            del dmidict[k]
            # Finished

    return dmidict

def get_hal_system_and_smbios():
    try:
        if using_gudev:
            props = get_computer_info()
        else:
            computer = get_hal_computer()
            props = computer.GetAllProperties()
    except Exception:
        log = up2dateLog.initLog()
        msg = "Error reading system and smbios information: %s\n" % (sys.exc_info()[1])
        log.log_debug(msg)
        return {}
    system_and_smbios = {}

    for key in props:
        if key.startswith('system'):
            system_and_smbios[ustr(key)] = ustr(props[key])

    system_and_smbios.update(get_smbios())
    return system_and_smbios

def get_smbios():
    """ Returns dictionary with values we are interested for.
        For historical reason it is in format, which use HAL.
        Currently in dictionary are keys:
        smbios.system.uuid, smbios.bios.vendor, smbios.system.serial,
        smbios.system.manufacturer.
    """
    _initialize_dmi_data()
    if _dmi_not_available:
        return {}
    else:
        return {
            'smbios.system.uuid': dmi_system_uuid(),
            'smbios.bios.vendor': dmi_vendor(),
            'smbios.system.serial': get_dmi_data('/dmidecode/SystemInfo/SerialNumber'),
            'smbios.system.manufacturer': get_dmi_data('/dmidecode/SystemInfo/Manufacturer'),
            'smbios.system.product': get_dmi_data('/dmidecode/SystemInfo/ProductName'),
            'smbios.system.skunumber': get_dmi_data('/dmidecode/SystemInfo/SKUnumber'),
            'smbios.system.family': get_dmi_data('/dmidecode/SystemInfo/Family'),
            'smbios.system.version': get_dmi_data('/dmidecode/SystemInfo/Version'),
        }

# this one reads it all
def Hardware():
    if using_gudev:
        allhw = get_devices()
    else:
        hal_status, dbus_status = check_hal_dbus_status()
        hwdaemon = 1
        if hal_status or dbus_status:
            # if status != 0 haldaemon or messagebus service not running.
            # set flag and dont try probing hardware and DMI info
            # and warn the user.
            log = up2dateLog.initLog()
            msg = "Warning: haldaemon or messagebus service not running. Cannot probe hardware and DMI information.\n"
            log.log_me(msg)
            hwdaemon = 0
        allhw = []

        if hwdaemon:
            try:
                ret = read_hal()
                if ret:
                    allhw = ret
            except:
                # bz253596 : Logging Dbus Error messages instead of printing on stdout
                log = up2dateLog.initLog()
                msg = "Error reading hardware information: %s\n" % (sys.exc_info()[0])
                log.log_me(msg)

    # all others return individual arrays

    # cpu info
    try:
        ret = read_cpuinfo()
        if ret: allhw.append(ret)
    except:
        print(_("Error reading cpu information:"), sys.exc_info()[0])

    # memory size info
    try:
        ret = read_memory()
        if ret: allhw.append(ret)
    except:
        print(_("Error reading system memory information:"), sys.exc_info()[0])

    cfg = config.initUp2dateConfig()
    if not cfg["skipNetwork"]:
        # minimal networking info
        try:
            ret = read_network()
            if ret:
                allhw.append(ret)
        except:
            print(_("Error reading networking information:"), sys.exc_info()[0])
    # dont like catchall exceptions but theres not
    # really anything useful we could do at this point
    # and its been trouble prone enough

    # minimal DMI info
    try:
        ret = read_dmi()
        if ret:
            allhw.append(ret)
    except:
        # bz253596 : Logging Dbus Error messages instead of printing on stdout
        log = up2dateLog.initLog()
        msg = "Error reading DMI information: %s\n" % (sys.exc_info()[0])
        log.log_me(msg)

    try:
        ret = read_installinfo()
        if ret:
            allhw.append(ret)
    except:
        print(_("Error reading install method information:"), sys.exc_info()[0])

    if not cfg["skipNetwork"]:
        try:
            ret = read_network_interfaces()
            if ret:
                allhw.append(ret)
        except:
            print(_("Error reading network interface information:"), sys.exc_info()[0])

    # all Done.
    return allhw

# XXX: Need more functions here:
#  - filesystems layout (/proc.mounts and /proc/mdstat)
#  - is the kudzu config enough or should we strat chasing lscpi and try to parse that
#    piece of crap output?

#
# Main program
#
if __name__ == '__main__':
    for hw in Hardware():
        for k in hw.keys():
            print("'%s' : '%s'" % (k, hw[k]))
        print
rhncli.py000064400000022167150516774050006417 0ustar00#
# Common cli related functions for RHN Client Tools
# Copyright (c) 1999--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.
#
# Authors:
#       Adrian Likins <alikins@redhat.com>
#       Preston Brown <pbrown@redhat.com>
#       James Bowes <jbowes@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.

import sys
import os
import socket

from optparse import Option
from optparse import OptionParser

from OpenSSL import SSL
from OpenSSL import crypto

from rhn import rpclib
from rhn.i18n import sstr

try: # python2
    import xmlrpclib
except ImportError: # python3
    import xmlrpc.client as xmlrpclib

import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

from up2date_client import config
from up2date_client import up2dateAuth
from up2date_client import up2dateErrors
from up2date_client import up2dateLog
from up2date_client import up2dateUtils
from up2date_client import pkgUtils

_optionsTable = [
    Option("-v", "--verbose", action="count", default=0,
        help=_("Show additional output")),
    Option("--proxy", action="store",
      help=_("Specify an http proxy to use")),
    Option("--proxyUser", action="store",
      help=_("Specify a username to use with an authenticated http proxy")),
    Option("--proxyPassword", action="store",
      help=_("Specify a password to use with an authenticated http proxy")),
    Option("--debug", action="store_true",
      help=_("Enable debug output (network requests)")),
   ]

class RhnCli(object):

    def __init__(self):
        self.optparser = OptionParser(option_list = _optionsTable,
            version = RhnCli.__versionString())

        self.options = None
        self.args = None

        self.hasGui = False

    def run(self):
        # catch any uncaught exceptions and handle them nicely
        sys.excepthook = exceptionHandler
        # main loop call
        try:
            self.initialize()
            sys.exit(self.main() or 0)
        except KeyboardInterrupt:
            sys.stderr.write(sstr(_("\nAborted.\n")))
            sys.exit(1)
        except OSError:
            sys.stderr.write(sstr(_("An unexpected OS error occurred: %s\n") % sys.exc_info()[1]))
            sys.exit(1)
        except rpclib.MalformedURIError: # Subclass of IOError so must come 1st?
            e = sys.exc_info()[1]
            if e is None or len(str(e)) == 0:
                sys.stderr.write(sstr(_("A connection was attempted with a malformed URI.\n")))
            else:
                sys.stderr.write(sstr(_("A connection was attempted with a malformed URI: %s.\n") % e))
        except IOError:
            sys.stderr.write(sstr(_("There was some sort of I/O error: %s\n") % sys.exc_info()[1]))
            sys.exit(1)
        except SSL.Error:
            sys.stderr.write(sstr(_("There was an SSL error: %s\n") % sys.exc_info()[1]))
            sys.stderr.write(sstr(_("A common cause of this error is the system time being incorrect. " \
                               "Verify that the time on this system is correct.\n")))
            sys.exit(1)
        except (SSL.SysCallError, socket.error):
            sys.stderr.write(sstr("OpenSSL.SSL.SysCallError: %s\n" % str(sys.exc_info()[1])))
            sys.exit(2)
        except crypto.Error:
            sys.stderr.write(sstr(_("There was a SSL crypto error: %s\n") % sys.exc_info()[1]))
        except SystemExit:
            raise
        except up2dateErrors.AuthenticationError:
            sys.stderr.write(sstr(_("There was an authentication error: %s\n") % sys.exc_info()[1]))
            sys.exit(1)
        except up2dateErrors.RpmError:
            sys.stderr.write(sstr("%s\n" % sys.exc_info()[1]))
            sys.exit(1)
        except xmlrpclib.ProtocolError:
            sys.stderr.write(sstr("XMLRPC ProtocolError: %s\n" % str(sys.exc_info()[1])))
            sys.exit(3)

    def initialize(self):
        (self.options, self.args) = self.optparser.parse_args()

        RhnCli.__setDebugLevel(self.options.verbose)

        # see if were running as root
        if os.geteuid() != 0:
            rootWarningMsg = _("You must be root to run %s") % sys.argv[0]
            self._warning_dialog(rootWarningMsg)
            sys.exit(1)

        if self.options.debug:
            self._initialize_debug_network_logs()

        self.__updateProxyConfig()

    def main(self):
        raise NotImplementedError

    def _initialize_debug_network_logs(self):
        """
        Enables logging of all all https requests to console
        """
        import logging
        try:
            from http.client import HTTPConnection  # py3
        except ImportError:
            from httplib import HTTPConnection  # py2

        HTTPConnection.debuglevel = 1

        logging.basicConfig()
        logging.getLogger().setLevel(logging.DEBUG)
        requests_log = logging.getLogger("requests.packages.urllib3")
        requests_log.setLevel(logging.DEBUG)
        requests_log.propagate = True

    def _testRhnLogin(self):
        try:
            up2dateAuth.updateLoginInfo()
            return True
        except up2dateErrors.ServerCapabilityError:
            print(sys.exc_info()[1])
            return False
        except up2dateErrors.AuthenticationError:
            return False
        except up2dateErrors.RhnServerException:
            log = up2dateLog.initLog()
            log.log_me('There was a RhnServerException while testing login:\n')
            log.log_exception(*sys.exc_info())
            return False

    def _warning_dialog(self, message):
        if self.hasGui:
            try:
                from up2date_client import gui
                gui.errorWindow(message)
            except:
                print(_("Unable to open gui. Try `up2date --nox`"))
                print(message)
        else:
            print(message)

    def __updateProxyConfig(self):
        """Update potential proxy configuration.
        Note: this will _not_ save the info to up2date's configuration file
        A separate call to config.initUp2dateConfig.save() is needed.
        """
        cfg = config.initUp2dateConfig()

        if self.options.proxy:
            cfg.set("httpProxy", self.options.proxy)
            cfg.set("enableProxy", 1)
        if self.options.proxyUser:
            cfg.set("proxyUser", self.options.proxyUser)
            cfg.set("enableProxyAuth", 1)
        if self.options.proxyPassword:
            cfg.set("proxyPassword", self.options.proxyPassword)
            cfg.set("enableProxyAuth", 1)

    def saveConfig(self):
        """
        Saves the current up2date configuration being used to disk.
        """
        cfg = config.initUp2dateConfig()
        cfg.save()

    def __faultError(self, errMsg):
        if self.hasGui:
            try:
                from up2date_client import gui
                gui.errorWindow(errMsg)
            except:
                print(_("Unable to open gui. Try `up2date --nox`"))
                print(errMsg)
        else:
            print(errMsg)

    @staticmethod
    def __versionString():
        versionString = _("%%prog (Spacewalk Client Tools) %s\n"
        "Copyright (C) 1999--2014 Red Hat, Inc.\n"
        "Licensed under the terms of the GPLv2.") % up2dateUtils.version()
        return versionString

    @staticmethod
    def __setDebugLevel(level):
        cfg = config.initUp2dateConfig()
        # figure out the debug level
        cfg["debug"] = cfg["debug"] + level
        if cfg["debug"] > 2:
            pkgUtils.setDebugVerbosity()

def exceptionHandler(type, value, tb):
    log = up2dateLog.initLog()
    sys.stderr.write(sstr(_("An error has occurred:") + "\n"))
    if hasattr(value, "errmsg"):
        sys.stderr.write(sstr(value.errmsg) + "\n")
        log.log_exception(type, value, tb)
    else:
        sys.stderr.write(sstr(str(type) + "\n"))
        log.log_exception(type, value, tb)

    sys.stderr.write(sstr(_("See /var/log/up2date for more information") + "\n"))
clientCaps.py000064400000004240150516774050007215 0ustar00
# a dict with "capability name" as the key, and the version
# as the value.

import glob
import os

from up2date_client.capabilities import parseCap

try: # python2
    import UserDict
except ImportError: # python3
    import collections as UserDict

class ClientCapabilities(UserDict.UserDict):
    def __init__(self):
        UserDict.UserDict.__init__(self)
        self.populate()

    def populate(self, capsToPopulate=None):
        # FIXME: at some point, this will be
        # intelligently populated...
        localcaps = {
            "caneatCheese":{'version':1, 'value': 1}
            }
        if capsToPopulate:
            localcaps = capsToPopulate
        self.data = localcaps

    def headerFormat(self):
        headerList = []
        for key in self.data.keys():
            headerName = "X-RHN-Client-Capability"
            value = "%s(%s)=%s" % (key,
                                   self.data[key]['version'],
                                   self.data[key]['value'])
            headerList.append((headerName, value))
        return headerList

caps = ClientCapabilities()

def loadLocalCaps(capsDir = "/etc/sysconfig/rhn/clientCaps.d"):

    capsFiles = glob.glob("%s/*" % capsDir)

    for capsFile in capsFiles:
        if os.path.isdir(capsFile):
            continue
        if not os.access(capsFile, os.R_OK):
            continue

        fd = open(capsFile, "r")
        for line in fd.readlines():
            line = line.strip()
            if not line or line[0] == "#":
                continue
            caplist = parseCap(line)

            for (cap,data) in caplist:
                caps.data[cap] = data

#    print(caps.data)

loadLocalCaps()

# register local caps we require.
def registerCap(cap, data):
    caps.data[cap] = data


# figure out something pretty here
registerCap("packages.runTransaction", {'version':'1', 'value':'1'})
registerCap("packages.rollBack", {'version':'1', 'value':'1'})
registerCap("packages.verify", {'version':'1', 'value':'1'})
registerCap("packages.extended_profile", {'version':'2', 'value':'1'})
registerCap("reboot.reboot", {'version':'1', 'value':'1'})
registerCap("packages.update", {'version':'2', 'value':'2'})
rhnChannel.py000064400000011647150516774050007221 0ustar00
# all the crap that is stored on the rhn side of stuff
# updating/fetching package lists, channels, etc

from up2date_client import up2dateAuth
from up2date_client import up2dateLog
from up2date_client import up2dateErrors
from up2date_client import config
from up2date_client import rhnserver

import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

# heh, dont get much more generic than this...
class rhnChannel:
    # shrug, use attributes for thetime being
    def __init__(self, **kwargs):
        self.dict = {}

        for kw in kwargs.keys():
            self.dict[kw] = kwargs[kw]

    def __getitem__(self, item):
        return self.dict[item]

    def __setitem__(self, item, value):
        self.dict[item] = value

    def __lt__(self, other):
        return (self.dict["name"] > other.dict["name"])

    def keys(self):
        return self.dict.keys()

    def values(self):
        return self.dict.values()

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

class rhnChannelList:
    def __init__(self):
        # probabaly need to keep these in order for
        #precedence
        self.list = []

    def addChannel(self, channel):
        self.list.append(channel)


    def channels(self):
        return self.list

    def getByLabel(self, channelname):
        for channel in self.list:
            if channel['label'] == channelname:
                return channel
    def getByName(self, channelname):
        return self.getByLabel(channelname)

    def getByType(self, type):
        channels = []
        for channel in self.list:
            if channel['type'] == type:
                channels.append(channel)
        return channels

# for the gui client that needs to show more info
# maybe we should always make this call? If nothing
# else, wrapper should have a way to show extended channel info
def getChannelDetails(timeout=None):

    channels = []
    sourceChannels = getChannels(timeout=timeout)

    for sourceChannel in sourceChannels.channels():
        if sourceChannel['type'] != 'up2date':
            # FIMXE: kluge since we dont have a good name, maybe be able to fix
            sourceChannel['name'] = sourceChannel['label']
            sourceChannel['description'] = "%s channel %s from  %s" % (sourceChannel['type'],
                                                                           sourceChannel['label'],
                                                                           sourceChannel['url'])
        channels.append(sourceChannel)
    return channels

cmdline_pkgs = []

global selected_channels
selected_channels = None
def getChannels(force=None, label_whitelist=None, timeout=None):
    """ return rhnChannelList containing list of channel we are subscribed to """
    cfg = config.initUp2dateConfig()
    log = up2dateLog.initLog()
    global selected_channels
    if not selected_channels and not force:
        selected_channels = rhnChannelList()
        s = rhnserver.RhnServer(timeout=timeout)

        if not up2dateAuth.getSystemId():
            raise up2dateErrors.NoSystemIdError(_("Unable to Locate SystemId"))

        up2dateChannels = s.up2date.listChannels(up2dateAuth.getSystemId())

        for chan in up2dateChannels:
            if label_whitelist and not chan['label'] in label_whitelist:
                continue

            channel = rhnChannel(type = 'up2date', url = config.getServerlURLFromMirror())
            for key in chan.keys():
                if key == "last_modified":
                    channel['version'] = chan['last_modified']
                else:
                    channel[key] = chan[key]

            if cfg['channelOverride']:
                channel['name'] = channel['label'] = \
                    channel['description'] = \
                    channel['summary'] = cfg['channelOverride']
                log.log_me('WARNING: Channel overridden locally: %s' % channel['name'])
                log.log_me('-------: If you see this warning outside of the leapp process')
                log.log_me('-------: contact CloudLinux support.')
            selected_channels.addChannel(channel)

    if len(selected_channels.list) == 0:
        raise up2dateErrors.NoChannelsError(_("This system may not be updated until it is associated with a channel."))

    return selected_channels


def setChannels(tempchannels):
    global selected_channels
    selected_channels = None
    whitelist = dict(map(lambda x: (x,1), tempchannels))
    return getChannels(label_whitelist=whitelist)



def subscribeChannels(channels,username,passwd):
    s = rhnserver.RhnServer()
    return s.up2date.subscribeChannels(up2dateAuth.getSystemId(), channels, username,
        passwd)

def unsubscribeChannels(channels,username,passwd):
    s = rhnserver.RhnServer()
    return s.up2date.unsubscribeChannels(up2dateAuth.getSystemId(), channels,
        username, passwd)
rpmUtils.py000064400000012311150516774050006745 0ustar00# some high level utility stuff for rpm handling

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


#
#  FIXME: Some exceptions in here are currently in up2date.py
#         fix by moving to up2dateErrors.py and importing from there
#
#

import os
import rpm
from rhn.i18n import sstr
from up2date_client import transaction

import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

def installedHeaderByKeyword(**kwargs):
    """ just cause this is such a potentially useful looking method... """
    _ts = transaction.initReadOnlyTransaction()
    mi = _ts.dbMatch()
    for keyword in kwargs.keys():
        mi.pattern(keyword, rpm.RPMMIRE_GLOB, kwargs[keyword])
        # we really shouldnt be getting multiples here, but what the heck
    headerList = []
    for h in mi:
        headerList.append(h)

    return headerList

def verifyPackages(packages):
    """ given a list of package labels, run rpm -V on them
        and return a dict keyed off that data
    """
    data = {}
    missing_packages = []
    # data structure is keyed off package
    # label, with value being an array of each
    # line of the output from -V


    retlist = []
    for package in packages:
        # we have to have at least name...

        # Note: we cant reliable match on epoch, so just
        # skip it... two packages that only diff by epoch is
        # way broken anyway
        keywords = {'name': package[0],
                    'version': package[1],
                    'release': package[2],
                    # we left our epoch
                    'arch': package[4]
                    }
        for key in (keywords.keys()):
            if (keywords[key] == None) or (keywords[key] == ""):
                del(keywords[key])

        headers = installedHeaderByKeyword(**keywords)
        if len(headers) == 0:
            missing_packages.append(package)

        for header in headers:
            epoch = header['epoch']
            if epoch == None:
                epoch = ""
            # gpg-pubkey "packages" can have an arch of None, see bz #162701
            arch = header["arch"]
            if arch == None:
                arch = ""

            pkg = (header['name'], header['version'],
                   header['release'], epoch,
                   arch)

            # dont include arch in the label if it's a None arch, #162701
            if header["arch"] == "":
                packageLabel = "%s-%s-%s" % (pkg[0], pkg[1], pkg[2])
            else:
                packageLabel = "%s-%s-%s.%s" % (pkg[0], pkg[1], pkg[2], pkg[4])

            verifystring = "/usr/bin/rpmverify -V %s" % packageLabel

            fd = os.popen(verifystring)
            res = fd.readlines()
            fd.close()

            reslist = []
            for line in res:
                reslist.append(line.strip())
            retlist.append([pkg, reslist])

    return retlist, missing_packages

#FIXME: this looks like a good candidate for caching, since it takes a second
# or two to run, and I can call it a couple of times
def getInstalledPackageList(msgCallback = None, progressCallback = None,
                            getArch=None, getInfo = None):
    """ Return list of packages. Package is hash with keys name, epoch,
        version, release and optionaly arch and cookie
    """
    pkg_list = []

    if msgCallback != None:
        msgCallback(_("Getting list of packages installed on the system"))

    _ts = transaction.initReadOnlyTransaction()
    count = 0
    total = 0

    for h in _ts.dbMatch():
        if h == None:
            break
        count = count + 1

    total = count

    count = 0
    for h in _ts.dbMatch():
        if h == None:
            break
        package = {
            'name': sstr(h['name']),
            'epoch': h['epoch'],
            'version': sstr(h['version']),
            'release': sstr(h['release']),
            'installtime': h['installtime']
        }
        if package['epoch'] == None:
            package['epoch'] = ""
        else: # convert it to string
            package['epoch'] = "%s" % package['epoch']
        if getArch:
            package['arch'] = h['arch']
            # the arch on gpg-pubkeys is "None"...
            if package['arch']:
                package['arch'] = sstr(package['arch'])
                pkg_list.append(package)
        elif getInfo:
            if h['arch']:
                package['arch'] = sstr(h['arch'])
            if h['cookie']:
                package['cookie'] = sstr(h['cookie'])
            pkg_list.append(package)
        else:
            pkg_list.append(package)

        if progressCallback != None:
            progressCallback(count, total)
        count = count + 1

    pkg_list.sort(key=lambda x:(x['name'], x['epoch'], x['version'], x['release']))
    return pkg_list

def setDebugVerbosity():
    """Set rpm's verbosity mode
    """
    try:
        rpm.setVerbosity(rpm.RPMLOG_DEBUG)
    except AttributeError:
        print("extra verbosity not supported in this version of rpm")
transaction.py000064400000010141150516774050007452 0ustar00
#
# Client code for Update Agent
# Copyright (c) 1999--2016 Red Hat, Inc.  Distributed under GPLv2.
#
#         Adrian Likins <alikins@redhat.com
#
#
# a couple of classes wrapping up transactions so that we
#    can share transactions instead of creating new ones all over
#

import rpm

read_ts = None
ts = None

# ************* NOTE: ************#
# for the sake of clarity, the names "added/removed" as used here
# are indicative of what happened when the original transaction was
# ran. Aka, if you "up2date foobar" and it updates foobar-1-0 with
# foobar-2-0, you added foobar-2-0 and removed foobar-1-0
#
# The reason I mention this explicitly is the trouble of describing
# what happens when you rollback the transaction, which is basically
# the opposite, and leads to plenty of confusion
#


class TransactionData:
    # simple data structure designed to transport info
    # about rpm transactions around
    def __init__(self):
        self.data = {}
        # a list of tuples of pkg info, and mode ('e', 'i', 'u')
        # the pkgInfo is tuple of [name, version, release, epoch, arch]
        # size is never used directly for this, it's here as a place holder
        # arch is optional, if the server specifies it, go with what
        # removed packages only need [n,v,r,e,arch]
        self.data['packages'] = []
        # list of flags to set for the transaction
        self.data['flags'] = []
        self.data['vsflags'] = []
        self.data['probFilterFlags'] = []


    def display(self):
        out = ""
        removed = []
        installed = []
        updated = []
        misc = []
        for (pkgInfo, mode) in self.data['packages']:
            if mode == 'u':
                updated.append(pkgInfo)
            elif mode == 'i':
                installed.append(pkgInfo)
            elif mode == 'e':
                removed.append(pkgInfo)
            else:
                misc.append(pkgInfo)
        for pkgInfo in removed:
            out = out + "\t\t[e] %s-%s-%s:%s\n" % (pkgInfo[0], pkgInfo[1], pkgInfo[2], pkgInfo[3])
        for pkgInfo in installed:
            out = out + "\t\t[i] %s-%s-%s:%s\n" % (pkgInfo[0], pkgInfo[1], pkgInfo[2], pkgInfo[3])
        for pkgInfo in updated:
            out = out + "\t\t[u] %s-%s-%s:%s\n" % (pkgInfo[0], pkgInfo[1], pkgInfo[2], pkgInfo[3])
        for pkgInfo in misc:
            out = out + "\t\t[%s] %s-%s-%s:%s\n" % (pkgInfo[5], pkgInfo[0], pkgInfo[1],
                                                    pkgInfo[2], pkgInfo[3])
        return out


# wrapper/proxy class for rpm.Transaction so we can
# instrument it, etc easily
class Up2dateTransaction:
    def __init__(self):
        self.ts = rpm.TransactionSet()
        self._methods = ['dbMatch',
                         'check',
                         'order',
                         'addErase',
                         'addInstall',
                         'run',
                         'IDTXload',
                         'IDTXglob',
                         'rollback',
                         'pgpImportPubkey',
                         'pgpPrtPkts',
                         'Debug',
                         'setFlags',
                         'setVSFlags',
                         'setProbFilter',
                         'hdrFromFdno']
        self.tsflags = []

    def __getattr__(self, attr):
        if attr in self._methods:
            return self.getMethod(attr)
        else:
            raise AttributeError(attr)

    def getMethod(self, method):
        # in theory, we can override this with
        # profile/etc info
        return getattr(self.ts, method)

    # push/pop methods so we dont lose the previous
    # set value, and we can potentiall debug a bit
    # easier
    def pushVSFlags(self, flags):
        self.tsflags.append(flags)
        self.ts.setVSFlags(self.tsflags[-1])

    def popVSFlags(self):
        del self.tsflags[-1]
        self.ts.setVSFlags(self.tsflags[-1])

def initReadOnlyTransaction():
    global read_ts
    if read_ts == None:
        read_ts =  Up2dateTransaction()
        # FIXME: replace with macro defination
        read_ts.pushVSFlags(-1)
    return read_ts

rhnPackageInfo.py000064400000004534150516774050010015 0ustar00
# all the crap that is stored on the rhn side of stuff
# updating/fetching package lists, channels, etc


from up2date_client import up2dateAuth
from up2date_client import up2dateLog
from up2date_client import rhnserver
from up2date_client import pkgUtils


def logDeltaPackages(pkgs):
    log = up2dateLog.initLog()
    log.log_me("Adding packages to package profile: %s" %
               pprint_pkglist(pkgs['added']))
    log.log_me("Removing packages from package profile: %s" %
               pprint_pkglist(pkgs['removed']))

# pylint: disable=unused-argument
def updatePackageProfile(timeout=None):
    """ get a list of installed packages and send it to rhnServer """

    # The endpoint that is called in this function (registration.update_packages)
    # is disabled on the CLN side, and can throw errors if called (CLOS-3032).
    return

    # Original code preserved below in case we ever need to re-enable this function.
    # log = up2dateLog.initLog()
    # log.log_me("Updating package profile")
    # packages = pkgUtils.getInstalledPackageList(getArch=1)
    # s = rhnserver.RhnServer(timeout=timeout)
    # if not s.capabilities.hasCapability('xmlrpc.packages.extended_profile', 2):
    #     # for older satellites and hosted - convert to old format
    #     packages = convertPackagesFromHashToList(packages)
    # s.registration.update_packages(up2dateAuth.getSystemId(), packages)

def pprint_pkglist(pkglist):
    if type(pkglist) == type([]):
        output = ["%s-%s-%s" % (a[0],a[1],a[2]) for a in pkglist]
    else:
        output = "%s-%s-%s" % (pkglist[0], pkglist[1], pkglist[2])
    return output

def convertPackagesFromHashToList(packages):
    """ takes list of hashes and covert it to list of lists
        resulting strucure is:
        [[name, version, release, epoch, arch, cookie], ... ]
    """
    result = []
    for package in packages:
        if 'arch' in package and 'cookie' in package:
            result.append([package['name'], package['version'], package['release'],
                package['epoch'], package['arch'], package['cookie']])
        elif 'arch' in package:
            result.append([package['name'], package['version'], package['release'],
                package['epoch'], package['arch']])
        else:
            result.append([package['name'], package['version'], package['release'], package['epoch']])
    return result