src/pgp_sequoia.c
branchsequoia
changeset 3191 53dcb2892c3f
child 3197 6eb348201d7f
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/pgp_sequoia.c	Sat Dec 15 17:03:46 2018 +0100
     1.3 @@ -0,0 +1,2151 @@
     1.4 +// This file is under GNU General Public License 3.0
     1.5 +// see LICENSE.txt
     1.6 +
     1.7 +#define _GNU_SOURCE 1
     1.8 +
     1.9 +#include "platform.h"
    1.10 +#include "pEp_internal.h"
    1.11 +#include "pgp_gpg.h"
    1.12 +
    1.13 +#include <limits.h>
    1.14 +#include <sys/stat.h>
    1.15 +#include <sys/types.h>
    1.16 +#include <error.h>
    1.17 +
    1.18 +#include <sqlite3.h>
    1.19 +
    1.20 +#include "wrappers.h"
    1.21 +
    1.22 +// Set to 0 to disable tracing.
    1.23 +#if 1
    1.24 +#  define _T(...) do {                          \
    1.25 +        fprintf(stderr, ##__VA_ARGS__);         \
    1.26 +    } while (0)
    1.27 +#else
    1.28 +#  define _T(...) do { } while (0)
    1.29 +#endif
    1.30 +
    1.31 +// Show the start of a tracepoint (i.e., don't print a newline).
    1.32 +#define TC(...) do {       \
    1.33 +    _T("%s: ", __func__);  \
    1.34 +    _T(__VA_ARGS__);       \
    1.35 +} while (0)
    1.36 +
    1.37 +// Show a trace point.
    1.38 +#  define T(...) do {  \
    1.39 +    TC(__VA_ARGS__); \
    1.40 +    _T("\n");          \
    1.41 +} while(0)
    1.42 +
    1.43 +// Verbosely displays errors.
    1.44 +#  define DUMP_ERR(__de_session, __de_status, ...) do {             \
    1.45 +    TC(__VA_ARGS__);                                                \
    1.46 +    _T(": ");                                                       \
    1.47 +    if ((__de_session->ctx)) {                                      \
    1.48 +        sq_error_t __de_err                                         \
    1.49 +            = sq_context_last_error((__de_session->ctx));           \
    1.50 +        if (__de_err)                                               \
    1.51 +            _T("Sequoia: %s => ", sq_error_string(__de_err));       \
    1.52 +        sq_error_free(__de_err);                                    \
    1.53 +    }                                                               \
    1.54 +    _T("%s\n", pep_status_to_string(__de_status));                  \
    1.55 +} while(0)
    1.56 +
    1.57 +// If __ec_status is an error, then disable the error, set 'status' to
    1.58 +// it, and jump to 'out'.
    1.59 +#define ERROR_OUT(__e_session, __ec_status, ...) do {               \
    1.60 +    PEP_STATUS ___ec_status = (__ec_status);                        \
    1.61 +    if ((___ec_status) != PEP_STATUS_OK) {                          \
    1.62 +        DUMP_ERR((__e_session), (___ec_status), ##__VA_ARGS__);     \
    1.63 +        status = (___ec_status);                                    \
    1.64 +        goto out;                                                   \
    1.65 +    }                                                               \
    1.66 +} while(0)
    1.67 +
    1.68 +PEP_STATUS pgp_init(PEP_SESSION session, bool in_first)
    1.69 +{
    1.70 +    PEP_STATUS status = PEP_STATUS_OK;
    1.71 +
    1.72 +    sq_error_t err;
    1.73 +    session->ctx = sq_context_new("foundation.pep", &err);
    1.74 +    if (session->ctx == NULL)
    1.75 +        ERROR_OUT(session, PEP_INIT_GPGME_INIT_FAILED,
    1.76 +                  "initializing sequoia context");
    1.77 +
    1.78 +    session->store = sq_store_open(session->ctx, "foundation.pep");
    1.79 +    if (session->store == NULL)
    1.80 +        ERROR_OUT(session, PEP_INIT_GPGME_INIT_FAILED, "opening the store");
    1.81 +
    1.82 +
    1.83 +    // Create the home directory.
    1.84 +    char *home_env = getenv("HOME");
    1.85 +    if (!home_env)
    1.86 +        ERROR_OUT(session, PEP_INIT_GPGME_INIT_FAILED, "HOME unset");
    1.87 +
    1.88 +    // Create the DB and initialize it.
    1.89 +    char *path = NULL;
    1.90 +    asprintf(&path, "%s/.pEp_keys.db", home_env);
    1.91 +    if (!path)
    1.92 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
    1.93 +
    1.94 +    int sqlite_result;
    1.95 +    sqlite_result = sqlite3_open_v2(path,
    1.96 +                                    &session->key_db,
    1.97 +                                    SQLITE_OPEN_READWRITE
    1.98 +                                    | SQLITE_OPEN_CREATE
    1.99 +                                    | SQLITE_OPEN_FULLMUTEX
   1.100 +                                    | SQLITE_OPEN_PRIVATECACHE,
   1.101 +                                    NULL);
   1.102 +    free(path);
   1.103 +    if (sqlite_result != SQLITE_OK)
   1.104 +        ERROR_OUT(session, PEP_INIT_CANNOT_OPEN_DB,
   1.105 +                  "opening keys DB: %s",
   1.106 +                  sqlite3_errmsg(session->key_db));
   1.107 +
   1.108 +    sqlite_result = sqlite3_exec(session->key_db,
   1.109 +                                 "PRAGMA locking_mode=NORMAL;\n"
   1.110 +                                 "PRAGMA journal_mode=WAL;\n",
   1.111 +                                 NULL, NULL, NULL);
   1.112 +    if (sqlite_result != SQLITE_OK)
   1.113 +        ERROR_OUT(session, PEP_INIT_CANNOT_OPEN_DB,
   1.114 +                  "setting pragmas: %s", sqlite3_errmsg(session->key_db));
   1.115 +
   1.116 +    sqlite3_busy_timeout(session->key_db, BUSY_WAIT_TIME);
   1.117 +
   1.118 +    sqlite_result = sqlite3_exec(session->key_db,
   1.119 +                                 "CREATE TABLE IF NOT EXISTS keys (\n"
   1.120 +                                 "   primary_key TEXT PRIMARY KEY,\n"
   1.121 +                                 "   tsk BLOB\n"
   1.122 +                                 ");\n",
   1.123 +                                 NULL, NULL, NULL);
   1.124 +    if (sqlite_result != SQLITE_OK)
   1.125 +        ERROR_OUT(session, PEP_INIT_CANNOT_OPEN_DB,
   1.126 +                  "creating keys table: %s",
   1.127 +                  sqlite3_errmsg(session->key_db));
   1.128 +
   1.129 +    sqlite_result = sqlite3_exec(session->key_db,
   1.130 +                                 "CREATE TABLE IF NOT EXISTS subkeys (\n"
   1.131 +                                 "   subkey TEXT PRIMARY KEY,\n"
   1.132 +                                 "   primary_key TEXT,\n"
   1.133 +                                 "   FOREIGN KEY (primary_key)\n"
   1.134 +                                 "       REFERENCES keys(primary_key)\n"
   1.135 +                                 "     ON DELETE CASCADE\n"
   1.136 +                                 ");\n",
   1.137 +                                 NULL, NULL, NULL);
   1.138 +    if (sqlite_result != SQLITE_OK)
   1.139 +        ERROR_OUT(session, PEP_INIT_CANNOT_OPEN_DB,
   1.140 +                  "creating subkeys table: %s",
   1.141 +                  sqlite3_errmsg(session->key_db));
   1.142 +
   1.143 +    sqlite_result
   1.144 +        = sqlite3_prepare_v2(session->key_db, "begin transaction",
   1.145 +                             -1, &session->begin_transaction, NULL);
   1.146 +    assert(sqlite_result == SQLITE_OK);
   1.147 +
   1.148 +    sqlite_result
   1.149 +        = sqlite3_prepare_v2(session->key_db, "commit transaction",
   1.150 +                             -1, &session->commit_transaction, NULL);
   1.151 +    assert(sqlite_result == SQLITE_OK);
   1.152 +
   1.153 +    sqlite_result
   1.154 +        = sqlite3_prepare_v2(session->key_db, "rollback transaction",
   1.155 +                             -1, &session->rollback_transaction, NULL);
   1.156 +    assert(sqlite_result == SQLITE_OK);
   1.157 +
   1.158 +    sqlite_result
   1.159 +        = sqlite3_prepare_v2(session->key_db,
   1.160 +                             "INSERT OR REPLACE INTO keys"
   1.161 +                             "   (primary_key, tsk)"
   1.162 +                             " VALUES (?, ?)",
   1.163 +                             -1, &session->tsk_save_insert_primary, NULL);
   1.164 +    assert(sqlite_result == SQLITE_OK);
   1.165 +
   1.166 +    sqlite_result
   1.167 +        = sqlite3_prepare_v2(session->key_db,
   1.168 +                             "INSERT OR REPLACE INTO subkeys"
   1.169 +                             "   (subkey, primary_key)"
   1.170 +                             " VALUES (?, ?)",
   1.171 +                             -1, &session->tsk_save_insert_subkeys, NULL);
   1.172 +    assert(sqlite_result == SQLITE_OK);
   1.173 +
   1.174 +    sqlite_result
   1.175 +        = sqlite3_prepare_v2(session->key_db, "select tsk from keys",
   1.176 +                             -1, &session->tsk_all, NULL);
   1.177 +    assert(sqlite_result == SQLITE_OK);
   1.178 +
   1.179 +    sqlite_result
   1.180 +        = sqlite3_prepare_v2(session->key_db,
   1.181 +                             "SELECT keys.tsk FROM subkeys"
   1.182 +                             " LEFT JOIN keys"
   1.183 +                             "  ON subkeys.primary_key"
   1.184 +                             "     == keys.primary_key"
   1.185 +                             " WHERE subkey == ?",
   1.186 +                             -1, &session->tsk_find_by_keyid, NULL);
   1.187 +    assert(sqlite_result == SQLITE_OK);
   1.188 +
   1.189 + out:
   1.190 +    if (status != PEP_STATUS_OK)
   1.191 +        pgp_release(session, in_first);
   1.192 +    return status;
   1.193 +}
   1.194 +
   1.195 +void pgp_release(PEP_SESSION session, bool out_last)
   1.196 +{
   1.197 +    if (session->begin_transaction)
   1.198 +        sqlite3_finalize(session->begin_transaction);
   1.199 +    session->begin_transaction = NULL;
   1.200 +    if (session->commit_transaction)
   1.201 +        sqlite3_finalize(session->commit_transaction);
   1.202 +    session->commit_transaction = NULL;
   1.203 +    if (session->rollback_transaction)
   1.204 +        sqlite3_finalize(session->rollback_transaction);
   1.205 +    session->rollback_transaction = NULL;
   1.206 +    if (session->tsk_save_insert_primary)
   1.207 +        sqlite3_finalize(session->tsk_save_insert_primary);
   1.208 +    session->tsk_save_insert_primary = NULL;
   1.209 +    if (session->tsk_save_insert_subkeys)
   1.210 +        sqlite3_finalize(session->tsk_save_insert_subkeys);
   1.211 +    session->tsk_save_insert_subkeys = NULL;
   1.212 +    if (session->tsk_all)
   1.213 +        sqlite3_finalize(session->tsk_all);
   1.214 +    session->tsk_all = NULL;
   1.215 +    if (session->tsk_find_by_keyid)
   1.216 +        sqlite3_finalize(session->tsk_find_by_keyid);
   1.217 +    session->tsk_find_by_keyid = NULL;
   1.218 +
   1.219 +    if (session->key_db) {
   1.220 +        int result = sqlite3_close_v2(session->key_db);
   1.221 +        if (result != 0)
   1.222 +            DUMP_ERR(session, PEP_UNKNOWN_ERROR,
   1.223 +                     "Closing key DB: sqlite3_close_v2: %s",
   1.224 +                     sqlite3_errstr(result));
   1.225 +        session->key_db = NULL;
   1.226 +    }
   1.227 +
   1.228 +    if (session->store) {
   1.229 +        sq_store_free(session->store);
   1.230 +        session->store = NULL;
   1.231 +    }
   1.232 +
   1.233 +    if (session->ctx) {
   1.234 +        sq_context_free(session->ctx);
   1.235 +        session->ctx = NULL;
   1.236 +    }
   1.237 +}
   1.238 +
   1.239 +// Ensures that a fingerprint is in canonical form.  A canonical
   1.240 +// fingerprint doesn't contain any white space.
   1.241 +//
   1.242 +// This function does *not* consume fpr.
   1.243 +static char *sq_fingerprint_canonicalize(const char *) __attribute__((nonnull));
   1.244 +static char *sq_fingerprint_canonicalize(const char *fpr)
   1.245 +{
   1.246 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
   1.247 +    char *fpr_canonicalized = sq_fingerprint_to_hex(sq_fpr);
   1.248 +    sq_fingerprint_free(sq_fpr);
   1.249 +
   1.250 +    return fpr_canonicalized;
   1.251 +}
   1.252 +
   1.253 +// Splits an OpenPGP user id into its name and email components.  A
   1.254 +// user id looks like:
   1.255 +//
   1.256 +//   Name (comment) <email>
   1.257 +//
   1.258 +// This function takes ownership of user_id!!!
   1.259 +//
   1.260 +// namep and emailp may be NULL if they are not required.
   1.261 +static void user_id_split(char *, char **, char **) __attribute__((nonnull(1)));
   1.262 +static void user_id_split(char *user_id, char **namep, char **emailp)
   1.263 +{
   1.264 +    if (namep)
   1.265 +        *namep = NULL;
   1.266 +    if (emailp)
   1.267 +        *emailp = NULL;
   1.268 +
   1.269 +    char *email = strchr(user_id, '<');
   1.270 +    if (email) {
   1.271 +        // NUL terminate the string here so that user_id now points at
   1.272 +        // most to: "Name (comment)"
   1.273 +        *email = 0;
   1.274 +
   1.275 +        if (emailp && email[1]) {
   1.276 +            email = email + 1;
   1.277 +            char *end = strchr(email, '>');
   1.278 +            if (end) {
   1.279 +                *end = 0;
   1.280 +                *emailp = strdup(email);
   1.281 +            }
   1.282 +        }
   1.283 +    }
   1.284 +
   1.285 +    if (!namep)
   1.286 +        return;
   1.287 +
   1.288 +    char *comment = strchr(user_id, '(');
   1.289 +    if (comment)
   1.290 +        *comment = 0;
   1.291 +
   1.292 +    // Kill any trailing white space.
   1.293 +    for (size_t l = strlen(user_id); l > 0 && user_id[l - 1] == ' '; l --)
   1.294 +        user_id[l - 1] = 0;
   1.295 +
   1.296 +    // Kill any leading whitespace.
   1.297 +    char *start = user_id;
   1.298 +    while (*start == ' ')
   1.299 +        start ++;
   1.300 +    if (start[0])
   1.301 +        *namep = strdup(start);
   1.302 +
   1.303 +    free(user_id);
   1.304 +}
   1.305 +
   1.306 +
   1.307 +// Returns the TSK identified by the provided keyid.
   1.308 +//
   1.309 +// If tsk is NULL, the TSK is not parsed and this function simply
   1.310 +// returns whether the key is locally available.
   1.311 +static PEP_STATUS tsk_find_by_keyid_hex(PEP_SESSION, const char *, sq_tsk_t *)
   1.312 +  __attribute__((nonnull(1, 2)));
   1.313 +static PEP_STATUS tsk_find_by_keyid_hex(
   1.314 +        PEP_SESSION session,
   1.315 +        const char *keyid_hex,
   1.316 +        sq_tsk_t *tsk)
   1.317 +{
   1.318 +    PEP_STATUS status = PEP_STATUS_OK;
   1.319 +    T("%s", keyid_hex);
   1.320 +
   1.321 +    sqlite3_stmt *stmt = session->tsk_find_by_keyid;
   1.322 +    sqlite3_bind_text(stmt, 1, keyid_hex, -1, SQLITE_STATIC);
   1.323 +    int sqlite_result = sqlite3_step(stmt);
   1.324 +    switch (sqlite_result) {
   1.325 +    case SQLITE_ROW:
   1.326 +        if (tsk) {
   1.327 +            // Get the TSK from the first column.
   1.328 +            int data_len = sqlite3_column_bytes(stmt, 0);
   1.329 +            const void *data = sqlite3_column_blob(stmt, 0);
   1.330 +
   1.331 +            sq_tpk_t tpk = sq_tpk_from_bytes(session->ctx, data, data_len);
   1.332 +            if (!tpk)
   1.333 +                ERROR_OUT(session, PEP_GET_KEY_FAILED, "parsing TPK");
   1.334 +
   1.335 +            *tsk = sq_tpk_into_tsk(tpk);
   1.336 +        }
   1.337 +        break;
   1.338 +    case SQLITE_DONE:
   1.339 +        // Got nothing.
   1.340 +        status = PEP_KEY_NOT_FOUND;
   1.341 +        break;
   1.342 +    default:
   1.343 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   1.344 +                  "stepping tsk_find_by_keyid: %s",
   1.345 +                  sqlite3_errmsg(session->key_db));
   1.346 +    }
   1.347 +
   1.348 + out:
   1.349 +    sqlite3_reset(stmt);
   1.350 +    T("%s -> %s", keyid_hex, pep_status_to_string(status));
   1.351 +    return status;
   1.352 +}
   1.353 +
   1.354 +// See tsk_find_by_keyid_hex.
   1.355 +PEP_STATUS tsk_find_by_keyid(PEP_SESSION, sq_keyid_t, sq_tsk_t *)
   1.356 +    __attribute__((nonnull(1, 2)));
   1.357 +PEP_STATUS tsk_find_by_keyid(
   1.358 +        PEP_SESSION session, sq_keyid_t keyid, sq_tsk_t *tsk)
   1.359 +{
   1.360 +    char *keyid_hex = sq_keyid_to_hex(keyid);
   1.361 +    if (! keyid_hex)
   1.362 +        return PEP_OUT_OF_MEMORY;
   1.363 +    PEP_STATUS status = tsk_find_by_keyid_hex(session, keyid_hex, tsk);
   1.364 +    free(keyid_hex);
   1.365 +    return status;
   1.366 +}
   1.367 +
   1.368 +// See tsk_find_by_keyid_hex.
   1.369 +static PEP_STATUS tsk_find_by_fpr(PEP_SESSION, sq_fingerprint_t, sq_tsk_t *)
   1.370 +    __attribute__((nonnull(1, 2)));
   1.371 +static PEP_STATUS tsk_find_by_fpr(
   1.372 +        PEP_SESSION session, sq_fingerprint_t fpr, sq_tsk_t *tsk)
   1.373 +{
   1.374 +    sq_keyid_t keyid = sq_fingerprint_to_keyid(fpr);
   1.375 +    if (! keyid)
   1.376 +        return PEP_OUT_OF_MEMORY;
   1.377 +    PEP_STATUS status = tsk_find_by_keyid(session, keyid, tsk);
   1.378 +    sq_keyid_free(keyid);
   1.379 +    return status;
   1.380 +}
   1.381 +
   1.382 +// See tsk_find_by_keyid_hex.
   1.383 +static PEP_STATUS tsk_find_by_fpr_hex(PEP_SESSION, const char *, sq_tsk_t *)
   1.384 +    __attribute__((nonnull(1, 2)));
   1.385 +static PEP_STATUS tsk_find_by_fpr_hex(
   1.386 +        PEP_SESSION session, const char *fpr, sq_tsk_t *tsk)
   1.387 +{
   1.388 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
   1.389 +    if (! sq_fpr)
   1.390 +        return PEP_OUT_OF_MEMORY;
   1.391 +    PEP_STATUS status = tsk_find_by_fpr(session, sq_fpr, tsk);
   1.392 +    sq_fingerprint_free(sq_fpr);
   1.393 +    return status;
   1.394 +}
   1.395 +
   1.396 +
   1.397 +// Saves the specified TSK.
   1.398 +//
   1.399 +// This function takes ownership of TSK.
   1.400 +static PEP_STATUS tsk_save(PEP_SESSION, sq_tsk_t) __attribute__((nonnull));
   1.401 +static PEP_STATUS tsk_save(PEP_SESSION session, sq_tsk_t tsk)
   1.402 +{
   1.403 +    PEP_STATUS status = PEP_STATUS_OK;
   1.404 +    sq_fingerprint_t sq_fpr = NULL;
   1.405 +    char *fpr = NULL;
   1.406 +    void *tsk_buffer = NULL;
   1.407 +    size_t tsk_buffer_len = 0;
   1.408 +    int tried_commit = 0;
   1.409 +    sq_tpk_t tpk = sq_tsk_tpk(tsk); /* Reference. */
   1.410 +    sq_tpk_key_iter_t key_iter = NULL;
   1.411 +
   1.412 +    sq_fpr = sq_tpk_fingerprint(tpk);
   1.413 +    fpr = sq_fingerprint_to_hex(sq_fpr);
   1.414 +    T("%s", fpr);
   1.415 +
   1.416 +    // Merge any existing data into TSK.
   1.417 +    sq_tsk_t current = NULL;
   1.418 +    status = tsk_find_by_fpr(session, sq_fpr, &current);
   1.419 +    if (status == PEP_KEY_NOT_FOUND)
   1.420 +        status = PEP_STATUS_OK;
   1.421 +    else
   1.422 +        ERROR_OUT(session, status, "Looking up %s", fpr);
   1.423 +    if (current) {
   1.424 +        tpk = sq_tpk_merge(session->ctx,
   1.425 +                           sq_tsk_into_tpk(tsk), sq_tsk_into_tpk(current));
   1.426 +        tsk = sq_tpk_into_tsk(tpk);
   1.427 +        tpk = sq_tsk_tpk(tsk);
   1.428 +    }
   1.429 +
   1.430 +
   1.431 +    // Serialize it.
   1.432 +    sq_writer_t writer = sq_writer_alloc(&tsk_buffer, &tsk_buffer_len);
   1.433 +    if (! writer)
   1.434 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
   1.435 +
   1.436 +    sq_status_t sq_status = sq_tsk_serialize(session->ctx, tsk, writer);
   1.437 +    //sq_writer_free(writer);
   1.438 +    if (sq_status != 0)
   1.439 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Serializing TSK");
   1.440 +
   1.441 +
   1.442 +    // Insert the TSK into the DB.
   1.443 +    sqlite3_stmt *stmt = session->begin_transaction;
   1.444 +    int sqlite_result = sqlite3_step(stmt);
   1.445 +    sqlite3_reset(stmt);
   1.446 +    if (sqlite_result != SQLITE_DONE)
   1.447 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   1.448 +                  "begin transaction failed: %s",
   1.449 +                  sqlite3_errmsg(session->key_db));
   1.450 +
   1.451 +    stmt = session->tsk_save_insert_primary;
   1.452 +    sqlite3_bind_text(stmt, 1, fpr, -1, SQLITE_STATIC);
   1.453 +    sqlite3_bind_blob(stmt, 2, tsk_buffer, tsk_buffer_len, SQLITE_STATIC);
   1.454 +
   1.455 +    sqlite_result = sqlite3_step(stmt);
   1.456 +    sqlite3_reset(stmt);
   1.457 +    if (sqlite_result != SQLITE_DONE)
   1.458 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   1.459 +                  "Saving TSK to DB: %s",
   1.460 +                  sqlite3_errmsg(session->key_db));
   1.461 +
   1.462 +    // Insert the "subkeys" (the primary key and the subkeys).
   1.463 +    stmt = session->tsk_save_insert_subkeys;
   1.464 +    key_iter = sq_tpk_key_iter(tpk);
   1.465 +    sq_p_key_t key;
   1.466 +    while ((key = sq_tpk_key_iter_next(key_iter, NULL, NULL))) {
   1.467 +        sq_keyid_t keyid = sq_p_key_keyid(key);
   1.468 +        char *keyid_hex = sq_keyid_to_hex(keyid);
   1.469 +        T("  subkey: %s", keyid_hex);
   1.470 +        sqlite3_bind_text(stmt, 1, keyid_hex, -1, SQLITE_STATIC);
   1.471 +        sqlite3_bind_text(stmt, 2, fpr, -1, SQLITE_STATIC);
   1.472 +
   1.473 +        sqlite_result = sqlite3_step(stmt);
   1.474 +        sqlite3_reset(stmt);
   1.475 +        free(keyid_hex);
   1.476 +        sq_keyid_free(keyid);
   1.477 +        if (sqlite_result != SQLITE_DONE) {
   1.478 +            sq_tpk_key_iter_free(key_iter);
   1.479 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   1.480 +                      "Updating subkeys: %s", sqlite3_errmsg(session->key_db));
   1.481 +        }
   1.482 +    }
   1.483 +    sq_tpk_key_iter_free(key_iter);
   1.484 +    key_iter = NULL;
   1.485 +
   1.486 + out:
   1.487 +    // Prevent ERROR_OUT from causing an infinite loop.
   1.488 +    if (! tried_commit) {
   1.489 +        tried_commit = 1;
   1.490 +        stmt = status == PEP_STATUS_OK
   1.491 +            ? session->commit_transaction : session->rollback_transaction;
   1.492 +        int sqlite_result = sqlite3_step(stmt);
   1.493 +        sqlite3_reset(stmt);
   1.494 +        if (sqlite_result != SQLITE_DONE)
   1.495 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   1.496 +                      status == PEP_STATUS_OK
   1.497 +                      ? "commit failed: %s" : "rollback failed: %s",
   1.498 +                      sqlite3_errmsg(session->key_db));
   1.499 +    }
   1.500 +
   1.501 +    T("(%s) -> %s", fpr, pep_status_to_string(status));
   1.502 +
   1.503 +    if (key_iter)
   1.504 +        sq_tpk_key_iter_free(key_iter);
   1.505 +    if (stmt)
   1.506 +      sqlite3_reset(stmt);
   1.507 +    free(tsk_buffer);
   1.508 +    sq_tsk_free(tsk);
   1.509 +    free(fpr);
   1.510 +    sq_fingerprint_free(sq_fpr);
   1.511 +
   1.512 +    return status;
   1.513 +}
   1.514 +
   1.515 +// Returns all known TSKs.
   1.516 +static PEP_STATUS tsk_all(PEP_SESSION, sq_tsk_t **, int *) __attribute__((nonnull));
   1.517 +static PEP_STATUS tsk_all(PEP_SESSION session, sq_tsk_t **tsksp, int *tsks_countp) {
   1.518 +    PEP_STATUS status = PEP_STATUS_OK;
   1.519 +
   1.520 +    int tsks_count = 0;
   1.521 +    int tsks_capacity = 8;
   1.522 +    sq_tsk_t *tsks = calloc(tsks_capacity, sizeof(sq_tsk_t));
   1.523 +    if (!tsks)
   1.524 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
   1.525 +
   1.526 +    sqlite3_stmt *stmt = session->tsk_all;
   1.527 +    while (true) {
   1.528 +        switch (sqlite3_step(stmt)) {
   1.529 +        case SQLITE_ROW: {
   1.530 +            int data_len = sqlite3_column_bytes(stmt, 0);
   1.531 +            const void *data = sqlite3_column_blob(stmt, 0);
   1.532 +            sq_tpk_t tpk = sq_tpk_from_bytes(session->ctx, data, data_len);
   1.533 +            if (!tpk) {
   1.534 +                ERROR_OUT(session, PEP_GET_KEY_FAILED, "parsing TSK");
   1.535 +            } else {
   1.536 +                if (tsks_count == tsks_capacity) {
   1.537 +                    tsks_capacity *= 2;
   1.538 +                    tsks = realloc(tsks, sizeof(tsks[0]) * tsks_capacity);
   1.539 +                    if (!tsks)
   1.540 +                        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "tsks");
   1.541 +                }
   1.542 +                tsks[tsks_count ++] = sq_tpk_into_tsk(tpk);
   1.543 +            }
   1.544 +            break;
   1.545 +        }
   1.546 +        default:
   1.547 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR,
   1.548 +                      "stepping sqlite statement: %s",
   1.549 +                      sqlite3_errmsg(session->key_db));
   1.550 +        case SQLITE_DONE:
   1.551 +            goto out;
   1.552 +        }
   1.553 +    }
   1.554 +
   1.555 + out:
   1.556 +    sqlite3_reset(stmt);
   1.557 +
   1.558 +    if (status != PEP_STATUS_OK) {
   1.559 +        for (int i = 0; i < tsks_count; i ++)
   1.560 +            sq_tsk_free(tsks[i]);
   1.561 +        free(tsks);
   1.562 +    } else {
   1.563 +        *tsksp = tsks;
   1.564 +        *tsks_countp = tsks_count;
   1.565 +    }
   1.566 +
   1.567 +    return status;
   1.568 +}
   1.569 +
   1.570 +// Returns the key with the label LABEL.
   1.571 +//
   1.572 +// The return is returned in *KEY and must be freed using sq_tpk_free.
   1.573 +//
   1.574 +// Note: we maintain labels for the fingerprint of primary keys, pep
   1.575 +// user ids, and email addresses.  If you want to look something up by
   1.576 +// subkey id, use tpk_find_by_keyid.
   1.577 +static PEP_STATUS tpk_find_by_label(PEP_SESSION, const char *, sq_tpk_t *)
   1.578 +    __attribute__((nonnull));
   1.579 +static PEP_STATUS tpk_find_by_label(PEP_SESSION session, const char *label, sq_tpk_t *tpk)
   1.580 +{
   1.581 +    PEP_STATUS status = PEP_STATUS_OK;
   1.582 +
   1.583 +    sq_binding_t binding
   1.584 +        = sq_store_lookup(session->ctx, session->store, label);
   1.585 +    if (!binding)
   1.586 +        ERROR_OUT(session, PEP_KEY_NOT_FOUND, "looking up label %s", label);
   1.587 +
   1.588 +    *tpk = sq_binding_tpk(session->ctx, binding);
   1.589 +    if (!*tpk)
   1.590 +        ERROR_OUT(session, PEP_GET_KEY_FAILED, "getting TPK");
   1.591 +
   1.592 + out:
   1.593 +    if (binding)
   1.594 +        sq_binding_free(binding);
   1.595 +
   1.596 +    return status;
   1.597 +}
   1.598 +
   1.599 +// Returns the key with keyid KEYID.
   1.600 +//
   1.601 +// Note: this function will match both the primary key as well as any
   1.602 +// subkeys.
   1.603 +static PEP_STATUS tpk_find_by_keyid(PEP_SESSION, sq_keyid_t, sq_tpk_t *)
   1.604 +    __attribute__((nonnull));
   1.605 +static PEP_STATUS tpk_find_by_keyid(PEP_SESSION session, sq_keyid_t keyid,
   1.606 +                                    sq_tpk_t *tpk)
   1.607 +{
   1.608 +    PEP_STATUS status = PEP_STATUS_OK;
   1.609 +    char *keyid_hex = sq_keyid_to_hex(keyid);
   1.610 +
   1.611 +    sq_key_t key = sq_store_lookup_by_subkeyid(session->ctx, keyid);
   1.612 +    if (!key)
   1.613 +        ERROR_OUT(session, PEP_KEY_NOT_FOUND,
   1.614 +                  "looking up key by keyid %s", keyid_hex);
   1.615 +
   1.616 +    *tpk = sq_key_tpk(session->ctx, key);
   1.617 +    if (!*tpk)
   1.618 +        ERROR_OUT(session, PEP_GET_KEY_FAILED, "getting TPK");
   1.619 +
   1.620 + out:
   1.621 +    free(keyid_hex);
   1.622 +
   1.623 +    return status;
   1.624 +}
   1.625 +
   1.626 +// Returns the key with fingerprint FPR.
   1.627 +//
   1.628 +// Note: this function will match both the primary key as well as any
   1.629 +// subkeys.
   1.630 +static PEP_STATUS tpk_find_by_fpr(PEP_SESSION, sq_fingerprint_t, sq_tpk_t *)
   1.631 +    __attribute__((nonnull));
   1.632 +static PEP_STATUS tpk_find_by_fpr(PEP_SESSION session, sq_fingerprint_t fpr,
   1.633 +                                  sq_tpk_t *tpk)
   1.634 +{
   1.635 +    sq_keyid_t keyid = sq_fingerprint_to_keyid(fpr);
   1.636 +    PEP_STATUS status = tpk_find_by_keyid(session, keyid, tpk);
   1.637 +    sq_keyid_free(keyid);
   1.638 +    return status;
   1.639 +}
   1.640 +
   1.641 +
   1.642 +
   1.643 +// Saves a TPK.
   1.644 +//
   1.645 +// Creates labels under the fingerprint, address (if not NULL), and
   1.646 +// the email address in each user id.
   1.647 +//
   1.648 +// If there are any keys with private key material, saves that
   1.649 +// information in private_idents (if not NULL).
   1.650 +//
   1.651 +// This function takes ownership of the tpk.
   1.652 +static PEP_STATUS tpk_save(PEP_SESSION, sq_tpk_t, const char *,
   1.653 +                           identity_list **, int)
   1.654 +  __attribute__((nonnull(1, 2)));
   1.655 +static PEP_STATUS tpk_save(PEP_SESSION session, sq_tpk_t tpk,
   1.656 +                           const char *address, identity_list **private_idents,
   1.657 +                           int replace_bindings)
   1.658 +{
   1.659 +    PEP_STATUS status = PEP_STATUS_OK;
   1.660 +    sq_user_id_binding_iter_t iter = NULL;
   1.661 +    sq_user_id_binding_t user_id_binding = NULL;
   1.662 +
   1.663 +    if (private_idents)
   1.664 +        *private_idents = NULL;
   1.665 +
   1.666 +    sq_fingerprint_t sq_fpr = sq_tpk_fingerprint(tpk);
   1.667 +    char *fpr = sq_fingerprint_to_hex(sq_fpr);
   1.668 +    T("(%s)", fpr);
   1.669 +
   1.670 +    // Import the public part in the store.  If it was already present
   1.671 +    // in the store, it will be merged.  We don't work with the merged
   1.672 +    // TPK, because we only care about new user ids.
   1.673 +    sq_tpk_t merged = sq_store_import(session->ctx, session->store, fpr, tpk);
   1.674 +    if (! merged)
   1.675 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Merging TPK (%s)", fpr);
   1.676 +    sq_tpk_free(merged);
   1.677 +
   1.678 +    // Add the pep user id label.
   1.679 +    if (address) {
   1.680 +        int first_try = 1;
   1.681 +        sq_binding_t binding;
   1.682 +
   1.683 +    make_address_binding:
   1.684 +        binding = sq_store_add(session->ctx, session->store, address, sq_fpr);
   1.685 +        if (! binding) {
   1.686 +            // An error occured.  There's a good chance this is
   1.687 +            // because the binding already exists.
   1.688 +            if (replace_bindings && first_try) {
   1.689 +                T("replacing userid binding %s -> %s", address, fpr);
   1.690 +
   1.691 +                // We should replace the existing binding.
   1.692 +                binding = sq_store_lookup(session->ctx, session->store, address);
   1.693 +                if (binding) {
   1.694 +                    if (sq_binding_delete(session->ctx, binding)) {
   1.695 +                        DUMP_ERR(session, PEP_STATUS_OK,
   1.696 +                                 "Delete binding %s", address);
   1.697 +                        sq_binding_free(binding);
   1.698 +                    }
   1.699 +
   1.700 +                    first_try = 0;
   1.701 +                    goto make_address_binding;
   1.702 +                }
   1.703 +            }
   1.704 +
   1.705 +            // This is a soft error: we always prefer the existing
   1.706 +            // binding.
   1.707 +            DUMP_ERR(session, PEP_STATUS_OK,
   1.708 +                     "Creating userid binding %s -> %s", address, fpr);
   1.709 +        } else {
   1.710 +            sq_binding_free(binding);
   1.711 +        }
   1.712 +    }
   1.713 +
   1.714 +    // Create a binding for each user id.
   1.715 +    //
   1.716 +    // Note: the iterator only returns valid user ids in the sense
   1.717 +    // that the user id has a self-signature or a self-revocation
   1.718 +    // certificate.
   1.719 +    int first = 1;
   1.720 +    iter = sq_tpk_user_id_binding_iter(tpk);
   1.721 +    while ((user_id_binding = sq_user_id_binding_iter_next(iter))) {
   1.722 +        char *user_id = sq_user_id_binding_user_id(user_id_binding);
   1.723 +        if (!user_id) {
   1.724 +            // Completely ignore insane user ids (those with interior
   1.725 +            // NUL bytes).
   1.726 +            free(user_id);
   1.727 +            continue;
   1.728 +        }
   1.729 +
   1.730 +        // Ignore bindings with a self-revocation certificate, but no
   1.731 +        // self-signature.
   1.732 +        if (!sq_user_id_binding_selfsig(user_id_binding)) {
   1.733 +            free(user_id);
   1.734 +            continue;
   1.735 +        }
   1.736 +
   1.737 +        char *name, *email;
   1.738 +        user_id_split(user_id, &name, &email); /* user_id is comsumed.  */
   1.739 +
   1.740 +        if (email) {
   1.741 +            int first_try = 1;
   1.742 +            sq_binding_t binding;
   1.743 +
   1.744 +        make_email_binding:
   1.745 +            binding = sq_store_add(session->ctx, session->store, email, sq_fpr);
   1.746 +            if (! binding) {
   1.747 +                // An error occured.  There's a good chance this is
   1.748 +                // because the binding already exists.
   1.749 +                if (replace_bindings && first_try) {
   1.750 +                    // We should replace the existing binding.
   1.751 +                    binding = sq_store_lookup(session->ctx, session->store, email);
   1.752 +                    if (binding) {
   1.753 +                        if (sq_binding_delete(session->ctx, binding)) {
   1.754 +                            DUMP_ERR(session, PEP_STATUS_OK,
   1.755 +                                     "Delete binding %s", email);
   1.756 +                            sq_binding_free(binding);
   1.757 +                        }
   1.758 +
   1.759 +                        first_try = 0;
   1.760 +                        goto make_email_binding;
   1.761 +                    }
   1.762 +                }
   1.763 +
   1.764 +                // This is a soft error: we always prefer the existing
   1.765 +                // binding.
   1.766 +                DUMP_ERR(session, PEP_UNKNOWN_ERROR,
   1.767 +                         "Creating email binding: %s -> %s", email, fpr);
   1.768 +            } else {
   1.769 +                sq_binding_free(binding);
   1.770 +            }
   1.771 +
   1.772 +            if (first && private_idents && sq_tpk_is_tsk(tpk)) {
   1.773 +                first = 0;
   1.774 +
   1.775 +                // Create an identity for the primary user id.
   1.776 +                pEp_identity *ident = new_identity(email, fpr, NULL, name);
   1.777 +                if (ident == NULL)
   1.778 +                    ERROR_OUT(session, PEP_OUT_OF_MEMORY, "new_identity");
   1.779 +
   1.780 +                *private_idents = identity_list_add(*private_idents, ident);
   1.781 +                if (*private_idents == NULL)
   1.782 +                    ERROR_OUT(session, PEP_OUT_OF_MEMORY, "identity_list_add");
   1.783 +            }
   1.784 +        }
   1.785 +    }
   1.786 +
   1.787 +    sq_user_id_binding_iter_free(iter);
   1.788 +    iter = NULL;
   1.789 +
   1.790 +    // If it has any private key material, save it in the TSK store.
   1.791 +    if (sq_tpk_is_tsk(tpk)) {
   1.792 +        status = tsk_save(session, sq_tpk_into_tsk(tpk));
   1.793 +        tpk = NULL;
   1.794 +        ERROR_OUT(session, status, "Saving TSK");
   1.795 +    }
   1.796 +
   1.797 + out:
   1.798 +    T("(%s) -> %s", fpr, pep_status_to_string(status));
   1.799 +
   1.800 +    if (iter)
   1.801 +        sq_user_id_binding_iter_free(iter);
   1.802 +    free(fpr);
   1.803 +    if (sq_fpr)
   1.804 +        sq_fingerprint_free(sq_fpr);
   1.805 +    if (tpk)
   1.806 +        sq_tpk_free(tpk);
   1.807 +
   1.808 +    return status;
   1.809 +}
   1.810 +
   1.811 +struct decrypt_cookie {
   1.812 +    PEP_SESSION session;
   1.813 +    int get_secret_keys_called;
   1.814 +    stringlist_t *recipient_keylist;
   1.815 +    stringlist_t *signer_keylist;
   1.816 +    int good_checksums;
   1.817 +    int missing_keys;
   1.818 +    int bad_checksums;
   1.819 +    int decrypted;
   1.820 +};
   1.821 +
   1.822 +static sq_status_t
   1.823 +get_public_keys_cb(void *cookie_raw,
   1.824 +                   sq_keyid_t *keyids, size_t keyids_len,
   1.825 +                   sq_tpk_t **tpks, size_t *tpk_len,
   1.826 +                   void (**our_free)(void *))
   1.827 +{
   1.828 +    struct decrypt_cookie *cookie = cookie_raw;
   1.829 +    PEP_SESSION session = cookie->session;
   1.830 +
   1.831 +    *tpks = calloc(keyids_len, sizeof(*tpks));
   1.832 +    if (!*tpks)
   1.833 +        return SQ_STATUS_UNKNOWN_ERROR;
   1.834 +    *our_free = free;
   1.835 +
   1.836 +    int i, j;
   1.837 +    j = 0;
   1.838 +    for (i = 0; i < keyids_len; i ++) {
   1.839 +        sq_tpk_t tpk = NULL;
   1.840 +        sq_status_t status = tpk_find_by_keyid(session, keyids[i], &tpk);
   1.841 +        if (status == SQ_STATUS_SUCCESS)
   1.842 +            (*tpks)[j ++] = tpk;
   1.843 +    }
   1.844 +    *tpk_len = j;
   1.845 +    return SQ_STATUS_SUCCESS;
   1.846 +}
   1.847 +
   1.848 +static sq_status_t
   1.849 +get_secret_keys_cb(void *cookie_opaque,
   1.850 +                   sq_pkesk_t *pkesks, size_t pkesk_count,
   1.851 +                   sq_skesk_t *skesks, size_t skesk_count,
   1.852 +                   sq_secret_t *secret)
   1.853 +{
   1.854 +    struct decrypt_cookie *cookie = cookie_opaque;
   1.855 +    PEP_SESSION session = cookie->session;
   1.856 +    sq_tsk_t *tsks = NULL;
   1.857 +    int tsks_count = 0;
   1.858 +    int wildcards = 0;
   1.859 +
   1.860 +    if (cookie->get_secret_keys_called)
   1.861 +        // Prevent iterations, which isn't needed since we don't
   1.862 +        // support SKESKs.
   1.863 +        return SQ_STATUS_UNKNOWN_ERROR;
   1.864 +    cookie->get_secret_keys_called = 1;
   1.865 +
   1.866 +    T("%zd PKESKs", pkesk_count);
   1.867 +
   1.868 +    for (int i = 0; i < pkesk_count; i ++) {
   1.869 +        sq_pkesk_t pkesk = pkesks[i];
   1.870 +        sq_keyid_t keyid = sq_pkesk_recipient(pkesk); /* Reference. */
   1.871 +        char *keyid_str = sq_keyid_to_hex(keyid);
   1.872 +        sq_tpk_key_iter_t key_iter = NULL;
   1.873 +
   1.874 +        T("Considering PKESK for %s", keyid_str);
   1.875 +
   1.876 +        if (strcmp(keyid_str, "0000000000000000") == 0) {
   1.877 +            // Initially ignore wildcards.
   1.878 +            wildcards = 1;
   1.879 +            goto eol;
   1.880 +        }
   1.881 +
   1.882 +        // Collect the recipients.  Note: we must return the primary
   1.883 +        // key's fingerprint.
   1.884 +        sq_tpk_t tpk = NULL;
   1.885 +        if (tpk_find_by_keyid(session, keyid, &tpk) == PEP_STATUS_OK) {
   1.886 +            sq_fingerprint_t fp = sq_tpk_fingerprint(tpk);
   1.887 +            char *fp_string = sq_fingerprint_to_hex(fp);
   1.888 +            stringlist_add_unique(cookie->recipient_keylist, fp_string);
   1.889 +            free(fp_string);
   1.890 +            sq_fingerprint_free(fp);
   1.891 +            sq_tpk_free(tpk);
   1.892 +        }
   1.893 +
   1.894 +        if (cookie->decrypted)
   1.895 +            goto eol;
   1.896 +
   1.897 +        // See if we have the secret key.
   1.898 +        sq_tsk_t tsk = NULL;
   1.899 +        PEP_STATUS s = tsk_find_by_keyid(cookie->session, keyid, &tsk);
   1.900 +        if (s != PEP_STATUS_OK) {
   1.901 +            if (s != PEP_KEY_NOT_FOUND)
   1.902 +                DUMP_ERR(cookie->session, s, "Parsing key %s", keyid_str);
   1.903 +            else
   1.904 +                T("No secret key material for %s", keyid_str);
   1.905 +            goto eol;
   1.906 +        }
   1.907 +
   1.908 +        tpk = sq_tsk_tpk(tsk);
   1.909 +        key_iter = sq_tpk_key_iter(tpk);
   1.910 +        sq_p_key_t key;
   1.911 +        while ((key = sq_tpk_key_iter_next(key_iter, NULL, NULL))) {
   1.912 +            sq_keyid_t this_keyid = sq_p_key_keyid(key);
   1.913 +            char *this_keyid_hex = sq_keyid_to_hex(this_keyid);
   1.914 +            sq_keyid_free(this_keyid);
   1.915 +
   1.916 +            int match = strcmp(keyid_str, this_keyid_hex) == 0;
   1.917 +            free(this_keyid_hex);
   1.918 +            if (match)
   1.919 +                break;
   1.920 +        }
   1.921 +
   1.922 +        if (key == NULL)
   1.923 +            assert(!"Inconsistent DB: key doesn't contain a subkey with keyid!");
   1.924 +
   1.925 +        uint8_t algo;
   1.926 +        uint8_t session_key[1024];
   1.927 +        size_t session_key_len = sizeof(session_key);
   1.928 +        if (sq_pkesk_decrypt(cookie->session->ctx,
   1.929 +                             pkesk, key, &algo,
   1.930 +                             session_key, &session_key_len) != 0) {
   1.931 +            DUMP_ERR(session, PEP_UNKNOWN_ERROR, "sq_pkesk_decrypt");
   1.932 +            goto eol;
   1.933 +        }
   1.934 +
   1.935 +        T("Decrypted PKESK for %s", keyid_str);
   1.936 +
   1.937 +        *secret = sq_secret_cached(algo, session_key, session_key_len);
   1.938 +        cookie->decrypted = 1;
   1.939 +
   1.940 +    eol:
   1.941 +        free(keyid_str);
   1.942 +        if (key_iter)
   1.943 +            sq_tpk_key_iter_free(key_iter);
   1.944 +    }
   1.945 +
   1.946 +    // Consider wildcard recipients.
   1.947 +    if (wildcards) for (int i = 0; i < pkesk_count && !cookie->decrypted; i ++) {
   1.948 +        sq_pkesk_t pkesk = pkesks[i];
   1.949 +        sq_keyid_t keyid = sq_pkesk_recipient(pkesk); /* Reference. */
   1.950 +        char *keyid_str = sq_keyid_to_hex(keyid);
   1.951 +        sq_tpk_key_iter_t key_iter = NULL;
   1.952 +
   1.953 +        if (strcmp(keyid_str, "0000000000000000") != 0)
   1.954 +            goto eol2;
   1.955 +
   1.956 +        if (!tsks) {
   1.957 +            if (tsk_all(session, &tsks, &tsks_count) != PEP_STATUS_OK) {
   1.958 +                DUMP_ERR(session, PEP_UNKNOWN_ERROR, "Getting all tsks");
   1.959 +            }
   1.960 +        }
   1.961 +
   1.962 +        for (int j = 0; j < tsks_count; j ++) {
   1.963 +            sq_tpk_t tpk = sq_tsk_tpk(tsks[j]);
   1.964 +
   1.965 +            key_iter = sq_tpk_key_iter(tpk);
   1.966 +            sq_p_key_t key;
   1.967 +            sq_signature_t selfsig;
   1.968 +            while ((key = sq_tpk_key_iter_next(key_iter, &selfsig, NULL))) {
   1.969 +                if (! (sq_signature_can_encrypt_at_rest(selfsig)
   1.970 +                       || sq_signature_can_encrypt_for_transport(selfsig)))
   1.971 +                    continue;
   1.972 +
   1.973 +                // Note: for decryption to appear to succeed, we must
   1.974 +                // get a valid algorithm (8 of 256 values) and a
   1.975 +                // 16-bit checksum must match.  Thus, we have about a
   1.976 +                // 1 in 2**21 chance of having a false positive here.
   1.977 +                uint8_t algo;
   1.978 +                uint8_t session_key[1024];
   1.979 +                size_t session_key_len = sizeof(session_key);
   1.980 +                if (sq_pkesk_decrypt(cookie->session->ctx, pkesk, key,
   1.981 +                                     &algo, session_key, &session_key_len))
   1.982 +                    continue;
   1.983 +
   1.984 +                // Add it to the recipient list.
   1.985 +                sq_fingerprint_t fp = sq_tpk_fingerprint(tpk);
   1.986 +                char *fp_string = sq_fingerprint_to_hex(fp);
   1.987 +                T("wildcard recipient appears to be %s", fp_string);
   1.988 +                stringlist_add_unique(cookie->recipient_keylist, fp_string);
   1.989 +                free(fp_string);
   1.990 +                sq_fingerprint_free(fp);
   1.991 +
   1.992 +                *secret = sq_secret_cached(algo, session_key, session_key_len);
   1.993 +                cookie->decrypted = 1;
   1.994 +            }
   1.995 +
   1.996 +            sq_tpk_key_iter_free(key_iter);
   1.997 +            key_iter = NULL;
   1.998 +        }
   1.999 +    eol2:
  1.1000 +        free(keyid_str);
  1.1001 +        if (key_iter)
  1.1002 +            sq_tpk_key_iter_free(key_iter);
  1.1003 +    }
  1.1004 +
  1.1005 +    if (tsks) {
  1.1006 +        for (int i = 0; i < tsks_count; i ++)
  1.1007 +            sq_tsk_free(tsks[i]);
  1.1008 +        free(tsks);
  1.1009 +    }
  1.1010 +
  1.1011 +    return cookie->decrypted ? SQ_STATUS_SUCCESS : SQ_STATUS_UNKNOWN_ERROR;
  1.1012 +}
  1.1013 +
  1.1014 +static sq_status_t
  1.1015 +check_signatures_cb(void *cookie_opaque,
  1.1016 +                   sq_verification_results_t results, size_t levels)
  1.1017 +{
  1.1018 +    struct decrypt_cookie *cookie = cookie_opaque;
  1.1019 +    PEP_SESSION session = cookie->session;
  1.1020 +
  1.1021 +    int level;
  1.1022 +    for (level = 0; level < levels; level ++) {
  1.1023 +        sq_verification_result_t *vrs;
  1.1024 +        size_t vr_count;
  1.1025 +        sq_verification_results_at_level(results, level, &vrs, &vr_count);
  1.1026 +
  1.1027 +        int i;
  1.1028 +        for (i = 0; i < vr_count; i ++) {
  1.1029 +            sq_tpk_t tpk = NULL;
  1.1030 +            sq_verification_result_code_t code
  1.1031 +                = sq_verification_result_code(vrs[i]);
  1.1032 +
  1.1033 +            if (code == SQ_VERIFICATION_RESULT_CODE_BAD_CHECKSUM) {
  1.1034 +                cookie->bad_checksums ++;
  1.1035 +                continue;
  1.1036 +            }
  1.1037 +            if (code == SQ_VERIFICATION_RESULT_CODE_MISSING_KEY) {
  1.1038 +                // No key, nothing we can do.
  1.1039 +                cookie->missing_keys ++;
  1.1040 +                continue;
  1.1041 +            }
  1.1042 +
  1.1043 +            // We need to add the fingerprint of the primary key to
  1.1044 +            // cookie->signer_keylist.
  1.1045 +            sq_signature_t sig = sq_verification_result_signature(vrs[i]);
  1.1046 +
  1.1047 +            // First try looking up by the TPK using the
  1.1048 +            // IssuerFingerprint subpacket.
  1.1049 +            sq_fingerprint_t issuer_fp = sq_signature_issuer_fingerprint(sig);
  1.1050 +            if (issuer_fp) {
  1.1051 +                sq_keyid_t issuer = sq_fingerprint_to_keyid(issuer_fp);
  1.1052 +                if (tpk_find_by_keyid(session, issuer, &tpk) != PEP_STATUS_OK)
  1.1053 +                    ; // Soft error.  Ignore.
  1.1054 +                sq_keyid_free(issuer);
  1.1055 +                sq_fingerprint_free(issuer_fp);
  1.1056 +            }
  1.1057 +
  1.1058 +            // If that is not available, try using the Issuer subpacket.
  1.1059 +            if (!tpk) {
  1.1060 +                sq_keyid_t issuer = sq_signature_issuer(sig);
  1.1061 +                if (issuer) {
  1.1062 +                    if (tpk_find_by_keyid(session, issuer, &tpk) != PEP_STATUS_OK)
  1.1063 +                        ; // Soft error.  Ignore.
  1.1064 +                }
  1.1065 +                sq_keyid_free(issuer);
  1.1066 +            }
  1.1067 +
  1.1068 +            if (tpk) {
  1.1069 +                // Ok, we have a TPK.
  1.1070 +                sq_fingerprint_t fp = sq_tpk_fingerprint(tpk);
  1.1071 +                char *fp_str = sq_fingerprint_to_hex(fp);
  1.1072 +                stringlist_add_unique(cookie->signer_keylist, fp_str);
  1.1073 +
  1.1074 +                // XXX: Check that the TPK and the key used to make
  1.1075 +                // the signature and the signature itself are alive
  1.1076 +                // and not revoked.  Revoked =>
  1.1077 +                // PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH; Expired key
  1.1078 +                // or sig => PEP_DECRYPTED.
  1.1079 +                cookie->good_checksums ++;
  1.1080 +
  1.1081 +                free(fp_str);
  1.1082 +                sq_fingerprint_free(fp);
  1.1083 +                sq_tpk_free(tpk);
  1.1084 +            } else {
  1.1085 +                // If we get
  1.1086 +                // SQ_VERIFICATION_RESULT_CODE_GOOD_CHECKSUM, then the
  1.1087 +                // TPK should be available.  But, another process
  1.1088 +                // could have deleted the key from the store in the
  1.1089 +                // mean time, so be tolerant.
  1.1090 +                cookie->missing_keys ++;
  1.1091 +            }
  1.1092 +        }
  1.1093 +    }
  1.1094 +
  1.1095 +    return SQ_STATUS_SUCCESS;
  1.1096 +}
  1.1097 +
  1.1098 +PEP_STATUS pgp_decrypt_and_verify(
  1.1099 +    PEP_SESSION session, const char *ctext, size_t csize,
  1.1100 +    const char *dsigtext, size_t dsigsize,
  1.1101 +    char **ptext, size_t *psize, stringlist_t **keylist,
  1.1102 +    char** filename_ptr)
  1.1103 +{
  1.1104 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1105 +    struct decrypt_cookie cookie = { session, 0, NULL, NULL, 0, 0, 0, };
  1.1106 +    sq_reader_t reader = NULL;
  1.1107 +    sq_writer_t writer = NULL;
  1.1108 +    *ptext = NULL;
  1.1109 +    *psize = 0;
  1.1110 +
  1.1111 +    // XXX: We don't yet handle detached signatures over encrypted
  1.1112 +    // messages.
  1.1113 +    assert(!dsigtext);
  1.1114 +
  1.1115 +    cookie.recipient_keylist = new_stringlist(NULL);
  1.1116 +    if (!cookie.recipient_keylist)
  1.1117 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "recipient_keylist");
  1.1118 +
  1.1119 +    cookie.signer_keylist = new_stringlist(NULL);
  1.1120 +    if (!cookie.signer_keylist)
  1.1121 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "signer_keylist");
  1.1122 +
  1.1123 +    reader = sq_reader_from_bytes((const uint8_t *) ctext, csize);
  1.1124 +    if (! reader)
  1.1125 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "Creating reader");
  1.1126 +
  1.1127 +    writer = sq_writer_alloc((void **) ptext, psize);
  1.1128 +    if (! writer)
  1.1129 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Creating writer");
  1.1130 +
  1.1131 +    sq_status_t sq_status = sq_decrypt(session->ctx, reader, writer,
  1.1132 +                                       get_public_keys_cb, get_secret_keys_cb,
  1.1133 +                                       check_signatures_cb, &cookie);
  1.1134 +    if (sq_status)
  1.1135 +        ERROR_OUT(session, PEP_DECRYPT_NO_KEY, "sq_decrypt");
  1.1136 +
  1.1137 +    if (! cookie.decrypted)
  1.1138 +        ERROR_OUT(session, PEP_DECRYPT_NO_KEY, "Decryption failed");
  1.1139 +
  1.1140 +    // Add a terminating NUL for naive users
  1.1141 +    void *t = realloc(*ptext, *psize + 1);
  1.1142 +    if (! t)
  1.1143 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  1.1144 +    *ptext = t;
  1.1145 +    (*ptext)[*psize] = 0;
  1.1146 +
  1.1147 +    if (! cookie.signer_keylist) {
  1.1148 +        cookie.signer_keylist = new_stringlist("");
  1.1149 +        if (! cookie.signer_keylist)
  1.1150 +            ERROR_OUT(session, PEP_OUT_OF_MEMORY, "cookie.signer_keylist");
  1.1151 +    }
  1.1152 +    if (!cookie.signer_keylist->value)
  1.1153 +        stringlist_add(cookie.signer_keylist, "");
  1.1154 +
  1.1155 +    *keylist = cookie.signer_keylist;
  1.1156 +    stringlist_append(*keylist, cookie.recipient_keylist);
  1.1157 +
  1.1158 + out:
  1.1159 +    if (status == PEP_STATUS_OK) {
  1.1160 +        if (cookie.bad_checksums) {
  1.1161 +            // If there are any bad signatures, fail.
  1.1162 +            status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  1.1163 +        } else if (cookie.good_checksums) {
  1.1164 +            // If there is at least one signature that we can verify,
  1.1165 +            // succeed.
  1.1166 +            status = PEP_DECRYPTED_AND_VERIFIED;
  1.1167 +        } else {
  1.1168 +            // We couldn't verify any signatures (possibly because we
  1.1169 +            // don't have the keys).
  1.1170 +            status = PEP_DECRYPTED;
  1.1171 +        }
  1.1172 +    } else {
  1.1173 +        free_stringlist(cookie.recipient_keylist);
  1.1174 +        free_stringlist(cookie.signer_keylist);
  1.1175 +        free(*ptext);
  1.1176 +    }
  1.1177 +
  1.1178 +    if (reader)
  1.1179 +        sq_reader_free(reader);
  1.1180 +    if (writer)
  1.1181 +        sq_writer_free(writer);
  1.1182 +
  1.1183 +    T("-> %s", pep_status_to_string(status));
  1.1184 +    return status;
  1.1185 +}
  1.1186 +
  1.1187 +PEP_STATUS pgp_verify_text(
  1.1188 +    PEP_SESSION session, const char *text, size_t size,
  1.1189 +    const char *signature, size_t sig_size, stringlist_t **keylist)
  1.1190 +{
  1.1191 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1192 +    struct decrypt_cookie cookie = { session, 0, NULL, NULL, 0, 0, 0, };
  1.1193 +    sq_reader_t reader = NULL;
  1.1194 +    sq_reader_t dsig_reader = NULL;
  1.1195 +
  1.1196 +    if (size == 0 || sig_size == 0)
  1.1197 +        return PEP_DECRYPT_WRONG_FORMAT;
  1.1198 +
  1.1199 +    cookie.recipient_keylist = new_stringlist(NULL);
  1.1200 +    if (!cookie.recipient_keylist)
  1.1201 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  1.1202 +
  1.1203 +    cookie.signer_keylist = new_stringlist(NULL);
  1.1204 +    if (!cookie.signer_keylist)
  1.1205 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  1.1206 +
  1.1207 +    reader = sq_reader_from_bytes((const uint8_t *) text, size);
  1.1208 +    if (! reader)
  1.1209 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "Creating reader");
  1.1210 +
  1.1211 +    dsig_reader = NULL;
  1.1212 +    if (signature) {
  1.1213 +        dsig_reader = sq_reader_from_bytes((uint8_t *) signature, sig_size);
  1.1214 +        if (! dsig_reader)
  1.1215 +            ERROR_OUT(session, PEP_OUT_OF_MEMORY, "Creating signature reader");
  1.1216 +    }
  1.1217 +
  1.1218 +    if (sq_verify(session->ctx, reader, dsig_reader, /* output */ NULL,
  1.1219 +                  get_public_keys_cb, check_signatures_cb, &cookie))
  1.1220 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "sq_verify");
  1.1221 +
  1.1222 +    if (! cookie.signer_keylist) {
  1.1223 +        cookie.signer_keylist = new_stringlist("");
  1.1224 +        if (! cookie.signer_keylist)
  1.1225 +            ERROR_OUT(session, PEP_OUT_OF_MEMORY, "cookie.signer_keylist");
  1.1226 +    }
  1.1227 +    if (!cookie.signer_keylist->value)
  1.1228 +        stringlist_add(cookie.signer_keylist, "");
  1.1229 +
  1.1230 +    *keylist = cookie.signer_keylist;
  1.1231 +    stringlist_append(*keylist, cookie.recipient_keylist);
  1.1232 +
  1.1233 + out:
  1.1234 +    if (status == PEP_STATUS_OK) {
  1.1235 +        if (cookie.bad_checksums) {
  1.1236 +            // If there are any bad signatures, fail.
  1.1237 +            status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  1.1238 +        } else if (cookie.good_checksums) {
  1.1239 +            // If there is at least one signature that we can verify,
  1.1240 +            // succeed.
  1.1241 +            status = PEP_VERIFIED;
  1.1242 +        } else {
  1.1243 +            // We couldn't verify any signatures (possibly because we
  1.1244 +            // don't have the keys).
  1.1245 +            status = PEP_UNENCRYPTED;
  1.1246 +        }
  1.1247 +    } else {
  1.1248 +        free_stringlist(cookie.recipient_keylist);
  1.1249 +        free_stringlist(cookie.signer_keylist);
  1.1250 +    }
  1.1251 +
  1.1252 +    if (reader)
  1.1253 +        sq_reader_free(reader);
  1.1254 +    if (dsig_reader)
  1.1255 +        sq_reader_free(dsig_reader);
  1.1256 +
  1.1257 +    T("-> %s", pep_status_to_string(status));
  1.1258 +    return status;
  1.1259 +}
  1.1260 +
  1.1261 +
  1.1262 +PEP_STATUS pgp_sign_only(
  1.1263 +    PEP_SESSION session, const char* fpr, const char *ptext,
  1.1264 +    size_t psize, char **stext, size_t *ssize)
  1.1265 +{
  1.1266 +    assert(session);
  1.1267 +    assert(fpr && fpr[0]);
  1.1268 +    assert(ptext);
  1.1269 +    assert(psize);
  1.1270 +    assert(stext);
  1.1271 +    assert(ssize);
  1.1272 +
  1.1273 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1274 +    sq_tsk_t signer = NULL;
  1.1275 +    sq_tpk_t signer_tpk = NULL; /* Reference.  */
  1.1276 +    sq_writer_stack_t ws = NULL;
  1.1277 +
  1.1278 +    status = tsk_find_by_fpr_hex(session, fpr, &signer);
  1.1279 +    ERROR_OUT(session, status, "Looking up key '%s'", fpr);
  1.1280 +    signer_tpk = sq_tsk_tpk(signer);
  1.1281 +
  1.1282 +    sq_writer_t writer = sq_writer_alloc((void **) stext, ssize);
  1.1283 +    writer = sq_armor_writer_new(session->ctx, writer,
  1.1284 +                                 SQ_ARMOR_KIND_MESSAGE, NULL, 0);
  1.1285 +    if (!writer)
  1.1286 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up armor writer");
  1.1287 +
  1.1288 +    ws = sq_writer_stack_message(writer);
  1.1289 +
  1.1290 +    ws = sq_signer_new_detached(session->ctx, ws, &signer_tpk, 1);
  1.1291 +    if (!ws)
  1.1292 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up signer");
  1.1293 +
  1.1294 +    sq_status_t write_status =
  1.1295 +        sq_writer_stack_write_all (session->ctx, ws,
  1.1296 +                                   (uint8_t *) ptext, psize);
  1.1297 +    if (write_status != 0)
  1.1298 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Encrypting message");
  1.1299 +
  1.1300 +    // Add a terminating NUL for naive users
  1.1301 +    void *t = realloc(*stext, *ssize + 1);
  1.1302 +    if (! t)
  1.1303 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  1.1304 +    *stext = t;
  1.1305 +    (*stext)[*ssize] = 0;
  1.1306 +
  1.1307 + out:
  1.1308 +    if (ws) {
  1.1309 +        sq_status_t sq_status = sq_writer_stack_finalize (session->ctx, ws);
  1.1310 +        ws = NULL;
  1.1311 +        if (sq_status != 0)
  1.1312 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Flushing writer");
  1.1313 +    }
  1.1314 +
  1.1315 +    if (signer)
  1.1316 +        sq_tsk_free(signer);
  1.1317 +
  1.1318 +    T("(%s)-> %s", fpr, pep_status_to_string(status));
  1.1319 +    return status;
  1.1320 +}
  1.1321 +
  1.1322 +static PEP_STATUS pgp_encrypt_sign_optional(
  1.1323 +    PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1.1324 +    size_t psize, char **ctext, size_t *csize, bool sign)
  1.1325 +{
  1.1326 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1327 +    int keys_count = 0;
  1.1328 +    sq_tpk_t *keys = NULL;
  1.1329 +    sq_tsk_t signer = NULL;
  1.1330 +    sq_tpk_t signer_tpk = NULL; /* Reference. */
  1.1331 +    sq_writer_stack_t ws = NULL;
  1.1332 +
  1.1333 +    assert(session);
  1.1334 +    assert(keylist);
  1.1335 +    assert(ptext);
  1.1336 +    assert(psize);
  1.1337 +    assert(ctext);
  1.1338 +    assert(csize);
  1.1339 +
  1.1340 +    *ctext = NULL;
  1.1341 +    *csize = 0;
  1.1342 +
  1.1343 +    keys = calloc(stringlist_length(keylist), sizeof(*keys));
  1.1344 +    if (keys == NULL)
  1.1345 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  1.1346 +
  1.1347 +    // Get the keys for the recipients.
  1.1348 +    const stringlist_t *_keylist;
  1.1349 +    for (_keylist = keylist; _keylist != NULL; _keylist = _keylist->next) {
  1.1350 +        assert(_keylist->value);
  1.1351 +        sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(_keylist->value);
  1.1352 +        status = tpk_find_by_fpr(session, sq_fpr, &keys[keys_count ++]);
  1.1353 +        sq_fingerprint_free(sq_fpr);
  1.1354 +        ERROR_OUT(session, status, "Looking up key '%s'", _keylist->value);
  1.1355 +    }
  1.1356 +
  1.1357 +    if (sign) {
  1.1358 +        // The first key in the keylist is the signer.
  1.1359 +        status = tsk_find_by_fpr_hex(session, keylist->value, &signer);
  1.1360 +        ERROR_OUT(session, status, "Looking up key '%s'", keylist->value);
  1.1361 +        signer_tpk = sq_tsk_tpk(signer);
  1.1362 +    }
  1.1363 +
  1.1364 +    sq_writer_t writer = sq_writer_alloc((void **) ctext, csize);
  1.1365 +    writer = sq_armor_writer_new(session->ctx, writer,
  1.1366 +                                 SQ_ARMOR_KIND_MESSAGE, NULL, 0);
  1.1367 +    if (!writer)
  1.1368 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up armor writer");
  1.1369 +
  1.1370 +    ws = sq_writer_stack_message(writer);
  1.1371 +    ws = sq_encryptor_new (session->ctx, ws,
  1.1372 +                           NULL, 0, keys, keys_count,
  1.1373 +                           SQ_ENCRYPTION_MODE_FOR_TRANSPORT);
  1.1374 +    if (!ws) {
  1.1375 +        sq_writer_free(writer);
  1.1376 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up encryptor");
  1.1377 +    }
  1.1378 +
  1.1379 +    if (sign) {
  1.1380 +        ws = sq_signer_new(session->ctx, ws, &signer_tpk, 1);
  1.1381 +        if (!ws)
  1.1382 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up signer");
  1.1383 +    }
  1.1384 +
  1.1385 +    ws = sq_literal_writer_new (session->ctx, ws);
  1.1386 +    if (!ws)
  1.1387 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Setting up literal writer");
  1.1388 +
  1.1389 +    sq_status_t write_status =
  1.1390 +        sq_writer_stack_write_all (session->ctx, ws,
  1.1391 +                                   (uint8_t *) ptext, psize);
  1.1392 +    if (write_status != 0)
  1.1393 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Encrypting message");
  1.1394 +
  1.1395 +    // Add a terminating NUL for naive users
  1.1396 +    void *t = realloc(*ctext, *csize + 1);
  1.1397 +    if (! t)
  1.1398 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "out of memory");
  1.1399 +    *ctext = t;
  1.1400 +    (*ctext)[*csize] = 0;
  1.1401 +
  1.1402 + out:
  1.1403 +    if (ws) {
  1.1404 +        sq_status_t sq_status = sq_writer_stack_finalize (session->ctx, ws);
  1.1405 +        ws = NULL;
  1.1406 +        if (sq_status != 0)
  1.1407 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Flushing writer");
  1.1408 +    }
  1.1409 +
  1.1410 +    if (signer)
  1.1411 +        sq_tsk_free(signer);
  1.1412 +    for (int i = 0; i < keys_count; i ++)
  1.1413 +        sq_tpk_free(keys[i]);
  1.1414 +    free(keys);
  1.1415 +
  1.1416 +    T("-> %s", pep_status_to_string(status));
  1.1417 +    return status;
  1.1418 +}
  1.1419 +
  1.1420 +PEP_STATUS pgp_encrypt_only(
  1.1421 +    PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1.1422 +    size_t psize, char **ctext, size_t *csize)
  1.1423 +{
  1.1424 +    return pgp_encrypt_sign_optional(session, keylist, ptext,
  1.1425 +        psize, ctext, csize, false);
  1.1426 +}
  1.1427 +
  1.1428 +PEP_STATUS pgp_encrypt_and_sign(
  1.1429 +    PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1.1430 +    size_t psize, char **ctext, size_t *csize)
  1.1431 +{
  1.1432 +    return pgp_encrypt_sign_optional(session, keylist, ptext,
  1.1433 +        psize, ctext, csize, true);
  1.1434 +}
  1.1435 +
  1.1436 +
  1.1437 +PEP_STATUS pgp_generate_keypair(PEP_SESSION session, pEp_identity *identity)
  1.1438 +{
  1.1439 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1440 +    char *userid = NULL;
  1.1441 +    sq_tpk_t tpk = NULL;
  1.1442 +    sq_fingerprint_t sq_fpr = NULL;
  1.1443 +    char *fpr = NULL;
  1.1444 +
  1.1445 +    assert(session);
  1.1446 +    assert(identity);
  1.1447 +    assert(identity->address);
  1.1448 +    assert(identity->fpr == NULL || identity->fpr[0] == 0);
  1.1449 +    assert(identity->username);
  1.1450 +
  1.1451 +    asprintf(&userid, "%s <%s>", identity->username, identity->address);
  1.1452 +    if (! userid)
  1.1453 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "asprintf");
  1.1454 +
  1.1455 +    // Generate a key.
  1.1456 +    sq_tsk_t tsk;
  1.1457 +    sq_signature_t rev;
  1.1458 +    if (sq_tsk_new(session->ctx, userid, &tsk, &rev) != 0)
  1.1459 +        ERROR_OUT(session, PEP_CANNOT_CREATE_KEY, "Generating a key pair");
  1.1460 +
  1.1461 +    // XXX: We should return this.
  1.1462 +    // sq_signature_free(rev);
  1.1463 +
  1.1464 +    tpk = sq_tsk_into_tpk(tsk);
  1.1465 +
  1.1466 +    // Get the fingerprint.
  1.1467 +    sq_fpr = sq_tpk_fingerprint(tpk);
  1.1468 +    fpr = sq_fingerprint_to_hex(sq_fpr);
  1.1469 +
  1.1470 +    status = tpk_save(session, tpk, identity->address, NULL, 1);
  1.1471 +    tpk = NULL;
  1.1472 +    if (status != 0)
  1.1473 +        ERROR_OUT(session, PEP_CANNOT_CREATE_KEY, "saving TSK");
  1.1474 +
  1.1475 +    free(identity->fpr);
  1.1476 +    identity->fpr = fpr;
  1.1477 +    fpr = NULL;
  1.1478 +
  1.1479 + out:
  1.1480 +    if (sq_fpr)
  1.1481 +        sq_fingerprint_free(sq_fpr);
  1.1482 +    free(fpr);
  1.1483 +    if (tpk)
  1.1484 +        sq_tpk_free(tpk);
  1.1485 +    free(userid);
  1.1486 +
  1.1487 +    T("-> %s", pep_status_to_string(status));
  1.1488 +    return status;
  1.1489 +}
  1.1490 +
  1.1491 +PEP_STATUS pgp_delete_keypair(PEP_SESSION session, const char *fpr_raw)
  1.1492 +{
  1.1493 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1494 +    char *fpr = sq_fingerprint_canonicalize(fpr_raw);
  1.1495 +
  1.1496 +    T("(%s)", fpr);
  1.1497 +
  1.1498 +    // XXX: Can also be used for deleting public keys!!!
  1.1499 +    assert(!"implement me");
  1.1500 +
  1.1501 +    T("(%s) -> %s", fpr, pep_status_to_string(status));
  1.1502 +
  1.1503 +    free(fpr);
  1.1504 +    return status;
  1.1505 +}
  1.1506 +
  1.1507 +// XXX: This needs to handle not only TPKs, but also keyrings and
  1.1508 +// revocation certificates.  Right now, we only import a single TPK
  1.1509 +// and ignore everything else.
  1.1510 +PEP_STATUS pgp_import_keydata(PEP_SESSION session, const char *key_data,
  1.1511 +                              size_t size, identity_list **private_idents)
  1.1512 +{
  1.1513 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1514 +
  1.1515 +    if (private_idents)
  1.1516 +        *private_idents = NULL;
  1.1517 +
  1.1518 +    T("parsing %zd bytes", size);
  1.1519 +
  1.1520 +    sq_packet_parser_result_t ppr
  1.1521 +        = sq_packet_parser_from_bytes(session->ctx, (uint8_t *) key_data, size);
  1.1522 +    if (! ppr)
  1.1523 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "Creating packet parser");
  1.1524 +
  1.1525 +    sq_tag_t tag = sq_packet_parser_result_tag(ppr);
  1.1526 +    switch (tag) {
  1.1527 +    case SQ_TAG_SIGNATURE:
  1.1528 +        // XXX: Implement me.
  1.1529 +        assert(!"Have possible revocation certificate!");
  1.1530 +        break;
  1.1531 +
  1.1532 +    case SQ_TAG_PUBLIC_KEY:
  1.1533 +    case SQ_TAG_SECRET_KEY: {
  1.1534 +        sq_tpk_t tpk = sq_tpk_from_packet_parser(session->ctx, ppr);
  1.1535 +        if (! tpk)
  1.1536 +            ERROR_OUT(session, PEP_UNKNOWN_ERROR, "parsing key data");
  1.1537 +
  1.1538 +        // If private_idents is not NULL and there is any private key
  1.1539 +        // material, it will be saved.
  1.1540 +        status = tpk_save(session, tpk, NULL, private_idents, false);
  1.1541 +        ERROR_OUT(session, status, "saving TPK");
  1.1542 +
  1.1543 +        break;
  1.1544 +    }
  1.1545 +    default:
  1.1546 +        ERROR_OUT(session, PEP_STATUS_OK,
  1.1547 +                  "Can't import %s", sq_tag_to_string(tag));
  1.1548 +        break;
  1.1549 +    }
  1.1550 +
  1.1551 + out:
  1.1552 +    T("-> %s", pep_status_to_string(status));
  1.1553 +    return status;
  1.1554 +}
  1.1555 +
  1.1556 +PEP_STATUS pgp_export_keydata(
  1.1557 +        PEP_SESSION session, const char *fpr, char **key_data, size_t *size,
  1.1558 +        bool secret)
  1.1559 +{
  1.1560 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1561 +    sq_tpk_t secret_key = NULL;
  1.1562 +    sq_tpk_t tpk = NULL;
  1.1563 +
  1.1564 +    assert(session);
  1.1565 +    assert(fpr);
  1.1566 +    assert(key_data);
  1.1567 +    assert(*key_data == NULL);
  1.1568 +    assert(size);
  1.1569 +
  1.1570 +    *size = 0;
  1.1571 +
  1.1572 +    T("(%s, %s)", fpr, secret ? "secret" : "public");
  1.1573 +
  1.1574 +    if (secret) {
  1.1575 +        sq_tsk_t tsk;
  1.1576 +        status = tsk_find_by_fpr_hex(session, fpr, &tsk);
  1.1577 +        if (status == PEP_KEY_NOT_FOUND) {
  1.1578 +            status = PEP_STATUS_OK;
  1.1579 +        } else if (status == PEP_STATUS_OK) {
  1.1580 +            secret_key = sq_tsk_into_tpk(tsk);
  1.1581 +        } else {
  1.1582 +            ERROR_OUT(session, status, "Looking up TSK");
  1.1583 +        }
  1.1584 +    }
  1.1585 +
  1.1586 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  1.1587 +    status = tpk_find_by_fpr(session, sq_fpr, &tpk);
  1.1588 +    sq_fingerprint_free(sq_fpr);
  1.1589 +    ERROR_OUT(session, status, "Looking up TPK for %s", fpr);
  1.1590 +
  1.1591 +    if (secret_key) {
  1.1592 +        tpk = sq_tpk_merge(session->ctx, tpk, secret_key);
  1.1593 +        // sq_tpk_merge can return NULL if the primary keys don't
  1.1594 +        // match.  But, we looked up the tpk by the secret key's
  1.1595 +        // fingerprint so this should not be possible.
  1.1596 +        assert(tpk);
  1.1597 +        secret_key = NULL;
  1.1598 +    }
  1.1599 +
  1.1600 +    sq_writer_t memory_writer = sq_writer_alloc((void **) key_data, size);
  1.1601 +    if (! memory_writer)
  1.1602 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "creating memory writer");
  1.1603 +    sq_writer_t armor_writer = sq_armor_writer_new(session->ctx,
  1.1604 +                                                   memory_writer,
  1.1605 +                                                   SQ_ARMOR_KIND_PUBLICKEY,
  1.1606 +                                                   NULL, 0);
  1.1607 +    if (! armor_writer) {
  1.1608 +        sq_writer_free(memory_writer);
  1.1609 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "creating armored writer");
  1.1610 +    }
  1.1611 +
  1.1612 +    if (secret) {
  1.1613 +        sq_tsk_t tsk = sq_tpk_into_tsk(tpk);
  1.1614 +        sq_tsk_serialize(session->ctx, tsk, armor_writer);
  1.1615 +        tpk = sq_tsk_into_tpk(tsk);
  1.1616 +    } else {
  1.1617 +        sq_tpk_serialize(session->ctx, tpk, armor_writer);
  1.1618 +    }
  1.1619 +
  1.1620 + out:
  1.1621 +    if (tpk)
  1.1622 +        sq_tpk_free(tpk);
  1.1623 +
  1.1624 +    if (armor_writer)
  1.1625 +        sq_writer_free(armor_writer);
  1.1626 +
  1.1627 +    if (secret_key)
  1.1628 +        sq_tpk_free(secret_key);
  1.1629 +
  1.1630 +    T("(%s) -> %s", fpr, pep_status_to_string(status));
  1.1631 +    return status;
  1.1632 +}
  1.1633 +
  1.1634 +static stringpair_list_t *add_key(PEP_SESSION session, stringpair_list_t *k,
  1.1635 +                                  sq_tpk_t tpk, sq_fingerprint_t fpr) {
  1.1636 +    sq_revocation_status_t rs = sq_tpk_revocation_status(tpk);
  1.1637 +    sq_revocation_status_variant_t rsv = sq_revocation_status_variant(rs);
  1.1638 +    sq_revocation_status_free(rs);
  1.1639 +    if (rsv == SQ_REVOCATION_STATUS_REVOKED)
  1.1640 +        return k;
  1.1641 +
  1.1642 +    int dealloc_fpr = 0;
  1.1643 +    if (!fpr) {
  1.1644 +        dealloc_fpr = 1;
  1.1645 +        fpr = sq_tpk_fingerprint(tpk);
  1.1646 +    }
  1.1647 +
  1.1648 +    char *fpr_str = sq_fingerprint_to_hex(fpr);
  1.1649 +    char *user_id = sq_tpk_primary_user_id(tpk);
  1.1650 +    if (user_id) {
  1.1651 +        T("  %s -> %s", fpr_str, user_id);
  1.1652 +        k = stringpair_list_add(k, new_stringpair(fpr_str, user_id));
  1.1653 +    }
  1.1654 +
  1.1655 +    free(user_id);
  1.1656 +    free(fpr_str);
  1.1657 +    if (dealloc_fpr)
  1.1658 +        sq_fingerprint_free(fpr);
  1.1659 +
  1.1660 +    return k;
  1.1661 +}
  1.1662 +
  1.1663 +// pattern could be empty, an fpr, or a mailbox.
  1.1664 +//
  1.1665 +// keyinfo_list is a list of <fpr, openpgp userid> tuples for the
  1.1666 +// matching keys.
  1.1667 +//
  1.1668 +// This function filters out revoked key, but not expired keys.
  1.1669 +PEP_STATUS pgp_list_keyinfo(PEP_SESSION session,
  1.1670 +                            const char* pattern,
  1.1671 +                            stringpair_list_t** keyinfo_list)
  1.1672 +{
  1.1673 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1674 +    sq_tpk_t tpk = NULL;
  1.1675 +    sq_fingerprint_t fpr = NULL;
  1.1676 +
  1.1677 +    T("('%s')", pattern);
  1.1678 +
  1.1679 +    *keyinfo_list = new_stringpair_list(NULL);
  1.1680 +    if (!*keyinfo_list)
  1.1681 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "new_stringlist");
  1.1682 +
  1.1683 +    // Trim any leading space.  This also makes it easier to recognize
  1.1684 +    // a string that is only whitespace.
  1.1685 +    while (*pattern == ' ')
  1.1686 +        pattern ++;
  1.1687 +
  1.1688 +    if (strchr(pattern, '@')) {
  1.1689 +        // Looks like a mailbox.
  1.1690 +        status = tpk_find_by_label(session, pattern, &tpk);
  1.1691 +        ERROR_OUT(session, status, "Looking up '%s'", pattern);
  1.1692 +        add_key(session, *keyinfo_list, tpk, NULL);
  1.1693 +
  1.1694 +        assert(!"pgp_list_keyinfo(email) untested, please make a test case");
  1.1695 +    } else if (// Only hex characters and spaces
  1.1696 +               pattern[strspn(pattern, "0123456789aAbBcCdDeEfF ")] == 0
  1.1697 +               // And a fair amount of them.
  1.1698 +               && strlen(pattern) >= 16) {
  1.1699 +        // Fingerprint.
  1.1700 +        fpr = sq_fingerprint_from_hex(pattern);
  1.1701 +        status = tpk_find_by_fpr(session, fpr, &tpk);
  1.1702 +        ERROR_OUT(session, status, "Looking up key");
  1.1703 +        add_key(session, *keyinfo_list, tpk, fpr);
  1.1704 +
  1.1705 +        assert(!"pgp_list_keyinfo(fpr) untested, please make a test case");
  1.1706 +    } else if (pattern[0] == 0) {
  1.1707 +        // Empty string.
  1.1708 +        sq_binding_iter_t iter = sq_store_iter(session->ctx, session->store);
  1.1709 +        sq_binding_t binding;
  1.1710 +        char *label;
  1.1711 +        stringpair_list_t *_k = *keyinfo_list;
  1.1712 +        while ((binding = sq_binding_iter_next(iter, &label, &fpr))) {
  1.1713 +            if (strchr(label, '@')) {
  1.1714 +                char *fpr_str = sq_fingerprint_to_hex(fpr);
  1.1715 +                T("  %s -> %s", fpr_str, label);
  1.1716 +                _k = stringpair_list_add(_k, new_stringpair(fpr_str, label));
  1.1717 +                free(fpr_str);
  1.1718 +            }
  1.1719 +            free(label);
  1.1720 +            sq_fingerprint_free(fpr);
  1.1721 +            fpr = NULL;
  1.1722 +            sq_binding_free(binding);
  1.1723 +        }
  1.1724 +        sq_binding_iter_free(iter);
  1.1725 +    }
  1.1726 +
  1.1727 + out:
  1.1728 +    if (tpk)
  1.1729 +        sq_tpk_free(tpk);
  1.1730 +    if (fpr)
  1.1731 +        sq_fingerprint_free(fpr);
  1.1732 +    if (status != PEP_STATUS_OK && *keyinfo_list) {
  1.1733 +        free_stringpair_list(*keyinfo_list);
  1.1734 +        *keyinfo_list = NULL;
  1.1735 +    }
  1.1736 +    if (status == PEP_KEY_NOT_FOUND)
  1.1737 +        status = PEP_STATUS_OK;
  1.1738 +
  1.1739 +    T("(%s) -> %s", pattern, pep_status_to_string(status));
  1.1740 +    return status;
  1.1741 +}
  1.1742 +
  1.1743 +PEP_STATUS pgp_recv_key(PEP_SESSION session, const char *pattern)
  1.1744 +{
  1.1745 +    assert(!"pgp_recv_key not implemented");
  1.1746 +    return PEP_UNKNOWN_ERROR;
  1.1747 +}
  1.1748 +
  1.1749 +char* _undot_address(const char* address) {
  1.1750 +    if (!address)
  1.1751 +        return NULL;
  1.1752 +
  1.1753 +    int addr_len = strlen(address);
  1.1754 +    const char* at = strstr(address, "@");
  1.1755 +
  1.1756 +    if (!at)
  1.1757 +        at = address + addr_len;
  1.1758 +
  1.1759 +    char* retval = calloc(1, addr_len + 1);
  1.1760 +
  1.1761 +    const char* addr_curr = address;
  1.1762 +    char* retval_curr = retval;
  1.1763 +
  1.1764 +    while (addr_curr < at) {
  1.1765 +        if (*addr_curr == '.') {
  1.1766 +            addr_curr++;
  1.1767 +            continue;
  1.1768 +        }
  1.1769 +        *retval_curr = *addr_curr;
  1.1770 +        retval_curr++;
  1.1771 +        addr_curr++;
  1.1772 +    }
  1.1773 +    if (*addr_curr == '@')
  1.1774 +        strcat(retval_curr, addr_curr);
  1.1775 +
  1.1776 +    return retval;
  1.1777 +}
  1.1778 +
  1.1779 +// Unlike pgp_list_keyinfo, this function returns revoked keys.
  1.1780 +static PEP_STATUS _pgp_search_keys(PEP_SESSION session, const char* pattern,
  1.1781 +                                   stringlist_t** keylist, int private_only) {
  1.1782 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1783 +    sq_binding_t binding = NULL;
  1.1784 +    sq_tpk_t tpk = NULL;
  1.1785 +    sq_fingerprint_t fingerprint = NULL;
  1.1786 +    char *fingerprint_hex = NULL;
  1.1787 +
  1.1788 +    *keylist = NULL;
  1.1789 +
  1.1790 +    // XXX: We only return an exact match.
  1.1791 +    T("(pattern: %s, private_only: %d)", pattern, private_only);
  1.1792 +
  1.1793 +    binding = sq_store_lookup(session->ctx, session->store, pattern);
  1.1794 +    if (! binding) {
  1.1795 +        // No binding is not an error: it means there is no match.
  1.1796 +        if (pattern != NULL) {
  1.1797 +            // If match failed, check to see if we've got a dotted
  1.1798 +            // address in the pattern.  If so, try again without dots.
  1.1799 +            const char* dotpos = strstr(pattern, ".");
  1.1800 +            const char* atpos = strstr(pattern, "@");
  1.1801 +            if (dotpos && atpos && (dotpos < atpos)) {
  1.1802 +                char* undotted = _undot_address(pattern);
  1.1803 +                if (undotted) {
  1.1804 +                    PEP_STATUS status = _pgp_search_keys(session, undotted,
  1.1805 +                                                         keylist, private_only);
  1.1806 +                    free(undotted);
  1.1807 +                    return status;
  1.1808 +                }
  1.1809 +            }
  1.1810 +        }
  1.1811 +        goto out;
  1.1812 +    }
  1.1813 +
  1.1814 +    tpk = sq_binding_tpk(session->ctx, binding);
  1.1815 +    if (! tpk)
  1.1816 +        ERROR_OUT(session, PEP_GET_KEY_FAILED, "Getting TPK");
  1.1817 +
  1.1818 +    fingerprint = sq_tpk_fingerprint(tpk);
  1.1819 +    if (!fingerprint)
  1.1820 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "Getting fingerprint");
  1.1821 +
  1.1822 +    if (private_only) {
  1.1823 +        // See if we have the private key.
  1.1824 +        status = tsk_find_by_fpr(session, fingerprint, NULL);
  1.1825 +        ERROR_OUT(session, status, "No private key material");
  1.1826 +    }
  1.1827 +
  1.1828 +    fingerprint_hex = sq_fingerprint_to_hex(fingerprint);
  1.1829 +    if (!fingerprint_hex)
  1.1830 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "sq_fingerprint_to_hex");
  1.1831 +
  1.1832 +    stringlist_t *_keylist = new_stringlist(fingerprint_hex);
  1.1833 +    if (_keylist == NULL)
  1.1834 +        ERROR_OUT(session, PEP_OUT_OF_MEMORY, "new_stringlist");
  1.1835 +    *keylist = _keylist;
  1.1836 +
  1.1837 + out:
  1.1838 +    free(fingerprint_hex);
  1.1839 +    if (fingerprint)
  1.1840 +        sq_fingerprint_free(fingerprint);
  1.1841 +    if (tpk)
  1.1842 +        sq_tpk_free(tpk);
  1.1843 +    if (binding)
  1.1844 +        sq_binding_free(binding);
  1.1845 +
  1.1846 +    T("(pattern: %s, private_only: %d) -> %s",
  1.1847 +      pattern, private_only, pep_status_to_string(status));
  1.1848 +    return status;
  1.1849 +}
  1.1850 +
  1.1851 +PEP_STATUS pgp_find_keys(
  1.1852 +    PEP_SESSION session, const char *pattern, stringlist_t **keylist)
  1.1853 +{
  1.1854 +    return _pgp_search_keys(session, pattern, keylist, 0);
  1.1855 +}
  1.1856 +
  1.1857 +PEP_STATUS pgp_find_private_keys(
  1.1858 +    PEP_SESSION session, const char *pattern, stringlist_t **keylist)
  1.1859 +{
  1.1860 +    return _pgp_search_keys(session, pattern, keylist, 1);
  1.1861 +}
  1.1862 +
  1.1863 +PEP_STATUS pgp_send_key(PEP_SESSION session, const char *pattern)
  1.1864 +{
  1.1865 +    assert(!"pgp_send_key not implemented");
  1.1866 +    return PEP_UNKNOWN_ERROR;
  1.1867 +}
  1.1868 +
  1.1869 +PEP_STATUS pgp_get_key_rating(
  1.1870 +    PEP_SESSION session, const char *fpr, PEP_comm_type *comm_type)
  1.1871 +{
  1.1872 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1873 +    sq_tpk_t tpk = NULL;
  1.1874 +
  1.1875 +    assert(session);
  1.1876 +    assert(fpr);
  1.1877 +    assert(comm_type);
  1.1878 +
  1.1879 +    *comm_type = PEP_ct_unknown;
  1.1880 +
  1.1881 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  1.1882 +    status = tpk_find_by_fpr(session, sq_fpr, &tpk);
  1.1883 +    sq_fingerprint_free(sq_fpr);
  1.1884 +    ERROR_OUT(session, status, "Looking up key: %s", fpr);
  1.1885 +
  1.1886 +    *comm_type = PEP_ct_OpenPGP_unconfirmed;
  1.1887 +
  1.1888 +    if (sq_tpk_expired(tpk)) {
  1.1889 +        *comm_type = PEP_ct_key_expired;
  1.1890 +        goto out;
  1.1891 +    }
  1.1892 +
  1.1893 +    sq_revocation_status_t rs = sq_tpk_revocation_status(tpk);
  1.1894 +    sq_revocation_status_variant_t rsv = sq_revocation_status_variant(rs);
  1.1895 +    sq_revocation_status_free(rs);
  1.1896 +    if (rsv == SQ_REVOCATION_STATUS_REVOKED) {
  1.1897 +        *comm_type = PEP_ct_key_revoked;
  1.1898 +        goto out;
  1.1899 +    }
  1.1900 +
  1.1901 +    PEP_comm_type best_enc = PEP_ct_no_encryption, best_sign = PEP_ct_no_encryption;
  1.1902 +    sq_tpk_key_iter_t key_iter = sq_tpk_key_iter(tpk);
  1.1903 +    sq_p_key_t key;
  1.1904 +    sq_signature_t sig;
  1.1905 +    sq_revocation_status_t rev;
  1.1906 +    while ((key = sq_tpk_key_iter_next(key_iter, &sig, &rev))) {
  1.1907 +        if (! sig)
  1.1908 +            continue;
  1.1909 +
  1.1910 +        if (sq_revocation_status_variant(rev) == SQ_REVOCATION_STATUS_REVOKED)
  1.1911 +            continue;
  1.1912 +
  1.1913 +        if (! sq_p_key_alive(key, sig))
  1.1914 +            continue;
  1.1915 +
  1.1916 +        PEP_comm_type curr = PEP_ct_no_encryption;
  1.1917 +
  1.1918 +        int can_enc = sq_signature_can_encrypt_for_transport(sig)
  1.1919 +            || sq_signature_can_encrypt_at_rest(sig);
  1.1920 +        int can_sign = sq_signature_can_sign(sig);
  1.1921 +
  1.1922 +        sq_public_key_algo_t pk_algo = sq_p_key_public_key_algo(key);
  1.1923 +        if (pk_algo == SQ_PUBLIC_KEY_ALGO_RSA_ENCRYPT_SIGN
  1.1924 +            || pk_algo == SQ_PUBLIC_KEY_ALGO_RSA_ENCRYPT
  1.1925 +            || pk_algo == SQ_PUBLIC_KEY_ALGO_RSA_SIGN) {
  1.1926 +            int bits = sq_p_key_public_key_bits(key);
  1.1927 +            if (bits < 1024)
  1.1928 +                curr = PEP_ct_key_too_short;
  1.1929 +            else if (bits == 1024)
  1.1930 +                curr = PEP_ct_OpenPGP_weak_unconfirmed;
  1.1931 +            else
  1.1932 +                curr = PEP_ct_OpenPGP_unconfirmed;
  1.1933 +        } else {
  1.1934 +            curr = PEP_ct_OpenPGP_unconfirmed;
  1.1935 +        }
  1.1936 +
  1.1937 +        if (can_enc)
  1.1938 +            best_enc = _MAX(best_enc, curr);
  1.1939 +
  1.1940 +        if (can_sign)
  1.1941 +            best_sign = _MAX(best_sign, curr);
  1.1942 +    }
  1.1943 +    sq_tpk_key_iter_free(key_iter);
  1.1944 +
  1.1945 +    if (best_enc == PEP_ct_no_encryption || best_sign == PEP_ct_no_encryption) {
  1.1946 +        *comm_type = PEP_ct_key_b0rken;
  1.1947 +        goto out;
  1.1948 +    } else {
  1.1949 +        *comm_type = _MIN(best_enc, best_sign);
  1.1950 +    }
  1.1951 +
  1.1952 + out:
  1.1953 +    if (tpk)
  1.1954 +        sq_tpk_free(tpk);
  1.1955 +
  1.1956 +    T("(%s) -> %s", fpr, pep_comm_type_to_string(*comm_type));
  1.1957 +    return status;
  1.1958 +}
  1.1959 +
  1.1960 +
  1.1961 +PEP_STATUS pgp_renew_key(
  1.1962 +    PEP_SESSION session, const char *fpr, const timestamp *ts)
  1.1963 +{
  1.1964 +    PEP_STATUS status = PEP_STATUS_OK;
  1.1965 +    sq_tsk_t tsk = NULL;
  1.1966 +    sq_tpk_t tpk = NULL;
  1.1967 +
  1.1968 +    time_t t = mktime((struct tm *) ts);
  1.1969 +
  1.1970 +    status = tsk_find_by_fpr_hex(session, fpr, &tsk);
  1.1971 +    ERROR_OUT(session, status, "Looking up '%s'", fpr);
  1.1972 +
  1.1973 +    tpk = sq_tsk_into_tpk(tsk);
  1.1974 +
  1.1975 +    uint32_t creation_time = sq_p_key_creation_time(sq_tpk_primary(tpk));
  1.1976 +    if (creation_time > t)
  1.1977 +        // The creation time is after the expiration time!
  1.1978 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR,
  1.1979 +                  "creation time can't be after expiration time");
  1.1980 +
  1.1981 +    uint32_t delta = t - creation_time;
  1.1982 +    tpk = sq_tpk_set_expiry(session->ctx, tpk, delta);
  1.1983 +    if (! tpk)
  1.1984 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "setting expiration");
  1.1985 +
  1.1986 +    status = tpk_save(session, tpk, NULL, NULL, false);
  1.1987 +    tpk = NULL;
  1.1988 +    ERROR_OUT(session, status, "Saving %s", fpr);
  1.1989 +
  1.1990 + out:
  1.1991 +    if (tpk)
  1.1992 +        sq_tpk_free(tpk);
  1.1993 +
  1.1994 +    return status;
  1.1995 +}
  1.1996 +
  1.1997 +PEP_STATUS pgp_revoke_key(
  1.1998 +    PEP_SESSION session, const char *fpr, const char *reason)
  1.1999 +{
  1.2000 +    PEP_STATUS status = PEP_STATUS_OK;
  1.2001 +    sq_tsk_t tsk = NULL;
  1.2002 +    sq_tpk_t tpk = NULL;
  1.2003 +
  1.2004 +    status = tsk_find_by_fpr_hex(session, fpr, &tsk);
  1.2005 +    ERROR_OUT(session, status, "Looking up %s", fpr);
  1.2006 +
  1.2007 +    tpk = sq_tsk_into_tpk(tsk);
  1.2008 +    tpk = sq_tpk_revoke_in_place(session->ctx, tpk,
  1.2009 +                                 SQ_REASON_FOR_REVOCATION_UNSPECIFIED,
  1.2010 +                                 reason);
  1.2011 +    if (! tpk)
  1.2012 +        ERROR_OUT(session, PEP_UNKNOWN_ERROR, "setting expiration");
  1.2013 +
  1.2014 +    assert(sq_revocation_status_variant(sq_tpk_revocation_status(tpk))
  1.2015 +           == SQ_REVOCATION_STATUS_REVOKED);
  1.2016 +
  1.2017 +    status = tpk_save(session, tpk, NULL, NULL, false);
  1.2018 +    tpk = NULL;
  1.2019 +    ERROR_OUT(session, status, "Saving %s", fpr);
  1.2020 +
  1.2021 + out:
  1.2022 +    if (tpk)
  1.2023 +        sq_tpk_free(tpk);
  1.2024 +
  1.2025 +    return status;
  1.2026 +}
  1.2027 +
  1.2028 +PEP_STATUS pgp_key_expired(PEP_SESSION session, const char *fpr,
  1.2029 +                           const time_t when, bool *expired)
  1.2030 +{
  1.2031 +    PEP_STATUS status = PEP_STATUS_OK;
  1.2032 +    sq_tpk_t tpk = NULL;
  1.2033 +
  1.2034 +    assert(session);
  1.2035 +    assert(fpr);
  1.2036 +    assert(expired);
  1.2037 +
  1.2038 +    *expired = false;
  1.2039 +
  1.2040 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  1.2041 +    status = tpk_find_by_fpr(session, sq_fpr, &tpk);
  1.2042 +    sq_fingerprint_free(sq_fpr);
  1.2043 +    ERROR_OUT(session, status, "Looking up %s", fpr);
  1.2044 +
  1.2045 +    // Is the TPK live?
  1.2046 +    *expired = !sq_tpk_alive_at(tpk, when);
  1.2047 +    if (*expired)
  1.2048 +        goto out;
  1.2049 +
  1.2050 +    // Are there at least one certification subkey, one signing subkey
  1.2051 +    // and one encryption subkey that are live?
  1.2052 +    int can_certify = 0, can_encrypt = 0, can_sign = 0;
  1.2053 +
  1.2054 +    sq_tpk_key_iter_t key_iter = sq_tpk_key_iter(tpk);
  1.2055 +    sq_p_key_t key;
  1.2056 +    sq_signature_t sig;
  1.2057 +    sq_revocation_status_t rev;
  1.2058 +    while ((key = sq_tpk_key_iter_next(key_iter, &sig, &rev))) {
  1.2059 +        if (! sig)
  1.2060 +            continue;
  1.2061 +
  1.2062 +        if (sq_revocation_status_variant(rev) == SQ_REVOCATION_STATUS_REVOKED)
  1.2063 +            continue;
  1.2064 +
  1.2065 +        if (!sq_p_key_alive_at(key, sig, when))
  1.2066 +            continue;
  1.2067 +
  1.2068 +        if (sq_signature_can_encrypt_for_transport(sig)
  1.2069 +            || sq_signature_can_encrypt_at_rest(sig))
  1.2070 +            can_encrypt = 1;
  1.2071 +        if (sq_signature_can_sign(sig))
  1.2072 +            can_sign = 1;
  1.2073 +        if (sq_signature_can_certify(sig))
  1.2074 +            can_certify = 1;
  1.2075 +
  1.2076 +        if (can_encrypt && can_sign && can_certify)
  1.2077 +            break;
  1.2078 +    }
  1.2079 +    sq_tpk_key_iter_free(key_iter);
  1.2080 +
  1.2081 +    *expired = !(can_encrypt && can_sign && can_certify);
  1.2082 +
  1.2083 + out:
  1.2084 +    if (tpk)
  1.2085 +        sq_tpk_free(tpk);
  1.2086 +    return status;
  1.2087 +}
  1.2088 +
  1.2089 +PEP_STATUS pgp_key_revoked(PEP_SESSION session, const char *fpr, bool *revoked)
  1.2090 +{
  1.2091 +    PEP_STATUS status = PEP_STATUS_OK;
  1.2092 +    sq_tpk_t tpk;
  1.2093 +
  1.2094 +    assert(session);
  1.2095 +    assert(fpr);
  1.2096 +    assert(revoked);
  1.2097 +
  1.2098 +    *revoked = false;
  1.2099 +
  1.2100 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  1.2101 +    status = tpk_find_by_fpr(session, sq_fpr, &tpk);
  1.2102 +    sq_fingerprint_free(sq_fpr);
  1.2103 +    ERROR_OUT(session, status, "Looking up %s", fpr);
  1.2104 +
  1.2105 +    sq_revocation_status_t rs = sq_tpk_revocation_status(tpk);
  1.2106 +    *revoked = sq_revocation_status_variant(rs) == SQ_REVOCATION_STATUS_REVOKED;
  1.2107 +    sq_revocation_status_free (rs);
  1.2108 +    sq_tpk_free(tpk);
  1.2109 +
  1.2110 + out:
  1.2111 +    return status;
  1.2112 +}
  1.2113 +
  1.2114 +PEP_STATUS pgp_key_created(PEP_SESSION session, const char *fpr, time_t *created)
  1.2115 +{
  1.2116 +    PEP_STATUS status = PEP_STATUS_OK;
  1.2117 +    sq_tpk_t tpk = NULL;
  1.2118 +
  1.2119 +    *created = 0;
  1.2120 +
  1.2121 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  1.2122 +    status = tpk_find_by_fpr(session, sq_fpr, &tpk);
  1.2123 +    sq_fingerprint_free(sq_fpr);
  1.2124 +    ERROR_OUT(session, status, "Looking up %s", fpr);
  1.2125 +
  1.2126 +    sq_p_key_t k = sq_tpk_primary(tpk);
  1.2127 +    *created = sq_p_key_creation_time(k);
  1.2128 +    sq_tpk_free(tpk);
  1.2129 +
  1.2130 + out:
  1.2131 +    return status;
  1.2132 +}
  1.2133 +
  1.2134 +PEP_STATUS pgp_binary(const char **path)
  1.2135 +{
  1.2136 +    return PEP_STATUS_OK;
  1.2137 +}
  1.2138 +
  1.2139 +PEP_STATUS pgp_contains_priv_key(PEP_SESSION session, const char *fpr,
  1.2140 +                                 bool *has_private)
  1.2141 +{
  1.2142 +    sq_fingerprint_t sq_fpr = sq_fingerprint_from_hex(fpr);
  1.2143 +    PEP_STATUS status = tsk_find_by_fpr(session, sq_fpr, NULL);
  1.2144 +    sq_fingerprint_free(sq_fpr);
  1.2145 +    if (status == PEP_STATUS_OK) {
  1.2146 +        *has_private = 1;
  1.2147 +        return PEP_STATUS_OK;
  1.2148 +    } else if (status == PEP_KEY_NOT_FOUND) {
  1.2149 +        *has_private = 0;
  1.2150 +        return PEP_STATUS_OK;
  1.2151 +    } else {
  1.2152 +        return status;
  1.2153 +    }
  1.2154 +}