+### 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 StorageBackend.CLASSES.itervalues()
+
+ @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, payload)
+
+ 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.