src/pgp_sequoia.c
author Neal H. Walfield <neal@pep.foundation>
Wed, 20 Mar 2019 18:37:47 +0100
branchsync
changeset 3354 e9d5bcbc88f8
parent 3353 821f22f98225
child 3355 dd4033892b54
permissions -rw-r--r--
sequoia: Don't assume that the caller initializes stext & ssize

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