Blame lang/python/src/core.py

Packit Service 6c01f9
# Copyright (C) 2016-2017 g10 Code GmbH
Packit Service 6c01f9
# Copyright (C) 2004,2008 Igor Belyi <belyi@users.sourceforge.net>
Packit Service 672cf4
# Copyright (C) 2002 John Goerzen <jgoerzen@complete.org>
Packit Service 672cf4
#
Packit Service 672cf4
#    This library is free software; you can redistribute it and/or
Packit Service 672cf4
#    modify it under the terms of the GNU Lesser General Public
Packit Service 672cf4
#    License as published by the Free Software Foundation; either
Packit Service 672cf4
#    version 2.1 of the License, or (at your option) any later version.
Packit Service 672cf4
#
Packit Service 672cf4
#    This library is distributed in the hope that it will be useful,
Packit Service 672cf4
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit Service 672cf4
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Packit Service 672cf4
#    Lesser General Public License for more details.
Packit Service 672cf4
#
Packit Service 672cf4
#    You should have received a copy of the GNU Lesser General Public
Packit Service 672cf4
#    License along with this library; if not, write to the Free Software
Packit Service 672cf4
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
Packit Service 6c01f9
Packit Service 672cf4
"""Core functionality
Packit Service 672cf4
Packit Service 672cf4
Core functionality of GPGME wrapped in a object-oriented fashion.
Packit Service 672cf4
Provides the 'Context' class for performing cryptographic operations,
Packit Service 672cf4
and the 'Data' class describing buffers of data.
Packit Service 672cf4
Packit Service 672cf4
"""
Packit Service 672cf4
Packit Service 6c01f9
from __future__ import absolute_import, print_function, unicode_literals
Packit Service 6c01f9
del absolute_import, print_function, unicode_literals
Packit Service 6c01f9
Packit Service 6c01f9
import re
Packit Service 6c01f9
import os
Packit Service 6c01f9
import warnings
Packit Service 6c01f9
import weakref
Packit Service 6c01f9
from . import gpgme
Packit Service 6c01f9
from .errors import errorcheck, GPGMEError
Packit Service 6c01f9
from . import constants
Packit Service 6c01f9
from . import errors
Packit Service 6c01f9
from . import util
Packit Service 672cf4
Packit Service 672cf4
class GpgmeWrapper(object):
Packit Service 672cf4
    """Base wrapper class
Packit Service 672cf4
Packit Service 672cf4
    Not to be instantiated directly.
Packit Service 672cf4
Packit Service 672cf4
    """
Packit Service 672cf4
Packit Service 672cf4
    def __init__(self, wrapped):
Packit Service 672cf4
        self._callback_excinfo = None
Packit Service 672cf4
        self.wrapped = wrapped
Packit Service 672cf4
Packit Service 672cf4
    def __repr__(self):
Packit Service 6c01f9
        return '<{}/{!r}>'.format(super(GpgmeWrapper, self).__repr__(),
Packit Service 6c01f9
                                  self.wrapped)
Packit Service 672cf4
Packit Service 672cf4
    def __str__(self):
Packit Service 672cf4
        acc = ['{}.{}'.format(__name__, self.__class__.__name__)]
Packit Service 672cf4
        flags = [f for f in self._boolean_properties if getattr(self, f)]
Packit Service 672cf4
        if flags:
Packit Service 672cf4
            acc.append('({})'.format(' '.join(flags)))
Packit Service 672cf4
Packit Service 672cf4
        return '<{}>'.format(' '.join(acc))
Packit Service 672cf4
Packit Service 672cf4
    def __hash__(self):
Packit Service 672cf4
        return hash(repr(self.wrapped))
Packit Service 672cf4
Packit Service 672cf4
    def __eq__(self, other):
Packit Service 6c01f9
        if other == None:
Packit Service 672cf4
            return False
Packit Service 672cf4
        else:
Packit Service 672cf4
            return repr(self.wrapped) == repr(other.wrapped)
Packit Service 672cf4
Packit Service 672cf4
    @property
Packit Service 672cf4
    def _ctype(self):
Packit Service 672cf4
        """The name of the c type wrapped by this class
Packit Service 672cf4
Packit Service 672cf4
        Must be set by child classes.
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        raise NotImplementedError()
Packit Service 672cf4
Packit Service 672cf4
    @property
Packit Service 672cf4
    def _cprefix(self):
Packit Service 672cf4
        """The common prefix of c functions wrapped by this class
Packit Service 672cf4
Packit Service 672cf4
        Must be set by child classes.
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        raise NotImplementedError()
Packit Service 672cf4
Packit Service 672cf4
    def _errorcheck(self, name):
Packit Service 672cf4
        """Must be implemented by child classes.
Packit Service 672cf4
Packit Service 672cf4
        This function must return a trueish value for all c functions
Packit Service 672cf4
        returning gpgme_error_t."""
Packit Service 672cf4
        raise NotImplementedError()
Packit Service 672cf4
Packit Service 672cf4
    """The set of all boolean properties"""
Packit Service 672cf4
    _boolean_properties = set()
Packit Service 672cf4
Packit Service 672cf4
    def __wrap_boolean_property(self, key, do_set=False, value=None):
Packit Service 6c01f9
        get_func = getattr(gpgme,
Packit Service 6c01f9
                           "{}get_{}".format(self._cprefix, key))
Packit Service 6c01f9
        set_func = getattr(gpgme,
Packit Service 6c01f9
                           "{}set_{}".format(self._cprefix, key))
Packit Service 672cf4
        def get(slf):
Packit Service 672cf4
            return bool(get_func(slf.wrapped))
Packit Service 672cf4
        def set_(slf, value):
Packit Service 672cf4
            set_func(slf.wrapped, bool(value))
Packit Service 672cf4
Packit Service 672cf4
        p = property(get, set_, doc="{} flag".format(key))
Packit Service 672cf4
        setattr(self.__class__, key, p)
Packit Service 672cf4
Packit Service 672cf4
        if do_set:
Packit Service 672cf4
            set_(self, bool(value))
Packit Service 672cf4
        else:
Packit Service 672cf4
            return get(self)
Packit Service 672cf4
Packit Service 672cf4
    _munge_docstring = re.compile(r'gpgme_([^(]*)\(([^,]*), (.*\) -> .*)')
Packit Service 672cf4
    def __getattr__(self, key):
Packit Service 672cf4
        """On-the-fly generation of wrapper methods and properties"""
Packit Service 6c01f9
        if key[0] == '_' or self._cprefix == None:
Packit Service 672cf4
            return None
Packit Service 672cf4
Packit Service 672cf4
        if key in self._boolean_properties:
Packit Service 672cf4
            return self.__wrap_boolean_property(key)
Packit Service 672cf4
Packit Service 672cf4
        name = self._cprefix + key
Packit Service 672cf4
        func = getattr(gpgme, name)
Packit Service 672cf4
Packit Service 672cf4
        if self._errorcheck(name):
Packit Service 672cf4
            def _funcwrap(slf, *args):
Packit Service 672cf4
                result = func(slf.wrapped, *args)
Packit Service 672cf4
                if slf._callback_excinfo:
Packit Service 672cf4
                    gpgme.gpg_raise_callback_exception(slf)
Packit Service 672cf4
                return errorcheck(result, name)
Packit Service 672cf4
        else:
Packit Service 672cf4
            def _funcwrap(slf, *args):
Packit Service 672cf4
                result = func(slf.wrapped, *args)
Packit Service 672cf4
                if slf._callback_excinfo:
Packit Service 672cf4
                    gpgme.gpg_raise_callback_exception(slf)
Packit Service 672cf4
                return result
Packit Service 672cf4
Packit Service 672cf4
        doc = self._munge_docstring.sub(r'\2.\1(\3', getattr(func, "__doc__"))
Packit Service 672cf4
        _funcwrap.__doc__ = doc
Packit Service 672cf4
Packit Service 672cf4
        # Monkey-patch the class.
Packit Service 672cf4
        setattr(self.__class__, key, _funcwrap)
Packit Service 672cf4
Packit Service 672cf4
        # Bind the method to 'self'.
Packit Service 672cf4
        def wrapper(*args):
Packit Service 672cf4
            return _funcwrap(self, *args)
Packit Service 672cf4
        wrapper.__doc__ = doc
Packit Service 672cf4
Packit Service 672cf4
        return wrapper
Packit Service 672cf4
Packit Service 672cf4
    def __setattr__(self, key, value):
Packit Service 672cf4
        """On-the-fly generation of properties"""
Packit Service 672cf4
        if key in self._boolean_properties:
Packit Service 672cf4
            self.__wrap_boolean_property(key, True, value)
Packit Service 672cf4
        else:
Packit Service 672cf4
            super(GpgmeWrapper, self).__setattr__(key, value)
Packit Service 672cf4
Packit Service 672cf4
class Context(GpgmeWrapper):
Packit Service 672cf4
    """Context for cryptographic operations
Packit Service 672cf4
Packit Service 672cf4
    All cryptographic operations in GPGME are performed within a
Packit Service 672cf4
    context, which contains the internal state of the operation as
Packit Service 672cf4
    well as configuration parameters.  By using several contexts you
Packit Service 672cf4
    can run several cryptographic operations in parallel, with
Packit Service 672cf4
    different configuration.
Packit Service 672cf4
Packit Service 672cf4
    Access to a context must be synchronized.
Packit Service 672cf4
Packit Service 672cf4
    """
Packit Service 672cf4
Packit Service 6c01f9
    def __init__(self, armor=False, textmode=False, offline=False,
Packit Service 6c01f9
                 signers=[], pinentry_mode=constants.PINENTRY_MODE_DEFAULT,
Packit Service 672cf4
                 protocol=constants.PROTOCOL_OpenPGP,
Packit Service 6c01f9
                 wrapped=None, home_dir=None):
