+ privatetrans = True
+
+ try:
+ # Insert paths
+ def generate_path_dicts():
+ for fullpath in fullpaths:
+ if fullpath.startswith( './' ):
+ fullpath = fullpath[2:]
+
+ yield {'filename':fullpath, 'id': binary_id }
+
+ for d in generate_path_dicts():
+ session.execute( "INSERT INTO bin_contents ( file, binary_id ) VALUES ( :filename, :id )",
+ d )
+
+ session.commit()
+ if privatetrans:
+ session.close()
+ return True
+
+ except:
+ traceback.print_exc()
+
+ # Only rollback if we set up the session ourself
+ if privatetrans:
+ session.rollback()
+ session.close()
+
+ return False
+
+__all__.append('insert_content_paths')
+
+################################################################################
+
+class DSCFile(object):
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def __repr__(self):
+ return '<DSCFile %s>' % self.dscfile_id
+
+__all__.append('DSCFile')
+
+@session_wrapper
+def get_dscfiles(dscfile_id=None, source_id=None, poolfile_id=None, session=None):
+ """
+ Returns a list of DSCFiles which may be empty
+
+ @type dscfile_id: int (optional)
+ @param dscfile_id: the dscfile_id of the DSCFiles to find
+
+ @type source_id: int (optional)
+ @param source_id: the source id related to the DSCFiles to find
+
+ @type poolfile_id: int (optional)
+ @param poolfile_id: the poolfile id related to the DSCFiles to find
+
+ @rtype: list
+ @return: Possibly empty list of DSCFiles
+ """
+
+ q = session.query(DSCFile)
+
+ if dscfile_id is not None:
+ q = q.filter_by(dscfile_id=dscfile_id)
+
+ if source_id is not None:
+ q = q.filter_by(source_id=source_id)
+
+ if poolfile_id is not None:
+ q = q.filter_by(poolfile_id=poolfile_id)
+
+ return q.all()
+
+__all__.append('get_dscfiles')
+
+################################################################################
+
+class ExternalOverride(ORMObject):
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def __repr__(self):
+ return '<ExternalOverride %s = %s: %s>' % (self.package, self.key, self.value)
+
+__all__.append('ExternalOverride')
+
+################################################################################
+
+class PoolFile(ORMObject):
+ def __init__(self, filename = None, location = None, filesize = -1, \
+ md5sum = None):
+ self.filename = filename
+ self.location = location
+ self.filesize = filesize
+ self.md5sum = md5sum
+
+ @property
+ def fullpath(self):
+ return os.path.join(self.location.path, self.filename)
+
+ def is_valid(self, filesize = -1, md5sum = None):
+ return self.filesize == long(filesize) and self.md5sum == md5sum
+
+ def properties(self):
+ return ['filename', 'file_id', 'filesize', 'md5sum', 'sha1sum', \
+ 'sha256sum', 'location', 'source', 'binary', 'last_used']
+
+ def not_null_constraints(self):
+ return ['filename', 'md5sum', 'location']
+
+ def identical_to(self, filename):
+ """
+ compare size and hash with the given file
+
+ @rtype: bool
+ @return: true if the given file has the same size and hash as this object; false otherwise
+ """
+ st = os.stat(filename)
+ if self.filesize != st.st_size:
+ return False
+
+ f = open(filename, "r")
+ sha256sum = apt_pkg.sha256sum(f)
+ if sha256sum != self.sha256sum:
+ return False
+
+ return True
+
+__all__.append('PoolFile')
+
+@session_wrapper
+def check_poolfile(filename, filesize, md5sum, location_id, session=None):
+ """
+ Returns a tuple:
+ (ValidFileFound [boolean], PoolFile object or None)
+
+ @type filename: string
+ @param filename: the filename of the file to check against the DB
+
+ @type filesize: int
+ @param filesize: the size of the file to check against the DB
+
+ @type md5sum: string
+ @param md5sum: the md5sum of the file to check against the DB
+
+ @type location_id: int
+ @param location_id: the id of the location to look in
+
+ @rtype: tuple
+ @return: Tuple of length 2.
+ - If valid pool file found: (C{True}, C{PoolFile object})
+ - If valid pool file not found:
+ - (C{False}, C{None}) if no file found
+ - (C{False}, C{PoolFile object}) if file found with size/md5sum mismatch
+ """
+
+ poolfile = session.query(Location).get(location_id). \
+ files.filter_by(filename=filename).first()
+ valid = False
+ if poolfile and poolfile.is_valid(filesize = filesize, md5sum = md5sum):
+ valid = True
+
+ return (valid, poolfile)
+
+__all__.append('check_poolfile')
+
+# TODO: the implementation can trivially be inlined at the place where the
+# function is called
+@session_wrapper
+def get_poolfile_by_id(file_id, session=None):
+ """
+ Returns a PoolFile objects or None for the given id
+
+ @type file_id: int
+ @param file_id: the id of the file to look for
+
+ @rtype: PoolFile or None
+ @return: either the PoolFile object or None
+ """
+
+ return session.query(PoolFile).get(file_id)
+
+__all__.append('get_poolfile_by_id')
+
+@session_wrapper
+def get_poolfile_like_name(filename, session=None):
+ """
+ Returns an array of PoolFile objects which are like the given name
+
+ @type filename: string
+ @param filename: the filename of the file to check against the DB
+
+ @rtype: array
+ @return: array of PoolFile objects
+ """
+
+ # TODO: There must be a way of properly using bind parameters with %FOO%
+ q = session.query(PoolFile).filter(PoolFile.filename.like('%%/%s' % filename))
+
+ return q.all()
+
+__all__.append('get_poolfile_like_name')
+
+@session_wrapper
+def add_poolfile(filename, datadict, location_id, session=None):
+ """
+ Add a new file to the pool
+
+ @type filename: string
+ @param filename: filename
+
+ @type datadict: dict
+ @param datadict: dict with needed data
+
+ @type location_id: int
+ @param location_id: database id of the location
+
+ @rtype: PoolFile
+ @return: the PoolFile object created
+ """
+ poolfile = PoolFile()
+ poolfile.filename = filename
+ poolfile.filesize = datadict["size"]
+ poolfile.md5sum = datadict["md5sum"]
+ poolfile.sha1sum = datadict["sha1sum"]
+ poolfile.sha256sum = datadict["sha256sum"]
+ poolfile.location_id = location_id
+
+ session.add(poolfile)
+ # Flush to get a file id (NB: This is not a commit)
+ session.flush()
+
+ return poolfile
+
+__all__.append('add_poolfile')
+
+################################################################################
+
+class Fingerprint(ORMObject):
+ def __init__(self, fingerprint = None):
+ self.fingerprint = fingerprint
+
+ def properties(self):
+ return ['fingerprint', 'fingerprint_id', 'keyring', 'uid', \
+ 'binary_reject']
+
+ def not_null_constraints(self):
+ return ['fingerprint']
+
+__all__.append('Fingerprint')
+
+@session_wrapper
+def get_fingerprint(fpr, session=None):
+ """
+ Returns Fingerprint object for given fpr.
+
+ @type fpr: string
+ @param fpr: The fpr to find / add
+
+ @type session: SQLAlchemy
+ @param session: Optional SQL session object (a temporary one will be
+ generated if not supplied).
+
+ @rtype: Fingerprint
+ @return: the Fingerprint object for the given fpr or None
+ """
+
+ q = session.query(Fingerprint).filter_by(fingerprint=fpr)
+
+ try:
+ ret = q.one()
+ except NoResultFound:
+ ret = None
+
+ return ret
+
+__all__.append('get_fingerprint')
+
+@session_wrapper
+def get_or_set_fingerprint(fpr, session=None):
+ """
+ Returns Fingerprint object for given fpr.
+
+ If no matching fpr is found, a row is inserted.
+
+ @type fpr: string
+ @param fpr: The fpr to find / add
+
+ @type session: SQLAlchemy
+ @param session: Optional SQL session object (a temporary one will be
+ generated if not supplied). If not passed, a commit will be performed at
+ the end of the function, otherwise the caller is responsible for commiting.
+ A flush will be performed either way.
+
+ @rtype: Fingerprint
+ @return: the Fingerprint object for the given fpr
+ """
+
+ q = session.query(Fingerprint).filter_by(fingerprint=fpr)
+
+ try:
+ ret = q.one()
+ except NoResultFound:
+ fingerprint = Fingerprint()
+ fingerprint.fingerprint = fpr
+ session.add(fingerprint)
+ session.commit_or_flush()
+ ret = fingerprint
+
+ return ret
+
+__all__.append('get_or_set_fingerprint')
+
+################################################################################
+
+# Helper routine for Keyring class
+def get_ldap_name(entry):
+ name = []
+ for k in ["cn", "mn", "sn"]:
+ ret = entry.get(k)
+ if ret and ret[0] != "" and ret[0] != "-":
+ name.append(ret[0])
+ return " ".join(name)
+
+################################################################################
+
+class Keyring(object):
+ gpg_invocation = "gpg --no-default-keyring --keyring %s" +\
+ " --with-colons --fingerprint --fingerprint"
+
+ keys = {}
+ fpr_lookup = {}
+
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def __repr__(self):
+ return '<Keyring %s>' % self.keyring_name
+
+ def de_escape_gpg_str(self, txt):
+ esclist = re.split(r'(\\x..)', txt)
+ for x in range(1,len(esclist),2):
+ esclist[x] = "%c" % (int(esclist[x][2:],16))
+ return "".join(esclist)
+
+ def parse_address(self, uid):
+ """parses uid and returns a tuple of real name and email address"""
+ import email.Utils
+ (name, address) = email.Utils.parseaddr(uid)
+ name = re.sub(r"\s*[(].*[)]", "", name)
+ name = self.de_escape_gpg_str(name)
+ if name == "":
+ name = uid
+ return (name, address)
+
+ def load_keys(self, keyring):
+ if not self.keyring_id:
+ raise Exception('Must be initialized with database information')
+
+ k = os.popen(self.gpg_invocation % keyring, "r")
+ key = None
+ signingkey = False
+
+ for line in k:
+ field = line.split(":")
+ if field[0] == "pub":
+ key = field[4]
+ self.keys[key] = {}
+ (name, addr) = self.parse_address(field[9])
+ if "@" in addr:
+ self.keys[key]["email"] = addr
+ self.keys[key]["name"] = name
+ self.keys[key]["fingerprints"] = []
+ signingkey = True
+ elif key and field[0] == "sub" and len(field) >= 12:
+ signingkey = ("s" in field[11])
+ elif key and field[0] == "uid":
+ (name, addr) = self.parse_address(field[9])
+ if "email" not in self.keys[key] and "@" in addr:
+ self.keys[key]["email"] = addr
+ self.keys[key]["name"] = name
+ elif signingkey and field[0] == "fpr":
+ self.keys[key]["fingerprints"].append(field[9])
+ self.fpr_lookup[field[9]] = key
+
+ def import_users_from_ldap(self, session):
+ import ldap
+ cnf = Config()
+
+ LDAPDn = cnf["Import-LDAP-Fingerprints::LDAPDn"]
+ LDAPServer = cnf["Import-LDAP-Fingerprints::LDAPServer"]
+
+ l = ldap.open(LDAPServer)
+ l.simple_bind_s("","")
+ Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
+ "(&(keyfingerprint=*)(gidnumber=%s))" % (cnf["Import-Users-From-Passwd::ValidGID"]),
+ ["uid", "keyfingerprint", "cn", "mn", "sn"])
+
+ ldap_fin_uid_id = {}
+
+ byuid = {}
+ byname = {}
+
+ for i in Attrs:
+ entry = i[1]
+ uid = entry["uid"][0]
+ name = get_ldap_name(entry)
+ fingerprints = entry["keyFingerPrint"]
+ keyid = None
+ for f in fingerprints:
+ key = self.fpr_lookup.get(f, None)
+ if key not in self.keys:
+ continue
+ self.keys[key]["uid"] = uid
+
+ if keyid != None:
+ continue
+ keyid = get_or_set_uid(uid, session).uid_id
+ byuid[keyid] = (uid, name)
+ byname[uid] = (keyid, name)
+
+ return (byname, byuid)
+
+ def generate_users_from_keyring(self, format, session):
+ byuid = {}
+ byname = {}
+ any_invalid = False
+ for x in self.keys.keys():
+ if "email" not in self.keys[x]:
+ any_invalid = True
+ self.keys[x]["uid"] = format % "invalid-uid"
+ else:
+ uid = format % self.keys[x]["email"]
+ keyid = get_or_set_uid(uid, session).uid_id
+ byuid[keyid] = (uid, self.keys[x]["name"])
+ byname[uid] = (keyid, self.keys[x]["name"])
+ self.keys[x]["uid"] = uid
+
+ if any_invalid:
+ uid = format % "invalid-uid"
+ keyid = get_or_set_uid(uid, session).uid_id
+ byuid[keyid] = (uid, "ungeneratable user id")
+ byname[uid] = (keyid, "ungeneratable user id")
+
+ return (byname, byuid)
+
+__all__.append('Keyring')
+
+@session_wrapper
+def get_keyring(keyring, session=None):
+ """
+ If C{keyring} does not have an entry in the C{keyrings} table yet, return None
+ If C{keyring} already has an entry, simply return the existing Keyring
+
+ @type keyring: string
+ @param keyring: the keyring name
+
+ @rtype: Keyring
+ @return: the Keyring object for this keyring
+ """
+
+ q = session.query(Keyring).filter_by(keyring_name=keyring)
+
+ try:
+ return q.one()
+ except NoResultFound:
+ return None
+
+__all__.append('get_keyring')
+
+@session_wrapper
+def get_active_keyring_paths(session=None):
+ """
+ @rtype: list
+ @return: list of active keyring paths
+ """
+ return [ x.keyring_name for x in session.query(Keyring).filter(Keyring.active == True).order_by(desc(Keyring.priority)).all() ]
+
+__all__.append('get_active_keyring_paths')
+
+@session_wrapper
+def get_primary_keyring_path(session=None):
+ """
+ Get the full path to the highest priority active keyring
+
+ @rtype: str or None
+ @return: path to the active keyring with the highest priority or None if no
+ keyring is configured
+ """
+ keyrings = get_active_keyring_paths()
+
+ if len(keyrings) > 0:
+ return keyrings[0]
+ else:
+ return None
+
+__all__.append('get_primary_keyring_path')
+
+################################################################################
+
+class KeyringACLMap(object):
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def __repr__(self):
+ return '<KeyringACLMap %s>' % self.keyring_acl_map_id
+
+__all__.append('KeyringACLMap')
+
+################################################################################
+
+class DBChange(object):
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def __repr__(self):
+ return '<DBChange %s>' % self.changesname
+
+ def clean_from_queue(self):
+ session = DBConn().session().object_session(self)
+
+ # Remove changes_pool_files entries
+ self.poolfiles = []
+
+ # Remove changes_pending_files references
+ self.files = []
+
+ # Clear out of queue
+ self.in_queue = None
+ self.approved_for_id = None
+
+__all__.append('DBChange')
+
+@session_wrapper
+def get_dbchange(filename, session=None):
+ """
+ returns DBChange object for given C{filename}.
+
+ @type filename: string
+ @param filename: the name of the file
+
+ @type session: Session
+ @param session: Optional SQLA session object (a temporary one will be
+ generated if not supplied)
+
+ @rtype: DBChange
+ @return: DBChange object for the given filename (C{None} if not present)
+
+ """
+ q = session.query(DBChange).filter_by(changesname=filename)
+
+ try:
+ return q.one()
+ except NoResultFound:
+ return None
+
+__all__.append('get_dbchange')
+
+################################################################################
+
+class Location(ORMObject):
+ def __init__(self, path = None, component = None):
+ self.path = path
+ self.component = component
+ # the column 'type' should go away, see comment at mapper
+ self.archive_type = 'pool'
+
+ def properties(self):
+ return ['path', 'location_id', 'archive_type', 'component', \
+ 'files_count']
+
+ def not_null_constraints(self):
+ return ['path', 'archive_type']
+
+__all__.append('Location')
+
+@session_wrapper
+def get_location(location, component=None, archive=None, session=None):
+ """
+ Returns Location object for the given combination of location, component
+ and archive
+
+ @type location: string
+ @param location: the path of the location, e.g. I{/srv/ftp-master.debian.org/ftp/pool/}
+
+ @type component: string
+ @param component: the component name (if None, no restriction applied)
+
+ @type archive: string
+ @param archive: the archive name (if None, no restriction applied)
+
+ @rtype: Location / None
+ @return: Either a Location object or None if one can't be found
+ """
+
+ q = session.query(Location).filter_by(path=location)
+
+ if archive is not None:
+ q = q.join(Archive).filter_by(archive_name=archive)
+
+ if component is not None:
+ q = q.join(Component).filter_by(component_name=component)
+
+ try:
+ return q.one()
+ except NoResultFound:
+ return None
+
+__all__.append('get_location')
+
+################################################################################
+
+class Maintainer(ORMObject):
+ def __init__(self, name = None):
+ self.name = name
+
+ def properties(self):
+ return ['name', 'maintainer_id']
+
+ def not_null_constraints(self):
+ return ['name']
+
+ def get_split_maintainer(self):
+ if not hasattr(self, 'name') or self.name is None:
+ return ('', '', '', '')
+
+ return fix_maintainer(self.name.strip())
+
+__all__.append('Maintainer')
+
+@session_wrapper
+def get_or_set_maintainer(name, session=None):
+ """
+ Returns Maintainer object for given maintainer name.
+
+ If no matching maintainer name is found, a row is inserted.
+
+ @type name: string
+ @param name: The maintainer name to add
+
+ @type session: SQLAlchemy
+ @param session: Optional SQL session object (a temporary one will be
+ generated if not supplied). If not passed, a commit will be performed at
+ the end of the function, otherwise the caller is responsible for commiting.
+ A flush will be performed either way.
+
+ @rtype: Maintainer
+ @return: the Maintainer object for the given maintainer
+ """
+
+ q = session.query(Maintainer).filter_by(name=name)
+ try:
+ ret = q.one()
+ except NoResultFound:
+ maintainer = Maintainer()
+ maintainer.name = name
+ session.add(maintainer)
+ session.commit_or_flush()
+ ret = maintainer
+
+ return ret
+
+__all__.append('get_or_set_maintainer')
+
+@session_wrapper
+def get_maintainer(maintainer_id, session=None):
+ """
+ Return the name of the maintainer behind C{maintainer_id} or None if that
+ maintainer_id is invalid.
+
+ @type maintainer_id: int
+ @param maintainer_id: the id of the maintainer
+
+ @rtype: Maintainer
+ @return: the Maintainer with this C{maintainer_id}
+ """
+
+ return session.query(Maintainer).get(maintainer_id)
+
+__all__.append('get_maintainer')
+
+################################################################################
+
+class NewComment(object):
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def __repr__(self):
+ return '''<NewComment for '%s %s' (%s)>''' % (self.package, self.version, self.comment_id)
+
+__all__.append('NewComment')
+
+@session_wrapper
+def has_new_comment(package, version, session=None):
+ """
+ Returns true if the given combination of C{package}, C{version} has a comment.
+
+ @type package: string
+ @param package: name of the package
+
+ @type version: string
+ @param version: package version
+
+ @type session: Session
+ @param session: Optional SQLA session object (a temporary one will be
+ generated if not supplied)
+
+ @rtype: boolean
+ @return: true/false
+ """
+
+ q = session.query(NewComment)
+ q = q.filter_by(package=package)
+ q = q.filter_by(version=version)
+
+ return bool(q.count() > 0)
+
+__all__.append('has_new_comment')
+
+@session_wrapper
+def get_new_comments(package=None, version=None, comment_id=None, session=None):
+ """
+ Returns (possibly empty) list of NewComment objects for the given
+ parameters
+
+ @type package: string (optional)
+ @param package: name of the package
+
+ @type version: string (optional)
+ @param version: package version
+
+ @type comment_id: int (optional)
+ @param comment_id: An id of a comment
+
+ @type session: Session
+ @param session: Optional SQLA session object (a temporary one will be
+ generated if not supplied)
+
+ @rtype: list
+ @return: A (possibly empty) list of NewComment objects will be returned
+ """
+
+ q = session.query(NewComment)
+ if package is not None: q = q.filter_by(package=package)
+ if version is not None: q = q.filter_by(version=version)
+ if comment_id is not None: q = q.filter_by(comment_id=comment_id)
+
+ return q.all()
+
+__all__.append('get_new_comments')
+
+################################################################################
+
+class Override(ORMObject):
+ def __init__(self, package = None, suite = None, component = None, overridetype = None, \
+ section = None, priority = None):
+ self.package = package
+ self.suite = suite
+ self.component = component
+ self.overridetype = overridetype
+ self.section = section
+ self.priority = priority
+
+ def properties(self):
+ return ['package', 'suite', 'component', 'overridetype', 'section', \
+ 'priority']
+
+ def not_null_constraints(self):
+ return ['package', 'suite', 'component', 'overridetype', 'section']
+
+__all__.append('Override')
+
+@session_wrapper
+def get_override(package, suite=None, component=None, overridetype=None, session=None):
+ """
+ Returns Override object for the given parameters
+
+ @type package: string
+ @param package: The name of the package
+
+ @type suite: string, list or None
+ @param suite: The name of the suite (or suites if a list) to limit to. If
+ None, don't limit. Defaults to None.
+
+ @type component: string, list or None
+ @param component: The name of the component (or components if a list) to
+ limit to. If None, don't limit. Defaults to None.
+
+ @type overridetype: string, list or None
+ @param overridetype: The name of the overridetype (or overridetypes if a list) to
+ limit to. If None, don't limit. Defaults to None.
+
+ @type session: Session
+ @param session: Optional SQLA session object (a temporary one will be
+ generated if not supplied)
+
+ @rtype: list
+ @return: A (possibly empty) list of Override objects will be returned
+ """
+
+ q = session.query(Override)
+ q = q.filter_by(package=package)
+
+ if suite is not None:
+ if not isinstance(suite, list): suite = [suite]
+ q = q.join(Suite).filter(Suite.suite_name.in_(suite))
+
+ if component is not None:
+ if not isinstance(component, list): component = [component]
+ q = q.join(Component).filter(Component.component_name.in_(component))
+
+ if overridetype is not None:
+ if not isinstance(overridetype, list): overridetype = [overridetype]
+ q = q.join(OverrideType).filter(OverrideType.overridetype.in_(overridetype))
+
+ return q.all()
+
+__all__.append('get_override')
+
+
+################################################################################
+
+class OverrideType(ORMObject):
+ def __init__(self, overridetype = None):
+ self.overridetype = overridetype
+
+ def properties(self):
+ return ['overridetype', 'overridetype_id', 'overrides_count']
+
+ def not_null_constraints(self):
+ return ['overridetype']
+
+__all__.append('OverrideType')
+
+@session_wrapper
+def get_override_type(override_type, session=None):
+ """
+ Returns OverrideType object for given C{override type}.
+
+ @type override_type: string
+ @param override_type: The name of the override type
+
+ @type session: Session
+ @param session: Optional SQLA session object (a temporary one will be
+ generated if not supplied)
+
+ @rtype: int
+ @return: the database id for the given override type
+ """
+
+ q = session.query(OverrideType).filter_by(overridetype=override_type)
+
+ try:
+ return q.one()
+ except NoResultFound: