Package up2date_client :: Module up2dateAuth
[hide private]
[frames] | no frames]

Source Code for Module up2date_client.up2dateAuth

  1  # 
  2   
  3  import os 
  4  import pickle 
  5  import time 
  6   
  7  try: # python2 
  8      from types import DictType 
  9  except ImportError: # python3 
 10      DictType = dict 
 11   
 12  from rhn import rpclib 
 13  from up2date_client import clientCaps 
 14  from up2date_client import config 
 15  from up2date_client import rhnserver 
 16  from up2date_client import up2dateErrors 
 17  from up2date_client import up2dateLog 
 18  from up2date_client import up2dateUtils 
 19   
 20  loginInfo = None 
 21  pcklAuthFileName = "/var/spool/up2date/loginAuth.pkl" 
 22   
23 -def getSystemId():
24 cfg = config.initUp2dateConfig() 25 path = cfg["systemIdPath"] 26 if not os.access(path, os.R_OK): 27 return None 28 29 f = open(path, "r") 30 ret = f.read() 31 32 f.close() 33 return ret
34 35 # if a user has upgraded to a newer release of Red Hat but still 36 # has a systemid from their older release, they need to get an updated 37 # systemid from the RHN servers. This takes care of that.
38 -def maybeUpdateVersion():
39 cfg = config.initUp2dateConfig() 40 try: 41 idVer = rpclib.xmlrpclib.loads(getSystemId())[0][0]['os_release'] 42 except: 43 # they may not even have a system id yet. 44 return 0 45 46 systemVer = up2dateUtils.getVersion() 47 48 if idVer != systemVer: 49 s = rhnserver.RhnServer() 50 51 newSystemId = s.registration.upgrade_version(getSystemId(), systemVer) 52 53 path = cfg["systemIdPath"] 54 dir = path[:path.rfind("/")] 55 if not os.access(dir, os.W_OK): 56 try: 57 os.mkdir(dir) 58 except: 59 return 0 60 if not os.access(dir, os.W_OK): 61 return 0 62 63 if os.access(path, os.F_OK): 64 # already have systemid file there; let's back it up 65 savePath = path + ".save" 66 try: 67 os.rename(path, savePath) 68 except: 69 return 0 70 71 f = open(path, "w") 72 f.write(newSystemId) 73 f.close() 74 try: 75 os.chmod(path, int('0600', 8)) 76 except: 77 pass
78 79
80 -def writeCachedLogin():
81 """ 82 Pickle loginInfo to a file 83 Returns: 84 True -- wrote loginInfo to a pickle file 85 False -- did _not_ write loginInfo to a pickle file 86 """ 87 log = up2dateLog.initLog() 88 log.log_debug("writeCachedLogin() invoked") 89 if not loginInfo: 90 log.log_debug("writeCachedLogin() loginInfo is None, so bailing.") 91 return False 92 data = {'time': time.time(), 93 'loginInfo': loginInfo} 94 95 pcklDir = os.path.dirname(pcklAuthFileName) 96 if not os.access(pcklDir, os.W_OK): 97 try: 98 os.mkdir(pcklDir) 99 os.chmod(pcklDir, int('0700', 8)) 100 except: 101 log.log_me("Unable to write pickled loginInfo to %s" % pcklDir) 102 return False 103 pcklAuth = open(pcklAuthFileName, 'wb') 104 os.chmod(pcklAuthFileName, int('0600', 8)) 105 pickle.dump(data, pcklAuth) 106 pcklAuth.close() 107 expireTime = data['time'] + float(loginInfo['X-RHN-Auth-Expire-Offset']) 108 log.log_debug("Wrote pickled loginInfo at ", data['time'], " with expiration of ", 109 expireTime, " seconds.") 110 return True
111
112 -def readCachedLogin():
113 """ 114 Read pickle info from a file 115 Caches authorization info for connecting to the server. 116 """ 117 log = up2dateLog.initLog() 118 log.log_debug("readCachedLogin invoked") 119 if not os.access(pcklAuthFileName, os.R_OK): 120 log.log_debug("Unable to read pickled loginInfo at: %s" % pcklAuthFileName) 121 return False 122 pcklAuth = open(pcklAuthFileName, 'rb') 123 try: 124 data = pickle.load(pcklAuth) 125 except (EOFError, ValueError): 126 log.log_debug("Unexpected EOF. Probably an empty file, \ 127 regenerate auth file") 128 pcklAuth.close() 129 return False 130 pcklAuth.close() 131 # Check if system_id has changed 132 try: 133 idVer = rpclib.xmlrpclib.loads(getSystemId())[0][0]['system_id'] 134 cidVer = "ID-%s" % data['loginInfo']['X-RHN-Server-Id'] 135 if idVer != cidVer: 136 log.log_debug("system id version changed: %s vs %s" % (idVer, cidVer)) 137 return False 138 except: 139 pass 140 createdTime = data['time'] 141 li = data['loginInfo'] 142 currentTime = time.time() 143 expireTime = createdTime + float(li['X-RHN-Auth-Expire-Offset']) 144 #Check if expired, offset is stored in "X-RHN-Auth-Expire-Offset" 145 log.log_debug("Checking pickled loginInfo, currentTime=", currentTime, 146 ", createTime=", createdTime, ", expire-offset=", 147 float(li['X-RHN-Auth-Expire-Offset'])) 148 if (currentTime > expireTime): 149 log.log_debug("Pickled loginInfo has expired, created = %s, expire = %s." \ 150 %(createdTime, expireTime)) 151 return False 152 _updateLoginInfo(li) 153 log.log_debug("readCachedLogin(): using pickled loginInfo set to expire at ", expireTime) 154 return True
155
156 -def _updateLoginInfo(li):
157 """ 158 Update the global var, "loginInfo" 159 """ 160 global loginInfo 161 if type(li) == DictType: 162 if type(loginInfo) == DictType: 163 # must retain the reference. 164 loginInfo.update(li) 165 else: 166 # this had better be the initial login or we lose the reference. 167 loginInfo = li 168 else: 169 loginInfo = None
170 171 # allow to pass in a system id for use in rhnreg 172 # a bit of a kluge to make caps work correctly
173 -def login(systemId=None, forceUpdate=False, timeout=None):
174 log = up2dateLog.initLog() 175 log.log_debug("login(forceUpdate=%s) invoked" % (forceUpdate)) 176 if not forceUpdate and not loginInfo: 177 if readCachedLogin(): 178 return loginInfo 179 180 server = rhnserver.RhnServer(timeout=timeout) 181 182 # send up the capabality info 183 headerlist = clientCaps.caps.headerFormat() 184 for (headerName, value) in headerlist: 185 server.add_header(headerName, value) 186 187 if systemId == None: 188 systemId = getSystemId() 189 190 if not systemId: 191 return None 192 193 maybeUpdateVersion() 194 log.log_me("logging into up2date server") 195 196 li = server.up2date.login(systemId) 197 198 # figure out if were missing any needed caps 199 server.capabilities.validate() 200 _updateLoginInfo(li) #update global var, loginInfo 201 writeCachedLogin() #pickle global loginInfo 202 203 if loginInfo: 204 log.log_me("successfully retrieved authentication token " 205 "from up2date server") 206 207 log.log_debug("logininfo:", loginInfo) 208 return loginInfo
209
210 -def updateLoginInfo(timeout=None):
211 log = up2dateLog.initLog() 212 log.log_me("updateLoginInfo() login info") 213 # NOTE: login() updates the loginInfo object 214 login(forceUpdate=True, timeout=timeout) 215 if not loginInfo: 216 raise up2dateErrors.AuthenticationError("Unable to authenticate") 217 return loginInfo
218 219
220 -def getLoginInfo(timeout=None):
221 global loginInfo 222 try: 223 loginInfo = loginInfo 224 except NameError: 225 loginInfo = None 226 if loginInfo: 227 return loginInfo 228 # NOTE: login() updates the loginInfo object 229 login(timeout=timeout) 230 return loginInfo
231