Packit Service 672cf4
        """Construct a context object
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        armor		-- enable ASCII armoring (default False)
Packit Service 672cf4
        textmode	-- enable canonical text mode (default False)
Packit Service 672cf4
        offline		-- do not contact external key sources (default False)
Packit Service 672cf4
        signers		-- list of keys used for signing (default [])
Packit Service 672cf4
        pinentry_mode	-- pinentry mode (default PINENTRY_MODE_DEFAULT)
Packit Service 672cf4
        protocol	-- protocol to use (default PROTOCOL_OpenPGP)
Packit Service 672cf4
        home_dir        -- state directory (default is the engine default)
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        if wrapped:
Packit Service 672cf4
            self.own = False
Packit Service 672cf4
        else:
Packit Service 672cf4
            tmp = gpgme.new_gpgme_ctx_t_p()
Packit Service 672cf4
            errorcheck(gpgme.gpgme_new(tmp))
Packit Service 672cf4
            wrapped = gpgme.gpgme_ctx_t_p_value(tmp)
Packit Service 672cf4
            gpgme.delete_gpgme_ctx_t_p(tmp)
Packit Service 672cf4
            self.own = True
Packit Service 672cf4
        super(Context, self).__init__(wrapped)
Packit Service 672cf4
        self.armor = armor
Packit Service 672cf4
        self.textmode = textmode
Packit Service 672cf4
        self.offline = offline
Packit Service 672cf4
        self.signers = signers
Packit Service 672cf4
        self.pinentry_mode = pinentry_mode
Packit Service 672cf4
        self.protocol = protocol
Packit Service 672cf4
        self.home_dir = home_dir
Packit Service 672cf4
Packit Service 672cf4
    def __read__(self, sink, data):
Packit Service 672cf4
        """Read helper
Packit Service 672cf4
Packit Service 672cf4
        Helper function to retrieve the results of an operation, or
Packit Service 672cf4
        None if SINK is given.
Packit Service 672cf4
        """
Packit Service 6c01f9
        if sink or data == None:
Packit Service 672cf4
            return None
Packit Service 672cf4
        data.seek(0, os.SEEK_SET)
Packit Service 672cf4
        return data.read()
Packit Service 672cf4
Packit Service 672cf4
    def __repr__(self):
Packit Service 6c01f9
        return (
Packit Service 6c01f9
            "Context(armor={0.armor}, "
Packit Service 6c01f9
            "textmode={0.textmode}, offline={0.offline}, "
Packit Service 6c01f9
            "signers={0.signers}, pinentry_mode={0.pinentry_mode}, "
Packit Service 6c01f9
            "protocol={0.protocol}, home_dir={0.home_dir}"
Packit Service 6c01f9
            ")").format(self)
Packit Service 6c01f9
Packit Service 6c01f9
    def encrypt(self, plaintext, recipients=[], sign=True, sink=None,
Packit Service 6c01f9
                passphrase=None, always_trust=False, add_encrypt_to=False,
Packit Service 6c01f9
                prepare=False, expect_sign=False, compress=True):
Packit Service 672cf4
        """Encrypt data
Packit Service 672cf4
Packit Service 672cf4
        Encrypt the given plaintext for the given recipients.  If the
Packit Service 672cf4
        list of recipients is empty, the data is encrypted
Packit Service 672cf4
        symmetrically with a passphrase.
Packit Service 672cf4
Packit Service 672cf4
        The passphrase can be given as parameter, using a callback
Packit Service 672cf4
        registered at the context, or out-of-band via pinentry.
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        recipients	-- list of keys to encrypt to
Packit Service 672cf4
        sign		-- sign plaintext (default True)
Packit Service 672cf4
        sink		-- write result to sink instead of returning it
Packit Service 672cf4
        passphrase	-- for symmetric encryption
Packit Service 672cf4
        always_trust	-- always trust the keys (default False)
Packit Service 672cf4
        add_encrypt_to	-- encrypt to configured additional keys (default False)
Packit Service 672cf4
        prepare		-- (ui) prepare for encryption (default False)
Packit Service 672cf4
        expect_sign	-- (ui) prepare for signing (default False)
Packit Service 672cf4
        compress	-- compress plaintext (default True)
Packit Service 672cf4
Packit Service 672cf4
        Returns:
Packit Service 672cf4
        ciphertext	-- the encrypted data (or None if sink is given)
Packit Service 672cf4
        result		-- additional information about the encryption
Packit Service 672cf4
        sign_result	-- additional information about the signature(s)
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        InvalidRecipients -- if encryption using a particular key failed
Packit Service 672cf4
        InvalidSigners	-- if signing using a particular key failed
Packit Service 672cf4
        GPGMEError	-- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        ciphertext = sink if sink else Data()
Packit Service 672cf4
        flags = 0
Packit Service 672cf4
        flags |= always_trust * constants.ENCRYPT_ALWAYS_TRUST
Packit Service 672cf4
        flags |= (not add_encrypt_to) * constants.ENCRYPT_NO_ENCRYPT_TO
Packit Service 672cf4
        flags |= prepare * constants.ENCRYPT_PREPARE
Packit Service 672cf4
        flags |= expect_sign * constants.ENCRYPT_EXPECT_SIGN
Packit Service 672cf4
        flags |= (not compress) * constants.ENCRYPT_NO_COMPRESS
Packit Service 672cf4
Packit Service 6c01f9
        if passphrase != None:
Packit Service 672cf4
            old_pinentry_mode = self.pinentry_mode
Packit Service 672cf4
            old_passphrase_cb = getattr(self, '_passphrase_cb', None)
Packit Service 672cf4
            self.pinentry_mode = constants.PINENTRY_MODE_LOOPBACK
Packit Service 672cf4
            def passphrase_cb(hint, desc, prev_bad, hook=None):
Packit Service 672cf4
                return passphrase
Packit Service 672cf4
            self.set_passphrase_cb(passphrase_cb)
Packit Service 672cf4
Packit Service 672cf4
        try:
Packit Service 672cf4
            if sign:
Packit Service 672cf4
                self.op_encrypt_sign(recipients, flags, plaintext, ciphertext)
Packit Service 672cf4
            else:
Packit Service 672cf4
                self.op_encrypt(recipients, flags, plaintext, ciphertext)
Packit Service 672cf4
        except errors.GPGMEError as e:
Packit Service 672cf4
            result = self.op_encrypt_result()
Packit Service 672cf4
            sig_result = self.op_sign_result() if sign else None
Packit Service 6c01f9
            results = (self.__read__(sink, ciphertext),
Packit Service 6c01f9
                       result, sig_result)
Packit Service 672cf4
            if e.getcode() == errors.UNUSABLE_PUBKEY:
Packit Service 672cf4
                if result.invalid_recipients:
Packit Service 6c01f9
                    raise errors.InvalidRecipients(result.invalid_recipients,
Packit Service 6c01f9
                                                   error=e.error,
Packit Service 6c01f9
                                                   results=results)
Packit Service 672cf4
            if e.getcode() == errors.UNUSABLE_SECKEY:
Packit Service 672cf4
                sig_result = self.op_sign_result()
Packit Service 672cf4
                if sig_result.invalid_signers:
Packit Service 6c01f9
                    raise errors.InvalidSigners(sig_result.invalid_signers,
Packit Service 6c01f9
                                                error=e.error,
Packit Service 6c01f9
                                                results=results)
Packit Service 672cf4
            # Otherwise, just raise the error, but attach the results
Packit Service 672cf4
            # first.
Packit Service 672cf4
            e.results = results
Packit Service 672cf4
            raise e
Packit Service 672cf4
        finally:
Packit Service 6c01f9
            if passphrase != None:
Packit Service 672cf4
                self.pinentry_mode = old_pinentry_mode
Packit Service 672cf4
                if old_passphrase_cb:
Packit Service 672cf4
                    self.set_passphrase_cb(*old_passphrase_cb[1:])
Packit Service 672cf4
Packit Service 672cf4
        result = self.op_encrypt_result()
Packit Service 672cf4
        assert not result.invalid_recipients
Packit Service 672cf4
        sig_result = self.op_sign_result() if sign else None
Packit Service 672cf4
        assert not sig_result or not sig_result.invalid_signers
Packit Service 672cf4
Packit Service 672cf4
        return self.__read__(sink, ciphertext), result, sig_result
Packit Service 672cf4
Packit Service 672cf4
    def decrypt(self, ciphertext, sink=None, passphrase=None, verify=True):
Packit Service 672cf4
        """Decrypt data
Packit Service 672cf4
Packit Service 672cf4
        Decrypt the given ciphertext and verify any signatures.  If
Packit Service 672cf4
        VERIFY is an iterable of keys, the ciphertext must be signed
Packit Service 6c01f9
        by all those keys, otherwise an error is raised.
Packit Service 672cf4
Packit Service 672cf4
        If the ciphertext is symmetrically encrypted using a
Packit Service 672cf4
        passphrase, that passphrase can be given as parameter, using a
Packit Service 672cf4
        callback registered at the context, or out-of-band via
Packit Service 672cf4
        pinentry.
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 6c01f9
        sink		-- write result to sink instead of returning it
Packit Service 6c01f9
        passphrase	-- for symmetric decryption
Packit Service 6c01f9
        verify		-- check signatures (default True)
Packit Service 672cf4
Packit Service 672cf4
        Returns:
Packit Service 6c01f9
        plaintext	-- the decrypted data (or None if sink is given)
Packit Service 6c01f9
        result		-- additional information about the decryption
Packit Service 6c01f9
        verify_result	-- additional information about the signature(s)
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        UnsupportedAlgorithm -- if an unsupported algorithm was used
Packit Service 6c01f9
        BadSignatures	-- if a bad signature is encountered
Packit Service 6c01f9
        MissingSignatures -- if expected signatures are missing or bad
Packit Service 6c01f9
        GPGMEError	-- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        plaintext = sink if sink else Data()
Packit Service 672cf4
Packit Service 6c01f9
        if passphrase != None:
Packit Service 672cf4
            old_pinentry_mode = self.pinentry_mode
Packit Service 672cf4
            old_passphrase_cb = getattr(self, '_passphrase_cb', None)
Packit Service 672cf4
            self.pinentry_mode = constants.PINENTRY_MODE_LOOPBACK
Packit Service 672cf4
            def passphrase_cb(hint, desc, prev_bad, hook=None):
Packit Service 672cf4
                return passphrase
Packit Service 672cf4
            self.set_passphrase_cb(passphrase_cb)
Packit Service 672cf4
Packit Service 672cf4
        try:
Packit Service 6c01f9
            if verify:
Packit Service 672cf4
                self.op_decrypt_verify(ciphertext, plaintext)
Packit Service 672cf4
            else:
Packit Service 672cf4
                self.op_decrypt(ciphertext, plaintext)
Packit Service 672cf4
        except errors.GPGMEError as e:
Packit Service 672cf4
            result = self.op_decrypt_result()
Packit Service 6c01f9
            verify_result = self.op_verify_result() if verify else None
Packit Service 672cf4
            # Just raise the error, but attach the results first.
Packit Service 6c01f9
            e.results = (self.__read__(sink, plaintext),
Packit Service 6c01f9
                         result, verify_result)
Packit Service 672cf4
            raise e
Packit Service 672cf4
        finally:
Packit Service 6c01f9
            if passphrase != None:
Packit Service 672cf4
                self.pinentry_mode = old_pinentry_mode
Packit Service 672cf4
                if old_passphrase_cb:
Packit Service 672cf4
                    self.set_passphrase_cb(*old_passphrase_cb[1:])
Packit Service 672cf4
Packit Service 672cf4
        result = self.op_decrypt_result()
Packit Service 6c01f9
        verify_result = self.op_verify_result() if verify else None
Packit Service 672cf4
        results = (self.__read__(sink, plaintext), result, verify_result)
Packit Service 672cf4
        if result.unsupported_algorithm:
Packit Service 672cf4
            raise errors.UnsupportedAlgorithm(result.unsupported_algorithm,
Packit Service 672cf4
                                              results=results)
Packit Service 672cf4
Packit Service 6c01f9
        if verify:
Packit Service 6c01f9
            if any(s.status != errors.NO_ERROR
Packit Service 6c01f9
                   for s in verify_result.signatures):
Packit Service 6c01f9
                raise errors.BadSignatures(verify_result, results=results)
Packit Service 6c01f9
Packit Service 6c01f9
        if verify and verify != True:
Packit Service 6c01f9
            missing = list()
Packit Service 6c01f9
            for key in verify:
Packit Service 6c01f9
                ok = False
Packit Service 6c01f9
                for subkey in key.subkeys:
Packit Service 6c01f9
                    for sig in verify_result.signatures:
Packit Service 6c01f9
                        if sig.summary & constants.SIGSUM_VALID == 0:
Packit Service 6c01f9
                            continue
Packit Service 6c01f9
                        if subkey.can_sign and subkey.fpr == sig.fpr:
Packit Service 6c01f9
                            ok = True
Packit Service 672cf4
                            break
Packit Service 6c01f9
                    if ok:
Packit Service 6c01f9
                        break
Packit Service 6c01f9
                if not ok:
Packit Service 6c01f9
                    missing.append(key)
Packit Service 6c01f9
            if missing:
Packit Service 6c01f9
                raise errors.MissingSignatures(verify_result, missing,
Packit Service 6c01f9
                                               results=results)
Packit Service 672cf4
Packit Service 672cf4
        return results
Packit Service 672cf4
Packit Service 672cf4
    def sign(self, data, sink=None, mode=constants.SIG_MODE_NORMAL):
Packit Service 672cf4
        """Sign data
