def __init__(self, db, seq): if not seq or not isinstance(seq, str): raise rhnException("First argument needs to be a sequence name", seq) self.__seq = seq if not isinstance(db, sql_base.Database): raise rhnException("Argument db is not a database instance", db) self.__db = db
def select(self, row): if not isinstance(row, dict) and not isinstance(row, UserDictCase): raise rhnException("Expecting hash argument. %s is invalid" % type(row), row) if row == {}: raise rhnException("The hash argument is empty", row) keys = row.keys() # Sort the list of keys, to always get the same list of arguments keys.sort() args = [] for col in keys: if row[col] in (None, ''): clause = "%s is null" % col else: clause = "%s = :%s" % (col, col) args.append(clause) sql = "select * from %s where " % self.__table cursor = self.__db.prepare(sql + string.join(args, " and ")) cursor.execute(**row) rows = cursor.fetchall_dict() if rows is None: return None # fill up the cache if self.__cache is not None: for row in rows: self.__cache[row[self.__hashid]] = row return map(lambda a: UserDictCase(a), rows)
def select(self, row): if not isinstance(row, dict) and not isinstance(row, UserDictCase): raise rhnException( "Expecting hash argument. %s is invalid" % type(row), row) if row == {}: raise rhnException("The hash argument is empty", row) keys = row.keys() # Sort the list of keys, to always get the same list of arguments keys.sort() args = [] for col in keys: if row[col] in (None, ''): clause = "%s is null" % col else: clause = "%s = :%s" % (col, col) args.append(clause) sql = "select * from %s where " % self.__table cursor = self.__db.prepare(sql + string.join(args, " and ")) cursor.execute(**row) rows = cursor.fetchall_dict() if rows is None: return None # fill up the cache if self.__cache is not None: for row in rows: self.__cache[row[self.__hashid]] = row return map(lambda a: UserDictCase(a), rows)
def __init__(self, db, table, hashid, cache=False): if not table or not isinstance(table, str): raise rhnException("First argument needs to be a table name", table) self.__table = table if not hashid or not isinstance(hashid, str): raise rhnException("Second argument needs to be the name of the unique index column", hashid) self.__hashid = hashid if not isinstance(db, sql_base.Database): raise rhnException("Argument db is not a database instance", db) self.__db = db self.__cache = None if cache: self.__cache = {}
def __create_server_group(group_label, org_id, maxnum=''): """ create the initial server groups for a new server """ # Add this new server to the pending group h = rhnSQL.prepare(""" select sg.id, sg.current_members from rhnServerGroup sg where sg.group_type = ( select id from rhnServerGroupType where label = :group_label ) and sg.org_id = :org_id """) h.execute(org_id=org_id, group_label=group_label) data = h.fetchone_dict() if not data: # create the requested group ret_id = rhnSQL.Sequence("rhn_server_group_id_seq")() h = rhnSQL.prepare(""" insert into rhnServerGroup ( id, name, description, max_members, group_type, org_id) select :new_id, sgt.name, sgt.name, :maxnum, sgt.id, :org_id from rhnServerGroupType sgt where sgt.label = :group_label """) rownum = h.execute(new_id=ret_id, org_id=org_id, group_label=group_label, maxnum=str(maxnum)) if rownum == 0: # No rows were created, probably invalid label raise rhnException("Could not create new group for org=`%s'" % org_id, group_label) else: ret_id = data["id"] return ret_id
def check_password(username, password, service): global __username, __password auth = PAM.pam() auth.start(service, username, __pam_conv) # Save the username and passwords in the globals, the conversation # function needs access to them __username = username __password = password try: try: auth.authenticate() auth.acct_mgmt() finally: # Something to be always executed - cleanup __username = __password = None except PAM.error: e = sys.exc_info()[1] resp, code = e.args[:2] log_error("Password check failed (%s): %s" % (code, resp)) return 0 except: raise_with_tb(rhnException('Internal PAM error'), sys.exc_info()[2]) else: # Good password return 1
def check_password(self, password): """ simple check for a password that might become more complex sometime """ good_pwd = str(self.contact["password"]) old_pwd = str(self.contact["old_password"]) if CFG.pam_auth_service: # a PAM service is defined # We have to check the user's rhnUserInfo.use_pam_authentication # XXX Should we create yet another __init_blah function? # since it's the first time we had to lool at rhnUserInfo, # I'll assume it's not something to happen very frequently, # so I'll use a query for now # - misa # h = rhnSQL.prepare(""" select ui.use_pam_authentication from web_contact w, rhnUserInfo ui where w.login_uc = UPPER(:login) and w.id = ui.user_id""") h.execute(login=self.contact["login"]) data = h.fetchone_dict() if not data: # This should not happen raise rhnException("No entry found for user %s" % self.contact["login"]) if data['use_pam_authentication'] == 'Y': # use PAM import rhnAuthPAM return rhnAuthPAM.check_password(self.contact["login"], password, CFG.pam_auth_service) # If the entry in rhnUserInfo is 'N', perform regular # authentication return check_password(password, good_pwd, old_pwd)
def update_kickstart_session(server_id, action_id, action_status, kickstart_state, next_action_type): log_debug(3, server_id, action_id, action_status, kickstart_state, next_action_type) # Is this a kickstart-related action? ks_session_id = get_kickstart_session_id(server_id, action_id) if ks_session_id is None: # Nothing more to do log_debug(4, "Kickstart session not found") return None # Check the current action state if action_status == 2: # Completed ks_status = kickstart_state # Get the next action - it has to be of the right type next_action_id = get_next_action_id(action_id, next_action_type) elif action_status == 3: # Failed ks_status = 'failed' next_action_id = None else: raise rhnException("Invalid action state %s" % action_status) update_ks_session_table(ks_session_id, ks_status, next_action_id, server_id) return ks_session_id
def __create_server_group(group_label, org_id): """ create the initial server groups for a new server """ # Add this new server to the pending group h = rhnSQL.prepare(""" select sg.id, sg.current_members from rhnServerGroup sg where sg.group_type = ( select id from rhnServerGroupType where label = :group_label ) and sg.org_id = :org_id """) h.execute(org_id=org_id, group_label=group_label) data = h.fetchone_dict() if not data: # create the requested group ret_id = rhnSQL.Sequence("rhn_server_group_id_seq")() h = rhnSQL.prepare(""" insert into rhnServerGroup ( id, name, description, group_type, org_id) select :new_id, sgt.name, sgt.name, sgt.id, :org_id from rhnServerGroupType sgt where sgt.label = :group_label """) rownum = h.execute(new_id=ret_id, org_id=org_id, group_label=group_label) if rownum == 0: # No rows were created, probably invalid label raise rhnException("Could not create new group for org=`%s'" % org_id, group_label) else: ret_id = data["id"] return ret_id
def join_groups(self): """ For a new server, join server groups """ # Sanity check - we should always have a user if not self.user: raise rhnException("User not specified") server_id = self.getid() user_id = self.user.getid() h = rhnSQL.prepare( """ select system_group_id from rhnUserDefaultSystemGroups where user_id = :user_id """ ) h.execute(user_id=user_id) while 1: row = h.fetchone_dict() if not row: break server_group_id = row["system_group_id"] log_debug(5, "Subscribing server to group %s" % server_group_id) server_lib.join_server_group(server_id, server_group_id)
def _execute_wrapper(self, function, *p, **kw): params = ','.join(["%s: %s" % (key, value) for key, value in list(kw.items())]) log_debug(5, "Executing SQL: \"%s\" with bind params: {%s}" % (self.sql, params)) if self.sql is None: raise rhnException("Cannot execute empty cursor") if self.blob_map: for blob_var in list(self.blob_map.keys()): kw[blob_var] = BufferType(kw[blob_var]) try: retval = function(*p, **kw) except psycopg2.InternalError: e = sys.exc_info()[1] error_code = 99999 m = re.match('ERROR: +-([0-9]+)', e.pgerror) if m: error_code = int(m.group(1)) raise sql_base.SQLSchemaError(error_code, e.pgerror, e) except psycopg2.ProgrammingError: e = sys.exc_info()[1] raise sql_base.SQLStatementPrepareError(self.dbh, e.pgerror, self.sql) except KeyError: e = sys.exc_info()[1] raise sql_base.SQLError("Unable to bound the following variable(s): %s" % (string.join(e.args, " "))) return retval
def __init__(self, dbh, sql=None, force=None, blob_map=None): try: sql_base.Cursor.__init__(self, dbh=dbh, sql=sql, force=force) self._type_mapping = ORACLE_TYPE_MAPPING self.blob_map = blob_map except sql_base.SQLSchemaError: e = sys.exc_info()[1] (errno, errmsg) = e.errno, e.errmsg if 900 <= errno <= 999: # Per Oracle's documentation, SQL parsing error raise_with_tb( sql_base.SQLStatementPrepareError(self.dbh, errmsg, self.sql), sys.exc_info()[2]) # XXX: we should be handling the lost connection cases # in here too, but we don't get that many of these and # besides, this is much harder to get right # XXX: Normally we expect the e.args to include a dump of # the SQL code we just passed in since we're dealing with # an OracleError. I hope this is always the case, of not, # we'll have to log the sql code here raise_with_tb(rhnException("Can not prepare statement", e.args), sys.exc_info()[2])
def getSourcePackagePath(self, _pkgFilename): """Returns the path to a package. OVERLOAD this in server and proxy rhnRepository. I.e.: they construct the path differently. """ # pylint: disable=R0201 raise rhnException("This function should be overloaded.")
def reload(self, server, reload_all=0): log_debug(4, server, "reload_all = %d" % reload_all) if not self.server.load(int(server)): log_error("Could not find server record for reload", server) raise rhnFault(29, "Could not find server record in the database") self.cert = None # it is lame that we have to do this h = rhnSQL.prepare(""" select label from rhnServerArch where id = :archid """) h.execute(archid=self.server["server_arch_id"]) data = h.fetchone_dict() if not data: raise rhnException( "Found server with invalid numeric " "architecture reference", self.server.data) self.archname = data['label'] # we don't know this one anymore (well, we could look for, but # why would we do that?) self.user = None self.addr.update(self.fetch_addr()) # XXX: Fix me if reload_all: if not self.reload_packages_byid(self.server["id"]) == 0: return -1 if not self.reload_hardware_byid(self.server["id"]) == 0: return -1 return 0
def _push_config_file(self, file): config_info_query = self._query_lookup_non_symlink_config_info if self._is_link(file) and file.get("symlink"): config_info_query = self._query_lookup_symlink_config_info # Look up the config info first h = rhnSQL.prepare(config_info_query) h.execute(**file) row = h.fetchone_dict() if not row: # Hmm raise rhnException("This query should always return a row") config_info_id = row['id'] file['config_info_id'] = config_info_id # Look up the config file itself h = rhnSQL.prepare(self._query_lookup_config_file) h.execute(**file) row = h.fetchone_dict() if row: # Yay we already have this file # Later down the road, we're going to update modified for this # table file['config_file_id'] = row['id'] return # Have to insert this config file, gotta use the api to keep quotas up2date... insert_call = rhnSQL.Function("rhn_config.insert_file", rhnSQL.types.NUMBER()) file['config_file_id'] = insert_call(file['config_channel_id'], file['path'])
def reload(self, server, reload_all=0): log_debug(4, server, "reload_all = %d" % reload_all) if not self.server.load(int(server)): log_error("Could not find server record for reload", server) raise rhnFault(29, "Could not find server record in the database") self.cert = None # it is lame that we have to do this h = rhnSQL.prepare(""" select label from rhnServerArch where id = :archid """) h.execute(archid=self.server["server_arch_id"]) data = h.fetchone_dict() if not data: raise rhnException("Found server with invalid numeric " "architecture reference", self.server.data) self.archname = data['label'] # we don't know this one anymore (well, we could look for, but # why would we do that?) self.user = None # XXX: Fix me if reload_all: if not self.reload_packages_byid(self.server["id"]) == 0: return -1 if not self.reload_hardware_byid(self.server["id"]) == 0: return -1 return 0
def _execute_wrapper(self, function, *p, **kw): params = ",".join(["%s: %s" % (repr(key), repr(value)) for key, value in kw.items()]) log_debug(5, 'Executing SQL: "%s" with bind params: {%s}' % (self.sql, params)) if self.sql is None: raise rhnException("Cannot execute empty cursor") if self.blob_map: blob_content = {} for orig_blob_var in self.blob_map.keys(): new_blob_var = orig_blob_var + "_blob" blob_content[new_blob_var] = kw[orig_blob_var] kw[new_blob_var] = self.var(cx_Oracle.BLOB) del kw[orig_blob_var] modified_params = self._munge_args(kw) try: retval = apply(function, p, kw) except self.OracleError, e: ret = self._get_oracle_error_info(e) if isinstance(ret, types.StringType): raise sql_base.SQLError(self.sql, p, kw, ret), None, sys.exc_info()[2] (errno, errmsg) = ret[:2] if 900 <= errno <= 999: # Per Oracle's documentation, SQL parsing error raise sql_base.SQLStatementPrepareError(errno, errmsg, self.sql), None, sys.exc_info()[2] if errno == 1475: # statement needs to be reparsed; force a prepare again if self.reparsed: # useless, tried that already. give up log_error("Reparsing cursor did not fix it", self.sql) args = ("Reparsing tried and still got this",) + tuple(ret) raise sql_base.SQLError(*args), None, sys.exc_info()[2] self._real_cursor = self.dbh.prepare(self.sql) self.reparsed = 1 apply(self._execute_wrapper, (function,) + p, kw) elif 20000 <= errno <= 20999: # error codes we know we raise as schema errors raise sql_base.SQLSchemaError(*ret), None, sys.exc_info()[2] raise apply(sql_base.SQLError, ret), None, sys.exc_info()[2]
def handler(self, req): """ Main handler to handle all requests pumped through this server. """ ret = rhnApache.handler(self, req) if ret != apache.OK: return ret log_debug(4, "METHOD", req.method) log_debug(4, "PATH_INFO", req.path_info) log_debug(4, "URI (full path info)", req.uri) log_debug(4, "Component", self._component) if self._component == COMPONENT_BROKER: from broker import rhnBroker handlerObj = rhnBroker.BrokerHandler(req) else: # Redirect from redirect import rhnRedirect handlerObj = rhnRedirect.RedirectHandler(req) try: ret = handlerObj.handler() except rhnFault as e: return self.response(req, e) if rhnFlags.test("NeedEncoding"): return self.response(req, ret) # All good; we expect ret to be an HTTP return code if not isinstance(ret, type(1)): raise rhnException("Invalid status code type %s" % type(ret)) log_debug(1, "Leaving with status code %s" % ret) return ret
def initDB(backend=None, host=None, port=None, username=None, password=None, database=None, sslmode=None, sslrootcert=None): """ Initialize the database. Either we get backend and all parameter which means the caller knows what they are doing, or we populate everything from the config files. """ if backend is None: if CFG is None or not CFG.is_initialized(): initCFG('server') backend = CFG.DB_BACKEND host = CFG.DB_HOST port = CFG.DB_PORT database = CFG.DB_NAME username = CFG.DB_USER password = CFG.DB_PASSWORD sslmode = None sslrootcert = None if CFG.DB_SSL_ENABLED: sslmode = 'verify-full' sslrootcert = CFG.DB_SSLROOTCERT if backend not in SUPPORTED_BACKENDS: raise rhnException("Unsupported database backend", backend) if port: port = int(port) # Hide the password add_to_seclist(password) try: __init__DB(backend, host, port, username, password, database, sslmode, sslrootcert) __init__DB2(backend, host, port, username, password, database, sslmode, sslrootcert) # except (rhnException, SQLError): # raise # pass on, we know those ones # except (KeyboardInterrupt, SystemExit): # raise except SQLConnectError, e: try: global __DB global __DB2 del __DB del __DB2 except NameError: pass raise e
def initDB(backend=None, host=None, port=None, username=None, password=None, database=None, sslmode=None, sslrootcert=None, initsecond=False): """ Initialize the database. Either we get backend and all parameter which means the caller knows what they are doing, or we populate everything from the config files. initsecond: If set to True it initialize a second DB connection. By default only one DB connection is needed. """ if backend is None: if CFG is None or not CFG.is_initialized(): initCFG('server') backend = CFG.DB_BACKEND host = CFG.DB_HOST port = CFG.DB_PORT database = CFG.DB_NAME username = CFG.DB_USER password = CFG.DB_PASSWORD sslmode = None sslrootcert = None if CFG.DB_SSL_ENABLED: sslmode = 'verify-full' sslrootcert = CFG.DB_SSLROOTCERT if backend not in SUPPORTED_BACKENDS: raise rhnException("Unsupported database backend", backend) if port: port = int(port) # Hide the password add_to_seclist(password) try: if initsecond == False: __init__DB(backend, host, port, username, password, database, sslmode, sslrootcert) else: __init__DB2(backend, host, port, username, password, database, sslmode, sslrootcert) # except (rhnException, SQLError): # raise # pass on, we know those ones # except (KeyboardInterrupt, SystemExit): # raise except SQLConnectError: e = sys.exc_info()[1] try: closeDB() except NameError: pass raise_with_tb(e, sys.exc_info()[2]) except: raise #e_type, e_value = sys.exc_info()[:2] # raise rhnException("Could not initialize Oracle database connection", # str(e_type), str(e_value)) return 0
def initDB(backend=None, host=None, port=None, username=None, password=None, database=None, sslmode=None, sslrootcert=None, initsecond=False): """ Initialize the database. Either we get backend and all parameter which means the caller knows what they are doing, or we populate everything from the config files. initsecond: If set to True it initialize a second DB connection. By default only one DB connection is needed. """ if backend is None: if CFG is None or not CFG.is_initialized(): initCFG('server') backend = CFG.DB_BACKEND host = CFG.DB_HOST port = CFG.DB_PORT database = CFG.DB_NAME username = CFG.DB_USER password = CFG.DB_PASSWORD sslmode = None sslrootcert = None if CFG.DB_SSL_ENABLED: sslmode = 'verify-full' sslrootcert = CFG.DB_SSLROOTCERT if backend not in SUPPORTED_BACKENDS: raise rhnException("Unsupported database backend", backend) if port: port = int(port) # Hide the password add_to_seclist(password) try: if initsecond == False: __init__DB(backend, host, port, username, password, database, sslmode, sslrootcert) else: __init__DB2(backend, host, port, username, password, database, sslmode, sslrootcert) # except (rhnException, SQLError): # raise # pass on, we know those ones # except (KeyboardInterrupt, SystemExit): # raise except SQLConnectError: e = sys.exc_info()[1] try: closeDB() except NameError: pass raise e except: raise #e_type, e_value = sys.exc_info()[:2] # raise rhnException("Could not initialize Oracle database connection", # str(e_type), str(e_value)) return 0
def _execute_wrapper(self, function, *p, **kw): params = ','.join([ "%s: %s" % (repr(key), repr(value)) for key, value in list(kw.items()) ]) log_debug( 5, "Executing SQL: \"%s\" with bind params: {%s}" % (self.sql, params)) if self.sql is None: raise rhnException("Cannot execute empty cursor") if self.blob_map: blob_content = {} for orig_blob_var in list(self.blob_map.keys()): new_blob_var = orig_blob_var + '_blob' blob_content[new_blob_var] = kw[orig_blob_var] kw[new_blob_var] = self.var(cx_Oracle.BLOB) del kw[orig_blob_var] modified_params = self._munge_args(kw) try: retval = function(*p, **kw) except self.OracleError: e = sys.exc_info()[1] ret = self._get_oracle_error_info(e) if isinstance(ret, usix.StringType): raise_with_tb(sql_base.SQLError(self.sql, p, kw, ret), sys.exc_info()[2]) (errno, errmsg) = ret[:2] if 900 <= errno <= 999: # Per Oracle's documentation, SQL parsing error raise_with_tb( sql_base.SQLStatementPrepareError(errno, errmsg, self.sql), sys.exc_info()[2]) if errno == 1475: # statement needs to be reparsed; force a prepare again if self.reparsed: # useless, tried that already. give up log_error("Reparsing cursor did not fix it", self.sql) args = ( "Reparsing tried and still got this", ) + tuple(ret) raise_with_tb(sql_base.SQLError(*args), sys.exc_info()[2]) self._real_cursor = self.dbh.prepare(self.sql) self.reparsed = 1 self._execute_wrapper(function, *p, **kw) elif 20000 <= errno <= 20999: # error codes we know we raise as schema errors raise_with_tb(sql_base.SQLSchemaError(*ret), sys.exc_info()[2]) raise_with_tb(sql_base.SQLError(*ret), sys.exc_info()[2]) except ValueError: # this is not good.Let the user know raise else: self.reparsed = 0 # reset the reparsed counter if self.blob_map: for blob_var, content in blob_content.items(): kw[blob_var].getvalue().write(content) # Munge back the values self._unmunge_args(kw, modified_params) return retval
def get_kickstart_session_info(kickstart_session_id, server_id): h = rhnSQL.prepare(_query_get_kickstart_session_info) h.execute(kickstart_session_id=kickstart_session_id) row = h.fetchone_dict() if not row: raise rhnException("Could not fetch kickstart session id %s " "for server %s" % (kickstart_session_id, server_id)) return row
def set_log_auth_login(login): h = prepare("select id from web_contact_all where login = :login") h.execute(login=login) row = h.fetchone_dict() if row: user_id = row['id'] set_log_auth(user_id) else: raise rhnException("No such log user", login)
def check_password(username, password, service): try: auth = pam.pam() if not auth.authenticate(username, password, service=service): log_error("Password check failed (%s): %s" % (auth.code, auth.reason)) return 0 else: return 1 except: raise_with_tb(rhnException('Internal PAM error'), sys.exc_info()[2])
def configure(serverId, actionId, dry_run=0): log_debug(3, dry_run) h = rhnSQL.prepare(_query_lookup_interval) h.execute(action_id=actionId) row = h.fetchone_dict() if not row: raise rhnException("rhnsd reconfig action scheduled, but no entries " "in rhnActionDaemonConfig found") # Format: (interval, restart) return (row['interval'], row['restart'])
def insert(self, rows): # insert a single row into the table def insert_row(row, self=self): if self.__cache is not None: self.__cache[row[self.__hashid]] = row return self.__setitem__(None, row) if isinstance(rows, dict) or isinstance(rows, UserDictCase): return insert_row(rows) if isinstance(rows, list): for x in rows: insert_row(x) return None raise rhnException("Invalid data %s passed" % type(rows), rows)
def reload(self, user_id): """ Reload the current data from the SQL database using the given id """ log_debug(3, user_id) # If we can not load these we have a fatal condition if not self.contact.load(user_id): raise rhnException("Could not find contact record for id", user_id) if not self.customer.load(self.contact["org_id"]): raise rhnException( "Could not find org record", "user_id = %s" % user_id, "org_id = %s" % self.contact["org_id"] ) # These other ones are non fatal because we can create dummy records if not self.info.load(user_id): self.__init_info() if not self.perms.load(user_id): self.__init_perms() # The site info is trickier, we need to find it first if not self.site.load_sql("web_user_id = :userid and type = 'M'", {"userid": user_id}): self.__init_site() # Fix the username self.username = self.contact["login"] return 0
def __init__(self, db, table, hashname, hashval=None): UserDictCase.__init__(self) if not isinstance(db, sql_base.Database): raise rhnException("Argument db is not a database instance", db) self.db = db self.table = table self.hashname = string.lower(hashname) # and the data dictionary self.data = {} # is this a real entry (ie, use insert or update) self.real = 0 if hashval is not None: # if we have to load an entry already... self.load(hashval)
def reload(self, user_id): """ Reload the current data from the SQL database using the given id """ log_debug(3, user_id) # If we can not load these we have a fatal condition if not self.contact.load(user_id): raise rhnException("Could not find contact record for id", user_id) if not self.customer.load(self.contact["org_id"]): raise rhnException("Could not find org record", "user_id = %s" % user_id, "org_id = %s" % self.contact["org_id"]) # These other ones are non fatal because we can create dummy records if not self.info.load(user_id): self.__init_info() if not self.perms.load(user_id): self.__init_perms() # The site info is trickier, we need to find it first if not self.site.load_sql("web_user_id = :userid and type = 'M'", {"userid": user_id}): self.__init_site() # Fix the username self.username = self.contact['login'] return 0
def _execute_wrapper(self, function, *p, **kw): params = ','.join(["%s: %s" % (repr(key), repr(value)) for key, value in list(kw.items())]) log_debug(5, "Executing SQL: \"%s\" with bind params: {%s}" % (self.sql, params)) if self.sql is None: raise rhnException("Cannot execute empty cursor") if self.blob_map: blob_content = {} for orig_blob_var in list(self.blob_map.keys()): new_blob_var = orig_blob_var + '_blob' blob_content[new_blob_var] = kw[orig_blob_var] kw[new_blob_var] = self.var(cx_Oracle.BLOB) del kw[orig_blob_var] modified_params = self._munge_args(kw) try: retval = function(*p, **kw) except self.OracleError: e = sys.exc_info()[1] ret = self._get_oracle_error_info(e) if isinstance(ret, usix.StringType): raise_with_tb(sql_base.SQLError(self.sql, p, kw, ret), sys.exc_info()[2]) (errno, errmsg) = ret[:2] if 900 <= errno <= 999: # Per Oracle's documentation, SQL parsing error raise_with_tb(sql_base.SQLStatementPrepareError(errno, errmsg, self.sql), sys.exc_info()[2]) if errno == 1475: # statement needs to be reparsed; force a prepare again if self.reparsed: # useless, tried that already. give up log_error("Reparsing cursor did not fix it", self.sql) args = ("Reparsing tried and still got this",) + tuple(ret) raise_with_tb(sql_base.SQLError(*args), sys.exc_info()[2]) self._real_cursor = self.dbh.prepare(self.sql) self.reparsed = 1 self._execute_wrapper(function, *p, **kw) elif 20000 <= errno <= 20999: # error codes we know we raise as schema errors raise_with_tb(sql_base.SQLSchemaError(*ret), sys.exc_info()[2]) raise_with_tb(sql_base.SQLError(*ret), sys.exc_info()[2]) except ValueError: # this is not good.Let the user know raise else: self.reparsed = 0 # reset the reparsed counter if self.blob_map: for blob_var, content in blob_content.items(): kw[blob_var].getvalue().write(content) # Munge back the values self._unmunge_args(kw, modified_params) return retval
def _validate_version(req): server_version = constants.PROTOCOL_VERSION vstr = 'X-RHN-Satellite-XML-Dump-Version' if vstr not in req.headers_in: raise rhnFault(3010, "Missing version string") client_version = req.headers_in[vstr] # set the client version through rhnFlags to access later rhnFlags.set('X-RHN-Satellite-XML-Dump-Version', client_version) log_debug(1, "Server version", server_version, "Client version", client_version) client_ver_arr = str(client_version).split(".") server_ver_arr = str(server_version).split(".") client_major = client_ver_arr[0] server_major = server_ver_arr[0] if len(client_ver_arr) >= 2: client_minor = client_ver_arr[1] else: client_minor = 0 server_minor = server_ver_arr[1] try: client_major = int(client_major) client_minor = int(client_minor) except ValueError: raise_with_tb( rhnFault(3011, "Invalid version string %s" % client_version), sys.exc_info()[2]) try: server_major = int(server_major) server_minor = int(server_minor) except ValueError: raise_with_tb( rhnException("Invalid server version string %s" % server_version), sys.exc_info()[2]) if client_major != server_major: raise rhnFault(3012, "Client version %s does not match" " server version %s" % (client_version, server_version), explain=0)
def _prepHandler(self): """ Handler part 0 """ # Just to be on the safe side if self.req.main: # A subrequest return apache.DECLINED log_debug(4, rhnFlags.all()) if not self.rhnParent: raise rhnException("Oops, no proxy parent! Exiting") # Copy the headers. rhnFlags.get('outputTransportOptions').clear() rhnFlags.get('outputTransportOptions').update(self._getHeaders(self.req)) return apache.OK
def handler(self, req): """ main Apache handler """ log_debug(2) ret = apacheSession.handler(self, req) if ret != apache.OK: return ret if not CFG.SEND_MESSAGE_TO_ALL: # Need to get any string template overrides here, before any app # code gets executed, as the rhnFault error messages use the # templates # If send_message_to_all, we don't have DB connectivity though h = rhnSQL.prepare("select label, value from rhnTemplateString") h.execute() templateStrings = {} while 1: row = h.fetchone_dict() if not row: break templateStrings[row['label']] = row['value'] if templateStrings: rhnFlags.set('templateOverrides', templateStrings) log_debug(4, "template strings: %s" % templateStrings) if not CFG.SECRET_KEY: # Secret key not defined, complain loudly try: raise rhnException("Secret key not found!") except: rhnTB.Traceback(mail=1, req=req, severity="schema") req.status = 500 req.send_http_header() return apache.OK # Try to authenticate the proxy if it this request passed # through a proxy. if self.proxyVersion: try: ret = self._req_processor.auth_proxy() except rhnFault, f: return self._req_processor.response(f.getxml())
def _execute_wrapper(self, function, *p, **kw): params = ','.join(["%s: %s" % (key, value) for key, value in kw.items()]) log_debug(5, "Executing SQL: \"%s\" with bind params: {%s}" % (self.sql, params)) if self.sql is None: raise rhnException("Cannot execute empty cursor") if self.blob_map: for blob_var in self.blob_map.keys(): kw[blob_var] = buffer(kw[blob_var]) try: retval = function(*p, **kw) except psycopg2.InternalError, e: error_code = 99999 m = re.match('ERROR: +-([0-9]+)', e.pgerror) if m: error_code = int(m.group(1)) raise sql_base.SQLSchemaError(error_code, e.pgerror, e)
def _check_token_limits(server_id, token_rec): token_id = token_rec["token_id"] # Mark that we used this token server_used_token(server_id, token_id) # now check we're not using this token too much h = rhnSQL.prepare(_query_check_token_limits) h.execute(token_id=token_id) ret = h.fetchone_dict() if not ret: raise rhnException("Could not check usage limits for token", server_id, token_rec) # See bug #79095: if usage_limit is NULL, it means unlimited reg tokens if ret["max_nr"] is not None and ret["max_nr"] < ret["curr_nr"]: log_error("Token usage limit exceeded", token_rec, ret["max_nr"], server_id) raise rhnFault(61, _("Maximum usage count of %s reached") % ret["max_nr"]) # all clean, we're below usage limits return 0
def __init__(self, dbh, sql=None, force=None, blob_map=None): try: sql_base.Cursor.__init__(self, dbh=dbh, sql=sql, force=force) self._type_mapping = ORACLE_TYPE_MAPPING self.blob_map = blob_map except sql_base.SQLSchemaError, e: (errno, errmsg) = e.errno, e.errmsg if 900 <= errno <= 999: # Per Oracle's documentation, SQL parsing error raise sql_base.SQLStatementPrepareError(self.dbh, errmsg, self.sql), None, sys.exc_info()[2] # XXX: we should be handling the lost connection cases # in here too, but we don't get that many of these and # besides, this is much harder to get right # XXX: Normally we expect the e.args to include a dump of # the SQL code we just passed in since we're dealing with # an OracleError. I hope this is always the case, of not, # we'll have to log the sql code here raise rhnException("Can not prepare statement", e.args), None, sys.exc_info()[2]
def check_password(self, password, allow_read_only=False): """ simple check for a password that might become more complex sometime """ if not allow_read_only and is_user_read_only(self.contact["login"]): raise rhnFault(702) good_pwd = str(self.contact["password"]) if CFG.pam_auth_service: # a PAM service is defined # We have to check the user's rhnUserInfo.use_pam_authentication # XXX Should we create yet another __init_blah function? # since it's the first time we had to lool at rhnUserInfo, # I'll assume it's not something to happen very frequently, # so I'll use a query for now # - misa # h = rhnSQL.prepare(""" select ui.use_pam_authentication from web_contact w, rhnUserInfo ui where w.login_uc = UPPER(:login) and w.id = ui.user_id""") h.execute(login=self.contact["login"]) data = h.fetchone_dict() if not data: # This should not happen raise rhnException("No entry found for user %s" % self.contact["login"]) if data['use_pam_authentication'] == 'Y': # use PAM import rhnAuthPAM return rhnAuthPAM.check_password(self.contact["login"], password, CFG.pam_auth_service) # If the entry in rhnUserInfo is 'N', perform regular authentication ret = check_password(password, good_pwd) if ret and CFG.encrypted_passwords and self.contact['password'].find( '$1$') == 0: # If successfully authenticated and the current password is # MD5 encoded, convert the password to SHA-256 and save it in the DB. self.contact['password'] = encrypt_password(password) self.contact.save() rhnSQL.commit() return ret
def _execute_wrapper(self, function, *p, **kw): params = ','.join( ["%s: %s" % (repr(key), repr(value)) for key, value in kw.items()]) log_debug( 5, "Executing SQL: \"%s\" with bind params: {%s}" % (self.sql, params)) if self.sql is None: raise rhnException("Cannot execute empty cursor") if self.blob_map: blob_content = {} for orig_blob_var in self.blob_map.keys(): new_blob_var = orig_blob_var + '_blob' blob_content[new_blob_var] = kw[orig_blob_var] kw[new_blob_var] = self.var(cx_Oracle.BLOB) del kw[orig_blob_var] modified_params = self._munge_args(kw) try: retval = apply(function, p, kw) except self.OracleError, e: ret = self._get_oracle_error_info(e) if isinstance(ret, types.StringType): raise sql_base.SQLError(self.sql, p, kw, ret), None, sys.exc_info()[2] (errno, errmsg) = ret[:2] if 900 <= errno <= 999: # Per Oracle's documentation, SQL parsing error raise sql_base.SQLStatementPrepareError( errno, errmsg, self.sql), None, sys.exc_info()[2] if errno == 1475: # statement needs to be reparsed; force a prepare again if self.reparsed: # useless, tried that already. give up log_error("Reparsing cursor did not fix it", self.sql) args = ( "Reparsing tried and still got this", ) + tuple(ret) raise sql_base.SQLError(*args), None, sys.exc_info()[2] self._real_cursor = self.dbh.prepare(self.sql) self.reparsed = 1 apply(self._execute_wrapper, (function, ) + p, kw) elif 20000 <= errno <= 20999: # error codes we know we raise as schema errors raise sql_base.SQLSchemaError(*ret), None, sys.exc_info()[2] raise apply(sql_base.SQLError, ret), None, sys.exc_info()[2]
def _validate_version(req): server_version = constants.PROTOCOL_VERSION vstr = 'X-RHN-Satellite-XML-Dump-Version' if vstr not in req.headers_in: raise rhnFault(3010, "Missing version string") client_version = req.headers_in[vstr] # set the client version through rhnFlags to access later rhnFlags.set('X-RHN-Satellite-XML-Dump-Version', client_version) log_debug(1, "Server version", server_version, "Client version", client_version) client_ver_arr = str(client_version).split(".") server_ver_arr = str(server_version).split(".") client_major = client_ver_arr[0] server_major = server_ver_arr[0] if len(client_ver_arr) >= 2: client_minor = client_ver_arr[1] else: client_minor = 0 server_minor = server_ver_arr[1] try: client_major = int(client_major) client_minor = int(client_minor) except ValueError: raise_with_tb(rhnFault(3011, "Invalid version string %s" % client_version), sys.exc_info()[2]) try: server_major = int(server_major) server_minor = int(server_minor) except ValueError: raise_with_tb(rhnException("Invalid server version string %s" % server_version), sys.exc_info()[2]) if client_major != server_major: raise rhnFault(3012, "Client version %s does not match" " server version %s" % (client_version, server_version), explain=0)
def download(self, system_id): log_debug(3) self.auth_system(system_id) server_id = self.server.server['id'] h = rhnSQL.prepare(""" select cert from rhnSatelliteInfo si where si.server_id = :server_id""") h.execute(server_id=server_id) row = h.fetchone_dict() if not row: # This should not happen - we're already authenticated raise rhnException("SUSE Manager Server certificate is unavailable after authentication?") # Bugzilla #219625 # cert is now a blob cert = row['cert'] cert = cert.read() return cert