src/pgp_sequoia.c
author Neal H. Walfield <neal@pep.foundation>
Fri, 10 May 2019 11:35:31 +0200
branchsync
changeset 3659 bd1c82a4f0ff
parent 3658 733edb269d7d
child 3661 448ed57fac2c
child 3662 54d7ca4f7529
permissions -rw-r--r--
sequoia: Track Sequoia API changes
     1 // This file is under GNU General Public License 3.0
     2 // see LICENSE.txt
     3 
     4 #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
     5 
     6 #define _GNU_SOURCE 1
     7 
     8 #include "platform.h"
     9 #include "pEp_internal.h"
    10 #include "pgp_gpg.h"
    11 
    12 #include <limits.h>
    13 #include <sys/stat.h>
    14 #include <sys/types.h>
    15 
    16 #include "wrappers.h"
    17 
    18 #define TRACING 0
    19 #ifndef TRACING
    20 #  ifndef NDEBUG
    21 #    define TRACING 0
    22 #  else
    23 #    define TRACING 1
    24 #  endif
    25 #endif
    26 
    27 // enable tracing if in debugging mode
    28 #if TRACING
    29 #include "status_to_string.h"
    30 #  define _T(...) do {                          \
    31         fprintf(stderr, ##__VA_ARGS__);         \
    32     } while (0)
    33 #else
    34 #  define _T(...) do { } while (0)
    35 #endif
    36 
    37 // Show the start of a tracepoint (i.e., don't print a newline).
    38 #define TC(...) do {       \
    39     _T("%s: ", __func__);  \
    40     _T(__VA_ARGS__);       \
    41 } while (0)
    42 
    43 // Show a trace point.
    44 #  define T(...) do {  \
    45     TC(__VA_ARGS__); \
    46     _T("\n");          \
    47 } while(0)
    48 
    49 // Verbosely displays errors.
    50 #  define DUMP_STATUS(__de_sq_status, __de_pep_status, ...) do { \
    51     TC(__VA_ARGS__);                                            \
    52     _T(": ");                                                   \
    53     if (__de_sq_status) {                                       \
    54         _T("Sequoia: %s => ", pgp_status_to_string(__de_sq_status));   \
    55     }                                                           \
    56     _T("%s\n", pEp_status_to_string(__de_pep_status));          \
    57 } while(0)
    58 
    59 #  define DUMP_ERR(__de_err, __de_status, ...) do {             \
    60     TC(__VA_ARGS__);                                            \
    61     _T(": ");                                                   \
    62     if (__de_err) {                                             \
    63         _T("Sequoia: %s => ", pgp_error_to_string(__de_err));   \
    64         pgp_error_free(__de_err);                               \
    65     }                                                           \
    66     _T("%s\n", pEp_status_to_string(__de_status));              \
    67 } while(0)
    68 
    69 // If __ec_status is an error, then disable the error, set 'status' to
    70 // it, and jump to 'out'.
    71 #define ERROR_OUT(__e_err, __ec_status, ...) do {                   \
    72     PEP_STATUS ___ec_status = (__ec_status);                        \
    73     if ((___ec_status) != PEP_STATUS_OK) {                          \
    74         DUMP_ERR((__e_err), (___ec_status), ##__VA_ARGS__);         \
    75         status = (___ec_status);                                    \
    76         goto out;                                                   \
    77     }                                                               \
    78 } while(0)
    79 
    80 int email_cmp(void *cookie, int a_len, const void *a, int b_len, const void *b)
    81 {
    82     pgp_packet_t a_userid = pgp_user_id_from_raw (a, a_len);
    83     pgp_packet_t b_userid = pgp_user_id_from_raw (b, b_len);
    84 
    85     T("(%.*s, %.*s)", a_len, (const char *) a, b_len, (const char *) b);
    86 
    87     char *a_address = NULL;
    88     pgp_user_id_address_normalized(NULL, a_userid, &a_address);
    89 
    90     char *b_address = NULL;
    91     pgp_user_id_address_normalized(NULL, b_userid, &b_address);
    92 
    93     pgp_packet_free(a_userid);
    94     pgp_packet_free(b_userid);
    95 
    96     // return an integer that is negative, zero, or positive if the
    97     // first string is less than, equal to, or greater than the
    98     // second, respectively.
    99     int result;
   100     if (!a_address && !b_address)
   101         result = 0;
   102     else if (!a_address)
   103         result = -1;
   104     else if (!b_address)
   105         result = 1;
   106     else
   107         result = strcmp(a_address, b_address);
   108 
   109     if (true) {
   110         T("'%s' %s '%s'",
   111           a_address,
   112           result == 0 ? "==" : result < 0 ? "<" : ">",
   113           b_address);
   114     }
   115 
   116     free(a_address);
   117     free(b_address);
   118 
   119     return result;
   120 }
   121 
   122 PEP_STATUS pgp_init(PEP_SESSION session, bool in_first)
   123 {
   124     PEP_STATUS status = PEP_STATUS_OK;
   125 
   126     // Create the home directory.
   127     char *home_env = getenv("HOME");
   128     if (!home_env)
   129         ERROR_OUT(NULL, PEP_INIT_GPGME_INIT_FAILED, "HOME unset");
   130 
   131     // Create the DB and initialize it.
   132     size_t path_size = strlen(home_env)+13+1;
   133     char *path = (char *) calloc(1, path_size);
   134     assert(path);
   135     if (!path)
   136         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
   137 
   138     int r = snprintf(path, path_size, "%s/.pEp_keys.db", home_env);
   139     assert(r >= 0 && r < path_size);
   140     if (r < 0)
   141         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR, "snprintf");
   142 
   143     int sqlite_result;
   144     sqlite_result = sqlite3_open_v2(path,
   145                                     &session->key_db,
   146                                     SQLITE_OPEN_READWRITE
   147                                     | SQLITE_OPEN_CREATE
   148                                     | SQLITE_OPEN_FULLMUTEX
   149                                     | SQLITE_OPEN_PRIVATECACHE,
   150                                     NULL);
   151     free(path);
   152     if (sqlite_result != SQLITE_OK)
   153         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   154                   "opening keys DB: %s", sqlite3_errmsg(session->key_db));
   155 
   156     sqlite_result = sqlite3_exec(session->key_db,
   157                                  "PRAGMA secure_delete=true;\n"
   158                                  "PRAGMA foreign_keys=true;\n"
   159                                  "PRAGMA locking_mode=NORMAL;\n"
   160                                  "PRAGMA journal_mode=WAL;\n",
   161                                  NULL, NULL, NULL);
   162     if (sqlite_result != SQLITE_OK)
   163         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   164                   "setting pragmas: %s", sqlite3_errmsg(session->key_db));
   165 
   166     sqlite3_busy_timeout(session->key_db, BUSY_WAIT_TIME);
   167 
   168     sqlite_result =
   169         sqlite3_create_collation(session->key_db,
   170                                 "EMAIL",
   171                                 SQLITE_UTF8,
   172                                 /* pArg (cookie) */ NULL,
   173                                 email_cmp);
   174     if (sqlite_result != SQLITE_OK)
   175         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   176                   "registering EMAIL collation function: %s",
   177                   sqlite3_errmsg(session->key_db));
   178 
   179     sqlite_result = sqlite3_exec(session->key_db,
   180                                  "CREATE TABLE IF NOT EXISTS keys (\n"
   181                                  "   primary_key TEXT UNIQUE PRIMARY KEY,\n"
   182                                  "   secret BOOLEAN,\n"
   183                                  "   tpk BLOB\n"
   184                                  ");\n"
   185                                  "CREATE INDEX IF NOT EXISTS keys_index\n"
   186                                  "  ON keys (primary_key, secret)\n",
   187                                  NULL, NULL, NULL);
   188     if (sqlite_result != SQLITE_OK)
   189         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   190                   "creating keys table: %s",
   191                   sqlite3_errmsg(session->key_db));
   192 
   193     sqlite_result = sqlite3_exec(session->key_db,
   194                                  "CREATE TABLE IF NOT EXISTS subkeys (\n"
   195                                  "   subkey TEXT NOT NULL,\n"
   196                                  "   primary_key TEXT NOT NULL,\n"
   197                                  "   UNIQUE(subkey, primary_key),\n"
   198                                  "   FOREIGN KEY (primary_key)\n"
   199                                  "       REFERENCES keys(primary_key)\n"
   200                                  "     ON DELETE CASCADE\n"
   201                                  ");\n"
   202                                  "CREATE INDEX IF NOT EXISTS subkeys_index\n"
   203                                  "  ON subkeys (subkey, primary_key)\n",
   204                                  NULL, NULL, NULL);
   205     if (sqlite_result != SQLITE_OK)
   206         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   207                   "creating subkeys table: %s",
   208                   sqlite3_errmsg(session->key_db));
   209 
   210     sqlite_result = sqlite3_exec(session->key_db,
   211                                  "CREATE TABLE IF NOT EXISTS userids (\n"
   212                                  "   userid TEXT NOT NULL COLLATE EMAIL,\n"
   213                                  "   primary_key TEXT NOT NULL,\n"
   214                                  "   UNIQUE(userid, primary_key),\n"
   215                                  "   FOREIGN KEY (primary_key)\n"
   216                                  "       REFERENCES keys(primary_key)\n"
   217                                  "     ON DELETE CASCADE\n"
   218                                  ");\n"
   219                                  "CREATE INDEX IF NOT EXISTS userids_index\n"
   220                                  "  ON userids (userid COLLATE EMAIL, primary_key)\n",
   221                                  NULL, NULL, NULL);
   222     if (sqlite_result != SQLITE_OK)
   223         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   224                   "creating userids table: %s",
   225                   sqlite3_errmsg(session->key_db));
   226 
   227     sqlite_result
   228         = sqlite3_prepare_v2(session->key_db, "begin transaction",
   229                              -1, &session->sq_sql.begin_transaction, NULL);
   230     assert(sqlite_result == SQLITE_OK);
   231 
   232     sqlite_result
   233         = sqlite3_prepare_v2(session->key_db, "commit transaction",
   234                              -1, &session->sq_sql.commit_transaction, NULL);
   235     assert(sqlite_result == SQLITE_OK);
   236 
   237     sqlite_result
   238         = sqlite3_prepare_v2(session->key_db, "rollback transaction",
   239                              -1, &session->sq_sql.rollback_transaction, NULL);
   240     assert(sqlite_result == SQLITE_OK);
   241 
   242     sqlite_result
   243         = sqlite3_prepare_v2(session->key_db,
   244                              "SELECT tpk, secret FROM keys"
   245                              " WHERE primary_key == ?",
   246                              -1, &session->sq_sql.tpk_find, NULL);
   247     assert(sqlite_result == SQLITE_OK);
   248 
   249     sqlite_result
   250         = sqlite3_prepare_v2(session->key_db,
   251                              "SELECT tpk, secret FROM keys"
   252                              " WHERE primary_key == ? and secret == 1",
   253                              -1, &session->sq_sql.tsk_find, NULL);
   254     assert(sqlite_result == SQLITE_OK);
   255 
   256     sqlite_result
   257         = sqlite3_prepare_v2(session->key_db,
   258                              "SELECT tpk, secret FROM subkeys"
   259                              " LEFT JOIN keys"
   260                              "  ON subkeys.primary_key == keys.primary_key"
   261                              " WHERE subkey == ?",
   262                              -1, &session->sq_sql.tpk_find_by_keyid, NULL);
   263     assert(sqlite_result == SQLITE_OK);
   264 
   265     sqlite_result
   266         = sqlite3_prepare_v2(session->key_db,
   267                              "SELECT tpk, secret FROM subkeys"
   268                              " LEFT JOIN keys"
   269                              "  ON subkeys.primary_key == keys.primary_key"
   270                              " WHERE subkey == ?",
   271                              -1, &session->sq_sql.tpk_find_by_keyid, NULL);
   272     assert(sqlite_result == SQLITE_OK);
   273 
   274     sqlite_result
   275         = sqlite3_prepare_v2(session->key_db,
   276                              "SELECT tpk, secret FROM subkeys"
   277                              " LEFT JOIN keys"
   278                              "  ON subkeys.primary_key == keys.primary_key"
   279                              " WHERE subkey == ? and keys.secret == 1",
   280                              -1, &session->sq_sql.tsk_find_by_keyid, NULL);
   281     assert(sqlite_result == SQLITE_OK);
   282 
   283     sqlite_result
   284         = sqlite3_prepare_v2(session->key_db,
   285                              "SELECT tpk, secret FROM userids"
   286                              " LEFT JOIN keys"
   287                              "  ON userids.primary_key == keys.primary_key"
   288                              " WHERE userid == ?",
   289                              -1, &session->sq_sql.tpk_find_by_email, NULL);
   290     assert(sqlite_result == SQLITE_OK);
   291 
   292     sqlite_result
   293         = sqlite3_prepare_v2(session->key_db,
   294                              "SELECT tpk, secret FROM userids"
   295                              " LEFT JOIN keys"
   296                              "  ON userids.primary_key == keys.primary_key"
   297                              " WHERE userid == ? and keys.secret == 1",
   298                              -1, &session->sq_sql.tsk_find_by_email, NULL);
   299     assert(sqlite_result == SQLITE_OK);
   300 
   301     sqlite_result
   302         = sqlite3_prepare_v2(session->key_db,
   303                              "select tpk, secret from keys",
   304                              -1, &session->sq_sql.tpk_all, NULL);
   305     assert(sqlite_result == SQLITE_OK);
   306 
   307     sqlite_result
   308         = sqlite3_prepare_v2(session->key_db,
   309                              "select tpk, secret from keys where secret = 1",
   310                              -1, &session->sq_sql.tsk_all, NULL);
   311     assert(sqlite_result == SQLITE_OK);
   312 
   313     sqlite_result
   314         = sqlite3_prepare_v2(session->key_db,
   315                              "INSERT OR REPLACE INTO keys"
   316                              "   (primary_key, secret, tpk)"
   317                              " VALUES (?, ?, ?)",
   318                              -1, &session->sq_sql.tpk_save_insert_primary, NULL);
   319     assert(sqlite_result == SQLITE_OK);
   320 
   321     sqlite_result
   322         = sqlite3_prepare_v2(session->key_db,
   323                              "INSERT OR REPLACE INTO subkeys"
   324                              "   (subkey, primary_key)"
   325                              " VALUES (?, ?)",
   326                              -1, &session->sq_sql.tpk_save_insert_subkeys, NULL);
   327     assert(sqlite_result == SQLITE_OK);
   328 
   329     sqlite_result
   330         = sqlite3_prepare_v2(session->key_db,
   331                              "INSERT OR REPLACE INTO userids"
   332                              "   (userid, primary_key)"
   333                              " VALUES (?, ?)",
   334                              -1, &session->sq_sql.tpk_save_insert_userids, NULL);
   335     assert(sqlite_result == SQLITE_OK);
   336 
   337  out:
   338     if (status != PEP_STATUS_OK)
   339         pgp_release(session, in_first);
   340     return status;
   341 }
   342 
   343 void pgp_release(PEP_SESSION session, bool out_last)
   344 {
   345     sqlite3_stmt **stmts = (sqlite3_stmt **) &session->sq_sql;
   346     for (int i = 0; i < sizeof(session->sq_sql) / sizeof(*stmts); i ++)
   347         if (stmts[i]) {
   348             sqlite3_finalize(stmts[i]);
   349             stmts[i] = NULL;
   350         }
   351 
   352     if (session->key_db) {
   353         int result = sqlite3_close_v2(session->key_db);
   354         if (result != 0)
   355             DUMP_ERR(NULL, PEP_UNKNOWN_ERROR,
   356                      "Closing key DB: sqlite3_close_v2: %s",
   357                      sqlite3_errstr(result));
   358         session->key_db = NULL;
   359     }
   360 }
   361 
   362 /* commented out to omit compiler warning about unused function
   363 
   364 // Ensures that a fingerprint is in canonical form.  A canonical
   365 // fingerprint doesn't contain any white space.
   366 //
   367 // This function does *not* consume fpr.
   368 static char *pgp_fingerprint_canonicalize(const char *) __attribute__((nonnull));
   369 static char *pgp_fingerprint_canonicalize(const char *fpr)
   370 {
   371     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
   372     char *fpr_canonicalized = pgp_fingerprint_to_hex(pgp_fpr);
   373     pgp_fingerprint_free(pgp_fpr);
   374 
   375     return fpr_canonicalized;
   376 }
   377 
   378 */
   379 
   380 // step statement and load the tpk and secret.
   381 static PEP_STATUS key_load(PEP_SESSION, sqlite3_stmt *, pgp_tpk_t *, int *)
   382     __attribute__((nonnull(1, 2)));
   383 static PEP_STATUS key_load(PEP_SESSION session, sqlite3_stmt *stmt,
   384                            pgp_tpk_t *tpkp, int *secretp)
   385 {
   386     PEP_STATUS status = PEP_STATUS_OK;
   387     int sqlite_result = sqlite3_step(stmt);
   388     switch (sqlite_result) {
   389     case SQLITE_ROW:
   390         if (tpkp) {
   391             int data_len = sqlite3_column_bytes(stmt, 0);
   392             const void *data = sqlite3_column_blob(stmt, 0);
   393 
   394             pgp_error_t err = NULL;
   395             *tpkp = pgp_tpk_from_bytes(&err, data, data_len);
   396             if (!*tpkp)
   397                 ERROR_OUT(err, PEP_GET_KEY_FAILED, "parsing TPK");
   398         }
   399 
   400         if (secretp)
   401             *secretp = sqlite3_column_int(stmt, 1);
   402 
   403         break;
   404     case SQLITE_DONE:
   405         // Got nothing.
   406         status = PEP_KEY_NOT_FOUND;
   407         break;
   408     default:
   409         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   410                   "stepping: %s", sqlite3_errmsg(session->key_db));
   411     }
   412 
   413  out:
   414     T(" -> %s", pEp_status_to_string(status));
   415     return status;
   416 }
   417 
   418 // step statement until exhausted and load the tpks.
   419 static PEP_STATUS key_loadn(PEP_SESSION, sqlite3_stmt *, pgp_tpk_t **, int *)
   420     __attribute__((nonnull));
   421 static PEP_STATUS key_loadn(PEP_SESSION session, sqlite3_stmt *stmt,
   422                             pgp_tpk_t **tpksp, int *tpks_countp)
   423 {
   424     PEP_STATUS status = PEP_STATUS_OK;
   425     int tpks_count = 0;
   426     int tpks_capacity = 8;
   427     pgp_tpk_t *tpks = calloc(tpks_capacity, sizeof(pgp_tpk_t));
   428     if (!tpks)
   429         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
   430 
   431     for (;;) {
   432         pgp_tpk_t tpk = NULL;
   433         status = key_load(session, stmt, &tpk, NULL);
   434         if (status == PEP_KEY_NOT_FOUND) {
   435             status = PEP_STATUS_OK;
   436             break;
   437         }
   438         ERROR_OUT(NULL, status, "loading TPK");
   439 
   440         if (tpks_count == tpks_capacity) {
   441             tpks_capacity *= 2;
   442             tpks = realloc(tpks, sizeof(tpks[0]) * tpks_capacity);
   443             if (!tpks)
   444                 ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "tpks");
   445         }
   446         tpks[tpks_count ++] = tpk;
   447     }
   448 
   449  out:
   450     if (status != PEP_STATUS_OK) {
   451         for (int i = 0; i < tpks_count; i ++)
   452             pgp_tpk_free(tpks[i]);
   453         free(tpks);
   454     } else {
   455         *tpksp = tpks;
   456         *tpks_countp = tpks_count;
   457     }
   458 
   459     T(" -> %s (%d tpks)", pEp_status_to_string(status), *tpks_countp);
   460     return status;
   461 }
   462 
   463 // Returns the TPK identified by the provided fingerprint.
   464 //
   465 // This function only matches on the primary key!
   466 static PEP_STATUS tpk_find(PEP_SESSION, pgp_fingerprint_t, int, pgp_tpk_t *, int *)
   467     __attribute__((nonnull(1, 2)));
   468 static PEP_STATUS tpk_find(PEP_SESSION session,
   469                            pgp_fingerprint_t fpr, int private_only,
   470                            pgp_tpk_t *tpk, int *secret)
   471 {
   472     PEP_STATUS status = PEP_STATUS_OK;
   473     char *fpr_str = pgp_fingerprint_to_hex(fpr);
   474 
   475     T("(%s, %d)", fpr_str, private_only);
   476 
   477     sqlite3_stmt *stmt
   478         = private_only ? session->sq_sql.tsk_find : session->sq_sql.tpk_find;
   479     sqlite3_bind_text(stmt, 1, fpr_str, -1, SQLITE_STATIC);
   480 
   481     status = key_load(session, stmt, tpk, secret);
   482     ERROR_OUT(NULL, status, "Looking up %s", fpr_str);
   483 
   484  out:
   485     sqlite3_reset(stmt);
   486     T("(%s, %d) -> %s", fpr_str, private_only, pEp_status_to_string(status));
   487     free(fpr_str);
   488     return status;
   489 }
   490 
   491 // Returns the TPK identified by the provided keyid.
   492 //
   493 // This function matches on both primary keys and subkeys!
   494 //
   495 // Note: There can be multiple TPKs for a given keyid.  This can
   496 // occur, because an encryption subkey can be bound to multiple TPKs.
   497 // Also, it is possible to collide key ids.  If there are multiple key
   498 // ids for a given key, this just returns one of them.
   499 //
   500 // If private_only is set, this will only consider TPKs with some
   501 // secret key material.
   502 static PEP_STATUS tpk_find_by_keyid_hex(PEP_SESSION, const char *, int, pgp_tpk_t *, int *)
   503   __attribute__((nonnull(1, 2)));
   504 static PEP_STATUS tpk_find_by_keyid_hex(
   505         PEP_SESSION session, const char *keyid_hex, int private_only,
   506         pgp_tpk_t *tpkp, int *secretp)
   507 {
   508     PEP_STATUS status = PEP_STATUS_OK;
   509     T("(%s, %d)", keyid_hex, private_only);
   510 
   511     sqlite3_stmt *stmt
   512         = private_only ? session->sq_sql.tsk_find_by_keyid : session->sq_sql.tpk_find_by_keyid;
   513     sqlite3_bind_text(stmt, 1, keyid_hex, -1, SQLITE_STATIC);
   514 
   515     status = key_load(session, stmt, tpkp, secretp);
   516     ERROR_OUT(NULL, status, "Looking up %s", keyid_hex);
   517 
   518  out:
   519     sqlite3_reset(stmt);
   520     T("(%s, %d) -> %s", keyid_hex, private_only, pEp_status_to_string(status));
   521     return status;
   522 }
   523 
   524 // See tpk_find_by_keyid_hex.
   525 PEP_STATUS tpk_find_by_keyid(PEP_SESSION, pgp_keyid_t, int, pgp_tpk_t *, int *)
   526     __attribute__((nonnull(1, 2)));
   527 PEP_STATUS tpk_find_by_keyid(PEP_SESSION session,
   528                              pgp_keyid_t keyid, int private_only,
   529                              pgp_tpk_t *tpkp, int *secretp)
   530 {
   531     char *keyid_hex = pgp_keyid_to_hex(keyid);
   532     if (! keyid_hex)
   533         return PEP_OUT_OF_MEMORY;
   534     PEP_STATUS status
   535         = tpk_find_by_keyid_hex(session, keyid_hex, private_only, tpkp, secretp);
   536     free(keyid_hex);
   537     return status;
   538 }
   539 
   540 // See tpk_find_by_keyid_hex.
   541 static PEP_STATUS tpk_find_by_fpr(PEP_SESSION, pgp_fingerprint_t, int,
   542                                   pgp_tpk_t *, int *)
   543     __attribute__((nonnull(1, 2)));
   544 static PEP_STATUS tpk_find_by_fpr(
   545     PEP_SESSION session, pgp_fingerprint_t fpr, int private_only,
   546     pgp_tpk_t *tpkp, int *secretp)
   547 {
   548     pgp_keyid_t keyid = pgp_fingerprint_to_keyid(fpr);
   549     if (! keyid)
   550         return PEP_OUT_OF_MEMORY;
   551     PEP_STATUS status
   552         = tpk_find_by_keyid(session, keyid, private_only, tpkp, secretp);
   553     pgp_keyid_free(keyid);
   554     return status;
   555 }
   556 
   557 // See tpk_find_by_keyid_hex.
   558 static PEP_STATUS tpk_find_by_fpr_hex(PEP_SESSION, const char *, int, pgp_tpk_t *, int *secret)
   559     __attribute__((nonnull(1, 2)));
   560 static PEP_STATUS tpk_find_by_fpr_hex(
   561     PEP_SESSION session, const char *fpr, int private_only,
   562     pgp_tpk_t *tpkp, int *secretp)
   563 {
   564     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
   565     if (! pgp_fpr)
   566         return PEP_OUT_OF_MEMORY;
   567     PEP_STATUS status
   568         = tpk_find_by_fpr(session, pgp_fpr, private_only, tpkp, secretp);
   569     pgp_fingerprint_free(pgp_fpr);
   570     return status;
   571 }
   572 
   573 // Returns all known TPKs.
   574 static PEP_STATUS tpk_all(PEP_SESSION, int, pgp_tpk_t **, int *) __attribute__((nonnull));
   575 static PEP_STATUS tpk_all(PEP_SESSION session, int private_only,
   576                           pgp_tpk_t **tpksp, int *tpks_countp) {
   577     PEP_STATUS status = PEP_STATUS_OK;
   578     sqlite3_stmt *stmt = private_only ? session->sq_sql.tsk_all : session->sq_sql.tpk_all;
   579     status = key_loadn(session, stmt, tpksp, tpks_countp);
   580     ERROR_OUT(NULL, status, "loading TPKs");
   581  out:
   582     sqlite3_reset(stmt);
   583     return status;
   584 }
   585 
   586 // Returns keys that have a user id that matches the specified pattern.
   587 //
   588 // The keys returned must be freed using pgp_tpk_free.
   589 static PEP_STATUS tpk_find_by_email(PEP_SESSION, const char *, int, pgp_tpk_t **, int *)
   590     __attribute__((nonnull));
   591 static PEP_STATUS tpk_find_by_email(PEP_SESSION session,
   592                                     const char *pattern, int private_only,
   593                                     pgp_tpk_t **tpksp, int *countp)
   594 {
   595     PEP_STATUS status = PEP_STATUS_OK;
   596     T("(%s)", pattern);
   597 
   598     sqlite3_stmt *stmt
   599         = private_only ? session->sq_sql.tsk_find_by_email : session->sq_sql.tpk_find_by_email;
   600     sqlite3_bind_text(stmt, 1, pattern, -1, SQLITE_STATIC);
   601 
   602     status = key_loadn(session, stmt, tpksp, countp);
   603     ERROR_OUT(NULL, status, "Searching for '%s'", pattern);
   604 
   605  out:
   606     sqlite3_reset(stmt);
   607     T("(%s) -> %s (%d results)", pattern, pEp_status_to_string(status), *countp);
   608     return status;
   609 }
   610 
   611 
   612 // Saves the specified TPK.
   613 //
   614 // This function takes ownership of TPK.
   615 static PEP_STATUS tpk_save(PEP_SESSION, pgp_tpk_t, identity_list **)
   616     __attribute__((nonnull(1, 2)));
   617 static PEP_STATUS tpk_save(PEP_SESSION session, pgp_tpk_t tpk,
   618                            identity_list **private_idents)
   619 {
   620     PEP_STATUS status = PEP_STATUS_OK;
   621     pgp_error_t err = NULL;
   622     pgp_fingerprint_t pgp_fpr = NULL;
   623     char *fpr = NULL;
   624     void *tsk_buffer = NULL;
   625     size_t tsk_buffer_len = 0;
   626     int tried_commit = 0;
   627     pgp_tpk_key_iter_t key_iter = NULL;
   628     pgp_user_id_binding_iter_t user_id_iter = NULL;
   629     char *email = NULL;
   630     char *name = NULL;
   631 
   632     sqlite3_stmt *stmt = session->sq_sql.begin_transaction;
   633     int sqlite_result = sqlite3_step(stmt);
   634     sqlite3_reset(stmt);
   635     if (sqlite_result != SQLITE_DONE)
   636         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   637                   "begin transaction failed: %s",
   638                   sqlite3_errmsg(session->key_db));
   639 
   640     pgp_fpr = pgp_tpk_fingerprint(tpk);
   641     fpr = pgp_fingerprint_to_hex(pgp_fpr);
   642     T("(%s, private_idents: %s)", fpr, private_idents ? "yes" : "no");
   643 
   644     // Merge any existing data into TPK.
   645     pgp_tpk_t current = NULL;
   646     status = tpk_find(session, pgp_fpr, false, &current, NULL);
   647     if (status == PEP_KEY_NOT_FOUND)
   648         status = PEP_STATUS_OK;
   649     else
   650         ERROR_OUT(NULL, status, "Looking up %s", fpr);
   651     if (current) {
   652         tpk = pgp_tpk_merge(&err, tpk, current);
   653         if (! tpk)
   654             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Merging TPKs");
   655     }
   656 
   657     int is_tsk = pgp_tpk_is_tsk(tpk);
   658 
   659     // Serialize it.
   660     pgp_writer_t writer = pgp_writer_alloc(&tsk_buffer, &tsk_buffer_len);
   661     if (! writer)
   662         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
   663 
   664     pgp_status_t pgp_status;
   665     pgp_tsk_t tsk = pgp_tpk_as_tsk(tpk);
   666     pgp_status = pgp_tsk_serialize(&err, tsk, writer);
   667     pgp_tsk_free(tsk);
   668     //pgp_writer_free(writer);
   669     if (pgp_status != 0)
   670         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Serializing TPK");
   671 
   672 
   673     // Insert the TSK into the DB.
   674     stmt = session->sq_sql.tpk_save_insert_primary;
   675     sqlite3_bind_text(stmt, 1, fpr, -1, SQLITE_STATIC);
   676     sqlite3_bind_int(stmt, 2, is_tsk);
   677     sqlite3_bind_blob(stmt, 3, tsk_buffer, tsk_buffer_len, SQLITE_STATIC);
   678 
   679     sqlite_result = sqlite3_step(stmt);
   680     sqlite3_reset(stmt);
   681     if (sqlite_result != SQLITE_DONE)
   682         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   683                   "Saving TPK: %s", sqlite3_errmsg(session->key_db));
   684 
   685     // Insert the "subkeys" (the primary key and the subkeys).
   686     stmt = session->sq_sql.tpk_save_insert_subkeys;
   687     // This inserts all of the keys in the TPK, i.e., revoked and
   688     // expired keys, which is what we want.
   689     key_iter = pgp_tpk_key_iter_all(tpk);
   690     pgp_key_t key;
   691     while ((key = pgp_tpk_key_iter_next(key_iter, NULL, NULL))) {
   692         pgp_keyid_t keyid = pgp_key_keyid(key);
   693         char *keyid_hex = pgp_keyid_to_hex(keyid);
   694         sqlite3_bind_text(stmt, 1, keyid_hex, -1, SQLITE_STATIC);
   695         sqlite3_bind_text(stmt, 2, fpr, -1, SQLITE_STATIC);
   696 
   697         sqlite_result = sqlite3_step(stmt);
   698         sqlite3_reset(stmt);
   699         free(keyid_hex);
   700         pgp_keyid_free(keyid);
   701         if (sqlite_result != SQLITE_DONE) {
   702             pgp_tpk_key_iter_free(key_iter);
   703             ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   704                       "Updating subkeys: %s", sqlite3_errmsg(session->key_db));
   705         }
   706     }
   707     pgp_tpk_key_iter_free(key_iter);
   708     key_iter = NULL;
   709 
   710     // Insert the "userids".
   711     stmt = session->sq_sql.tpk_save_insert_userids;
   712     user_id_iter = pgp_tpk_user_id_binding_iter(tpk);
   713     pgp_user_id_binding_t binding;
   714     int first = 1;
   715     while ((binding = pgp_user_id_binding_iter_next(user_id_iter))) {
   716         char *user_id_value = pgp_user_id_binding_user_id(binding);
   717         if (!user_id_value || !*user_id_value)
   718             continue;
   719 
   720         // Ignore bindings with a self-revocation certificate, but no
   721         // self-signature.
   722         if (!pgp_user_id_binding_selfsig(binding)) {
   723             free(user_id_value);
   724             continue;
   725         }
   726 
   727         free(name);
   728         name = NULL;
   729         free(email);
   730         email = NULL;
   731 
   732         pgp_packet_t userid = pgp_user_id_new (user_id_value);
   733         pgp_user_id_name(NULL, userid, &name);
   734         pgp_user_id_address(NULL, userid, &email);
   735         pgp_packet_free(userid);
   736         free(user_id_value);
   737 
   738         if (email) {
   739             T("  userid: %s", email);
   740 
   741             sqlite3_bind_text(stmt, 1, email, -1, SQLITE_STATIC);
   742             sqlite3_bind_text(stmt, 2, fpr, -1, SQLITE_STATIC);
   743 
   744             sqlite_result = sqlite3_step(stmt);
   745             sqlite3_reset(stmt);
   746 
   747             if (sqlite_result != SQLITE_DONE) {
   748                 pgp_user_id_binding_iter_free(user_id_iter);
   749                 ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   750                           "Updating userids: %s", sqlite3_errmsg(session->key_db));
   751             }
   752         }
   753 
   754         if (first && private_idents && is_tsk) {
   755             first = 0;
   756 
   757             // Create an identity for the primary user id.
   758             pEp_identity *ident = new_identity(email, fpr, NULL, name);
   759             if (ident == NULL)
   760                 ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "new_identity");
   761 
   762             *private_idents = identity_list_add(*private_idents, ident);
   763             if (*private_idents == NULL)
   764                 ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "identity_list_add");
   765         }
   766 
   767     }
   768     pgp_user_id_binding_iter_free(user_id_iter);
   769     user_id_iter = NULL;
   770 
   771  out:
   772     // Prevent ERROR_OUT from causing an infinite loop.
   773     if (! tried_commit) {
   774         tried_commit = 1;
   775         stmt = status == PEP_STATUS_OK
   776             ? session->sq_sql.commit_transaction
   777             : session->sq_sql.rollback_transaction;
   778         int sqlite_result = sqlite3_step(stmt);
   779         sqlite3_reset(stmt);
   780         if (sqlite_result != SQLITE_DONE)
   781             ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   782                       status == PEP_STATUS_OK
   783                       ? "commit failed: %s" : "rollback failed: %s",
   784                       sqlite3_errmsg(session->key_db));
   785     }
   786 
   787     T("(%s) -> %s", fpr, pEp_status_to_string(status));
   788 
   789     free(email);
   790     free(name);
   791     if (user_id_iter)
   792         pgp_user_id_binding_iter_free(user_id_iter);
   793     if (key_iter)
   794         pgp_tpk_key_iter_free(key_iter);
   795     if (stmt)
   796       sqlite3_reset(stmt);
   797     free(tsk_buffer);
   798     if (tpk)
   799         pgp_tpk_free(tpk);
   800     free(fpr);
   801     pgp_fingerprint_free(pgp_fpr);
   802 
   803     return status;
   804 }
   805 
   806 struct decrypt_cookie {
   807     PEP_SESSION session;
   808     int get_secret_keys_called;
   809     stringlist_t *recipient_keylist;
   810     stringlist_t *signer_keylist;
   811     int good_checksums;
   812     int missing_keys;
   813     int bad_checksums;
   814     int decrypted;
   815 };
   816 
   817 static pgp_status_t
   818 get_public_keys_cb(void *cookie_raw,
   819                    pgp_keyid_t *keyids, size_t keyids_len,
   820                    pgp_tpk_t **tpks, size_t *tpk_len,
   821                    void (**our_free)(void *))
   822 {
   823     struct decrypt_cookie *cookie = cookie_raw;
   824     PEP_SESSION session = cookie->session;
   825 
   826     *tpks = calloc(keyids_len, sizeof(*tpks));
   827     if (!*tpks)
   828         return PGP_STATUS_UNKNOWN_ERROR;
   829     *our_free = free;
   830 
   831     int i, j;
   832     j = 0;
   833     for (i = 0; i < keyids_len; i ++) {
   834         pgp_tpk_t tpk = NULL;
   835         PEP_STATUS status
   836             = tpk_find_by_keyid(session, keyids[i], false, &tpk, NULL);
   837         if (status == PEP_STATUS_OK)
   838             (*tpks)[j ++] = tpk;
   839     }
   840     *tpk_len = j;
   841     return PGP_STATUS_SUCCESS;
   842 }
   843 
   844 static pgp_status_t
   845 decrypt_cb(void *cookie_opaque,
   846            pgp_pkesk_t *pkesks, size_t pkesk_count,
   847            pgp_skesk_t *skesks, size_t skesk_count,
   848            pgp_decryptor_do_decrypt_cb_t *decrypt,
   849            void *decrypt_cookie,
   850            pgp_fingerprint_t *identity_out)
   851 {
   852     pgp_error_t err = NULL;
   853     struct decrypt_cookie *cookie = cookie_opaque;
   854     PEP_SESSION session = cookie->session;
   855     pgp_tpk_t *tsks = NULL;
   856     int tsks_count = 0;
   857     int wildcards = 0;
   858 
   859     if (cookie->get_secret_keys_called)
   860         // Prevent iterations, which isn't needed since we don't
   861         // support SKESKs.
   862         return PGP_STATUS_UNKNOWN_ERROR;
   863     cookie->get_secret_keys_called = 1;
   864 
   865     T("%zd PKESKs", pkesk_count);
   866 
   867     for (int i = 0; i < pkesk_count; i ++) {
   868         pgp_pkesk_t pkesk = pkesks[i];
   869         pgp_keyid_t keyid = pgp_pkesk_recipient(pkesk); /* Reference. */
   870         char *keyid_str = pgp_keyid_to_hex(keyid);
   871         pgp_tpk_key_iter_t key_iter = NULL;
   872         pgp_session_key_t sk = NULL;
   873 
   874         T("Considering PKESK for %s", keyid_str);
   875 
   876         if (strcmp(keyid_str, "0000000000000000") == 0) {
   877             // Initially ignore wildcards.
   878             wildcards = 1;
   879             goto eol;
   880         }
   881 
   882         // Collect the recipients.  Note: we must return the primary
   883         // key's fingerprint.
   884         pgp_tpk_t tpk = NULL;
   885         int is_tsk = 0;
   886         if (tpk_find_by_keyid(session, keyid, false, &tpk, &is_tsk) != PEP_STATUS_OK)
   887             goto eol;
   888 
   889         pgp_fingerprint_t fp = pgp_tpk_fingerprint(tpk);
   890         char *fp_string = pgp_fingerprint_to_hex(fp);
   891         stringlist_add_unique(cookie->recipient_keylist, fp_string);
   892         free(fp_string);
   893         pgp_fingerprint_free(fp);
   894 
   895         if (cookie->decrypted)
   896             goto eol;
   897 
   898         // See if we have the secret key.
   899         assert(is_tsk == pgp_tpk_is_tsk(tpk));
   900         if (! is_tsk)
   901             goto eol;
   902 
   903         key_iter = pgp_tpk_key_iter_all(tpk);
   904         pgp_key_t key;
   905         while ((key = pgp_tpk_key_iter_next(key_iter, NULL, NULL))) {
   906             pgp_keyid_t this_keyid = pgp_key_keyid(key);
   907             char *this_keyid_hex = pgp_keyid_to_hex(this_keyid);
   908             pgp_keyid_free(this_keyid);
   909 
   910             int match = strcmp(keyid_str, this_keyid_hex) == 0;
   911             free(this_keyid_hex);
   912             if (match)
   913                 break;
   914         }
   915 
   916         if (key == NULL) {
   917             assert(!"Inconsistent DB: key doesn't contain a subkey with keyid!");
   918             goto eol;
   919         }
   920 
   921         uint8_t algo;
   922         uint8_t session_key[1024];
   923         size_t session_key_len = sizeof(session_key);
   924         if (pgp_pkesk_decrypt(&err, pkesk, key, &algo,
   925                               session_key, &session_key_len) != 0) {
   926             DUMP_ERR(err, PEP_UNKNOWN_ERROR, "pgp_pkesk_decrypt");
   927             goto eol;
   928         }
   929 
   930         sk = pgp_session_key_from_bytes (session_key, session_key_len);
   931         pgp_status_t status;
   932         if ((status = decrypt (decrypt_cookie, algo, sk))) {
   933             DUMP_STATUS(status, PEP_UNKNOWN_ERROR, "decrypt_cb");
   934             goto eol;
   935         }
   936 
   937         T("Decrypted PKESK for %s", keyid_str);
   938 
   939         *identity_out = pgp_tpk_fingerprint(tpk);
   940         cookie->decrypted = 1;
   941 
   942     eol:
   943         if (sk)
   944             pgp_session_key_free (sk);
   945         free(keyid_str);
   946         if (key_iter)
   947             pgp_tpk_key_iter_free(key_iter);
   948         if (tpk)
   949             pgp_tpk_free(tpk);
   950     }
   951 
   952     // Consider wildcard recipients.
   953     if (wildcards) for (int i = 0; i < pkesk_count && !cookie->decrypted; i ++) {
   954         pgp_pkesk_t pkesk = pkesks[i];
   955         pgp_keyid_t keyid = pgp_pkesk_recipient(pkesk); /* Reference. */
   956         char *keyid_str = pgp_keyid_to_hex(keyid);
   957         pgp_tpk_key_iter_t key_iter = NULL;
   958         pgp_session_key_t sk = NULL;
   959 
   960         if (strcmp(keyid_str, "0000000000000000") != 0)
   961             goto eol2;
   962 
   963         if (!tsks) {
   964             if (tpk_all(session, true, &tsks, &tsks_count) != PEP_STATUS_OK) {
   965                 DUMP_ERR(NULL, PEP_UNKNOWN_ERROR, "Getting all tsks");
   966             }
   967         }
   968 
   969         for (int j = 0; j < tsks_count; j ++) {
   970             pgp_tpk_t tsk = tsks[j];
   971 
   972             key_iter = pgp_tpk_key_iter_all(tsk);
   973             pgp_key_t key;
   974             pgp_signature_t selfsig;
   975             while ((key = pgp_tpk_key_iter_next(key_iter, &selfsig, NULL))) {
   976                 if (! (pgp_signature_can_encrypt_at_rest(selfsig)
   977                        || pgp_signature_can_encrypt_for_transport(selfsig)))
   978                     continue;
   979 
   980                 fprintf(stderr, "key: %s\n", pgp_key_debug(key));
   981 
   982                 // Note: for decryption to appear to succeed, we must
   983                 // get a valid algorithm (8 of 256 values) and a
   984                 // 16-bit checksum must match.  Thus, we have about a
   985                 // 1 in 2**21 chance of having a false positive here.
   986                 uint8_t algo;
   987                 uint8_t session_key[1024];
   988                 size_t session_key_len = sizeof(session_key);
   989                 if (pgp_pkesk_decrypt(&err, pkesk, key,
   990                                       &algo, session_key, &session_key_len)) {
   991                     pgp_error_free(err);
   992                     err = NULL;
   993                     continue;
   994                 }
   995 
   996                 // Add it to the recipient list.
   997                 pgp_fingerprint_t fp = pgp_tpk_fingerprint(tsk);
   998                 char *fp_string = pgp_fingerprint_to_hex(fp);
   999                 T("wildcard recipient appears to be %s", fp_string);
  1000                 stringlist_add_unique(cookie->recipient_keylist, fp_string);
  1001                 free(fp_string);
  1002                 pgp_fingerprint_free(fp);
  1003 
  1004                 pgp_session_key_t sk = pgp_session_key_from_bytes (session_key,
  1005                                                                    session_key_len);
  1006                 pgp_status_t status;
  1007                 if ((status = decrypt (decrypt_cookie, algo, sk))) {
  1008                     DUMP_STATUS(status, PEP_UNKNOWN_ERROR, "decrypt_cb");
  1009                     goto eol2;
  1010                 }
  1011 
  1012                 *identity_out = pgp_tpk_fingerprint(tsk);
  1013                 cookie->decrypted = 1;
  1014 
  1015                 break;
  1016             }
  1017 
  1018             pgp_tpk_key_iter_free(key_iter);
  1019             key_iter = NULL;
  1020         }
  1021     eol2:
  1022         if (sk)
  1023             pgp_session_key_free (sk);
  1024         free(keyid_str);
  1025         if (key_iter)
  1026             pgp_tpk_key_iter_free(key_iter);
  1027     }
  1028 
  1029     if (tsks) {
  1030         for (int i = 0; i < tsks_count; i ++)
  1031             pgp_tpk_free(tsks[i]);
  1032         free(tsks);
  1033     }
  1034 
  1035     return cookie->decrypted ? PGP_STATUS_SUCCESS : PGP_STATUS_UNKNOWN_ERROR;
  1036 }
  1037 
  1038 static pgp_status_t
  1039 check_signatures_cb(void *cookie_opaque, pgp_message_structure_t structure)
  1040 {
  1041     struct decrypt_cookie *cookie = cookie_opaque;
  1042     PEP_SESSION session = cookie->session;
  1043 
  1044     pgp_message_structure_iter_t iter
  1045         = pgp_message_structure_iter (structure);
  1046     for (pgp_message_layer_t layer = pgp_message_structure_iter_next (iter);
  1047          layer;
  1048          layer = pgp_message_structure_iter_next (iter)) {
  1049         pgp_verification_result_iter_t results;
  1050 
  1051         switch (pgp_message_layer_variant (layer)) {
  1052         case PGP_MESSAGE_LAYER_COMPRESSION:
  1053         case PGP_MESSAGE_LAYER_ENCRYPTION:
  1054             break;
  1055 
  1056         case PGP_MESSAGE_LAYER_SIGNATURE_GROUP:
  1057             pgp_message_layer_signature_group(layer, &results);
  1058             pgp_verification_result_t result;
  1059             while ((result = pgp_verification_result_iter_next (results))) {
  1060                 pgp_signature_t sig;
  1061                 pgp_keyid_t keyid = NULL;
  1062                 char *keyid_str = NULL;
  1063 
  1064                 switch (pgp_verification_result_variant (result)) {
  1065                 case PGP_VERIFICATION_RESULT_GOOD_CHECKSUM:
  1066                     // We need to add the fingerprint of the primary
  1067                     // key to cookie->signer_keylist.
  1068 
  1069                     pgp_verification_result_good_checksum (result, &sig, NULL,
  1070                                                            NULL, NULL, NULL);
  1071 
  1072                     // First try looking up by the TPK using the
  1073                     // IssuerFingerprint subpacket.
  1074                     pgp_fingerprint_t fpr
  1075                         = pgp_signature_issuer_fingerprint(sig);
  1076                     if (fpr) {
  1077                         // Even though we have a fingerprint, we have
  1078                         // to look the key up by keyid, because we
  1079                         // want to match on subkeys and we only store
  1080                         // keyids for subkeys.
  1081                         keyid = pgp_fingerprint_to_keyid(fpr);
  1082                         pgp_fingerprint_free(fpr);
  1083                     } else {
  1084                         // That is not available, try using the Issuer
  1085                         // subpacket.
  1086                         keyid = pgp_signature_issuer(sig);
  1087                     }
  1088 
  1089                     if (! keyid) {
  1090                         T("signature with no Issuer or Issuer Fingerprint subpacket!");
  1091                         goto eol;
  1092                     }
  1093 
  1094                     pgp_tpk_t tpk;
  1095                     if (tpk_find_by_keyid(session, keyid, false,
  1096                                           &tpk, NULL) != PEP_STATUS_OK)
  1097                         ; // Soft error.  Ignore.
  1098 
  1099                     if (tpk) {
  1100                         // Ok, we have a TPK.
  1101 
  1102                         // We need the primary key's fingerprint (not
  1103                         // the issuer fingerprint).
  1104                         pgp_fingerprint_t primary_fpr
  1105                             = pgp_tpk_fingerprint(tpk);
  1106                         char *primary_fpr_str
  1107                             = pgp_fingerprint_to_hex(primary_fpr);
  1108                         stringlist_add_unique(cookie->signer_keylist,
  1109                                               primary_fpr_str);
  1110 
  1111                         T("Good signature from %s", primary_fpr_str);
  1112 
  1113                         // XXX: Check that the TPK and the key used to make
  1114                         // the signature and the signature itself are alive
  1115                         // and not revoked.  Revoked =>
  1116                         // PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH; Expired key
  1117                         // or sig => PEP_DECRYPTED.
  1118                         cookie->good_checksums ++;
  1119 
  1120                         free(primary_fpr_str);
  1121                         pgp_fingerprint_free(primary_fpr);
  1122                         pgp_tpk_free(tpk);
  1123                     } else {
  1124                         // If we get
  1125                         // PGP_VERIFICATION_RESULT_CODE_GOOD_CHECKSUM, then the
  1126                         // TPK should be available.  But, another process
  1127                         // could have deleted the key from the store in the
  1128                         // mean time, so be tolerant.
  1129                         T("Key to check signature from %s disappeared",
  1130                           keyid_str);
  1131                         cookie->missing_keys ++;
  1132                     }
  1133                     break;
  1134 
  1135                 case PGP_VERIFICATION_RESULT_MISSING_KEY:
  1136                     pgp_verification_result_missing_key (result, &sig);
  1137                     keyid = pgp_signature_issuer (sig);
  1138                     keyid_str = pgp_keyid_to_string (keyid);
  1139                     T("No key to check signature from %s", keyid_str);
  1140 
  1141                     cookie->missing_keys ++;
  1142                     break;
  1143 
  1144                 case PGP_VERIFICATION_RESULT_BAD_CHECKSUM:
  1145                     pgp_verification_result_bad_checksum (result, &sig);
  1146                     keyid = pgp_signature_issuer (sig);
  1147                     if (keyid) {
  1148                         keyid_str = pgp_keyid_to_string (keyid);
  1149                         T("Bad signature from %s", keyid_str);
  1150                     } else {
  1151                         T("Bad signature without issuer information");
  1152                     }
  1153 
  1154                     cookie->bad_checksums ++;
  1155                     break;
  1156 
  1157                 default:
  1158                     assert (! "reachable");
  1159                 }
  1160 
  1161             eol:
  1162                 free (keyid_str);
  1163                 pgp_signature_free (sig);
  1164                 pgp_verification_result_free (result);
  1165             }
  1166             pgp_verification_result_iter_free (results);
  1167             break;
  1168 
  1169         default:
  1170             assert (! "reachable");
  1171         }
  1172 
  1173         pgp_message_layer_free (layer);
  1174     }
  1175 
  1176     pgp_message_structure_iter_free (iter);
  1177     pgp_message_structure_free (structure);
  1178 
  1179     return PGP_STATUS_SUCCESS;
  1180 }
  1181 
  1182 PEP_STATUS pgp_decrypt_and_verify(
  1183     PEP_SESSION session, const char *ctext, size_t csize,
  1184     const char *dsigtext, size_t dsigsize,
  1185     char **ptext, size_t *psize, stringlist_t **keylist,
  1186     char** filename_ptr)
  1187 {
  1188     PEP_STATUS status = PEP_STATUS_OK;
  1189     struct decrypt_cookie cookie = { session, 0, NULL, NULL, 0, 0, 0, };
  1190     pgp_reader_t reader = NULL;
  1191     pgp_writer_t writer = NULL;
  1192     pgp_reader_t decryptor = NULL;
  1193     *ptext = NULL;
  1194     *psize = 0;
  1195 
  1196     // XXX: We don't yet handle detached signatures over encrypted
  1197     // messages.
  1198     assert(!dsigtext);
  1199 
  1200     cookie.recipient_keylist = new_stringlist(NULL);
  1201     if (!cookie.recipient_keylist)
  1202         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "recipient_keylist");
  1203 
  1204     cookie.signer_keylist = new_stringlist(NULL);
  1205     if (!cookie.signer_keylist)
  1206         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "signer_keylist");
  1207 
  1208     reader = pgp_reader_from_bytes((const uint8_t *) ctext, csize);
  1209     if (! reader)
  1210         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "Creating reader");
  1211 
  1212     writer = pgp_writer_alloc((void **) ptext, psize);
  1213     if (! writer)
  1214         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR, "Creating writer");
  1215 
  1216     pgp_error_t err = NULL;
  1217     decryptor = pgp_decryptor_new(&err, reader,
  1218                                   get_public_keys_cb, decrypt_cb,
  1219                                   check_signatures_cb, &cookie, 0);
  1220     if (! decryptor)
  1221         ERROR_OUT(err, PEP_DECRYPT_NO_KEY, "pgp_decryptor_new");
  1222 
  1223     // Copy 128 MB at a time.
  1224     ssize_t nread;
  1225     while ((nread = pgp_reader_copy (&err, decryptor, writer,
  1226                                      128 * 1024 * 1024) > 0))
  1227         ;
  1228     if (nread < 0)
  1229         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "pgp_reader_read");
  1230 
  1231     // Add a terminating NUL for naive users
  1232     pgp_writer_write(&err, writer, (const uint8_t *) &""[0], 1);
  1233 
  1234     if (! cookie.decrypted)
  1235         ERROR_OUT(err, PEP_DECRYPT_NO_KEY, "Decryption failed");
  1236 
  1237     if (! cookie.signer_keylist) {
  1238         cookie.signer_keylist = new_stringlist("");
  1239         if (! cookie.signer_keylist)
  1240             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "cookie.signer_keylist");
  1241     }
  1242     if (!cookie.signer_keylist->value)
  1243         stringlist_add(cookie.signer_keylist, "");
  1244 
  1245     *keylist = cookie.signer_keylist;
  1246     stringlist_append(*keylist, cookie.recipient_keylist);
  1247 
  1248  out:
  1249     if (status == PEP_STATUS_OK) {
  1250         if (cookie.bad_checksums) {
  1251             // If there are any bad signatures, fail.
  1252             status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  1253         } else if (cookie.good_checksums) {
  1254             // If there is at least one signature that we can verify,
  1255             // succeed.
  1256             status = PEP_DECRYPTED_AND_VERIFIED;
  1257         } else {
  1258             // We couldn't verify any signatures (possibly because we
  1259             // don't have the keys).
  1260             status = PEP_DECRYPTED;
  1261         }
  1262     } else {
  1263         free_stringlist(cookie.recipient_keylist);
  1264         free_stringlist(cookie.signer_keylist);
  1265         free(*ptext);
  1266     }
  1267 
  1268     if (reader)
  1269         pgp_reader_free(reader);
  1270     if (decryptor)
  1271         pgp_reader_free(decryptor);
  1272     if (writer)
  1273         pgp_writer_free(writer);
  1274 
  1275     T("-> %s", pEp_status_to_string(status));
  1276     return status;
  1277 }
  1278 
  1279 PEP_STATUS pgp_verify_text(
  1280     PEP_SESSION session, const char *text, size_t size,
  1281     const char *signature, size_t sig_size, stringlist_t **keylist)
  1282 {
  1283     PEP_STATUS status = PEP_STATUS_OK;
  1284     pgp_error_t err = NULL;
  1285     struct decrypt_cookie cookie = { session, 0, NULL, NULL, 0, 0, 0, };
  1286     pgp_reader_t reader = NULL;
  1287     pgp_reader_t dsig_reader = NULL;
  1288     pgp_reader_t verifier = NULL;
  1289 
  1290     if (size == 0 || sig_size == 0)
  1291         return PEP_DECRYPT_WRONG_FORMAT;
  1292 
  1293     cookie.recipient_keylist = new_stringlist(NULL);
  1294     if (!cookie.recipient_keylist)
  1295         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1296 
  1297     cookie.signer_keylist = new_stringlist(NULL);
  1298     if (!cookie.signer_keylist)
  1299         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1300 
  1301     reader = pgp_reader_from_bytes((const uint8_t *) text, size);
  1302     if (! reader)
  1303         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "Creating reader");
  1304 
  1305     dsig_reader = NULL;
  1306     if (signature) {
  1307         dsig_reader = pgp_reader_from_bytes((uint8_t *) signature, sig_size);
  1308         if (! dsig_reader)
  1309             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "Creating signature reader");
  1310     }
  1311 
  1312     if (dsig_reader)
  1313         verifier = pgp_detached_verifier_new(&err, dsig_reader, reader,
  1314                                              get_public_keys_cb,
  1315                                              check_signatures_cb,
  1316                                              &cookie, 0);
  1317     else
  1318         verifier = pgp_verifier_new(&err, reader,
  1319                                     get_public_keys_cb,
  1320                                     check_signatures_cb,
  1321                                     &cookie, 0);
  1322     if (! verifier)
  1323         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Creating verifier");
  1324     if (pgp_reader_discard(&err, verifier) < 0)
  1325         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "verifier");
  1326 
  1327     if (! cookie.signer_keylist) {
  1328         cookie.signer_keylist = new_stringlist("");
  1329         if (! cookie.signer_keylist)
  1330             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "cookie.signer_keylist");
  1331     }
  1332     if (!cookie.signer_keylist->value)
  1333         stringlist_add(cookie.signer_keylist, "");
  1334 
  1335     *keylist = cookie.signer_keylist;
  1336     stringlist_append(*keylist, cookie.recipient_keylist);
  1337 
  1338  out:
  1339     if (status == PEP_STATUS_OK) {
  1340         if (cookie.bad_checksums) {
  1341             // If there are any bad signatures, fail.
  1342             status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  1343         } else if (cookie.good_checksums) {
  1344             // If there is at least one signature that we can verify,
  1345             // succeed.
  1346             status = PEP_VERIFIED;
  1347         } else {
  1348             // We couldn't verify any signatures (possibly because we
  1349             // don't have the keys).
  1350             status = PEP_UNENCRYPTED;
  1351         }
  1352     } else {
  1353         free_stringlist(cookie.recipient_keylist);
  1354         free_stringlist(cookie.signer_keylist);
  1355     }
  1356 
  1357     if (verifier)
  1358         pgp_reader_free(verifier);
  1359     if (reader)
  1360         pgp_reader_free(reader);
  1361     if (dsig_reader)
  1362         pgp_reader_free(dsig_reader);
  1363 
  1364     T("-> %s", pEp_status_to_string(status));
  1365     return status;
  1366 }
  1367 
  1368 
  1369 PEP_STATUS pgp_sign_only(
  1370     PEP_SESSION session, const char* fpr, const char *ptext,
  1371     size_t psize, char **stext, size_t *ssize)
  1372 {
  1373     assert(session);
  1374     assert(fpr && fpr[0]);
  1375     assert(ptext);
  1376     assert(psize);
  1377     assert(stext);
  1378     assert(ssize);
  1379     *stext = NULL;
  1380     *ssize = 0;
  1381 
  1382     PEP_STATUS status = PEP_STATUS_OK;
  1383     pgp_error_t err = NULL;
  1384     pgp_tpk_t signer_tpk = NULL;
  1385     pgp_tpk_key_iter_t iter = NULL;
  1386     pgp_key_pair_t signing_keypair = NULL;
  1387     pgp_signer_t signer = NULL;
  1388     pgp_writer_stack_t ws = NULL;
  1389 
  1390     status = tpk_find_by_fpr_hex(session, fpr, true, &signer_tpk, NULL);
  1391     ERROR_OUT(NULL, status, "Looking up key '%s'", fpr);
  1392 
  1393     iter = pgp_tpk_key_iter_valid(signer_tpk);
  1394     pgp_tpk_key_iter_signing_capable (iter);
  1395     pgp_tpk_key_iter_unencrypted_secret (iter, true);
  1396 
  1397     // If there are multiple signing capable subkeys, we just take
  1398     // the first one, whichever one that happens to be.
  1399     pgp_key_t key = pgp_tpk_key_iter_next (iter, NULL, NULL);
  1400     if (! key)
  1401         ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  1402                    "%s has no signing capable key", fpr);
  1403 
  1404     signing_keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  1405     if (! signing_keypair)
  1406         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  1407 
  1408     signer = pgp_key_pair_as_signer (signing_keypair);
  1409     if (! signer)
  1410         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  1411 
  1412 
  1413     pgp_writer_t writer = pgp_writer_alloc((void **) stext, ssize);
  1414     writer = pgp_armor_writer_new(&err, writer,
  1415                                   PGP_ARMOR_KIND_MESSAGE, NULL, 0);
  1416     if (!writer)
  1417         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up armor writer");
  1418 
  1419     ws = pgp_writer_stack_message(writer);
  1420 
  1421     ws = pgp_signer_new_detached(&err, ws, &signer, 1, 0);
  1422     if (!ws)
  1423         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up signer");
  1424 
  1425     pgp_status_t write_status =
  1426         pgp_writer_stack_write_all (&err, ws,
  1427                                     (uint8_t *) ptext, psize);
  1428     if (write_status != 0)
  1429         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Encrypting message");
  1430 
  1431     // Add a terminating NUL for naive users
  1432     void *t = realloc(*stext, *ssize + 1);
  1433     if (! t)
  1434         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1435     *stext = t;
  1436     (*stext)[*ssize] = 0;
  1437 
  1438  out:
  1439     if (ws) {
  1440         pgp_status_t pgp_status = pgp_writer_stack_finalize (&err, ws);
  1441         ws = NULL;
  1442         if (pgp_status != 0)
  1443             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Flushing writer");
  1444     }
  1445 
  1446     if (signer)
  1447         pgp_signer_free (signer);
  1448     if (signing_keypair)
  1449         pgp_key_pair_free (signing_keypair);
  1450     if (iter)
  1451         pgp_tpk_key_iter_free (iter);
  1452     if (signer_tpk)
  1453         pgp_tpk_free(signer_tpk);
  1454 
  1455     T("(%s)-> %s", fpr, pEp_status_to_string(status));
  1456     return status;
  1457 }
  1458 
  1459 static PEP_STATUS pgp_encrypt_sign_optional(
  1460     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1461     size_t psize, char **ctext, size_t *csize, bool sign)
  1462 {
  1463     PEP_STATUS status = PEP_STATUS_OK;
  1464     pgp_error_t err = NULL;
  1465     int keys_count = 0;
  1466     pgp_tpk_t *keys = NULL;
  1467     pgp_tpk_t signer_tpk = NULL;
  1468     pgp_writer_stack_t ws = NULL;
  1469     pgp_tpk_key_iter_t iter = NULL;
  1470     pgp_key_pair_t signing_keypair = NULL;
  1471     pgp_signer_t signer = NULL;
  1472 
  1473     assert(session);
  1474     assert(keylist);
  1475     assert(ptext);
  1476     assert(psize);
  1477     assert(ctext);
  1478     assert(csize);
  1479 
  1480     *ctext = NULL;
  1481     *csize = 0;
  1482 
  1483     keys = calloc(stringlist_length(keylist), sizeof(*keys));
  1484     if (keys == NULL)
  1485         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1486 
  1487     // Get the keys for the recipients.
  1488     const stringlist_t *_keylist;
  1489     for (_keylist = keylist; _keylist != NULL; _keylist = _keylist->next) {
  1490         assert(_keylist->value);
  1491         pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(_keylist->value);
  1492         status = tpk_find_by_fpr(session, pgp_fpr, false, &keys[keys_count ++], NULL);
  1493         pgp_fingerprint_free(pgp_fpr);
  1494         ERROR_OUT(NULL, status, "Looking up key for recipient '%s'", _keylist->value);
  1495     }
  1496 
  1497     if (sign) {
  1498         // The first key in the keylist is the signer.
  1499         status = tpk_find_by_fpr_hex(session, keylist->value, true, &signer_tpk, NULL);
  1500         ERROR_OUT(NULL, status, "Looking up key for signing '%s'", keylist->value);
  1501     }
  1502 
  1503     pgp_writer_t writer = pgp_writer_alloc((void **) ctext, csize);
  1504     writer = pgp_armor_writer_new(&err, writer,
  1505                                   PGP_ARMOR_KIND_MESSAGE, NULL, 0);
  1506     if (!writer)
  1507         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up armor writer");
  1508 
  1509     ws = pgp_writer_stack_message(writer);
  1510     ws = pgp_encryptor_new (&err, ws,
  1511                             NULL, 0, keys, keys_count,
  1512                             PGP_ENCRYPTION_MODE_FOR_TRANSPORT, 0);
  1513     if (!ws)
  1514         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up encryptor");
  1515 
  1516     if (sign) {
  1517         iter = pgp_tpk_key_iter_valid(signer_tpk);
  1518         pgp_tpk_key_iter_signing_capable (iter);
  1519         pgp_tpk_key_iter_unencrypted_secret (iter, true);
  1520 
  1521         // If there are multiple signing capable subkeys, we just take
  1522         // the first one, whichever one that happens to be.
  1523         pgp_key_t key = pgp_tpk_key_iter_next (iter, NULL, NULL);
  1524         if (! key)
  1525             ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  1526                        "%s has no signing capable key", keylist->value);
  1527 
  1528         signing_keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  1529         if (! signing_keypair)
  1530             ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  1531 
  1532         signer = pgp_key_pair_as_signer (signing_keypair);
  1533         if (! signer)
  1534             ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  1535 
  1536         ws = pgp_signer_new(&err, ws, &signer, 1, 0);
  1537         if (!ws)
  1538             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up signer");
  1539     }
  1540 
  1541     ws = pgp_literal_writer_new (&err, ws);
  1542     if (!ws)
  1543         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up literal writer");
  1544 
  1545     pgp_status_t write_status =
  1546         pgp_writer_stack_write_all (&err, ws,
  1547                                     (uint8_t *) ptext, psize);
  1548     if (write_status != 0)
  1549         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Encrypting message");
  1550 
  1551     // Add a terminating NUL for naive users
  1552     void *t = realloc(*ctext, *csize + 1);
  1553     if (! t)
  1554         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1555     *ctext = t;
  1556     (*ctext)[*csize] = 0;
  1557 
  1558  out:
  1559     if (ws) {
  1560         pgp_status_t pgp_status = pgp_writer_stack_finalize (&err, ws);
  1561         ws = NULL;
  1562         if (pgp_status != 0)
  1563             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Flushing writer");
  1564     }
  1565 
  1566     if (signer)
  1567         pgp_signer_free (signer);
  1568     if (signing_keypair)
  1569         pgp_key_pair_free (signing_keypair);
  1570     if (iter)
  1571         pgp_tpk_key_iter_free (iter);
  1572     if (signer_tpk)
  1573         pgp_tpk_free(signer_tpk);
  1574 
  1575     for (int i = 0; i < keys_count; i ++)
  1576         pgp_tpk_free(keys[i]);
  1577     free(keys);
  1578 
  1579     T("-> %s", pEp_status_to_string(status));
  1580     return status;
  1581 }
  1582 
  1583 PEP_STATUS pgp_encrypt_only(
  1584     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1585     size_t psize, char **ctext, size_t *csize)
  1586 {
  1587     return pgp_encrypt_sign_optional(session, keylist, ptext,
  1588         psize, ctext, csize, false);
  1589 }
  1590 
  1591 PEP_STATUS pgp_encrypt_and_sign(
  1592     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1593     size_t psize, char **ctext, size_t *csize)
  1594 {
  1595     return pgp_encrypt_sign_optional(session, keylist, ptext,
  1596         psize, ctext, csize, true);
  1597 }
  1598 
  1599 
  1600 PEP_STATUS pgp_generate_keypair(PEP_SESSION session, pEp_identity *identity)
  1601 {
  1602     PEP_STATUS status = PEP_STATUS_OK;
  1603     pgp_error_t err = NULL;
  1604     char *userid = NULL;
  1605     pgp_tpk_t tpk = NULL;
  1606     pgp_fingerprint_t pgp_fpr = NULL;
  1607     char *fpr = NULL;
  1608 
  1609     assert(session);
  1610     assert(identity);
  1611     assert(identity->address);
  1612     assert(identity->fpr == NULL || identity->fpr[0] == 0);
  1613     assert(identity->username);
  1614 
  1615     size_t userid_size = strlen(identity->username)+strlen(identity->address)+3+1;
  1616     userid = (char *) calloc(1, userid_size);
  1617     assert(userid);
  1618     if (!userid)
  1619         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1620 
  1621     int r = snprintf(userid, userid_size, "%s <%s>", identity->username, identity->address);
  1622     assert(r >= 0 && r < userid_size);
  1623     if (r < 0)
  1624         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR, "snprintf");
  1625 
  1626     T("(%s)", userid);
  1627 
  1628     // Generate a key.
  1629     pgp_tpk_builder_t tpkb = pgp_tpk_builder_general_purpose
  1630         (PGP_TPK_CIPHER_SUITE_RSA3K, userid);
  1631     pgp_signature_t rev;
  1632     if (pgp_tpk_builder_generate(&err, tpkb, &tpk, &rev))
  1633         ERROR_OUT(err, PEP_CANNOT_CREATE_KEY, "Generating a key pair");
  1634 
  1635     // XXX: We should return this.
  1636     pgp_signature_free(rev);
  1637 
  1638     // Get the fingerprint.
  1639     pgp_fpr = pgp_tpk_fingerprint(tpk);
  1640     fpr = pgp_fingerprint_to_hex(pgp_fpr);
  1641 
  1642     status = tpk_save(session, tpk, NULL);
  1643     tpk = NULL;
  1644     if (status != 0)
  1645         ERROR_OUT(NULL, PEP_CANNOT_CREATE_KEY, "saving TSK");
  1646 
  1647     free(identity->fpr);
  1648     identity->fpr = fpr;
  1649     fpr = NULL;
  1650 
  1651  out:
  1652     if (pgp_fpr)
  1653         pgp_fingerprint_free(pgp_fpr);
  1654     free(fpr);
  1655     if (tpk)
  1656         pgp_tpk_free(tpk);
  1657     free(userid);
  1658 
  1659     T("-> %s", pEp_status_to_string(status));
  1660     return status;
  1661 }
  1662 
  1663 #define SQL_DELETE "DELETE FROM keys WHERE primary_key = '%s' ;"
  1664 static const char *sql_delete = SQL_DELETE;
  1665 static const size_t sql_delete_size = sizeof(SQL_DELETE);
  1666 
  1667 // FIXME: this is deleting the key from the index but not the key data
  1668 
  1669 PEP_STATUS pgp_delete_keypair(PEP_SESSION session, const char *fpr)
  1670 {
  1671     assert(session && fpr && fpr[0]);
  1672     if (!(session && fpr && fpr[0]))
  1673         return PEP_ILLEGAL_VALUE;
  1674 
  1675     size_t sql_size = sql_delete_size + strlen(fpr);
  1676     char *sql = calloc(1, sql_size);
  1677     assert(sql);
  1678     if (!sql)
  1679         return PEP_OUT_OF_MEMORY;
  1680 
  1681     int r = snprintf(sql, sql_size, sql_delete, fpr);
  1682     assert(r > 0 && r < sql_size);
  1683     if (r < 0)
  1684         return PEP_UNKNOWN_ERROR;
  1685 
  1686     int sqlite_result = sqlite3_exec(session->key_db, sql, NULL, NULL, NULL);
  1687     assert(sqlite_result == SQLITE_OK);
  1688     if (sqlite_result != SQLITE_OK)
  1689         return PEP_CANNOT_DELETE_KEY;
  1690 
  1691     sqlite_result = sqlite3_changes(session->key_db);
  1692     assert(sqlite_result >= 0 && sqlite_result < 2);
  1693     if (sqlite_result < 1)
  1694         return PEP_KEY_NOT_FOUND;
  1695 
  1696     return PEP_STATUS_OK;
  1697 }
  1698 
  1699 // XXX: This also needs to handle revocation certificates.
  1700 PEP_STATUS pgp_import_keydata(PEP_SESSION session, const char *key_data,
  1701                               size_t size, identity_list **private_idents)
  1702 {
  1703     PEP_STATUS status = PEP_NO_KEY_IMPORTED;
  1704     pgp_error_t err;
  1705     pgp_tpk_parser_t parser = NULL;
  1706 
  1707     if (private_idents)
  1708         *private_idents = NULL;
  1709 
  1710     T("parsing %zd bytes", size);
  1711 
  1712     pgp_packet_parser_result_t ppr
  1713         = pgp_packet_parser_from_bytes(&err, (uint8_t *) key_data, size);
  1714     if (! ppr)
  1715         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Creating packet parser");
  1716 
  1717     pgp_tag_t tag = pgp_packet_parser_result_tag(ppr);
  1718     switch (tag) {
  1719     case PGP_TAG_SIGNATURE: {
  1720         // The following asserts can't fail, because
  1721         // pgp_packet_parser_result_tag succeeded and the tag is
  1722         // right.
  1723         pgp_packet_parser_t pp = pgp_packet_parser_result_packet_parser (ppr);
  1724         assert(pp);
  1725 
  1726         pgp_packet_t packet = NULL;
  1727         if (pgp_packet_parser_next(&err, pp, &packet, &ppr))
  1728             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Getting signature packet");
  1729 
  1730         pgp_signature_t sig = pgp_packet_ref_signature (packet);
  1731         assert(sig);
  1732 
  1733         pgp_tpk_t tpk = NULL;
  1734 
  1735         pgp_fingerprint_t issuer_fpr = pgp_signature_issuer_fingerprint(sig);
  1736         if (issuer_fpr) {
  1737             char *issuer_fpr_hex = pgp_fingerprint_to_hex(issuer_fpr);
  1738             T("Importing a signature issued by %s", issuer_fpr_hex);
  1739 
  1740             status = tpk_find_by_fpr_hex(session, issuer_fpr_hex,
  1741                                          false, &tpk, NULL);
  1742             if (status && status != PEP_KEY_NOT_FOUND)
  1743                 DUMP_ERR(NULL, status, "Looking up %s", issuer_fpr_hex);
  1744 
  1745             free(issuer_fpr_hex);
  1746             pgp_fingerprint_free(issuer_fpr);
  1747         }
  1748 
  1749         if (! tpk) {
  1750             pgp_keyid_t issuer = pgp_signature_issuer(sig);
  1751             if (issuer) {
  1752                 char *issuer_hex = pgp_keyid_to_hex(issuer);
  1753                 T("Importing a signature issued by %s", issuer_hex);
  1754 
  1755                 status = tpk_find_by_keyid_hex(session, issuer_hex,
  1756                                                false, &tpk, NULL);
  1757                 if (status && status != PEP_KEY_NOT_FOUND)
  1758                     DUMP_ERR(NULL, status, "Looking up %s", issuer_hex);
  1759 
  1760                 free(issuer_hex);
  1761                 pgp_keyid_free(issuer);
  1762             }
  1763         }
  1764 
  1765         // We need a packet.  sig is only a reference, so we just need
  1766         // to free it.
  1767         pgp_signature_free(sig);
  1768 
  1769         if (tpk) {
  1770             T("Merging packet: %s", pgp_packet_debug(packet));
  1771 
  1772             tpk = pgp_tpk_merge_packets (&err, tpk, &packet, 1);
  1773             if (! tpk)
  1774                 ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Merging signature");
  1775 
  1776             status = tpk_save(session, tpk, NULL);
  1777             if (status)
  1778                 ERROR_OUT(NULL, status, "saving merged TPK");
  1779             status = PEP_KEY_IMPORTED;
  1780         }
  1781         break;
  1782     }
  1783     case PGP_TAG_PUBLIC_KEY:
  1784     case PGP_TAG_SECRET_KEY: {
  1785         parser = pgp_tpk_parser_from_packet_parser(ppr);
  1786         pgp_tpk_t tpk;
  1787         int count = 0;
  1788         err = NULL;
  1789         while ((tpk = pgp_tpk_parser_next(&err, parser))) {
  1790             count ++;
  1791 
  1792             T("#%d. TPK for %s, %s",
  1793               count, pgp_tpk_primary_user_id(tpk),
  1794               pgp_fingerprint_to_hex(pgp_tpk_fingerprint(tpk)));
  1795 
  1796             // If private_idents is not NULL and there is any private key
  1797             // material, it will be saved.
  1798             status = tpk_save(session, tpk, private_idents);
  1799             if (status == PEP_STATUS_OK)
  1800                 status = PEP_KEY_IMPORTED;
  1801             else
  1802                 ERROR_OUT(NULL, status, "saving TPK");
  1803         }
  1804         if (err || count == 0)
  1805             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "parsing key data");
  1806         break;
  1807     }
  1808     default:
  1809         ERROR_OUT(NULL, PEP_NO_KEY_IMPORTED,
  1810                   "Can't import %s", pgp_tag_to_string(tag));
  1811         break;
  1812     }
  1813 
  1814  out:
  1815     if (parser)
  1816         pgp_tpk_parser_free(parser);
  1817 
  1818     T("-> %s", pEp_status_to_string(status));
  1819     return status;
  1820 }
  1821 
  1822 PEP_STATUS pgp_export_keydata(
  1823         PEP_SESSION session, const char *fpr, char **key_data, size_t *size,
  1824         bool secret)
  1825 {
  1826     PEP_STATUS status = PEP_STATUS_OK;
  1827     pgp_error_t err = NULL;
  1828     pgp_tpk_t tpk = NULL;
  1829     pgp_writer_t armor_writer = NULL;
  1830 
  1831     assert(session);
  1832     assert(fpr);
  1833     assert(key_data);
  1834     assert(*key_data == NULL);
  1835     assert(size);
  1836 
  1837     *size = 0;
  1838 
  1839     T("(%s, %s)", fpr, secret ? "secret" : "public");
  1840 
  1841     // If the caller asks for a secret key and we only have a
  1842     // public key, then we return an error.
  1843     status = tpk_find_by_fpr_hex(session, fpr, secret, &tpk, NULL);
  1844     ERROR_OUT(NULL, status, "Looking up TSK for %s", fpr);
  1845 
  1846     pgp_writer_t memory_writer = pgp_writer_alloc((void **) key_data, size);
  1847     if (! memory_writer)
  1848         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR, "creating memory writer");
  1849     armor_writer = pgp_armor_writer_new(&err, memory_writer,
  1850                                         PGP_ARMOR_KIND_PUBLICKEY, NULL, 0);
  1851     if (! armor_writer) {
  1852         pgp_writer_free(memory_writer);
  1853         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "creating armored writer");
  1854     }
  1855 
  1856     if (secret) {
  1857         pgp_tsk_t tsk = pgp_tpk_as_tsk(tpk);
  1858         if (pgp_tsk_serialize(&err, tsk, armor_writer))
  1859             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "serializing TSK");
  1860         pgp_tsk_free(tsk);
  1861     } else {
  1862         if (pgp_tpk_serialize(&err, tpk, armor_writer))
  1863             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "serializing TPK");
  1864     }
  1865 
  1866  out:
  1867     if (armor_writer)
  1868         pgp_writer_free(armor_writer);
  1869 
  1870     if (tpk)
  1871         pgp_tpk_free(tpk);
  1872 
  1873     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  1874     return status;
  1875 }
  1876 
  1877 char* _undot_address(const char* address) {
  1878     if (!address)
  1879         return NULL;
  1880 
  1881     int addr_len = strlen(address);
  1882     const char* at = strstr(address, "@");
  1883 
  1884     if (!at)
  1885         at = address + addr_len;
  1886 
  1887     char* retval = calloc(1, addr_len + 1);
  1888 
  1889     const char* addr_curr = address;
  1890     char* retval_curr = retval;
  1891 
  1892     while (addr_curr < at) {
  1893         if (*addr_curr == '.') {
  1894             addr_curr++;
  1895             continue;
  1896         }
  1897         *retval_curr = *addr_curr;
  1898         retval_curr++;
  1899         addr_curr++;
  1900     }
  1901     if (*addr_curr == '@')
  1902         strcat(retval_curr, addr_curr);
  1903 
  1904     return retval;
  1905 }
  1906 
  1907 static stringpair_list_t *add_key(PEP_SESSION session,
  1908                                   stringpair_list_t *keyinfo_list,
  1909                                   stringlist_t* keylist,
  1910                                   pgp_tpk_t tpk, pgp_fingerprint_t fpr) {
  1911     bool revoked = false;
  1912     // Don't add revoked keys to the keyinfo_list.
  1913     if (keyinfo_list) {
  1914         pgp_revocation_status_t rs = pgp_tpk_revocation_status(tpk);
  1915         pgp_revocation_status_variant_t rsv = pgp_revocation_status_variant(rs);
  1916         pgp_revocation_status_free(rs);
  1917         if (rsv == PGP_REVOCATION_STATUS_REVOKED)
  1918             revoked = true;
  1919     }
  1920 
  1921     if (revoked && ! keylist)
  1922         return keyinfo_list;
  1923 
  1924     int dealloc_fpr = 0;
  1925     if (!fpr) {
  1926         dealloc_fpr = 1;
  1927         fpr = pgp_tpk_fingerprint(tpk);
  1928     }
  1929     char *fpr_str = pgp_fingerprint_to_hex(fpr);
  1930 
  1931     if (!revoked && keyinfo_list) {
  1932         char *user_id = pgp_tpk_primary_user_id(tpk);
  1933         if (user_id)
  1934             keyinfo_list = stringpair_list_add(keyinfo_list,
  1935                                                new_stringpair(fpr_str, user_id));
  1936         free(user_id);
  1937     }
  1938 
  1939     if (keylist)
  1940         keylist = stringlist_add(keylist, fpr_str);
  1941 
  1942     free(fpr_str);
  1943     if (dealloc_fpr)
  1944         pgp_fingerprint_free(fpr);
  1945 
  1946     return keyinfo_list;
  1947 }
  1948 
  1949 static PEP_STATUS list_keys(PEP_SESSION session,
  1950                             const char* pattern, int private_only,
  1951                             stringpair_list_t** keyinfo_list, stringlist_t** keylist)
  1952 {
  1953     PEP_STATUS status = PEP_STATUS_OK;
  1954     pgp_tpk_t tpk = NULL;
  1955     pgp_fingerprint_t fpr = NULL;
  1956 
  1957     T("('%s', private: %d)", pattern, private_only);
  1958 
  1959     stringpair_list_t* _keyinfo_list = NULL;
  1960     if (keyinfo_list) {
  1961         _keyinfo_list = new_stringpair_list(NULL);
  1962         if (!_keyinfo_list)
  1963             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "new_stringpair_list");
  1964     }
  1965     stringlist_t* _keylist = NULL;
  1966     if (keylist) {
  1967         _keylist = new_stringlist(NULL);
  1968         if (!_keylist)
  1969             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "new_string_list");
  1970     }
  1971 
  1972     // Trim any leading space.  This also makes it easier to recognize
  1973     // a string that is only whitespace.
  1974     while (*pattern == ' ')
  1975         pattern ++;
  1976 
  1977     if (strchr(pattern, '@')) {
  1978         // Looks like a mailbox.
  1979         pgp_tpk_t *tpks = NULL;
  1980         int count = 0;
  1981         status = tpk_find_by_email(session, pattern, private_only, &tpks, &count);
  1982         ERROR_OUT(NULL, status, "Looking up '%s'", pattern);
  1983         for (int i = 0; i < count; i ++) {
  1984             add_key(session, _keyinfo_list, _keylist, tpks[i], NULL);
  1985             pgp_tpk_free(tpks[i]);
  1986         }
  1987         free(tpks);
  1988 
  1989         if (count == 0) {
  1990             // If match failed, check to see if we've got a dotted
  1991             // address in the pattern.  If so, try again without dots.
  1992             const char* dotpos = strstr(pattern, ".");
  1993             const char* atpos = strstr(pattern, "@");
  1994             if (dotpos && atpos && (dotpos < atpos)) {
  1995                 char* undotted = _undot_address(pattern);
  1996                 if (undotted) {
  1997                     PEP_STATUS status = list_keys(session, undotted, private_only,
  1998                                                   keyinfo_list, keylist);
  1999                     free(undotted);
  2000                     return status;
  2001                 }
  2002             }
  2003         }
  2004     } else if (// Only hex characters and spaces
  2005                pattern[strspn(pattern, "0123456789aAbBcCdDeEfF ")] == 0
  2006                // And a fair amount of them.
  2007                && strlen(pattern) >= 16) {
  2008         // Fingerprint.  Note: the pep engine never looks keys up by
  2009         // keyid, so we don't handle them.
  2010         fpr = pgp_fingerprint_from_hex(pattern);
  2011         status = tpk_find_by_fpr(session, fpr, false, &tpk, NULL);
  2012         ERROR_OUT(NULL, status, "Looking up key");
  2013         add_key(session, _keyinfo_list, _keylist, tpk, fpr);
  2014     } else if (pattern[0] == 0) {
  2015         // Empty string.
  2016 
  2017         pgp_tpk_t *tpks = NULL;
  2018         int count = 0;
  2019         status = tpk_all(session, private_only, &tpks, &count);
  2020         ERROR_OUT(NULL, status, "Looking up '%s'", pattern);
  2021         for (int i = 0; i < count; i ++) {
  2022             add_key(session, _keyinfo_list, _keylist, tpks[i], NULL);
  2023             pgp_tpk_free(tpks[i]);
  2024         }
  2025         free(tpks);
  2026     } else {
  2027         T("unsupported pattern '%s'", pattern);
  2028     }
  2029 
  2030  out:
  2031     if (tpk)
  2032         pgp_tpk_free(tpk);
  2033     if (fpr)
  2034         pgp_fingerprint_free(fpr);
  2035 
  2036     if (status == PEP_KEY_NOT_FOUND)
  2037         status = PEP_STATUS_OK;
  2038 
  2039     if (status != PEP_STATUS_OK || (_keyinfo_list && !_keyinfo_list->value)) {
  2040         free_stringpair_list(_keyinfo_list);
  2041         _keyinfo_list = NULL;
  2042     }
  2043     if (keyinfo_list)
  2044         *keyinfo_list = _keyinfo_list;
  2045 
  2046     if (status != PEP_STATUS_OK || (_keylist && !_keylist->value)) {
  2047         free_stringlist(_keylist);
  2048         _keylist = NULL;
  2049     }
  2050     if (keylist)
  2051         *keylist = _keylist;
  2052 
  2053     int len = -1;
  2054     if (keylist)
  2055         len = stringlist_length(*keylist);
  2056     else if (keyinfo_list)
  2057         len = stringpair_list_length(*keyinfo_list);
  2058     T("(%s) -> %s (%d keys)", pattern, pEp_status_to_string(status), len);
  2059     return status;
  2060 }
  2061 
  2062 // pattern could be empty, an fpr, or a mailbox.
  2063 //
  2064 // keyinfo_list is a list of <fpr, openpgp userid> tuples for the
  2065 // matching keys.
  2066 //
  2067 // This function filters out revoked key, but not expired keys.
  2068 PEP_STATUS pgp_list_keyinfo(PEP_SESSION session,
  2069                             const char* pattern,
  2070                             stringpair_list_t** keyinfo_list)
  2071 {
  2072     return list_keys(session, pattern, false, keyinfo_list, NULL);
  2073 }
  2074 
  2075 PEP_STATUS pgp_recv_key(PEP_SESSION session, const char *pattern)
  2076 {
  2077     assert(!"pgp_recv_key not implemented");
  2078     return PEP_UNKNOWN_ERROR;
  2079 }
  2080 
  2081 // Unlike pgp_list_keyinfo, this function returns revoked keys.
  2082 PEP_STATUS pgp_find_keys(
  2083     PEP_SESSION session, const char *pattern, stringlist_t **keylist)
  2084 {
  2085     return list_keys(session, pattern, false, NULL, keylist);
  2086 }
  2087 
  2088 // Unlike pgp_list_keyinfo, this function returns revoked keys.
  2089 PEP_STATUS pgp_find_private_keys(
  2090     PEP_SESSION session, const char *pattern, stringlist_t **keylist)
  2091 {
  2092     return list_keys(session, pattern, true, NULL, keylist);
  2093 }
  2094 
  2095 PEP_STATUS pgp_send_key(PEP_SESSION session, const char *pattern)
  2096 {
  2097     assert(!"pgp_send_key not implemented");
  2098     return PEP_UNKNOWN_ERROR;
  2099 }
  2100 
  2101 PEP_STATUS pgp_get_key_rating(
  2102     PEP_SESSION session, const char *fpr, PEP_comm_type *comm_type)
  2103 {
  2104     PEP_STATUS status = PEP_STATUS_OK;
  2105     pgp_tpk_t tpk = NULL;
  2106 
  2107     assert(session);
  2108     assert(fpr);
  2109     assert(comm_type);
  2110 
  2111     *comm_type = PEP_ct_unknown;
  2112 
  2113     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  2114     status = tpk_find_by_fpr(session, pgp_fpr, false, &tpk, NULL);
  2115     pgp_fingerprint_free(pgp_fpr);
  2116     ERROR_OUT(NULL, status, "Looking up key: %s", fpr);
  2117 
  2118     *comm_type = PEP_ct_OpenPGP_unconfirmed;
  2119 
  2120     if (pgp_tpk_expired(tpk)) {
  2121         *comm_type = PEP_ct_key_expired;
  2122         goto out;
  2123     }
  2124 
  2125     pgp_revocation_status_t rs = pgp_tpk_revocation_status(tpk);
  2126     pgp_revocation_status_variant_t rsv = pgp_revocation_status_variant(rs);
  2127     pgp_revocation_status_free(rs);
  2128     if (rsv == PGP_REVOCATION_STATUS_REVOKED) {
  2129         *comm_type = PEP_ct_key_revoked;
  2130         goto out;
  2131     }
  2132 
  2133     PEP_comm_type best_enc = PEP_ct_no_encryption, best_sign = PEP_ct_no_encryption;
  2134     pgp_tpk_key_iter_t key_iter = pgp_tpk_key_iter_valid(tpk);
  2135     pgp_key_t key;
  2136     pgp_signature_t sig;
  2137     pgp_revocation_status_t rev;
  2138     while ((key = pgp_tpk_key_iter_next(key_iter, &sig, &rev))) {
  2139         if (! sig)
  2140             continue;
  2141 
  2142         PEP_comm_type curr = PEP_ct_no_encryption;
  2143 
  2144         int can_enc = pgp_signature_can_encrypt_for_transport(sig)
  2145             || pgp_signature_can_encrypt_at_rest(sig);
  2146         int can_sign = pgp_signature_can_sign(sig);
  2147 
  2148         pgp_public_key_algo_t pk_algo = pgp_key_public_key_algo(key);
  2149         if (pk_algo == PGP_PUBLIC_KEY_ALGO_RSA_ENCRYPT_SIGN
  2150             || pk_algo == PGP_PUBLIC_KEY_ALGO_RSA_ENCRYPT
  2151             || pk_algo == PGP_PUBLIC_KEY_ALGO_RSA_SIGN) {
  2152             int bits = pgp_key_public_key_bits(key);
  2153             if (bits < 1024)
  2154                 curr = PEP_ct_key_too_short;
  2155             else if (bits == 1024)
  2156                 curr = PEP_ct_OpenPGP_weak_unconfirmed;
  2157             else
  2158                 curr = PEP_ct_OpenPGP_unconfirmed;
  2159         } else {
  2160             curr = PEP_ct_OpenPGP_unconfirmed;
  2161         }
  2162 
  2163         if (can_enc)
  2164             best_enc = _MAX(best_enc, curr);
  2165 
  2166         if (can_sign)
  2167             best_sign = _MAX(best_sign, curr);
  2168     }
  2169     pgp_tpk_key_iter_free(key_iter);
  2170 
  2171     if (best_enc == PEP_ct_no_encryption || best_sign == PEP_ct_no_encryption) {
  2172         *comm_type = PEP_ct_key_b0rken;
  2173         goto out;
  2174     } else {
  2175         *comm_type = _MIN(best_enc, best_sign);
  2176     }
  2177 
  2178  out:
  2179     if (tpk)
  2180         pgp_tpk_free(tpk);
  2181 
  2182     T("(%s) -> %s", fpr, pep_comm_type_to_string(*comm_type));
  2183     return status;
  2184 }
  2185 
  2186 
  2187 PEP_STATUS pgp_renew_key(
  2188     PEP_SESSION session, const char *fpr, const timestamp *ts)
  2189 {
  2190     PEP_STATUS status = PEP_STATUS_OK;
  2191     pgp_error_t err = NULL;
  2192     pgp_tpk_t tpk = NULL;
  2193     pgp_tpk_key_iter_t iter = NULL;
  2194     pgp_key_pair_t keypair = NULL;
  2195     pgp_signer_t signer = NULL;
  2196     time_t t = mktime((struct tm *) ts);
  2197 
  2198     T("(%s)", fpr);
  2199 
  2200     status = tpk_find_by_fpr_hex(session, fpr, true, &tpk, NULL);
  2201     ERROR_OUT(NULL, status, "Looking up '%s'", fpr);
  2202 
  2203     uint32_t creation_time = pgp_key_creation_time(pgp_tpk_primary(tpk));
  2204     if (creation_time > t)
  2205         // The creation time is after the expiration time!
  2206         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
  2207                   "creation time can't be after expiration time");
  2208 
  2209     uint32_t delta = t - creation_time;
  2210 
  2211 
  2212     iter = pgp_tpk_key_iter_valid(tpk);
  2213     pgp_tpk_key_iter_certification_capable (iter);
  2214     pgp_tpk_key_iter_unencrypted_secret (iter, true);
  2215 
  2216     // If there are multiple certification capable subkeys, we just
  2217     // take the first one, whichever one that happens to be.
  2218     pgp_key_t key = pgp_tpk_key_iter_next (iter, NULL, NULL);
  2219     if (! key)
  2220         ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  2221                    "%s has no usable certification capable key", fpr);
  2222 
  2223     keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  2224     if (! keypair)
  2225         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  2226 
  2227     signer = pgp_key_pair_as_signer (keypair);
  2228     if (! signer)
  2229         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  2230 
  2231     tpk = pgp_tpk_set_expiry(&err, tpk, signer, delta);
  2232     if (! tpk)
  2233         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "setting expiration");
  2234 
  2235     status = tpk_save(session, tpk, NULL);
  2236     tpk = NULL;
  2237     ERROR_OUT(NULL, status, "Saving %s", fpr);
  2238 
  2239  out:
  2240     if (signer)
  2241         pgp_signer_free (signer);
  2242     if (keypair)
  2243         pgp_key_pair_free (keypair);
  2244     if (iter)
  2245         pgp_tpk_key_iter_free (iter);
  2246     if (tpk)
  2247         pgp_tpk_free(tpk);
  2248 
  2249     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2250     return status;
  2251 }
  2252 
  2253 PEP_STATUS pgp_revoke_key(
  2254     PEP_SESSION session, const char *fpr, const char *reason)
  2255 {
  2256     PEP_STATUS status = PEP_STATUS_OK;
  2257     pgp_error_t err = NULL;
  2258     pgp_tpk_t tpk = NULL;
  2259     pgp_tpk_key_iter_t iter = NULL;
  2260     pgp_key_pair_t keypair = NULL;
  2261     pgp_signer_t signer = NULL;
  2262 
  2263     T("(%s)", fpr);
  2264 
  2265     status = tpk_find_by_fpr_hex(session, fpr, true, &tpk, NULL);
  2266     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  2267 
  2268     iter = pgp_tpk_key_iter_valid(tpk);
  2269     pgp_tpk_key_iter_certification_capable (iter);
  2270     pgp_tpk_key_iter_unencrypted_secret (iter, true);
  2271 
  2272     // If there are multiple certification capable subkeys, we just
  2273     // take the first one, whichever one that happens to be.
  2274     pgp_key_t key = pgp_tpk_key_iter_next (iter, NULL, NULL);
  2275     if (! key)
  2276         ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  2277                    "%s has no usable certification capable key", fpr);
  2278 
  2279     keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  2280     if (! keypair)
  2281         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  2282 
  2283     signer = pgp_key_pair_as_signer (keypair);
  2284     if (! signer)
  2285         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  2286 
  2287     tpk = pgp_tpk_revoke_in_place(&err, tpk, signer,
  2288                                   PGP_REASON_FOR_REVOCATION_UNSPECIFIED,
  2289                                   reason);
  2290     if (! tpk)
  2291         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "setting expiration");
  2292 
  2293     assert(pgp_revocation_status_variant(pgp_tpk_revocation_status(tpk))
  2294            == PGP_REVOCATION_STATUS_REVOKED);
  2295 
  2296     status = tpk_save(session, tpk, NULL);
  2297     tpk = NULL;
  2298     ERROR_OUT(NULL, status, "Saving %s", fpr);
  2299 
  2300  out:
  2301     if (signer)
  2302         pgp_signer_free (signer);
  2303     if (keypair)
  2304         pgp_key_pair_free (keypair);
  2305     if (iter)
  2306         pgp_tpk_key_iter_free (iter);
  2307     if (tpk)
  2308         pgp_tpk_free(tpk);
  2309 
  2310     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2311     return status;
  2312 }
  2313 
  2314 PEP_STATUS pgp_key_expired(PEP_SESSION session, const char *fpr,
  2315                            const time_t when, bool *expired)
  2316 {
  2317     PEP_STATUS status = PEP_STATUS_OK;
  2318     pgp_tpk_t tpk = NULL;
  2319     T("(%s)", fpr);
  2320 
  2321     assert(session);
  2322     assert(fpr);
  2323     assert(expired);
  2324 
  2325     *expired = false;
  2326 
  2327     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  2328     status = tpk_find_by_fpr(session, pgp_fpr, false, &tpk, NULL);
  2329     pgp_fingerprint_free(pgp_fpr);
  2330     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  2331 
  2332     // Is the TPK live?
  2333     *expired = !pgp_tpk_alive_at(tpk, when);
  2334     if (*expired)
  2335         goto out;
  2336 
  2337     // Are there at least one certification subkey, one signing subkey
  2338     // and one encryption subkey that are live?
  2339     int can_certify = 0, can_encrypt = 0, can_sign = 0;
  2340 
  2341     pgp_tpk_key_iter_t key_iter = pgp_tpk_key_iter_valid(tpk);
  2342     pgp_key_t key;
  2343     pgp_signature_t sig;
  2344     pgp_revocation_status_t rev;
  2345     while ((key = pgp_tpk_key_iter_next(key_iter, &sig, &rev))) {
  2346         if (! sig)
  2347             continue;
  2348 
  2349         if (pgp_signature_can_encrypt_for_transport(sig)
  2350             || pgp_signature_can_encrypt_at_rest(sig))
  2351             can_encrypt = 1;
  2352         if (pgp_signature_can_sign(sig))
  2353             can_sign = 1;
  2354         if (pgp_signature_can_certify(sig))
  2355             can_certify = 1;
  2356 
  2357         if (can_encrypt && can_sign && can_certify)
  2358             break;
  2359     }
  2360     pgp_tpk_key_iter_free(key_iter);
  2361 
  2362     *expired = !(can_encrypt && can_sign && can_certify);
  2363 
  2364  out:
  2365     if (tpk)
  2366         pgp_tpk_free(tpk);
  2367     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2368     return status;
  2369 }
  2370 
  2371 PEP_STATUS pgp_key_revoked(PEP_SESSION session, const char *fpr, bool *revoked)
  2372 {
  2373     PEP_STATUS status = PEP_STATUS_OK;
  2374     pgp_tpk_t tpk;
  2375 
  2376     T("(%s)", fpr);
  2377 
  2378     assert(session);
  2379     assert(fpr);
  2380     assert(revoked);
  2381 
  2382     *revoked = false;
  2383 
  2384     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  2385     status = tpk_find_by_fpr(session, pgp_fpr, false, &tpk, NULL);
  2386     pgp_fingerprint_free(pgp_fpr);
  2387     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  2388 
  2389     pgp_revocation_status_t rs = pgp_tpk_revocation_status(tpk);
  2390     *revoked = pgp_revocation_status_variant(rs) == PGP_REVOCATION_STATUS_REVOKED;
  2391     pgp_revocation_status_free (rs);
  2392     pgp_tpk_free(tpk);
  2393 
  2394  out:
  2395     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2396     return status;
  2397 }
  2398 
  2399 PEP_STATUS pgp_key_created(PEP_SESSION session, const char *fpr, time_t *created)
  2400 {
  2401     PEP_STATUS status = PEP_STATUS_OK;
  2402     pgp_tpk_t tpk = NULL;
  2403     T("(%s)", fpr);
  2404 
  2405     *created = 0;
  2406 
  2407     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  2408     status = tpk_find_by_fpr(session, pgp_fpr, false, &tpk, NULL);
  2409     pgp_fingerprint_free(pgp_fpr);
  2410     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  2411 
  2412     pgp_key_t k = pgp_tpk_primary(tpk);
  2413     *created = pgp_key_creation_time(k);
  2414     pgp_tpk_free(tpk);
  2415 
  2416  out:
  2417     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2418     return status;
  2419 }
  2420 
  2421 PEP_STATUS pgp_binary(const char **path)
  2422 {
  2423     *path = NULL;
  2424     return PEP_STATUS_OK;
  2425 }
  2426 
  2427 PEP_STATUS pgp_contains_priv_key(PEP_SESSION session, const char *fpr,
  2428                                  bool *has_private)
  2429 {
  2430     T("(%s)", fpr);
  2431     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  2432     PEP_STATUS status = tpk_find_by_fpr(session, pgp_fpr, true, NULL, NULL);
  2433     pgp_fingerprint_free(pgp_fpr);
  2434     if (status == PEP_STATUS_OK) {
  2435         *has_private = 1;
  2436     } else if (status == PEP_KEY_NOT_FOUND) {
  2437         *has_private = 0;
  2438         status = PEP_STATUS_OK;
  2439     }
  2440     T("(%s) -> %s, %s",
  2441       fpr, *has_private ? "priv" : "pub", pEp_status_to_string(status));
  2442     return status;
  2443 }