Packit Service 672cf4
Packit Service 672cf4
        Sign the given data with either the configured default local
Packit Service 672cf4
        key, or the 'signers' keys of this context.
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        mode		-- signature mode (default: normal, see below)
Packit Service 672cf4
        sink		-- write result to sink instead of returning it
Packit Service 672cf4
Packit Service 672cf4
        Returns:
Packit Service 672cf4
        either
Packit Service 672cf4
          signed_data	-- encoded data and signature (normal mode)
Packit Service 672cf4
          signature	-- only the signature data (detached mode)
Packit Service 672cf4
          cleartext	-- data and signature as text (cleartext mode)
Packit Service 672cf4
            (or None if sink is given)
Packit Service 672cf4
        result		-- additional information about the signature(s)
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        InvalidSigners	-- if signing using a particular key failed
Packit Service 672cf4
        GPGMEError	-- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        signeddata = sink if sink else Data()
Packit Service 672cf4
Packit Service 672cf4
        try:
Packit Service 672cf4
            self.op_sign(data, signeddata, mode)
Packit Service 672cf4
        except errors.GPGMEError as e:
Packit Service 6c01f9
            results = (self.__read__(sink, signeddata),
Packit Service 6c01f9
                       self.op_sign_result())
Packit Service 672cf4
            if e.getcode() == errors.UNUSABLE_SECKEY:
Packit Service 672cf4
                if results[1].invalid_signers:
Packit Service 6c01f9
                    raise errors.InvalidSigners(results[1].invalid_signers,
Packit Service 6c01f9
                                                error=e.error,
Packit Service 6c01f9
                                                results=results)
Packit Service 672cf4
            e.results = results
Packit Service 672cf4
            raise e
Packit Service 672cf4
Packit Service 672cf4
        result = self.op_sign_result()
Packit Service 672cf4
        assert not result.invalid_signers
Packit Service 672cf4
Packit Service 672cf4
        return self.__read__(sink, signeddata), result
Packit Service 672cf4
Packit Service 672cf4
    def verify(self, signed_data, signature=None, sink=None, verify=[]):
Packit Service 672cf4
        """Verify signatures
Packit Service 672cf4
Packit Service 672cf4
        Verify signatures over data.  If VERIFY is an iterable of
Packit Service 672cf4
        keys, the ciphertext must be signed by all those keys,
Packit Service 672cf4
        otherwise an error is raised.
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        signature	-- detached signature data
Packit Service 672cf4
        sink		-- write result to sink instead of returning it
Packit Service 672cf4
Packit Service 672cf4
        Returns:
Packit Service 672cf4
        data		-- the plain data
Packit Service 672cf4
            (or None if sink is given, or we verified a detached signature)
Packit Service 672cf4
        result		-- additional information about the signature(s)
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        BadSignatures	-- if a bad signature is encountered
Packit Service 672cf4
        MissingSignatures -- if expected signatures are missing or bad
Packit Service 672cf4
        GPGMEError	-- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        if signature:
Packit Service 672cf4
            # Detached signature, we don't return the plain text.
Packit Service 672cf4
            data = None
Packit Service 672cf4
        else:
Packit Service 672cf4
            data = sink if sink else Data()
Packit Service 672cf4
Packit Service 672cf4
        try:
Packit Service 672cf4
            if signature:
Packit Service 672cf4
                self.op_verify(signature, signed_data, None)
Packit Service 672cf4
            else:
Packit Service 672cf4
                self.op_verify(signed_data, None, data)
Packit Service 672cf4
        except errors.GPGMEError as e:
Packit Service 672cf4
            # Just raise the error, but attach the results first.
Packit Service 6c01f9
            e.results = (self.__read__(sink, data),
Packit Service 6c01f9
                         self.op_verify_result())
Packit Service 672cf4
            raise e
Packit Service 672cf4
Packit Service 672cf4
        results = (self.__read__(sink, data), self.op_verify_result())
Packit Service 672cf4
        if any(s.status != errors.NO_ERROR for s in results[1].signatures):
Packit Service 672cf4
            raise errors.BadSignatures(results[1], results=results)
Packit Service 672cf4
Packit Service 672cf4
        missing = list()
Packit Service 672cf4
        for key in verify:
Packit Service 672cf4
            ok = False
Packit Service 672cf4
            for subkey in key.subkeys:
Packit Service 672cf4
                for sig in results[1].signatures:
Packit Service 672cf4
                    if sig.summary & constants.SIGSUM_VALID == 0:
Packit Service 672cf4
                        continue
Packit Service 672cf4
                    if subkey.can_sign and subkey.fpr == sig.fpr:
Packit Service 672cf4
                        ok = True
Packit Service 672cf4
                        break
Packit Service 672cf4
                if ok:
Packit Service 672cf4
                    break
Packit Service 672cf4
            if not ok:
Packit Service 672cf4
                missing.append(key)
Packit Service 672cf4
        if missing:
Packit Service 6c01f9
            raise errors.MissingSignatures(results[1], missing,
Packit Service 6c01f9
                                           results=results)
Packit Service 672cf4
Packit Service 672cf4
        return results
Packit Service 672cf4
Packit Service 6c01f9
    def keylist(self, pattern=None, secret=False,
Packit Service 672cf4
                mode=constants.keylist.mode.LOCAL,
Packit Service 672cf4
                source=None):
Packit Service 672cf4
        """List keys
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        pattern	-- return keys matching pattern (default: all keys)
Packit Service 672cf4
        secret	-- return only secret keys (default: False)
Packit Service 672cf4
        mode    -- keylist mode (default: list local keys)
Packit Service 672cf4
        source  -- read keys from source instead from the keyring
Packit Service 672cf4
                       (all other options are ignored in this case)
Packit Service 672cf4
Packit Service 672cf4
        Returns:
Packit Service 672cf4
                -- an iterator returning key objects
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        GPGMEError	-- as signaled by the underlying library
Packit Service 672cf4
        """
Packit Service 672cf4
        if not source:
Packit Service 672cf4
            self.set_keylist_mode(mode)
Packit Service 672cf4
            self.op_keylist_start(pattern, secret)
Packit Service 672cf4
        else:
Packit Service 672cf4
            # Automatic wrapping of SOURCE is not possible here,
Packit Service 672cf4
            # because the object must not be deallocated until the
Packit Service 672cf4
            # iteration over the results ends.
Packit Service 672cf4
            if not isinstance(source, Data):
Packit Service 672cf4
                source = Data(file=source)
Packit Service 672cf4
            self.op_keylist_from_data_start(source, 0)
Packit Service 672cf4
Packit Service 672cf4
        key = self.op_keylist_next()
Packit Service 672cf4
        while key:
Packit Service 672cf4
            yield key
Packit Service 672cf4
            key = self.op_keylist_next()
Packit Service 672cf4
        self.op_keylist_end()
Packit Service 672cf4
Packit Service 6c01f9
    def create_key(self, userid, algorithm=None, expires_in=0, expires=True,
Packit Service 6c01f9
                   sign=False, encrypt=False, certify=False, authenticate=False,
Packit Service 6c01f9
                   passphrase=None, force=False):
Packit Service 672cf4
        """Create a primary key
Packit Service 672cf4
Packit Service 672cf4
        Create a primary key for the user id USERID.
Packit Service 672cf4
Packit Service 672cf4
        ALGORITHM may be used to specify the public key encryption
Packit Service 672cf4
        algorithm for the new key.  By default, a reasonable default
Packit Service 672cf4
        is chosen.  You may use "future-default" to select an
Packit Service 672cf4
        algorithm that will be the default in a future implementation
Packit Service 672cf4
        of the engine.  ALGORITHM may be a string like "rsa", or
Packit Service 672cf4
        "rsa2048" to explicitly request an algorithm and a key size.
Packit Service 672cf4
Packit Service 672cf4
        EXPIRES_IN specifies the expiration time of the key in number
Packit Service 672cf4
        of seconds since the keys creation.  By default, a reasonable
Packit Service 672cf4
        expiration time is chosen.  If you want to create a key that
Packit Service 672cf4
        does not expire, use the keyword argument EXPIRES.
