Page MenuHome GnuPG

No OneTemporary

diff --git a/helpers.c b/helpers.c
index 5b13fee..bc8aed4 100644
--- a/helpers.c
+++ b/helpers.c
@@ -1,1109 +1,1117 @@
/*
# Copyright (C) 2016 g10 Code GmbH
# Copyright (C) 2004 Igor Belyi <belyi@users.sourceforge.net>
# Copyright (C) 2002 John Goerzen <jgoerzen@complete.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <assert.h>
#include <stdio.h>
#include <gpgme.h>
#include <stdlib.h>
#include <string.h>
#include "Python.h"
#include "helpers.h"
#include "private.h"
/* Flag specifying whether this is an in-tree build. */
int pyme_in_tree_build =
#if IN_TREE_BUILD
1
#else
0
#endif
;
static PyObject *GPGMEError = NULL;
void _pyme_exception_init(void) {
if (GPGMEError == NULL) {
PyObject *errors;
PyObject *from_list = PyList_New(0);
errors = PyImport_ImportModuleLevel("errors", PyEval_GetGlobals(),
PyEval_GetLocals(), from_list, 1);
Py_XDECREF(from_list);
if (errors) {
GPGMEError=PyDict_GetItemString(PyModule_GetDict(errors), "GPGMEError");
Py_XINCREF(GPGMEError);
}
}
}
static PyObject *
_pyme_raise_exception(gpgme_error_t err)
{
PyObject *e;
_pyme_exception_init();
if (GPGMEError == NULL)
return PyErr_Format(PyExc_RuntimeError, "Got gpgme_error_t %d", err);
e = PyObject_CallFunction(GPGMEError, "l", (long) err);
if (e == NULL)
return NULL;
PyErr_SetObject(GPGMEError, e);
Py_DECREF(e);
return NULL; /* raise */
}
gpgme_error_t _pyme_exception2code(void) {
gpgme_error_t err_status = gpg_error(GPG_ERR_GENERAL);
if (GPGMEError && PyErr_ExceptionMatches(GPGMEError)) {
PyObject *type = 0, *value = 0, *traceback = 0;
PyObject *error = 0;
PyErr_Fetch(&type, &value, &traceback);
PyErr_NormalizeException(&type, &value, &traceback);
error = PyObject_GetAttrString(value, "error");
err_status = PyLong_AsLong(error);
Py_DECREF(error);
PyErr_Restore(type, value, traceback);
}
return err_status;
}
/* Exception support for callbacks. */
#define EXCINFO "_callback_excinfo"
static void _pyme_stash_callback_exception(PyObject *weak_self)
{
PyObject *self, *ptype, *pvalue, *ptraceback, *excinfo;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
excinfo = PyTuple_New(3);
PyTuple_SetItem(excinfo, 0, ptype);
if (pvalue)
PyTuple_SetItem(excinfo, 1, pvalue);
else {
Py_INCREF(Py_None);
PyTuple_SetItem(excinfo, 1, Py_None);
}
if (ptraceback)
PyTuple_SetItem(excinfo, 2, ptraceback);
else {
Py_INCREF(Py_None);
PyTuple_SetItem(excinfo, 2, Py_None);
}
self = PyWeakref_GetObject(weak_self);
/* self only has a borrowed reference. */
if (self == Py_None) {
/* This should not happen, as even if we're called from the data
release callback triggered from the wrappers destructor, the
object is still alive and hence the weak reference still refers
to the object. However, in case this ever changes, not seeing
any exceptions is worse than having a little extra code, so
here we go. */
fprintf(stderr,
"Error occurred in callback, but the wrapper object "
"has been deallocated.\n");
PyErr_Restore(ptype, pvalue, ptraceback);
PyErr_Print();
}
else
PyObject_SetAttrString(self, EXCINFO, excinfo);
Py_DECREF(excinfo);
}
PyObject *pyme_raise_callback_exception(PyObject *self)
{
PyObject *ptype, *pvalue, *ptraceback, *excinfo;
if (! PyObject_HasAttrString(self, EXCINFO))
goto leave;
excinfo = PyObject_GetAttrString(self, EXCINFO);
if (! PyTuple_Check(excinfo))
{
Py_DECREF(excinfo);
goto leave;
}
ptype = PyTuple_GetItem(excinfo, 0);
Py_INCREF(excinfo);
pvalue = PyTuple_GetItem(excinfo, 1);
if (pvalue == Py_None)
pvalue = NULL;
else
Py_INCREF(pvalue);
ptraceback = PyTuple_GetItem(excinfo, 2);
if (ptraceback == Py_None)
ptraceback = NULL;
else
Py_INCREF(ptraceback);
/* We now have references for the extracted items. */
Py_DECREF(excinfo);
/* Clear the exception information. It is important to do this
before setting the error, because setting the attribute may
execute python code, and the runtime system raises a SystemError
if an exception is set but values are returned. */
Py_INCREF(Py_None);
PyObject_SetAttrString(self, EXCINFO, Py_None);
/* Restore exception. */
PyErr_Restore(ptype, pvalue, ptraceback);
return NULL; /* Raise exception. */
leave:
Py_INCREF(Py_None);
return Py_None;
}
#undef EXCINFO
/* Argument conversion. */
/* Convert object to a pointer to gpgme type, generic version. */
PyObject *
_pyme_obj2gpgme_t(PyObject *input, const char *objtype, int argnum)
{
PyObject *pyname = NULL, *pypointer = NULL;
pyname = PyObject_GetAttrString(input, "_ctype");
if (pyname && PyUnicode_Check(pyname))
{
PyObject *encoded = PyUnicode_AsUTF8String(pyname);
if (strcmp(PyBytes_AsString(encoded), objtype) != 0)
{
PyErr_Format(PyExc_TypeError,
"arg %d: Expected value of type %s, but got %s",
argnum, objtype, PyBytes_AsString(encoded));
Py_DECREF(encoded);
Py_DECREF(pyname);
return NULL;
}
Py_DECREF(encoded);
}
else
return NULL;
Py_DECREF(pyname);
pypointer = PyObject_GetAttrString(input, "wrapped");
if (pypointer == NULL) {
PyErr_Format(PyExc_TypeError,
"arg %d: Use of uninitialized Python object %s",
argnum, objtype);
return NULL;
}
return pypointer;
}
/* Convert object to a pointer to gpgme type, version for data
objects. Constructs a wrapper Python on the fly e.g. for file-like
objects with a fileno method, returning it in WRAPPER. This object
must be de-referenced when no longer needed. */
PyObject *
_pyme_obj2gpgme_data_t(PyObject *input, int argnum, gpgme_data_t *wrapper,
PyObject **bytesio, Py_buffer *view)
{
gpgme_error_t err;
PyObject *data;
PyObject *fd;
/* See if it is a file-like object with file number. */
fd = PyObject_CallMethod(input, "fileno", NULL);
if (fd) {
err = gpgme_data_new_from_fd(wrapper, (int) PyLong_AsLong(fd));
Py_DECREF(fd);
if (err)
return _pyme_raise_exception (err);
return _pyme_wrap_gpgme_data_t(*wrapper);
}
else
PyErr_Clear();
/* No? Maybe it implements the buffer protocol. */
data = PyObject_CallMethod(input, "getbuffer", NULL);
if (data)
{
/* Save a reference to input, which seems to be a BytesIO
object. */
Py_INCREF(input);
*bytesio = input;
}
else
{
PyErr_Clear();
/* No, but maybe the user supplied a buffer object? */
data = input;
}
/* Do we have a buffer object? */
if (PyObject_CheckBuffer(data))
{
if (PyObject_GetBuffer(data, view, PyBUF_SIMPLE) < 0)
return NULL;
if (data != input)
Py_DECREF(data);
assert (view->obj);
assert (view->ndim == 1);
assert (view->shape == NULL);
assert (view->strides == NULL);
assert (view->suboffsets == NULL);
err = gpgme_data_new_from_mem(wrapper, view->buf, (size_t) view->len, 0);
if (err)
return _pyme_raise_exception (err);
return _pyme_wrap_gpgme_data_t(*wrapper);
}
/* As last resort we assume it is a wrapped data object. */
if (PyObject_HasAttrString(data, "_ctype"))
return _pyme_obj2gpgme_t(data, "gpgme_data_t", argnum);
return PyErr_Format(PyExc_TypeError,
"arg %d: expected pyme.Data, file, or an object "
"implementing the buffer protocol, got %s",
argnum, data->ob_type->tp_name);
}
PyObject *
_pyme_wrap_result(PyObject *fragile, const char *classname)
{
static PyObject *results;
PyObject *class;
PyObject *replacement;
if (results == NULL)
{
PyObject *from_list = PyList_New(0);
if (from_list == NULL)
return NULL;
results = PyImport_ImportModuleLevel("results", PyEval_GetGlobals(),
PyEval_GetLocals(), from_list, 1);
Py_DECREF(from_list);
if (results == NULL)
return NULL;
}
class = PyMapping_GetItemString(PyModule_GetDict(results), classname);
if (class == NULL)
return NULL;
replacement = PyObject_CallFunctionObjArgs(class, fragile, NULL);
Py_DECREF(class);
return replacement;
}
/* Callback support. */
static gpgme_error_t pyPassphraseCb(void *hook,
const char *uid_hint,
const char *passphrase_info,
int prev_was_bad,
int fd) {
PyObject *pyhook = (PyObject *) hook;
PyObject *self = NULL;
PyObject *func = NULL;
PyObject *args = NULL;
PyObject *retval = NULL;
PyObject *dataarg = NULL;
PyObject *encoded = NULL;
gpgme_error_t err_status = 0;
_pyme_exception_init();
assert (PyTuple_Check(pyhook));
assert (PyTuple_Size(pyhook) == 2 || PyTuple_Size(pyhook) == 3);
self = PyTuple_GetItem(pyhook, 0);
func = PyTuple_GetItem(pyhook, 1);
if (PyTuple_Size(pyhook) == 3) {
dataarg = PyTuple_GetItem(pyhook, 2);
args = PyTuple_New(4);
} else {
args = PyTuple_New(3);
}
if (uid_hint == NULL)
{
Py_INCREF(Py_None);
PyTuple_SetItem(args, 0, Py_None);
}
else
PyTuple_SetItem(args, 0, PyUnicode_DecodeUTF8(uid_hint, strlen (uid_hint),
"strict"));
if (PyErr_Occurred()) {
Py_DECREF(args);
err_status = gpg_error(GPG_ERR_GENERAL);
goto leave;
}
PyTuple_SetItem(args, 1, PyBytes_FromString(passphrase_info));
PyTuple_SetItem(args, 2, PyBool_FromLong((long)prev_was_bad));
if (dataarg) {
Py_INCREF(dataarg); /* Because GetItem doesn't give a ref but SetItem taketh away */
PyTuple_SetItem(args, 3, dataarg);
}
retval = PyObject_CallObject(func, args);
Py_DECREF(args);
if (PyErr_Occurred()) {
err_status = _pyme_exception2code();
} else {
if (!retval) {
if (write(fd, "\n", 1) < 0) {
err_status = gpgme_error_from_syserror ();
_pyme_raise_exception (err_status);
}
} else {
char *buf;
size_t len;
if (PyBytes_Check(retval))
buf = PyBytes_AsString(retval), len = PyBytes_Size(retval);
else if (PyUnicode_Check(retval))
{
Py_ssize_t ssize;
encoded = PyUnicode_AsUTF8String(retval);
if (encoded == NULL)
{
err_status = gpg_error(GPG_ERR_GENERAL);
goto leave;
}
if (PyBytes_AsStringAndSize(encoded, &buf, &ssize) == -1)
{
err_status = gpg_error(GPG_ERR_GENERAL);
goto leave;
}
assert (! buf || ssize >= 0);
len = (size_t) ssize;
}
else
{
PyErr_Format(PyExc_TypeError,
"expected str or bytes from passphrase callback, got %s",
retval->ob_type->tp_name);
err_status = gpg_error(GPG_ERR_GENERAL);
goto leave;
}
if (write(fd, buf, len) < 0) {
err_status = gpgme_error_from_syserror ();
_pyme_raise_exception (err_status);
}
if (! err_status && write(fd, "\n", 1) < 0) {
err_status = gpgme_error_from_syserror ();
_pyme_raise_exception (err_status);
}
Py_DECREF(retval);
}
}
leave:
if (err_status)
_pyme_stash_callback_exception(self);
Py_XDECREF(encoded);
return err_status;
}
PyObject *
pyme_set_passphrase_cb(PyObject *self, PyObject *cb) {
PyObject *wrapped;
gpgme_ctx_t ctx;
wrapped = PyObject_GetAttrString(self, "wrapped");
if (wrapped == NULL)
{
assert (PyErr_Occurred ());
return NULL;
}
ctx = _pyme_unwrap_gpgme_ctx_t(wrapped);
Py_DECREF(wrapped);
if (ctx == NULL)
{
if (cb == Py_None)
goto out;
else
return PyErr_Format(PyExc_RuntimeError, "wrapped is NULL");
}
if (cb == Py_None) {
gpgme_set_passphrase_cb(ctx, NULL, NULL);
PyObject_SetAttrString(self, "_passphrase_cb", Py_None);
goto out;
}
if (! PyTuple_Check(cb))
return PyErr_Format(PyExc_TypeError, "cb must be a tuple");
if (PyTuple_Size(cb) != 2 && PyTuple_Size(cb) != 3)
return PyErr_Format(PyExc_TypeError,
"cb must be a tuple of size 2 or 3");
gpgme_set_passphrase_cb(ctx, (gpgme_passphrase_cb_t) pyPassphraseCb,
(void *) cb);
PyObject_SetAttrString(self, "_passphrase_cb", cb);
out:
Py_INCREF(Py_None);
return Py_None;
}
static void pyProgressCb(void *hook, const char *what, int type, int current,
int total) {
PyObject *func = NULL, *dataarg = NULL, *args = NULL, *retval = NULL;
PyObject *pyhook = (PyObject *) hook;
PyObject *self = NULL;
assert (PyTuple_Check(pyhook));
assert (PyTuple_Size(pyhook) == 2 || PyTuple_Size(pyhook) == 3);
self = PyTuple_GetItem(pyhook, 0);
func = PyTuple_GetItem(pyhook, 1);
if (PyTuple_Size(pyhook) == 3) {
dataarg = PyTuple_GetItem(pyhook, 2);
args = PyTuple_New(5);
} else {
args = PyTuple_New(4);
}
PyTuple_SetItem(args, 0, PyUnicode_DecodeUTF8(what, strlen (what),
"strict"));
if (PyErr_Occurred()) {
_pyme_stash_callback_exception(self);
Py_DECREF(args);
return;
}
PyTuple_SetItem(args, 1, PyLong_FromLong((long) type));
PyTuple_SetItem(args, 2, PyLong_FromLong((long) current));
PyTuple_SetItem(args, 3, PyLong_FromLong((long) total));
if (dataarg) {
Py_INCREF(dataarg); /* Because GetItem doesn't give a ref but SetItem taketh away */
PyTuple_SetItem(args, 4, dataarg);
}
retval = PyObject_CallObject(func, args);
if (PyErr_Occurred())
_pyme_stash_callback_exception(self);
Py_DECREF(args);
Py_XDECREF(retval);
}
PyObject *
pyme_set_progress_cb(PyObject *self, PyObject *cb) {
PyObject *wrapped;
gpgme_ctx_t ctx;
wrapped = PyObject_GetAttrString(self, "wrapped");
if (wrapped == NULL)
{
assert (PyErr_Occurred ());
return NULL;
}
ctx = _pyme_unwrap_gpgme_ctx_t(wrapped);
Py_DECREF(wrapped);
if (ctx == NULL)
{
if (cb == Py_None)
goto out;
else
return PyErr_Format(PyExc_RuntimeError, "wrapped is NULL");
}
if (cb == Py_None) {
gpgme_set_progress_cb(ctx, NULL, NULL);
PyObject_SetAttrString(self, "_progress_cb", Py_None);
goto out;
}
if (! PyTuple_Check(cb))
return PyErr_Format(PyExc_TypeError, "cb must be a tuple");
if (PyTuple_Size(cb) != 2 && PyTuple_Size(cb) != 3)
return PyErr_Format(PyExc_TypeError,
"cb must be a tuple of size 2 or 3");
gpgme_set_progress_cb(ctx, (gpgme_progress_cb_t) pyProgressCb, (void *) cb);
PyObject_SetAttrString(self, "_progress_cb", cb);
out:
Py_INCREF(Py_None);
return Py_None;
}
/* Status callbacks. */
static gpgme_error_t pyStatusCb(void *hook, const char *keyword,
const char *args) {
gpgme_error_t err = 0;
PyObject *pyhook = (PyObject *) hook;
PyObject *self = NULL;
PyObject *func = NULL;
PyObject *dataarg = NULL;
PyObject *pyargs = NULL;
PyObject *retval = NULL;
assert (PyTuple_Check(pyhook));
assert (PyTuple_Size(pyhook) == 2 || PyTuple_Size(pyhook) == 3);
self = PyTuple_GetItem(pyhook, 0);
func = PyTuple_GetItem(pyhook, 1);
if (PyTuple_Size(pyhook) == 3) {
dataarg = PyTuple_GetItem(pyhook, 2);
pyargs = PyTuple_New(3);
} else {
pyargs = PyTuple_New(2);
}
if (keyword)
PyTuple_SetItem(pyargs, 0, PyUnicode_DecodeUTF8(keyword, strlen (keyword),
"strict"));
else
{
Py_INCREF(Py_None);
PyTuple_SetItem(pyargs, 0, Py_None);
}
PyTuple_SetItem(pyargs, 1, PyUnicode_DecodeUTF8(args, strlen (args),
"strict"));
if (PyErr_Occurred()) {
err = gpg_error(GPG_ERR_GENERAL);
Py_DECREF(pyargs);
goto leave;
}
if (dataarg) {
Py_INCREF(dataarg);
PyTuple_SetItem(pyargs, 2, dataarg);
}
retval = PyObject_CallObject(func, pyargs);
if (PyErr_Occurred())
err = _pyme_exception2code();
Py_DECREF(pyargs);
Py_XDECREF(retval);
leave:
if (err)
_pyme_stash_callback_exception(self);
return err;
}
PyObject *
pyme_set_status_cb(PyObject *self, PyObject *cb) {
PyObject *wrapped;
gpgme_ctx_t ctx;
wrapped = PyObject_GetAttrString(self, "wrapped");
if (wrapped == NULL)
{
assert (PyErr_Occurred ());
return NULL;
}
ctx = _pyme_unwrap_gpgme_ctx_t(wrapped);
Py_DECREF(wrapped);
if (ctx == NULL)
{
if (cb == Py_None)
goto out;
else
return PyErr_Format(PyExc_RuntimeError, "wrapped is NULL");
}
if (cb == Py_None) {
gpgme_set_status_cb(ctx, NULL, NULL);
PyObject_SetAttrString(self, "_status_cb", Py_None);
goto out;
}
if (! PyTuple_Check(cb))
return PyErr_Format(PyExc_TypeError, "cb must be a tuple");
if (PyTuple_Size(cb) != 2 && PyTuple_Size(cb) != 3)
return PyErr_Format(PyExc_TypeError,
"cb must be a tuple of size 2 or 3");
gpgme_set_status_cb(ctx, (gpgme_status_cb_t) pyStatusCb, (void *) cb);
PyObject_SetAttrString(self, "_status_cb", cb);
out:
Py_INCREF(Py_None);
return Py_None;
}
/* Edit callbacks. */
gpgme_error_t _pyme_edit_cb(void *opaque, gpgme_status_code_t status,
const char *args, int fd) {
PyObject *func = NULL, *dataarg = NULL, *pyargs = NULL, *retval = NULL;
PyObject *pyopaque = (PyObject *) opaque;
gpgme_error_t err_status = 0;
PyObject *self = NULL;
_pyme_exception_init();
assert (PyTuple_Check(pyopaque));
assert (PyTuple_Size(pyopaque) == 2 || PyTuple_Size(pyopaque) == 3);
self = PyTuple_GetItem(pyopaque, 0);
func = PyTuple_GetItem(pyopaque, 1);
if (PyTuple_Size(pyopaque) == 3) {
dataarg = PyTuple_GetItem(pyopaque, 2);
pyargs = PyTuple_New(3);
} else {
pyargs = PyTuple_New(2);
}
PyTuple_SetItem(pyargs, 0, PyLong_FromLong((long) status));
PyTuple_SetItem(pyargs, 1, PyUnicode_FromString(args));
if (dataarg) {
Py_INCREF(dataarg); /* Because GetItem doesn't give a ref but SetItem taketh away */
PyTuple_SetItem(pyargs, 2, dataarg);
}
retval = PyObject_CallObject(func, pyargs);
Py_DECREF(pyargs);
if (PyErr_Occurred()) {
err_status = _pyme_exception2code();
} else {
if (fd>=0 && retval && PyUnicode_Check(retval)) {
PyObject *encoded = NULL;
char *buffer;
Py_ssize_t size;
encoded = PyUnicode_AsUTF8String(retval);
if (encoded == NULL)
{
err_status = gpg_error(GPG_ERR_GENERAL);
goto leave;
}
if (PyBytes_AsStringAndSize(encoded, &buffer, &size) == -1)
{
Py_DECREF(encoded);
err_status = gpg_error(GPG_ERR_GENERAL);
goto leave;
}
if (write(fd, buffer, size) < 0) {
err_status = gpgme_error_from_syserror ();
_pyme_raise_exception (err_status);
}
if (! err_status && write(fd, "\n", 1) < 0) {
err_status = gpgme_error_from_syserror ();
_pyme_raise_exception (err_status);
}
Py_DECREF(encoded);
}
}
leave:
if (err_status)
_pyme_stash_callback_exception(self);
Py_XDECREF(retval);
return err_status;
}
/* Data callbacks. */
/* Read up to SIZE bytes into buffer BUFFER from the data object with
the handle HOOK. Return the number of characters read, 0 on EOF
and -1 on error. If an error occurs, errno is set. */
static ssize_t pyDataReadCb(void *hook, void *buffer, size_t size)
{
ssize_t result;
PyObject *pyhook = (PyObject *) hook;
PyObject *self = NULL;
PyObject *func = NULL;
PyObject *dataarg = NULL;
PyObject *pyargs = NULL;
PyObject *retval = NULL;
assert (PyTuple_Check(pyhook));
assert (PyTuple_Size(pyhook) == 5 || PyTuple_Size(pyhook) == 6);
self = PyTuple_GetItem(pyhook, 0);
func = PyTuple_GetItem(pyhook, 1);
if (PyTuple_Size(pyhook) == 6) {
dataarg = PyTuple_GetItem(pyhook, 5);
pyargs = PyTuple_New(2);
} else {
pyargs = PyTuple_New(1);
}
PyTuple_SetItem(pyargs, 0, PyLong_FromSize_t(size));
if (dataarg) {
Py_INCREF(dataarg);
PyTuple_SetItem(pyargs, 1, dataarg);
}
retval = PyObject_CallObject(func, pyargs);
Py_DECREF(pyargs);
if (PyErr_Occurred()) {
_pyme_stash_callback_exception(self);
result = -1;
goto leave;
}
if (! PyBytes_Check(retval)) {
PyErr_Format(PyExc_TypeError,
"expected bytes from read callback, got %s",
retval->ob_type->tp_name);
_pyme_stash_callback_exception(self);
result = -1;
goto leave;
}
if (PyBytes_Size(retval) > size) {
PyErr_Format(PyExc_TypeError,
"expected %zu bytes from read callback, got %zu",
size, PyBytes_Size(retval));
_pyme_stash_callback_exception(self);
result = -1;
goto leave;
}
memcpy(buffer, PyBytes_AsString(retval), PyBytes_Size(retval));
result = PyBytes_Size(retval);
leave:
Py_XDECREF(retval);
return result;
}
/* Write up to SIZE bytes from buffer BUFFER to the data object with
the handle HOOK. Return the number of characters written, or -1
on error. If an error occurs, errno is set. */
static ssize_t pyDataWriteCb(void *hook, const void *buffer, size_t size)
{
ssize_t result;
PyObject *pyhook = (PyObject *) hook;
PyObject *self = NULL;
PyObject *func = NULL;
PyObject *dataarg = NULL;
PyObject *pyargs = NULL;
PyObject *retval = NULL;
assert (PyTuple_Check(pyhook));
assert (PyTuple_Size(pyhook) == 5 || PyTuple_Size(pyhook) == 6);
self = PyTuple_GetItem(pyhook, 0);
func = PyTuple_GetItem(pyhook, 2);
if (PyTuple_Size(pyhook) == 6) {
dataarg = PyTuple_GetItem(pyhook, 5);
pyargs = PyTuple_New(2);
} else {
pyargs = PyTuple_New(1);
}
PyTuple_SetItem(pyargs, 0, PyBytes_FromStringAndSize(buffer, size));
if (dataarg) {
Py_INCREF(dataarg);
PyTuple_SetItem(pyargs, 1, dataarg);
}
retval = PyObject_CallObject(func, pyargs);
Py_DECREF(pyargs);
if (PyErr_Occurred()) {
_pyme_stash_callback_exception(self);
result = -1;
goto leave;
}
- if (! PyLong_Check(retval)) {
+#if PY_MAJOR_VERSION < 3
+ if (PyInt_Check(retval))
+ result = PyInt_AsSsize_t(retval);
+ else
+#endif
+ if (PyLong_Check(retval))
+ result = PyLong_AsSsize_t(retval);
+ else {
PyErr_Format(PyExc_TypeError,
- "expected int from read callback, got %s",
+ "expected int from write callback, got %s",
retval->ob_type->tp_name);
_pyme_stash_callback_exception(self);
result = -1;
- goto leave;
}
- result = PyLong_AsSsize_t(retval);
-
leave:
Py_XDECREF(retval);
return result;
}
/* Set the current position from where the next read or write starts
in the data object with the handle HOOK to OFFSET, relativ to
WHENCE. Returns the new offset in bytes from the beginning of the
data object. */
static off_t pyDataSeekCb(void *hook, off_t offset, int whence)
{
off_t result;
PyObject *pyhook = (PyObject *) hook;
PyObject *self = NULL;
PyObject *func = NULL;
PyObject *dataarg = NULL;
PyObject *pyargs = NULL;
PyObject *retval = NULL;
assert (PyTuple_Check(pyhook));
assert (PyTuple_Size(pyhook) == 5 || PyTuple_Size(pyhook) == 6);
self = PyTuple_GetItem(pyhook, 0);
func = PyTuple_GetItem(pyhook, 3);
if (PyTuple_Size(pyhook) == 6) {
dataarg = PyTuple_GetItem(pyhook, 5);
pyargs = PyTuple_New(3);
} else {
pyargs = PyTuple_New(2);
}
#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64
PyTuple_SetItem(pyargs, 0, PyLong_FromLongLong((long long) offset));
#else
PyTuple_SetItem(pyargs, 0, PyLong_FromLong((long) offset));
#endif
PyTuple_SetItem(pyargs, 1, PyLong_FromLong((long) whence));
if (dataarg) {
Py_INCREF(dataarg);
PyTuple_SetItem(pyargs, 2, dataarg);
}
retval = PyObject_CallObject(func, pyargs);
Py_DECREF(pyargs);
if (PyErr_Occurred()) {
_pyme_stash_callback_exception(self);
result = -1;
goto leave;
}
- if (! PyLong_Check(retval)) {
+#if PY_MAJOR_VERSION < 3
+ if (PyInt_Check(retval))
+ result = PyInt_AsLong(retval);
+ else
+#endif
+ if (PyLong_Check(retval))
+#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64
+ result = PyLong_AsLongLong(retval);
+#else
+ result = PyLong_AsLong(retval);
+#endif
+ else {
PyErr_Format(PyExc_TypeError,
- "expected int from read callback, got %s",
+ "expected int from seek callback, got %s",
retval->ob_type->tp_name);
_pyme_stash_callback_exception(self);
result = -1;
- goto leave;
}
-#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64
- result = PyLong_AsLongLong(retval);
-#else
- result = PyLong_AsLong(retval);
-#endif
-
leave:
Py_XDECREF(retval);
return result;
}
/* Close the data object with the handle HOOK. */
static void pyDataReleaseCb(void *hook)
{
PyObject *pyhook = (PyObject *) hook;
PyObject *self = NULL;
PyObject *func = NULL;
PyObject *dataarg = NULL;
PyObject *pyargs = NULL;
PyObject *retval = NULL;
assert (PyTuple_Check(pyhook));
assert (PyTuple_Size(pyhook) == 5 || PyTuple_Size(pyhook) == 6);
self = PyTuple_GetItem(pyhook, 0);
func = PyTuple_GetItem(pyhook, 4);
if (PyTuple_Size(pyhook) == 6) {
dataarg = PyTuple_GetItem(pyhook, 5);
pyargs = PyTuple_New(1);
} else {
pyargs = PyTuple_New(0);
}
if (dataarg) {
Py_INCREF(dataarg);
PyTuple_SetItem(pyargs, 0, dataarg);
}
retval = PyObject_CallObject(func, pyargs);
Py_XDECREF(retval);
Py_DECREF(pyargs);
if (PyErr_Occurred())
_pyme_stash_callback_exception(self);
}
PyObject *
pyme_data_new_from_cbs(PyObject *self,
PyObject *pycbs,
gpgme_data_t *r_data)
{
static struct gpgme_data_cbs cbs = {
pyDataReadCb,
pyDataWriteCb,
pyDataSeekCb,
pyDataReleaseCb,
};
gpgme_error_t err;
if (! PyTuple_Check(pycbs))
return PyErr_Format(PyExc_TypeError, "pycbs must be a tuple");
if (PyTuple_Size(pycbs) != 5 && PyTuple_Size(pycbs) != 6)
return PyErr_Format(PyExc_TypeError,
"pycbs must be a tuple of size 5 or 6");
err = gpgme_data_new_from_cbs(r_data, &cbs, (void *) pycbs);
if (err)
return _pyme_raise_exception(err);
PyObject_SetAttrString(self, "_data_cbs", pycbs);
Py_INCREF(Py_None);
return Py_None;
}
/* The assuan callbacks. */
gpgme_error_t
_pyme_assuan_data_cb (void *hook, const void *data, size_t datalen)
{
gpgme_error_t err = 0;
PyObject *pyhook = (PyObject *) hook;
PyObject *self = NULL;
PyObject *func = NULL;
PyObject *py_data = NULL;
PyObject *retval = NULL;
assert (PyTuple_Check(pyhook));
assert (PyTuple_Size(pyhook) == 2);
self = PyTuple_GetItem(pyhook, 0);
func = PyTuple_GetItem(pyhook, 1);
assert (PyCallable_Check(func));
py_data = PyBytes_FromStringAndSize(data, datalen);
if (py_data == NULL)
{
err = _pyme_exception2code();
goto leave;
}
retval = PyObject_CallFunctionObjArgs(func, py_data, NULL);
if (PyErr_Occurred())
err = _pyme_exception2code();
Py_DECREF(py_data);
Py_XDECREF(retval);
leave:
if (err)
_pyme_stash_callback_exception(self);
return err;
}
gpgme_error_t
_pyme_assuan_inquire_cb (void *hook, const char *name, const char *args,
gpgme_data_t *r_data)
{
gpgme_error_t err = 0;
PyObject *pyhook = (PyObject *) hook;
PyObject *self = NULL;
PyObject *func = NULL;
PyObject *py_name = NULL;
PyObject *py_args = NULL;
PyObject *retval = NULL;
assert (PyTuple_Check(pyhook));
assert (PyTuple_Size(pyhook) == 2);
self = PyTuple_GetItem(pyhook, 0);
func = PyTuple_GetItem(pyhook, 1);
assert (PyCallable_Check(func));
py_name = PyUnicode_FromString(name);
if (py_name == NULL)
{
err = _pyme_exception2code();
goto leave;
}
py_args = PyUnicode_FromString(args);
if (py_args == NULL)
{
err = _pyme_exception2code();
goto leave;
}
retval = PyObject_CallFunctionObjArgs(func, py_name, py_args, NULL);
if (PyErr_Occurred())
err = _pyme_exception2code();
Py_XDECREF(retval);
/* FIXME: Returning data is not yet implemented. */
*r_data = NULL;
leave:
Py_XDECREF(py_name);
Py_XDECREF(py_args);
if (err)
_pyme_stash_callback_exception(self);
return err;
}
gpgme_error_t
_pyme_assuan_status_cb (void *hook, const char *status, const char *args)
{
gpgme_error_t err = 0;
PyObject *pyhook = (PyObject *) hook;
PyObject *self = NULL;
PyObject *func = NULL;
PyObject *py_status = NULL;
PyObject *py_args = NULL;
PyObject *retval = NULL;
assert (PyTuple_Check(pyhook));
assert (PyTuple_Size(pyhook) == 2);
self = PyTuple_GetItem(pyhook, 0);
func = PyTuple_GetItem(pyhook, 1);
assert (PyCallable_Check(func));
py_status = PyUnicode_FromString(status);
if (py_status == NULL)
{
err = _pyme_exception2code();
goto leave;
}
py_args = PyUnicode_FromString(args);
if (py_args == NULL)
{
err = _pyme_exception2code();
goto leave;
}
retval = PyObject_CallFunctionObjArgs(func, py_status, py_args, NULL);
if (PyErr_Occurred())
err = _pyme_exception2code();
Py_XDECREF(retval);
leave:
Py_XDECREF(py_status);
Py_XDECREF(py_args);
if (err)
_pyme_stash_callback_exception(self);
return err;
}
diff --git a/pyme/core.py b/pyme/core.py
index 4bbbc17..a71426b 100644
--- a/pyme/core.py
+++ b/pyme/core.py
@@ -1,1105 +1,1105 @@
# Copyright (C) 2016 g10 Code GmbH
# Copyright (C) 2004,2008 Igor Belyi <belyi@users.sourceforge.net>
# Copyright (C) 2002 John Goerzen <jgoerzen@complete.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Core functionality
Core functionality of GPGME wrapped in a object-oriented fashion.
Provides the 'Context' class for performing cryptographic operations,
and the 'Data' class describing buffers of data.
"""
import re
import os
import weakref
from . import gpgme
from .errors import errorcheck, GPGMEError
from . import constants
from . import errors
from . import util
class GpgmeWrapper(object):
"""Base wrapper class
Not to be instantiated directly.
"""
def __init__(self, wrapped):
self._callback_excinfo = None
self.wrapped = wrapped
def __repr__(self):
return '<{}/{!r}>'.format(super(GpgmeWrapper, self).__repr__(),
self.wrapped)
def __str__(self):
acc = ['{}.{}'.format(__name__, self.__class__.__name__)]
flags = [f for f in self._boolean_properties if getattr(self, f)]
if flags:
acc.append('({})'.format(' '.join(flags)))
return '<{}>'.format(' '.join(acc))
def __hash__(self):
return hash(repr(self.wrapped))
def __eq__(self, other):
if other == None:
return False
else:
return repr(self.wrapped) == repr(other.wrapped)
@property
def _ctype(self):
"""The name of the c type wrapped by this class
Must be set by child classes.
"""
raise NotImplementedError()
@property
def _cprefix(self):
"""The common prefix of c functions wrapped by this class
Must be set by child classes.
"""
raise NotImplementedError()
def _errorcheck(self, name):
"""Must be implemented by child classes.
This function must return a trueish value for all c functions
returning gpgme_error_t."""
raise NotImplementedError()
"""The set of all boolean properties"""
_boolean_properties = set()
def __wrap_boolean_property(self, key, do_set=False, value=None):
get_func = getattr(gpgme,
"{}get_{}".format(self._cprefix, key))
set_func = getattr(gpgme,
"{}set_{}".format(self._cprefix, key))
def get(slf):
return bool(get_func(slf.wrapped))
def set_(slf, value):
set_func(slf.wrapped, bool(value))
p = property(get, set_, doc="{} flag".format(key))
setattr(self.__class__, key, p)
if do_set:
set_(self, bool(value))
else:
return get(self)
_munge_docstring = re.compile(r'gpgme_([^(]*)\(([^,]*), (.*\) -> .*)')
def __getattr__(self, key):
"""On-the-fly generation of wrapper methods and properties"""
if key[0] == '_' or self._cprefix == None:
return None
if key in self._boolean_properties:
return self.__wrap_boolean_property(key)
name = self._cprefix + key
func = getattr(gpgme, name)
if self._errorcheck(name):
def _funcwrap(slf, *args):
result = func(slf.wrapped, *args)
if slf._callback_excinfo:
gpgme.pyme_raise_callback_exception(slf)
return errorcheck(result, "Invocation of " + name)
else:
def _funcwrap(slf, *args):
result = func(slf.wrapped, *args)
if slf._callback_excinfo:
gpgme.pyme_raise_callback_exception(slf)
return result
doc = self._munge_docstring.sub(r'\2.\1(\3', getattr(func, "__doc__"))
_funcwrap.__doc__ = doc
# Monkey-patch the class.
setattr(self.__class__, key, _funcwrap)
# Bind the method to 'self'.
def wrapper(*args):
return _funcwrap(self, *args)
wrapper.__doc__ = doc
return wrapper
def __setattr__(self, key, value):
"""On-the-fly generation of properties"""
if key in self._boolean_properties:
self.__wrap_boolean_property(key, True, value)
else:
super(GpgmeWrapper, self).__setattr__(key, value)
class Context(GpgmeWrapper):
"""Context for cryptographic operations
All cryptographic operations in GPGME are performed within a
context, which contains the internal state of the operation as
well as configuration parameters. By using several contexts you
can run several cryptographic operations in parallel, with
different configuration.
Access to a context must be synchronized.
"""
def __init__(self, armor=False, textmode=False, offline=False,
signers=[], pinentry_mode=constants.PINENTRY_MODE_DEFAULT,
protocol=constants.PROTOCOL_OpenPGP,
wrapped=None):
"""Construct a context object
Keyword arguments:
armor -- enable ASCII armoring (default False)
textmode -- enable canonical text mode (default False)
offline -- do not contact external key sources (default False)
signers -- list of keys used for signing (default [])
pinentry_mode -- pinentry mode (default PINENTRY_MODE_DEFAULT)
protocol -- protocol to use (default PROTOCOL_OpenPGP)
"""
if wrapped:
self.own = False
else:
tmp = gpgme.new_gpgme_ctx_t_p()
errorcheck(gpgme.gpgme_new(tmp))
wrapped = gpgme.gpgme_ctx_t_p_value(tmp)
gpgme.delete_gpgme_ctx_t_p(tmp)
self.own = True
super(Context, self).__init__(wrapped)
self.armor = armor
self.textmode = textmode
self.offline = offline
self.signers = signers
self.pinentry_mode = pinentry_mode
self.protocol = protocol
def encrypt(self, plaintext, recipients=[], sign=True, sink=None,
passphrase=None, always_trust=False, add_encrypt_to=False,
prepare=False, expect_sign=False, compress=True):
"""Encrypt data
Encrypt the given plaintext for the given recipients. If the
list of recipients is empty, the data is encrypted
symmetrically with a passphrase.
The passphrase can be given as parameter, using a callback
registered at the context, or out-of-band via pinentry.
Keyword arguments:
recipients -- list of keys to encrypt to
sign -- sign plaintext (default True)
sink -- write result to sink instead of returning it
passphrase -- for symmetric encryption
always_trust -- always trust the keys (default False)
add_encrypt_to -- encrypt to configured additional keys (default False)
prepare -- (ui) prepare for encryption (default False)
expect_sign -- (ui) prepare for signing (default False)
compress -- compress plaintext (default True)
Returns:
ciphertext -- the encrypted data (or None if sink is given)
result -- additional information about the encryption
sign_result -- additional information about the signature(s)
Raises:
InvalidRecipients -- if encryption using a particular key failed
InvalidSigners -- if signing using a particular key failed
GPGMEError -- as signaled by the underlying library
"""
ciphertext = sink if sink else Data()
flags = 0
flags |= always_trust * constants.ENCRYPT_ALWAYS_TRUST
flags |= (not add_encrypt_to) * constants.ENCRYPT_NO_ENCRYPT_TO
flags |= prepare * constants.ENCRYPT_PREPARE
flags |= expect_sign * constants.ENCRYPT_EXPECT_SIGN
flags |= (not compress) * constants.ENCRYPT_NO_COMPRESS
if passphrase != None:
old_pinentry_mode = self.pinentry_mode
old_passphrase_cb = getattr(self, '_passphrase_cb', None)
self.pinentry_mode = constants.PINENTRY_MODE_LOOPBACK
def passphrase_cb(hint, desc, prev_bad, hook=None):
return passphrase
self.set_passphrase_cb(passphrase_cb)
try:
if sign:
self.op_encrypt_sign(recipients, flags, plaintext, ciphertext)
else:
self.op_encrypt(recipients, flags, plaintext, ciphertext)
except errors.GPGMEError as e:
if e.getcode() == errors.UNUSABLE_PUBKEY:
result = self.op_encrypt_result()
if result.invalid_recipients:
raise errors.InvalidRecipients(result.invalid_recipients)
if e.getcode() == errors.UNUSABLE_SECKEY:
sig_result = self.op_sign_result()
if sig_result.invalid_signers:
raise errors.InvalidSigners(sig_result.invalid_signers)
raise
finally:
if passphrase != None:
self.pinentry_mode = old_pinentry_mode
if old_passphrase_cb:
self.set_passphrase_cb(*old_passphrase_cb[1:])
result = self.op_encrypt_result()
assert not result.invalid_recipients
sig_result = self.op_sign_result() if sign else None
assert not sig_result or not sig_result.invalid_signers
cipherbytes = None
if not sink:
ciphertext.seek(0, os.SEEK_SET)
cipherbytes = ciphertext.read()
return cipherbytes, result, sig_result
def decrypt(self, ciphertext, sink=None, passphrase=None, verify=True):
"""Decrypt data
Decrypt the given ciphertext and verify any signatures. If
VERIFY is an iterable of keys, the ciphertext must be signed
by all those keys, otherwise an error is raised.
If the ciphertext is symmetrically encrypted using a
passphrase, that passphrase can be given as parameter, using a
callback registered at the context, or out-of-band via
pinentry.
Keyword arguments:
sink -- write result to sink instead of returning it
passphrase -- for symmetric decryption
verify -- check signatures (default True)
Returns:
plaintext -- the decrypted data (or None if sink is given)
result -- additional information about the decryption
verify_result -- additional information about the signature(s)
Raises:
UnsupportedAlgorithm -- if an unsupported algorithm was used
BadSignatures -- if a bad signature is encountered
MissingSignatures -- if expected signatures are missing or bad
GPGMEError -- as signaled by the underlying library
"""
plaintext = sink if sink else Data()
if passphrase != None:
old_pinentry_mode = self.pinentry_mode
old_passphrase_cb = getattr(self, '_passphrase_cb', None)
self.pinentry_mode = constants.PINENTRY_MODE_LOOPBACK
def passphrase_cb(hint, desc, prev_bad, hook=None):
return passphrase
self.set_passphrase_cb(passphrase_cb)
try:
if verify:
self.op_decrypt_verify(ciphertext, plaintext)
else:
self.op_decrypt(ciphertext, plaintext)
finally:
if passphrase != None:
self.pinentry_mode = old_pinentry_mode
if old_passphrase_cb:
self.set_passphrase_cb(*old_passphrase_cb[1:])
result = self.op_decrypt_result()
verify_result = self.op_verify_result() if verify else None
if result.unsupported_algorithm:
raise errors.UnsupportedAlgorithm(result.unsupported_algorithm)
if verify:
if any(s.status != errors.NO_ERROR
for s in verify_result.signatures):
raise errors.BadSignatures(verify_result)
if verify and verify != True:
missing = list()
for key in verify:
ok = False
for subkey in key.subkeys:
for sig in verify_result.signatures:
if sig.summary & constants.SIGSUM_VALID == 0:
continue
if subkey.can_sign and subkey.fpr == sig.fpr:
ok = True
break
if ok:
break
if not ok:
missing.append(key)
if missing:
raise errors.MissingSignatures(verify_result, missing)
plainbytes = None
if not sink:
plaintext.seek(0, os.SEEK_SET)
plainbytes = plaintext.read()
return plainbytes, result, verify_result
def sign(self, data, sink=None, mode=constants.SIG_MODE_NORMAL):
"""Sign data
Sign the given data with either the configured default local
key, or the 'signers' keys of this context.
Keyword arguments:
mode -- signature mode (default: normal, see below)
sink -- write result to sink instead of returning it
Returns:
either
signed_data -- encoded data and signature (normal mode)
signature -- only the signature data (detached mode)
cleartext -- data and signature as text (cleartext mode)
(or None if sink is given)
result -- additional information about the signature(s)
Raises:
InvalidSigners -- if signing using a particular key failed
GPGMEError -- as signaled by the underlying library
"""
signeddata = sink if sink else Data()
try:
self.op_sign(data, signeddata, mode)
except errors.GPGMEError as e:
if e.getcode() == errors.UNUSABLE_SECKEY:
result = self.op_sign_result()
if result.invalid_signers:
raise errors.InvalidSigners(result.invalid_signers)
raise
result = self.op_sign_result()
assert not result.invalid_signers
signedbytes = None
if not sink:
signeddata.seek(0, os.SEEK_SET)
signedbytes = signeddata.read()
return signedbytes, result
def verify(self, signed_data, signature=None, sink=None, verify=[]):
"""Verify signatures
Verify signatures over data. If VERIFY is an iterable of
keys, the ciphertext must be signed by all those keys,
otherwise an error is raised.
Keyword arguments:
signature -- detached signature data
sink -- write result to sink instead of returning it
Returns:
data -- the plain data
(or None if sink is given, or we verified a detached signature)
result -- additional information about the signature(s)
Raises:
BadSignatures -- if a bad signature is encountered
MissingSignatures -- if expected signatures are missing or bad
GPGMEError -- as signaled by the underlying library
"""
if signature:
# Detached signature, we don't return the plain text.
data = None
else:
data = sink if sink else Data()
if signature:
self.op_verify(signature, signed_data, None)
else:
self.op_verify(signed_data, None, data)
result = self.op_verify_result()
if any(s.status != errors.NO_ERROR for s in result.signatures):
raise errors.BadSignatures(result)
missing = list()
for key in verify:
ok = False
for subkey in key.subkeys:
for sig in result.signatures:
if sig.summary & constants.SIGSUM_VALID == 0:
continue
if subkey.can_sign and subkey.fpr == sig.fpr:
ok = True
break
if ok:
break
if not ok:
missing.append(key)
if missing:
raise errors.MissingSignatures(result, missing)
plainbytes = None
if data and not sink:
data.seek(0, os.SEEK_SET)
plainbytes = data.read()
return plainbytes, result
def keylist(self, pattern=None, secret=False):
"""List keys
Keyword arguments:
pattern -- return keys matching pattern (default: all keys)
secret -- return only secret keys
Returns:
-- an iterator returning key objects
Raises:
GPGMEError -- as signaled by the underlying library
"""
return self.op_keylist_all(pattern, secret)
def assuan_transact(self, command,
data_cb=None, inquire_cb=None, status_cb=None):
"""Issue a raw assuan command
This function can be used to issue a raw assuan command to the
engine.
If command is a string or bytes, it will be used as-is. If it
is an iterable of strings, it will be properly escaped and
joined into an well-formed assuan command.
Keyword arguments:
data_cb -- a callback receiving data lines
inquire_cb -- a callback providing more information
status_cb -- a callback receiving status lines
Returns:
result -- the result of command as GPGMEError
Raises:
GPGMEError -- as signaled by the underlying library
"""
if isinstance(command, (str, bytes)):
cmd = command
else:
cmd = " ".join(util.percent_escape(f) for f in command)
errptr = gpgme.new_gpgme_error_t_p()
err = gpgme.gpgme_op_assuan_transact_ext(
self.wrapped,
cmd,
(weakref.ref(self), data_cb) if data_cb else None,
(weakref.ref(self), inquire_cb) if inquire_cb else None,
(weakref.ref(self), status_cb) if status_cb else None,
errptr)
if self._callback_excinfo:
gpgme.pyme_raise_callback_exception(self)
errorcheck(err)
status = gpgme.gpgme_error_t_p_value(errptr)
gpgme.delete_gpgme_error_t_p(errptr)
return GPGMEError(status) if status != 0 else None
@property
def signers(self):
"""Keys used for signing"""
return [self.signers_enum(i) for i in range(self.signers_count())]
@signers.setter
def signers(self, signers):
old = self.signers
self.signers_clear()
try:
for key in signers:
self.signers_add(key)
except:
self.signers = old
raise
@property
def pinentry_mode(self):
"""Pinentry mode"""
return self.get_pinentry_mode()
@pinentry_mode.setter
def pinentry_mode(self, value):
self.set_pinentry_mode(value)
@property
def protocol(self):
"""Protocol to use"""
return self.get_protocol()
@protocol.setter
def protocol(self, value):
errorcheck(gpgme.gpgme_engine_check_version(value))
self.set_protocol(value)
_ctype = 'gpgme_ctx_t'
_cprefix = 'gpgme_'
def _errorcheck(self, name):
"""This function should list all functions returning gpgme_error_t"""
return ((name.startswith('gpgme_op_')
and not name.endswith('_result'))
or name in {
'gpgme_set_ctx_flag',
'gpgme_set_protocol',
'gpgme_set_sub_protocol',
'gpgme_set_keylist_mode',
'gpgme_set_pinentry_mode',
'gpgme_set_locale',
'gpgme_set_engine_info',
'gpgme_signers_add',
'gpgme_get_sig_key',
'gpgme_sig_notation_add',
'gpgme_cancel',
'gpgme_cancel_async',
'gpgme_cancel_get_key',
})
_boolean_properties = {'armor', 'textmode', 'offline'}
def __del__(self):
if not gpgme:
# At interpreter shutdown, gpgme is set to NONE.
return
self._free_passcb()
self._free_progresscb()
self._free_statuscb()
if self.own and self.wrapped and gpgme.gpgme_release:
gpgme.gpgme_release(self.wrapped)
self.wrapped = None
# Implement the context manager protocol.
def __enter__(self):
return self
def __exit__(self, type, value, tb):
self.__del__()
def op_keylist_all(self, *args, **kwargs):
self.op_keylist_start(*args, **kwargs)
key = self.op_keylist_next()
while key:
yield key
key = self.op_keylist_next()
self.op_keylist_end()
def op_keylist_next(self):
"""Returns the next key in the list created
by a call to op_keylist_start(). The object returned
is of type Key."""
ptr = gpgme.new_gpgme_key_t_p()
try:
errorcheck(gpgme.gpgme_op_keylist_next(self.wrapped, ptr))
key = gpgme.gpgme_key_t_p_value(ptr)
except errors.GPGMEError as excp:
key = None
if excp.getcode() != errors.EOF:
raise excp
gpgme.delete_gpgme_key_t_p(ptr)
if key:
key.__del__ = lambda self: gpgme.gpgme_key_unref(self)
return key
def get_key(self, fpr, secret):
"""Return the key corresponding to the fingerprint 'fpr'"""
ptr = gpgme.new_gpgme_key_t_p()
errorcheck(gpgme.gpgme_get_key(self.wrapped, fpr, ptr, secret))
key = gpgme.gpgme_key_t_p_value(ptr)
gpgme.delete_gpgme_key_t_p(ptr)
if key:
key.__del__ = lambda self: gpgme.gpgme_key_unref(self)
return key
def op_trustlist_all(self, *args, **kwargs):
self.op_trustlist_start(*args, **kwargs)
trust = self.op_trustlist_next()
while trust:
yield trust
trust = self.op_trustlist_next()
self.op_trustlist_end()
def op_trustlist_next(self):
"""Returns the next trust item in the list created
by a call to op_trustlist_start(). The object returned
is of type TrustItem."""
ptr = gpgme.new_gpgme_trust_item_t_p()
try:
errorcheck(gpgme.gpgme_op_trustlist_next(self.wrapped, ptr))
trust = gpgme.gpgme_trust_item_t_p_value(ptr)
except errors.GPGMEError as excp:
trust = None
if excp.getcode() != errors.EOF:
raise
gpgme.delete_gpgme_trust_item_t_p(ptr)
return trust
def set_passphrase_cb(self, func, hook=None):
"""Sets the passphrase callback to the function specified by func.
When the system needs a passphrase, it will call func with three args:
hint, a string describing the key it needs the passphrase for;
desc, a string describing the passphrase it needs;
prev_bad, a boolean equal True if this is a call made after
unsuccessful previous attempt.
If hook has a value other than None it will be passed into the func
as a forth argument.
Please see the GPGME manual for more information.
"""
if func == None:
hookdata = None
else:
if hook == None:
hookdata = (weakref.ref(self), func)
else:
hookdata = (weakref.ref(self), func, hook)
gpgme.pyme_set_passphrase_cb(self, hookdata)
def _free_passcb(self):
if gpgme.pyme_set_passphrase_cb:
self.set_passphrase_cb(None)
def set_progress_cb(self, func, hook=None):
"""Sets the progress meter callback to the function specified by FUNC.
If FUNC is None, the callback will be cleared.
This function will be called to provide an interactive update
of the system's progress. The function will be called with
three arguments, type, total, and current. If HOOK is not
None, it will be supplied as fourth argument.
Please see the GPGME manual for more information.
"""
if func == None:
hookdata = None
else:
if hook == None:
hookdata = (weakref.ref(self), func)
else:
hookdata = (weakref.ref(self), func, hook)
gpgme.pyme_set_progress_cb(self, hookdata)
def _free_progresscb(self):
if gpgme.pyme_set_progress_cb:
self.set_progress_cb(None)
def set_status_cb(self, func, hook=None):
"""Sets the status callback to the function specified by FUNC. If
FUNC is None, the callback will be cleared.
The function will be called with two arguments, keyword and
args. If HOOK is not None, it will be supplied as third
argument.
Please see the GPGME manual for more information.
"""
if func == None:
hookdata = None
else:
if hook == None:
hookdata = (weakref.ref(self), func)
else:
hookdata = (weakref.ref(self), func, hook)
gpgme.pyme_set_status_cb(self, hookdata)
def _free_statuscb(self):
if gpgme.pyme_set_status_cb:
self.set_status_cb(None)
@property
def engine_info(self):
"""Configuration of the engine currently in use"""
p = self.protocol
infos = [i for i in self.get_engine_info() if i.protocol == p]
assert len(infos) == 1
return infos[0]
def get_engine_info(self):
"""Get engine configuration
Returns information about all configured and installed
engines.
Returns:
infos -- a list of engine infos
"""
return gpgme.gpgme_ctx_get_engine_info(self.wrapped)
def set_engine_info(self, proto, file_name=None, home_dir=None):
"""Change engine configuration
Changes the configuration of the crypto engine implementing
the protocol 'proto' for the context.
Keyword arguments:
file_name -- engine program file name (unchanged if None)
home_dir -- configuration directory (unchanged if None)
"""
errorcheck(gpgme.gpgme_ctx_set_engine_info(
self.wrapped, proto, file_name, home_dir))
def wait(self, hang):
"""Wait for asynchronous call to finish. Wait forever if hang is True.
Raises an exception on errors.
Please read the GPGME manual for more information.
"""
ptr = gpgme.new_gpgme_error_t_p()
gpgme.gpgme_wait(self.wrapped, ptr, hang)
status = gpgme.gpgme_error_t_p_value(ptr)
gpgme.delete_gpgme_error_t_p(ptr)
errorcheck(status)
def op_edit(self, key, func, fnc_value, out):
"""Start key editing using supplied callback function"""
if key == None:
raise ValueError("op_edit: First argument cannot be None")
if fnc_value:
opaquedata = (weakref.ref(self), func, fnc_value)
else:
opaquedata = (weakref.ref(self), func)
result = gpgme.gpgme_op_edit(self.wrapped, key, opaquedata, out)
if self._callback_excinfo:
gpgme.pyme_raise_callback_exception(self)
errorcheck(result)
class Data(GpgmeWrapper):
"""Data buffer
A lot of data has to be exchanged between the user and the crypto
engine, like plaintext messages, ciphertext, signatures and
information about the keys. The technical details about
exchanging the data information are completely abstracted by
GPGME. The user provides and receives the data via `gpgme_data_t'
objects, regardless of the communication protocol between GPGME
and the crypto engine in use.
This Data class is the implementation of the GpgmeData objects.
Please see the information about __init__ for instantiation.
"""
_ctype = 'gpgme_data_t'
_cprefix = 'gpgme_data_'
def _errorcheck(self, name):
"""This function should list all functions returning gpgme_error_t"""
return name not in {
'gpgme_data_release_and_get_mem',
'gpgme_data_get_encoding',
'gpgme_data_seek',
'gpgme_data_get_file_name',
}
def __init__(self, string=None, file=None, offset=None,
length=None, cbs=None, copy=True):
"""Initialize a new gpgme_data_t object.
If no args are specified, make it an empty object.
If string alone is specified, initialize it with the data
contained there.
If file, offset, and length are all specified, file must
be either a filename or a file-like object, and the object
will be initialized by reading the specified chunk from the file.
If cbs is specified, it MUST be a tuple of the form:
(read_cb, write_cb, seek_cb, release_cb[, hook])
where the first four items are functions implementing reading,
writing, seeking the data, and releasing any resources once
the data object is deallocated. The functions must match the
following prototypes:
def read(amount, hook=None):
return <a b"bytes" object>
def write(data, hook=None):
return <the number of bytes written>
def seek(offset, whence, hook=None):
return <the new file position>
def release(hook=None):
<return value and exceptions are ignored>
The functions may be bound methods. In that case, you can
simply use the 'self' reference instead of using a hook.
If file is specified without any other arguments, then
it must be a filename, and the object will be initialized from
that file.
"""
super(Data, self).__init__(None)
self.data_cbs = None
if cbs != None:
self.new_from_cbs(*cbs)
elif string != None:
self.new_from_mem(string, copy)
elif file != None and offset != None and length != None:
self.new_from_filepart(file, offset, length)
elif file != None:
- if type(file) == type("x"):
+ if util.is_a_string(file):
self.new_from_file(file, copy)
else:
self.new_from_fd(file)
else:
self.new()
def __del__(self):
if not gpgme:
# At interpreter shutdown, gpgme is set to NONE.
return
if self.wrapped != None and gpgme.gpgme_data_release:
gpgme.gpgme_data_release(self.wrapped)
if self._callback_excinfo:
gpgme.pyme_raise_callback_exception(self)
self.wrapped = None
self._free_datacbs()
# Implement the context manager protocol.
def __enter__(self):
return self
def __exit__(self, type, value, tb):
self.__del__()
def _free_datacbs(self):
self._data_cbs = None
def new(self):
tmp = gpgme.new_gpgme_data_t_p()
errorcheck(gpgme.gpgme_data_new(tmp))
self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
gpgme.delete_gpgme_data_t_p(tmp)
def new_from_mem(self, string, copy=True):
tmp = gpgme.new_gpgme_data_t_p()
errorcheck(gpgme.gpgme_data_new_from_mem(tmp,string,len(string),copy))
self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
gpgme.delete_gpgme_data_t_p(tmp)
def new_from_file(self, filename, copy=True):
tmp = gpgme.new_gpgme_data_t_p()
try:
errorcheck(gpgme.gpgme_data_new_from_file(tmp, filename, copy))
except errors.GPGMEError as e:
if e.getcode() == errors.INV_VALUE and not copy:
raise ValueError("delayed reads are not yet supported")
else:
raise e
self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
gpgme.delete_gpgme_data_t_p(tmp)
def new_from_cbs(self, read_cb, write_cb, seek_cb, release_cb, hook=None):
tmp = gpgme.new_gpgme_data_t_p()
if hook != None:
hookdata = (weakref.ref(self),
read_cb, write_cb, seek_cb, release_cb, hook)
else:
hookdata = (weakref.ref(self),
read_cb, write_cb, seek_cb, release_cb)
gpgme.pyme_data_new_from_cbs(self, hookdata, tmp)
self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
gpgme.delete_gpgme_data_t_p(tmp)
def new_from_filepart(self, file, offset, length):
"""This wraps the GPGME gpgme_data_new_from_filepart() function.
The argument "file" may be:
* a string specifying a file name, or
* a file-like object supporting the fileno() and the mode attribute.
"""
tmp = gpgme.new_gpgme_data_t_p()
filename = None
fp = None
- if type(file) == type("x"):
+ if util.is_a_string(file):
filename = file
else:
fp = gpgme.fdopen(file.fileno(), file.mode)
if fp == None:
raise ValueError("Failed to open file from %s arg %s" % \
(str(type(file)), str(file)))
errorcheck(gpgme.gpgme_data_new_from_filepart(tmp, filename, fp,
offset, length))
self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
gpgme.delete_gpgme_data_t_p(tmp)
def new_from_fd(self, file):
"""This wraps the GPGME gpgme_data_new_from_fd() function. The
argument "file" must be a file-like object, supporting the
fileno() method.
"""
tmp = gpgme.new_gpgme_data_t_p()
errorcheck(gpgme.gpgme_data_new_from_fd(tmp, file.fileno()))
self.wrapped = gpgme.gpgme_data_t_p_value(tmp)
gpgme.delete_gpgme_data_t_p(tmp)
def new_from_stream(self, file):
"""This wrap around gpgme_data_new_from_stream is an alias for
new_from_fd() method since in python there's not difference
between file stream and file descriptor"""
self.new_from_fd(file)
def write(self, buffer):
"""Write buffer given as string or bytes.
If a string is given, it is implicitly encoded using UTF-8."""
written = gpgme.gpgme_data_write(self.wrapped, buffer)
if written < 0:
if self._callback_excinfo:
gpgme.pyme_raise_callback_exception(self)
else:
raise GPGMEError.fromSyserror()
return written
def read(self, size = -1):
"""Read at most size bytes, returned as bytes.
If the size argument is negative or omitted, read until EOF is reached.
Returns the data read, or the empty string if there was no data
to read before EOF was reached."""
if size == 0:
return ''
if size > 0:
try:
result = gpgme.gpgme_data_read(self.wrapped, size)
except:
if self._callback_excinfo:
gpgme.pyme_raise_callback_exception(self)
else:
raise
return result
else:
chunks = []
while True:
try:
result = gpgme.gpgme_data_read(self.wrapped, 4096)
except:
if self._callback_excinfo:
gpgme.pyme_raise_callback_exception(self)
else:
raise
if len(result) == 0:
break
chunks.append(result)
return b''.join(chunks)
def pubkey_algo_name(algo):
return gpgme.gpgme_pubkey_algo_name(algo)
def hash_algo_name(algo):
return gpgme.gpgme_hash_algo_name(algo)
def get_protocol_name(proto):
return gpgme.gpgme_get_protocol_name(proto)
def check_version(version=None):
return gpgme.gpgme_check_version(version)
# check_version also makes sure that several subsystems are properly
# initialized, and it must be run at least once before invoking any
# other function. We do it here so that the user does not have to do
# it unless she really wants to check for a certain version.
check_version()
def engine_check_version (proto):
try:
errorcheck(gpgme.gpgme_engine_check_version(proto))
return True
except errors.GPGMEError:
return False
def get_engine_info():
ptr = gpgme.new_gpgme_engine_info_t_p()
try:
errorcheck(gpgme.gpgme_get_engine_info(ptr))
info = gpgme.gpgme_engine_info_t_p_value(ptr)
except errors.GPGMEError:
info = None
gpgme.delete_gpgme_engine_info_t_p(ptr)
return info
def set_engine_info(proto, file_name, home_dir=None):
"""Changes the default configuration of the crypto engine implementing
the protocol 'proto'. 'file_name' is the file name of
the executable program implementing this protocol. 'home_dir' is the
directory name of the configuration directory (engine's default is
used if omitted)."""
errorcheck(gpgme.gpgme_set_engine_info(proto, file_name, home_dir))
def set_locale(category, value):
"""Sets the default locale used by contexts"""
errorcheck(gpgme.gpgme_set_locale(None, category, value))
def wait(hang):
"""Wait for asynchronous call on any Context to finish.
Wait forever if hang is True.
For finished anynch calls it returns a tuple (status, context):
status - status return by asnynchronous call.
context - context which caused this call to return.
Please read the GPGME manual of more information."""
ptr = gpgme.new_gpgme_error_t_p()
context = gpgme.gpgme_wait(None, ptr, hang)
status = gpgme.gpgme_error_t_p_value(ptr)
gpgme.delete_gpgme_error_t_p(ptr)
if context == None:
errorcheck(status)
else:
context = Context(context)
return (status, context)
diff --git a/pyme/util.py b/pyme/util.py
index c4c9e18..bf25ccb 100644
--- a/pyme/util.py
+++ b/pyme/util.py
@@ -1,38 +1,50 @@
# Copyright (C) 2016 g10 Code GmbH
# Copyright (C) 2004,2008 Igor Belyi <belyi@users.sourceforge.net>
# Copyright (C) 2002 John Goerzen <jgoerzen@complete.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+import sys
+
def process_constants(prefix, scope):
"""Called by the constant modules to load up the constants from the C
library starting with PREFIX. Matching constants will be inserted
into SCOPE with PREFIX stripped from the names. Returns the names
of inserted constants.
"""
from . import gpgme
index = len(prefix)
constants = {identifier[index:]: getattr(gpgme, identifier)
for identifier in dir(gpgme)
if identifier.startswith(prefix)}
scope.update(constants)
return list(constants.keys())
def percent_escape(s):
return ''.join(
'%{0:2x}'.format(ord(c))
if c == '+' or c == '"' or c == '%' or ord(c) <= 0x20 else c
for c in s)
+
+# Python2/3 compatibility
+if sys.version_info[0] == 3:
+ # Python3
+ def is_a_string(x):
+ return isinstance(x, str)
+else:
+ # Python2
+ def is_a_string(x):
+ return isinstance(x, basestring)
diff --git a/tests/t-encrypt-large.py b/tests/t-encrypt-large.py
index 69aed48..29f9de2 100755
--- a/tests/t-encrypt-large.py
+++ b/tests/t-encrypt-large.py
@@ -1,63 +1,63 @@
#!/usr/bin/env python3
# Copyright (C) 2016 g10 Code GmbH
#
# This file is part of GPGME.
#
# GPGME is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# GPGME is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
# Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, see <http://www.gnu.org/licenses/>.
import sys
import random
from pyme import core, constants
import support
if len(sys.argv) == 2:
nbytes = int(sys.argv[1])
else:
nbytes = 100000
support.init_gpgme(constants.PROTOCOL_OpenPGP)
c = core.Context()
ntoread = nbytes
def read_cb(amount):
global ntoread
chunk = ntoread if ntoread < amount else amount
ntoread -= chunk
assert ntoread >= 0
assert chunk >= 0
- return bytes(random.randrange(256) for i in range(chunk))
+ return bytes(bytearray(random.randrange(256) for i in range(chunk)))
nwritten = 0
def write_cb(data):
global nwritten
nwritten += len(data)
return len(data)
source = core.Data(cbs=(read_cb, None, None, lambda: None))
sink = core.Data(cbs=(None, write_cb, None, lambda: None))
keys = []
keys.append(c.get_key("A0FF4590BB6122EDEF6E3C542D727CC768697734", False))
keys.append(c.get_key("D695676BDCEDCC2CDD6152BCFE180B1DA9E3B0B2", False))
c.op_encrypt(keys, constants.ENCRYPT_ALWAYS_TRUST, source, sink)
result = c.op_encrypt_result()
assert not result.invalid_recipients, \
"Invalid recipient encountered: {}".format(result.invalid_recipients.fpr)
assert ntoread == 0
if support.verbose:
sys.stderr.write(
"plaintext={} bytes, ciphertext={} bytes\n".format(nbytes, nwritten))
diff --git a/tests/t-idiomatic.py b/tests/t-idiomatic.py
index 1989c92..726bbb9 100755
--- a/tests/t-idiomatic.py
+++ b/tests/t-idiomatic.py
@@ -1,76 +1,81 @@
#!/usr/bin/env python3
# Copyright (C) 2016 g10 Code GmbH
#
# This file is part of GPGME.
#
# GPGME is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# GPGME is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
# Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, see <http://www.gnu.org/licenses/>.
+import sys
import io
import os
import tempfile
import pyme
import support
support.init_gpgme(pyme.constants.PROTOCOL_OpenPGP)
# Both Context and Data can be used as context manager:
with pyme.Context() as c, pyme.Data() as d:
c.get_engine_info()
d.write(b"Halloechen")
leak_c = c
leak_d = d
assert leak_c.wrapped == None
assert leak_d.wrapped == None
def sign_and_verify(source, signed, sink):
with pyme.Context() as c:
c.op_sign(source, signed, pyme.constants.SIG_MODE_NORMAL)
signed.seek(0, os.SEEK_SET)
c.op_verify(signed, None, sink)
result = c.op_verify_result()
assert len(result.signatures) == 1, "Unexpected number of signatures"
sig = result.signatures[0]
assert sig.summary == (pyme.constants.SIGSUM_VALID |
pyme.constants.SIGSUM_GREEN)
assert pyme.errors.GPGMEError(sig.status).getcode() == pyme.errors.NO_ERROR
sink.seek(0, os.SEEK_SET)
assert sink.read() == b"Hallo Leute\n"
# Demonstrate automatic wrapping of file-like objects with 'fileno'
# method.
with tempfile.TemporaryFile() as source, \
tempfile.TemporaryFile() as signed, \
tempfile.TemporaryFile() as sink:
source.write(b"Hallo Leute\n")
source.seek(0, os.SEEK_SET)
sign_and_verify(source, signed, sink)
-# XXX: Python's io.BytesIo.truncate does not work as advertised.
-# http://bugs.python.org/issue27261
-bio = io.BytesIO()
-bio.truncate(1)
-if len(bio.getvalue()) != 1:
- # This version of Python is affected, preallocate buffer.
- preallocate = 128*b'\x00'
-else:
- preallocate = b''
+if sys.version_info[0] == 3:
+ # Python2's io.BytesIO does not implement the buffer interface,
+ # hence we cannot use it as sink.
-# Demonstrate automatic wrapping of objects implementing the buffer
-# interface, and the use of data objects with the 'with' statement.
-with io.BytesIO(preallocate) as signed, pyme.Data() as sink:
- sign_and_verify(b"Hallo Leute\n", signed, sink)
+ # XXX: Python's io.BytesIo.truncate does not work as advertised.
+ # http://bugs.python.org/issue27261
+ bio = io.BytesIO()
+ bio.truncate(1)
+ if len(bio.getvalue()) != 1:
+ # This version of Python is affected, preallocate buffer.
+ preallocate = 128*b'\x00'
+ else:
+ preallocate = b''
+
+ # Demonstrate automatic wrapping of objects implementing the buffer
+ # interface, and the use of data objects with the 'with' statement.
+ with io.BytesIO(preallocate) as signed, pyme.Data() as sink:
+ sign_and_verify(b"Hallo Leute\n", signed, sink)
diff --git a/tests/t-verify.py b/tests/t-verify.py
index b88bd07..ed5a91a 100755
--- a/tests/t-verify.py
+++ b/tests/t-verify.py
@@ -1,188 +1,192 @@
#!/usr/bin/env python3
# Copyright (C) 2016 g10 Code GmbH
#
# This file is part of GPGME.
#
# GPGME is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# GPGME is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
# Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, see <http://www.gnu.org/licenses/>.
+import sys
import os
import pyme
from pyme import core, constants, errors
import support
test_text1 = b"Just GNU it!\n"
test_text1f= b"Just GNU it?\n"
test_sig1 = b"""-----BEGIN PGP SIGNATURE-----
iN0EABECAJ0FAjoS+i9FFIAAAAAAAwA5YmFyw7bDpMO8w58gZGFzIHdhcmVuIFVt
bGF1dGUgdW5kIGpldHp0IGVpbiBwcm96ZW50JS1aZWljaGVuNRSAAAAAAAgAJGZv
b2Jhci4xdGhpcyBpcyBhIG5vdGF0aW9uIGRhdGEgd2l0aCAyIGxpbmVzGhpodHRw
Oi8vd3d3Lmd1Lm9yZy9wb2xpY3kvAAoJEC1yfMdoaXc0JBIAoIiLlUsvpMDOyGEc
dADGKXF/Hcb+AKCJWPphZCphduxSvrzH0hgzHdeQaA==
=nts1
-----END PGP SIGNATURE-----
"""
test_sig2 = b"""-----BEGIN PGP MESSAGE-----
owGbwMvMwCSoW1RzPCOz3IRxjXQSR0lqcYleSUWJTZOvjVdpcYmCu1+oQmaJIleH
GwuDIBMDGysTSIqBi1MApi+nlGGuwDeHao53HBr+FoVGP3xX+kvuu9fCMJvl6IOf
y1kvP4y+8D5a11ang0udywsA
=Crq6
-----END PGP MESSAGE-----
"""
# A message with a prepended but unsigned plaintext packet.
double_plaintext_sig = b"""-----BEGIN PGP MESSAGE-----
rDRiCmZvb2Jhci50eHRF4pxNVGhpcyBpcyBteSBzbmVha3kgcGxhaW50ZXh0IG1l
c3NhZ2UKowGbwMvMwCSoW1RzPCOz3IRxTWISa6JebnG666MFD1wzSzJSixQ81XMV
UlITUxTyixRyKxXKE0uSMxQyEosVikvyCwpSU/S4FNCArq6Ce1F+aXJGvoJvYlGF
erFCTmJxiUJ5flFKMVeHGwuDIBMDGysTyA4GLk4BmO036xgWzMgzt9V85jCtfDFn
UqVooWlGXHwNw/xg/fVzt9VNbtjtJ/fhUqYo0/LyCGEA
=6+AK
-----END PGP MESSAGE-----
"""
def check_result(result, summary, validity, fpr, status, notation):
assert len(result.signatures) == 1, "Unexpected number of signatures"
sig = result.signatures[0]
assert sig.summary == summary, \
"Unexpected signature summary: {}, want: {}".format(sig.summary,
summary)
assert sig.fpr == fpr
assert errors.GPGMEError(sig.status).getcode() == status
if notation:
expected_notations = {
- "bar": b"\xc3\xb6\xc3\xa4\xc3\xbc\xc3\x9f".decode() +
- " das waren Umlaute und jetzt ein prozent%-Zeichen",
+ "bar": (b"\xc3\xb6\xc3\xa4\xc3\xbc\xc3\x9f" +
+ b" das waren Umlaute und jetzt ein prozent%-Zeichen"
+ if sys.version_info[0] < 3 else
+ b"\xc3\xb6\xc3\xa4\xc3\xbc\xc3\x9f".decode() +
+ " das waren Umlaute und jetzt ein prozent%-Zeichen"),
"foobar.1": "this is a notation data with 2 lines",
None: "http://www.gu.org/policy/",
}
assert len(sig.notations) == len(expected_notations)
for r in sig.notations:
assert not 'name_len' in dir(r)
assert not 'value_len' in dir(r)
assert r.name in expected_notations
assert r.value == expected_notations[r.name], \
"Expected {!r}, got {!r}".format(expected_notations[r.name],
r.value)
expected_notations.pop(r.name)
assert len(expected_notations) == 0
assert not sig.wrong_key_usage
assert sig.validity == validity, \
"Unexpected signature validity: {}, want: {}".format(
sig.validity, validity)
assert errors.GPGMEError(sig.validity_reason).getcode() == errors.NO_ERROR
support.init_gpgme(constants.PROTOCOL_OpenPGP)
c = core.Context()
c.set_armor(True)
# Checking a valid message.
text = core.Data(test_text1)
sig = core.Data(test_sig1)
c.op_verify(sig, text, None)
result = c.op_verify_result()
check_result(result, constants.SIGSUM_VALID | constants.SIGSUM_GREEN,
constants.VALIDITY_FULL,
"A0FF4590BB6122EDEF6E3C542D727CC768697734",
errors.NO_ERROR, True)
# Checking a manipulated message.
text = core.Data(test_text1f)
sig.seek(0, os.SEEK_SET)
c.op_verify(sig, text, None)
result = c.op_verify_result()
check_result(result, constants.SIGSUM_RED, constants.VALIDITY_UNKNOWN,
"2D727CC768697734", errors.BAD_SIGNATURE, False)
# Checking a normal signature.
text = core.Data()
sig = core.Data(test_sig2)
c.op_verify(sig, None, text)
result = c.op_verify_result()
check_result(result, constants.SIGSUM_VALID | constants.SIGSUM_GREEN,
constants.VALIDITY_FULL,
"A0FF4590BB6122EDEF6E3C542D727CC768697734",
errors.NO_ERROR, False)
# Checking an invalid message.
text = core.Data()
sig = core.Data(double_plaintext_sig)
try:
c.op_verify(sig, None, text)
except Exception as e:
assert type(e) == errors.GPGMEError
assert e.getcode() == errors.BAD_DATA
else:
assert False, "Expected an error but got none."
# Idiomatic interface.
with pyme.Context(armor=True) as c:
# Checking a valid message.
_, result = c.verify(test_text1, test_sig1)
check_result(result, constants.SIGSUM_VALID | constants.SIGSUM_GREEN,
constants.VALIDITY_FULL,
"A0FF4590BB6122EDEF6E3C542D727CC768697734",
errors.NO_ERROR, True)
# Checking a manipulated message.
try:
c.verify(test_text1f, test_sig1)
except errors.BadSignatures as e:
check_result(e.result, constants.SIGSUM_RED,
constants.VALIDITY_UNKNOWN,
"2D727CC768697734", errors.BAD_SIGNATURE, False)
else:
assert False, "Expected an error but got none."
# Checking a normal signature.
sig = core.Data(test_sig2)
data, result = c.verify(test_sig2)
check_result(result, constants.SIGSUM_VALID | constants.SIGSUM_GREEN,
constants.VALIDITY_FULL,
"A0FF4590BB6122EDEF6E3C542D727CC768697734",
errors.NO_ERROR, False)
assert data == test_text1
# Checking an invalid message.
try:
c.verify(double_plaintext_sig)
except errors.GPGMEError as e:
assert e.getcode() == errors.BAD_DATA
else:
assert False, "Expected an error but got none."
alpha = c.get_key("A0FF4590BB6122EDEF6E3C542D727CC768697734", False)
bob = c.get_key("D695676BDCEDCC2CDD6152BCFE180B1DA9E3B0B2", False)
# Checking a valid message.
c.verify(test_text1, test_sig1, verify=[alpha])
try:
c.verify(test_text1, test_sig1, verify=[alpha, bob])
except errors.MissingSignatures as e:
assert len(e.missing) == 1
assert e.missing[0] == bob
else:
assert False, "Expected an error, got none"

File Metadata

Mime Type
text/x-diff
Expires
Sun, Dec 7, 12:23 AM (2 h, 56 m)
Storage Engine
local-disk
Storage Format
Raw Data
Storage Handle
3e/10/9c2f3aacd5575e9763b33895d682

Event Timeline