Initial port to Sequoia. sequoia
authorNeal H. Walfield <neal@pep.foundation>
Sat, 15 Dec 2018 17:03:46 +0100
branchsequoia
changeset 319153dcb2892c3f
parent 3190 92c7a348b84f
child 3194 40948fabe025
Initial port to Sequoia.
default.conf
src/Makefile
src/cryptotech.c
src/openpgp_compat.h
src/pEp_internal.h
src/pgp_sequoia.c
src/pgp_sequoia.h
src/pgp_sequoia_internal.h
test/Makefile
     1.1 --- a/default.conf	Sat Dec 15 17:00:09 2018 +0100
     1.2 +++ b/default.conf	Sat Dec 15 17:03:46 2018 +0100
     1.3 @@ -204,8 +204,8 @@
     1.4  # gpgconf is not available for old version of GPG, for example GPG 2.0.30. Override this variable, if you compile the engine for such an old version.
     1.5  GPG_CMD:=$(shell gpgconf --list-components | awk -F: '/^gpg:/ { print $$3; exit 0; }')
     1.6  
     1.7 -# Selects OpenPGP implementation. must be either `GPG` or `NETPGP`
     1.8 -OPENPGP=GPG
     1.9 +# Selects OpenPGP implementation. must be either `GPG` or `NETPGP` or `SEQUOIA`
    1.10 +OPENPGP=SEQUOIA
    1.11  
    1.12  # Path of libGPGME binary
    1.13  ifeq ($(BUILD_FOR),Linux)
    1.14 @@ -236,6 +236,11 @@
    1.15  NETPGP_INC=
    1.16  #NETPGP_INC=-I$(PREFIX)/include
    1.17  
    1.18 +SEQUOIA_CFLAGS=$(shell pkg-config --cflags-only-other sequoia)
    1.19 +SEQUOIA_LDFLAGS=$(shell pkg-config --libs-only-L --libs-only-other sequoia)
    1.20 +SEQUOIA_LIB=$(shell pkg-config --libs-only-l sequoia)
    1.21 +SEQUOIA_INC=$(shell pkg-config --cflags-only-I sequoia)
    1.22 +
    1.23  
    1.24  ######### OpenPGP #########
    1.25  # CppUnit library search flag
     2.1 --- a/src/Makefile	Sat Dec 15 17:00:09 2018 +0100
     2.2 +++ b/src/Makefile	Sat Dec 15 17:03:46 2018 +0100
     2.3 @@ -35,15 +35,20 @@
     2.4  endif
     2.5  
     2.6  ifeq ($(OPENPGP),GPG)
     2.7 -    NO_SOURCE+= pgp_netpgp.c
     2.8 +    NO_SOURCE+= pgp_netpgp.c pgp_sequoia.c
     2.9      CFLAGS+= -DUSE_GPG $(GPGME_INC) -DLIBGPGME=\"$(LIBGPGME)\"
    2.10      LDFLAGS+= $(GPGME_LIB)
    2.11      # No extra LDLIBS are needed here, because GPGME is dynamically loaded
    2.12  else ifeq ($(OPENPGP),NETPGP)
    2.13 -    NO_SOURCE+= pgp_gpg.c
    2.14 +    NO_SOURCE+= pgp_gpg.c pgp_sequoia.c
    2.15      CFLAGS+= -DUSE_NETPGP $(NETGPG_INC)
    2.16      LDFLAGS+= $(NETGPG_LIB)
    2.17      LDLIBS+= -lnetpgp -lcurl
    2.18 +else ifeq ($(OPENPGP),SEQUOIA)
    2.19 +    NO_SOURCE+= pgp_gpg.c pgp_netpgp.c
    2.20 +    CFLAGS+= -DUSE_SEQUOIA $(SEQUOIA_CFLAGS) $(SEQUOIA_INC)
    2.21 +    LDFLAGS+= $(SEQUOIA_LDFLAGS)
    2.22 +    LDLIBS+= $(SEQUOIA_LIB)
    2.23  else
    2.24      $(error Unknown OpenPGP library: $(OPENPGP))
    2.25  endif
     3.1 --- a/src/cryptotech.c	Sat Dec 15 17:00:09 2018 +0100
     3.2 +++ b/src/cryptotech.c	Sat Dec 15 17:03:46 2018 +0100
     3.3 @@ -8,6 +8,10 @@
     3.4  #else
     3.5  #ifdef USE_NETPGP
     3.6  #include "pgp_netpgp.h"
     3.7 +#else
     3.8 +#ifdef USE_SEQUOIA
     3.9 +#include "pgp_sequoia.h"
    3.10 +#endif
    3.11  #endif
    3.12  #endif
    3.13  // 
     4.1 --- a/src/openpgp_compat.h	Sat Dec 15 17:00:09 2018 +0100
     4.2 +++ b/src/openpgp_compat.h	Sat Dec 15 17:03:46 2018 +0100
     4.3 @@ -24,6 +24,10 @@
     4.4  #else
     4.5  #ifdef USE_NETPGP
     4.6  #include "pgp_netpgp.h"
     4.7 +#else
     4.8 +#ifdef USE_SEQUOIA
     4.9 +#include "pgp_sequoia.h"
    4.10 +#endif
    4.11  #endif
    4.12  #endif    
    4.13      
     5.1 --- a/src/pEp_internal.h	Sat Dec 15 17:00:09 2018 +0100
     5.2 +++ b/src/pEp_internal.h	Sat Dec 15 17:03:46 2018 +0100
     5.3 @@ -91,16 +91,20 @@
     5.4  #include "pEpEngine.h"
     5.5  
     5.6  // If not specified, build for GPG
     5.7 +#ifndef USE_SEQUOIA
     5.8  #ifndef USE_NETPGP
     5.9  #ifndef USE_GPG
    5.10  #define USE_GPG
    5.11  #endif
    5.12  #endif
    5.13 +#endif
    5.14  
    5.15  #ifdef USE_GPG
    5.16  #include "pgp_gpg_internal.h"
    5.17  #elif defined(USE_NETPGP)
    5.18  #include "pgp_netpgp_internal.h"
    5.19 +#elif defined(USE_SEQUOIA)
    5.20 +#include "pgp_sequoia_internal.h"
    5.21  #endif
    5.22  
    5.23  #include "keymanagement.h"
    5.24 @@ -123,6 +127,17 @@
    5.25      gpgme_ctx_t ctx;
    5.26  #elif defined(USE_NETPGP)
    5.27      pEpNetPGPSession ctx;
    5.28 +#elif defined(USE_SEQUOIA)
    5.29 +    sq_context_t ctx;
    5.30 +    sq_store_t store;
    5.31 +    sqlite3 *key_db;
    5.32 +    sqlite3_stmt *begin_transaction;
    5.33 +    sqlite3_stmt *commit_transaction;
    5.34 +    sqlite3_stmt *rollback_transaction;
    5.35 +    sqlite3_stmt *tsk_save_insert_primary;
    5.36 +    sqlite3_stmt *tsk_save_insert_subkeys;
    5.37 +    sqlite3_stmt *tsk_all;
    5.38 +    sqlite3_stmt *tsk_find_by_keyid;
    5.39  #endif
    5.40  
    5.41      PEP_cryptotech_t *cryptotech;
     6.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     6.2 +++ b/src/pgp_sequoia.c	Sat Dec 15 17:03:46 2018 +0100
     6.3 @@ -0,0 +1,2151 @@
     6.4 +// This file is under GNU General Public License 3.0
     6.5 +// see LICENSE.txt
     6.6 +
     6.7 +#define _GNU_SOURCE 1
     6.8 +
     6.9 +#include "platform.h"
    6.10 +#include "pEp_internal.h"
    6.11 +#include "pgp_gpg.h"
    6.12 +
    6.13 +#include <limits.h>
    6.14 +#include <sys/stat.h>
    6.15 +#include <sys/types.h>
    6.16 +#include <error.h>
    6.17 +
    6.18 +#include <sqlite3.h>
    6.19 +
    6.20 +#include "wrappers.h"
    6.21 +
    6.22 +// Set to 0 to disable tracing.
    6.23 +#if 1
    6.24 +#  define _T(...) do {                          \
    6.25 +        fprintf(stderr, ##__VA_ARGS__);         \
    6.26 +    } while (0)
    6.27 +#else
    6.28 +#  define _T(...) do { } while (0)
    6.29 +#endif
    6.30 +
    6.31 +// Show the start of a tracepoint (i.e., don't print a newline).
    6.32 +#define TC(...) do {       \
    6.33 +    _T("%s: ", __func__);  \
    6.34 +    _T(__VA_ARGS__);       \
    6.35 +} while (0)
    6.36 +
    6.37 +// Show a trace point.
    6.38 +#  define T(...) do {  \
    6.39 +    TC(__VA_ARGS__); \
    6.40 +    _T("\n");          \
    6.41 +} while(0)
    6.42 +
    6.43 +// Verbosely displays errors.
    6.44 +#  define DUMP_ERR(__de_session, __de_status, ...) do {             \
    6.45 +    TC(__VA_ARGS__);                                                \
    6.46 +    _T(": ");                                                       \
    6.47 +    if ((__de_session->ctx)) {                                      \
    6.48 +        sq_error_t __de_err                                         \
    6.49 +            = sq_context_last_error((__de_session->ctx));           \
    6.50 +        if (__de_err)                                               \
    6.51 +            _T("Sequoia: %s => ", sq_error_string(__de_err));       \
    6.52 +        sq_error_free(__de_err);                                    \
    6.53 +    }                                                               \
    6.54 +    _T("%s\n", pep_status_to_string(__de_status));                  \
    6.55 +} while(0)
    6.56 +
    6.57 +// If __ec_status is an error, then disable the error, set 'status' to
    6.58 +// it, and jump to 'out'.
    6.59 +#define ERROR_OUT(__e_session, __ec_status, ...) do {               \
    6.60 +    PEP_STATUS ___ec_status = (__ec_status);                        \
    6.61 +    if ((___ec_status) != PEP_STATUS_OK) {                          \
    6.62 +        DUMP_ERR((__e_session), (___ec_status), ##__VA_ARGS__);     \
    6.63 +        status = (___ec_status);                                    \
    6.64 +        goto out;                                                   \
    6.65 +    }                                                               \
    6.66 +} while(0)
    6.67 +
    6.68 +PEP_STATUS pgp_init(PEP_SESSION session, bool in_first)
    6.69 +{
    6.70 +    PEP_STATUS status = PEP_STATUS_OK;
    6.71 +
    6.72 +    sq_error_t err;
    6.73 +    session->ctx = sq_context_new("foundation.pep", &err);
    6.74 +    if (session->ctx == NULL)
    6.75 +        ERROR_OUT(session, PEP_INIT_GPGME_INIT_FAILED,
    6.76 +                  "initializing sequoia context");
    6.77 +
    6.78 +    session->store = sq_store_open(session->ctx, "foundation.pep");
    6.79 +    if (session->store == NULL)
    6.80 +        ERROR_OUT(session, PEP_INIT_GPGME_INIT_FAILED, "opening the store");
    6.81 +
    6.82 +
    6.83 +    // Create the home directory.
    6.84 +    char *home_env = getenv("HOME");
    6.85 +    if (!home_env)
    6.86 +        ERROR_OUT(session, PEP_INIT_GPGME_INIT_FAILED, "HOME unset");
    6.87 +
    6.88 +    // Create the DB and initialize it.
    6.89 +    char *path = NULL;
    6.90 +    asprintf(&path, "%s/.pEp_keys.db", home_env);
    6.91 +    if (!path)
    6.92 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
    6.93 +
    6.94 +    int sqlite_result;
    6.95 +    sqlite_result = sqlite3_open_v2(path,
    6.96 +                                    &session->key_db,
    6.97 +                                    SQLITE_OPEN_READWRITE
    6.98 +                                    | SQLITE_OPEN_CREATE
    6.99 +                                    | SQLITE_OPEN_FULLMUTEX
   6.100 +                                    | SQLITE_OPEN_PRIVATECACHE,
   6.101 +                                    NULL);
   6.102 +    free(path);
   6.103 +    if (sqlite_result != SQLITE_OK)
   6.104 +        ERROR_OUT(session, PEP_INIT_CANNOT_OPEN_DB,
   6.105 +                  "opening keys DB: %s",
   6.106 +                  sqlite3_errmsg(session->key_db));
   6.107 +
   6.108 +    sqlite_result = sqlite3_exec(session->key_db,
   6.109 +                                 "PRAGMA locking_mode=NORMAL;\n"
   6.110 +                                 "PRAGMA journal_mode=WAL;\n",
   6.111 +                                 NULL, NULL, NULL);
   6.112 +    if (sqlite_result != SQLITE_OK)
   6.113 +        ERROR_OUT(session, PEP_INIT_CANNOT_OPEN_DB,
   6.114 +                  "setting pragmas: %s", sqlite3_errmsg(session->key_db));
   6.115 +
   6.116 +    sqlite3_busy_timeout(session->key_db, BUSY_WAIT_TIME);
   6.117 +
   6.118 +    sqlite_result = sqlite3_exec(session->key_db,
   6.119 +                                 "CREATE TABLE IF NOT EXISTS keys (\n"
   6.120 +                                 "   primary_key TEXT PRIMARY KEY,\n"
   6.121 +                                 "   tsk BLOB\n"
   6.122 +                                 ");\n",
   6.123 +                                 NULL, NULL, NULL);
   6.124 +    if (sqlite_result != SQLITE_OK)
   6.125 +        ERROR_OUT(session, PEP_INIT_CANNOT_OPEN_DB,
   6.126 +                  "creating keys table: %s",
   6.127 +                  sqlite3_errmsg(session->key_db));
   6.128 +
   6.129 +    sqlite_result = sqlite3_exec(session->key_db,
   6.130 +                                 "CREATE TABLE IF NOT EXISTS subkeys (\n"
   6.131 +                                 "   subkey TEXT PRIMARY KEY,\n"
   6.132 +                                 "   primary_key TEXT,\n"
   6.133 +                                 "   FOREIGN KEY (primary_key)\n"
   6.134 +                                 "       REFERENCES keys(primary_key)\n"
   6.135 +                                 "     ON DELETE CASCADE\n"
   6.136 +                                 ");\n",
   6.137 +                                 NULL, NULL, NULL);
   6.138 +    if (sqlite_result != SQLITE_OK)
   6.139 +        ERROR_OUT(session, PEP_INIT_CANNOT_OPEN_DB,
   6.140 +                  "creating subkeys table: %s",
   6.141 +                  sqlite3_errmsg(session->key_db));
   6.142 +
   6.143 +    sqlite_result
   6.144 +        = sqlite3_prepare_v2(session->key_db, "begin transaction",
   6.145 +                             -1, &session->begin_transaction, NULL);
   6.146 +    assert(sqlite_result == SQLITE_OK);
   6.147 +
   6.148 +    sqlite_result
   6.149 +        = sqlite3_prepare_v2(session->key_db, "commit transaction",
   6.150 +                             -1, &session->commit_transaction, NULL);
   6.151 +    assert(sqlite_result == SQLITE_OK);
   6.152 +
   6.153 +    sqlite_result
   6.154 +        = sqlite3_prepare_v2(session->key_db, "rollback transaction",
   6.155 +                             -1, &session->rollback_transaction, NULL);
   6.156 +    assert(sqlite_result == SQLITE_OK);
   6.157 +
   6.158 +    sqlite_result
   6.159 +        = sqlite3_prepare_v2(session->key_db,
   6.160 +                             "INSERT OR REPLACE INTO keys"
   6.161 +                             "   (primary_key, tsk)"
   6.162 +                             " VALUES (?, ?)",
   6.163 +                             -1, &session->tsk_save_insert_primary, NULL);
   6.164 +    assert(sqlite_result == SQLITE_OK);
   6.165 +
   6.166 +    sqlite_result
   6.167 +        = sqlite3_prepare_v2(session->key_db,
   6.168 +                             "INSERT OR REPLACE INTO subkeys"
   6.169 +                             "   (subkey, primary_key)"
   6.170 +                             " VALUES (?, ?)",
   6.171 +                             -1, &session->tsk_save_insert_subkeys, NULL);
   6.172 +    assert(sqlite_result == SQLITE_OK);
   6.173 +
   6.174 +    sqlite_result
   6.175 +        = sqlite3_prepare_v2(session->key_db, "select tsk from keys",
   6.176 +                             -1, &session->tsk_all, NULL);
   6.177 +    assert(sqlite_result == SQLITE_OK);
   6.178 +
   6.179 +    sqlite_result
   6.180 +        = sqlite3_prepare_v2(session->key_db,
   6.181 +                             "SELECT keys.tsk FROM subkeys"
   6.182 +                             " LEFT JOIN keys"
   6.183 +                             "  ON subkeys.primary_key"
   6.184 +                             "     == keys.primary_key"
   6.185 +                             " WHERE subkey == ?",
   6.186 +                             -1, &session->tsk_find_by_keyid, NULL);
   6.187 +    assert(sqlite_result == SQLITE_OK);
   6.188 +
   6.189 + out:
   6.190 +    if (status != PEP_STATUS_OK)
   6.191 +        pgp_release(session, in_first);
   6.192 +    return status;
   6.193 +}
   6.194 +
   6.195 +void pgp_release(PEP_SESSION session, bool out_last)
   6.196 +{
   6.197 +    if (session->begin_transaction)
   6.198 +        sqlite3_finalize(session->begin_transaction);
   6.199 +    session->begin_transaction = NULL;
   6.200 +    if (session->commit_transaction)
   6.201 +        sqlite3_finalize(session->commit_transaction);
   6.202 +    session->commit_transaction = NULL;
   6.203 +    if (session->rollback_transaction)
   6.204 +        sqlite3_finalize(session->rollback_transaction);
   6.205 +    session->rollback_transaction = NULL;
   6.206 +    if (session->tsk_save_insert_primary)
   6.207 +        sqlite3_finalize(session->tsk_save_insert_primary);
   6.208 +    session->tsk_save_insert_primary = NULL;
   6.209 +    if (session->tsk_save_insert_subkeys)
   6.210 +        sqlite3_finalize(session->tsk_save_insert_subkeys);
   6.211 +    session->tsk_save_insert_subkeys = NULL;
   6.212 +    if (session->tsk_all)
   6.213 +        sqlite3_finalize(session->tsk_all);
   6.214 +    session->tsk_all = NULL;
   6.215 +    if (session->tsk_find_by_keyid)
   6.216 +        sqlite3_finalize(session->tsk_find_by_keyid);
   6.217 +    session->tsk_find_by_keyid = NULL;
   6.218 +
   6.219 +    if (session->key_db) {
   6.220 +        int result = sqlite3_close_v2(session->key_db);
   6.221 +        if (result != 0)
   6.222 +            DUMP_ERR(session, PEP_UNKNOWN_ERROR,
   6.223 +                     "Closing key DB: sqlite3_close_v2: %s",
   6.224 +                     sqlite3_errstr(result));
   6.225 +        session->key_db = NULL;
   6.226 +    }
   6.227 +
   6.228 +    if (session->store) {
   6.229 +        sq_store_free(session->store);
   6.230 +        session->store = NULL;
   6.231 +    }
   6.232 +
   6.233 +    if (session->ctx) {
   6.234 +        sq_context_free(session->ctx);
   6.235 +        session->ctx = NULL;
   6.236 +    }
   6.237 +}
   6.238 +
   6.239 +// Ensures that a fingerprint is in canonical form.  A canonical
   6.240 +// fingerprint doesn't contain any white space.
   6.241 +//
   6.242 +// This function does *not* consume fpr.
   6.243 +static char *sq_fingerprint_canonicalize(const char *) __attribute__((nonnull));
   6.244 +static char *sq_fingerprint_canonicalize(const char *fpr)
   6.245 +{
   6.246 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
   6.247 +    char *fpr_canonicalized = sq_fingerprint_to_hex(sq_fpr);
   6.248 +    sq_fingerprint_free(sq_fpr);
   6.249 +
   6.250 +    return fpr_canonicalized;
   6.251 +}
   6.252 +
   6.253 +// Splits an OpenPGP user id into its name and email components.  A
   6.254 +// user id looks like:
   6.255 +//
   6.256 +//   Name (comment) <email>
   6.257 +//
   6.258 +// This function takes ownership of user_id!!!
   6.259 +//
   6.260 +// namep and emailp may be NULL if they are not required.
   6.261 +static void user_id_split(char *, char **, char **) __attribute__((nonnull(1)));
   6.262 +static void user_id_split(char *user_id, char **namep, char **emailp)
   6.263 +{
   6.264 +    if (namep)
   6.265 +        *namep = NULL;
   6.266 +    if (emailp)
   6.267 +        *emailp = NULL;
   6.268 +
   6.269 +    char *email = strchr(user_id, '<');
   6.270 +    if (email) {
   6.271 +        // NUL terminate the string here so that user_id now points at
   6.272 +        // most to: "Name (comment)"
   6.273 +        *email = 0;
   6.274 +
   6.275 +        if (emailp && email[1]) {
   6.276 +            email = email + 1;
   6.277 +            char *end = strchr(email, '>');
   6.278 +            if (end) {
   6.279 +                *end = 0;
   6.280 +                *emailp = strdup(email);
   6.281 +            }
   6.282 +        }
   6.283 +    }
   6.284 +
   6.285 +    if (!namep)
   6.286 +        return;
   6.287 +
   6.288 +    char *comment = strchr(user_id, '(');
   6.289 +    if (comment)
   6.290 +        *comment = 0;
   6.291 +
   6.292 +    // Kill any trailing white space.
   6.293 +    for (size_t l = strlen(user_id); l > 0 && user_id[l - 1] == ' '; l --)
   6.294 +        user_id[l - 1] = 0;
   6.295 +
   6.296 +    // Kill any leading whitespace.
   6.297 +    char *start = user_id;
   6.298 +    while (*start == ' ')
   6.299 +        start ++;
   6.300 +    if (start[0])
   6.301 +        *namep = strdup(start);
   6.302 +
   6.303 +    free(user_id);
   6.304 +}
   6.305 +
   6.306 +
   6.307 +// Returns the TSK identified by the provided keyid.
   6.308 +//
   6.309 +// If tsk is NULL, the TSK is not parsed and this function simply
   6.310 +// returns whether the key is locally available.
   6.311 +static PEP_STATUS tsk_find_by_keyid_hex(PEP_SESSION, const char *, sq_tsk_t *)
   6.312 +  __attribute__((nonnull(1, 2)));
   6.313 +static PEP_STATUS tsk_find_by_keyid_hex(
   6.314 +        PEP_SESSION session,
   6.315 +        const char *keyid_hex,
   6.316 +        sq_tsk_t *tsk)
   6.317 +{
   6.318 +    PEP_STATUS status = PEP_STATUS_OK;
   6.319 +    T("%s", keyid_hex);
   6.320 +
   6.321 +    sqlite3_stmt *stmt = session->tsk_find_by_keyid;
   6.322 +    sqlite3_bind_text(stmt, 1, keyid_hex, -1, SQLITE_STATIC);
   6.323 +    int sqlite_result = sqlite3_step(stmt);
   6.324 +    switch (sqlite_result) {
   6.325 +    case SQLITE_ROW:
   6.326 +        if (tsk) {
   6.327 +            // Get the TSK from the first column.
   6.328 +            int data_len = sqlite3_column_bytes(stmt, 0);
   6.329 +            const void *data = sqlite3_column_blob(stmt, 0);
   6.330 +
   6.331 +            sq_tpk_t tpk = sq_tpk_from_bytes(session->ctx, data, data_len);
   6.332 +            if (!tpk)
   6.333 +                ERROR_OUT(session, PEP_GET_KEY_FAILED, "parsing TPK");
   6.334 +
   6.335 +            *tsk = sq_tpk_into_tsk(tpk);
   6.336 +        }
   6.337 +        break;
   6.338 +    case SQLITE_DONE:
   6.339 +        // Got nothing.
   6.340 +        status = PEP_KEY_NOT_FOUND;
   6.341 +        break;
   6.342 +    default:
   6.343 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   6.344 +                  "stepping tsk_find_by_keyid: %s",
   6.345 +                  sqlite3_errmsg(session->key_db));
   6.346 +    }
   6.347 +
   6.348 + out:
   6.349 +    sqlite3_reset(stmt);
   6.350 +    T("%s -> %s", keyid_hex, pep_status_to_string(status));
   6.351 +    return status;
   6.352 +}
   6.353 +
   6.354 +// See tsk_find_by_keyid_hex.
   6.355 +PEP_STATUS tsk_find_by_keyid(PEP_SESSION, sq_keyid_t, sq_tsk_t *)
   6.356 +    __attribute__((nonnull(1, 2)));
   6.357 +PEP_STATUS tsk_find_by_keyid(
   6.358 +        PEP_SESSION session, sq_keyid_t keyid, sq_tsk_t *tsk)
   6.359 +{
   6.360 +    char *keyid_hex = sq_keyid_to_hex(keyid);
   6.361 +    if (! keyid_hex)
   6.362 +        return PEP_OUT_OF_MEMORY;
   6.363 +    PEP_STATUS status = tsk_find_by_keyid_hex(session, keyid_hex, tsk);
   6.364 +    free(keyid_hex);
   6.365 +    return status;
   6.366 +}
   6.367 +
   6.368 +// See tsk_find_by_keyid_hex.
   6.369 +static PEP_STATUS tsk_find_by_fpr(PEP_SESSION, sq_fingerprint_t, sq_tsk_t *)
   6.370 +    __attribute__((nonnull(1, 2)));
   6.371 +static PEP_STATUS tsk_find_by_fpr(
   6.372 +        PEP_SESSION session, sq_fingerprint_t fpr, sq_tsk_t *tsk)
   6.373 +{
   6.374 +    sq_keyid_t keyid = sq_fingerprint_to_keyid(fpr);
   6.375 +    if (! keyid)
   6.376 +        return PEP_OUT_OF_MEMORY;
   6.377 +    PEP_STATUS status = tsk_find_by_keyid(session, keyid, tsk);
   6.378 +    sq_keyid_free(keyid);
   6.379 +    return status;
   6.380 +}
   6.381 +
   6.382 +// See tsk_find_by_keyid_hex.
   6.383 +static PEP_STATUS tsk_find_by_fpr_hex(PEP_SESSION, const char *, sq_tsk_t *)
   6.384 +    __attribute__((nonnull(1, 2)));
   6.385 +static PEP_STATUS tsk_find_by_fpr_hex(
   6.386 +        PEP_SESSION session, const char *fpr, sq_tsk_t *tsk)
   6.387 +{
   6.388 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
   6.389 +    if (! sq_fpr)
   6.390 +        return PEP_OUT_OF_MEMORY;
   6.391 +    PEP_STATUS status = tsk_find_by_fpr(session, sq_fpr, tsk);
   6.392 +    sq_fingerprint_free(sq_fpr);
   6.393 +    return status;
   6.394 +}
   6.395 +
   6.396 +
   6.397 +// Saves the specified TSK.
   6.398 +//
   6.399 +// This function takes ownership of TSK.
   6.400 +static PEP_STATUS tsk_save(PEP_SESSION, sq_tsk_t) __attribute__((nonnull));
   6.401 +static PEP_STATUS tsk_save(PEP_SESSION session, sq_tsk_t tsk)
   6.402 +{
   6.403 +    PEP_STATUS status = PEP_STATUS_OK;
   6.404 +    sq_fingerprint_t sq_fpr = NULL;
   6.405 +    char *fpr = NULL;
   6.406 +    void *tsk_buffer = NULL;
   6.407 +    size_t tsk_buffer_len = 0;
   6.408 +    int tried_commit = 0;
   6.409 +    sq_tpk_t tpk = sq_tsk_tpk(tsk); /* Reference. */
   6.410 +    sq_tpk_key_iter_t key_iter = NULL;
   6.411 +
   6.412 +    sq_fpr = sq_tpk_fingerprint(tpk);
   6.413 +    fpr = sq_fingerprint_to_hex(sq_fpr);
   6.414 +    T("%s", fpr);
   6.415 +
   6.416 +    // Merge any existing data into TSK.
   6.417 +    sq_tsk_t current = NULL;
   6.418 +    status = tsk_find_by_fpr(session, sq_fpr, &current);
   6.419 +    if (status == PEP_KEY_NOT_FOUND)
   6.420 +        status = PEP_STATUS_OK;
   6.421 +    else
   6.422 +        ERROR_OUT(session, status, "Looking up %s", fpr);
   6.423 +    if (current) {
   6.424 +        tpk = sq_tpk_merge(session->ctx,
   6.425 +                           sq_tsk_into_tpk(tsk), sq_tsk_into_tpk(current));
   6.426 +        tsk = sq_tpk_into_tsk(tpk);
   6.427 +        tpk = sq_tsk_tpk(tsk);
   6.428 +    }
   6.429 +
   6.430 +
   6.431 +    // Serialize it.
   6.432 +    sq_writer_t writer = sq_writer_alloc(&tsk_buffer, &tsk_buffer_len);
   6.433 +    if (! writer)
   6.434 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
   6.435 +
   6.436 +    sq_status_t sq_status = sq_tsk_serialize(session->ctx, tsk, writer);
   6.437 +    //sq_writer_free(writer);
   6.438 +    if (sq_status != 0)
   6.439 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Serializing TSK");
   6.440 +
   6.441 +
   6.442 +    // Insert the TSK into the DB.
   6.443 +    sqlite3_stmt *stmt = session->begin_transaction;
   6.444 +    int sqlite_result = sqlite3_step(stmt);
   6.445 +    sqlite3_reset(stmt);
   6.446 +    if (sqlite_result != SQLITE_DONE)
   6.447 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   6.448 +                  "begin transaction failed: %s",
   6.449 +                  sqlite3_errmsg(session->key_db));
   6.450 +
   6.451 +    stmt = session->tsk_save_insert_primary;
   6.452 +    sqlite3_bind_text(stmt, 1, fpr, -1, SQLITE_STATIC);
   6.453 +    sqlite3_bind_blob(stmt, 2, tsk_buffer, tsk_buffer_len, SQLITE_STATIC);
   6.454 +
   6.455 +    sqlite_result = sqlite3_step(stmt);
   6.456 +    sqlite3_reset(stmt);
   6.457 +    if (sqlite_result != SQLITE_DONE)
   6.458 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   6.459 +                  "Saving TSK to DB: %s",
   6.460 +                  sqlite3_errmsg(session->key_db));
   6.461 +
   6.462 +    // Insert the "subkeys" (the primary key and the subkeys).
   6.463 +    stmt = session->tsk_save_insert_subkeys;
   6.464 +    key_iter = sq_tpk_key_iter(tpk);
   6.465 +    sq_p_key_t key;
   6.466 +    while ((key = sq_tpk_key_iter_next(key_iter, NULL, NULL))) {
   6.467 +        sq_keyid_t keyid = sq_p_key_keyid(key);
   6.468 +        char *keyid_hex = sq_keyid_to_hex(keyid);
   6.469 +        T("  subkey: %s", keyid_hex);
   6.470 +        sqlite3_bind_text(stmt, 1, keyid_hex, -1, SQLITE_STATIC);
   6.471 +        sqlite3_bind_text(stmt, 2, fpr, -1, SQLITE_STATIC);
   6.472 +
   6.473 +        sqlite_result = sqlite3_step(stmt);
   6.474 +        sqlite3_reset(stmt);
   6.475 +        free(keyid_hex);
   6.476 +        sq_keyid_free(keyid);
   6.477 +        if (sqlite_result != SQLITE_DONE) {
   6.478 +            sq_tpk_key_iter_free(key_iter);
   6.479 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   6.480 +                      "Updating subkeys: %s", sqlite3_errmsg(session->key_db));
   6.481 +        }
   6.482 +    }
   6.483 +    sq_tpk_key_iter_free(key_iter);
   6.484 +    key_iter = NULL;
   6.485 +
   6.486 + out:
   6.487 +    // Prevent ERROR_OUT from causing an infinite loop.
   6.488 +    if (! tried_commit) {
   6.489 +        tried_commit = 1;
   6.490 +        stmt = status == PEP_STATUS_OK
   6.491 +            ? session->commit_transaction : session->rollback_transaction;
   6.492 +        int sqlite_result = sqlite3_step(stmt);
   6.493 +        sqlite3_reset(stmt);
   6.494 +        if (sqlite_result != SQLITE_DONE)
   6.495 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   6.496 +                      status == PEP_STATUS_OK
   6.497 +                      ? "commit failed: %s" : "rollback failed: %s",
   6.498 +                      sqlite3_errmsg(session->key_db));
   6.499 +    }
   6.500 +
   6.501 +    T("(%s) -> %s", fpr, pep_status_to_string(status));
   6.502 +
   6.503 +    if (key_iter)
   6.504 +        sq_tpk_key_iter_free(key_iter);
   6.505 +    if (stmt)
   6.506 +      sqlite3_reset(stmt);
   6.507 +    free(tsk_buffer);
   6.508 +    sq_tsk_free(tsk);
   6.509 +    free(fpr);
   6.510 +    sq_fingerprint_free(sq_fpr);
   6.511 +
   6.512 +    return status;
   6.513 +}
   6.514 +
   6.515 +// Returns all known TSKs.
   6.516 +static PEP_STATUS tsk_all(PEP_SESSION, sq_tsk_t **, int *) __attribute__((nonnull));
   6.517 +static PEP_STATUS tsk_all(PEP_SESSION session, sq_tsk_t **tsksp, int *tsks_countp) {
   6.518 +    PEP_STATUS status = PEP_STATUS_OK;
   6.519 +
   6.520 +    int tsks_count = 0;
   6.521 +    int tsks_capacity = 8;
   6.522 +    sq_tsk_t *tsks = calloc(tsks_capacity, sizeof(sq_tsk_t));
   6.523 +    if (!tsks)
   6.524 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
   6.525 +
   6.526 +    sqlite3_stmt *stmt = session->tsk_all;
   6.527 +    while (true) {
   6.528 +        switch (sqlite3_step(stmt)) {
   6.529 +        case SQLITE_ROW: {
   6.530 +            int data_len = sqlite3_column_bytes(stmt, 0);
   6.531 +            const void *data = sqlite3_column_blob(stmt, 0);
   6.532 +            sq_tpk_t tpk = sq_tpk_from_bytes(session->ctx, data, data_len);
   6.533 +            if (!tpk) {
   6.534 +                ERROR_OUT(session, PEP_GET_KEY_FAILED, "parsing TSK");
   6.535 +            } else {
   6.536 +                if (tsks_count == tsks_capacity) {
   6.537 +                    tsks_capacity *= 2;
   6.538 +                    tsks = realloc(tsks, sizeof(tsks[0]) * tsks_capacity);
   6.539 +                    if (!tsks)
   6.540 +                        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "tsks");
   6.541 +                }
   6.542 +                tsks[tsks_count ++] = sq_tpk_into_tsk(tpk);
   6.543 +            }
   6.544 +            break;
   6.545 +        }
   6.546 +        default:
   6.547 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   6.548 +                      "stepping sqlite statement: %s",
   6.549 +                      sqlite3_errmsg(session->key_db));
   6.550 +        case SQLITE_DONE:
   6.551 +            goto out;
   6.552 +        }
   6.553 +    }
   6.554 +
   6.555 + out:
   6.556 +    sqlite3_reset(stmt);
   6.557 +
   6.558 +    if (status != PEP_STATUS_OK) {
   6.559 +        for (int i = 0; i < tsks_count; i ++)
   6.560 +            sq_tsk_free(tsks[i]);
   6.561 +        free(tsks);
   6.562 +    } else {
   6.563 +        *tsksp = tsks;
   6.564 +        *tsks_countp = tsks_count;
   6.565 +    }
   6.566 +
   6.567 +    return status;
   6.568 +}
   6.569 +
   6.570 +// Returns the key with the label LABEL.
   6.571 +//
   6.572 +// The return is returned in *KEY and must be freed using sq_tpk_free.
   6.573 +//
   6.574 +// Note: we maintain labels for the fingerprint of primary keys, pep
   6.575 +// user ids, and email addresses.  If you want to look something up by
   6.576 +// subkey id, use tpk_find_by_keyid.
   6.577 +static PEP_STATUS tpk_find_by_label(PEP_SESSION, const char *, sq_tpk_t *)
   6.578 +    __attribute__((nonnull));
   6.579 +static PEP_STATUS tpk_find_by_label(PEP_SESSION session, const char *label, sq_tpk_t *tpk)
   6.580 +{
   6.581 +    PEP_STATUS status = PEP_STATUS_OK;
   6.582 +
   6.583 +    sq_binding_t binding
   6.584 +        = sq_store_lookup(session->ctx, session->store, label);
   6.585 +    if (!binding)
   6.586 +        ERROR_OUT(session, PEP_KEY_NOT_FOUND, "looking up label %s", label);
   6.587 +
   6.588 +    *tpk = sq_binding_tpk(session->ctx, binding);
   6.589 +    if (!*tpk)
   6.590 +        ERROR_OUT(session, PEP_GET_KEY_FAILED, "getting TPK");
   6.591 +
   6.592 + out:
   6.593 +    if (binding)
   6.594 +        sq_binding_free(binding);
   6.595 +
   6.596 +    return status;
   6.597 +}
   6.598 +
   6.599 +// Returns the key with keyid KEYID.
   6.600 +//
   6.601 +// Note: this function will match both the primary key as well as any
   6.602 +// subkeys.
   6.603 +static PEP_STATUS tpk_find_by_keyid(PEP_SESSION, sq_keyid_t, sq_tpk_t *)
   6.604 +    __attribute__((nonnull));
   6.605 +static PEP_STATUS tpk_find_by_keyid(PEP_SESSION session, sq_keyid_t keyid,
   6.606 +                                    sq_tpk_t *tpk)
   6.607 +{
   6.608 +    PEP_STATUS status = PEP_STATUS_OK;
   6.609 +    char *keyid_hex = sq_keyid_to_hex(keyid);
   6.610 +
   6.611 +    sq_key_t key = sq_store_lookup_by_subkeyid(session->ctx, keyid);
   6.612 +    if (!key)
   6.613 +        ERROR_OUT(session, PEP_KEY_NOT_FOUND,
   6.614 +                  "looking up key by keyid %s", keyid_hex);
   6.615 +
   6.616 +    *tpk = sq_key_tpk(session->ctx, key);
   6.617 +    if (!*tpk)
   6.618 +        ERROR_OUT(session, PEP_GET_KEY_FAILED, "getting TPK");
   6.619 +
   6.620 + out:
   6.621 +    free(keyid_hex);
   6.622 +
   6.623 +    return status;
   6.624 +}
   6.625 +
   6.626 +// Returns the key with fingerprint FPR.
   6.627 +//
   6.628 +// Note: this function will match both the primary key as well as any
   6.629 +// subkeys.
   6.630 +static PEP_STATUS tpk_find_by_fpr(PEP_SESSION, sq_fingerprint_t, sq_tpk_t *)
   6.631 +    __attribute__((nonnull));
   6.632 +static PEP_STATUS tpk_find_by_fpr(PEP_SESSION session, sq_fingerprint_t fpr,
   6.633 +                                  sq_tpk_t *tpk)
   6.634 +{
   6.635 +    sq_keyid_t keyid = sq_fingerprint_to_keyid(fpr);
   6.636 +    PEP_STATUS status = tpk_find_by_keyid(session, keyid, tpk);
   6.637 +    sq_keyid_free(keyid);
   6.638 +    return status;
   6.639 +}
   6.640 +
   6.641 +
   6.642 +
   6.643 +// Saves a TPK.
   6.644 +//
   6.645 +// Creates labels under the fingerprint, address (if not NULL), and
   6.646 +// the email address in each user id.
   6.647 +//
   6.648 +// If there are any keys with private key material, saves that
   6.649 +// information in private_idents (if not NULL).
   6.650 +//
   6.651 +// This function takes ownership of the tpk.
   6.652 +static PEP_STATUS tpk_save(PEP_SESSION, sq_tpk_t, const char *,
   6.653 +                           identity_list **, int)
   6.654 +  __attribute__((nonnull(1, 2)));
   6.655 +static PEP_STATUS tpk_save(PEP_SESSION session, sq_tpk_t tpk,
   6.656 +                           const char *address, identity_list **private_idents,
   6.657 +                           int replace_bindings)
   6.658 +{
   6.659 +    PEP_STATUS status = PEP_STATUS_OK;
   6.660 +    sq_user_id_binding_iter_t iter = NULL;
   6.661 +    sq_user_id_binding_t user_id_binding = NULL;
   6.662 +
   6.663 +    if (private_idents)
   6.664 +        *private_idents = NULL;
   6.665 +
   6.666 +    sq_fingerprint_t sq_fpr = sq_tpk_fingerprint(tpk);
   6.667 +    char *fpr = sq_fingerprint_to_hex(sq_fpr);
   6.668 +    T("(%s)", fpr);
   6.669 +
   6.670 +    // Import the public part in the store.  If it was already present
   6.671 +    // in the store, it will be merged.  We don't work with the merged
   6.672 +    // TPK, because we only care about new user ids.
   6.673 +    sq_tpk_t merged = sq_store_import(session->ctx, session->store, fpr, tpk);
   6.674 +    if (! merged)
   6.675 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Merging TPK (%s)", fpr);
   6.676 +    sq_tpk_free(merged);
   6.677 +
   6.678 +    // Add the pep user id label.
   6.679 +    if (address) {
   6.680 +        int first_try = 1;
   6.681 +        sq_binding_t binding;
   6.682 +
   6.683 +    make_address_binding:
   6.684 +        binding = sq_store_add(session->ctx, session->store, address, sq_fpr);
   6.685 +        if (! binding) {
   6.686 +            // An error occured.  There's a good chance this is
   6.687 +            // because the binding already exists.
   6.688 +            if (replace_bindings && first_try) {
   6.689 +                T("replacing userid binding %s -> %s", address, fpr);
   6.690 +
   6.691 +                // We should replace the existing binding.
   6.692 +                binding = sq_store_lookup(session->ctx, session->store, address);
   6.693 +                if (binding) {
   6.694 +                    if (sq_binding_delete(session->ctx, binding)) {
   6.695 +                        DUMP_ERR(session, PEP_STATUS_OK,
   6.696 +                                 "Delete binding %s", address);
   6.697 +                        sq_binding_free(binding);
   6.698 +                    }
   6.699 +
   6.700 +                    first_try = 0;
   6.701 +                    goto make_address_binding;
   6.702 +                }
   6.703 +            }
   6.704 +
   6.705 +            // This is a soft error: we always prefer the existing
   6.706 +            // binding.
   6.707 +            DUMP_ERR(session, PEP_STATUS_OK,
   6.708 +                     "Creating userid binding %s -> %s", address, fpr);
   6.709 +        } else {
   6.710 +            sq_binding_free(binding);
   6.711 +        }
   6.712 +    }
   6.713 +
   6.714 +    // Create a binding for each user id.
   6.715 +    //
   6.716 +    // Note: the iterator only returns valid user ids in the sense
   6.717 +    // that the user id has a self-signature or a self-revocation
   6.718 +    // certificate.
   6.719 +    int first = 1;
   6.720 +    iter = sq_tpk_user_id_binding_iter(tpk);
   6.721 +    while ((user_id_binding = sq_user_id_binding_iter_next(iter))) {
   6.722 +        char *user_id = sq_user_id_binding_user_id(user_id_binding);
   6.723 +        if (!user_id) {
   6.724 +            // Completely ignore insane user ids (those with interior
   6.725 +            // NUL bytes).
   6.726 +            free(user_id);
   6.727 +            continue;
   6.728 +        }
   6.729 +
   6.730 +        // Ignore bindings with a self-revocation certificate, but no
   6.731 +        // self-signature.
   6.732 +        if (!sq_user_id_binding_selfsig(user_id_binding)) {
   6.733 +            free(user_id);
   6.734 +            continue;
   6.735 +        }
   6.736 +
   6.737 +        char *name, *email;
   6.738 +        user_id_split(user_id, &name, &email); /* user_id is comsumed.  */
   6.739 +
   6.740 +        if (email) {
   6.741 +            int first_try = 1;
   6.742 +            sq_binding_t binding;
   6.743 +
   6.744 +        make_email_binding:
   6.745 +            binding = sq_store_add(session->ctx, session->store, email, sq_fpr);
   6.746 +            if (! binding) {
   6.747 +                // An error occured.  There's a good chance this is
   6.748 +                // because the binding already exists.
   6.749 +                if (replace_bindings && first_try) {
   6.750 +                    // We should replace the existing binding.
   6.751 +                    binding = sq_store_lookup(session->ctx, session->store, email);
   6.752 +                    if (binding) {
   6.753 +                        if (sq_binding_delete(session->ctx, binding)) {
   6.754 +                            DUMP_ERR(session, PEP_STATUS_OK,
   6.755 +                                     "Delete binding %s", email);
   6.756 +                            sq_binding_free(binding);
   6.757 +                        }
   6.758 +
   6.759 +                        first_try = 0;
   6.760 +                        goto make_email_binding;
   6.761 +                    }
   6.762 +                }
   6.763 +
   6.764 +                // This is a soft error: we always prefer the existing
   6.765 +                // binding.
   6.766 +                DUMP_ERR(session, PEP_UNKNOWN_ERROR,
   6.767 +                         "Creating email binding: %s -> %s", email, fpr);
   6.768 +            } else {
   6.769 +                sq_binding_free(binding);
   6.770 +            }
   6.771 +
   6.772 +            if (first && private_idents && sq_tpk_is_tsk(tpk)) {
   6.773 +                first = 0;
   6.774 +
   6.775 +                // Create an identity for the primary user id.
   6.776 +                pEp_identity *ident = new_identity(email, fpr, NULL, name);
   6.777 +                if (ident == NULL)
   6.778 +                    ERROR_OUT(session, PEP_OUT_OF_MEMORY, "new_identity");
   6.779 +
   6.780 +                *private_idents = identity_list_add(*private_idents, ident);
   6.781 +                if (*private_idents == NULL)
   6.782 +                    ERROR_OUT(session, PEP_OUT_OF_MEMORY, "identity_list_add");
   6.783 +            }
   6.784 +        }
   6.785 +    }
   6.786 +
   6.787 +    sq_user_id_binding_iter_free(iter);
   6.788 +    iter = NULL;
   6.789 +
   6.790 +    // If it has any private key material, save it in the TSK store.
   6.791 +    if (sq_tpk_is_tsk(tpk)) {
   6.792 +        status = tsk_save(session, sq_tpk_into_tsk(tpk));
   6.793 +        tpk = NULL;
   6.794 +        ERROR_OUT(session, status, "Saving TSK");
   6.795 +    }
   6.796 +
   6.797 + out:
   6.798 +    T("(%s) -> %s", fpr, pep_status_to_string(status));
   6.799 +
   6.800 +    if (iter)
   6.801 +        sq_user_id_binding_iter_free(iter);
   6.802 +    free(fpr);
   6.803 +    if (sq_fpr)
   6.804 +        sq_fingerprint_free(sq_fpr);
   6.805 +    if (tpk)
   6.806 +        sq_tpk_free(tpk);
   6.807 +
   6.808 +    return status;
   6.809 +}
   6.810 +
   6.811 +struct decrypt_cookie {
   6.812 +    PEP_SESSION session;
   6.813 +    int get_secret_keys_called;
   6.814 +    stringlist_t *recipient_keylist;
   6.815 +    stringlist_t *signer_keylist;
   6.816 +    int good_checksums;
   6.817 +    int missing_keys;
   6.818 +    int bad_checksums;
   6.819 +    int decrypted;
   6.820 +};
   6.821 +
   6.822 +static sq_status_t
   6.823 +get_public_keys_cb(void *cookie_raw,
   6.824 +                   sq_keyid_t *keyids, size_t keyids_len,
   6.825 +                   sq_tpk_t **tpks, size_t *tpk_len,
   6.826 +                   void (**our_free)(void *))
   6.827 +{
   6.828 +    struct decrypt_cookie *cookie = cookie_raw;
   6.829 +    PEP_SESSION session = cookie->session;
   6.830 +
   6.831 +    *tpks = calloc(keyids_len, sizeof(*tpks));
   6.832 +    if (!*tpks)
   6.833 +        return SQ_STATUS_UNKNOWN_ERROR;
   6.834 +    *our_free = free;
   6.835 +
   6.836 +    int i, j;
   6.837 +    j = 0;
   6.838 +    for (i = 0; i < keyids_len; i ++) {
   6.839 +        sq_tpk_t tpk = NULL;
   6.840 +        sq_status_t status = tpk_find_by_keyid(session, keyids[i], &tpk);
   6.841 +        if (status == SQ_STATUS_SUCCESS)
   6.842 +            (*tpks)[j ++] = tpk;
   6.843 +    }
   6.844 +    *tpk_len = j;
   6.845 +    return SQ_STATUS_SUCCESS;
   6.846 +}
   6.847 +
   6.848 +static sq_status_t
   6.849 +get_secret_keys_cb(void *cookie_opaque,
   6.850 +                   sq_pkesk_t *pkesks, size_t pkesk_count,
   6.851 +                   sq_skesk_t *skesks, size_t skesk_count,
   6.852 +                   sq_secret_t *secret)
   6.853 +{
   6.854 +    struct decrypt_cookie *cookie = cookie_opaque;
   6.855 +    PEP_SESSION session = cookie->session;
   6.856 +    sq_tsk_t *tsks = NULL;
   6.857 +    int tsks_count = 0;
   6.858 +    int wildcards = 0;
   6.859 +
   6.860 +    if (cookie->get_secret_keys_called)
   6.861 +        // Prevent iterations, which isn't needed since we don't
   6.862 +        // support SKESKs.
   6.863 +        return SQ_STATUS_UNKNOWN_ERROR;
   6.864 +    cookie->get_secret_keys_called = 1;
   6.865 +
   6.866 +    T("%zd PKESKs", pkesk_count);
   6.867 +
   6.868 +    for (int i = 0; i < pkesk_count; i ++) {
   6.869 +        sq_pkesk_t pkesk = pkesks[i];
   6.870 +        sq_keyid_t keyid = sq_pkesk_recipient(pkesk); /* Reference. */
   6.871 +        char *keyid_str = sq_keyid_to_hex(keyid);
   6.872 +        sq_tpk_key_iter_t key_iter = NULL;
   6.873 +
   6.874 +        T("Considering PKESK for %s", keyid_str);
   6.875 +
   6.876 +        if (strcmp(keyid_str, "0000000000000000") == 0) {
   6.877 +            // Initially ignore wildcards.
   6.878 +            wildcards = 1;
   6.879 +            goto eol;
   6.880 +        }
   6.881 +
   6.882 +        // Collect the recipients.  Note: we must return the primary
   6.883 +        // key's fingerprint.
   6.884 +        sq_tpk_t tpk = NULL;
   6.885 +        if (tpk_find_by_keyid(session, keyid, &tpk) == PEP_STATUS_OK) {
   6.886 +            sq_fingerprint_t fp = sq_tpk_fingerprint(tpk);
   6.887 +            char *fp_string = sq_fingerprint_to_hex(fp);
   6.888 +            stringlist_add_unique(cookie->recipient_keylist, fp_string);
   6.889 +            free(fp_string);
   6.890 +            sq_fingerprint_free(fp);
   6.891 +            sq_tpk_free(tpk);
   6.892 +        }
   6.893 +
   6.894 +        if (cookie->decrypted)
   6.895 +            goto eol;
   6.896 +
   6.897 +        // See if we have the secret key.
   6.898 +        sq_tsk_t tsk = NULL;
   6.899 +        PEP_STATUS s = tsk_find_by_keyid(cookie->session, keyid, &tsk);
   6.900 +        if (s != PEP_STATUS_OK) {
   6.901 +            if (s != PEP_KEY_NOT_FOUND)
   6.902 +                DUMP_ERR(cookie->session, s, "Parsing key %s", keyid_str);
   6.903 +            else
   6.904 +                T("No secret key material for %s", keyid_str);
   6.905 +            goto eol;
   6.906 +        }
   6.907 +
   6.908 +        tpk = sq_tsk_tpk(tsk);
   6.909 +        key_iter = sq_tpk_key_iter(tpk);
   6.910 +        sq_p_key_t key;
   6.911 +        while ((key = sq_tpk_key_iter_next(key_iter, NULL, NULL))) {
   6.912 +            sq_keyid_t this_keyid = sq_p_key_keyid(key);
   6.913 +            char *this_keyid_hex = sq_keyid_to_hex(this_keyid);
   6.914 +            sq_keyid_free(this_keyid);
   6.915 +
   6.916 +            int match = strcmp(keyid_str, this_keyid_hex) == 0;
   6.917 +            free(this_keyid_hex);
   6.918 +            if (match)
   6.919 +                break;
   6.920 +        }
   6.921 +
   6.922 +        if (key == NULL)
   6.923 +            assert(!"Inconsistent DB: key doesn't contain a subkey with keyid!");
   6.924 +
   6.925 +        uint8_t algo;
   6.926 +        uint8_t session_key[1024];
   6.927 +        size_t session_key_len = sizeof(session_key);
   6.928 +        if (sq_pkesk_decrypt(cookie->session->ctx,
   6.929 +                             pkesk, key, &algo,
   6.930 +                             session_key, &session_key_len) != 0) {
   6.931 +            DUMP_ERR(session, PEP_UNKNOWN_ERROR, "sq_pkesk_decrypt");
   6.932 +            goto eol;
   6.933 +        }
   6.934 +
   6.935 +        T("Decrypted PKESK for %s", keyid_str);
   6.936 +
   6.937 +        *secret = sq_secret_cached(algo, session_key, session_key_len);
   6.938 +        cookie->decrypted = 1;
   6.939 +
   6.940 +    eol:
   6.941 +        free(keyid_str);
   6.942 +        if (key_iter)
   6.943 +            sq_tpk_key_iter_free(key_iter);
   6.944 +    }
   6.945 +
   6.946 +    // Consider wildcard recipients.
   6.947 +    if (wildcards) for (int i = 0; i < pkesk_count && !cookie->decrypted; i ++) {
   6.948 +        sq_pkesk_t pkesk = pkesks[i];
   6.949 +        sq_keyid_t keyid = sq_pkesk_recipient(pkesk); /* Reference. */
   6.950 +        char *keyid_str = sq_keyid_to_hex(keyid);
   6.951 +        sq_tpk_key_iter_t key_iter = NULL;
   6.952 +
   6.953 +        if (strcmp(keyid_str, "0000000000000000") != 0)
   6.954 +            goto eol2;
   6.955 +
   6.956 +        if (!tsks) {
   6.957 +            if (tsk_all(session, &tsks, &tsks_count) != PEP_STATUS_OK) {
   6.958 +                DUMP_ERR(session, PEP_UNKNOWN_ERROR, "Getting all tsks");
   6.959 +            }
   6.960 +        }
   6.961 +
   6.962 +        for (int j = 0; j < tsks_count; j ++) {
   6.963 +            sq_tpk_t tpk = sq_tsk_tpk(tsks[j]);
   6.964 +
   6.965 +            key_iter = sq_tpk_key_iter(tpk);
   6.966 +            sq_p_key_t key;
   6.967 +            sq_signature_t selfsig;
   6.968 +            while ((key = sq_tpk_key_iter_next(key_iter, &selfsig, NULL))) {
   6.969 +                if (! (sq_signature_can_encrypt_at_rest(selfsig)
   6.970 +                       || sq_signature_can_encrypt_for_transport(selfsig)))
   6.971 +                    continue;
   6.972 +
   6.973 +                // Note: for decryption to appear to succeed, we must
   6.974 +                // get a valid algorithm (8 of 256 values) and a
   6.975 +                // 16-bit checksum must match.  Thus, we have about a
   6.976 +                // 1 in 2**21 chance of having a false positive here.
   6.977 +                uint8_t algo;
   6.978 +                uint8_t session_key[1024];
   6.979 +                size_t session_key_len = sizeof(session_key);
   6.980 +                if (sq_pkesk_decrypt(cookie->session->ctx, pkesk, key,
   6.981 +                                     &algo, session_key, &session_key_len))
   6.982 +                    continue;
   6.983 +
   6.984 +                // Add it to the recipient list.
   6.985 +                sq_fingerprint_t fp = sq_tpk_fingerprint(tpk);
   6.986 +                char *fp_string = sq_fingerprint_to_hex(fp);
   6.987 +                T("wildcard recipient appears to be %s", fp_string);
   6.988 +                stringlist_add_unique(cookie->recipient_keylist, fp_string);
   6.989 +                free(fp_string);
   6.990 +                sq_fingerprint_free(fp);
   6.991 +
   6.992 +                *secret = sq_secret_cached(algo, session_key, session_key_len);
   6.993 +                cookie->decrypted = 1;
   6.994 +            }
   6.995 +
   6.996 +            sq_tpk_key_iter_free(key_iter);
   6.997 +            key_iter = NULL;
   6.998 +        }
   6.999 +    eol2:
  6.1000 +        free(keyid_str);
  6.1001 +        if (key_iter)
  6.1002 +            sq_tpk_key_iter_free(key_iter);
  6.1003 +    }
  6.1004 +
  6.1005 +    if (tsks) {
  6.1006 +        for (int i = 0; i < tsks_count; i ++)
  6.1007 +            sq_tsk_free(tsks[i]);
  6.1008 +        free(tsks);
  6.1009 +    }
  6.1010 +
  6.1011 +    return cookie->decrypted ? SQ_STATUS_SUCCESS : SQ_STATUS_UNKNOWN_ERROR;
  6.1012 +}
  6.1013 +
  6.1014 +static sq_status_t
  6.1015 +check_signatures_cb(void *cookie_opaque,
  6.1016 +                   sq_verification_results_t results, size_t levels)
  6.1017 +{
  6.1018 +    struct decrypt_cookie *cookie = cookie_opaque;
  6.1019 +    PEP_SESSION session = cookie->session;
  6.1020 +
  6.1021 +    int level;
  6.1022 +    for (level = 0; level < levels; level ++) {
  6.1023 +        sq_verification_result_t *vrs;
  6.1024 +        size_t vr_count;
  6.1025 +        sq_verification_results_at_level(results, level, &vrs, &vr_count);
  6.1026 +
  6.1027 +        int i;
  6.1028 +        for (i = 0; i < vr_count; i ++) {
  6.1029 +            sq_tpk_t tpk = NULL;
  6.1030 +            sq_verification_result_code_t code
  6.1031 +                = sq_verification_result_code(vrs[i]);
  6.1032 +
  6.1033 +            if (code == SQ_VERIFICATION_RESULT_CODE_BAD_CHECKSUM) {
  6.1034 +                cookie->bad_checksums ++;
  6.1035 +                continue;
  6.1036 +            }
  6.1037 +            if (code == SQ_VERIFICATION_RESULT_CODE_MISSING_KEY) {
  6.1038 +                // No key, nothing we can do.
  6.1039 +                cookie->missing_keys ++;
  6.1040 +                continue;
  6.1041 +            }
  6.1042 +
  6.1043 +            // We need to add the fingerprint of the primary key to
  6.1044 +            // cookie->signer_keylist.
  6.1045 +            sq_signature_t sig = sq_verification_result_signature(vrs[i]);
  6.1046 +
  6.1047 +            // First try looking up by the TPK using the
  6.1048 +            // IssuerFingerprint subpacket.
  6.1049 +            sq_fingerprint_t issuer_fp = sq_signature_issuer_fingerprint(sig);
  6.1050 +            if (issuer_fp) {
  6.1051 +                sq_keyid_t issuer = sq_fingerprint_to_keyid(issuer_fp);
  6.1052 +                if (tpk_find_by_keyid(session, issuer, &tpk) != PEP_STATUS_OK)
  6.1053 +                    ; // Soft error.  Ignore.
  6.1054 +                sq_keyid_free(issuer);
  6.1055 +                sq_fingerprint_free(issuer_fp);
  6.1056 +            }
  6.1057 +
  6.1058 +            // If that is not available, try using the Issuer subpacket.
  6.1059 +            if (!tpk) {
  6.1060 +                sq_keyid_t issuer = sq_signature_issuer(sig);
  6.1061 +                if (issuer) {
  6.1062 +                    if (tpk_find_by_keyid(session, issuer, &tpk) != PEP_STATUS_OK)
  6.1063 +                        ; // Soft error.  Ignore.
  6.1064 +                }
  6.1065 +                sq_keyid_free(issuer);
  6.1066 +            }
  6.1067 +
  6.1068 +            if (tpk) {
  6.1069 +                // Ok, we have a TPK.
  6.1070 +                sq_fingerprint_t fp = sq_tpk_fingerprint(tpk);
  6.1071 +                char *fp_str = sq_fingerprint_to_hex(fp);
  6.1072 +                stringlist_add_unique(cookie->signer_keylist, fp_str);
  6.1073 +
  6.1074 +                // XXX: Check that the TPK and the key used to make
  6.1075 +                // the signature and the signature itself are alive
  6.1076 +                // and not revoked.  Revoked =>
  6.1077 +                // PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH; Expired key
  6.1078 +                // or sig => PEP_DECRYPTED.
  6.1079 +                cookie->good_checksums ++;
  6.1080 +
  6.1081 +                free(fp_str);
  6.1082 +                sq_fingerprint_free(fp);
  6.1083 +                sq_tpk_free(tpk);
  6.1084 +            } else {
  6.1085 +                // If we get
  6.1086 +                // SQ_VERIFICATION_RESULT_CODE_GOOD_CHECKSUM, then the
  6.1087 +                // TPK should be available.  But, another process
  6.1088 +                // could have deleted the key from the store in the
  6.1089 +                // mean time, so be tolerant.
  6.1090 +                cookie->missing_keys ++;
  6.1091 +            }
  6.1092 +        }
  6.1093 +    }
  6.1094 +
  6.1095 +    return SQ_STATUS_SUCCESS;
  6.1096 +}
  6.1097 +
  6.1098 +PEP_STATUS pgp_decrypt_and_verify(
  6.1099 +    PEP_SESSION session, const char *ctext, size_t csize,
  6.1100 +    const char *dsigtext, size_t dsigsize,
  6.1101 +    char **ptext, size_t *psize, stringlist_t **keylist,
  6.1102 +    char** filename_ptr)
  6.1103 +{
  6.1104 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1105 +    struct decrypt_cookie cookie = { session, 0, NULL, NULL, 0, 0, 0, };
  6.1106 +    sq_reader_t reader = NULL;
  6.1107 +    sq_writer_t writer = NULL;
  6.1108 +    *ptext = NULL;
  6.1109 +    *psize = 0;
  6.1110 +
  6.1111 +    // XXX: We don't yet handle detached signatures over encrypted
  6.1112 +    // messages.
  6.1113 +    assert(!dsigtext);
  6.1114 +
  6.1115 +    cookie.recipient_keylist = new_stringlist(NULL);
  6.1116 +    if (!cookie.recipient_keylist)
  6.1117 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "recipient_keylist");
  6.1118 +
  6.1119 +    cookie.signer_keylist = new_stringlist(NULL);
  6.1120 +    if (!cookie.signer_keylist)
  6.1121 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "signer_keylist");
  6.1122 +
  6.1123 +    reader = sq_reader_from_bytes((const uint8_t *) ctext, csize);
  6.1124 +    if (! reader)
  6.1125 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "Creating reader");
  6.1126 +
  6.1127 +    writer = sq_writer_alloc((void **) ptext, psize);
  6.1128 +    if (! writer)
  6.1129 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Creating writer");
  6.1130 +
  6.1131 +    sq_status_t sq_status = sq_decrypt(session->ctx, reader, writer,
  6.1132 +                                       get_public_keys_cb, get_secret_keys_cb,
  6.1133 +                                       check_signatures_cb, &cookie);
  6.1134 +    if (sq_status)
  6.1135 +        ERROR_OUT(session, PEP_DECRYPT_NO_KEY, "sq_decrypt");
  6.1136 +
  6.1137 +    if (! cookie.decrypted)
  6.1138 +        ERROR_OUT(session, PEP_DECRYPT_NO_KEY, "Decryption failed");
  6.1139 +
  6.1140 +    // Add a terminating NUL for naive users
  6.1141 +    void *t = realloc(*ptext, *psize + 1);
  6.1142 +    if (! t)
  6.1143 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  6.1144 +    *ptext = t;
  6.1145 +    (*ptext)[*psize] = 0;
  6.1146 +
  6.1147 +    if (! cookie.signer_keylist) {
  6.1148 +        cookie.signer_keylist = new_stringlist("");
  6.1149 +        if (! cookie.signer_keylist)
  6.1150 +            ERROR_OUT(session, PEP_OUT_OF_MEMORY, "cookie.signer_keylist");
  6.1151 +    }
  6.1152 +    if (!cookie.signer_keylist->value)
  6.1153 +        stringlist_add(cookie.signer_keylist, "");
  6.1154 +
  6.1155 +    *keylist = cookie.signer_keylist;
  6.1156 +    stringlist_append(*keylist, cookie.recipient_keylist);
  6.1157 +
  6.1158 + out:
  6.1159 +    if (status == PEP_STATUS_OK) {
  6.1160 +        if (cookie.bad_checksums) {
  6.1161 +            // If there are any bad signatures, fail.
  6.1162 +            status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  6.1163 +        } else if (cookie.good_checksums) {
  6.1164 +            // If there is at least one signature that we can verify,
  6.1165 +            // succeed.
  6.1166 +            status = PEP_DECRYPTED_AND_VERIFIED;
  6.1167 +        } else {
  6.1168 +            // We couldn't verify any signatures (possibly because we
  6.1169 +            // don't have the keys).
  6.1170 +            status = PEP_DECRYPTED;
  6.1171 +        }
  6.1172 +    } else {
  6.1173 +        free_stringlist(cookie.recipient_keylist);
  6.1174 +        free_stringlist(cookie.signer_keylist);
  6.1175 +        free(*ptext);
  6.1176 +    }
  6.1177 +
  6.1178 +    if (reader)
  6.1179 +        sq_reader_free(reader);
  6.1180 +    if (writer)
  6.1181 +        sq_writer_free(writer);
  6.1182 +
  6.1183 +    T("-> %s", pep_status_to_string(status));
  6.1184 +    return status;
  6.1185 +}
  6.1186 +
  6.1187 +PEP_STATUS pgp_verify_text(
  6.1188 +    PEP_SESSION session, const char *text, size_t size,
  6.1189 +    const char *signature, size_t sig_size, stringlist_t **keylist)
  6.1190 +{
  6.1191 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1192 +    struct decrypt_cookie cookie = { session, 0, NULL, NULL, 0, 0, 0, };
  6.1193 +    sq_reader_t reader = NULL;
  6.1194 +    sq_reader_t dsig_reader = NULL;
  6.1195 +
  6.1196 +    if (size == 0 || sig_size == 0)
  6.1197 +        return PEP_DECRYPT_WRONG_FORMAT;
  6.1198 +
  6.1199 +    cookie.recipient_keylist = new_stringlist(NULL);
  6.1200 +    if (!cookie.recipient_keylist)
  6.1201 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  6.1202 +
  6.1203 +    cookie.signer_keylist = new_stringlist(NULL);
  6.1204 +    if (!cookie.signer_keylist)
  6.1205 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  6.1206 +
  6.1207 +    reader = sq_reader_from_bytes((const uint8_t *) text, size);
  6.1208 +    if (! reader)
  6.1209 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "Creating reader");
  6.1210 +
  6.1211 +    dsig_reader = NULL;
  6.1212 +    if (signature) {
  6.1213 +        dsig_reader = sq_reader_from_bytes((uint8_t *) signature, sig_size);
  6.1214 +        if (! dsig_reader)
  6.1215 +            ERROR_OUT(session, PEP_OUT_OF_MEMORY, "Creating signature reader");
  6.1216 +    }
  6.1217 +
  6.1218 +    if (sq_verify(session->ctx, reader, dsig_reader, /* output */ NULL,
  6.1219 +                  get_public_keys_cb, check_signatures_cb, &cookie))
  6.1220 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "sq_verify");
  6.1221 +
  6.1222 +    if (! cookie.signer_keylist) {
  6.1223 +        cookie.signer_keylist = new_stringlist("");
  6.1224 +        if (! cookie.signer_keylist)
  6.1225 +            ERROR_OUT(session, PEP_OUT_OF_MEMORY, "cookie.signer_keylist");
  6.1226 +    }
  6.1227 +    if (!cookie.signer_keylist->value)
  6.1228 +        stringlist_add(cookie.signer_keylist, "");
  6.1229 +
  6.1230 +    *keylist = cookie.signer_keylist;
  6.1231 +    stringlist_append(*keylist, cookie.recipient_keylist);
  6.1232 +
  6.1233 + out:
  6.1234 +    if (status == PEP_STATUS_OK) {
  6.1235 +        if (cookie.bad_checksums) {
  6.1236 +            // If there are any bad signatures, fail.
  6.1237 +            status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  6.1238 +        } else if (cookie.good_checksums) {
  6.1239 +            // If there is at least one signature that we can verify,
  6.1240 +            // succeed.
  6.1241 +            status = PEP_VERIFIED;
  6.1242 +        } else {
  6.1243 +            // We couldn't verify any signatures (possibly because we
  6.1244 +            // don't have the keys).
  6.1245 +            status = PEP_UNENCRYPTED;
  6.1246 +        }
  6.1247 +    } else {
  6.1248 +        free_stringlist(cookie.recipient_keylist);
  6.1249 +        free_stringlist(cookie.signer_keylist);
  6.1250 +    }
  6.1251 +
  6.1252 +    if (reader)
  6.1253 +        sq_reader_free(reader);
  6.1254 +    if (dsig_reader)
  6.1255 +        sq_reader_free(dsig_reader);
  6.1256 +
  6.1257 +    T("-> %s", pep_status_to_string(status));
  6.1258 +    return status;
  6.1259 +}
  6.1260 +
  6.1261 +
  6.1262 +PEP_STATUS pgp_sign_only(
  6.1263 +    PEP_SESSION session, const char* fpr, const char *ptext,
  6.1264 +    size_t psize, char **stext, size_t *ssize)
  6.1265 +{
  6.1266 +    assert(session);
  6.1267 +    assert(fpr && fpr[0]);
  6.1268 +    assert(ptext);
  6.1269 +    assert(psize);
  6.1270 +    assert(stext);
  6.1271 +    assert(ssize);
  6.1272 +
  6.1273 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1274 +    sq_tsk_t signer = NULL;
  6.1275 +    sq_tpk_t signer_tpk = NULL; /* Reference.  */
  6.1276 +    sq_writer_stack_t ws = NULL;
  6.1277 +
  6.1278 +    status = tsk_find_by_fpr_hex(session, fpr, &signer);
  6.1279 +    ERROR_OUT(session, status, "Looking up key '%s'", fpr);
  6.1280 +    signer_tpk = sq_tsk_tpk(signer);
  6.1281 +
  6.1282 +    sq_writer_t writer = sq_writer_alloc((void **) stext, ssize);
  6.1283 +    writer = sq_armor_writer_new(session->ctx, writer,
  6.1284 +                                 SQ_ARMOR_KIND_MESSAGE, NULL, 0);
  6.1285 +    if (!writer)
  6.1286 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up armor writer");
  6.1287 +
  6.1288 +    ws = sq_writer_stack_message(writer);
  6.1289 +
  6.1290 +    ws = sq_signer_new_detached(session->ctx, ws, &signer_tpk, 1);
  6.1291 +    if (!ws)
  6.1292 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up signer");
  6.1293 +
  6.1294 +    sq_status_t write_status =
  6.1295 +        sq_writer_stack_write_all (session->ctx, ws,
  6.1296 +                                   (uint8_t *) ptext, psize);
  6.1297 +    if (write_status != 0)
  6.1298 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Encrypting message");
  6.1299 +
  6.1300 +    // Add a terminating NUL for naive users
  6.1301 +    void *t = realloc(*stext, *ssize + 1);
  6.1302 +    if (! t)
  6.1303 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  6.1304 +    *stext = t;
  6.1305 +    (*stext)[*ssize] = 0;
  6.1306 +
  6.1307 + out:
  6.1308 +    if (ws) {
  6.1309 +        sq_status_t sq_status = sq_writer_stack_finalize (session->ctx, ws);
  6.1310 +        ws = NULL;
  6.1311 +        if (sq_status != 0)
  6.1312 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Flushing writer");
  6.1313 +    }
  6.1314 +
  6.1315 +    if (signer)
  6.1316 +        sq_tsk_free(signer);
  6.1317 +
  6.1318 +    T("(%s)-> %s", fpr, pep_status_to_string(status));
  6.1319 +    return status;
  6.1320 +}
  6.1321 +
  6.1322 +static PEP_STATUS pgp_encrypt_sign_optional(
  6.1323 +    PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  6.1324 +    size_t psize, char **ctext, size_t *csize, bool sign)
  6.1325 +{
  6.1326 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1327 +    int keys_count = 0;
  6.1328 +    sq_tpk_t *keys = NULL;
  6.1329 +    sq_tsk_t signer = NULL;
  6.1330 +    sq_tpk_t signer_tpk = NULL; /* Reference. */
  6.1331 +    sq_writer_stack_t ws = NULL;
  6.1332 +
  6.1333 +    assert(session);
  6.1334 +    assert(keylist);
  6.1335 +    assert(ptext);
  6.1336 +    assert(psize);
  6.1337 +    assert(ctext);
  6.1338 +    assert(csize);
  6.1339 +
  6.1340 +    *ctext = NULL;
  6.1341 +    *csize = 0;
  6.1342 +
  6.1343 +    keys = calloc(stringlist_length(keylist), sizeof(*keys));
  6.1344 +    if (keys == NULL)
  6.1345 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  6.1346 +
  6.1347 +    // Get the keys for the recipients.
  6.1348 +    const stringlist_t *_keylist;
  6.1349 +    for (_keylist = keylist; _keylist != NULL; _keylist = _keylist->next) {
  6.1350 +        assert(_keylist->value);
  6.1351 +        sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(_keylist->value);
  6.1352 +        status = tpk_find_by_fpr(session, sq_fpr, &keys[keys_count ++]);
  6.1353 +        sq_fingerprint_free(sq_fpr);
  6.1354 +        ERROR_OUT(session, status, "Looking up key '%s'", _keylist->value);
  6.1355 +    }
  6.1356 +
  6.1357 +    if (sign) {
  6.1358 +        // The first key in the keylist is the signer.
  6.1359 +        status = tsk_find_by_fpr_hex(session, keylist->value, &signer);
  6.1360 +        ERROR_OUT(session, status, "Looking up key '%s'", keylist->value);
  6.1361 +        signer_tpk = sq_tsk_tpk(signer);
  6.1362 +    }
  6.1363 +
  6.1364 +    sq_writer_t writer = sq_writer_alloc((void **) ctext, csize);
  6.1365 +    writer = sq_armor_writer_new(session->ctx, writer,
  6.1366 +                                 SQ_ARMOR_KIND_MESSAGE, NULL, 0);
  6.1367 +    if (!writer)
  6.1368 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up armor writer");
  6.1369 +
  6.1370 +    ws = sq_writer_stack_message(writer);
  6.1371 +    ws = sq_encryptor_new (session->ctx, ws,
  6.1372 +                           NULL, 0, keys, keys_count,
  6.1373 +                           SQ_ENCRYPTION_MODE_FOR_TRANSPORT);
  6.1374 +    if (!ws) {
  6.1375 +        sq_writer_free(writer);
  6.1376 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up encryptor");
  6.1377 +    }
  6.1378 +
  6.1379 +    if (sign) {
  6.1380 +        ws = sq_signer_new(session->ctx, ws, &signer_tpk, 1);
  6.1381 +        if (!ws)
  6.1382 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up signer");
  6.1383 +    }
  6.1384 +
  6.1385 +    ws = sq_literal_writer_new (session->ctx, ws);
  6.1386 +    if (!ws)
  6.1387 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up literal writer");
  6.1388 +
  6.1389 +    sq_status_t write_status =
  6.1390 +        sq_writer_stack_write_all (session->ctx, ws,
  6.1391 +                                   (uint8_t *) ptext, psize);
  6.1392 +    if (write_status != 0)
  6.1393 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Encrypting message");
  6.1394 +
  6.1395 +    // Add a terminating NUL for naive users
  6.1396 +    void *t = realloc(*ctext, *csize + 1);
  6.1397 +    if (! t)
  6.1398 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  6.1399 +    *ctext = t;
  6.1400 +    (*ctext)[*csize] = 0;
  6.1401 +
  6.1402 + out:
  6.1403 +    if (ws) {
  6.1404 +        sq_status_t sq_status = sq_writer_stack_finalize (session->ctx, ws);
  6.1405 +        ws = NULL;
  6.1406 +        if (sq_status != 0)
  6.1407 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Flushing writer");
  6.1408 +    }
  6.1409 +
  6.1410 +    if (signer)
  6.1411 +        sq_tsk_free(signer);
  6.1412 +    for (int i = 0; i < keys_count; i ++)
  6.1413 +        sq_tpk_free(keys[i]);
  6.1414 +    free(keys);
  6.1415 +
  6.1416 +    T("-> %s", pep_status_to_string(status));
  6.1417 +    return status;
  6.1418 +}
  6.1419 +
  6.1420 +PEP_STATUS pgp_encrypt_only(
  6.1421 +    PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  6.1422 +    size_t psize, char **ctext, size_t *csize)
  6.1423 +{
  6.1424 +    return pgp_encrypt_sign_optional(session, keylist, ptext,
  6.1425 +        psize, ctext, csize, false);
  6.1426 +}
  6.1427 +
  6.1428 +PEP_STATUS pgp_encrypt_and_sign(
  6.1429 +    PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  6.1430 +    size_t psize, char **ctext, size_t *csize)
  6.1431 +{
  6.1432 +    return pgp_encrypt_sign_optional(session, keylist, ptext,
  6.1433 +        psize, ctext, csize, true);
  6.1434 +}
  6.1435 +
  6.1436 +
  6.1437 +PEP_STATUS pgp_generate_keypair(PEP_SESSION session, pEp_identity *identity)
  6.1438 +{
  6.1439 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1440 +    char *userid = NULL;
  6.1441 +    sq_tpk_t tpk = NULL;
  6.1442 +    sq_fingerprint_t sq_fpr = NULL;
  6.1443 +    char *fpr = NULL;
  6.1444 +
  6.1445 +    assert(session);
  6.1446 +    assert(identity);
  6.1447 +    assert(identity->address);
  6.1448 +    assert(identity->fpr == NULL || identity->fpr[0] == 0);
  6.1449 +    assert(identity->username);
  6.1450 +
  6.1451 +    asprintf(&userid, "%s <%s>", identity->username, identity->address);
  6.1452 +    if (! userid)
  6.1453 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "asprintf");
  6.1454 +
  6.1455 +    // Generate a key.
  6.1456 +    sq_tsk_t tsk;
  6.1457 +    sq_signature_t rev;
  6.1458 +    if (sq_tsk_new(session->ctx, userid, &tsk, &rev) != 0)
  6.1459 +        ERROR_OUT(session, PEP_CANNOT_CREATE_KEY, "Generating a key pair");
  6.1460 +
  6.1461 +    // XXX: We should return this.
  6.1462 +    // sq_signature_free(rev);
  6.1463 +
  6.1464 +    tpk = sq_tsk_into_tpk(tsk);
  6.1465 +
  6.1466 +    // Get the fingerprint.
  6.1467 +    sq_fpr = sq_tpk_fingerprint(tpk);
  6.1468 +    fpr = sq_fingerprint_to_hex(sq_fpr);
  6.1469 +
  6.1470 +    status = tpk_save(session, tpk, identity->address, NULL, 1);
  6.1471 +    tpk = NULL;
  6.1472 +    if (status != 0)
  6.1473 +        ERROR_OUT(session, PEP_CANNOT_CREATE_KEY, "saving TSK");
  6.1474 +
  6.1475 +    free(identity->fpr);
  6.1476 +    identity->fpr = fpr;
  6.1477 +    fpr = NULL;
  6.1478 +
  6.1479 + out:
  6.1480 +    if (sq_fpr)
  6.1481 +        sq_fingerprint_free(sq_fpr);
  6.1482 +    free(fpr);
  6.1483 +    if (tpk)
  6.1484 +        sq_tpk_free(tpk);
  6.1485 +    free(userid);
  6.1486 +
  6.1487 +    T("-> %s", pep_status_to_string(status));
  6.1488 +    return status;
  6.1489 +}
  6.1490 +
  6.1491 +PEP_STATUS pgp_delete_keypair(PEP_SESSION session, const char *fpr_raw)
  6.1492 +{
  6.1493 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1494 +    char *fpr = sq_fingerprint_canonicalize(fpr_raw);
  6.1495 +
  6.1496 +    T("(%s)", fpr);
  6.1497 +
  6.1498 +    // XXX: Can also be used for deleting public keys!!!
  6.1499 +    assert(!"implement me");
  6.1500 +
  6.1501 +    T("(%s) -> %s", fpr, pep_status_to_string(status));
  6.1502 +
  6.1503 +    free(fpr);
  6.1504 +    return status;
  6.1505 +}
  6.1506 +
  6.1507 +// XXX: This needs to handle not only TPKs, but also keyrings and
  6.1508 +// revocation certificates.  Right now, we only import a single TPK
  6.1509 +// and ignore everything else.
  6.1510 +PEP_STATUS pgp_import_keydata(PEP_SESSION session, const char *key_data,
  6.1511 +                              size_t size, identity_list **private_idents)
  6.1512 +{
  6.1513 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1514 +
  6.1515 +    if (private_idents)
  6.1516 +        *private_idents = NULL;
  6.1517 +
  6.1518 +    T("parsing %zd bytes", size);
  6.1519 +
  6.1520 +    sq_packet_parser_result_t ppr
  6.1521 +        = sq_packet_parser_from_bytes(session->ctx, (uint8_t *) key_data, size);
  6.1522 +    if (! ppr)
  6.1523 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Creating packet parser");
  6.1524 +
  6.1525 +    sq_tag_t tag = sq_packet_parser_result_tag(ppr);
  6.1526 +    switch (tag) {
  6.1527 +    case SQ_TAG_SIGNATURE:
  6.1528 +        // XXX: Implement me.
  6.1529 +        assert(!"Have possible revocation certificate!");
  6.1530 +        break;
  6.1531 +
  6.1532 +    case SQ_TAG_PUBLIC_KEY:
  6.1533 +    case SQ_TAG_SECRET_KEY: {
  6.1534 +        sq_tpk_t tpk = sq_tpk_from_packet_parser(session->ctx, ppr);
  6.1535 +        if (! tpk)
  6.1536 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR, "parsing key data");
  6.1537 +
  6.1538 +        // If private_idents is not NULL and there is any private key
  6.1539 +        // material, it will be saved.
  6.1540 +        status = tpk_save(session, tpk, NULL, private_idents, false);
  6.1541 +        ERROR_OUT(session, status, "saving TPK");
  6.1542 +
  6.1543 +        break;
  6.1544 +    }
  6.1545 +    default:
  6.1546 +        ERROR_OUT(session, PEP_STATUS_OK,
  6.1547 +                  "Can't import %s", sq_tag_to_string(tag));
  6.1548 +        break;
  6.1549 +    }
  6.1550 +
  6.1551 + out:
  6.1552 +    T("-> %s", pep_status_to_string(status));
  6.1553 +    return status;
  6.1554 +}
  6.1555 +
  6.1556 +PEP_STATUS pgp_export_keydata(
  6.1557 +        PEP_SESSION session, const char *fpr, char **key_data, size_t *size,
  6.1558 +        bool secret)
  6.1559 +{
  6.1560 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1561 +    sq_tpk_t secret_key = NULL;
  6.1562 +    sq_tpk_t tpk = NULL;
  6.1563 +
  6.1564 +    assert(session);
  6.1565 +    assert(fpr);
  6.1566 +    assert(key_data);
  6.1567 +    assert(*key_data == NULL);
  6.1568 +    assert(size);
  6.1569 +
  6.1570 +    *size = 0;
  6.1571 +
  6.1572 +    T("(%s, %s)", fpr, secret ? "secret" : "public");
  6.1573 +
  6.1574 +    if (secret) {
  6.1575 +        sq_tsk_t tsk;
  6.1576 +        status = tsk_find_by_fpr_hex(session, fpr, &tsk);
  6.1577 +        if (status == PEP_KEY_NOT_FOUND) {
  6.1578 +            status = PEP_STATUS_OK;
  6.1579 +        } else if (status == PEP_STATUS_OK) {
  6.1580 +            secret_key = sq_tsk_into_tpk(tsk);
  6.1581 +        } else {
  6.1582 +            ERROR_OUT(session, status, "Looking up TSK");
  6.1583 +        }
  6.1584 +    }
  6.1585 +
  6.1586 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  6.1587 +    status = tpk_find_by_fpr(session, sq_fpr, &tpk);
  6.1588 +    sq_fingerprint_free(sq_fpr);
  6.1589 +    ERROR_OUT(session, status, "Looking up TPK for %s", fpr);
  6.1590 +
  6.1591 +    if (secret_key) {
  6.1592 +        tpk = sq_tpk_merge(session->ctx, tpk, secret_key);
  6.1593 +        // sq_tpk_merge can return NULL if the primary keys don't
  6.1594 +        // match.  But, we looked up the tpk by the secret key's
  6.1595 +        // fingerprint so this should not be possible.
  6.1596 +        assert(tpk);
  6.1597 +        secret_key = NULL;
  6.1598 +    }
  6.1599 +
  6.1600 +    sq_writer_t memory_writer = sq_writer_alloc((void **) key_data, size);
  6.1601 +    if (! memory_writer)
  6.1602 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "creating memory writer");
  6.1603 +    sq_writer_t armor_writer = sq_armor_writer_new(session->ctx,
  6.1604 +                                                   memory_writer,
  6.1605 +                                                   SQ_ARMOR_KIND_PUBLICKEY,
  6.1606 +                                                   NULL, 0);
  6.1607 +    if (! armor_writer) {
  6.1608 +        sq_writer_free(memory_writer);
  6.1609 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "creating armored writer");
  6.1610 +    }
  6.1611 +
  6.1612 +    if (secret) {
  6.1613 +        sq_tsk_t tsk = sq_tpk_into_tsk(tpk);
  6.1614 +        sq_tsk_serialize(session->ctx, tsk, armor_writer);
  6.1615 +        tpk = sq_tsk_into_tpk(tsk);
  6.1616 +    } else {
  6.1617 +        sq_tpk_serialize(session->ctx, tpk, armor_writer);
  6.1618 +    }
  6.1619 +
  6.1620 + out:
  6.1621 +    if (tpk)
  6.1622 +        sq_tpk_free(tpk);
  6.1623 +
  6.1624 +    if (armor_writer)
  6.1625 +        sq_writer_free(armor_writer);
  6.1626 +
  6.1627 +    if (secret_key)
  6.1628 +        sq_tpk_free(secret_key);
  6.1629 +
  6.1630 +    T("(%s) -> %s", fpr, pep_status_to_string(status));
  6.1631 +    return status;
  6.1632 +}
  6.1633 +
  6.1634 +static stringpair_list_t *add_key(PEP_SESSION session, stringpair_list_t *k,
  6.1635 +                                  sq_tpk_t tpk, sq_fingerprint_t fpr) {
  6.1636 +    sq_revocation_status_t rs = sq_tpk_revocation_status(tpk);
  6.1637 +    sq_revocation_status_variant_t rsv = sq_revocation_status_variant(rs);
  6.1638 +    sq_revocation_status_free(rs);
  6.1639 +    if (rsv == SQ_REVOCATION_STATUS_REVOKED)
  6.1640 +        return k;
  6.1641 +
  6.1642 +    int dealloc_fpr = 0;
  6.1643 +    if (!fpr) {
  6.1644 +        dealloc_fpr = 1;
  6.1645 +        fpr = sq_tpk_fingerprint(tpk);
  6.1646 +    }
  6.1647 +
  6.1648 +    char *fpr_str = sq_fingerprint_to_hex(fpr);
  6.1649 +    char *user_id = sq_tpk_primary_user_id(tpk);
  6.1650 +    if (user_id) {
  6.1651 +        T("  %s -> %s", fpr_str, user_id);
  6.1652 +        k = stringpair_list_add(k, new_stringpair(fpr_str, user_id));
  6.1653 +    }
  6.1654 +
  6.1655 +    free(user_id);
  6.1656 +    free(fpr_str);
  6.1657 +    if (dealloc_fpr)
  6.1658 +        sq_fingerprint_free(fpr);
  6.1659 +
  6.1660 +    return k;
  6.1661 +}
  6.1662 +
  6.1663 +// pattern could be empty, an fpr, or a mailbox.
  6.1664 +//
  6.1665 +// keyinfo_list is a list of <fpr, openpgp userid> tuples for the
  6.1666 +// matching keys.
  6.1667 +//
  6.1668 +// This function filters out revoked key, but not expired keys.
  6.1669 +PEP_STATUS pgp_list_keyinfo(PEP_SESSION session,
  6.1670 +                            const char* pattern,
  6.1671 +                            stringpair_list_t** keyinfo_list)
  6.1672 +{
  6.1673 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1674 +    sq_tpk_t tpk = NULL;
  6.1675 +    sq_fingerprint_t fpr = NULL;
  6.1676 +
  6.1677 +    T("('%s')", pattern);
  6.1678 +
  6.1679 +    *keyinfo_list = new_stringpair_list(NULL);
  6.1680 +    if (!*keyinfo_list)
  6.1681 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "new_stringlist");
  6.1682 +
  6.1683 +    // Trim any leading space.  This also makes it easier to recognize
  6.1684 +    // a string that is only whitespace.
  6.1685 +    while (*pattern == ' ')
  6.1686 +        pattern ++;
  6.1687 +
  6.1688 +    if (strchr(pattern, '@')) {
  6.1689 +        // Looks like a mailbox.
  6.1690 +        status = tpk_find_by_label(session, pattern, &tpk);
  6.1691 +        ERROR_OUT(session, status, "Looking up '%s'", pattern);
  6.1692 +        add_key(session, *keyinfo_list, tpk, NULL);
  6.1693 +
  6.1694 +        assert(!"pgp_list_keyinfo(email) untested, please make a test case");
  6.1695 +    } else if (// Only hex characters and spaces
  6.1696 +               pattern[strspn(pattern, "0123456789aAbBcCdDeEfF ")] == 0
  6.1697 +               // And a fair amount of them.
  6.1698 +               && strlen(pattern) >= 16) {
  6.1699 +        // Fingerprint.
  6.1700 +        fpr = sq_fingerprint_from_hex(pattern);
  6.1701 +        status = tpk_find_by_fpr(session, fpr, &tpk);
  6.1702 +        ERROR_OUT(session, status, "Looking up key");
  6.1703 +        add_key(session, *keyinfo_list, tpk, fpr);
  6.1704 +
  6.1705 +        assert(!"pgp_list_keyinfo(fpr) untested, please make a test case");
  6.1706 +    } else if (pattern[0] == 0) {
  6.1707 +        // Empty string.
  6.1708 +        sq_binding_iter_t iter = sq_store_iter(session->ctx, session->store);
  6.1709 +        sq_binding_t binding;
  6.1710 +        char *label;
  6.1711 +        stringpair_list_t *_k = *keyinfo_list;
  6.1712 +        while ((binding = sq_binding_iter_next(iter, &label, &fpr))) {
  6.1713 +            if (strchr(label, '@')) {
  6.1714 +                char *fpr_str = sq_fingerprint_to_hex(fpr);
  6.1715 +                T("  %s -> %s", fpr_str, label);
  6.1716 +                _k = stringpair_list_add(_k, new_stringpair(fpr_str, label));
  6.1717 +                free(fpr_str);
  6.1718 +            }
  6.1719 +            free(label);
  6.1720 +            sq_fingerprint_free(fpr);
  6.1721 +            fpr = NULL;
  6.1722 +            sq_binding_free(binding);
  6.1723 +        }
  6.1724 +        sq_binding_iter_free(iter);
  6.1725 +    }
  6.1726 +
  6.1727 + out:
  6.1728 +    if (tpk)
  6.1729 +        sq_tpk_free(tpk);
  6.1730 +    if (fpr)
  6.1731 +        sq_fingerprint_free(fpr);
  6.1732 +    if (status != PEP_STATUS_OK && *keyinfo_list) {
  6.1733 +        free_stringpair_list(*keyinfo_list);
  6.1734 +        *keyinfo_list = NULL;
  6.1735 +    }
  6.1736 +    if (status == PEP_KEY_NOT_FOUND)
  6.1737 +        status = PEP_STATUS_OK;
  6.1738 +
  6.1739 +    T("(%s) -> %s", pattern, pep_status_to_string(status));
  6.1740 +    return status;
  6.1741 +}
  6.1742 +
  6.1743 +PEP_STATUS pgp_recv_key(PEP_SESSION session, const char *pattern)
  6.1744 +{
  6.1745 +    assert(!"pgp_recv_key not implemented");
  6.1746 +    return PEP_UNKNOWN_ERROR;
  6.1747 +}
  6.1748 +
  6.1749 +char* _undot_address(const char* address) {
  6.1750 +    if (!address)
  6.1751 +        return NULL;
  6.1752 +
  6.1753 +    int addr_len = strlen(address);
  6.1754 +    const char* at = strstr(address, "@");
  6.1755 +
  6.1756 +    if (!at)
  6.1757 +        at = address + addr_len;
  6.1758 +
  6.1759 +    char* retval = calloc(1, addr_len + 1);
  6.1760 +
  6.1761 +    const char* addr_curr = address;
  6.1762 +    char* retval_curr = retval;
  6.1763 +
  6.1764 +    while (addr_curr < at) {
  6.1765 +        if (*addr_curr == '.') {
  6.1766 +            addr_curr++;
  6.1767 +            continue;
  6.1768 +        }
  6.1769 +        *retval_curr = *addr_curr;
  6.1770 +        retval_curr++;
  6.1771 +        addr_curr++;
  6.1772 +    }
  6.1773 +    if (*addr_curr == '@')
  6.1774 +        strcat(retval_curr, addr_curr);
  6.1775 +
  6.1776 +    return retval;
  6.1777 +}
  6.1778 +
  6.1779 +// Unlike pgp_list_keyinfo, this function returns revoked keys.
  6.1780 +static PEP_STATUS _pgp_search_keys(PEP_SESSION session, const char* pattern,
  6.1781 +                                   stringlist_t** keylist, int private_only) {
  6.1782 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1783 +    sq_binding_t binding = NULL;
  6.1784 +    sq_tpk_t tpk = NULL;
  6.1785 +    sq_fingerprint_t fingerprint = NULL;
  6.1786 +    char *fingerprint_hex = NULL;
  6.1787 +
  6.1788 +    *keylist = NULL;
  6.1789 +
  6.1790 +    // XXX: We only return an exact match.
  6.1791 +    T("(pattern: %s, private_only: %d)", pattern, private_only);
  6.1792 +
  6.1793 +    binding = sq_store_lookup(session->ctx, session->store, pattern);
  6.1794 +    if (! binding) {
  6.1795 +        // No binding is not an error: it means there is no match.
  6.1796 +        if (pattern != NULL) {
  6.1797 +            // If match failed, check to see if we've got a dotted
  6.1798 +            // address in the pattern.  If so, try again without dots.
  6.1799 +            const char* dotpos = strstr(pattern, ".");
  6.1800 +            const char* atpos = strstr(pattern, "@");
  6.1801 +            if (dotpos && atpos && (dotpos < atpos)) {
  6.1802 +                char* undotted = _undot_address(pattern);
  6.1803 +                if (undotted) {
  6.1804 +                    PEP_STATUS status = _pgp_search_keys(session, undotted,
  6.1805 +                                                         keylist, private_only);
  6.1806 +                    free(undotted);
  6.1807 +                    return status;
  6.1808 +                }
  6.1809 +            }
  6.1810 +        }
  6.1811 +        goto out;
  6.1812 +    }
  6.1813 +
  6.1814 +    tpk = sq_binding_tpk(session->ctx, binding);
  6.1815 +    if (! tpk)
  6.1816 +        ERROR_OUT(session, PEP_GET_KEY_FAILED, "Getting TPK");
  6.1817 +
  6.1818 +    fingerprint = sq_tpk_fingerprint(tpk);
  6.1819 +    if (!fingerprint)
  6.1820 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "Getting fingerprint");
  6.1821 +
  6.1822 +    if (private_only) {
  6.1823 +        // See if we have the private key.
  6.1824 +        status = tsk_find_by_fpr(session, fingerprint, NULL);
  6.1825 +        ERROR_OUT(session, status, "No private key material");
  6.1826 +    }
  6.1827 +
  6.1828 +    fingerprint_hex = sq_fingerprint_to_hex(fingerprint);
  6.1829 +    if (!fingerprint_hex)
  6.1830 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "sq_fingerprint_to_hex");
  6.1831 +
  6.1832 +    stringlist_t *_keylist = new_stringlist(fingerprint_hex);
  6.1833 +    if (_keylist == NULL)
  6.1834 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "new_stringlist");
  6.1835 +    *keylist = _keylist;
  6.1836 +
  6.1837 + out:
  6.1838 +    free(fingerprint_hex);
  6.1839 +    if (fingerprint)
  6.1840 +        sq_fingerprint_free(fingerprint);
  6.1841 +    if (tpk)
  6.1842 +        sq_tpk_free(tpk);
  6.1843 +    if (binding)
  6.1844 +        sq_binding_free(binding);
  6.1845 +
  6.1846 +    T("(pattern: %s, private_only: %d) -> %s",
  6.1847 +      pattern, private_only, pep_status_to_string(status));
  6.1848 +    return status;
  6.1849 +}
  6.1850 +
  6.1851 +PEP_STATUS pgp_find_keys(
  6.1852 +    PEP_SESSION session, const char *pattern, stringlist_t **keylist)
  6.1853 +{
  6.1854 +    return _pgp_search_keys(session, pattern, keylist, 0);
  6.1855 +}
  6.1856 +
  6.1857 +PEP_STATUS pgp_find_private_keys(
  6.1858 +    PEP_SESSION session, const char *pattern, stringlist_t **keylist)
  6.1859 +{
  6.1860 +    return _pgp_search_keys(session, pattern, keylist, 1);
  6.1861 +}
  6.1862 +
  6.1863 +PEP_STATUS pgp_send_key(PEP_SESSION session, const char *pattern)
  6.1864 +{
  6.1865 +    assert(!"pgp_send_key not implemented");
  6.1866 +    return PEP_UNKNOWN_ERROR;
  6.1867 +}
  6.1868 +
  6.1869 +PEP_STATUS pgp_get_key_rating(
  6.1870 +    PEP_SESSION session, const char *fpr, PEP_comm_type *comm_type)
  6.1871 +{
  6.1872 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1873 +    sq_tpk_t tpk = NULL;
  6.1874 +
  6.1875 +    assert(session);
  6.1876 +    assert(fpr);
  6.1877 +    assert(comm_type);
  6.1878 +
  6.1879 +    *comm_type = PEP_ct_unknown;
  6.1880 +
  6.1881 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  6.1882 +    status = tpk_find_by_fpr(session, sq_fpr, &tpk);
  6.1883 +    sq_fingerprint_free(sq_fpr);
  6.1884 +    ERROR_OUT(session, status, "Looking up key: %s", fpr);
  6.1885 +
  6.1886 +    *comm_type = PEP_ct_OpenPGP_unconfirmed;
  6.1887 +
  6.1888 +    if (sq_tpk_expired(tpk)) {
  6.1889 +        *comm_type = PEP_ct_key_expired;
  6.1890 +        goto out;
  6.1891 +    }
  6.1892 +
  6.1893 +    sq_revocation_status_t rs = sq_tpk_revocation_status(tpk);
  6.1894 +    sq_revocation_status_variant_t rsv = sq_revocation_status_variant(rs);
  6.1895 +    sq_revocation_status_free(rs);
  6.1896 +    if (rsv == SQ_REVOCATION_STATUS_REVOKED) {
  6.1897 +        *comm_type = PEP_ct_key_revoked;
  6.1898 +        goto out;
  6.1899 +    }
  6.1900 +
  6.1901 +    PEP_comm_type best_enc = PEP_ct_no_encryption, best_sign = PEP_ct_no_encryption;
  6.1902 +    sq_tpk_key_iter_t key_iter = sq_tpk_key_iter(tpk);
  6.1903 +    sq_p_key_t key;
  6.1904 +    sq_signature_t sig;
  6.1905 +    sq_revocation_status_t rev;
  6.1906 +    while ((key = sq_tpk_key_iter_next(key_iter, &sig, &rev))) {
  6.1907 +        if (! sig)
  6.1908 +            continue;
  6.1909 +
  6.1910 +        if (sq_revocation_status_variant(rev) == SQ_REVOCATION_STATUS_REVOKED)
  6.1911 +            continue;
  6.1912 +
  6.1913 +        if (! sq_p_key_alive(key, sig))
  6.1914 +            continue;
  6.1915 +
  6.1916 +        PEP_comm_type curr = PEP_ct_no_encryption;
  6.1917 +
  6.1918 +        int can_enc = sq_signature_can_encrypt_for_transport(sig)
  6.1919 +            || sq_signature_can_encrypt_at_rest(sig);
  6.1920 +        int can_sign = sq_signature_can_sign(sig);
  6.1921 +
  6.1922 +        sq_public_key_algo_t pk_algo = sq_p_key_public_key_algo(key);
  6.1923 +        if (pk_algo == SQ_PUBLIC_KEY_ALGO_RSA_ENCRYPT_SIGN
  6.1924 +            || pk_algo == SQ_PUBLIC_KEY_ALGO_RSA_ENCRYPT
  6.1925 +            || pk_algo == SQ_PUBLIC_KEY_ALGO_RSA_SIGN) {
  6.1926 +            int bits = sq_p_key_public_key_bits(key);
  6.1927 +            if (bits < 1024)
  6.1928 +                curr = PEP_ct_key_too_short;
  6.1929 +            else if (bits == 1024)
  6.1930 +                curr = PEP_ct_OpenPGP_weak_unconfirmed;
  6.1931 +            else
  6.1932 +                curr = PEP_ct_OpenPGP_unconfirmed;
  6.1933 +        } else {
  6.1934 +            curr = PEP_ct_OpenPGP_unconfirmed;
  6.1935 +        }
  6.1936 +
  6.1937 +        if (can_enc)
  6.1938 +            best_enc = _MAX(best_enc, curr);
  6.1939 +
  6.1940 +        if (can_sign)
  6.1941 +            best_sign = _MAX(best_sign, curr);
  6.1942 +    }
  6.1943 +    sq_tpk_key_iter_free(key_iter);
  6.1944 +
  6.1945 +    if (best_enc == PEP_ct_no_encryption || best_sign == PEP_ct_no_encryption) {
  6.1946 +        *comm_type = PEP_ct_key_b0rken;
  6.1947 +        goto out;
  6.1948 +    } else {
  6.1949 +        *comm_type = _MIN(best_enc, best_sign);
  6.1950 +    }
  6.1951 +
  6.1952 + out:
  6.1953 +    if (tpk)
  6.1954 +        sq_tpk_free(tpk);
  6.1955 +
  6.1956 +    T("(%s) -> %s", fpr, pep_comm_type_to_string(*comm_type));
  6.1957 +    return status;
  6.1958 +}
  6.1959 +
  6.1960 +
  6.1961 +PEP_STATUS pgp_renew_key(
  6.1962 +    PEP_SESSION session, const char *fpr, const timestamp *ts)
  6.1963 +{
  6.1964 +    PEP_STATUS status = PEP_STATUS_OK;
  6.1965 +    sq_tsk_t tsk = NULL;
  6.1966 +    sq_tpk_t tpk = NULL;
  6.1967 +
  6.1968 +    time_t t = mktime((struct tm *) ts);
  6.1969 +
  6.1970 +    status = tsk_find_by_fpr_hex(session, fpr, &tsk);
  6.1971 +    ERROR_OUT(session, status, "Looking up '%s'", fpr);
  6.1972 +
  6.1973 +    tpk = sq_tsk_into_tpk(tsk);
  6.1974 +
  6.1975 +    uint32_t creation_time = sq_p_key_creation_time(sq_tpk_primary(tpk));
  6.1976 +    if (creation_time > t)
  6.1977 +        // The creation time is after the expiration time!
  6.1978 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR,
  6.1979 +                  "creation time can't be after expiration time");
  6.1980 +
  6.1981 +    uint32_t delta = t - creation_time;
  6.1982 +    tpk = sq_tpk_set_expiry(session->ctx, tpk, delta);
  6.1983 +    if (! tpk)
  6.1984 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "setting expiration");
  6.1985 +
  6.1986 +    status = tpk_save(session, tpk, NULL, NULL, false);
  6.1987 +    tpk = NULL;
  6.1988 +    ERROR_OUT(session, status, "Saving %s", fpr);
  6.1989 +
  6.1990 + out:
  6.1991 +    if (tpk)
  6.1992 +        sq_tpk_free(tpk);
  6.1993 +
  6.1994 +    return status;
  6.1995 +}
  6.1996 +
  6.1997 +PEP_STATUS pgp_revoke_key(
  6.1998 +    PEP_SESSION session, const char *fpr, const char *reason)
  6.1999 +{
  6.2000 +    PEP_STATUS status = PEP_STATUS_OK;
  6.2001 +    sq_tsk_t tsk = NULL;
  6.2002 +    sq_tpk_t tpk = NULL;
  6.2003 +
  6.2004 +    status = tsk_find_by_fpr_hex(session, fpr, &tsk);
  6.2005 +    ERROR_OUT(session, status, "Looking up %s", fpr);
  6.2006 +
  6.2007 +    tpk = sq_tsk_into_tpk(tsk);
  6.2008 +    tpk = sq_tpk_revoke_in_place(session->ctx, tpk,
  6.2009 +                                 SQ_REASON_FOR_REVOCATION_UNSPECIFIED,
  6.2010 +                                 reason);
  6.2011 +    if (! tpk)
  6.2012 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "setting expiration");
  6.2013 +
  6.2014 +    assert(sq_revocation_status_variant(sq_tpk_revocation_status(tpk))
  6.2015 +           == SQ_REVOCATION_STATUS_REVOKED);
  6.2016 +
  6.2017 +    status = tpk_save(session, tpk, NULL, NULL, false);
  6.2018 +    tpk = NULL;
  6.2019 +    ERROR_OUT(session, status, "Saving %s", fpr);
  6.2020 +
  6.2021 + out:
  6.2022 +    if (tpk)
  6.2023 +        sq_tpk_free(tpk);
  6.2024 +
  6.2025 +    return status;
  6.2026 +}
  6.2027 +
  6.2028 +PEP_STATUS pgp_key_expired(PEP_SESSION session, const char *fpr,
  6.2029 +                           const time_t when, bool *expired)
  6.2030 +{
  6.2031 +    PEP_STATUS status = PEP_STATUS_OK;
  6.2032 +    sq_tpk_t tpk = NULL;
  6.2033 +
  6.2034 +    assert(session);
  6.2035 +    assert(fpr);
  6.2036 +    assert(expired);
  6.2037 +
  6.2038 +    *expired = false;
  6.2039 +
  6.2040 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  6.2041 +    status = tpk_find_by_fpr(session, sq_fpr, &tpk);
  6.2042 +    sq_fingerprint_free(sq_fpr);
  6.2043 +    ERROR_OUT(session, status, "Looking up %s", fpr);
  6.2044 +
  6.2045 +    // Is the TPK live?
  6.2046 +    *expired = !sq_tpk_alive_at(tpk, when);
  6.2047 +    if (*expired)
  6.2048 +        goto out;
  6.2049 +
  6.2050 +    // Are there at least one certification subkey, one signing subkey
  6.2051 +    // and one encryption subkey that are live?
  6.2052 +    int can_certify = 0, can_encrypt = 0, can_sign = 0;
  6.2053 +
  6.2054 +    sq_tpk_key_iter_t key_iter = sq_tpk_key_iter(tpk);
  6.2055 +    sq_p_key_t key;
  6.2056 +    sq_signature_t sig;
  6.2057 +    sq_revocation_status_t rev;
  6.2058 +    while ((key = sq_tpk_key_iter_next(key_iter, &sig, &rev))) {
  6.2059 +        if (! sig)
  6.2060 +            continue;
  6.2061 +
  6.2062 +        if (sq_revocation_status_variant(rev) == SQ_REVOCATION_STATUS_REVOKED)
  6.2063 +            continue;
  6.2064 +
  6.2065 +        if (!sq_p_key_alive_at(key, sig, when))
  6.2066 +            continue;
  6.2067 +
  6.2068 +        if (sq_signature_can_encrypt_for_transport(sig)
  6.2069 +            || sq_signature_can_encrypt_at_rest(sig))
  6.2070 +            can_encrypt = 1;
  6.2071 +        if (sq_signature_can_sign(sig))
  6.2072 +            can_sign = 1;
  6.2073 +        if (sq_signature_can_certify(sig))
  6.2074 +            can_certify = 1;
  6.2075 +
  6.2076 +        if (can_encrypt && can_sign && can_certify)
  6.2077 +            break;
  6.2078 +    }
  6.2079 +    sq_tpk_key_iter_free(key_iter);
  6.2080 +
  6.2081 +    *expired = !(can_encrypt && can_sign && can_certify);
  6.2082 +
  6.2083 + out:
  6.2084 +    if (tpk)
  6.2085 +        sq_tpk_free(tpk);
  6.2086 +    return status;
  6.2087 +}
  6.2088 +
  6.2089 +PEP_STATUS pgp_key_revoked(PEP_SESSION session, const char *fpr, bool *revoked)
  6.2090 +{
  6.2091 +    PEP_STATUS status = PEP_STATUS_OK;
  6.2092 +    sq_tpk_t tpk;
  6.2093 +
  6.2094 +    assert(session);
  6.2095 +    assert(fpr);
  6.2096 +    assert(revoked);
  6.2097 +
  6.2098 +    *revoked = false;
  6.2099 +
  6.2100 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  6.2101 +    status = tpk_find_by_fpr(session, sq_fpr, &tpk);
  6.2102 +    sq_fingerprint_free(sq_fpr);
  6.2103 +    ERROR_OUT(session, status, "Looking up %s", fpr);
  6.2104 +
  6.2105 +    sq_revocation_status_t rs = sq_tpk_revocation_status(tpk);
  6.2106 +    *revoked = sq_revocation_status_variant(rs) == SQ_REVOCATION_STATUS_REVOKED;
  6.2107 +    sq_revocation_status_free (rs);
  6.2108 +    sq_tpk_free(tpk);
  6.2109 +
  6.2110 + out:
  6.2111 +    return status;
  6.2112 +}
  6.2113 +
  6.2114 +PEP_STATUS pgp_key_created(PEP_SESSION session, const char *fpr, time_t *created)
  6.2115 +{
  6.2116 +    PEP_STATUS status = PEP_STATUS_OK;
  6.2117 +    sq_tpk_t tpk = NULL;
  6.2118 +
  6.2119 +    *created = 0;
  6.2120 +
  6.2121 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  6.2122 +    status = tpk_find_by_fpr(session, sq_fpr, &tpk);
  6.2123 +    sq_fingerprint_free(sq_fpr);
  6.2124 +    ERROR_OUT(session, status, "Looking up %s", fpr);
  6.2125 +
  6.2126 +    sq_p_key_t k = sq_tpk_primary(tpk);
  6.2127 +    *created = sq_p_key_creation_time(k);
  6.2128 +    sq_tpk_free(tpk);
  6.2129 +
  6.2130 + out:
  6.2131 +    return status;
  6.2132 +}
  6.2133 +
  6.2134 +PEP_STATUS pgp_binary(const char **path)
  6.2135 +{
  6.2136 +    return PEP_STATUS_OK;
  6.2137 +}
  6.2138 +
  6.2139 +PEP_STATUS pgp_contains_priv_key(PEP_SESSION session, const char *fpr,
  6.2140 +                                 bool *has_private)
  6.2141 +{
  6.2142 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  6.2143 +    PEP_STATUS status = tsk_find_by_fpr(session, sq_fpr, NULL);
  6.2144 +    sq_fingerprint_free(sq_fpr);
  6.2145 +    if (status == PEP_STATUS_OK) {
  6.2146 +        *has_private = 1;
  6.2147 +        return PEP_STATUS_OK;
  6.2148 +    } else if (status == PEP_KEY_NOT_FOUND) {
  6.2149 +        *has_private = 0;
  6.2150 +        return PEP_STATUS_OK;
  6.2151 +    } else {
  6.2152 +        return status;
  6.2153 +    }
  6.2154 +}
     7.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     7.2 +++ b/src/pgp_sequoia.h	Sat Dec 15 17:03:46 2018 +0100
     7.3 @@ -0,0 +1,115 @@
     7.4 +// This file is under GNU General Public License 3.0
     7.5 +// see LICENSE.txt
     7.6 +
     7.7 +#pragma once
     7.8 +
     7.9 +#include "pEpEngine.h"
    7.10 +
    7.11 +PEP_STATUS pgp_init(PEP_SESSION session, bool in_first);
    7.12 +void pgp_release(PEP_SESSION session, bool out_last);
    7.13 +
    7.14 +PEP_STATUS pgp_decrypt_and_verify(
    7.15 +        PEP_SESSION session, const char *ctext, size_t csize,
    7.16 +        const char *dsigtext, size_t dsigsize,
    7.17 +        char **ptext, size_t *psize, stringlist_t **keylist,
    7.18 +        char** filename_ptr
    7.19 +    );
    7.20 +
    7.21 +PEP_STATUS pgp_encrypt_and_sign(
    7.22 +        PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
    7.23 +        size_t psize, char **ctext, size_t *csize
    7.24 +    );
    7.25 +
    7.26 +PEP_STATUS pgp_sign_only(
    7.27 +        PEP_SESSION session, const char* fpr, const char *ptext,
    7.28 +        size_t psize, char **stext, size_t *ssize
    7.29 +    );
    7.30 +
    7.31 +PEP_STATUS pgp_encrypt_only(
    7.32 +        PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
    7.33 +        size_t psize, char **ctext, size_t *csize
    7.34 +    );
    7.35 +
    7.36 +
    7.37 +PEP_STATUS pgp_verify_text(
    7.38 +        PEP_SESSION session, const char *text, size_t size,
    7.39 +        const char *signature, size_t sig_size, stringlist_t **keylist
    7.40 +    );
    7.41 +
    7.42 +PEP_STATUS pgp_delete_keypair(PEP_SESSION session, const char *fpr);
    7.43 +
    7.44 +PEP_STATUS pgp_export_keydata(
    7.45 +        PEP_SESSION session, const char *fpr, char **key_data, size_t *size,
    7.46 +        bool secret
    7.47 +    );
    7.48 +
    7.49 +PEP_STATUS pgp_find_keys(
    7.50 +        PEP_SESSION session, const char *pattern, stringlist_t **keylist
    7.51 +    );
    7.52 +
    7.53 +PEP_STATUS pgp_list_keyinfo(
    7.54 +        PEP_SESSION session, const char* pattern, stringpair_list_t** keyinfo_list
    7.55 +    );
    7.56 +
    7.57 +PEP_STATUS pgp_generate_keypair(
    7.58 +        PEP_SESSION session, pEp_identity *identity
    7.59 +    );
    7.60 +
    7.61 +PEP_STATUS pgp_get_key_rating(
    7.62 +        PEP_SESSION session,
    7.63 +        const char *fpr,
    7.64 +        PEP_comm_type *comm_type
    7.65 +    );
    7.66 +
    7.67 +PEP_STATUS pgp_import_keydata(PEP_SESSION session, const char *key_data,
    7.68 +                              size_t size, identity_list **private_idents);
    7.69 +
    7.70 +PEP_STATUS pgp_import_private_keydata(PEP_SESSION session, const char *key_data,
    7.71 +                                      size_t size, identity_list **private_idents);
    7.72 +
    7.73 +PEP_STATUS pgp_recv_key(PEP_SESSION session, const char *pattern);
    7.74 +PEP_STATUS pgp_send_key(PEP_SESSION session, const char *pattern);
    7.75 +
    7.76 +PEP_STATUS pgp_renew_key(
    7.77 +        PEP_SESSION session,
    7.78 +        const char *fpr,
    7.79 +        const timestamp *ts
    7.80 +    );
    7.81 +
    7.82 +PEP_STATUS pgp_revoke_key(
    7.83 +        PEP_SESSION session,
    7.84 +        const char *fpr,
    7.85 +        const char *reason
    7.86 +    );
    7.87 +
    7.88 +PEP_STATUS pgp_key_expired(
    7.89 +        PEP_SESSION session,
    7.90 +        const char *fpr,
    7.91 +        const time_t when,
    7.92 +        bool *expired
    7.93 +    );
    7.94 +
    7.95 +PEP_STATUS pgp_key_revoked(
    7.96 +        PEP_SESSION session,
    7.97 +        const char *fpr,
    7.98 +        bool *revoked
    7.99 +    );
   7.100 +
   7.101 +PEP_STATUS pgp_key_created(
   7.102 +        PEP_SESSION session,
   7.103 +        const char *fpr,
   7.104 +        time_t *created
   7.105 +    );
   7.106 +
   7.107 +PEP_STATUS pgp_contains_priv_key(
   7.108 +        PEP_SESSION session, 
   7.109 +        const char *fpr,
   7.110 +        bool *has_private);
   7.111 +
   7.112 +PEP_STATUS pgp_find_private_keys(
   7.113 +    PEP_SESSION session, const char *pattern, stringlist_t **keylist
   7.114 +);
   7.115 +
   7.116 +PEP_STATUS pgp_binary(const char **path);
   7.117 +
   7.118 +#define PGP_BINARY_PATH pgp_binary
     8.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     8.2 +++ b/src/pgp_sequoia_internal.h	Sat Dec 15 17:03:46 2018 +0100
     8.3 @@ -0,0 +1,6 @@
     8.4 +// This file is under GNU General Public License 3.0
     8.5 +// see LICENSE.txt
     8.6 +
     8.7 +#pragma once
     8.8 +
     8.9 +#include <sequoia.h>
     9.1 --- a/test/Makefile	Sat Dec 15 17:00:09 2018 +0100
     9.2 +++ b/test/Makefile	Sat Dec 15 17:03:46 2018 +0100
     9.3 @@ -41,6 +41,13 @@
     9.4  endif
     9.5  endif
     9.6  
     9.7 +ifeq ($(OPENPGP),SEQUOIA)
     9.8 +	LDFLAGS+= $(SEQUOIA_LDFLAGS)
     9.9 +	LDLIBS+= $(SEQUOIA_LIB)
    9.10 +	CFLAGS+= $(SEQUOIA_CFLAGS)
    9.11 +	INC_FLAGS+= $(SEQUOIA_INC)
    9.12 +endif
    9.13 +
    9.14  ifdef SQLITE3_FROM_OS
    9.15  	LDLIBS+= -lsqlite3
    9.16  endif
    9.17 @@ -121,8 +128,8 @@
    9.18  
    9.19  .PHONY: test
    9.20  test: all
    9.21 -	$(TEST_DEBUGGER) ./$(TARGET)
    9.22 -	
    9.23 +	ulimit -n 20000; $(TEST_DEBUGGER) ./$(TARGET)
    9.24 +
    9.25  .PHONY: clean
    9.26  clean:
    9.27  	$(RM) $(TARGET) $(OBJS) $(DEPS)