Packit Service 672cf4
Packit Service 672cf4
        SIGN, ENCRYPT, CERTIFY, and AUTHENTICATE can be used to
Packit Service 672cf4
        request the capabilities of the new key.  If you don't request
Packit Service 672cf4
        any, a reasonable set of capabilities is selected, and in case
Packit Service 672cf4
        of OpenPGP, a subkey with a reasonable set of capabilities is
Packit Service 672cf4
        created.
Packit Service 672cf4
Packit Service 672cf4
        If PASSPHRASE is None (the default), then the key will not be
Packit Service 672cf4
        protected with a passphrase.  If PASSPHRASE is a string, it
Packit Service 672cf4
        will be used to protect the key.  If PASSPHRASE is True, the
Packit Service 672cf4
        passphrase must be supplied using a passphrase callback or
Packit Service 672cf4
        out-of-band with a pinentry.
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        algorithm    -- public key algorithm, see above (default: reasonable)
Packit Service 672cf4
        expires_in   -- expiration time in seconds (default: reasonable)
Packit Service 672cf4
        expires      -- whether or not the key should expire (default: True)
Packit Service 672cf4
        sign         -- request the signing capability (see above)
Packit Service 672cf4
        encrypt      -- request the encryption capability (see above)
Packit Service 672cf4
        certify      -- request the certification capability (see above)
Packit Service 672cf4
        authenticate -- request the authentication capability (see above)
Packit Service 6c01f9
        passphrase   -- protect the key with a passphrase (default: no passphrase)
Packit Service 6c01f9
        force        -- force key creation even if a key with the same userid exists
Packit Service 6c01f9
                                                          (default: False)
Packit Service 672cf4
Packit Service 672cf4
        Returns:
Packit Service 672cf4
                     -- an object describing the result of the key creation
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        GPGMEError   -- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        if util.is_a_string(passphrase):
Packit Service 672cf4
            old_pinentry_mode = self.pinentry_mode
Packit Service 672cf4
            old_passphrase_cb = getattr(self, '_passphrase_cb', None)
Packit Service 672cf4
            self.pinentry_mode = constants.PINENTRY_MODE_LOOPBACK
Packit Service 672cf4
            def passphrase_cb(hint, desc, prev_bad, hook=None):
Packit Service 672cf4
                return passphrase
Packit Service 672cf4
            self.set_passphrase_cb(passphrase_cb)
Packit Service 672cf4
Packit Service 672cf4
        try:
Packit Service 6c01f9
            self.op_createkey(userid, algorithm,
Packit Service 6c01f9
                              0, # reserved
Packit Service 6c01f9
                              expires_in,
Packit Service 6c01f9
                              None, # extrakey
Packit Service 6c01f9
                              ((constants.create.SIGN if sign else 0)
Packit Service 6c01f9
                               | (constants.create.ENCR if encrypt else 0)
Packit Service 6c01f9
                               | (constants.create.CERT if certify else 0)
Packit Service 6c01f9
                               | (constants.create.AUTH if authenticate else 0)
Packit Service 6c01f9
                               | (constants.create.NOPASSWD if passphrase == None else 0)
Packit Service 6c01f9
                               | (0 if expires else constants.create.NOEXPIRE)
Packit Service 6c01f9
                               | (constants.create.FORCE if force else 0)))
Packit Service 672cf4
        finally:
Packit Service 672cf4
            if util.is_a_string(passphrase):
Packit Service 672cf4
                self.pinentry_mode = old_pinentry_mode
Packit Service 672cf4
                if old_passphrase_cb:
Packit Service 672cf4
                    self.set_passphrase_cb(*old_passphrase_cb[1:])
Packit Service 672cf4
Packit Service 672cf4
        return self.op_genkey_result()
Packit Service 672cf4
Packit Service 6c01f9
    def create_subkey(self, key, algorithm=None, expires_in=0, expires=True,
Packit Service 6c01f9
                      sign=False, encrypt=False, authenticate=False, passphrase=None):
Packit Service 672cf4
        """Create a subkey
Packit Service 672cf4
Packit Service 672cf4
        Create a subkey for the given KEY.  As subkeys are a concept
Packit Service 672cf4
        of OpenPGP, calling this is only valid for the OpenPGP
Packit Service 672cf4
        protocol.
Packit Service 672cf4
Packit Service 672cf4
        ALGORITHM may be used to specify the public key encryption
Packit Service 672cf4
        algorithm for the new subkey.  By default, a reasonable
Packit Service 672cf4
        default is chosen.  You may use "future-default" to select an
Packit Service 672cf4
        algorithm that will be the default in a future implementation
Packit Service 672cf4
        of the engine.  ALGORITHM may be a string like "rsa", or
Packit Service 672cf4
        "rsa2048" to explicitly request an algorithm and a key size.
Packit Service 672cf4
Packit Service 672cf4
        EXPIRES_IN specifies the expiration time of the subkey in
Packit Service 672cf4
        number of seconds since the subkeys creation.  By default, a
Packit Service 672cf4
        reasonable expiration time is chosen.  If you want to create a
Packit Service 672cf4
        subkey that does not expire, use the keyword argument EXPIRES.
Packit Service 672cf4
Packit Service 672cf4
        SIGN, ENCRYPT, and AUTHENTICATE can be used to request the
Packit Service 672cf4
        capabilities of the new subkey.  If you don't request any, an
Packit Service 672cf4
        encryption subkey is generated.
Packit Service 672cf4
Packit Service 672cf4
        If PASSPHRASE is None (the default), then the subkey will not
Packit Service 672cf4
        be protected with a passphrase.  If PASSPHRASE is a string, it
Packit Service 672cf4
        will be used to protect the subkey.  If PASSPHRASE is True,
Packit Service 672cf4
        the passphrase must be supplied using a passphrase callback or
Packit Service 672cf4
        out-of-band with a pinentry.
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        algorithm    -- public key algorithm, see above (default: reasonable)
Packit Service 672cf4
        expires_in   -- expiration time in seconds (default: reasonable)
Packit Service 672cf4
        expires      -- whether or not the subkey should expire (default: True)
Packit Service 672cf4
        sign         -- request the signing capability (see above)
Packit Service 672cf4
        encrypt      -- request the encryption capability (see above)
Packit Service 672cf4
        authenticate -- request the authentication capability (see above)
Packit Service 6c01f9
        passphrase   -- protect the subkey with a passphrase (default: no passphrase)
Packit Service 672cf4
Packit Service 672cf4
        Returns:
Packit Service 672cf4
                     -- an object describing the result of the subkey creation
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        GPGMEError   -- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        if util.is_a_string(passphrase):
Packit Service 672cf4
            old_pinentry_mode = self.pinentry_mode
Packit Service 672cf4
            old_passphrase_cb = getattr(self, '_passphrase_cb', None)
Packit Service 672cf4
            self.pinentry_mode = constants.PINENTRY_MODE_LOOPBACK
Packit Service 672cf4
            def passphrase_cb(hint, desc, prev_bad, hook=None):
Packit Service 672cf4
                return passphrase
Packit Service 672cf4
            self.set_passphrase_cb(passphrase_cb)
Packit Service 672cf4
Packit Service 672cf4
        try:
Packit Service 6c01f9
            self.op_createsubkey(key, algorithm,
Packit Service 6c01f9
                                 0, # reserved
Packit Service 6c01f9
                                 expires_in,
Packit Service 6c01f9
                                 ((constants.create.SIGN if sign else 0)
Packit Service 6c01f9
                                  | (constants.create.ENCR if encrypt else 0)
Packit Service 6c01f9
                                  | (constants.create.AUTH if authenticate else 0)
Packit Service 6c01f9
                                  | (constants.create.NOPASSWD
Packit Service 6c01f9
                                     if passphrase == None else 0)
Packit Service 6c01f9
                                  | (0 if expires else constants.create.NOEXPIRE)))
Packit Service 672cf4
        finally:
Packit Service 672cf4
            if util.is_a_string(passphrase):
Packit Service 672cf4
                self.pinentry_mode = old_pinentry_mode
Packit Service 672cf4
                if old_passphrase_cb:
Packit Service 672cf4
                    self.set_passphrase_cb(*old_passphrase_cb[1:])
Packit Service 672cf4
Packit Service 672cf4
        return self.op_genkey_result()
Packit Service 672cf4
Packit Service 672cf4
    def key_add_uid(self, key, uid):
Packit Service 672cf4
        """Add a UID
Packit Service 672cf4
Packit Service 672cf4
        Add the uid UID to the given KEY.  Calling this function is
Packit Service 672cf4
        only valid for the OpenPGP protocol.
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        GPGMEError   -- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        self.op_adduid(key, uid, 0)
Packit Service 672cf4
Packit Service 672cf4
    def key_revoke_uid(self, key, uid):
Packit Service 672cf4
        """Revoke a UID
Packit Service 672cf4
Packit Service 672cf4
        Revoke the uid UID from the given KEY.  Calling this function
Packit Service 672cf4
        is only valid for the OpenPGP protocol.
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        GPGMEError   -- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        self.op_revuid(key, uid, 0)
Packit Service 672cf4
Packit Service 672cf4
    def key_sign(self, key, uids=None, expires_in=False, local=False):
Packit Service 672cf4
        """Sign a key
Packit Service 672cf4
Packit Service 672cf4
        Sign a key with the current set of signing keys.  Calling this
Packit Service 672cf4
        function is only valid for the OpenPGP protocol.
Packit Service 672cf4
Packit Service 672cf4
        If UIDS is None (the default), then all UIDs are signed.  If
Packit Service 672cf4
        it is a string, then only the matching UID is signed.  If it
Packit Service 672cf4
        is a list of strings, then all matching UIDs are signed.  Note
Packit Service 672cf4
        that a case-sensitive exact string comparison is done.
Packit Service 672cf4
Packit Service 672cf4
        EXPIRES_IN specifies the expiration time of the signature in
Packit Service 672cf4
        seconds.  If EXPIRES_IN is False, the signature does not
Packit Service 672cf4
        expire.
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        uids         -- user ids to sign, see above (default: sign all)
Packit Service 672cf4
        expires_in   -- validity period of the signature in seconds
Packit Service 672cf4
                                               (default: do not expire)
Packit Service 672cf4
        local        -- create a local, non-exportable signature
Packit Service 672cf4
                                               (default: False)
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        GPGMEError   -- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        flags = 0
Packit Service 6c01f9
        if uids == None or util.is_a_string(uids):
Packit Service 6c01f9
            pass#through unchanged
Packit Service 672cf4
        else:
