?¡ëPNG  IHDR ? f ??C1 sRGB ??¨¦ gAMA ¡À? ¨¹a pHYs ? ??o¡§d GIDATx^¨ª¨¹L¡±¡Âe¡ÂY?a?("Bh?_¨°???¡é¡ì?q5k?*:t0A-o??£¤]VkJ¡éM??f?¡À8\k2¨ªll¡ê1]q?¨´???T
Warning: file_get_contents(https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/ru.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/user1137782/www/china1.by/classwithtostring.php on line 86

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 213

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 214

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 215

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 216

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 217

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 218
rhnHardware.py000066600000000420150501002420007350 0ustar00 import up2dateAuth import rpcServer import hardware def updateHardware(): s = rpcServer.getServer() hardwareList = hardware.Hardware() s.registration.refresh_hw_profile(up2dateAuth.getSystemId(), hardwareList) haltree.pyc000066600000007325150501002420006705 0ustar00Ñò ú4™Pc@s6ddkZddd„ƒYZddd„ƒYZdS(iÿÿÿÿNt HalDevicecBs eZdZd„Zd„ZRS(s5An object containing its udi, properties and childrencCs_|d|_||_g|_d|_|idƒo|d|_n d|_d|_dS(Nsinfo.udis info.parent(tudit propertiestchildrentNonetclassificationthas_keyt parent_uditparent(tselfR((s(/usr/share/rhn/up2date_client/haltree.pyt__init__s     cCsA|iGdGHx.|iiƒD]\}}dG|GdG|GHqWdS(Nt:s s ==> (RRtitems(R tpropertytvalue((s(/usr/share/rhn/up2date_client/haltree.pytprint_properties,s  (t__name__t __module__t__doc__R R(((s(/usr/share/rhn/up2date_client/haltree.pyRs tHalTreecBsMeZd„Zd„Zd„Zd„Zed„ƒZd„Zd„Z RS(cCsd|_g|_dS(N(Rtheadt no_parent_yet(R ((s(/usr/share/rhn/up2date_client/haltree.pyR 5s cCsn|ioJ|i|iƒ}|o|ii|ƒ||_q]|ii|ƒn ||_|i|ƒdS(N(Rt_HalTree__find_nodeRtappendRRRt_HalTree__get_lost_children(R t hal_deviceR((s(/usr/share/rhn/up2date_client/haltree.pytadd:s   cCskg}g}|i}xN|D]F}|i|ijo-||_|ii|ƒ|ii|ƒqqWdS(N(RRRRRRtremove(R Rt found_listtindexestno_parent_yet_copytdev((s(/usr/share/rhn/up2date_client/haltree.pyt__get_lost_childrenIs  cCse|io%ti|i|ƒ}|o|Snx/|iD]$}ti||ƒ}|o|Sq9WdS(sp This takes a node in the HalDevice tree and returns the HalDevice with the given udi. N(RRt_HalTree__find_node_workerRR(R Rtnodet found_node((s(/usr/share/rhn/up2date_client/haltree.pyt __find_nodeSs    cCsK|i|jo|Sx/|iD]$}ti||ƒ}|o|SqWdS(N(RRRR!R(R"Rtdevicetres((s(/usr/share/rhn/up2date_client/haltree.pyt__find_node_workercs  cCs|i|idƒdS(Nt(t_HalTree__print_dev_treeR(R ((s(/usr/share/rhn/up2date_client/haltree.pyt print_treemscCs"|G|iGH|GdG|iGHxÖ|iiƒD]Å\}}t|ƒtijoO|iƒo'|dGd|tt |ƒƒfGHqñ|dGd||fGHq,t|ƒti jo'|dGd|tt |ƒƒfGHq,|dGd||fGHq,WHx%|i D]}|i ||dƒqWdS(NsCLASS:s s %-20s ==> %s( RRRR ttypettypest StringTypetisdigitthextinttIntTypeRR)(R R"tindenttnameR tchild((s(/usr/share/rhn/up2date_client/haltree.pyt__print_dev_treeps   '' ( RRR RRRt staticmethodR!R*R)(((s(/usr/share/rhn/up2date_client/haltree.pyR4s    (((R,RR(((s(/usr/share/rhn/up2date_client/haltree.pyts config.py000066600000024422150501002420006360 0ustar00# This file is a portion of the Red Hat Update Agent # Copyright (c) 1999 - 2002 Red Hat, Inc. Distributed under GPL # # Authors: # Cristian Gafton # Adrian Likins # # $Id$ """ This module includes the Config and Up2date Config classes use by the up2date agent to hold config info. """ import os import sys import gettext t = gettext.translation('rhn-client-tools', fallback=True) _ = 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.rhn.redhat.com/XMLRPC"), '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.redhat.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/RHNS-CA-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 == 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 = 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 = str(value) 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 self.dict.has_key(key): # 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 == 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, "w") os.chmod(self.fileName, 0644) 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("%s[comment]=%s\n" % (key, comment)) if type(value) != type([]): value = [ value ] if key in FileOptions: value = map(os.path.abspath, value) f.write("%s=%s\n" % (key, ';'.join(map(str, value)))) f.write("\n") f.close() # dictionary interface def has_key(self, name): return self.dict.has_key(name) def keys(self): return self.dict.keys() def values(self): return map(lambda a: a[1], 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 self.dict.has_key(name): return self.dict[name][1] return None def __setitem__(self, name, value): if self.dict.has_key(name): 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 self.dict.has_key(name): 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 has_key(self, name): if self.runtime.has_key(name): return True if self.stored.has_key(name): return True return False def keys(self): ret = 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 self.runtime.has_key(name): return self.runtime[name] if self.stored.has_key(name): 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 not self.runtime.has_key(k): 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 self.runtime.has_key(name): del self.runtime[name] def getProxySetting(): cfg = initUp2dateConfig() proxy = None proxyHost = cfg["httpProxy"] if proxyHost: if proxyHost[:7] == "http://": proxy = proxyHost[7:] else: proxy = proxyHost return proxy def getServerlURL(): """ return list of serverURL from config Note: in config may be one value or more values, but this function always return list """ cfg = initUp2dateConfig() # serverURL may be a list in the config file, so by default, grab the # first element. if type(cfg['serverURL']) == type([]): return cfg['serverURL'] else: return [cfg['serverURL']] def initUp2dateConfig(cfg_file = "/etc/sysconfig/rhn/up2date"): """This function is the right way to get at the up2date config.""" global cfg try: cfg = cfg except NameError: cfg = None if cfg == None: cfg = Config(cfg_file) cfg["isatty"] = False if sys.stdout.isatty(): cfg["isatty"] = True return cfg rhnChannel.py000066600000010251150501002420007166 0ustar00 # all the crap that is stored on the rhn side of stuff # updating/fetching package lists, channels, etc import up2dateAuth import up2dateErrors import config import rhnserver import gettext t = gettext.translation('rhn-client-tools', fallback=True) _ = 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 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() 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 label_whitelist.has_key(chan['label']): continue channel = rhnChannel(type = 'up2date', url = cfg["serverURL"]) for key in chan.keys(): if key == "last_modified": channel['version'] = chan['last_modified'] else: channel[key] = chan[key] 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) transaction.pyc000066600000006334150501002420007605 0ustar00Ñò ú4™Pc@sKddkZdadZddd„ƒYZddd„ƒYZd„ZdS( iÿÿÿÿNtTransactionDatacBseZd„Zd„ZRS(cCsAh|_g|id s .+hardware_gudev.pyc000066600000022517150501002420010250 0ustar00Ñò ¹ÏÅZc@sÍddkZddkZddkZddkZddklZlZd„Zd„ZdZ dZ dZ dZ d Z d Zd Zd ZdZdZdZd Zd Zd ZdZdZdZd ZdZdZdZdZd ZdZ dZ!dZ"dZ#d Z$d Z%dZ&dZ'dZ(dZ)d Z*dZ+dZ,dZ-dZ.d Z/d Z0dZ1dZ2dZ3dZ4d Z5d Z6d Z7dZ8dZ9dZ:dZ;d Z<d Z=dZ>d„Z?d„Z@d„ZAd„ZBd„ZCdS(iÿÿÿÿN(tPCItUSBc Cs›tidgƒ}|idƒ|idƒ|idƒ|idƒ|idƒ}g}x9|D]1}|iƒ}h|d6|iƒd6t|ƒd 6d d 6t|ƒd 6t|ƒd 6}|d d(jod|d RARvRxRwRztPCI_CLASS_STORAGE_IPIRytPCI_CLASS_STORAGE_OTHERRmtPCI_CLASS_NETWORK_ETHERNETtPCI_CLASS_NETWORK_TOKEN_RINGtPCI_CLASS_NETWORK_FDDItPCI_CLASS_NETWORK_ATMtPCI_CLASS_NETWORK_OTHERRrtPCI_CLASS_DISPLAY_VGAtPCI_CLASS_DISPLAY_XGAtPCI_CLASS_DISPLAY_3DtPCI_CLASS_DISPLAY_OTHERR~RR€tPCI_CLASS_MULTIMEDIA_PHONEtPCI_CLASS_MULTIMEDIA_OTHERRtPCI_CLASS_BRIDGE_HOSTtPCI_CLASS_BRIDGE_ISAtPCI_CLASS_BRIDGE_EISAtPCI_CLASS_BRIDGE_MCtPCI_CLASS_BRIDGE_PCIR‚tPCI_CLASS_BRIDGE_NUBUSRƒtPCI_CLASS_BRIDGE_RACEWAYtPCI_CLASS_BRIDGE_OTHERR{tPCI_CLASS_COMMUNICATION_SERIALt PCI_CLASS_COMMUNICATION_PARALLELt#PCI_CLASS_COMMUNICATION_MULTISERIALR|tPCI_CLASS_COMMUNICATION_OTHERRnRotPCI_CLASS_INPUT_PENRpR}tPCI_CLASS_INPUT_GAMEPORTtPCI_CLASS_INPUT_OTHERRsRutPCI_CLASS_SERIAL_ACCESStPCI_CLASS_SERIAL_SSARttPCI_CLASS_SERIAL_FIBERtPCI_CLASS_SERIAL_SMBUSR(R)R*RlR„(((s//usr/share/rhn/up2date_client/hardware_gudev.pyts‚     P   ` " hardware.pyc000066600000051402150501002420007051 0ustar00Ñò ºÏÅZc@sïdZddklZlZlZlZddkZddkZddkZddkZddk Z ddk Z ddk Z ddk Z ddk Z e iddeƒZeiZddkZddkZddkZy ddklZlZdZWn5ej o)ddklZlZlZd ZnXyddkZWnej o dZnXei!i"d ƒydd k#l$Z%eZ&Wnej o e'Z&nXda(d a)d „Z*e*ƒZ+e+o+ei,ƒei-ƒZ.e.i/d e+ƒnd„Z0d„Z1d„Z2d„Z3d„Z4d„Z5d„Z6d„Z7d„Z8d„Z9d„Z:d„Z;d„Z<d„Z=d„Z>d„Z?d„Z@d„ZAd „Z$eBd!joCx@e$ƒD]1ZCx'eCiDƒD]ZEd"eEeCeEfGHqÅWHq²WndS(#s1Used to read hardware info from kudzu, /proc, etciÿÿÿÿ(t gethostnamet getaddrinfotAF_INETtAF_INET6Nsrhn-client-toolstfallback(t get_devicestget_computer_infoi(tcheck_hal_dbus_statustget_hal_computertread_halis/usr/share/rhsm(tHardwarecCsttdƒpdStiƒS(Nt get_warnings(thasattrt dmidecodetNoneR (((s)/usr/share/rhn/up2date_client/hardware.pyt dmi_warnings<ss.Warnings collected during dmidecode import: %scCsÆtdjoµtodStiƒ}|itiƒyN|idƒ}tƒ}|o+ti ƒt i ƒ}|i d|ƒnWn,datƒ}|oti ƒndSX|i ƒantS(s= Initialize _dmi_data unless it already exist and returns it tallsdmidecode warnings: iN(t _dmi_dataRt_dmi_not_availableR t dmidecodeXMLt SetResultTypet DMIXML_DOCt QuerySectionRtclear_warningst up2dateLogtinitLogt log_debugtxpathNewContext(tdmixmltdatatdmi_warntlog((s)/usr/share/rhn/up2date_client/hardware.pyt_initialize_dmi_dataHs(      cCsKtƒ}|djodS|i|ƒ}|gjo |diSdSdS(s½ 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. tiN(R Rt xpathEvaltcontent(tpathtdmi_dataR((s)/usr/share/rhn/up2date_client/hardware.pyt get_dmi_datads    cCs tdƒS(st Return Vendor from dmidecode bios information. If this value could not be fetch, returns empty string. s/dmidecode/BIOSinfo/Vendor(R&(((s)/usr/share/rhn/up2date_client/hardware.pyt dmi_vendorsscCs!tdƒ}|p d}n|S(st Return UUID from dmidecode system information. If this value could not be fetch, returns empty string. s7/dmidecode/SystemInfo/SystemUUID[not(@unavailable='1')]R!(R&(tuuid((s)/usr/share/rhn/up2date_client/hardware.pytdmi_system_uuidys  cCsÖtidtiƒphStddƒiƒ}h}d|d }y$t t t|ƒƒd$ƒ|d%Esiis 127.0.0.1cSs|dtijS(i(RÀR(Rä((s)/usr/share/rhn/up2date_client/hardware.pyRåNss::1R!(RÖRRRtfilter(tnetdictt list_of_addrst ipv4_addrst ipv6_addrs((s)/usr/share/rhn/up2date_client/hardware.pyt read_network9s0 cCsh}d|ds‚"                            8 à   ! E  ! C :   ]   rpmUtils.py000066600000012344150501002420006732 0ustar00# some high level utility stuff for rpm handling # Client code for Update Agent # Copyright (c) 1999-2002 Red Hat, Inc. Distributed under GPL. # # Author: Preston Brown # Adrian Likins # # # FIXME: Some exceptions in here are currently in up2date.py # fix by moving to up2dateErrors.py and importing from there # # import os import rpm import transaction import gettext t = gettext.translation('rhn-client-tools', fallback=True) _ = 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 def verifyAllPackages(): """ run the equiv of `rpm -Va`. It aint gonna be fast, but... """ data = {} packages = getInstalledPackageList(getArch=1) ret,missing_packages = verifyPackages(packages) return ret #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': h['name'], 'epoch': h['epoch'], 'version': h['version'], 'release': h['release'], 'installtime': h['installtime'] } if package['epoch'] == None: package['epoch'] = "" if getArch: package['arch'] = h['arch'] # the arch on gpg-pubkeys is "None"... if package['arch']: pkg_list.append(package) elif getInfo: if h['arch']: package['arch'] = h['arch'] if h['cookie']: package['cookie'] = 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 rhnserver.pyc000066600000012416150501002420007274 0ustar00Ñò ºÏÅZc @s|ddkZddkZddkZddkZddklZddkZdefd„ƒYZdefd„ƒYZ dS(iÿÿÿÿN(trpclibt_DoCallWrappercBs2eZdZd„Zd„Zd„Zd„ZRS(se A callable object that will handle multiple levels of attributes, and catch exceptions. cCs||_||_dS(N(t_servert _method_name(tselftservert method_name((s*/usr/share/rhn/up2date_client/rhnserver.pyt__init__%s cCst|id|i|fƒS(s= Recursively build up the method name to pass to the server. s%s.%s(RRR(RR((s*/usr/share/rhn/up2date_client/rhnserver.pyt __getattr__)s c Os1t|i|iƒ}yti|||ŽSWnþtij o}|i|ƒ‚nÙti i j oÆ}t |ƒ}|i dƒ}|i dƒ}d}t|ƒdjo|d}n"t|ƒdjo|d}n|i dƒ}|djotiƒ‚q-ti|ƒdtiƒd‚nXdS( s3 Call the method. Catch faults and translate them. s[()]t,tiis 'scertificate verify failedN(tgetattrRRt rpcServertdoCallRtFaultt$_DoCallWrapper__exception_from_faulttOpenSSLtSSLtErrortstrtstriptsplittlent up2dateErrorstSSLCertificateVerifyFailedErrort NetworkErrortNonetsystexc_info( Rtargstkwargstmethodtfteterrortpiecestmessage((s*/usr/share/rhn/up2date_client/rhnserver.pyt__call__.s$  cCs¨|idjoti|iƒ}n|idjoti|iƒ}nY|idjoti|iƒ}n3|idjoti|iƒ}n |idjoti|iƒ}nç|idjoti|iƒ}nÁ|idjoti|iƒ}n›|idjoti|iƒ}nu|id joti |iƒ}nO|id joti |iƒ}n)t |iƒd joti |iƒ}nýt |iƒd joti |iƒ}nÑt |iƒd joti|iƒ}n¥|idjoti|iƒ}nt |iƒdjoti |iƒ}nS|idjoti|iƒ}n-|idjoti|iƒ}n|idjoti|iƒ}ná|idjoti|iƒ}n»|idjp|idjoti|iƒ}n…|idjoti|iƒ}n_|idjoti|iƒ}n9|idjoti|iƒ}nti|iƒ}|S(NiýÿÿÿiþÿÿÿiÿÿÿÿióÿÿÿiòÿÿÿiñÿÿÿiðÿÿÿiíÿÿÿiáÿÿÿiÜÿÿÿi1i<iiici[i–ÿÿÿi¨ýÿÿi§ýÿÿi¦ýÿÿi/øÿÿiDýÿÿiCýÿÿiÃÿÿÿiûÿÿÿ(t faultCodeRt$AuthenticationOrAccountCreationErrort faultStringtUnknownMethodExceptiontLoginMinLengthErrortPasswordMinLengthErrortValidationErrortNoBaseChannelErrortInsuffMgmntEntsErrort PasswordErrortabst AbuseErrortAuthenticationTicketErrortRhnUuidUniquenessErrort DelayErrortInvalidRegistrationNumberErrortNotEntitlingErrortPasswordMaxLengthErrortActivationKeyUsageLimitErrortUnableToCreateUsertCommunicationError(Rtfaultt exception((s*/usr/share/rhn/up2date_client/rhnserver.pyt__exception_from_faultHsj (t__name__t __module__t__doc__RRR%R(((s*/usr/share/rhn/up2date_client/rhnserver.pyRs    t RhnServercBsGeZdZdddd„Zd„ZeeƒZd„Zd„Z RS(sb An rpc server object that calls doCall for you, and catches lower level exceptions cCsB|djotid|d|ƒ|_n ||_d|_dS(NtserverOverridettimeout(RR t getServerRt _capabilities(RRBRCtrpcServerOverride((s*/usr/share/rhn/up2date_client/rhnserver.pyR˜s   cCsv|idjo_|iiƒ}|djo |iiƒ|iiƒ}ntiƒ|_|ii|ƒn|iS(N( RERRtget_response_headerst registrationtwelcome_messaget capabilitiest Capabilitiestpopulate(Rtheaders((s*/usr/share/rhn/up2date_client/rhnserver.pyt__get_capabilities s  cCs|ii||ƒdS(N(Rt add_header(Rtkeytvalue((s*/usr/share/rhn/up2date_client/rhnserver.pyRO¬scCst|i|ƒS(s8 Return a callable object that will do the work for us. (RR(RR((s*/usr/share/rhn/up2date_client/rhnserver.pyR¯sN( R>R?R@RRt_RhnServer__get_capabilitiestpropertyRJROR(((s*/usr/share/rhn/up2date_client/rhnserver.pyRA‘s   ( RR RRJtrhnRRtobjectRRA(((s*/usr/share/rhn/up2date_client/rhnserver.pyts     shardware.pyo000066600000051402150501002420007065 0ustar00Ñò ºÏÅZc@sïdZddklZlZlZlZddkZddkZddkZddkZddk Z ddk Z ddk Z ddk Z ddk Z e iddeƒZeiZddkZddkZddkZy ddklZlZdZWn5ej o)ddklZlZlZd ZnXyddkZWnej o dZnXei!i"d ƒydd k#l$Z%eZ&Wnej o e'Z&nXda(d a)d „Z*e*ƒZ+e+o+ei,ƒei-ƒZ.e.i/d e+ƒnd„Z0d„Z1d„Z2d„Z3d„Z4d„Z5d„Z6d„Z7d„Z8d„Z9d„Z:d„Z;d„Z<d„Z=d„Z>d„Z?d„Z@d„ZAd „Z$eBd!joCx@e$ƒD]1ZCx'eCiDƒD]ZEd"eEeCeEfGHqÅWHq²WndS(#s1Used to read hardware info from kudzu, /proc, etciÿÿÿÿ(t gethostnamet getaddrinfotAF_INETtAF_INET6Nsrhn-client-toolstfallback(t get_devicestget_computer_infoi(tcheck_hal_dbus_statustget_hal_computertread_halis/usr/share/rhsm(tHardwarecCsttdƒpdStiƒS(Nt get_warnings(thasattrt dmidecodetNoneR (((s)/usr/share/rhn/up2date_client/hardware.pyt dmi_warnings<ss.Warnings collected during dmidecode import: %scCsÆtdjoµtodStiƒ}|itiƒyN|idƒ}tƒ}|o+ti ƒt i ƒ}|i d|ƒnWn,datƒ}|oti ƒndSX|i ƒantS(s= Initialize _dmi_data unless it already exist and returns it tallsdmidecode warnings: iN(t _dmi_dataRt_dmi_not_availableR t dmidecodeXMLt SetResultTypet DMIXML_DOCt QuerySectionRtclear_warningst up2dateLogtinitLogt log_debugtxpathNewContext(tdmixmltdatatdmi_warntlog((s)/usr/share/rhn/up2date_client/hardware.pyt_initialize_dmi_dataHs(      cCsKtƒ}|djodS|i|ƒ}|gjo |diSdSdS(s½ 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. tiN(R Rt xpathEvaltcontent(tpathtdmi_dataR((s)/usr/share/rhn/up2date_client/hardware.pyt get_dmi_datads    cCs tdƒS(st Return Vendor from dmidecode bios information. If this value could not be fetch, returns empty string. s/dmidecode/BIOSinfo/Vendor(R&(((s)/usr/share/rhn/up2date_client/hardware.pyt dmi_vendorsscCs!tdƒ}|p d}n|S(st Return UUID from dmidecode system information. If this value could not be fetch, returns empty string. s7/dmidecode/SystemInfo/SystemUUID[not(@unavailable='1')]R!(R&(tuuid((s)/usr/share/rhn/up2date_client/hardware.pytdmi_system_uuidys  cCsÖtidtiƒphStddƒiƒ}h}d|d }y$t t t|ƒƒd$ƒ|d%Esiis 127.0.0.1cSs|dtijS(i(RÀR(Rä((s)/usr/share/rhn/up2date_client/hardware.pyRåNss::1R!(RÖRRRtfilter(tnetdictt list_of_addrst ipv4_addrst ipv6_addrs((s)/usr/share/rhn/up2date_client/hardware.pyt read_network9s0 cCsh}d|ds‚"                            8 à   ! E  ! C :   ]   up2dateLog.py000066600000004152150501002420007117 0ustar00# # $Id$ import time import string import config import traceback 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() 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: if not isinstance(i, unicode): # we really need unicode(str(i)) here, because i can be anything # from string or int to list, dict or even class i = unicode(str(i), 'utf-8', 'ignore') 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() bar = string.join(traceback.format_list(x)) self.write_log(bar) def log_exception(self, type, 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" % (type, 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" % (self.log_info, s) log_file.write(msg.encode('utf-8')) log_file.flush() log_file.close() def initLog(): global log try: log = log except NameError: log = None if log == None: log = Log() return log up2dateUtils.pyc000066600000004667150501002420007654 0ustar00Ñò ½ÏÅZc @s¦dZddkZddkZddkZddkZddkZddkZeiddeƒZ e i Z d„Z d„Z d„Zd„Zd „Zd „ZdS( sutility functions for up2dateiÿÿÿÿNsrhn-client-toolstfallbackcCsƒtiƒ}tiƒ}xd|iddƒD]A}|do|d}n |d}|d||df}|SWtidƒ‚dS(Nt Providenamesredhat-releasetversionOverridetversiontnametreleases{Could not determine what version of Red Hat Linux you are running. If you get this error, try running rpm --rebuilddb (tconfigtinitUp2dateConfigt transactiontinitReadOnlyTransactiontdbMatcht up2dateErrorstRpmError(tcfgttsthRtosVersionRelease((s-/usr/share/rhn/up2date_client/up2dateUtils.pyt_getOSVersionAndReleases    cCstƒ\}}}t|ƒS(s3 Returns the version of redhat-release rpm (Rtstr(t os_releaseRR((s-/usr/share/rhn/up2date_client/up2dateUtils.pyt getVersion%scCstƒ\}}}|S(s4 Returns the name of the redhat-release rpm (R(RRR((s-/usr/share/rhn/up2date_client/up2dateUtils.pyt getOSRelease,scCstƒ\}}}|S(s7 Returns the release of the redhat-release rpm (R(RRR((s-/usr/share/rhn/up2date_client/up2dateUtils.pyt getRelease3scCsxtidtiƒptiƒdStddƒ}ti|iƒƒ}hdd6}|i|ƒo||}n|S(Ns/etc/rpm/platformitrsx86_64-redhat-linuxsia32e-redhat-linux( tostaccesstR_OKtunametopentstringtstriptreadthas_key(tfdtplatformtreplace((s-/usr/share/rhn/up2date_client/up2dateUtils.pytgetArch:s cCsdS(Ns1.0.0.1-45.el6((((s-/usr/share/rhn/up2date_client/up2dateUtils.pyRJs(t__doc__RRR RRtgettextt translationtTruetttugettextt_RRRRR$R(((s-/usr/share/rhn/up2date_client/up2dateUtils.pyts            up2dateUtils.py000066600000003732150501002420007501 0ustar00# Client code for Update Agent # Copyright (c) 1999-2002 Red Hat, Inc. Distributed under GPL. # # Author: Preston Brown # Adrian Likins # """utility functions for up2date""" import os import string import up2dateErrors import transaction import config import gettext t = gettext.translation('rhn-client-tools', fallback=True) _ = t.ugettext def _getOSVersionAndRelease(): cfg = config.initUp2dateConfig() ts = transaction.initReadOnlyTransaction() for h in ts.dbMatch('Providename', "redhat-release"): if cfg["versionOverride"]: version = cfg["versionOverride"] else: version = h['version'] osVersionRelease = (h['name'], version, h['release']) return osVersionRelease else: raise up2dateErrors.RpmError( "Could not determine what version of Red Hat Linux 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 ''' os_release, version, release = _getOSVersionAndRelease() return str(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 not os.access("/etc/rpm/platform", os.R_OK): return os.uname()[4] fd = open("/etc/rpm/platform", "r") platform = string.strip(fd.read()) #bz 216225 #handle some replacements.. replace = {"ia32e-redhat-linux": "x86_64-redhat-linux"} if replace.has_key(platform): platform = replace[platform] return platform def version(): # substituted to the real version by the Makefile at installation time. return "1.0.0.1-45.el6" up2dateLog.pyo000066600000006244150501002420007302 0ustar00Ñò ºÏÅZc@sPddkZddkZddkZddkZddd„ƒYZd„ZdS(iÿÿÿÿNtLogcBsMeZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z RS(s„ attempt to log all interesting stuff, namely, anything that hits the network any error messages, package installs, etc cCsd|_tiƒ|_dS(Ntup2date(tapptconfigtinitUp2dateConfigtcfg(tself((s+/usr/share/rhn/up2date_client/up2dateLog.pyt__init__s cCst|ƒ|_dS(N(tstrR(Rtname((s+/usr/share/rhn/up2date_client/up2dateLog.pyt set_app_namescGs,|iddjo|id|ŒndS(NtdebugisD: (Rtlog_me(Rtargs((s+/usr/share/rhn/up2date_client/up2dateLog.pyt log_debugscGs dtitiƒƒ|if|_d}xD|D]<}t|tƒptt|ƒddƒ}n||7}q2W|iddjo |GHn|i|ƒdS(sPGeneral logging function. Eg: log_me("I am a banana.") s[%s] %susutf-8tignoreR iN( ttimetctimeRtlog_infot isinstancetunicodeRRt write_log(RR tsti((s+/usr/share/rhn/up2date_client/up2dateLog.pyR s% cCsZdtitiƒƒ|if|_tiƒ}titi|ƒƒ}|i |ƒdS(Ns[%s] %s( RRRRt tracebackt extract_stacktstringtjoint format_listR(Rtxtbar((s+/usr/share/rhn/up2date_client/up2dateLog.pyttrace_me*s% cCsˆdtitiƒƒ|if|_dg}|idƒ|titi|ƒƒ}|id||fƒ|idi |ƒƒdS(Ns[%s] %ss s#Traceback (most recent call last): s%s: %s t( RRRRtappendRRt extract_tbRR(Rttypetvaluettbtoutput((s+/usr/share/rhn/up2date_client/up2dateLog.pyt log_exception0s %  cCsd|idpd}t|dƒ}d|i|f}|i|idƒƒ|iƒ|iƒdS(NtlogFiles/var/log/up2datetau%s %s sutf-8(RtopenRtwritetencodetflushtclose(RRtlog_nametlog_filetmsg((s+/usr/share/rhn/up2date_client/up2dateLog.pyR8s  ( t__name__t __module__t__doc__RR RR RR'R(((s+/usr/share/rhn/up2date_client/up2dateLog.pyR s      cCsDy taWntj o danXtdjo tƒantS(N(tlogt NameErrortNoneR(((s+/usr/share/rhn/up2date_client/up2dateLog.pytinitLogAs    ((RRRRRR8(((s+/usr/share/rhn/up2date_client/up2dateLog.pyts    8up2dateLog.pyc000066600000006244150501002420007266 0ustar00Ñò ºÏÅZc@sPddkZddkZddkZddkZddd„ƒYZd„ZdS(iÿÿÿÿNtLogcBsMeZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z RS(s„ attempt to log all interesting stuff, namely, anything that hits the network any error messages, package installs, etc cCsd|_tiƒ|_dS(Ntup2date(tapptconfigtinitUp2dateConfigtcfg(tself((s+/usr/share/rhn/up2date_client/up2dateLog.pyt__init__s cCst|ƒ|_dS(N(tstrR(Rtname((s+/usr/share/rhn/up2date_client/up2dateLog.pyt set_app_namescGs,|iddjo|id|ŒndS(NtdebugisD: (Rtlog_me(Rtargs((s+/usr/share/rhn/up2date_client/up2dateLog.pyt log_debugscGs dtitiƒƒ|if|_d}xD|D]<}t|tƒptt|ƒddƒ}n||7}q2W|iddjo |GHn|i|ƒdS(sPGeneral logging function. Eg: log_me("I am a banana.") s[%s] %susutf-8tignoreR iN( ttimetctimeRtlog_infot isinstancetunicodeRRt write_log(RR tsti((s+/usr/share/rhn/up2date_client/up2dateLog.pyR s% cCsZdtitiƒƒ|if|_tiƒ}titi|ƒƒ}|i |ƒdS(Ns[%s] %s( RRRRt tracebackt extract_stacktstringtjoint format_listR(Rtxtbar((s+/usr/share/rhn/up2date_client/up2dateLog.pyttrace_me*s% cCsˆdtitiƒƒ|if|_dg}|idƒ|titi|ƒƒ}|id||fƒ|idi |ƒƒdS(Ns[%s] %ss s#Traceback (most recent call last): s%s: %s t( RRRRtappendRRt extract_tbRR(Rttypetvaluettbtoutput((s+/usr/share/rhn/up2date_client/up2dateLog.pyt log_exception0s %  cCsd|idpd}t|dƒ}d|i|f}|i|idƒƒ|iƒ|iƒdS(NtlogFiles/var/log/up2datetau%s %s sutf-8(RtopenRtwritetencodetflushtclose(RRtlog_nametlog_filetmsg((s+/usr/share/rhn/up2date_client/up2dateLog.pyR8s  ( t__name__t __module__t__doc__RR RR RR'R(((s+/usr/share/rhn/up2date_client/up2dateLog.pyR s      cCsDy taWntj o danXtdjo tƒantS(N(tlogt NameErrortNoneR(((s+/usr/share/rhn/up2date_client/up2dateLog.pytinitLogAs    ((RRRRRR8(((s+/usr/share/rhn/up2date_client/up2dateLog.pyts    8rhnHardware.pyc000066600000001036150501002420007517 0ustar00Ñò ú4™Pc@s1ddkZddkZddkZd„ZdS(iÿÿÿÿNcCs5tiƒ}tiƒ}|iitiƒ|ƒdS(N(t rpcServert getServerthardwaretHardwaret registrationtrefresh_hw_profilet up2dateAutht getSystemId(tst hardwareList((s,/usr/share/rhn/up2date_client/rhnHardware.pytupdateHardwares  (RRRR (((s,/usr/share/rhn/up2date_client/rhnHardware.pyts   hwdata.py000066600000015130150501002420006357 0ustar00# # Copyright (c) 1999--2010 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. # """ Query hwdata database and return decription of vendor and/or device. """ class USB: """ Interace to usb.ids from hwdata package """ filename = '/usr/share/hwdata/usb.ids' devices = None def __init__(self, filename=None): """ Load pci.ids from file to internal data structure. parameter 'filename' can specify location of this file """ if filename: self.filename = filename else: self.filename = USB.filename self.cache = 1 if self.cache and not USB.devices: # parse usb.ids USB.devices = {} for line in open(self.filename).readlines(): l = line.split() if line.startswith('#'): if line.startswith('# List of known device classes, subclasses and protocols'): break # end of database of devices, rest is protocols, types etc. else: continue elif len(l) == 0: continue elif line.startswith('\t\t'): interface_id = l[0].lower() if len(l) > 2: interface_name = ' '.join(l[1:]) else: interface_name = '' USB.devices[vendor][1][device][0][interface_id] = interface_name elif line.startswith('\t'): device = l[0].lower() device_name = ' '.join(l[1:]) USB.devices[vendor][1][device] = [device_name, {}] else: vendor = l[0].lower() vendor_name = ' '.join(l[1:]) if not USB.devices.has_key(vendor): USB.devices[vendor] = [vendor_name, {}] else: # this should not happen USB.devices[vendor][0] = vendor_name def get_vendor(self, vendor): """ Return description of vendor. Parameter is two byte code in hexa. If vendor is unknown None is returned. """ vendor = vendor.lower() if self.cache: if USB.devices.has_key(vendor): return USB.devices[vendor][0] else: return None else: raise # not implemented yet def get_device(self, vendor, device): """ Return description of device. Parameters are two byte code variables in hexa. If device is unknown None is returned. """ vendor = vendor.lower() if device == None: return None device = device.lower() if self.cache: if USB.devices.has_key(vendor): if USB.devices[vendor][1].has_key(device): return USB.devices[vendor][1][device][0] else: return None else: return None else: raise # not implemented yet class PCI: """ Interace to pci.ids from hwdata package """ filename = '/usr/share/hwdata/pci.ids' devices = None def __init__(self, filename=None): """ Load pci.ids from file to internal data structure. parameter 'filename' can specify location of this file """ if filename: self.filename = filename else: self.filename = PCI.filename self.cache = 1 if self.cache and not PCI.devices: # parse pci.ids pcirec = {} PCI.devices = {} for line in open(self.filename).readlines(): l = line.split() if line.startswith('#'): continue elif len(l) == 0: continue elif line.startswith('\t\t'): subvendor = l[0].lower() if len(l) > 2: subdevice = l[1].lower() else: subdevice = '' if len(l) > 3: subsystem_name = ' '.join(l[2:]) else: subsystem_name = '' if not PCI.devices.has_key(subvendor): PCI.devices[subvendor] = [vendor_name, {subdevice: subsystem_name}] else: # this should not happen PCI.devices[subvendor][1][subdevice] = subsystem_name elif line.startswith('\t'): device = l[0].lower() device_name = ' '.join(l[1:]) PCI.devices[vendor][1][device] = device_name else: vendor = l[0].lower() vendor_name = ' '.join(l[1:]) if not PCI.devices.has_key(vendor): PCI.devices[vendor] = [vendor_name, {}] else: # this should not happen PCI.devices[vendor][0] = vendor_name def get_vendor(self, vendor): """ Return description of vendor. Parameter is two byte code in hexa. If vendor is unknown None is returned. """ vendor = vendor.lower() if self.cache: if PCI.devices.has_key(vendor): return PCI.devices[vendor][0] else: return None else: raise # not implemented yet def get_device(self, vendor, device): """ Return description of device. Parameters are two byte code variables in hexa. If device is unknown None is returned. """ vendor = vendor.lower() if device == None: return None device = device.lower() if self.cache: if PCI.devices.has_key(vendor): if PCI.devices[vendor][1].has_key(device): return PCI.devices[vendor][1][device] else: return None else: return None else: raise # not implemented yet rhnChannel.pyo000066600000012470150501002420007352 0ustar00Ñò ¹ÏÅZc @sÉddkZddkZddkZddkZddkZeiddeƒZeiZ dd d„ƒYZ ddd„ƒYZ dd„Z gZdadddd „Zd „Zd „Zd „ZdS(iÿÿÿÿNsrhn-client-toolstfallbackt rhnChannelcBs>eZd„Zd„Zd„Zd„Zd„Zd„ZRS(cKs5h|_x%|iƒD]}|||i|eZd„Zd„Zd„Zd„Zd„Zd„ZRS(cCs g|_dS(N(tlist(R((s+/usr/share/rhn/up2date_client/rhnChannel.pyR'scCs|ii|ƒdS(N(Rtappend(Rtchannel((s+/usr/share/rhn/up2date_client/rhnChannel.pyt addChannel,scCs|iS(N(R(R((s+/usr/share/rhn/up2date_client/rhnChannel.pytchannels0scCs.x'|iD]}|d|jo|Sq WdS(Ntlabel(R(Rt channelnameR((s+/usr/share/rhn/up2date_client/rhnChannel.pyt getByLabel3s cCs |i|ƒS(N(R(RR((s+/usr/share/rhn/up2date_client/rhnChannel.pyt getByName7scCs@g}x3|iD](}|d|jo|i|ƒqqW|S(Nttype(RR(RRRR((s+/usr/share/rhn/up2date_client/rhnChannel.pyt getByType:s  (RRRRRRRR(((s+/usr/share/rhn/up2date_client/rhnChannel.pyR&s      cCsƒg}td|ƒ}xg|iƒD]Y}|ddjo5|d|dysR7(tNoneR*RtmapR!(t tempchannelst whitelist((s+/usr/share/rhn/up2date_client/rhnChannel.pyt setChannelsvscCs+tiƒ}|iitiƒ|||ƒS(N(R+R,RtsubscribeChannelsR-R.(RtusernametpasswdR9((s+/usr/share/rhn/up2date_client/rhnChannel.pyRD~s cCs+tiƒ}|iitiƒ|||ƒS(N(R+R,RtunsubscribeChannelsR-R.(RRERFR9((s+/usr/share/rhn/up2date_client/rhnChannel.pyRGƒs (((R-R/R(R+tgettextt translationtTruetttugettextR1RRR?R$t cmdline_pkgsR*R!RCRDRG(((s+/usr/share/rhn/up2date_client/rhnChannel.pyts         rhnserver.py000066600000017017150501002420007133 0ustar00 # rhn-client-tools # # Copyright (C) 2006 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; either version 2 of the License, or # (at your option) any later version. # # 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 import sys import rpcServer import up2dateErrors import capabilities from rhn import rpclib import OpenSSL 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 rpclib.Fault, f: raise self.__exception_from_fault(f) except OpenSSL.SSL.Error, e: # 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(e) 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 up2dateErrors.SSLCertificateVerifyFailedError() else: raise up2dateErrors.NetworkError(message), None, sys.exc_info()[2] 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 == -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) == 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): if rpcServerOverride is None: self._server = rpcServer.getServer(serverOverride=serverOverride, timeout=timeout) 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) hwdata.pyc000066600000011271150501002420006524 0ustar00Ñò ºÏÅZc@s0dZddd„ƒYZddd„ƒYZdS(sF Query hwdata database and return decription of vendor and/or device. tUSBcBs8eZdZdZdZdd„Zd„Zd„ZRS(s) Interace to usb.ids from hwdata package s/usr/share/hwdata/usb.idsc Csâ|o ||_n ti|_d|_|io«ti o ht_x”t|iƒiƒD]y}|iƒ}|idƒo|idƒoPqÖq]q]t|ƒdjoq]q]|idƒoa|di ƒ}t|ƒdjodi |dƒ}nd}|ti|d|d|sNrpmUtils.pyo000066600000007213150501002420007110 0ustar00Ñò ú4™Pc @s‚ddkZddkZddkZddkZeiddeƒZeiZd„Z d„Z d„Z ddddd„Z dS(iÿÿÿÿNsrhn-client-toolstfallbackcKsqtiƒ}|iƒ}x.|iƒD] }|i|ti||ƒq%Wg}x|D]}|i|ƒqVW|S(s@ just cause this is such a potentially useful looking method... (t transactiontinitReadOnlyTransactiontdbMatchtkeystpatterntrpmt RPMMIRE_GLOBtappend(tkwargst_tstmitkeywordt headerListth((s)/usr/share/rhn/up2date_client/rpmUtils.pytinstalledHeaderByKeywords   c Cs h}g}g}xî|D]æ}h|dd6|dd6|dd6|dd6}xA|iƒD]3}||djp||d jo ||=q^q^Wt|}t|ƒdjo|i|ƒnx7|D]/}|d } | djo d } n|d} | djo d } n|d|d|d| | f} |dd jo#d | d| d| df} n'd | d| d| d| df} d | } ti| ƒ}|iƒ}|iƒg}x!|D]}|i|i ƒƒqËW|i| |gƒqÌWqW||fS(sf given a list of package labels, run rpm -V on them and return a dict keyed off that data itnameitversionitreleaseitarchttepochs%s-%s-%ss %s-%s-%s.%ss/usr/bin/rpmverify -V %sN( RtNoneRtlenRtostpopent readlinestclosetstrip(tpackagestdatatmissing_packagestretlisttpackagetkeywordstkeytheaderstheaderRRtpkgt packageLabelt verifystringtfdtrestreslisttline((s)/usr/share/rhn/up2date_client/rpmUtils.pytverifyPackages&sP   "         #&   cCs+h}tddƒ}t|ƒ\}}|S(sG run the equiv of `rpm -Va`. It aint gonna be fast, but... tgetArchi(tgetInstalledPackageListR-(RRtretR((s)/usr/share/rhn/up2date_client/rpmUtils.pytverifyAllPackagesfsc CsÖg}|djo|tdƒƒntiƒ}d}d}x0|iƒD]"}|djoPn|d}qLW|}d}x>|iƒD]0}|djoPnh|dd6|dd6|dd6|dd6|dd6} | ddjod | d§sN(Rt_RRRRtsort( t msgCallbacktprogressCallbackR.tgetInfotpkg_listR tcountttotalRR!((s)/usr/share/rhn/up2date_client/rpmUtils.pyR/ssR               (RRRtgettextt translationtTruetttugettextR6RR-R1RR/(((s)/usr/share/rhn/up2date_client/rpmUtils.pyts      @ transaction.py000066600000010046150501002420007435 0ustar00 # # Client code for Update Agent # Copyright (c) 1999-2002 Red Hat, Inc. Distributed under GPL. # # Adrian Likins |iƒD]0}|djoPnh|dd6|dd6|dd6|dd6|dd6} | ddjod | d§sN(Rt_RRRRtsort( t msgCallbacktprogressCallbackR.tgetInfotpkg_listR tcountttotalRR!((s)/usr/share/rhn/up2date_client/rpmUtils.pyR/ssR               (RRRtgettextt translationtTruetttugettextR6RR-R1RR/(((s)/usr/share/rhn/up2date_client/rpmUtils.pyts      @ config.pyo000066600000024101150501002420006531 0ustar00Ñò ºÏÅZc @sdZddkZddkZddkZeiddeƒZeiZh d.d6d/d 6d0d 6d1d6d2d6d3d6d4d6d5d6d6d6d7d6d8d 6d9d"6d#d d d$d"gfd$6Z dd d%gZ d&d:d'„ƒYZ d(d;d)„ƒYZ d*„Z d+„Zd,d-„ZdS(<sj This module includes the Config and Up2date Config classes use by the up2date agent to hold config info. iÿÿÿÿNsrhn-client-toolstfallbacksUse a HTTP Proxyit enableProxysRemote server URLs$https://xmlrpc.rhn.redhat.com/XMLRPCt serverURLs#Whether or not debugging is enabledtdebugsLocation of system ids/etc/sysconfig/rhn/systemidt systemIdPaths4Override the automatically determined system versionttversionOverrides:HTTP proxy in host:port format, e.g. squid.redhat.com:3128t httpProxys'The username for an authenticated proxyt proxyUsers.The password to use for an authenticated proxyt proxyPasswords$To use an authenticated proxy or nottenableProxyAuthsBNumber of attempts to make at network connections before giving upitnetworkRetriess)The CA cert used to verify the ssl servers/usr/share/rhn/RHNS-CA-CERTt sslCACertsDisable the reboot actiontnoRebootsDConfig options that can not be overwritten by a config update actiontdisallowConfChangesttmpDirt ConfigFilecBsneZdZd d„Zd d„Zd„Zd„Zd„Zd„Z d„Z d„Z d „Z d „Z RS( s;class for handling persistent config options for the clientcCs.h|_||_|io|iƒndS(N(tdicttfileNametload(tselftfilename((s'/usr/share/rhn/up2date_client/config.pyt__init__=s   cCs»|o ||_n|idjodSti|itiƒpdSt|idƒ}d}xK|iƒD]=}|idƒdjoqln||iƒ}|pqln|ddjo|d iƒ}qlnd}|i ddƒ}t |ƒd joqln|diƒ}|diƒ}d}|id ƒ} | djo|| }|}d}n|oÀ|i d ƒ} |djot |ƒ}q*t | ƒdjo*yt |ƒ}Wq&t j oq&Xq*| ddjo g}q*g} | D]$} | iƒo| | iƒqùqù~ }n||f} |ii|ƒoS|i|} |dj o|| df} n|dj o| d|f} qœn| |i|µs(R>RR1(R((s'/usr/share/rhn/up2date_client/config.pyR1´scCs|ii|ƒdS(N(Rtupdate(RR((s'/usr/share/rhn/up2date_client/config.pyRE·scCs'|ii|ƒo|i|dSdS(Ni(RR(R(RRB((s'/usr/share/rhn/up2date_client/config.pyt __getitem__¼scCsE|ii|ƒo|i|}nd}|d|f|i|tƒ}t|dƒtgƒjo |dS|dgSdS(s return list of serverURL from config Note: in config may be one value or more values, but this function always return list RN(RXR<(RY((s'/usr/share/rhn/up2date_client/config.pyt getServerlURL)s  s/etc/sysconfig/rhn/up2datecCsoy taWntj o danXtdjo8t|ƒattd sN     –K rhnPackageInfo.pyo000066600000004637150501002420010157 0ustar00Ñò ¹ÏÅZc@s[ddkZddkZddkZddkZd„Zdd„Zd„Zd„ZdS(iÿÿÿÿNcCsFtiƒ}|idt|dƒƒ|idt|dƒƒdS(Ns&Adding packages to package profile: %staddeds*Removing packages from package profile: %stremoved(t up2dateLogtinitLogtlog_metpprint_pkglist(tpkgstlog((s//usr/share/rhn/up2date_client/rhnPackageInfo.pytlogDeltaPackages s    cCs€tiƒ}|idƒtiddƒ}tid|ƒ}|iiddƒpt |ƒ}n|i i t i ƒ|ƒdS(s; get a list of installed packages and send it to rhnServer sUpdating package profiletgetArchittimeouts xmlrpc.packages.extended_profileiN(RRRtrpmUtilstgetInstalledPackageListt rhnservert RhnServert capabilitiest hasCapabilitytconvertPackagesFromHashToListt registrationtupdate_packagest up2dateAutht getSystemId(R Rtpackagests((s//usr/share/rhn/up2date_client/rhnPackageInfo.pytupdatePackageProfiles  cCsRt|ƒtgƒjotd„|ƒ}n d|d|d|df}|S(NcSsd|d|d|dfS(s%s-%s-%siii((ta((s//usr/share/rhn/up2date_client/rhnPackageInfo.pyt ss%s-%s-%siii(ttypetmap(tpkglisttoutput((s//usr/share/rhn/up2date_client/rhnPackageInfo.pyRsc Csãg}xÖ|D]Î}|idƒoK|idƒo;|i|d|d|d|d|d|dgƒq |idƒo4|i|d|d|d|d|dgƒq |i|d|d|d|dgƒq W|S(s– takes list of hashes and covert it to list of lists resulting strucure is: [[name, version, release, epoch, arch, cookie], ... ] tarchtcookietnametversiontreleasetepoch(thas_keytappend(Rtresulttpackage((s//usr/share/rhn/up2date_client/rhnPackageInfo.pyR%s  -( RRR R RtNoneRRR(((s//usr/share/rhn/up2date_client/rhnPackageInfo.pyts      clientCaps.pyc000066600000005031150501002420007336 0ustar00Ñò ú4™Pc @s;ddkZddkZddkZddkZddkZdeifd„ƒYZeƒZdd„Zeƒd„Zedhdd 6dd 6ƒed hdd 6dd 6ƒed hdd 6dd 6ƒed hdd 6dd 6ƒedhdd 6dd 6ƒedhdd 6dd 6ƒedhdd 6dd 6ƒdS(iÿÿÿÿNtClientCapabilitiescBs&eZd„Zdd„Zd„ZRS(cCstii|ƒ|iƒdS(N(tUserDictt__init__tpopulate(tself((s+/usr/share/rhn/up2date_client/clientCaps.pyR scCs9hhdd6dd6d6}|o |}n||_dS(Nitversiontvaluet caneatCheese(tdata(RtcapsToPopulatet localcaps((s+/usr/share/rhn/up2date_client/clientCaps.pyRs  cCsfg}xY|iiƒD]H}d}d||i|d|i|df}|i||fƒqW|S(NsX-RHN-Client-Capabilitys %s(%s)=%sRR(Rtkeystappend(Rt headerListtkeyt headerNameR((s+/usr/share/rhn/up2date_client/clientCaps.pyt headerFormatsN(t__name__t __module__RtNoneRR(((s+/usr/share/rhn/up2date_client/clientCaps.pyR s  s/etc/sysconfig/rhn/clientCaps.dcCsÝtid|ƒ}xÃ|D]»}tii|ƒoqnti|tiƒpqnt|dƒ}xl|iƒD]^}ti |ƒ|ddjoqsnt i |ƒ}x!|D]\}}|t i |s        clientCaps.py000066600000004203150501002420007173 0ustar00 # a dict with "capability name" as the key, and the version # as the value. import UserDict import glob import os import string import capabilities 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(): string.strip(line) if line[0] == "#": continue caplist = capabilities.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.verifyAll", {'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'}) rhnPackageInfo.pyc000066600000004637150501002420010143 0ustar00Ñò ¹ÏÅZc@s[ddkZddkZddkZddkZd„Zdd„Zd„Zd„ZdS(iÿÿÿÿNcCsFtiƒ}|idt|dƒƒ|idt|dƒƒdS(Ns&Adding packages to package profile: %staddeds*Removing packages from package profile: %stremoved(t up2dateLogtinitLogtlog_metpprint_pkglist(tpkgstlog((s//usr/share/rhn/up2date_client/rhnPackageInfo.pytlogDeltaPackages s    cCs€tiƒ}|idƒtiddƒ}tid|ƒ}|iiddƒpt |ƒ}n|i i t i ƒ|ƒdS(s; get a list of installed packages and send it to rhnServer sUpdating package profiletgetArchittimeouts xmlrpc.packages.extended_profileiN(RRRtrpmUtilstgetInstalledPackageListt rhnservert RhnServert capabilitiest hasCapabilitytconvertPackagesFromHashToListt registrationtupdate_packagest up2dateAutht getSystemId(R Rtpackagests((s//usr/share/rhn/up2date_client/rhnPackageInfo.pytupdatePackageProfiles  cCsRt|ƒtgƒjotd„|ƒ}n d|d|d|df}|S(NcSsd|d|d|dfS(s%s-%s-%siii((ta((s//usr/share/rhn/up2date_client/rhnPackageInfo.pyt ss%s-%s-%siii(ttypetmap(tpkglisttoutput((s//usr/share/rhn/up2date_client/rhnPackageInfo.pyRsc Csãg}xÖ|D]Î}|idƒoK|idƒo;|i|d|d|d|d|d|dgƒq |idƒo4|i|d|d|d|d|dgƒq |i|d|d|d|dgƒq W|S(s– takes list of hashes and covert it to list of lists resulting strucure is: [[name, version, release, epoch, arch, cookie], ... ] tarchtcookietnametversiontreleasetepoch(thas_keytappend(Rtresulttpackage((s//usr/share/rhn/up2date_client/rhnPackageInfo.pyR%s  -( RRR R RtNoneRRR(((s//usr/share/rhn/up2date_client/rhnPackageInfo.pyts      capabilities.py000066600000016546150501002420007554 0ustar00 import UserDict import config import up2dateErrors import string import gettext t = gettext.translation('rhn-client-tools', fallback=True) _ = 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.remaining_subscriptions": {'version': '1'}, "registration.update_contact_info": {'version': "1"}, "registration.extended_update_support": {"version" : "1"}, "registration.smbios": {"version" : "1"}} def parseCap(capstring): value = None caps = string.split(capstring, ',') capslist = [] for cap in caps: try: (key_version, value) = map(string.strip, string.split(cap, "=", 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) = string.split(key_version, "(", 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 in headers.keys(): if key == "x-rhn-server-capability": capslist = parseCap(headers[key]) for (cap,data) in capslist: self.data[cap] = data def parseCapVersion(self, versionString): index = string.find(versionString, '-') # version of "-" is bogus, ditto for "1-" if index > 0: rng = string.split(versionString, "-") start = rng[0] end = rng[1] versions = range(int(start), int(end)+1) return versions vers = string.split(versionString, ':') if len(vers) > 1: versions = map(lambda a:int(a), vers) return versions return [int(versionString)] def validateCap(self, cap, capvalue): if not self.data.has_key(cap): 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 self.tmpCaps.has_key(key): 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 self.tmpCaps.has_key(key): # 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.remaining_subscriptions" : 'supportsRemainingSubscriptions', "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 self.data.has_key(capability): return False if version: data = self.data[capability] if int(version) not in self.parseCapVersion(data['version']): return False return True rhncli.pyc000066600000020171150501002420006532 0ustar00Ñò ú4™Pc@s½ddkZddkZddkZddkZddkZddklZddklZddkl Z ddkl Z ddk l Z ddk Z e iddeƒZeiZeiid ƒdd klZdd klZdd klZdd klZddklZd„ZedddddddedƒƒeddddedƒƒeddddedƒƒeddddedƒƒgZdefd „ƒYZd!„ZdS("iÿÿÿÿN(tOption(t OptionParser(tSSL(tcrypto(trpclibsrhn-client-toolstfallbacks/usr/share/rhn/(tconfig(t up2dateAuth(t up2dateErrors(t up2dateLog(t up2dateUtilscCs't|tƒo|idƒ}n|S(sg python 2.6- (i.e. RHEL6 and older) could not write unicode to stderr, encode it to utf-8. sutf-8(t isinstancetunicodetencode(tmsg((s'/usr/share/rhn/up2date_client/rhncli.pyt utf8_encode0ss-vs --verbosetactiontcounttdefaultithelpsShow additional outputs--proxytstoresSpecify an http proxy to uses --proxyUsers:Specify a username to use with an authenticated http proxys--proxyPasswords:Specify a password to use with an authenticated http proxytRhnClicBsweZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z e d „ƒZ e d „ƒZ RS( cCs=tdtdtiƒƒ|_d|_d|_t|_ dS(Nt option_listtversion( Rt _optionsTableRt_RhnCli__versionStringt optparsertNonetoptionstargstFalsethasGui(tself((s'/usr/share/rhn/up2date_client/rhncli.pyt__init__Es    cCs7tt_y(|iƒti|iƒpdƒWnÿtj o0tiit t dƒƒƒtidƒnÅt j o6}tiit t dƒ|ƒƒtidƒn„t i j oo}|djptt|ƒƒdjo tiit t dƒƒƒq3tiit t dƒ|ƒƒntj o6}tiit t dƒ|ƒƒtidƒnÆtij oR}tiit t dƒ|ƒƒtiit t d ƒƒƒtidƒnftitifj o6}tiit d t|ƒƒƒtid ƒntij o)}tiit t d ƒ|ƒƒnâtj o}|‚nÈtij o6}tiit t d ƒ|ƒƒtidƒn„tij o0}tiit d|ƒƒtidƒnFtij o6}tiit dt|ƒƒƒtidƒnXdS(Nis Aborted. is$An unexpected OS error occurred: %s s1A connection was attempted with a malformed URI. s5A connection was attempted with a malformed URI: %s. s%There was some sort of I/O error: %s sThere was an SSL error: %s sqA common cause of this error is the system time being incorrect. Verify that the time on this system is correct. sOpenSSL.SSL.SysCallError: %s is!There was a SSL crypto error: %s s&There was an authentication error: %s s%s sXMLRPC ProtocolError: %s i(texceptionHandlertsyst excepthookt initializetexittmaintKeyboardInterrupttstderrtwriteRt_tOSErrorRtMalformedURIErrorRtlentstrtIOErrorRtErrort SysCallErrortsocketterrorRt SystemExitRtAuthenticationErrortRpmErrort xmlrpclibt ProtocolError(R te((s'/usr/share/rhn/up2date_client/rhncli.pytrunNsJ   & $   $   cCs„|iiƒ\|_|_ti|iiƒtiƒdjo5t dƒt i d}|i |ƒt i dƒn|iƒdS(NisYou must be root to run %si(Rt parse_argsRRRt_RhnCli__setDebugLeveltverbosetostgeteuidR+R#targvt_warning_dialogR&t_RhnCli__updateProxyConfig(R trootWarningMsg((s'/usr/share/rhn/up2date_client/rhncli.pyR%ys cCs t‚dS(N(tNotImplementedError(R ((s'/usr/share/rhn/up2date_client/rhncli.pyR'†scCs“ytiƒtSWnztij o}|GHtStij o }tStij o6}ti ƒ}|i dƒ|i t i ƒŒtSXdS(Ns4There was a RhnServerException while testing login: (RtupdateLoginInfotTrueRtServerCapabilityErrorRR6tRhnServerExceptionR tinitLogtlog_met log_exceptionR#texc_info(R R:tlog((s'/usr/share/rhn/up2date_client/rhncli.pyt _testRhnLogin‰s   cCsR|io?y!ddkl}|i|ƒWqNtdƒGH|GHqNXn|GHdS(Niÿÿÿÿ(tguis'Unable to open gui. Try `up2date --nox`(Rtup2date_clientRPt errorWindowR+(R tmessageRP((s'/usr/share/rhn/up2date_client/rhncli.pyRB˜s   cCsµtiƒ}|iio*|id|iiƒ|iddƒn|iio*|id|iiƒ|iddƒn|iio*|id|iiƒ|iddƒndS(sÀ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. t httpProxyt enableProxyit proxyUsertenableProxyAutht proxyPasswordN(RtinitUp2dateConfigRtproxytsetRVRX(R tcfg((s'/usr/share/rhn/up2date_client/rhncli.pyt__updateProxyConfig£s    cCstiƒ}|iƒdS(sM Saves the current up2date configuration being used to disk. N(RRYtsave(R R\((s'/usr/share/rhn/up2date_client/rhncli.pyt saveConfig´s cCsR|io?y!ddkl}|i|ƒWqNtdƒGH|GHqNXn|GHdS(Niÿÿÿÿ(RPs'Unable to open gui. Try `up2date --nox`(RRQRPRRR+(R terrMsgRP((s'/usr/share/rhn/up2date_client/rhncli.pyt __faultError»s   cCstdƒtiƒ}|S(Nsv%%prog (Red Hat Network Client Tools) %s Copyright (C) 1999--2010 Red Hat, Inc. Licensed under the terms of the GPLv2.(R+R R(t versionString((s'/usr/share/rhn/up2date_client/rhncli.pyt__versionStringÆs  cCsftiƒ}|d||d<|ddjo3ytitiƒWqbtj o dGHqbXndS(Ntdebugis4extra verbosity not supported in this version of rpm(RRYtrpmt setVerbosityt RPMLOG_DEBUGtAttributeError(tlevelR\((s'/usr/share/rhn/up2date_client/rhncli.pyt__setDebugLevelÍs (t__name__t __module__R!R;R%R'RORBRCR_t_RhnCli__faultErrort staticmethodRR=(((s'/usr/share/rhn/up2date_client/rhncli.pyRCs +     cCsÇtiƒ}tiittdƒdƒƒt|dƒo4tiit|iƒdƒ|i |||ƒn4tiitt |ƒdƒƒ|i |||ƒtiittdƒdƒƒdS(NsAn error has occurred:s terrmsgs)See /var/log/up2date for more information( R RJR#R)R*RR+thasattrRoRLR/(ttypetvaluettbRN((s'/usr/share/rhn/up2date_client/rhncli.pyR"Ùs   ( R#R?ReR8R3toptparseRRtOpenSSLRRtrhnRtgettextt translationRGtttugettextR+tpathtappendRQRRRR R RRtobjectRR"(((s'/usr/share/rhn/up2date_client/rhncli.pyts:           –up2dateAuth.pyo000066600000013652150501002420007463 0ustar00Ñò ¹ÏÅZc@sÿddkZddkZddkZddkZddkZddkZddkZddkZddkZddk Z ddk l Z ddk l Z dadZd„Zd„Zd„Zd„Zd „Zdedd „Zdd „Zdd „ZdS( iÿÿÿÿN(tDictType(trpclibs /var/spool/up2date/loginAuth.pklcCsZtiƒ}|d}ti|tiƒpdSt|dƒ}|iƒ}|iƒ|S(Nt systemIdPathtr( tconfigtinitUp2dateConfigtostaccesstR_OKtNonetopentreadtclose(tcfgtpathtftret((s,/usr/share/rhn/up2date_client/up2dateAuth.pyt getSystemIds    c Csytiƒ}y%tiitƒƒddd}WndSXtiƒ}||jo ti ƒ}|i i tƒ|ƒ}|d}|t i |dƒ }ti|tiƒp yti|ƒWqÏdSXnti|tiƒpdSti|tiƒo-|d}yti||ƒWq-dSXnt|dƒ}|i|ƒ|iƒyti|dƒWququXndS(Nit os_releaseRt/s.savetwi€(RRRt xmlrpclibtloadsRt up2dateUtilst getVersiont rhnservert RhnServert registrationtupgrade_versiontstringtrfindRRtW_OKtmkdirtF_OKtrenameR twriteR tchmod( R tidVert systemVertst newSystemIdRtdirtsavePathR((s,/usr/share/rhn/up2date_client/up2dateAuth.pytmaybeUpdateVersion%s> %         c Cs'tiƒ}|idƒtp|idƒtShtiƒd6td6}tiit ƒ}ti |ti ƒpAy!ti |ƒti |dƒWqµ|id|ƒtSXntt dƒ}ti t dƒti||ƒ|iƒ|dttd ƒ}|id |dd |d ƒtS( s› Pickle loginInfo to a file Returns: True -- wrote loginInfo to a pickle file False -- did _not_ write loginInfo to a pickle file swriteCachedLogin() invokeds1writeCachedLogin() loginInfo is None, so bailing.ttimet loginInfoiÀs'Unable to write pickled loginInfo to %stwbi€sX-RHN-Auth-Expire-OffsetsWrote pickled loginInfo at s with expiration of s seconds.(t up2dateLogtinitLogt log_debugR-tFalseR,RRtdirnametpcklAuthFileNameRRR R$tlog_meR tpickletdumpR tfloattTrue(tlogtdatatpcklDirtpcklAutht expireTime((s,/usr/share/rhn/up2date_client/up2dateAuth.pytwriteCachedLoginOs.        c Cs@tiƒ}|idƒtittiƒp|idtƒtSttdƒ}yt i |ƒ}Wn+t j o|idƒ|i ƒtSX|i ƒ|d}|d}t i ƒ}|t|dƒ}|id|d |d t|dƒƒ||jo|id ||fƒtSt|ƒ|id |ƒtS( sb Read pickle info from a file Caches authorization info for connecting to the server. sreadCachedLogin invokeds'Unable to read pickled loginInfo at: %strbsSUnexpected EOF. Probably an empty file, regenerate auth fileR,R-sX-RHN-Auth-Expire-Offsets(Checking pickled loginInfo, currentTime=s , createTime=s, expire-offset=s9Pickled loginInfo has expired, created = %s, expire = %s.s<readCachedLogin(): using pickled loginInfo set to expire at (R/R0R1RRR4RR2R R6tloadtEOFErrorR R,R8t_updateLoginInfoR9(R:R=R;t createdTimetlit currentTimeR>((s,/usr/share/rhn/up2date_client/up2dateAuth.pytreadCachedLoginos8            cCsKt|ƒtjo.ttƒtjoti|ƒqG|andadS(s, Update the global var, "loginInfo" N(ttypeRR-tupdateR (RE((s,/usr/share/rhn/up2date_client/up2dateAuth.pyRC’s  c Cstiƒ}|id|ƒ| ot otƒotSntid|ƒ}tii ƒ}x$|D]\}}|i ||ƒqhW|djo t ƒ}n|pdSt ƒ|idƒ|ii|ƒ}|iiƒt|ƒtƒto|idƒn|idtƒtS(Nslogin(forceUpdate=%s) invokedttimeoutslogging into up2date servers?successfully retrieved authentication token from up2date servers logininfo:(R/R0R1R-RGRRt clientCapstcapst headerFormatt add_headerR RR+R5tup2datetlogint capabilitiestvalidateRCR?( tsystemIdt forceUpdateRJR:tservert headerlistt headerNametvalueRE((s,/usr/share/rhn/up2date_client/up2dateAuth.pyRP£s0         cCsJtiƒ}|idƒtdtd|ƒtptidƒ‚ntS(NsupdateLoginInfo() login infoRTRJsUnable to authenticate(R/R0R5RPR9R-t up2dateErrorstAuthenticationError(RJR:((s,/usr/share/rhn/up2date_client/up2dateAuth.pytupdateLoginInfoÈs   cCsCy taWntj o danXtotStd|ƒtS(NRJ(R-t NameErrorR RP(RJ((s,/usr/share/rhn/up2date_client/up2dateAuth.pyt getLoginInfoÒs   (RRRRYRRR/RKR6R,ttypesRtrhnRR R-R4RR+R?RGRCR2RPR[R](((s,/usr/share/rhn/up2date_client/up2dateAuth.pyts*            * # % haltree.py000066600000010765150501002420006544 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. import types 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 properties.has_key('info.parent'): 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) == types.StringType): if property.isdigit(): print indent + " ", "%-20s ==> %s" % (name, hex(int(property))) else: print indent + " ", "%-20s ==> %s" % (name, property) elif (type(property) == types.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 + " ") rhncli.pyo000066600000020171150501002420006546 0ustar00Ñò ú4™Pc@s½ddkZddkZddkZddkZddkZddklZddklZddkl Z ddkl Z ddk l Z ddk Z e iddeƒZeiZeiid ƒdd klZdd klZdd klZdd klZddklZd„ZedddddddedƒƒeddddedƒƒeddddedƒƒeddddedƒƒgZdefd „ƒYZd!„ZdS("iÿÿÿÿN(tOption(t OptionParser(tSSL(tcrypto(trpclibsrhn-client-toolstfallbacks/usr/share/rhn/(tconfig(t up2dateAuth(t up2dateErrors(t up2dateLog(t up2dateUtilscCs't|tƒo|idƒ}n|S(sg python 2.6- (i.e. RHEL6 and older) could not write unicode to stderr, encode it to utf-8. sutf-8(t isinstancetunicodetencode(tmsg((s'/usr/share/rhn/up2date_client/rhncli.pyt utf8_encode0ss-vs --verbosetactiontcounttdefaultithelpsShow additional outputs--proxytstoresSpecify an http proxy to uses --proxyUsers:Specify a username to use with an authenticated http proxys--proxyPasswords:Specify a password to use with an authenticated http proxytRhnClicBsweZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z e d „ƒZ e d „ƒZ RS( cCs=tdtdtiƒƒ|_d|_d|_t|_ dS(Nt option_listtversion( Rt _optionsTableRt_RhnCli__versionStringt optparsertNonetoptionstargstFalsethasGui(tself((s'/usr/share/rhn/up2date_client/rhncli.pyt__init__Es    cCs7tt_y(|iƒti|iƒpdƒWnÿtj o0tiit t dƒƒƒtidƒnÅt j o6}tiit t dƒ|ƒƒtidƒn„t i j oo}|djptt|ƒƒdjo tiit t dƒƒƒq3tiit t dƒ|ƒƒntj o6}tiit t dƒ|ƒƒtidƒnÆtij oR}tiit t dƒ|ƒƒtiit t d ƒƒƒtidƒnftitifj o6}tiit d t|ƒƒƒtid ƒntij o)}tiit t d ƒ|ƒƒnâtj o}|‚nÈtij o6}tiit t d ƒ|ƒƒtidƒn„tij o0}tiit d|ƒƒtidƒnFtij o6}tiit dt|ƒƒƒtidƒnXdS(Nis Aborted. is$An unexpected OS error occurred: %s s1A connection was attempted with a malformed URI. s5A connection was attempted with a malformed URI: %s. s%There was some sort of I/O error: %s sThere was an SSL error: %s sqA common cause of this error is the system time being incorrect. Verify that the time on this system is correct. sOpenSSL.SSL.SysCallError: %s is!There was a SSL crypto error: %s s&There was an authentication error: %s s%s sXMLRPC ProtocolError: %s i(texceptionHandlertsyst excepthookt initializetexittmaintKeyboardInterrupttstderrtwriteRt_tOSErrorRtMalformedURIErrorRtlentstrtIOErrorRtErrort SysCallErrortsocketterrorRt SystemExitRtAuthenticationErrortRpmErrort xmlrpclibt ProtocolError(R te((s'/usr/share/rhn/up2date_client/rhncli.pytrunNsJ   & $   $   cCs„|iiƒ\|_|_ti|iiƒtiƒdjo5t dƒt i d}|i |ƒt i dƒn|iƒdS(NisYou must be root to run %si(Rt parse_argsRRRt_RhnCli__setDebugLeveltverbosetostgeteuidR+R#targvt_warning_dialogR&t_RhnCli__updateProxyConfig(R trootWarningMsg((s'/usr/share/rhn/up2date_client/rhncli.pyR%ys cCs t‚dS(N(tNotImplementedError(R ((s'/usr/share/rhn/up2date_client/rhncli.pyR'†scCs“ytiƒtSWnztij o}|GHtStij o }tStij o6}ti ƒ}|i dƒ|i t i ƒŒtSXdS(Ns4There was a RhnServerException while testing login: (RtupdateLoginInfotTrueRtServerCapabilityErrorRR6tRhnServerExceptionR tinitLogtlog_met log_exceptionR#texc_info(R R:tlog((s'/usr/share/rhn/up2date_client/rhncli.pyt _testRhnLogin‰s   cCsR|io?y!ddkl}|i|ƒWqNtdƒGH|GHqNXn|GHdS(Niÿÿÿÿ(tguis'Unable to open gui. Try `up2date --nox`(Rtup2date_clientRPt errorWindowR+(R tmessageRP((s'/usr/share/rhn/up2date_client/rhncli.pyRB˜s   cCsµtiƒ}|iio*|id|iiƒ|iddƒn|iio*|id|iiƒ|iddƒn|iio*|id|iiƒ|iddƒndS(sÀ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. t httpProxyt enableProxyit proxyUsertenableProxyAutht proxyPasswordN(RtinitUp2dateConfigRtproxytsetRVRX(R tcfg((s'/usr/share/rhn/up2date_client/rhncli.pyt__updateProxyConfig£s    cCstiƒ}|iƒdS(sM Saves the current up2date configuration being used to disk. N(RRYtsave(R R\((s'/usr/share/rhn/up2date_client/rhncli.pyt saveConfig´s cCsR|io?y!ddkl}|i|ƒWqNtdƒGH|GHqNXn|GHdS(Niÿÿÿÿ(RPs'Unable to open gui. Try `up2date --nox`(RRQRPRRR+(R terrMsgRP((s'/usr/share/rhn/up2date_client/rhncli.pyt __faultError»s   cCstdƒtiƒ}|S(Nsv%%prog (Red Hat Network Client Tools) %s Copyright (C) 1999--2010 Red Hat, Inc. Licensed under the terms of the GPLv2.(R+R R(t versionString((s'/usr/share/rhn/up2date_client/rhncli.pyt__versionStringÆs  cCsftiƒ}|d||d<|ddjo3ytitiƒWqbtj o dGHqbXndS(Ntdebugis4extra verbosity not supported in this version of rpm(RRYtrpmt setVerbosityt RPMLOG_DEBUGtAttributeError(tlevelR\((s'/usr/share/rhn/up2date_client/rhncli.pyt__setDebugLevelÍs (t__name__t __module__R!R;R%R'RORBRCR_t_RhnCli__faultErrort staticmethodRR=(((s'/usr/share/rhn/up2date_client/rhncli.pyRCs +     cCsÇtiƒ}tiittdƒdƒƒt|dƒo4tiit|iƒdƒ|i |||ƒn4tiitt |ƒdƒƒ|i |||ƒtiittdƒdƒƒdS(NsAn error has occurred:s terrmsgs)See /var/log/up2date for more information( R RJR#R)R*RR+thasattrRoRLR/(ttypetvaluettbRN((s'/usr/share/rhn/up2date_client/rhncli.pyR"Ùs   ( R#R?ReR8R3toptparseRRtOpenSSLRRtrhnRtgettextt translationRGtttugettextR+tpathtappendRQRRRR R RRtobjectRR"(((s'/usr/share/rhn/up2date_client/rhncli.pyts:           –rpcServer.pyo000066600000020564150501002420007250 0ustar00Ñò ºÏÅZc@s*ddkZddkZddkZddkZddkZddkZddkZddkZddkZddk Z ddk Z ddk Z ddk Z ddk lZddkZeiddeƒZeiZd„Zdeifd„ƒYZdd d „ƒYZdddd „Zd „ZdS( iÿÿÿÿN(trpclibsrhn-client-toolstfallbackcCs |GHdS(N((tmsg((s*/usr/share/rhn/up2date_client/rpcServer.pytstdoutMsgCallbackst RetryServercBs,eZd„Zd„Zd„Zd„ZRS(cCsdS(N((tself((s*/usr/share/rhn/up2date_client/rpcServer.pytfoobarscCs ||_dS(N(t serverList(RR((s*/usr/share/rhn/up2date_client/rpcServer.pyt addServerList!sc Csætiƒ|_xÐy|i||ƒ}Wn³tij o ‚nœtij o ‚n„tij o4|ii dƒt t dƒƒt i dƒnB|iiƒ}|djo|iiƒ‚nd|i}|dt it if}|d|iiƒ}|ii |ƒddk}|i|iiƒƒ\}}|iƒ}|d jotd|ƒ‚n|i|ƒ\|_|_|i|_||_|iiƒ|_|ip d |_nd |_qnXPq|S( Ns,Error: Server Unavailable. Please try later.iÿÿÿÿs An error occured talking to %s: s%s %s sTrying the next serverURL: %s thttpthttpss%Redirected to unsupported protocol %ss/RPC2i(R R (t up2dateLogtinitLogtlogt_requestRtInvalidRedirectionErrortFaultthttplibt BadStatusLinetlog_meRt_tsystexitRtnexttNonetresetServerIndext_hosttexc_typet exc_valuetserverturllibt splittypetlowert splithostt_handlert _orig_handlert_typet_urit_allow_redirect( Rt methodnametparamstretRRRttypturi((s*/usr/share/rhn/up2date_client/rpcServer.pyt _request1$sL            cCstii|i|ƒS(N(Rt xmlrpclibt_MethodR,(Rtname((s*/usr/share/rhn/up2date_client/rpcServer.pyt __getattr__Vs(t__name__t __module__RRR,R0(((s*/usr/share/rhn/up2date_client/rpcServer.pyRs   2t ServerListcBs8eZgd„Zd„Zd„Zd„Zd„ZRS(cCs||_d|_dS(Ni(Rtindex(Rt serverlist((s*/usr/share/rhn/up2date_client/rpcServer.pyt__init__]s cCs|i|i|_|iS(N(RR4t serverurl(R((s*/usr/share/rhn/up2date_client/rpcServer.pyRascCs8|id|_|it|iƒjodS|iƒS(Ni(R4tlenRRR(R((s*/usr/share/rhn/up2date_client/rpcServer.pyRfscCs||_d|_dS(Ni(RR4(RR5((s*/usr/share/rhn/up2date_client/rpcServer.pytresetServerListls cCs d|_dS(Ni(R4(R((s*/usr/share/rhn/up2date_client/rpcServer.pyRps(R1R2R6RRR9R(((s*/usr/share/rhn/up2date_client/rpcServer.pyR3\s     cCs½tiƒ}tiƒ}|d}t|ƒtdƒjo |g}n|pdg}|dotiƒ}nd}|ptiƒ}n|}t|ƒ} d} d} |do&|dpd} |dpd} nd} xhdD]`} t i i | ƒoGt i | pqìnt i | i d ƒd } | i dƒd } PqìqìWt | iƒd|d|d| d| d|ƒ}|i| ƒ|idtiƒƒ| o|i| ƒng}|iiD]+}ti|ƒd djo |tqÌqÌ~}|orxo|D]c}t i|t iƒp:dtdƒ|f}|id|ƒti|ƒ‚n|i|ƒqWntiƒti i!ƒ}x$|D]\}}|i||ƒq™W|S(Nt sslCACertts/usr/share/rhn/RHNS-CA-CERTt enableProxytenableProxyAutht proxyUsert proxyPasswordtLANGUAGEtLC_ALLt LC_MESSAGEStLANGt:it.trefreshCallbacktproxytusernametpasswordttimeoutsX-Up2date-VersionR s%s: %ss ERROR: can not find RHNS CA files%s(R@RARBRC("R R tconfigtinitUp2dateConfigttypetgetProxySettingRt getServerlURLR3tostenvironthas_keytsplitRRRt add_headert up2dateUtilstversiontsetlangRturlparsetTruetaccesstR_OKRRt up2dateErrorstSSLCertificateFileNotFoundtadd_trusted_certt clientCapst loadLocalCapstcapst headerFormat(RFtserverOverrideRJR tcfgtcat rhns_ca_certst proxyHostt serverUrlsRR>R?tlangtenvtst_[1]titneed_cat rhns_ca_certRt headerlistt headerNametvalue((s*/usr/share/rhn/up2date_client/rpcServer.pyt getServertsl          .    c Osetiƒ}|id|idƒtiƒ}d}d}yt|dƒ}Wntj o d}nX|djo d}nxÛd}d}y|||Ž}Wn\t j ot i t dƒƒ‚n6t it ifj o}} |id| |fƒ||joJt| iƒdjot i | idƒ‚q_t i | idƒ‚qd}n¢tij odGHt i dƒ‚nytij o^} d } | d | i} | d | i} | d | i} |i| ƒt i | ƒ‚n tij oÙ} |id | i|fƒ| idjo%|id| iƒ|idƒnti| i ƒ\} } d} t!| ƒdjo|id| ƒt"i#ƒnt!| ƒdjo)|it dƒƒt i | iƒ‚nt!| ƒdjo®t$|dƒt$gƒjo|d}n |d}t$|ƒt$gƒjo*d|d|d|d|df}n|}d|| f} |i| ƒt i%| ƒ‚n| p-||jot i | iƒ‚qÛd}qn&ti&j ot i dƒ‚nX|djoPnd}|ot'i(dƒ|d}n||jot i dƒ‚q†q†|S(NsrpcServer: Calling XMLRPC %st _Method__nameitnetworkRetriesisConnection aborted by the users(A socket error occurred: %s, attempt #%sshttplib.IncompleteReads An HTTP error occurred: sURL: %s sStatus Code: %s sError Message: %s s,A protocol error occurred: %s , attempt #%s,i”sCould not find URL, %ss)Check server name and/or URL, then retry i"s'Auth token timeout occurred errmsg: %si3s.Server has refused connection due to high loadis %s-%s-%s.%siisFile Not Found: %s %ss Broken response from the server.is0The data returned from the server was incomplete()R R t log_debugt__dict__RKRLRtintt ValueErrortKeyboardInterruptR\tCommunicationErrorRtsocketterrortsslerrorRR8targsRtIncompleteReadturllib2t HTTPErrortfilenametcodeRRt ProtocolErrorterrmsgterrcodeturlt reportErrortheaderstabst up2dateAuthtupdateLoginInfoRMtFileNotFoundErrort ResponseErrorttimetsleep(tmethodRtkwargsR RdR)t attempt_counttattemptstfailureteRterrCodeterrMsgtresettpkgtpkgName((s*/usr/share/rhn/up2date_client/rpcServer.pytdoCallÀsš            *     ((RPRRKR|RRRR_R R\RURŒRXtrhnRtgettextt translationRYtttugettextRRtServerRR3RRsR(((s*/usr/share/rhn/up2date_client/rpcServer.pyts*                ?Ltransaction.pyo000066600000006334150501002420007621 0ustar00Ñò ú4™Pc@sKddkZdadZddd„ƒYZddd„ƒYZd„ZdS( iÿÿÿÿNtTransactionDatacBseZd„Zd„ZRS(cCsAh|_g|id s .+up2dateAuth.py000066600000014445150501002420007305 0ustar00# # $Id$ import rhnserver import config import os import up2dateErrors import up2dateUtils import string import up2dateLog import clientCaps import pickle import time from types import DictType from rhn import rpclib 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 # 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(): 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 idVer != systemVer: s = rhnserver.RhnServer() newSystemId = s.registration.upgrade_version(getSystemId(), systemVer) path = cfg["systemIdPath"] dir = path[:string.rfind(path, "/")] 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, 0600) 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, 0700) except: log.log_me("Unable to write pickled loginInfo to %s" % pcklDir) return False pcklAuth = open(pcklAuthFileName, 'wb') os.chmod(pcklAuthFileName, 0600) 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: log.log_debug("Unexpected EOF. Probably an empty file, \ regenerate auth file") pcklAuth.close() return False pcklAuth.close() 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) # 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 __init__.py000066600000000000150501002420006634 0ustar00rhncli.py000066600000017514150501002420006376 0ustar00# # Common cli related functions for RHN Client Tools # Copyright (c) 1999--2010 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 # Preston Brown # James Bowes import sys import os import rpm import xmlrpclib import socket from optparse import Option from optparse import OptionParser from OpenSSL import SSL from OpenSSL import crypto from rhn import rpclib import gettext t = gettext.translation('rhn-client-tools', fallback=True) _ = t.ugettext sys.path.append("/usr/share/rhn/") 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 def utf8_encode(msg): """ python 2.6- (i.e. RHEL6 and older) could not write unicode to stderr, encode it to utf-8. """ if isinstance(msg, unicode): msg = msg.encode('utf-8') return(msg) _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")), ] 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(utf8_encode(_("\nAborted.\n"))) sys.exit(1) except OSError, e: sys.stderr.write(utf8_encode(_("An unexpected OS error occurred: %s\n") % e)) sys.exit(1) except rpclib.MalformedURIError, e: # Subclass of IOError so must come 1st? if e is None or len(str(e)) == 0: sys.stderr.write(utf8_encode(_("A connection was attempted with a malformed URI.\n"))) else: sys.stderr.write(utf8_encode(_("A connection was attempted with a malformed URI: %s.\n") % e)) except IOError, e: sys.stderr.write(utf8_encode(_("There was some sort of I/O error: %s\n") % e)) sys.exit(1) except SSL.Error, e: sys.stderr.write(utf8_encode(_("There was an SSL error: %s\n") % e)) sys.stderr.write(utf8_encode(_("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), e: sys.stderr.write(utf8_encode("OpenSSL.SSL.SysCallError: %s\n" % str(e))) sys.exit(2) except crypto.Error, e: sys.stderr.write(utf8_encode(_("There was a SSL crypto error: %s\n") % e)) except SystemExit, e: raise e except up2dateErrors.AuthenticationError, e: sys.stderr.write(utf8_encode(_("There was an authentication error: %s\n") % e)) sys.exit(1) except up2dateErrors.RpmError, e: sys.stderr.write(utf8_encode("%s\n" % e)) sys.exit(1) except xmlrpclib.ProtocolError, e: sys.stderr.write(utf8_encode("XMLRPC ProtocolError: %s\n" % str(e))) 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) self.__updateProxyConfig() def main(self): raise NotImplementedError def _testRhnLogin(self): try: up2dateAuth.updateLoginInfo() return True except up2dateErrors.ServerCapabilityError, e: print e return False except up2dateErrors.AuthenticationError, e: return False except up2dateErrors.RhnServerException, e: 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 (Red Hat Network Client Tools) %s\n" "Copyright (C) 1999--2010 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: # Set rpm's verbosity mode try: rpm.setVerbosity(rpm.RPMLOG_DEBUG) except AttributeError: print "extra verbosity not supported in this version of rpm" def exceptionHandler(type, value, tb): log = up2dateLog.initLog() sys.stderr.write(utf8_encode(_("An error has occurred:") + "\n")) if hasattr(value, "errmsg"): sys.stderr.write(utf8_encode(value.errmsg) + "\n") log.log_exception(type, value, tb) else: sys.stderr.write(utf8_encode(str(type) + "\n")) log.log_exception(type, value, tb) sys.stderr.write(utf8_encode(_("See /var/log/up2date for more information") + "\n")) up2dateErrors.pyc000066600000040423150501002420010016 0ustar00Ñò ºÏÅZc @sûddkZddkZeiddeƒZeiZddkZddkZddk Z e i de i d e _ ddk l Z l Z de fd„ƒYZdefd „ƒYZd efd „ƒYZd efd „ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZd efd!„ƒYZd"eefd#„ƒYZd$efd%„ƒYZd&eefd'„ƒYZd(efd)„ƒYZd*efd+„ƒYZ d,efd-„ƒYZ!d.eefd/„ƒYZ"d0eefd1„ƒYZ#d2eefd3„ƒYZ$d4efd5„ƒYZ%d6efd7„ƒYZ&d8efd9„ƒYZ'd:e efd;„ƒYZ(d<efd=„ƒYZ)d>efd?„ƒYZ*d@efdA„ƒYZ+dBefdC„ƒYZ,dDefdE„ƒYZ-dFefdG„ƒYZ.dHefdI„ƒYZ/dJefdK„ƒYZ0dLefdM„ƒYZ1dNefdO„ƒYZ2dPefdQ„ƒYZ3dRefdS„ƒYZ4dS(TiÿÿÿÿNsrhn-client-toolstfallbacki(t RepoErrort YumBaseErrortErrorcBs8eZdZdZd„Zd„Zd„Zd„ZRS(sbase class for errorstcCs]t|tƒpt|ddƒ}nti||ƒd|i||_tiƒ|_dS(Nsutf-8tignores rhn-plugin: ( t isinstancetunicodeRt__init__tpremsgtvaluet up2dateLogtinitLogtlog(tselfterrmsg((s./usr/share/rhn/up2date_client/up2dateErrors.pyRs cCs|ii|iƒ|iS(N(R tlog_meR (R((s./usr/share/rhn/up2date_client/up2dateErrors.pyt__repr__scCsx|djo|iSttdƒoti||ƒS||ijo |i|Sttdƒ|ii|fƒ‚dS(sG Spacewalk backend still use errmsg, let have errmsg as alias to value Rt __getattr__sclass %s has no attribute '%s'N( R thasattrRRt__dict__tAttributeErrort_t __class__t__name__(Rtname((s./usr/share/rhn/up2date_client/up2dateErrors.pyR"s  cCsV|djo||id¿s tNoChannelsErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyR@Ést NetworkErrorcBseZdZedƒZRS(sC some generic network error occured, e.g. connection reset by peer sNetwork error: (RRRRR (((s./usr/share/rhn/up2date_client/up2dateErrors.pyRAÌstSSLCertificateVerifyFailedErrorcBseZd„ZeiZRS(cCstiƒ}|d}t|dƒ}|iƒ}|iƒtiitii|ƒ}|i ƒot i |d|ƒnt i |dƒdS(Nt sslCACerttrsnThe certificate %s is expired. Please ensure you have the correct certificate and your system time is correct.s(The SSL certificate failed verification.( tconfigtinitUp2dateConfigtopentreadtclosetOpenSSLtcryptotload_certificatet FILETYPE_PEMt has_expiredRR(Rt up2dateConfigtcertFiletftbufttempCert((s./usr/share/rhn/up2date_client/up2dateErrors.pyRÑs       (RRRRR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRBÐs tSSLCertificateFileNotFoundcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRTâst$AuthenticationOrAccountCreationErrorcBseZdZRS(s,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. (RRR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRUæs tNotEntitlingErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRVôstInvalidProtocolErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRW÷stUnableToCreateUsercBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRXústActivationKeyUsageLimitErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRYýstLoginMinLengthErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRZstPasswordMinLengthErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyR[stPasswordMaxLengthErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyR\stInsuffMgmntEntsErrorcBs#eZd„Zd„Zd„ZRS(cCs|i|ƒ|_dS(N(tchangeExplanationR (RR ((s./usr/share/rhn/up2date_client/up2dateErrors.pyR scCs|iS(N(R (R((s./usr/share/rhn/up2date_client/up2dateErrors.pyRscCs7tdƒ}d}|i|ƒt|ƒ}|| |S(Ns Your organization does not have enough Management entitlements to register this system to Red Hat 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 Red Hat Network and visiting the 'Subscription Management' page in the 'Your RHN' section of RHN. 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.s Explanation:(Rtrindextlen(RR tnewExplnttermtloc((s./usr/share/rhn/up2date_client/up2dateErrors.pyR^s  (RRRRR^(((s./usr/share/rhn/up2date_client/up2dateErrors.pyR] s  tNoSystemIdErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRd"stInvalidRedirectionErrorcBseZdZRS(s7 Raise when redirect requests could'nt return a package(RRR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRe%s(5R tgettextt translationtTruetttugettextRRJREtsystpatht yum.ErrorsRRRRRR"R#R$R&R)R+R,R-R.R3R4R5R6R7R8R9R:R;R<R=R>R@RARBRTRURVRWRXRYRZR[R\R]RdRe(((s./usr/share/rhn/up2date_client/up2dateErrors.pyt s^      '      rhnPackageInfo.py000066600000003757150501002420010002 0ustar00 # all the crap that is stored on the rhn side of stuff # updating/fetching package lists, channels, etc import up2dateAuth import up2dateLog import rhnserver import rpmUtils 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'])) def updatePackageProfile(timeout=None): """ get a list of installed packages and send it to rhnServer """ log = up2dateLog.initLog() log.log_me("Updating package profile") packages = rpmUtils.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 = map(lambda a : "%s-%s-%s" % (a[0],a[1],a[2]), 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 package.has_key('arch') and package.has_key('cookie'): result.append([package['name'], package['version'], package['release'], package['epoch'], package['arch'], package['cookie']]) elif package.has_key('arch'): 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 capabilities.pyo000066600000014555150501002420007731 0ustar00Ñò ú4™Pc @sddkZddkZddkZddkZddkZeiddeƒZeiZ h hdd6d6hdd6d6hdd6d 6hdd6d 6hdd6d 6hdd6d 6hdd6d 6hdd6d6hdd6d6Z d„Z deifd„ƒYZ dS(iÿÿÿÿNsrhn-client-toolstfallbackt21tversiont caneatCheeset1tsupportsAutoUp2dateOptionsregistration.finish_messages xmlrpc.packages.extended_profilesregistration.delta_packagess$registration.remaining_subscriptionss registration.update_contact_infos$registration.extended_update_supportsregistration.smbiosc CsÝd}ti|dƒ}g}x¸|D]°}y+ttiti|ddƒƒ\}}Wntj o q%nXti|ddƒ\}}|ddjo dGHn|d }h|d6|d 6}|i||fƒq%W|S( Nt,t=it(iÿÿÿÿt)s2something broke in parsing the capabilited headersRtvalue(tNonetstringtsplittmaptstript ValueErrortappend( t capstringR tcapstcapslisttcapt key_versiontkeyRtdata((s-/usr/share/rhn/up2date_client/capabilities.pytparseCaps +  t CapabilitiescBsSeZd„Zd„Zd„Zd„Zd„Zd„Zd„Zdd„Z RS( cCs5tii|ƒh|_t|_tiƒ|_dS(N(tUserDictt__init__t missingCapst neededCapstconfigtinitUp2dateConfigtcfg(tself((s-/usr/share/rhn/up2date_client/capabilities.pyR5s  cCs`xY|iƒD]K}|djo8t||ƒ}x%|D]\}}||i|s   cCs²ti|dƒ}|djoJti|dƒ}|d}|d}tt|ƒt|ƒdƒ}|Sti|dƒ}t|ƒdjotd„|ƒ}|St|ƒgS(Nt-iit:cSs t|ƒS((tint(ta((s-/usr/share/rhn/up2date_client/capabilities.pytRs(R tfindR trangeR(tlenR(R"t versionStringtindextrngtstarttendtversionstvers((s-/usr/share/rhn/up2date_client/capabilities.pytparseCapVersionFs   cCs|ii|ƒp!tdƒ|}d|i|s"       hardware_gudev.pyo000066600000022517150501002420010264 0ustar00Ñò ¹ÏÅZc@sÍddkZddkZddkZddkZddklZlZd„Zd„ZdZ dZ dZ dZ d Z d Zd Zd ZdZdZdZd Zd Zd ZdZdZdZd ZdZdZdZdZd ZdZ dZ!dZ"dZ#d Z$d Z%dZ&dZ'dZ(dZ)d Z*dZ+dZ,dZ-dZ.d Z/d Z0dZ1dZ2dZ3dZ4d Z5d Z6d Z7dZ8dZ9dZ:dZ;d Z<d Z=dZ>d„Z?d„Z@d„ZAd„ZBd„ZCdS(iÿÿÿÿN(tPCItUSBc Cs›tidgƒ}|idƒ|idƒ|idƒ|idƒ|idƒ}g}x9|D]1}|iƒ}h|d6|iƒd6t|ƒd 6d d 6t|ƒd 6t|ƒd 6}|d d(jod|d RARvRxRwRztPCI_CLASS_STORAGE_IPIRytPCI_CLASS_STORAGE_OTHERRmtPCI_CLASS_NETWORK_ETHERNETtPCI_CLASS_NETWORK_TOKEN_RINGtPCI_CLASS_NETWORK_FDDItPCI_CLASS_NETWORK_ATMtPCI_CLASS_NETWORK_OTHERRrtPCI_CLASS_DISPLAY_VGAtPCI_CLASS_DISPLAY_XGAtPCI_CLASS_DISPLAY_3DtPCI_CLASS_DISPLAY_OTHERR~RR€tPCI_CLASS_MULTIMEDIA_PHONEtPCI_CLASS_MULTIMEDIA_OTHERRtPCI_CLASS_BRIDGE_HOSTtPCI_CLASS_BRIDGE_ISAtPCI_CLASS_BRIDGE_EISAtPCI_CLASS_BRIDGE_MCtPCI_CLASS_BRIDGE_PCIR‚tPCI_CLASS_BRIDGE_NUBUSRƒtPCI_CLASS_BRIDGE_RACEWAYtPCI_CLASS_BRIDGE_OTHERR{tPCI_CLASS_COMMUNICATION_SERIALt PCI_CLASS_COMMUNICATION_PARALLELt#PCI_CLASS_COMMUNICATION_MULTISERIALR|tPCI_CLASS_COMMUNICATION_OTHERRnRotPCI_CLASS_INPUT_PENRpR}tPCI_CLASS_INPUT_GAMEPORTtPCI_CLASS_INPUT_OTHERRsRutPCI_CLASS_SERIAL_ACCESStPCI_CLASS_SERIAL_SSARttPCI_CLASS_SERIAL_FIBERtPCI_CLASS_SERIAL_SMBUSR(R)R*RlR„(((s//usr/share/rhn/up2date_client/hardware_gudev.pyts‚     P   ` " hwdata.pyo000066600000011271150501002420006540 0ustar00Ñò ºÏÅZc@s0dZddd„ƒYZddd„ƒYZdS(sF Query hwdata database and return decription of vendor and/or device. tUSBcBs8eZdZdZdZdd„Zd„Zd„ZRS(s) Interace to usb.ids from hwdata package s/usr/share/hwdata/usb.idsc Csâ|o ||_n ti|_d|_|io«ti o ht_x”t|iƒiƒD]y}|iƒ}|idƒo|idƒoPqÖq]q]t|ƒdjoq]q]|idƒoa|di ƒ}t|ƒdjodi |dƒ}nd}|ti|d|d|sNhaltree.pyo000066600000007325150501002420006721 0ustar00Ñò ú4™Pc@s6ddkZddd„ƒYZddd„ƒYZdS(iÿÿÿÿNt HalDevicecBs eZdZd„Zd„ZRS(s5An object containing its udi, properties and childrencCs_|d|_||_g|_d|_|idƒo|d|_n d|_d|_dS(Nsinfo.udis info.parent(tudit propertiestchildrentNonetclassificationthas_keyt parent_uditparent(tselfR((s(/usr/share/rhn/up2date_client/haltree.pyt__init__s     cCsA|iGdGHx.|iiƒD]\}}dG|GdG|GHqWdS(Nt:s s ==> (RRtitems(R tpropertytvalue((s(/usr/share/rhn/up2date_client/haltree.pytprint_properties,s  (t__name__t __module__t__doc__R R(((s(/usr/share/rhn/up2date_client/haltree.pyRs tHalTreecBsMeZd„Zd„Zd„Zd„Zed„ƒZd„Zd„Z RS(cCsd|_g|_dS(N(Rtheadt no_parent_yet(R ((s(/usr/share/rhn/up2date_client/haltree.pyR 5s cCsn|ioJ|i|iƒ}|o|ii|ƒ||_q]|ii|ƒn ||_|i|ƒdS(N(Rt_HalTree__find_nodeRtappendRRRt_HalTree__get_lost_children(R t hal_deviceR((s(/usr/share/rhn/up2date_client/haltree.pytadd:s   cCskg}g}|i}xN|D]F}|i|ijo-||_|ii|ƒ|ii|ƒqqWdS(N(RRRRRRtremove(R Rt found_listtindexestno_parent_yet_copytdev((s(/usr/share/rhn/up2date_client/haltree.pyt__get_lost_childrenIs  cCse|io%ti|i|ƒ}|o|Snx/|iD]$}ti||ƒ}|o|Sq9WdS(sp This takes a node in the HalDevice tree and returns the HalDevice with the given udi. N(RRt_HalTree__find_node_workerRR(R Rtnodet found_node((s(/usr/share/rhn/up2date_client/haltree.pyt __find_nodeSs    cCsK|i|jo|Sx/|iD]$}ti||ƒ}|o|SqWdS(N(RRRR!R(R"Rtdevicetres((s(/usr/share/rhn/up2date_client/haltree.pyt__find_node_workercs  cCs|i|idƒdS(Nt(t_HalTree__print_dev_treeR(R ((s(/usr/share/rhn/up2date_client/haltree.pyt print_treemscCs"|G|iGH|GdG|iGHxÖ|iiƒD]Å\}}t|ƒtijoO|iƒo'|dGd|tt |ƒƒfGHqñ|dGd||fGHq,t|ƒti jo'|dGd|tt |ƒƒfGHq,|dGd||fGHq,WHx%|i D]}|i ||dƒqWdS(NsCLASS:s s %-20s ==> %s( RRRR ttypettypest StringTypetisdigitthextinttIntTypeRR)(R R"tindenttnameR tchild((s(/usr/share/rhn/up2date_client/haltree.pyt__print_dev_treeps   '' ( RRR RRRt staticmethodR!R*R)(((s(/usr/share/rhn/up2date_client/haltree.pyR4s    (((R,RR(((s(/usr/share/rhn/up2date_client/haltree.pyts __init__.pyo000066600000000200150501002420007015 0ustar00Ñò ú4™Pc@sdS(N((((s)/usr/share/rhn/up2date_client/__init__.pytsrhnHardware.pyo000066600000001036150501002420007533 0ustar00Ñò ú4™Pc@s1ddkZddkZddkZd„ZdS(iÿÿÿÿNcCs5tiƒ}tiƒ}|iitiƒ|ƒdS(N(t rpcServert getServerthardwaretHardwaret registrationtrefresh_hw_profilet up2dateAutht getSystemId(tst hardwareList((s,/usr/share/rhn/up2date_client/rhnHardware.pytupdateHardwares  (RRRR (((s,/usr/share/rhn/up2date_client/rhnHardware.pyts   clientCaps.pyo000066600000005031150501002420007352 0ustar00Ñò ú4™Pc @s;ddkZddkZddkZddkZddkZdeifd„ƒYZeƒZdd„Zeƒd„Zedhdd 6dd 6ƒed hdd 6dd 6ƒed hdd 6dd 6ƒed hdd 6dd 6ƒedhdd 6dd 6ƒedhdd 6dd 6ƒedhdd 6dd 6ƒdS(iÿÿÿÿNtClientCapabilitiescBs&eZd„Zdd„Zd„ZRS(cCstii|ƒ|iƒdS(N(tUserDictt__init__tpopulate(tself((s+/usr/share/rhn/up2date_client/clientCaps.pyR scCs9hhdd6dd6d6}|o |}n||_dS(Nitversiontvaluet caneatCheese(tdata(RtcapsToPopulatet localcaps((s+/usr/share/rhn/up2date_client/clientCaps.pyRs  cCsfg}xY|iiƒD]H}d}d||i|d|i|df}|i||fƒqW|S(NsX-RHN-Client-Capabilitys %s(%s)=%sRR(Rtkeystappend(Rt headerListtkeyt headerNameR((s+/usr/share/rhn/up2date_client/clientCaps.pyt headerFormatsN(t__name__t __module__RtNoneRR(((s+/usr/share/rhn/up2date_client/clientCaps.pyR s  s/etc/sysconfig/rhn/clientCaps.dcCsÝtid|ƒ}xÃ|D]»}tii|ƒoqnti|tiƒpqnt|dƒ}xl|iƒD]^}ti |ƒ|ddjoqsnt i |ƒ}x!|D]\}}|t i |s        config.pyc000066600000024101150501002420006515 0ustar00Ñò ºÏÅZc @sdZddkZddkZddkZeiddeƒZeiZh d.d6d/d 6d0d 6d1d6d2d6d3d6d4d6d5d6d6d6d7d6d8d 6d9d"6d#d d d$d"gfd$6Z dd d%gZ d&d:d'„ƒYZ d(d;d)„ƒYZ d*„Z d+„Zd,d-„ZdS(<sj This module includes the Config and Up2date Config classes use by the up2date agent to hold config info. iÿÿÿÿNsrhn-client-toolstfallbacksUse a HTTP Proxyit enableProxysRemote server URLs$https://xmlrpc.rhn.redhat.com/XMLRPCt serverURLs#Whether or not debugging is enabledtdebugsLocation of system ids/etc/sysconfig/rhn/systemidt systemIdPaths4Override the automatically determined system versionttversionOverrides:HTTP proxy in host:port format, e.g. squid.redhat.com:3128t httpProxys'The username for an authenticated proxyt proxyUsers.The password to use for an authenticated proxyt proxyPasswords$To use an authenticated proxy or nottenableProxyAuthsBNumber of attempts to make at network connections before giving upitnetworkRetriess)The CA cert used to verify the ssl servers/usr/share/rhn/RHNS-CA-CERTt sslCACertsDisable the reboot actiontnoRebootsDConfig options that can not be overwritten by a config update actiontdisallowConfChangesttmpDirt ConfigFilecBsneZdZd d„Zd d„Zd„Zd„Zd„Zd„Z d„Z d„Z d „Z d „Z RS( s;class for handling persistent config options for the clientcCs.h|_||_|io|iƒndS(N(tdicttfileNametload(tselftfilename((s'/usr/share/rhn/up2date_client/config.pyt__init__=s   cCs»|o ||_n|idjodSti|itiƒpdSt|idƒ}d}xK|iƒD]=}|idƒdjoqln||iƒ}|pqln|ddjo|d iƒ}qlnd}|i ddƒ}t |ƒd joqln|diƒ}|diƒ}d}|id ƒ} | djo|| }|}d}n|oÀ|i d ƒ} |djot |ƒ}q*t | ƒdjo*yt |ƒ}Wq&t j oq&Xq*| ddjo g}q*g} | D]$} | iƒo| | iƒqùqù~ }n||f} |ii|ƒoS|i|} |dj o|| df} n|dj o| d|f} qœn| |i|µs(R>RR1(R((s'/usr/share/rhn/up2date_client/config.pyR1´scCs|ii|ƒdS(N(Rtupdate(RR((s'/usr/share/rhn/up2date_client/config.pyRE·scCs'|ii|ƒo|i|dSdS(Ni(RR(R(RRB((s'/usr/share/rhn/up2date_client/config.pyt __getitem__¼scCsE|ii|ƒo|i|}nd}|d|f|i|tƒ}t|dƒtgƒjo |dS|dgSdS(s return list of serverURL from config Note: in config may be one value or more values, but this function always return list RN(RXR<(RY((s'/usr/share/rhn/up2date_client/config.pyt getServerlURL)s  s/etc/sysconfig/rhn/up2datecCsoy taWntj o danXtdjo8t|ƒattd sN     –K rpcServer.py000066600000023717150501002420007074 0ustar00# # $Id$ import os import sys import config import socket import time import httplib import urllib2 import clientCaps import up2dateLog import up2dateErrors import up2dateUtils import up2dateAuth import urlparse from rhn import rpclib import gettext t = gettext.translation('rhn-client-tools', fallback=True) _ = t.ugettext def stdoutMsgCallback(msg): print msg class RetryServer(rpclib.Server): def foobar(self): pass 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 rpclib.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 == 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() raise msg = "An error occured talking to %s:\n" % self._host msg = msg + "%s\n%s\n" % (sys.exc_type, sys.exc_value) msg = msg + "Trying the next serverURL: %s\n" % self.serverList.server() self.log.log_me(msg) # try a different url # use the next serverURL import urllib typ, uri = urllib.splittype(self.serverList.server()) typ = typ.lower() if typ not in ("http", "https"): raise InvalidRedirectionError( "Redirected to unsupported protocol %s" % typ) self._host, self._handler = urllib.splithost(uri) 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 resetServerList(self, serverlist): self.serverList = serverlist self.index = 0 def resetServerIndex(self): self.index = 0 def getServer(refreshCallback=None, serverOverride=None, timeout=None): 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 type(ca) == type(""): ca = [ca] rhns_ca_certs = ca or ["/usr/share/rhn/RHNS-CA-CERT"] if cfg["enableProxy"]: proxyHost = config.getProxySetting() else: proxyHost = None if not serverOverride: serverUrls = config.getServerlURL() 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 os.environ.has_key(env): 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 RHNS-CA-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 up2dateErrors.CommunicationError(_( "Connection aborted by the user")) # if we get a socket error, keep tryingx2 except (socket.error, socket.sslerror), e: log.log_me("A socket error occurred: %s, attempt #%s" % ( e, attempt_count)) if attempt_count >= attempts: if len(e.args) > 1: raise up2dateErrors.CommunicationError(e.args[1]) else: raise up2dateErrors.CommunicationError(e.args[0]) else: failure = 1 except httplib.IncompleteRead: print "httplib.IncompleteRead" raise up2dateErrors.CommunicationError("httplib.IncompleteRead") except urllib2.HTTPError, e: 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 up2dateErrors.CommunicationError(msg) except rpclib.ProtocolError, e: 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 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 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 up2dateErrors.FileNotFoundError(msg) if not reset: if attempt_count >= attempts: raise up2dateErrors.CommunicationError(e.errmsg) else: failure = 1 except rpclib.ResponseError: raise 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 hardware_gudev.py000066600000031305150501002420010100 0ustar00# Copyright (c) 2010 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 gudev import glib 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 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, device.get_property('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 capabilities.pyc000066600000014703150501002420007710 0ustar00Ñò ú4™Pc @sddkZddkZddkZddkZddkZeiddeƒZeiZ h hdd6d6hdd6d6hdd6d 6hdd6d 6hdd6d 6hdd6d 6hdd6d 6hdd6d6hdd6d6Z d„Z deifd„ƒYZ dS(iÿÿÿÿNsrhn-client-toolstfallbackt21tversiont caneatCheeset1tsupportsAutoUp2dateOptionsregistration.finish_messages xmlrpc.packages.extended_profilesregistration.delta_packagess$registration.remaining_subscriptionss registration.update_contact_infos$registration.extended_update_supportsregistration.smbiosc CsÝd}ti|dƒ}g}x¸|D]°}y+ttiti|ddƒƒ\}}Wntj o q%nXti|ddƒ\}}|ddjo dGHn|d }h|d6|d 6}|i||fƒq%W|S( Nt,t=it(iÿÿÿÿt)s2something broke in parsing the capabilited headersRtvalue(tNonetstringtsplittmaptstript ValueErrortappend( t capstringR tcapstcapslisttcapt key_versiontkeyRtdata((s-/usr/share/rhn/up2date_client/capabilities.pytparseCaps +  t CapabilitiescBsSeZd„Zd„Zd„Zd„Zd„Zd„Zd„Zdd„Z RS( cCs5tii|ƒh|_t|_tiƒ|_dS(N(tUserDictt__init__t missingCapst neededCapstconfigtinitUp2dateConfigtcfg(tself((s-/usr/share/rhn/up2date_client/capabilities.pyR5s  cCs`xY|iƒD]K}|djo8t||ƒ}x%|D]\}}||i|s   cCs²ti|dƒ}|djoJti|dƒ}|d}|d}tt|ƒt|ƒdƒ}|Sti|dƒ}t|ƒdjotd„|ƒ}|St|ƒgS(Nt-iit:cSs t|ƒS((tint(ta((s-/usr/share/rhn/up2date_client/capabilities.pytRs(R tfindR trangeR(tlenR(R"t versionStringtindextrngtstarttendtversionstvers((s-/usr/share/rhn/up2date_client/capabilities.pytparseCapVersionFs   cCs|ii|ƒp!tdƒ|}d|i|s"       up2dateUtils.pyo000066600000004667150501002420007670 0ustar00Ñò ½ÏÅZc @s¦dZddkZddkZddkZddkZddkZddkZeiddeƒZ e i Z d„Z d„Z d„Zd„Zd „Zd „ZdS( sutility functions for up2dateiÿÿÿÿNsrhn-client-toolstfallbackcCsƒtiƒ}tiƒ}xd|iddƒD]A}|do|d}n |d}|d||df}|SWtidƒ‚dS(Nt Providenamesredhat-releasetversionOverridetversiontnametreleases{Could not determine what version of Red Hat Linux you are running. If you get this error, try running rpm --rebuilddb (tconfigtinitUp2dateConfigt transactiontinitReadOnlyTransactiontdbMatcht up2dateErrorstRpmError(tcfgttsthRtosVersionRelease((s-/usr/share/rhn/up2date_client/up2dateUtils.pyt_getOSVersionAndReleases    cCstƒ\}}}t|ƒS(s3 Returns the version of redhat-release rpm (Rtstr(t os_releaseRR((s-/usr/share/rhn/up2date_client/up2dateUtils.pyt getVersion%scCstƒ\}}}|S(s4 Returns the name of the redhat-release rpm (R(RRR((s-/usr/share/rhn/up2date_client/up2dateUtils.pyt getOSRelease,scCstƒ\}}}|S(s7 Returns the release of the redhat-release rpm (R(RRR((s-/usr/share/rhn/up2date_client/up2dateUtils.pyt getRelease3scCsxtidtiƒptiƒdStddƒ}ti|iƒƒ}hdd6}|i|ƒo||}n|S(Ns/etc/rpm/platformitrsx86_64-redhat-linuxsia32e-redhat-linux( tostaccesstR_OKtunametopentstringtstriptreadthas_key(tfdtplatformtreplace((s-/usr/share/rhn/up2date_client/up2dateUtils.pytgetArch:s cCsdS(Ns1.0.0.1-45.el6((((s-/usr/share/rhn/up2date_client/up2dateUtils.pyRJs(t__doc__RRR RRtgettextt translationtTruetttugettextt_RRRRR$R(((s-/usr/share/rhn/up2date_client/up2dateUtils.pyts            rpcServer.pyc000066600000020564150501002420007234 0ustar00Ñò ºÏÅZc@s*ddkZddkZddkZddkZddkZddkZddkZddkZddkZddk Z ddk Z ddk Z ddk Z ddk lZddkZeiddeƒZeiZd„Zdeifd„ƒYZdd d „ƒYZdddd „Zd „ZdS( iÿÿÿÿN(trpclibsrhn-client-toolstfallbackcCs |GHdS(N((tmsg((s*/usr/share/rhn/up2date_client/rpcServer.pytstdoutMsgCallbackst RetryServercBs,eZd„Zd„Zd„Zd„ZRS(cCsdS(N((tself((s*/usr/share/rhn/up2date_client/rpcServer.pytfoobarscCs ||_dS(N(t serverList(RR((s*/usr/share/rhn/up2date_client/rpcServer.pyt addServerList!sc Csætiƒ|_xÐy|i||ƒ}Wn³tij o ‚nœtij o ‚n„tij o4|ii dƒt t dƒƒt i dƒnB|iiƒ}|djo|iiƒ‚nd|i}|dt it if}|d|iiƒ}|ii |ƒddk}|i|iiƒƒ\}}|iƒ}|d jotd|ƒ‚n|i|ƒ\|_|_|i|_||_|iiƒ|_|ip d |_nd |_qnXPq|S( Ns,Error: Server Unavailable. Please try later.iÿÿÿÿs An error occured talking to %s: s%s %s sTrying the next serverURL: %s thttpthttpss%Redirected to unsupported protocol %ss/RPC2i(R R (t up2dateLogtinitLogtlogt_requestRtInvalidRedirectionErrortFaultthttplibt BadStatusLinetlog_meRt_tsystexitRtnexttNonetresetServerIndext_hosttexc_typet exc_valuetserverturllibt splittypetlowert splithostt_handlert _orig_handlert_typet_urit_allow_redirect( Rt methodnametparamstretRRRttypturi((s*/usr/share/rhn/up2date_client/rpcServer.pyt _request1$sL            cCstii|i|ƒS(N(Rt xmlrpclibt_MethodR,(Rtname((s*/usr/share/rhn/up2date_client/rpcServer.pyt __getattr__Vs(t__name__t __module__RRR,R0(((s*/usr/share/rhn/up2date_client/rpcServer.pyRs   2t ServerListcBs8eZgd„Zd„Zd„Zd„Zd„ZRS(cCs||_d|_dS(Ni(Rtindex(Rt serverlist((s*/usr/share/rhn/up2date_client/rpcServer.pyt__init__]s cCs|i|i|_|iS(N(RR4t serverurl(R((s*/usr/share/rhn/up2date_client/rpcServer.pyRascCs8|id|_|it|iƒjodS|iƒS(Ni(R4tlenRRR(R((s*/usr/share/rhn/up2date_client/rpcServer.pyRfscCs||_d|_dS(Ni(RR4(RR5((s*/usr/share/rhn/up2date_client/rpcServer.pytresetServerListls cCs d|_dS(Ni(R4(R((s*/usr/share/rhn/up2date_client/rpcServer.pyRps(R1R2R6RRR9R(((s*/usr/share/rhn/up2date_client/rpcServer.pyR3\s     cCs½tiƒ}tiƒ}|d}t|ƒtdƒjo |g}n|pdg}|dotiƒ}nd}|ptiƒ}n|}t|ƒ} d} d} |do&|dpd} |dpd} nd} xhdD]`} t i i | ƒoGt i | pqìnt i | i d ƒd } | i dƒd } PqìqìWt | iƒd|d|d| d| d|ƒ}|i| ƒ|idtiƒƒ| o|i| ƒng}|iiD]+}ti|ƒd djo |tqÌqÌ~}|orxo|D]c}t i|t iƒp:dtdƒ|f}|id|ƒti|ƒ‚n|i|ƒqWntiƒti i!ƒ}x$|D]\}}|i||ƒq™W|S(Nt sslCACertts/usr/share/rhn/RHNS-CA-CERTt enableProxytenableProxyAutht proxyUsert proxyPasswordtLANGUAGEtLC_ALLt LC_MESSAGEStLANGt:it.trefreshCallbacktproxytusernametpasswordttimeoutsX-Up2date-VersionR s%s: %ss ERROR: can not find RHNS CA files%s(R@RARBRC("R R tconfigtinitUp2dateConfigttypetgetProxySettingRt getServerlURLR3tostenvironthas_keytsplitRRRt add_headert up2dateUtilstversiontsetlangRturlparsetTruetaccesstR_OKRRt up2dateErrorstSSLCertificateFileNotFoundtadd_trusted_certt clientCapst loadLocalCapstcapst headerFormat(RFtserverOverrideRJR tcfgtcat rhns_ca_certst proxyHostt serverUrlsRR>R?tlangtenvtst_[1]titneed_cat rhns_ca_certRt headerlistt headerNametvalue((s*/usr/share/rhn/up2date_client/rpcServer.pyt getServertsl          .    c Osetiƒ}|id|idƒtiƒ}d}d}yt|dƒ}Wntj o d}nX|djo d}nxÛd}d}y|||Ž}Wn\t j ot i t dƒƒ‚n6t it ifj o}} |id| |fƒ||joJt| iƒdjot i | idƒ‚q_t i | idƒ‚qd}n¢tij odGHt i dƒ‚nytij o^} d } | d | i} | d | i} | d | i} |i| ƒt i | ƒ‚n tij oÙ} |id | i|fƒ| idjo%|id| iƒ|idƒnti| i ƒ\} } d} t!| ƒdjo|id| ƒt"i#ƒnt!| ƒdjo)|it dƒƒt i | iƒ‚nt!| ƒdjo®t$|dƒt$gƒjo|d}n |d}t$|ƒt$gƒjo*d|d|d|d|df}n|}d|| f} |i| ƒt i%| ƒ‚n| p-||jot i | iƒ‚qÛd}qn&ti&j ot i dƒ‚nX|djoPnd}|ot'i(dƒ|d}n||jot i dƒ‚q†q†|S(NsrpcServer: Calling XMLRPC %st _Method__nameitnetworkRetriesisConnection aborted by the users(A socket error occurred: %s, attempt #%sshttplib.IncompleteReads An HTTP error occurred: sURL: %s sStatus Code: %s sError Message: %s s,A protocol error occurred: %s , attempt #%s,i”sCould not find URL, %ss)Check server name and/or URL, then retry i"s'Auth token timeout occurred errmsg: %si3s.Server has refused connection due to high loadis %s-%s-%s.%siisFile Not Found: %s %ss Broken response from the server.is0The data returned from the server was incomplete()R R t log_debugt__dict__RKRLRtintt ValueErrortKeyboardInterruptR\tCommunicationErrorRtsocketterrortsslerrorRR8targsRtIncompleteReadturllib2t HTTPErrortfilenametcodeRRt ProtocolErrorterrmsgterrcodeturlt reportErrortheaderstabst up2dateAuthtupdateLoginInfoRMtFileNotFoundErrort ResponseErrorttimetsleep(tmethodRtkwargsR RdR)t attempt_counttattemptstfailureteRterrCodeterrMsgtresettpkgtpkgName((s*/usr/share/rhn/up2date_client/rpcServer.pytdoCallÀsš            *     ((RPRRKR|RRRR_R R\RURŒRXtrhnRtgettextt translationRYtttugettextRRtServerRR3RRsR(((s*/usr/share/rhn/up2date_client/rpcServer.pyts*                ?Lhardware.py000066600000070340150501002420006710 0ustar00# # Copyright (c) 1999--2010 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 import string import config import rhnserver import ethtool import gettext t = gettext.translation('rhn-client-tools', fallback=True) _ = t.ugettext import dbus import dmidecode import up2dateLog try: # F13 and EL6 from hardware_gudev import get_devices, get_computer_info using_gudev = 1 except ImportError: from 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: " % 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 = string.split(info, '=') if len(vals) <= 1: continue strippedstring = string.strip(vals[0]) vals[0] = strippedstring installdict[vals[0]] = string.strip(string.join(vals[1:])) 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: dir = os.listdir('/sys/devices/system/cpu/') except OSError: dir = [] re_cpu = re.compile(r"^cpu[0-9]+$") return len([i for i in 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 = [] for line in lines: if 'physical id' in line: socket_index = int(line.split(':')[1].strip()) if not socket_index in socket_ids: socket_ids += [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 = string.lower(entry) if not a.has_key(e): 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 string.split(cpulist, "\n\n"): if not len(cpu): continue count = count + 1 if count > 1: break # no need to parse rest for cpu_attr in string.split(cpu, "\n"): if not len(cpu_attr): continue vals = string.split(cpu_attr, ":") if len(vals) != 2: # XXX: make at least some effort to recover this data... continue name, value = string.strip(vals[0]), string.strip(vals[1]) tmpdict[string.lower(name)] = 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 = string.lower(os.uname()[4]) 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 = string.split(hz_speed) 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['vendor'] = 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 string.split(cpulist, "\n"): vals = string.split(cpu, ": ") 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 = string.split(meminfo,"\n") curline = lines[1] memlist = string.split(curline) 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 = string.split(curline) # 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 = string.split(meminfo,"\n") dict = {} for line in lines: blobs = string.split(line, ":", 1) key = blobs[0] if len(blobs) == 1: continue #print blobs value = string.strip(blobs[1]) dict[key] = value memdict = {} memdict["class"] = "MEMORY" total_str = dict['MemTotal'] blips = string.split(total_str, " ") total_k = long(blips[0]) megs = long(total_k/(1024)) swap_str = dict['SwapTotal'] blips = string.split(swap_str, ' ') 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 = cfg['serverURL'] if type(sl) == type(""): sl = [sl] 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) = string.split(server_port, ':') 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 one in /etc/sysconfig/network # for bz# 457953 if 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 = string.split(info, '=') if len(vals) <= 1: continue strippedstring = string.strip(vals[0]) vals[0] = strippedstring if vals[0] == "HOSTNAME": hostname = string.strip(string.join(vals[1:])) 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 string.find(line, "Permanent HW addr: ") != -1: hwaddr = string.split(line)[3] break if string.find(line, "Slave Interface: ") != -1: ifname = string.split(line)[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 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" interfaces = list(set(ethtool.get_devices() + ethtool.get_active_devices())) for interface in interfaces: try: hwaddr = ethtool.get_hwaddr(interface) 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: module = ethtool.get_module(interface) except: if interface == 'lo': module = "loopback" else: module = "Unknown" try: ipaddr = ethtool.get_ipaddr(interface) except: ipaddr = "" try: netmask = ethtool.get_netmask(interface) except: netmask = "" try: broadcast = ethtool.get_broadcast(interface) except: broadcast = "" ip6_list = [] 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 }) 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 = string.lower(os.uname()[4]) 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 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, e: log = up2dateLog.initLog() msg = "Error reading system and smbios information: %s\n" % (e) log.log_debug(msg) return {} system_and_smbios = {} for key in props: if key.startswith('system'): system_and_smbios[unicode(key)] = unicode(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_type) 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_type # memory size info try: ret = read_memory() if ret: allhw.append(ret) except: print _("Error reading system memory information:"), sys.exc_type 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_type # 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_type) log.log_me(msg) try: ret = read_installinfo() if ret: allhw.append(ret) except: print _("Error reading install method information:"), sys.exc_type if not cfg["skipNetwork"]: try: ret = read_network_interfaces() if ret: allhw.append(ret) except: print _("Error reading network interface information:"), sys.exc_type # 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 up2dateErrors.pyo000066600000040423150501002420010032 0ustar00Ñò ºÏÅZc @sûddkZddkZeiddeƒZeiZddkZddkZddk Z e i de i d e _ ddk l Z l Z de fd„ƒYZdefd „ƒYZd efd „ƒYZd efd „ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZd efd!„ƒYZd"eefd#„ƒYZd$efd%„ƒYZd&eefd'„ƒYZd(efd)„ƒYZd*efd+„ƒYZ d,efd-„ƒYZ!d.eefd/„ƒYZ"d0eefd1„ƒYZ#d2eefd3„ƒYZ$d4efd5„ƒYZ%d6efd7„ƒYZ&d8efd9„ƒYZ'd:e efd;„ƒYZ(d<efd=„ƒYZ)d>efd?„ƒYZ*d@efdA„ƒYZ+dBefdC„ƒYZ,dDefdE„ƒYZ-dFefdG„ƒYZ.dHefdI„ƒYZ/dJefdK„ƒYZ0dLefdM„ƒYZ1dNefdO„ƒYZ2dPefdQ„ƒYZ3dRefdS„ƒYZ4dS(TiÿÿÿÿNsrhn-client-toolstfallbacki(t RepoErrort YumBaseErrortErrorcBs8eZdZdZd„Zd„Zd„Zd„ZRS(sbase class for errorstcCs]t|tƒpt|ddƒ}nti||ƒd|i||_tiƒ|_dS(Nsutf-8tignores rhn-plugin: ( t isinstancetunicodeRt__init__tpremsgtvaluet up2dateLogtinitLogtlog(tselfterrmsg((s./usr/share/rhn/up2date_client/up2dateErrors.pyRs cCs|ii|iƒ|iS(N(R tlog_meR (R((s./usr/share/rhn/up2date_client/up2dateErrors.pyt__repr__scCsx|djo|iSttdƒoti||ƒS||ijo |i|Sttdƒ|ii|fƒ‚dS(sG Spacewalk backend still use errmsg, let have errmsg as alias to value Rt __getattr__sclass %s has no attribute '%s'N( R thasattrRRt__dict__tAttributeErrort_t __class__t__name__(Rtname((s./usr/share/rhn/up2date_client/up2dateErrors.pyR"s  cCsV|djo||id¿s tNoChannelsErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyR@Ést NetworkErrorcBseZdZedƒZRS(sC some generic network error occured, e.g. connection reset by peer sNetwork error: (RRRRR (((s./usr/share/rhn/up2date_client/up2dateErrors.pyRAÌstSSLCertificateVerifyFailedErrorcBseZd„ZeiZRS(cCstiƒ}|d}t|dƒ}|iƒ}|iƒtiitii|ƒ}|i ƒot i |d|ƒnt i |dƒdS(Nt sslCACerttrsnThe certificate %s is expired. Please ensure you have the correct certificate and your system time is correct.s(The SSL certificate failed verification.( tconfigtinitUp2dateConfigtopentreadtclosetOpenSSLtcryptotload_certificatet FILETYPE_PEMt has_expiredRR(Rt up2dateConfigtcertFiletftbufttempCert((s./usr/share/rhn/up2date_client/up2dateErrors.pyRÑs       (RRRRR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRBÐs tSSLCertificateFileNotFoundcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRTâst$AuthenticationOrAccountCreationErrorcBseZdZRS(s,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. (RRR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRUæs tNotEntitlingErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRVôstInvalidProtocolErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRW÷stUnableToCreateUsercBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRXústActivationKeyUsageLimitErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRYýstLoginMinLengthErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRZstPasswordMinLengthErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyR[stPasswordMaxLengthErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyR\stInsuffMgmntEntsErrorcBs#eZd„Zd„Zd„ZRS(cCs|i|ƒ|_dS(N(tchangeExplanationR (RR ((s./usr/share/rhn/up2date_client/up2dateErrors.pyR scCs|iS(N(R (R((s./usr/share/rhn/up2date_client/up2dateErrors.pyRscCs7tdƒ}d}|i|ƒt|ƒ}|| |S(Ns Your organization does not have enough Management entitlements to register this system to Red Hat 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 Red Hat Network and visiting the 'Subscription Management' page in the 'Your RHN' section of RHN. 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.s Explanation:(Rtrindextlen(RR tnewExplnttermtloc((s./usr/share/rhn/up2date_client/up2dateErrors.pyR^s  (RRRRR^(((s./usr/share/rhn/up2date_client/up2dateErrors.pyR] s  tNoSystemIdErrorcBseZRS((RR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRd"stInvalidRedirectionErrorcBseZdZRS(s7 Raise when redirect requests could'nt return a package(RRR(((s./usr/share/rhn/up2date_client/up2dateErrors.pyRe%s(5R tgettextt translationtTruetttugettextRRJREtsystpatht yum.ErrorsRRRRRR"R#R$R&R)R+R,R-R.R3R4R5R6R7R8R9R:R;R<R=R>R@RARBRTRURVRWRXRYRZR[R\R]RdRe(((s./usr/share/rhn/up2date_client/up2dateErrors.pyt s^      '      rhnChannel.pyc000066600000012470150501002420007336 0ustar00Ñò ¹ÏÅZc @sÉddkZddkZddkZddkZddkZeiddeƒZeiZ dd d„ƒYZ ddd„ƒYZ dd„Z gZdadddd „Zd „Zd „Zd „ZdS(iÿÿÿÿNsrhn-client-toolstfallbackt rhnChannelcBs>eZd„Zd„Zd„Zd„Zd„Zd„ZRS(cKs5h|_x%|iƒD]}|||i|eZd„Zd„Zd„Zd„Zd„Zd„ZRS(cCs g|_dS(N(tlist(R((s+/usr/share/rhn/up2date_client/rhnChannel.pyR'scCs|ii|ƒdS(N(Rtappend(Rtchannel((s+/usr/share/rhn/up2date_client/rhnChannel.pyt addChannel,scCs|iS(N(R(R((s+/usr/share/rhn/up2date_client/rhnChannel.pytchannels0scCs.x'|iD]}|d|jo|Sq WdS(Ntlabel(R(Rt channelnameR((s+/usr/share/rhn/up2date_client/rhnChannel.pyt getByLabel3s cCs |i|ƒS(N(R(RR((s+/usr/share/rhn/up2date_client/rhnChannel.pyt getByName7scCs@g}x3|iD](}|d|jo|i|ƒqqW|S(Nttype(RR(RRRR((s+/usr/share/rhn/up2date_client/rhnChannel.pyt getByType:s  (RRRRRRRR(((s+/usr/share/rhn/up2date_client/rhnChannel.pyR&s      cCsƒg}td|ƒ}xg|iƒD]Y}|ddjo5|d|dysR7(tNoneR*RtmapR!(t tempchannelst whitelist((s+/usr/share/rhn/up2date_client/rhnChannel.pyt setChannelsvscCs+tiƒ}|iitiƒ|||ƒS(N(R+R,RtsubscribeChannelsR-R.(RtusernametpasswdR9((s+/usr/share/rhn/up2date_client/rhnChannel.pyRD~s cCs+tiƒ}|iitiƒ|||ƒS(N(R+R,RtunsubscribeChannelsR-R.(RRERFR9((s+/usr/share/rhn/up2date_client/rhnChannel.pyRGƒs (((R-R/R(R+tgettextt translationtTruetttugettextR1RRR?R$t cmdline_pkgsR*R!RCRDRG(((s+/usr/share/rhn/up2date_client/rhnChannel.pyts         rhnserver.pyo000066600000012416150501002420007310 0ustar00Ñò ºÏÅZc @s|ddkZddkZddkZddkZddklZddkZdefd„ƒYZdefd„ƒYZ dS(iÿÿÿÿN(trpclibt_DoCallWrappercBs2eZdZd„Zd„Zd„Zd„ZRS(se A callable object that will handle multiple levels of attributes, and catch exceptions. cCs||_||_dS(N(t_servert _method_name(tselftservert method_name((s*/usr/share/rhn/up2date_client/rhnserver.pyt__init__%s cCst|id|i|fƒS(s= Recursively build up the method name to pass to the server. s%s.%s(RRR(RR((s*/usr/share/rhn/up2date_client/rhnserver.pyt __getattr__)s c Os1t|i|iƒ}yti|||ŽSWnþtij o}|i|ƒ‚nÙti i j oÆ}t |ƒ}|i dƒ}|i dƒ}d}t|ƒdjo|d}n"t|ƒdjo|d}n|i dƒ}|djotiƒ‚q-ti|ƒdtiƒd‚nXdS( s3 Call the method. Catch faults and translate them. s[()]t,tiis 'scertificate verify failedN(tgetattrRRt rpcServertdoCallRtFaultt$_DoCallWrapper__exception_from_faulttOpenSSLtSSLtErrortstrtstriptsplittlent up2dateErrorstSSLCertificateVerifyFailedErrort NetworkErrortNonetsystexc_info( Rtargstkwargstmethodtfteterrortpiecestmessage((s*/usr/share/rhn/up2date_client/rhnserver.pyt__call__.s$  cCs¨|idjoti|iƒ}n|idjoti|iƒ}nY|idjoti|iƒ}n3|idjoti|iƒ}n |idjoti|iƒ}nç|idjoti|iƒ}nÁ|idjoti|iƒ}n›|idjoti|iƒ}nu|id joti |iƒ}nO|id joti |iƒ}n)t |iƒd joti |iƒ}nýt |iƒd joti |iƒ}nÑt |iƒd joti|iƒ}n¥|idjoti|iƒ}nt |iƒdjoti |iƒ}nS|idjoti|iƒ}n-|idjoti|iƒ}n|idjoti|iƒ}ná|idjoti|iƒ}n»|idjp|idjoti|iƒ}n…|idjoti|iƒ}n_|idjoti|iƒ}n9|idjoti|iƒ}nti|iƒ}|S(NiýÿÿÿiþÿÿÿiÿÿÿÿióÿÿÿiòÿÿÿiñÿÿÿiðÿÿÿiíÿÿÿiáÿÿÿiÜÿÿÿi1i<iiici[i–ÿÿÿi¨ýÿÿi§ýÿÿi¦ýÿÿi/øÿÿiDýÿÿiCýÿÿiÃÿÿÿiûÿÿÿ(t faultCodeRt$AuthenticationOrAccountCreationErrort faultStringtUnknownMethodExceptiontLoginMinLengthErrortPasswordMinLengthErrortValidationErrortNoBaseChannelErrortInsuffMgmntEntsErrort PasswordErrortabst AbuseErrortAuthenticationTicketErrortRhnUuidUniquenessErrort DelayErrortInvalidRegistrationNumberErrortNotEntitlingErrortPasswordMaxLengthErrortActivationKeyUsageLimitErrortUnableToCreateUsertCommunicationError(Rtfaultt exception((s*/usr/share/rhn/up2date_client/rhnserver.pyt__exception_from_faultHsj (t__name__t __module__t__doc__RRR%R(((s*/usr/share/rhn/up2date_client/rhnserver.pyRs    t RhnServercBsGeZdZdddd„Zd„ZeeƒZd„Zd„Z RS(sb An rpc server object that calls doCall for you, and catches lower level exceptions cCsB|djotid|d|ƒ|_n ||_d|_dS(NtserverOverridettimeout(RR t getServerRt _capabilities(RRBRCtrpcServerOverride((s*/usr/share/rhn/up2date_client/rhnserver.pyR˜s   cCsv|idjo_|iiƒ}|djo |iiƒ|iiƒ}ntiƒ|_|ii|ƒn|iS(N( RERRtget_response_headerst registrationtwelcome_messaget capabilitiest Capabilitiestpopulate(Rtheaders((s*/usr/share/rhn/up2date_client/rhnserver.pyt__get_capabilities s  cCs|ii||ƒdS(N(Rt add_header(Rtkeytvalue((s*/usr/share/rhn/up2date_client/rhnserver.pyRO¬scCst|i|ƒS(s8 Return a callable object that will do the work for us. (RR(RR((s*/usr/share/rhn/up2date_client/rhnserver.pyR¯sN( R>R?R@RRt_RhnServer__get_capabilitiestpropertyRJROR(((s*/usr/share/rhn/up2date_client/rhnserver.pyRA‘s   ( RR RRJtrhnRRtobjectRRA(((s*/usr/share/rhn/up2date_client/rhnserver.pyts     sup2dateAuth.pyc000066600000013652150501002420007447 0ustar00Ñò ¹ÏÅZc@sÿddkZddkZddkZddkZddkZddkZddkZddkZddkZddk Z ddk l Z ddk l Z dadZd„Zd„Zd„Zd„Zd „Zdedd „Zdd „Zdd „ZdS( iÿÿÿÿN(tDictType(trpclibs /var/spool/up2date/loginAuth.pklcCsZtiƒ}|d}ti|tiƒpdSt|dƒ}|iƒ}|iƒ|S(Nt systemIdPathtr( tconfigtinitUp2dateConfigtostaccesstR_OKtNonetopentreadtclose(tcfgtpathtftret((s,/usr/share/rhn/up2date_client/up2dateAuth.pyt getSystemIds    c Csytiƒ}y%tiitƒƒddd}WndSXtiƒ}||jo ti ƒ}|i i tƒ|ƒ}|d}|t i |dƒ }ti|tiƒp yti|ƒWqÏdSXnti|tiƒpdSti|tiƒo-|d}yti||ƒWq-dSXnt|dƒ}|i|ƒ|iƒyti|dƒWququXndS(Nit os_releaseRt/s.savetwi€(RRRt xmlrpclibtloadsRt up2dateUtilst getVersiont rhnservert RhnServert registrationtupgrade_versiontstringtrfindRRtW_OKtmkdirtF_OKtrenameR twriteR tchmod( R tidVert systemVertst newSystemIdRtdirtsavePathR((s,/usr/share/rhn/up2date_client/up2dateAuth.pytmaybeUpdateVersion%s> %         c Cs'tiƒ}|idƒtp|idƒtShtiƒd6td6}tiit ƒ}ti |ti ƒpAy!ti |ƒti |dƒWqµ|id|ƒtSXntt dƒ}ti t dƒti||ƒ|iƒ|dttd ƒ}|id |dd |d ƒtS( s› Pickle loginInfo to a file Returns: True -- wrote loginInfo to a pickle file False -- did _not_ write loginInfo to a pickle file swriteCachedLogin() invokeds1writeCachedLogin() loginInfo is None, so bailing.ttimet loginInfoiÀs'Unable to write pickled loginInfo to %stwbi€sX-RHN-Auth-Expire-OffsetsWrote pickled loginInfo at s with expiration of s seconds.(t up2dateLogtinitLogt log_debugR-tFalseR,RRtdirnametpcklAuthFileNameRRR R$tlog_meR tpickletdumpR tfloattTrue(tlogtdatatpcklDirtpcklAutht expireTime((s,/usr/share/rhn/up2date_client/up2dateAuth.pytwriteCachedLoginOs.        c Cs@tiƒ}|idƒtittiƒp|idtƒtSttdƒ}yt i |ƒ}Wn+t j o|idƒ|i ƒtSX|i ƒ|d}|d}t i ƒ}|t|dƒ}|id|d |d t|dƒƒ||jo|id ||fƒtSt|ƒ|id |ƒtS( sb Read pickle info from a file Caches authorization info for connecting to the server. sreadCachedLogin invokeds'Unable to read pickled loginInfo at: %strbsSUnexpected EOF. Probably an empty file, regenerate auth fileR,R-sX-RHN-Auth-Expire-Offsets(Checking pickled loginInfo, currentTime=s , createTime=s, expire-offset=s9Pickled loginInfo has expired, created = %s, expire = %s.s<readCachedLogin(): using pickled loginInfo set to expire at (R/R0R1RRR4RR2R R6tloadtEOFErrorR R,R8t_updateLoginInfoR9(R:R=R;t createdTimetlit currentTimeR>((s,/usr/share/rhn/up2date_client/up2dateAuth.pytreadCachedLoginos8            cCsKt|ƒtjo.ttƒtjoti|ƒqG|andadS(s, Update the global var, "loginInfo" N(ttypeRR-tupdateR (RE((s,/usr/share/rhn/up2date_client/up2dateAuth.pyRC’s  c Cstiƒ}|id|ƒ| ot otƒotSntid|ƒ}tii ƒ}x$|D]\}}|i ||ƒqhW|djo t ƒ}n|pdSt ƒ|idƒ|ii|ƒ}|iiƒt|ƒtƒto|idƒn|idtƒtS(Nslogin(forceUpdate=%s) invokedttimeoutslogging into up2date servers?successfully retrieved authentication token from up2date servers logininfo:(R/R0R1R-RGRRt clientCapstcapst headerFormatt add_headerR RR+R5tup2datetlogint capabilitiestvalidateRCR?( tsystemIdt forceUpdateRJR:tservert headerlistt headerNametvalueRE((s,/usr/share/rhn/up2date_client/up2dateAuth.pyRP£s0         cCsJtiƒ}|idƒtdtd|ƒtptidƒ‚ntS(NsupdateLoginInfo() login infoRTRJsUnable to authenticate(R/R0R5RPR9R-t up2dateErrorstAuthenticationError(RJR:((s,/usr/share/rhn/up2date_client/up2dateAuth.pytupdateLoginInfoÈs   cCsCy taWntj o danXtotStd|ƒtS(NRJ(R-t NameErrorR RP(RJ((s,/usr/share/rhn/up2date_client/up2dateAuth.pyt getLoginInfoÒs   (RRRRYRRR/RKR6R,ttypesRtrhnRR R-R4RR+R?RGRCR2RPR[R](((s,/usr/share/rhn/up2date_client/up2dateAuth.pyts*            * # % __init__.pyc000066600000000200150501002420007001 0ustar00Ñò ú4™Pc@sdS(N((((s)/usr/share/rhn/up2date_client/__init__.pytsup2dateErrors.py000066600000022744150501002420007661 0ustar00# # Client code for Update Agent # Copyright (c) 1999-2002 Red Hat, Inc. Distributed under GPL. # # Author: Preston Brown # Adrian Likins # import up2dateLog import gettext t = gettext.translation('rhn-client-tools', fallback=True) _ = t.ugettext import OpenSSL import config import sys sys.path = sys.path[1:] + sys.path[:1] from yum.Errors import RepoError, YumBaseError class Error(YumBaseError): """base class for errors""" premsg = '' def __init__(self, errmsg): if not isinstance(errmsg, unicode): errmsg = unicode(errmsg, 'utf-8', 'ignore') YumBaseError.__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(YumBaseError, '__getattr__'): # rhel5 has no __getattribute__() return YumBaseError.__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(YumBaseError, '__setattr__'): # rhel5 has no __setattr__() YumBaseError.__setattr__(self, name, value) else: self.__dict__[name] = value class RpmError(Error): """rpm itself raised an error condition""" premsg = _("RPM error. The message was:\n") class RpmInstallError(Error): """Raise when a package fails to install properly""" def __init__(self, msg, pkg = None): self.errmsg = msg self.pkg = pkg def __repr__(self): msg = _("There was a fatal error installing the package:\n") msg = msg + self.errmsg log = up2dateLog.initLog() log.log_me(msg) return msg 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 UnsolvedDependencyError(Error): """Raise when we have a dependency that the server can not find""" def __init__(self, msg, dep=None, pkgs=None): self.errmsg = msg self.dep = dep self.pkgs = pkgs def __repr__(self): msg = _("RPM dependency error. The message was:\n") + self.errmsg log = up2dateLog.initLog() log.log_me(msg) return msg class SkipListError(Error): """Raise when all the packages you want updated are on a skip list""" def __init__(self, msg, pkglist=None): self.errmsg = msg self.pkglist = pkglist def __repr__(self): msg = _("Package Skip List error. The message was:\n") + self.errmsg log = up2dateLog.initLog() log.log_me(msg) return msg 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): self.args = args self.value = "" for key in self.args.keys(): if not isinstance(errmsg, self.args[key]): self.args[key] = unicode(self.args[key], 'utf-8', 'ignore') 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): if not isinstance(msg, unicode): msg = unicode(msg, 'utf-8', 'ignore') 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 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 occured, 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 ): self.value = 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 Red Hat 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 Red Hat Network and visiting the 'Subscription Management' page in the 'Your RHN' section of RHN. 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