+### Backend storage.
+
+class StorageBackendRefusal (Exception):
+ """
+ I signify that a StorageBackend subclass has refused to open a file.
+
+ This is used by the StorageBackend.open class method.
+ """
+ pass
+
+class StorageBackendClass (type):
+ """
+ I am a metaclass for StorageBackend classes.
+
+ My main feature is that I register my concrete instances (with a `NAME'
+ which is not `None') with the StorageBackend class.
+ """
+ def __init__(me, name, supers, dict):
+ """
+ Register a new concrete StorageBackend subclass.
+ """
+ super(StorageBackendClass, me).__init__(name, supers, dict)
+ if me.NAME is not None: StorageBackend.register_concrete_subclass(me)
+
+class StorageBackend (object):
+ """
+ I provide basic protocol for password storage backends.
+
+ I'm an abstract class: you want one of my subclasses if you actually want
+ to do something useful. But I maintain a list of my subclasses and can
+ choose an appropriate one to open a database file you've found lying about.
+
+ Backends are responsible for storing and retrieving stuff, but not for the
+ cryptographic details. Backends need to store two kinds of information:
+
+ * metadata, consisting of a number of property names and their values;
+ and
+
+ * password mappings, consisting of a number of binary labels and
+ payloads.
+
+ Backends need to implement the following ordinary methods. See the calling
+ methods for details of the subclass responsibilities.
+
+ BE._create(FILE) Create a new database in FILE; used by `create'.
+
+ BE._open(FILE, WRITEP)
+ Open the existing database FILE; used by `open'.
+
+ BE._close(ABRUPTP) Close the database, freeing up any resources. If
+ ABRUPTP then don't try to commit changes.
+
+ BE._get_meta(NAME, DEFAULT)
+ Return the value of the metadata item with the given
+ NAME, or DEFAULT if it doesn't exist; used by
+ `get_meta'.
+
+ BE._put_meta(NAME, VALUE)
+ Set the VALUE of the metadata item with the given
+ NAME, creating one if necessary; used by `put_meta'.
+
+ BE._del_meta(NAME) Forget the metadata item with the given NAME; raise
+ `KeyError' if there is no such item; used by
+ `del_meta'.
+
+ BE._iter_meta() Return an iterator over the metadata (NAME, VALUE)
+ pairs; used by `iter_meta'.
+
+ BE._get_passwd(LABEL)
+ Return the password payload stored with the (binary)
+ LABEL; used by `get_passwd'.
+
+ BE._put_passwd(LABEL, PAYLOAD)
+ Associate the (binary) PAYLOAD with the LABEL,
+ forgetting any previous payload for that LABEL; used
+ by `put_passwd'.
+
+ BE._del_passwd(LABEL) Forget the password record with the given LABEL; used
+ by `_del_passwd'.
+
+ BE._iter_passwds() Return an iterator over the password (LABEL, PAYLOAD)
+ pairs; used by `iter_passwds'.
+
+ Also, concrete subclasses should define the following class attributes.
+
+ NAME The name of the backend, so that the user can select
+ it when creating a new database.
+
+ PRIO An integer priority: backends are tried in decreasing
+ priority order when opening an existing database.
+ """
+
+ __metaclass__ = StorageBackendClass
+ NAME = None
+ PRIO = 10
+
+ ## The registry of subclasses.
+ CLASSES = {}
+
+ FAIL = ['FAIL']
+
+ @staticmethod
+ def register_concrete_subclass(sub):
+ """Register a concrete subclass, so that `open' can try it."""
+ StorageBackend.CLASSES[sub.NAME] = sub
+
+ @staticmethod
+ def byname(name):
+ """
+ Return the concrete subclass with the given NAME.
+
+ Raise `KeyError' if the name isn't found.
+ """
+ return StorageBackend.CLASSES[name]
+
+ @staticmethod
+ def classes():
+ """Return an iterator over the concrete subclasses."""
+ return _itervalues(StorageBackend.CLASSES)
+
+ @staticmethod
+ def open(file, writep = False):
+ """Open a database FILE, using some appropriate backend."""
+ _OS.stat(file)
+ for cls in sorted(StorageBackend.CLASSES.values(), reverse = True,
+ key = lambda cls: cls.PRIO):
+ try: return cls(file, writep)
+ except StorageBackendRefusal: pass
+ raise StorageBackendRefusal
+
+ @classmethod
+ def create(cls, file):
+ """
+ Create a new database in the named FILE, using this backend.
+
+ Subclasses must implement the `_create' instance method.
+ """
+ return cls(writep = True, _magic = lambda me: me._create(file))
+
+ def __init__(me, file = None, writep = False, _magic = None, *args, **kw):
+ """
+ Main constructor.
+
+ Subclasses are not, in general, expected to override this: there's a
+ somewhat hairy protocol between the constructor and some of the class
+ methods. Instead, the main hook for customization is the subclass's
+ `_open' method, which is invoked in the usual case.
+ """
+ super(StorageBackend, me).__init__(*args, **kw)
+ if me.NAME is None: raise ValueError('abstract class')
+ if _magic is not None: _magic(me)
+ elif file is None: raise ValueError('missing file parameter')
+ else: me._open(file, writep)
+ me._writep = writep
+ me._livep = True
+
+ def close(me, abruptp = False):
+ """
+ Close the database.
+
+ It is harmless to attempt to close a database which has been closed
+ already. Calls the subclass's `_close' method.
+ """
+ if me._livep:
+ me._livep = False
+ me._close(abruptp)
+
+ ## Utilities.
+
+ def _check_live(me):
+ """Raise an error if the receiver has been closed."""
+ if not me._livep: raise ValueError('database is closed')
+
+ def _check_write(me):
+ """Raise an error if the receiver is not open for writing."""
+ me._check_live()
+ if not me._writep: raise ValueError('database is read-only')
+
+ def _check_meta_name(me, name):
+ """
+ Raise an error unless NAME is a valid name for a metadata item.
+
+ Metadata names may not start with `$': such names are reserved for
+ password storage.
+ """
+ if name.startswith('$'):
+ raise ValueError("invalid metadata key `%s'" % name)
+
+ ## Context protocol.
+
+ def __enter__(me):
+ """Context protocol: make sure the database is closed on exit."""
+ return me
+ def __exit__(me, exctype, excvalue, exctb):
+ """Context protocol: see `__enter__'."""
+ me.close(excvalue is not None)
+
+ ## Metadata.
+
+ def get_meta(me, name, default = FAIL):
+ """
+ Fetch the value for the metadata item NAME.
+
+ If no such item exists, then return DEFAULT if that was set; otherwise
+ raise a `KeyError'.
+
+ This calls the subclass's `_get_meta' method, which should return the
+ requested item or return the given DEFAULT value. It may assume that the
+ name is valid and the database is open.
+ """
+ me._check_meta_name(name)
+ me._check_live()
+ value = me._get_meta(name, default)
+ if value is StorageBackend.FAIL: raise KeyError(name)
+ return value
+
+ def put_meta(me, name, value):
+ """
+ Store VALUE in the metadata item called NAME.
+
+ This calls the subclass's `_put_meta' method, which may assume that the
+ name is valid and the database is open for writing.
+ """
+ me._check_meta_name(name)
+ me._check_write()
+ me._put_meta(name, value)
+
+ def del_meta(me, name):
+ """
+ Forget about the metadata item with the given NAME.
+
+ This calls the subclass's `_del_meta' method, which may assume that the
+ name is valid and the database is open for writing.
+ """
+ me._check_meta_name(name)
+ me._check_write()
+ me._del_meta(name)
+
+ def iter_meta(me):
+ """
+ Return an iterator over the name/value metadata items.
+
+ This calls the subclass's `_iter_meta' method, which may assume that the
+ database is open.
+ """
+ me._check_live()
+ return me._iter_meta()
+
+ def get_passwd(me, label):
+ """
+ Fetch and return the payload stored with the (opaque, binary) LABEL.
+
+ If there is no such payload then raise `KeyError'.
+
+ This calls the subclass's `_get_passwd' method, which may assume that the
+ database is open.
+ """
+ me._check_live()
+ return me._get_passwd(label)
+
+ def put_passwd(me, label, payload):
+ """
+ Associate the (opaque, binary) PAYLOAD with the (opaque, binary) LABEL.
+
+ Any previous payload for LABEL is forgotten.
+
+ This calls the subclass's `_put_passwd' method, which may assume that the
+ database is open for writing.
+ """
+ me._check_write()
+ me._put_passwd(label, payload)
+
+ def del_passwd(me, label):
+ """
+ Forget any PAYLOAD associated with the (opaque, binary) LABEL.
+
+ If there is no such payload then raise `KeyError'.
+
+ This calls the subclass's `_del_passwd' method, which may assume that the
+ database is open for writing.
+ """
+ me._check_write()
+ me._del_passwd(label)
+
+ def iter_passwds(me):
+ """
+ Return an iterator over the stored password label/payload pairs.
+
+ This calls the subclass's `_iter_passwds' method, which may assume that
+ the database is open.
+ """
+ me._check_live()
+ return me._iter_passwds()
+
+try: import gdbm as _G
+except ImportError: pass
+else:
+ class GDBMStorageBackend (StorageBackend):
+ """
+ My instances store password data in a GDBM database.
+
+ Metadata and password entries are mixed into the same database. The key
+ for a metadata item is simply its name; the key for a password entry is
+ the entry's label prefixed by `$', since we're guaranteed that no
+ metadata item name begins with `$'.
+ """
+
+ NAME = 'gdbm'
+
+ def _open(me, file, writep):
+ try: me._db = _G.open(file, writep and 'w' or 'r')
+ except _G.error: raise StorageBackendRefusal(_excval())
+
+ def _create(me, file):
+ me._db = _G.open(file, 'n', 0600)
+
+ def _close(me, abruptp):
+ me._db.close()
+ me._db = None
+
+ def _get_meta(me, name, default):
+ try: return me._db[name]
+ except KeyError: return default
+
+ def _put_meta(me, name, value):
+ me._db[name] = value
+
+ def _del_meta(me, name):
+ del me._db[name]
+
+ def _iter_meta(me):
+ k = me._db.firstkey()
+ while k is not None:
+ if not k.startswith('$'): yield k, me._db[k]
+ k = me._db.nextkey(k)
+
+ def _get_passwd(me, label):
+ return me._db['$' + label]
+
+ def _put_passwd(me, label, payload):
+ me._db['$' + label] = payload
+
+ def _del_passwd(me, label):
+ del me._db['$' + label]
+
+ def _iter_passwds(me):
+ k = me._db.firstkey()
+ while k is not None:
+ if k.startswith('$'): yield k[1:], me._db[k]
+ k = me._db.nextkey(k)
+
+try: import sqlite3 as _Q
+except ImportError: pass
+else:
+ class SQLiteStorageBackend (StorageBackend):
+ """
+ I represent a password database stored in SQLite.
+
+ Metadata and password items are stored in separate tables, so there's no
+ conflict. Some additional metadata is stored in the `meta' table, with
+ names beginning with `$' so as not to conflict with clients:
+
+ $version The schema version of the table.
+ """
+
+ NAME = 'sqlite'
+ VERSION = 0
+
+ def _open(me, file, writep):
+ try:
+ me._db = _Q.connect(file)
+ ver = me._query_scalar(
+ "SELECT value FROM meta WHERE name = '$version'",
+ "version check")
+ except (_Q.DatabaseError, _Q.OperationalError):
+ raise StorageBackendRefusal(_excval())
+ if ver is None: raise ValueError('database broken (missing $version)')
+ elif ver < me.VERSION: me._upgrade(ver)
+ elif ver > me.VERSION: raise ValueError \
+ ('unknown database schema version (%d > %d)' % (ver, me.VERSION))
+
+ def _create(me, file):
+ fd = _OS.open(file, _OS.O_WRONLY | _OS.O_CREAT | _OS.O_EXCL, 0600)
+ _OS.close(fd)
+ try:
+ me._db = _Q.connect(file)
+ c = me._db.cursor()
+ c.execute("""
+ CREATE TABLE meta (
+ name TEXT PRIMARY KEY NOT NULL,
+ value BLOB NOT NULL);
+ """)
+ c.execute("""
+ CREATE TABLE passwd (
+ label BLOB PRIMARY KEY NOT NULL,
+ payload BLOB NOT NULL);
+ """)
+ c.execute("""
+ INSERT INTO meta (name, value) VALUES ('$version', ?);
+ """, [me.VERSION])
+ except:
+ try: _OS.unlink(file)
+ except OSError: pass
+ raise
+
+ def _upgrade(me, ver):
+ """Upgrade the database from schema version VER."""
+ assert False, 'how embarrassing'
+
+ def _close(me, abruptp):
+ if not abruptp: me._db.commit()
+ me._db.close()
+ me._db = None
+
+ def _fetch_scalar(me, c, what, default = None):
+ try: row = next(c)
+ except StopIteration: val = default
+ else: val, = row
+ try: row = next(c)
+ except StopIteration: pass
+ else: raise ValueError('multiple matching records for %s' % what)
+ return val
+
+ def _query_scalar(me, query, what, default = None, args = []):
+ c = me._db.cursor()
+ c.execute(query, args)
+ return me._fetch_scalar(c, what, default)
+
+ def _get_meta(me, name, default):
+ v = me._query_scalar("SELECT value FROM meta WHERE name = ?",
+ "metadata item `%s'" % name,
+ default = default, args = [name])
+ if v is default: return v
+ else: return str(v)
+
+ def _put_meta(me, name, value):
+ c = me._db.cursor()
+ c.execute("INSERT OR REPLACE INTO meta (name, value) VALUES (?, ?)",
+ [name, buffer(value)])