Packit Service 672cf4
            flags |= constants.keysign.LFSEP
Packit Service 672cf4
            uids = "\n".join(uids)
Packit Service 672cf4
Packit Service 672cf4
        if not expires_in:
Packit Service 672cf4
            flags |= constants.keysign.NOEXPIRE
Packit Service 672cf4
Packit Service 672cf4
        if local:
Packit Service 672cf4
            flags |= constants.keysign.LOCAL
Packit Service 672cf4
Packit Service 672cf4
        self.op_keysign(key, uids, expires_in, flags)
Packit Service 672cf4
Packit Service 672cf4
    def key_tofu_policy(self, key, policy):
Packit Service 672cf4
        """Set a keys' TOFU policy
Packit Service 672cf4
Packit Service 672cf4
        Set the TOFU policy associated with KEY to POLICY.  Calling
Packit Service 672cf4
        this function is only valid for the OpenPGP protocol.
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        GPGMEError   -- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        self.op_tofu_policy(key, policy)
Packit Service 672cf4
Packit Service 6c01f9
    def assuan_transact(self, command,
Packit Service 6c01f9
                        data_cb=None, inquire_cb=None, status_cb=None):
Packit Service 672cf4
        """Issue a raw assuan command
Packit Service 672cf4
Packit Service 672cf4
        This function can be used to issue a raw assuan command to the
Packit Service 672cf4
        engine.
Packit Service 672cf4
Packit Service 672cf4
        If command is a string or bytes, it will be used as-is.  If it
Packit Service 672cf4
        is an iterable of strings, it will be properly escaped and
Packit Service 672cf4
        joined into an well-formed assuan command.
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        data_cb		-- a callback receiving data lines
Packit Service 672cf4
        inquire_cb	-- a callback providing more information
Packit Service 672cf4
        status_cb	-- a callback receiving status lines
Packit Service 672cf4
Packit Service 672cf4
        Returns:
Packit Service 672cf4
        result		-- the result of command as GPGMEError
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        GPGMEError	-- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
Packit Service 672cf4
        if util.is_a_string(command) or isinstance(command, bytes):
Packit Service 672cf4
            cmd = command
Packit Service 672cf4
        else:
Packit Service 672cf4
            cmd = " ".join(util.percent_escape(f) for f in command)
Packit Service 672cf4
Packit Service 672cf4
        errptr = gpgme.new_gpgme_error_t_p()
Packit Service 672cf4
Packit Service 672cf4
        err = gpgme.gpgme_op_assuan_transact_ext(
Packit Service 6c01f9
            self.wrapped,
Packit Service 6c01f9
            cmd,
Packit Service 6c01f9
            (weakref.ref(self), data_cb) if data_cb else None,
Packit Service 6c01f9
            (weakref.ref(self), inquire_cb) if inquire_cb else None,
Packit Service 6c01f9
            (weakref.ref(self), status_cb) if status_cb else None,
Packit Service 6c01f9
            errptr)
Packit Service 672cf4
Packit Service 672cf4
        if self._callback_excinfo:
Packit Service 672cf4
            gpgme.gpg_raise_callback_exception(self)
Packit Service 672cf4
Packit Service 672cf4
        errorcheck(err)
Packit Service 672cf4
Packit Service 672cf4
        status = gpgme.gpgme_error_t_p_value(errptr)
Packit Service 672cf4
        gpgme.delete_gpgme_error_t_p(errptr)
Packit Service 672cf4
Packit Service 672cf4
        return GPGMEError(status) if status != 0 else None
Packit Service 672cf4
Packit Service 672cf4
    def interact(self, key, func, sink=None, flags=0, fnc_value=None):
Packit Service 672cf4
        """Interact with the engine
Packit Service 672cf4
Packit Service 672cf4
        This method can be used to edit keys and cards interactively.
Packit Service 672cf4
        KEY is the key to edit, FUNC is called repeatedly with two
Packit Service 672cf4
        unicode arguments, 'keyword' and 'args'.  See the GPGME manual
Packit Service 672cf4
        for details.
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        sink		-- if given, additional output is written here
Packit Service 672cf4
        flags		-- use constants.INTERACT_CARD to edit a card
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        GPGMEError	-- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 6c01f9
        if key == None:
Packit Service 672cf4
            raise ValueError("First argument cannot be None")
Packit Service 672cf4
Packit Service 6c01f9
        if sink == None:
Packit Service 672cf4
            sink = Data()
Packit Service 672cf4
Packit Service 672cf4
        if fnc_value:
Packit Service 672cf4
            opaquedata = (weakref.ref(self), func, fnc_value)
Packit Service 672cf4
        else:
Packit Service 672cf4
            opaquedata = (weakref.ref(self), func)
Packit Service 672cf4
Packit Service 6c01f9
        result = gpgme.gpgme_op_interact(self.wrapped, key, flags,
Packit Service 6c01f9
                                         opaquedata, sink)
Packit Service 672cf4
        if self._callback_excinfo:
Packit Service 672cf4
            gpgme.gpg_raise_callback_exception(self)
Packit Service 672cf4
        errorcheck(result)
Packit Service 672cf4
Packit Service 672cf4
    @property
Packit Service 672cf4
    def signers(self):
Packit Service 672cf4
        """Keys used for signing"""
Packit Service 672cf4
        return [self.signers_enum(i) for i in range(self.signers_count())]
Packit Service 672cf4
    @signers.setter
Packit Service 672cf4
    def signers(self, signers):
Packit Service 672cf4
        old = self.signers
Packit Service 672cf4
        self.signers_clear()
Packit Service 672cf4
        try:
Packit Service 672cf4
            for key in signers:
Packit Service 672cf4
                self.signers_add(key)
Packit Service 672cf4
        except:
Packit Service 672cf4
            self.signers = old
Packit Service 672cf4
            raise
Packit Service 672cf4
Packit Service 672cf4
    @property
Packit Service 672cf4
    def pinentry_mode(self):
Packit Service 672cf4
        """Pinentry mode"""
Packit Service 672cf4
        return self.get_pinentry_mode()
Packit Service 672cf4
    @pinentry_mode.setter
Packit Service 672cf4
    def pinentry_mode(self, value):
Packit Service 672cf4
        self.set_pinentry_mode(value)
Packit Service 672cf4
Packit Service 672cf4
    @property
Packit Service 672cf4
    def protocol(self):
Packit Service 672cf4
        """Protocol to use"""
Packit Service 672cf4
        return self.get_protocol()
Packit Service 672cf4
    @protocol.setter
Packit Service 672cf4
    def protocol(self, value):
Packit Service 672cf4
        errorcheck(gpgme.gpgme_engine_check_version(value))
Packit Service 672cf4
        self.set_protocol(value)
Packit Service 672cf4
Packit Service 672cf4
    @property
Packit Service 672cf4
    def home_dir(self):
Packit Service 672cf4
        """Engine's home directory"""
Packit Service 672cf4
        return self.engine_info.home_dir
Packit Service 672cf4
    @home_dir.setter
Packit Service 672cf4
    def home_dir(self, value):
Packit Service 672cf4
        self.set_engine_info(self.protocol, home_dir=value)
Packit Service 672cf4
Packit Service 672cf4
    _ctype = 'gpgme_ctx_t'
Packit Service 672cf4
    _cprefix = 'gpgme_'
Packit Service 672cf4
Packit Service 672cf4
    def _errorcheck(self, name):
Packit Service 672cf4
        """This function should list all functions returning gpgme_error_t"""
Packit Service 672cf4
        # The list of functions is created using:
Packit Service 672cf4
        #
Packit Service 672cf4
        # $ grep '^gpgme_error_t ' obj/lang/python/python3.5-gpg/gpgme.h \
Packit Service 6c01f9
        #   | grep -v _op_ | awk "/\(gpgme_ctx/ { printf (\"'%s',\\n\", \$2) } "
Packit Service 6c01f9
        return ((name.startswith('gpgme_op_')
Packit Service 6c01f9
                 and not name.endswith('_result'))
Packit Service 6c01f9
                or name in {
Packit Service 6c01f9
                    'gpgme_new',
Packit Service 6c01f9
                    'gpgme_set_ctx_flag',
Packit Service 6c01f9
                    'gpgme_set_protocol',
Packit Service 6c01f9
                    'gpgme_set_sub_protocol',
Packit Service 6c01f9
                    'gpgme_set_keylist_mode',
Packit Service 6c01f9
                    'gpgme_set_pinentry_mode',
Packit Service 6c01f9
                    'gpgme_set_locale',
Packit Service 6c01f9
                    'gpgme_ctx_set_engine_info',
Packit Service 6c01f9
                    'gpgme_signers_add',
Packit Service 6c01f9
                    'gpgme_sig_notation_add',
Packit Service 6c01f9
                    'gpgme_set_sender',
Packit Service 6c01f9
                    'gpgme_cancel',
Packit Service 6c01f9
                    'gpgme_cancel_async',
Packit Service 6c01f9
                    'gpgme_get_key',
Packit Service 672cf4
                })
Packit Service 672cf4
Packit Service 672cf4
    _boolean_properties = {'armor', 'textmode', 'offline'}
Packit Service 672cf4
Packit Service 672cf4
    def __del__(self):
Packit Service 672cf4
        if not gpgme:
Packit Service 672cf4
            # At interpreter shutdown, gpgme is set to NONE.
Packit Service 672cf4
            return
Packit Service 672cf4
Packit Service 672cf4
        self._free_passcb()
Packit Service 672cf4
        self._free_progresscb()
Packit Service 672cf4
        self._free_statuscb()
Packit Service 672cf4
        if self.own and self.wrapped and gpgme.gpgme_release:
Packit Service 672cf4
            gpgme.gpgme_release(self.wrapped)
Packit Service 672cf4
            self.wrapped = None
Packit Service 672cf4
Packit Service 672cf4
    # Implement the context manager protocol.
Packit Service 672cf4
    def __enter__(self):
Packit Service 672cf4
        return self
Packit Service 672cf4
    def __exit__(self, type, value, tb):
Packit Service 672cf4
        self.__del__()
Packit Service 672cf4
Packit Service 672cf4
    def op_keylist_all(self, *args, **kwargs):
Packit Service 672cf4
        self.op_keylist_start(*args, **kwargs)
Packit Service 672cf4
        key = self.op_keylist_next()
Packit Service 672cf4
        while key:
Packit Service 672cf4
            yield key
Packit Service 672cf4
            key = self.op_keylist_next()
Packit Service 672cf4
        self.op_keylist_end()
Packit Service 672cf4
Packit Service 672cf4
    def op_keylist_next(self):
Packit Service 672cf4
        """Returns the next key in the list created
Packit Service 672cf4
        by a call to op_keylist_start().  The object returned
Packit Service 672cf4
        is of type Key."""
Packit Service 672cf4
        ptr = gpgme.new_gpgme_key_t_p()
Packit Service 672cf4
        try:
Packit Service 672cf4
            errorcheck(gpgme.gpgme_op_keylist_next(self.wrapped, ptr))
Packit Service 672cf4
            key = gpgme.gpgme_key_t_p_value(ptr)
Packit Service 672cf4
        except errors.GPGMEError as excp:
Packit Service 672cf4
            key = None
Packit Service 672cf4
            if excp.getcode() != errors.EOF:
Packit Service 672cf4
                raise excp
Packit Service 672cf4
        gpgme.delete_gpgme_key_t_p(ptr)
Packit Service 672cf4
        if key:
Packit Service 672cf4
            key.__del__ = lambda self: gpgme.gpgme_key_unref(self)
Packit Service 672cf4
            return key
Packit Service 672cf4
Packit Service 672cf4
    def get_key(self, fpr, secret=False):
Packit Service 672cf4
        """Get a key given a fingerprint
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        secret		-- to request a secret key
Packit Service 672cf4
Packit Service 672cf4
        Returns:
Packit Service 672cf4
                        -- the matching key
Packit Service 672cf4
Packit Service 672cf4
        Raises:
Packit Service 672cf4
        KeyError	-- if the key was not found
Packit Service 672cf4
        GPGMEError	-- as signaled by the underlying library
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        ptr = gpgme.new_gpgme_key_t_p()
Packit Service 672cf4
Packit Service 672cf4
        try:
Packit Service 672cf4
            errorcheck(gpgme.gpgme_get_key(self.wrapped, fpr, ptr, secret))
Packit Service 672cf4
        except errors.GPGMEError as e:
Packit Service 672cf4
            if e.getcode() == errors.EOF:
Packit Service 672cf4
                raise errors.KeyNotFound(fpr)
Packit Service 672cf4
            raise e
Packit Service 672cf4
Packit Service 672cf4
        key = gpgme.gpgme_key_t_p_value(ptr)
Packit Service 672cf4
        gpgme.delete_gpgme_key_t_p(ptr)
Packit Service 672cf4
        assert key
Packit Service 672cf4
        key.__del__ = lambda self: gpgme.gpgme_key_unref(self)
Packit Service 672cf4
        return key
Packit Service 672cf4
Packit Service 672cf4
    def op_trustlist_all(self, *args, **kwargs):
Packit Service 672cf4
        self.op_trustlist_start(*args, **kwargs)
Packit Service 672cf4
        trust = self.op_trustlist_next()
Packit Service 672cf4
        while trust:
Packit Service 672cf4
            yield trust
Packit Service 672cf4
            trust = self.op_trustlist_next()
Packit Service 672cf4
        self.op_trustlist_end()
Packit Service 672cf4
Packit Service 672cf4
    def op_trustlist_next(self):
Packit Service 672cf4
        """Returns the next trust item in the list created
Packit Service 672cf4
        by a call to op_trustlist_start().  The object returned
Packit Service 672cf4
        is of type TrustItem."""
Packit Service 672cf4
        ptr = gpgme.new_gpgme_trust_item_t_p()
Packit Service 672cf4
        try:
Packit Service 672cf4
            errorcheck(gpgme.gpgme_op_trustlist_next(self.wrapped, ptr))
Packit Service 672cf4
            trust = gpgme.gpgme_trust_item_t_p_value(ptr)
Packit Service 672cf4
        except errors.GPGMEError as excp:
Packit Service 672cf4
            trust = None
Packit Service 672cf4
            if excp.getcode() != errors.EOF:
Packit Service 672cf4
                raise
Packit Service 672cf4
        gpgme.delete_gpgme_trust_item_t_p(ptr)
Packit Service 672cf4
        return trust
Packit Service 672cf4
Packit Service 672cf4
    def set_passphrase_cb(self, func, hook=None):
Packit Service 672cf4
        """Sets the passphrase callback to the function specified by func.
Packit Service 672cf4
Packit Service 672cf4
        When the system needs a passphrase, it will call func with three args:
Packit Service 672cf4
        hint, a string describing the key it needs the passphrase for;
Packit Service 672cf4
        desc, a string describing the passphrase it needs;
Packit Service 672cf4
        prev_bad, a boolean equal True if this is a call made after
Packit Service 672cf4
        unsuccessful previous attempt.
Packit Service 672cf4
Packit Service 672cf4
        If hook has a value other than None it will be passed into the func
Packit Service 672cf4
        as a forth argument.
Packit Service 672cf4
Packit Service 672cf4
        Please see the GPGME manual for more information.
Packit Service 672cf4
        """
Packit Service 6c01f9
        if func == None:
Packit Service 672cf4
            hookdata = None
Packit Service 672cf4
        else:
Packit Service 6c01f9
            if hook == None:
Packit Service 672cf4
                hookdata = (weakref.ref(self), func)
Packit Service 672cf4
            else:
Packit Service 672cf4
                hookdata = (weakref.ref(self), func, hook)
Packit Service 672cf4
        gpgme.gpg_set_passphrase_cb(self, hookdata)
Packit Service 672cf4
Packit Service 672cf4
    def _free_passcb(self):
Packit Service 672cf4
        if gpgme.gpg_set_passphrase_cb:
Packit Service 672cf4
            self.set_passphrase_cb(None)
Packit Service 672cf4
Packit Service 672cf4
    def set_progress_cb(self, func, hook=None):
Packit Service 672cf4
        """Sets the progress meter callback to the function specified by FUNC.
Packit Service 672cf4
        If FUNC is None, the callback will be cleared.
Packit Service 672cf4
Packit Service 672cf4
        This function will be called to provide an interactive update
Packit Service 672cf4
        of the system's progress.  The function will be called with
Packit Service 672cf4
        three arguments, type, total, and current.  If HOOK is not
Packit Service 672cf4
        None, it will be supplied as fourth argument.
Packit Service 672cf4
Packit Service 672cf4
        Please see the GPGME manual for more information.
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 6c01f9
        if func == None:
Packit Service 672cf4
            hookdata = None
Packit Service 672cf4
        else:
Packit Service 6c01f9
            if hook == None:
Packit Service 672cf4
                hookdata = (weakref.ref(self), func)
Packit Service 672cf4
            else:
Packit Service 672cf4
                hookdata = (weakref.ref(self), func, hook)
Packit Service 672cf4
        gpgme.gpg_set_progress_cb(self, hookdata)
Packit Service 672cf4
Packit Service 672cf4
    def _free_progresscb(self):
Packit Service 672cf4
        if gpgme.gpg_set_progress_cb:
Packit Service 672cf4
            self.set_progress_cb(None)
Packit Service 672cf4
Packit Service 672cf4
    def set_status_cb(self, func, hook=None):
Packit Service 672cf4
        """Sets the status callback to the function specified by FUNC.  If
Packit Service 672cf4
        FUNC is None, the callback will be cleared.
Packit Service 672cf4
Packit Service 672cf4
        The function will be called with two arguments, keyword and
Packit Service 672cf4
        args.  If HOOK is not None, it will be supplied as third
Packit Service 672cf4
        argument.
Packit Service 672cf4
Packit Service 672cf4
        Please see the GPGME manual for more information.
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 6c01f9
        if func == None:
Packit Service 672cf4
            hookdata = None
Packit Service 672cf4
        else:
Packit Service 6c01f9
            if hook == None:
Packit Service 672cf4
                hookdata = (weakref.ref(self), func)
Packit Service 672cf4
            else:
Packit Service 672cf4
                hookdata = (weakref.ref(self), func, hook)
Packit Service 672cf4
        gpgme.gpg_set_status_cb(self, hookdata)
Packit Service 672cf4
Packit Service 672cf4
    def _free_statuscb(self):
Packit Service 672cf4
        if gpgme.gpg_set_status_cb:
Packit Service 672cf4
            self.set_status_cb(None)
Packit Service 672cf4
Packit Service 672cf4
    @property
Packit Service 672cf4
    def engine_info(self):
Packit Service 672cf4
        """Configuration of the engine currently in use"""
Packit Service 672cf4
        p = self.protocol
Packit Service 672cf4
        infos = [i for i in self.get_engine_info() if i.protocol == p]
Packit Service 672cf4
        assert len(infos) == 1
Packit Service 672cf4
        return infos[0]
Packit Service 672cf4
Packit Service 672cf4
    def get_engine_info(self):
Packit Service 672cf4
        """Get engine configuration
Packit Service 672cf4
Packit Service 672cf4
        Returns information about all configured and installed
Packit Service 672cf4
        engines.
Packit Service 672cf4
Packit Service 672cf4
        Returns:
Packit Service 672cf4
        infos		-- a list of engine infos
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        return gpgme.gpgme_ctx_get_engine_info(self.wrapped)
Packit Service 672cf4
Packit Service 672cf4
    def set_engine_info(self, proto, file_name=None, home_dir=None):
Packit Service 672cf4
        """Change engine configuration
Packit Service 672cf4
Packit Service 672cf4
        Changes the configuration of the crypto engine implementing
Packit Service 672cf4
        the protocol 'proto' for the context.
Packit Service 672cf4
Packit Service 672cf4
        Keyword arguments:
Packit Service 672cf4
        file_name	-- engine program file name (unchanged if None)
Packit Service 672cf4
        home_dir	-- configuration directory (unchanged if None)
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        self.ctx_set_engine_info(proto, file_name, home_dir)
Packit Service 672cf4
Packit Service 672cf4
    def wait(self, hang):
Packit Service 672cf4
        """Wait for asynchronous call to finish. Wait forever if hang is True.
Packit Service 672cf4
        Raises an exception on errors.
Packit Service 672cf4
Packit Service 672cf4
        Please read the GPGME manual for more information.
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        ptr = gpgme.new_gpgme_error_t_p()
Packit Service 672cf4
        gpgme.gpgme_wait(self.wrapped, ptr, hang)
Packit Service 672cf4
        status = gpgme.gpgme_error_t_p_value(ptr)
Packit Service 672cf4
        gpgme.delete_gpgme_error_t_p(ptr)
Packit Service 672cf4
        errorcheck(status)
Packit Service 672cf4
Packit Service 672cf4
    def op_edit(self, key, func, fnc_value, out):
Packit Service 672cf4
        """Start key editing using supplied callback function
Packit Service 672cf4
Packit Service 672cf4
        Note: This interface is deprecated and will be removed with
Packit Service 672cf4
        GPGME 1.8.  Please use .interact instead.  Furthermore, we
Packit Service 672cf4
        implement this using gpgme_op_interact, so callbacks will get
Packit Service 672cf4
        called with string keywords instead of numeric status
Packit Service 672cf4
        messages.  Code that is using constants.STATUS_X or
Packit Service 672cf4
        constants.status.X will continue to work, whereas code using
Packit Service 672cf4
        magic numbers will break as a result.
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 6c01f9
        warnings.warn("Call to deprecated method op_edit.",
Packit Service 6c01f9
                      category=DeprecationWarning)
Packit Service 672cf4
        return self.interact(key, func, sink=out, fnc_value=fnc_value)
Packit Service 672cf4
Packit Service 672cf4
Packit Service 672cf4
class Data(GpgmeWrapper):
Packit Service 672cf4
    """Data buffer
Packit Service 672cf4
Packit Service 672cf4
    A lot of data has to be exchanged between the user and the crypto
Packit Service 672cf4
    engine, like plaintext messages, ciphertext, signatures and
Packit Service 672cf4
    information about the keys.  The technical details about
Packit Service 672cf4
    exchanging the data information are completely abstracted by
Packit Service 672cf4
    GPGME.  The user provides and receives the data via `gpgme_data_t'
Packit Service 672cf4
    objects, regardless of the communication protocol between GPGME
Packit Service 672cf4
    and the crypto engine in use.
Packit Service 672cf4
Packit Service 672cf4
    This Data class is the implementation of the GpgmeData objects.
Packit Service 672cf4
Packit Service 672cf4
    Please see the information about __init__ for instantiation.
Packit Service 672cf4
Packit Service 672cf4
    """
Packit Service 672cf4
Packit Service 672cf4
    _ctype = 'gpgme_data_t'
Packit Service 672cf4
    _cprefix = 'gpgme_data_'
Packit Service 672cf4
Packit Service 672cf4
    def _errorcheck(self, name):
Packit Service 672cf4
        """This function should list all functions returning gpgme_error_t"""
Packit Service 672cf4
        # This list is compiled using
Packit Service 672cf4
        #
Packit Service 672cf4
        # $ grep -v '^gpgme_error_t ' obj/lang/python/python3.5-gpg/gpgme.h \
Packit Service 6c01f9
        #   | awk "/\(gpgme_data_t/ { printf (\"'%s',\\n\", \$2) } " | sed "s/'\\*/'/"
Packit Service 672cf4
        return name not in {
Packit Service 672cf4
            'gpgme_data_read',
Packit Service 672cf4
            'gpgme_data_write',
Packit Service 672cf4
            'gpgme_data_seek',
Packit Service 672cf4
            'gpgme_data_release',
Packit Service 672cf4
            'gpgme_data_release_and_get_mem',
Packit Service 672cf4
            'gpgme_data_get_encoding',
Packit Service 672cf4
            'gpgme_data_get_file_name',
Packit Service 672cf4
            'gpgme_data_identify',
Packit Service 672cf4
        }
Packit Service 672cf4
Packit Service 6c01f9
    def __init__(self, string=None, file=None, offset=None,
Packit Service 6c01f9
                 length=None, cbs=None, copy=True):
Packit Service 672cf4
        """Initialize a new gpgme_data_t object.
Packit Service 672cf4
Packit Service 672cf4
        If no args are specified, make it an empty object.
Packit Service 672cf4
Packit Service 672cf4
        If string alone is specified, initialize it with the data
Packit Service 672cf4
        contained there.
Packit Service 672cf4
Packit Service 672cf4
        If file, offset, and length are all specified, file must
Packit Service 672cf4
        be either a filename or a file-like object, and the object
Packit Service 672cf4
        will be initialized by reading the specified chunk from the file.
Packit Service 672cf4
Packit Service 672cf4
        If cbs is specified, it MUST be a tuple of the form:
Packit Service 672cf4
Packit Service 672cf4
        (read_cb, write_cb, seek_cb, release_cb[, hook])
Packit Service 672cf4
Packit Service 672cf4
        where the first four items are functions implementing reading,
Packit Service 672cf4
        writing, seeking the data, and releasing any resources once
Packit Service 672cf4
        the data object is deallocated.  The functions must match the
Packit Service 672cf4
        following prototypes:
Packit Service 672cf4
Packit Service 672cf4
            def read(amount, hook=None):
Packit Service 672cf4
                return 
Packit Service 672cf4
Packit Service 672cf4
            def write(data, hook=None):
Packit Service 672cf4
                return <the number of bytes written>
Packit Service 672cf4
Packit Service 672cf4
            def seek(offset, whence, hook=None):
Packit Service 672cf4
                return <the new file position>
Packit Service 672cf4
Packit Service 672cf4
            def release(hook=None):
Packit Service 672cf4
                <return value and exceptions are ignored>
Packit Service 672cf4
Packit Service 672cf4
        The functions may be bound methods.  In that case, you can
Packit Service 672cf4
        simply use the 'self' reference instead of using a hook.
Packit Service 672cf4
Packit Service 672cf4
        If file is specified without any other arguments, then
Packit Service 672cf4
        it must be a filename, and the object will be initialized from
Packit Service 672cf4
        that file.
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        super(Data, self).__init__(None)
Packit Service 672cf4
        self.data_cbs = None
Packit Service 672cf4
Packit Service 6c01f9
        if cbs != None:
Packit Service 672cf4
            self.new_from_cbs(*cbs)
Packit Service 6c01f9
        elif string != None:
Packit Service 672cf4
            self.new_from_mem(string, copy)
Packit Service 6c01f9
        elif file != None and offset != None and length != None:
Packit Service 672cf4
            self.new_from_filepart(file, offset, length)
Packit Service 6c01f9
        elif file != None:
Packit Service 672cf4
            if util.is_a_string(file):
Packit Service 672cf4
                self.new_from_file(file, copy)
Packit Service 672cf4
            else:
Packit Service 672cf4
                self.new_from_fd(file)
Packit Service 672cf4
        else:
Packit Service 672cf4
            self.new()
Packit Service 672cf4
Packit Service 672cf4
    def __del__(self):
Packit Service 672cf4
        if not gpgme:
Packit Service 672cf4
            # At interpreter shutdown, gpgme is set to NONE.
Packit Service 672cf4
            return
Packit Service 672cf4
Packit Service 6c01f9
        if self.wrapped != None and gpgme.gpgme_data_release:
Packit Service 672cf4
            gpgme.gpgme_data_release(self.wrapped)
Packit Service 672cf4
            if self._callback_excinfo:
Packit Service 672cf4
                gpgme.gpg_raise_callback_exception(self)
Packit Service 672cf4
            self.wrapped = None
Packit Service 672cf4
        self._free_datacbs()
Packit Service 672cf4
Packit Service 672cf4
    # Implement the context manager protocol.
Packit Service 672cf4
    def __enter__(self):
Packit Service 672cf4
        return self
Packit Service 672cf4
    def __exit__(self, type, value, tb):
Packit Service 672cf4
        self.__del__()
Packit Service 672cf4
Packit Service 672cf4
    def _free_datacbs(self):
Packit Service 672cf4
        self._data_cbs = None
Packit Service 672cf4
Packit Service 672cf4
    def new(self):
Packit Service 672cf4
        tmp = gpgme.new_gpgme_data_t_p()
Packit Service 672cf4
        errorcheck(gpgme.gpgme_data_new(tmp))
Packit Service 672cf4
        self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
Packit Service 672cf4
        gpgme.delete_gpgme_data_t_p(tmp)
Packit Service 672cf4
Packit Service 672cf4
    def new_from_mem(self, string, copy=True):
Packit Service 672cf4
        tmp = gpgme.new_gpgme_data_t_p()
Packit Service 6c01f9
        errorcheck(gpgme.gpgme_data_new_from_mem(tmp,string,len(string),copy))
Packit Service 672cf4
        self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
Packit Service 672cf4
        gpgme.delete_gpgme_data_t_p(tmp)
Packit Service 672cf4
Packit Service 672cf4
    def new_from_file(self, filename, copy=True):
Packit Service 672cf4
        tmp = gpgme.new_gpgme_data_t_p()
Packit Service 672cf4
        try:
Packit Service 672cf4
            errorcheck(gpgme.gpgme_data_new_from_file(tmp, filename, copy))
Packit Service 672cf4
        except errors.GPGMEError as e:
Packit Service 672cf4
            if e.getcode() == errors.INV_VALUE and not copy:
Packit Service 672cf4
                raise ValueError("delayed reads are not yet supported")
Packit Service 672cf4
            else:
Packit Service 672cf4
                raise e
Packit Service 672cf4
        self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
Packit Service 672cf4
        gpgme.delete_gpgme_data_t_p(tmp)
Packit Service 672cf4
Packit Service 672cf4
    def new_from_cbs(self, read_cb, write_cb, seek_cb, release_cb, hook=None):
Packit Service 672cf4
        tmp = gpgme.new_gpgme_data_t_p()
Packit Service 6c01f9
        if hook != None:
Packit Service 6c01f9
            hookdata = (weakref.ref(self),
Packit Service 6c01f9
                        read_cb, write_cb, seek_cb, release_cb, hook)
Packit Service 672cf4
        else:
Packit Service 6c01f9
            hookdata = (weakref.ref(self),
Packit Service 6c01f9
                        read_cb, write_cb, seek_cb, release_cb)
Packit Service 672cf4
        gpgme.gpg_data_new_from_cbs(self, hookdata, tmp)
Packit Service 672cf4
        self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
Packit Service 672cf4
        gpgme.delete_gpgme_data_t_p(tmp)
Packit Service 672cf4
Packit Service 672cf4
    def new_from_filepart(self, file, offset, length):
Packit Service 672cf4
        """This wraps the GPGME gpgme_data_new_from_filepart() function.
Packit Service 672cf4
        The argument "file" may be:
Packit Service 672cf4
Packit Service 672cf4
        * a string specifying a file name, or
Packit Service 672cf4
        * a file-like object supporting the fileno() and the mode attribute.
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
Packit Service 672cf4
        tmp = gpgme.new_gpgme_data_t_p()
Packit Service 672cf4
        filename = None
Packit Service 672cf4
        fp = None
Packit Service 672cf4
Packit Service 672cf4
        if util.is_a_string(file):
Packit Service 672cf4
            filename = file
Packit Service 672cf4
        else:
Packit Service 672cf4
            fp = gpgme.fdopen(file.fileno(), file.mode)
Packit Service 6c01f9
            if fp == None:
Packit Service 6c01f9
                raise ValueError("Failed to open file from %s arg %s" % \
Packit Service 6c01f9
                      (str(type(file)), str(file)))
Packit Service 672cf4
Packit Service 6c01f9
        errorcheck(gpgme.gpgme_data_new_from_filepart(tmp, filename, fp,
Packit Service 6c01f9
                                                      offset, length))
Packit Service 672cf4
        self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
Packit Service 672cf4
        gpgme.delete_gpgme_data_t_p(tmp)
Packit Service 672cf4
Packit Service 672cf4
    def new_from_fd(self, file):
Packit Service 672cf4
        """This wraps the GPGME gpgme_data_new_from_fd() function.  The
Packit Service 672cf4
        argument "file" must be a file-like object, supporting the
Packit Service 672cf4
        fileno() method.
Packit Service 672cf4
Packit Service 672cf4
        """
Packit Service 672cf4
        tmp = gpgme.new_gpgme_data_t_p()
Packit Service 672cf4
        errorcheck(gpgme.gpgme_data_new_from_fd(tmp, file.fileno()))
Packit Service 672cf4
        self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
Packit Service 672cf4
        gpgme.delete_gpgme_data_t_p(tmp)
Packit Service 672cf4
Packit Service 672cf4
    def new_from_stream(self, file):
Packit Service 672cf4
        """This wrap around gpgme_data_new_from_stream is an alias for
Packit Service 6c01f9
        new_from_fd() method since in python there's not difference
Packit Service 6c01f9
        between file stream and file descriptor"""
Packit Service 672cf4
        self.new_from_fd(file)
Packit Service 672cf4
Packit Service 672cf4
    def write(self, buffer):
Packit Service 672cf4
        """Write buffer given as string or bytes.
Packit Service 672cf4
Packit Service 672cf4
        If a string is given, it is implicitly encoded using UTF-8."""
Packit Service 672cf4
        written = gpgme.gpgme_data_write(self.wrapped, buffer)
Packit Service 672cf4
        if written < 0:
Packit Service 672cf4
            if self._callback_excinfo:
Packit Service 672cf4
                gpgme.gpg_raise_callback_exception(self)
Packit Service 672cf4
            else:
Packit Service 672cf4
                raise GPGMEError.fromSyserror()
Packit Service 672cf4
        return written
Packit Service 672cf4
Packit Service 6c01f9
    def read(self, size = -1):
Packit Service 672cf4
        """Read at most size bytes, returned as bytes.
Packit Service 672cf4
Packit Service 672cf4
        If the size argument is negative or omitted, read until EOF is reached.
Packit Service 672cf4
Packit Service 672cf4
        Returns the data read, or the empty string if there was no data
Packit Service 672cf4
        to read before EOF was reached."""
Packit Service 672cf4
Packit Service 672cf4
        if size == 0:
Packit Service 672cf4
            return ''
Packit Service 672cf4
Packit Service 672cf4
        if size > 0:
Packit Service 672cf4
            try:
Packit Service 672cf4
                result = gpgme.gpgme_data_read(self.wrapped, size)
Packit Service 672cf4
            except:
Packit Service 672cf4
                if self._callback_excinfo:
Packit Service 672cf4
                    gpgme.gpg_raise_callback_exception(self)
Packit Service 672cf4
                else:
Packit Service 672cf4
                    raise
Packit Service 672cf4
            return result
Packit Service 672cf4
        else:
Packit Service 672cf4
            chunks = []
Packit Service 672cf4
            while True:
Packit Service 672cf4
                try:
Packit Service 672cf4
                    result = gpgme.gpgme_data_read(self.wrapped, 4096)
Packit Service 672cf4
                except:
Packit Service 672cf4
                    if self._callback_excinfo:
Packit Service 672cf4
                        gpgme.gpg_raise_callback_exception(self)
Packit Service 672cf4
                    else:
Packit Service 672cf4
                        raise
Packit Service 672cf4
                if len(result) == 0:
Packit Service 672cf4
                    break
Packit Service 672cf4
                chunks.append(result)
Packit Service 672cf4
            return b''.join(chunks)
Packit Service 672cf4
Packit Service 672cf4
def pubkey_algo_string(subkey):
Packit Service 672cf4
    """Return short algorithm string
Packit Service 672cf4
Packit Service 672cf4
    Return a public key algorithm string (e.g. "rsa2048") for a given
Packit Service 672cf4
    SUBKEY.
Packit Service 672cf4
Packit Service 672cf4
    Returns:
Packit Service 672cf4
    algo      - a string
Packit Service 672cf4
Packit Service 672cf4
    """
Packit Service 672cf4
    return gpgme.gpgme_pubkey_algo_string(subkey)
Packit Service 672cf4
Packit Service 672cf4
def pubkey_algo_name(algo):
Packit Service 672cf4
    """Return name of public key algorithm
Packit Service 672cf4
Packit Service 672cf4
    Return the name of the public key algorithm for a given numeric
Packit Service 672cf4
    algorithm id ALGO (cf. RFC4880).
Packit Service 672cf4
Packit Service 672cf4
    Returns:
Packit Service 672cf4
    algo      - a string
Packit Service 672cf4
Packit Service 672cf4
    """
Packit Service 672cf4
    return gpgme.gpgme_pubkey_algo_name(algo)
Packit Service 672cf4
Packit Service 672cf4
def hash_algo_name(algo):
Packit Service 672cf4
    """Return name of hash algorithm
Packit Service 672cf4
Packit Service 672cf4
    Return the name of the hash algorithm for a given numeric
Packit Service 672cf4
    algorithm id ALGO (cf. RFC4880).
Packit Service 672cf4
Packit Service 672cf4
    Returns:
Packit Service 672cf4
    algo      - a string
Packit Service 672cf4
Packit Service 672cf4
    """
Packit Service 672cf4
    return gpgme.gpgme_hash_algo_name(algo)
Packit Service 672cf4
Packit Service 672cf4
def get_protocol_name(proto):
Packit Service 672cf4
    """Get protocol description
Packit Service 672cf4
Packit Service 672cf4
    Get the string describing protocol PROTO.
Packit Service 672cf4
Packit Service 672cf4
    Returns:
Packit Service 672cf4
    proto     - a string
Packit Service 672cf4
Packit Service 672cf4
    """
Packit Service 672cf4
    return gpgme.gpgme_get_protocol_name(proto)
Packit Service 672cf4
Packit Service 672cf4
def addrspec_from_uid(uid):
Packit Service 672cf4
    """Return the address spec
Packit Service 672cf4
Packit Service 672cf4
    Return the addr-spec (cf. RFC2822 section 4.3) from a user id UID.
Packit Service 672cf4
Packit Service 672cf4
    Returns:
Packit Service 672cf4
    addr_spec - a string
Packit Service 672cf4
Packit Service 672cf4
    """
Packit Service 672cf4
    return gpgme.gpgme_addrspec_from_uid(uid)
Packit Service 672cf4
Packit Service 672cf4
def check_version(version=None):
Packit Service 672cf4
    return gpgme.gpgme_check_version(version)
Packit Service 672cf4
Packit Service 672cf4
# check_version also makes sure that several subsystems are properly
Packit Service 672cf4
# initialized, and it must be run at least once before invoking any
Packit Service 672cf4
# other function.  We do it here so that the user does not have to do
Packit Service 672cf4
# it unless she really wants to check for a certain version.
Packit Service 672cf4
check_version()
Packit Service 672cf4
Packit Service 6c01f9
def engine_check_version (proto):
Packit Service 672cf4
    try:
Packit Service 672cf4
        errorcheck(gpgme.gpgme_engine_check_version(proto))
Packit Service 672cf4
        return True
Packit Service 672cf4
    except errors.GPGMEError:
Packit Service 672cf4
        return False
Packit Service 672cf4
Packit Service 672cf4
def get_engine_info():
Packit Service 672cf4
    ptr = gpgme.new_gpgme_engine_info_t_p()
Packit Service 672cf4
    try:
Packit Service 672cf4
        errorcheck(gpgme.gpgme_get_engine_info(ptr))
Packit Service 672cf4
        info = gpgme.gpgme_engine_info_t_p_value(ptr)
Packit Service 672cf4
    except errors.GPGMEError:
Packit Service 672cf4
        info = None
Packit Service 672cf4
    gpgme.delete_gpgme_engine_info_t_p(ptr)
Packit Service 672cf4
    return info
Packit Service 672cf4
Packit Service 672cf4
def set_engine_info(proto, file_name, home_dir=None):
Packit Service 672cf4
    """Changes the default configuration of the crypto engine implementing
Packit Service 672cf4
    the protocol 'proto'. 'file_name' is the file name of
Packit Service 672cf4
    the executable program implementing this protocol. 'home_dir' is the
Packit Service 672cf4
    directory name of the configuration directory (engine's default is
Packit Service 672cf4
    used if omitted)."""
Packit Service 672cf4
    errorcheck(gpgme.gpgme_set_engine_info(proto, file_name, home_dir))
Packit Service 672cf4
Packit Service 672cf4
def set_locale(category, value):
Packit Service 672cf4
    """Sets the default locale used by contexts"""
Packit Service 672cf4
    errorcheck(gpgme.gpgme_set_locale(None, category, value))
Packit Service 672cf4
Packit Service 672cf4
def wait(hang):
Packit Service 672cf4
    """Wait for asynchronous call on any Context  to finish.
Packit Service 672cf4
    Wait forever if hang is True.
Packit Service 672cf4
Packit Service 672cf4
    For finished anynch calls it returns a tuple (status, context):
Packit Service 672cf4
        status  - status return by asnynchronous call.
Packit Service 672cf4
        context - context which caused this call to return.
Packit Service 672cf4
Packit Service 672cf4
    Please read the GPGME manual of more information."""
Packit Service 672cf4
    ptr = gpgme.new_gpgme_error_t_p()
Packit Service 672cf4
    context = gpgme.gpgme_wait(None, ptr, hang)
Packit Service 672cf4
    status = gpgme.gpgme_error_t_p_value(ptr)
Packit Service 672cf4
    gpgme.delete_gpgme_error_t_p(ptr)
Packit Service 6c01f9
    if context == None:
Packit Service 672cf4
        errorcheck(status)
Packit Service 672cf4
    else:
Packit Service 672cf4
        context = Context(context)
Packit Service 672cf4
    return (status, context)