src/pgp_sequoia.c
author Krista 'DarthMama' Bennett <krista@pep.foundation>
Wed, 17 Jun 2020 19:38:23 +0200
branch2.0.5_p4a_log_test
changeset 4749 c276c93c972f
parent 4748 85cfc14aaa20
child 4750 39b0b5829e14
permissions -rw-r--r--
Yeah, helps to have a session
     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_sequoia.h"
    11 
    12 #include <limits.h>
    13 #include <sys/stat.h>
    14 #include <sys/types.h>
    15 #include <stdlib.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 #include "status_to_string.h"
    31 
    32 #  ifdef ANDROID
    33 #    include <android/log.h>
    34 #    define _T(...) do {                                                \
    35         __android_log_print(ANDROID_LOG_DEBUG, "pEpEngine-sequoia",     \
    36                             ##__VA_ARGS__);                             \
    37     } while (0)
    38 #  elif _WIN32
    39 #    define _T(...) do {                        \
    40         char str[256];                          \
    41         snprintf(str, 256, ##__VA_ARGS__);      \
    42         OutputDebugStringA(str);                \
    43         fprintf(stderr, ##__VA_ARGS__);         \
    44     } while (0)
    45 
    46 #  else
    47 #    define _T(...) do {                        \
    48         fprintf(stderr, ##__VA_ARGS__);         \
    49     } while (0)
    50 #  endif
    51 #else
    52 #  define _T(...) do { } while (0)
    53 #endif
    54 
    55 // Show the start of a tracepoint (i.e., don't print a newline).
    56 #define TC(...) do {       \
    57     _T("%s: ", __func__);  \
    58     _T(__VA_ARGS__);       \
    59 } while (0)
    60 
    61 // Show a trace point.
    62 #  define T(...) do {  \
    63     TC(__VA_ARGS__); \
    64     _T("\n");          \
    65 } while(0)
    66 
    67 // Verbosely displays errors.
    68 #  define DUMP_STATUS(__de_sq_status, __de_pep_status, ...) do { \
    69     TC(__VA_ARGS__);                                            \
    70     _T(": ");                                                   \
    71     if (__de_sq_status) {                                       \
    72         _T("Sequoia: %s => ", pgp_status_to_string(__de_sq_status));   \
    73     }                                                           \
    74     _T("%s\n", pEp_status_to_string(__de_pep_status));          \
    75 } while(0)
    76 
    77 #  define DUMP_ERR(__de_err, __de_status, ...) do {             \
    78     TC(__VA_ARGS__);                                            \
    79     _T(": ");                                                   \
    80     if (__de_err) {                                             \
    81         _T("Sequoia: %s => ", pgp_error_to_string(__de_err));   \
    82         pgp_error_free(__de_err);                               \
    83     }                                                           \
    84     _T("%s\n", pEp_status_to_string(__de_status));              \
    85 } while(0)
    86 
    87 // If __ec_status is an error, then dump the error, set 'status' to
    88 // it, and jump to 'out'.
    89 #define ERROR_OUT(__e_err, __ec_status, ...) do {                   \
    90     PEP_STATUS ___ec_status = (__ec_status);                        \
    91     if ((___ec_status) != PEP_STATUS_OK) {                          \
    92         DUMP_ERR((__e_err), (___ec_status), ##__VA_ARGS__);         \
    93         status = (___ec_status);                                    \
    94         goto out;                                                   \
    95     }                                                               \
    96 } while(0)
    97 
    98 #ifdef _PEP_SQLITE_DEBUG
    99 int sq_sql_trace_callback (unsigned trace_constant,
   100                         void* context_ptr,
   101                         void* P,
   102                         void* X) {
   103     const char* TC_str = "";
   104     const char* info_str = "";
   105     const char* title = "SEQUOIA_SQL_DEBUG";
   106                                 
   107     switch (trace_constant) {
   108         case SQLITE_TRACE_STMT:
   109             TC_str = "STMT";
   110             info_str = (const char*) X;
   111             if (EMPTYSTR(info_str) || info_str[0] != '-' || info_str[1] != '-')
   112                 info_str = sqlite3_expanded_sql((sqlite3_stmt*)P);
   113             break;
   114         case SQLITE_TRACE_ROW:
   115             TC_str = "ROW";
   116             info_str = sqlite3_expanded_sql((sqlite3_stmt*)P);
   117             break;
   118         case SQLITE_TRACE_CLOSE:
   119             TC_str = "CLOSE";
   120             break;
   121         default:
   122             break;
   123     }
   124 
   125 #ifndef ANDROID
   126     fprintf(stderr, "%s: %s - %s\n", title, TC_str, info_str);
   127 #else
   128     __android_log_print(ANDROID_LOG_DEBUG, "pEpEngine", " %s :: %s :: %s :: %s ",
   129             title, TC_str, info_str, NULL);
   130 #endif    
   131     return 0;
   132 }
   133 #endif
   134 
   135 /* This is reallocarray taken from OpenBSD. See README.md for licensing. */
   136 /* Symbols are renamed for clashes, not to hide source. */
   137 /*
   138  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
   139  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
   140  */
   141 #define PEP_MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
   142 static void* _pEp_reallocarray(void *optr, size_t nmemb, size_t size)
   143 {
   144     if ((nmemb >= PEP_MUL_NO_OVERFLOW || size >= PEP_MUL_NO_OVERFLOW) &&
   145         nmemb > 0 && SIZE_MAX / nmemb < size) {
   146             errno = ENOMEM;
   147             return NULL;
   148     }
   149     return realloc(optr, size * nmemb);
   150 }
   151 
   152 
   153 PEP_STATUS pgp_config_cipher_suite(PEP_SESSION session,
   154         PEP_CIPHER_SUITE suite)
   155 {
   156     switch (suite) {
   157         // supported cipher suites
   158         case PEP_CIPHER_SUITE_RSA2K:
   159         case PEP_CIPHER_SUITE_RSA3K:
   160         case PEP_CIPHER_SUITE_CV25519:
   161         case PEP_CIPHER_SUITE_P256:
   162         case PEP_CIPHER_SUITE_P384:
   163         case PEP_CIPHER_SUITE_P521:
   164             session->cipher_suite = suite;
   165             return PEP_STATUS_OK;
   166 
   167         case PEP_CIPHER_SUITE_DEFAULT:
   168             session->cipher_suite = PEP_CIPHER_SUITE_RSA2K;
   169             return PEP_STATUS_OK;
   170 
   171         // unsupported cipher suites
   172         default:
   173             session->cipher_suite = PEP_CIPHER_SUITE_RSA2K;
   174             return PEP_CANNOT_CONFIG;
   175     }
   176 }
   177 
   178 static pgp_cert_cipher_suite_t cipher_suite(PEP_CIPHER_SUITE suite)
   179 {
   180     switch (suite) {
   181         // supported cipher suites
   182         case PEP_CIPHER_SUITE_RSA2K:
   183             return PGP_CERT_CIPHER_SUITE_RSA2K;
   184         case PEP_CIPHER_SUITE_RSA3K:
   185             return PGP_CERT_CIPHER_SUITE_RSA3K;
   186         case PEP_CIPHER_SUITE_CV25519:
   187             return PGP_CERT_CIPHER_SUITE_CV25519;
   188         case PEP_CIPHER_SUITE_P256:
   189             return PGP_CERT_CIPHER_SUITE_P256;
   190         case PEP_CIPHER_SUITE_P384:
   191             return PGP_CERT_CIPHER_SUITE_P384;
   192         case PEP_CIPHER_SUITE_P521:
   193             return PGP_CERT_CIPHER_SUITE_P521;
   194         default:
   195             return PGP_CERT_CIPHER_SUITE_RSA2K;
   196     }
   197 }
   198 
   199 int email_cmp(void *cookie, int a_len, const void *a, int b_len, const void *b)
   200 {
   201     pgp_packet_t a_userid = pgp_user_id_from_raw (a, a_len);
   202     pgp_packet_t b_userid = pgp_user_id_from_raw (b, b_len);
   203 
   204     char *a_email = NULL;
   205     pgp_user_id_email_normalized(NULL, a_userid, &a_email);
   206     if (!a_email)
   207         pgp_user_id_uri(NULL, a_userid, &a_email);
   208 
   209     char *b_email = NULL;
   210     pgp_user_id_email_normalized(NULL, b_userid, &b_email);
   211     if (!b_email)
   212         pgp_user_id_uri(NULL, b_userid, &b_email);
   213 
   214     pgp_packet_free(a_userid);
   215     pgp_packet_free(b_userid);
   216 
   217     // return an integer that is negative, zero, or positive if the
   218     // first string is less than, equal to, or greater than the
   219     // second, respectively.
   220     int result;
   221     if (!a_email && !b_email)
   222         result = 0;
   223     else if (!a_email)
   224         result = -1;
   225     else if (!b_email)
   226         result = 1;
   227     else
   228         result = strcmp(a_email, b_email);
   229 
   230     if (true) {
   231         T("'%s' %s '%s'",
   232           a_email,
   233           result == 0 ? "==" : result < 0 ? "<" : ">",
   234           b_email);
   235     }
   236 
   237     free(a_email);
   238     free(b_email);
   239 
   240     return result;
   241 }
   242 
   243 PEP_STATUS pgp_init(PEP_SESSION session, bool in_first)
   244 {
   245     PEP_STATUS status = PEP_STATUS_OK;
   246 
   247 #ifdef _WIN32
   248 	int sqlite_result;
   249 	sqlite_result = sqlite3_open_v2(KEYS_DB,
   250 		&session->key_db,
   251 		SQLITE_OPEN_READWRITE
   252 		| SQLITE_OPEN_CREATE
   253 		| SQLITE_OPEN_FULLMUTEX
   254 		| SQLITE_OPEN_PRIVATECACHE,
   255 		NULL);
   256 #else
   257     // Create the home directory.
   258     char *home_env = NULL;
   259 #ifndef NDEBUG
   260     home_env = getenv("PEP_HOME");
   261 #endif
   262 
   263 #define PEP_KEYS_PATH "/.pEp/keys.db"
   264 
   265     if (!home_env)
   266         home_env = getenv("HOME");
   267 
   268     if (!home_env)
   269         ERROR_OUT(NULL, PEP_INIT_GPGME_INIT_FAILED, "HOME unset");
   270 
   271     // Create the DB and initialize it.
   272     size_t path_size = strlen(home_env) + sizeof(PEP_KEYS_PATH);
   273     char *path = (char *) calloc(path_size, 1);
   274     assert(path);
   275     if (!path)
   276         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
   277 
   278 	int r = snprintf(path, path_size, "%s" PEP_KEYS_PATH, home_env);
   279     assert(r >= 0 && r < path_size);
   280     if (r < 0) {
   281         free(path);
   282         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR, "snprintf");
   283     }
   284 
   285     int sqlite_result;
   286     sqlite_result = sqlite3_open_v2(path,
   287                                     &session->key_db,
   288                                     SQLITE_OPEN_READWRITE
   289                                     | SQLITE_OPEN_CREATE
   290                                     | SQLITE_OPEN_FULLMUTEX
   291                                     | SQLITE_OPEN_PRIVATECACHE,
   292                                     NULL);
   293     free(path);
   294 #endif
   295 
   296 #ifdef _PEP_SQLITE_DEBUG
   297     sqlite3_trace_v2(session->key_db,
   298         SQLITE_TRACE_STMT | SQLITE_TRACE_ROW | SQLITE_TRACE_CLOSE,
   299         sq_sql_trace_callback,
   300         NULL);
   301 #endif
   302 
   303     if (sqlite_result != SQLITE_OK)
   304         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   305                   "opening keys DB: %s", sqlite3_errmsg(session->key_db));
   306 
   307     sqlite_result = sqlite3_exec(session->key_db,
   308                                  "PRAGMA secure_delete=true;\n"
   309                                  "PRAGMA foreign_keys=true;\n"
   310                                  "PRAGMA locking_mode=NORMAL;\n"
   311                                  "PRAGMA journal_mode=WAL;\n",
   312                                  NULL, NULL, NULL);
   313     if (sqlite_result != SQLITE_OK)
   314         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   315                   "setting pragmas: %s", sqlite3_errmsg(session->key_db));
   316 
   317     sqlite3_busy_timeout(session->key_db, BUSY_WAIT_TIME);
   318 
   319     sqlite_result =
   320         sqlite3_create_collation(session->key_db,
   321                                 "EMAIL",
   322                                 SQLITE_UTF8,
   323                                 /* pArg (cookie) */ NULL,
   324                                 email_cmp);
   325     if (sqlite_result != SQLITE_OK)
   326         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   327                   "registering EMAIL collation function: %s",
   328                   sqlite3_errmsg(session->key_db));
   329 
   330     sqlite_result = sqlite3_exec(session->key_db,
   331                                  "CREATE TABLE IF NOT EXISTS keys (\n"
   332                                  "   primary_key TEXT UNIQUE PRIMARY KEY,\n"
   333                                  "   secret BOOLEAN,\n"
   334                                  "   tpk BLOB\n"
   335                                  ");\n"
   336                                  "CREATE INDEX IF NOT EXISTS keys_index\n"
   337                                  "  ON keys (primary_key, secret)\n",
   338                                  NULL, NULL, NULL);
   339     if (sqlite_result != SQLITE_OK)
   340         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   341                   "creating keys table: %s",
   342                   sqlite3_errmsg(session->key_db));
   343 
   344     sqlite_result = sqlite3_exec(session->key_db,
   345                                  "CREATE TABLE IF NOT EXISTS subkeys (\n"
   346                                  "   subkey TEXT NOT NULL,\n"
   347                                  "   primary_key TEXT NOT NULL,\n"
   348                                  "   UNIQUE(subkey, primary_key),\n"
   349                                  "   FOREIGN KEY (primary_key)\n"
   350                                  "       REFERENCES keys(primary_key)\n"
   351                                  "     ON DELETE CASCADE\n"
   352                                  ");\n"
   353                                  "CREATE INDEX IF NOT EXISTS subkeys_index\n"
   354                                  "  ON subkeys (subkey, primary_key)\n",
   355                                  NULL, NULL, NULL);
   356     if (sqlite_result != SQLITE_OK)
   357         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   358                   "creating subkeys table: %s",
   359                   sqlite3_errmsg(session->key_db));
   360 
   361     sqlite_result = sqlite3_exec(session->key_db,
   362                                  "CREATE TABLE IF NOT EXISTS userids (\n"
   363                                  "   userid TEXT NOT NULL COLLATE EMAIL,\n"
   364                                  "   primary_key TEXT NOT NULL,\n"
   365                                  "   UNIQUE(userid, primary_key),\n"
   366                                  "   FOREIGN KEY (primary_key)\n"
   367                                  "       REFERENCES keys(primary_key)\n"
   368                                  "     ON DELETE CASCADE\n"
   369                                  ");\n"
   370                                  "CREATE INDEX IF NOT EXISTS userids_index\n"
   371                                  "  ON userids (userid COLLATE EMAIL, primary_key)\n",
   372                                  NULL, NULL, NULL);
   373     if (sqlite_result != SQLITE_OK)
   374         ERROR_OUT(NULL, PEP_INIT_CANNOT_OPEN_DB,
   375                   "creating userids table: %s",
   376                   sqlite3_errmsg(session->key_db));
   377 
   378     sqlite_result
   379         = sqlite3_prepare_v2(session->key_db, "begin transaction",
   380                              -1, &session->sq_sql.begin_transaction, NULL);
   381     assert(sqlite_result == SQLITE_OK);
   382 
   383     sqlite_result
   384         = sqlite3_prepare_v2(session->key_db, "commit transaction",
   385                              -1, &session->sq_sql.commit_transaction, NULL);
   386     assert(sqlite_result == SQLITE_OK);
   387 
   388     sqlite_result
   389         = sqlite3_prepare_v2(session->key_db, "rollback transaction",
   390                              -1, &session->sq_sql.rollback_transaction, NULL);
   391     assert(sqlite_result == SQLITE_OK);
   392 
   393     sqlite_result
   394         = sqlite3_prepare_v2(session->key_db,
   395                              "SELECT tpk, secret FROM keys"
   396                              " WHERE primary_key == ?",
   397                              -1, &session->sq_sql.cert_find, NULL);
   398     assert(sqlite_result == SQLITE_OK);
   399 
   400     sqlite_result
   401         = sqlite3_prepare_v2(session->key_db,
   402                              "SELECT tpk, secret FROM keys"
   403                              " WHERE primary_key == ? and secret == 1",
   404                              -1, &session->sq_sql.tsk_find, NULL);
   405     assert(sqlite_result == SQLITE_OK);
   406 
   407     sqlite_result
   408         = sqlite3_prepare_v2(session->key_db,
   409                              "SELECT tpk, secret FROM subkeys"
   410                              " LEFT JOIN keys"
   411                              "  ON subkeys.primary_key == keys.primary_key"
   412                              " WHERE subkey == ?",
   413                              -1, &session->sq_sql.cert_find_by_keyid, NULL);
   414     assert(sqlite_result == SQLITE_OK);
   415 
   416     sqlite_result
   417         = sqlite3_prepare_v2(session->key_db,
   418                              "SELECT tpk, secret FROM subkeys"
   419                              " LEFT JOIN keys"
   420                              "  ON subkeys.primary_key == keys.primary_key"
   421                              " WHERE subkey == ?",
   422                              -1, &session->sq_sql.cert_find_by_keyid, NULL);
   423     assert(sqlite_result == SQLITE_OK);
   424 
   425     sqlite_result
   426         = sqlite3_prepare_v2(session->key_db,
   427                              "SELECT tpk, secret FROM subkeys"
   428                              " LEFT JOIN keys"
   429                              "  ON subkeys.primary_key == keys.primary_key"
   430                              " WHERE subkey == ? and keys.secret == 1",
   431                              -1, &session->sq_sql.tsk_find_by_keyid, NULL);
   432     assert(sqlite_result == SQLITE_OK);
   433 
   434     sqlite_result
   435         = sqlite3_prepare_v2(session->key_db,
   436                              "SELECT tpk, secret FROM userids"
   437                              " LEFT JOIN keys"
   438                              "  ON userids.primary_key == keys.primary_key"
   439                              " WHERE userid == ?",
   440                              -1, &session->sq_sql.cert_find_by_email, NULL);
   441     assert(sqlite_result == SQLITE_OK);
   442 
   443     sqlite_result
   444         = sqlite3_prepare_v2(session->key_db,
   445                              "SELECT tpk, secret FROM userids"
   446                              " LEFT JOIN keys"
   447                              "  ON userids.primary_key == keys.primary_key"
   448                              " WHERE userid == ? and keys.secret == 1",
   449                              -1, &session->sq_sql.tsk_find_by_email, NULL);
   450     assert(sqlite_result == SQLITE_OK);
   451 
   452     sqlite_result
   453         = sqlite3_prepare_v2(session->key_db,
   454                              "select tpk, secret from keys",
   455                              -1, &session->sq_sql.cert_all, NULL);
   456     assert(sqlite_result == SQLITE_OK);
   457 
   458     sqlite_result
   459         = sqlite3_prepare_v2(session->key_db,
   460                              "select tpk, secret from keys where secret = 1",
   461                              -1, &session->sq_sql.tsk_all, NULL);
   462     assert(sqlite_result == SQLITE_OK);
   463 
   464     sqlite_result
   465         = sqlite3_prepare_v2(session->key_db,
   466                              "INSERT OR REPLACE INTO keys"
   467                              "   (primary_key, secret, tpk)"
   468                              " VALUES (?, ?, ?)",
   469                              -1, &session->sq_sql.cert_save_insert_primary, NULL);
   470     assert(sqlite_result == SQLITE_OK);
   471 
   472     sqlite_result
   473         = sqlite3_prepare_v2(session->key_db,
   474                              "INSERT OR REPLACE INTO subkeys"
   475                              "   (subkey, primary_key)"
   476                              " VALUES (?, ?)",
   477                              -1, &session->sq_sql.cert_save_insert_subkeys, NULL);
   478     assert(sqlite_result == SQLITE_OK);
   479 
   480     sqlite_result
   481         = sqlite3_prepare_v2(session->key_db,
   482                              "INSERT OR REPLACE INTO userids"
   483                              "   (userid, primary_key)"
   484                              " VALUES (?, ?)",
   485                              -1, &session->sq_sql.cert_save_insert_userids, NULL);
   486     assert(sqlite_result == SQLITE_OK);
   487 
   488     sqlite_result
   489         = sqlite3_prepare_v2(session->key_db,
   490                              "DELETE FROM keys WHERE primary_key = ?",
   491                              -1, &session->sq_sql.delete_keypair, NULL);
   492     assert(sqlite_result == SQLITE_OK);
   493 
   494     session->policy = pgp_null_policy ();
   495     if (! session->policy)
   496         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY,
   497                   "initializing openpgp policy");
   498 
   499  out:
   500     if (status != PEP_STATUS_OK)
   501         pgp_release(session, in_first);
   502     return status;
   503 }
   504 
   505 void pgp_release(PEP_SESSION session, bool out_last)
   506 {
   507     pgp_policy_free (session->policy);
   508     session->policy = NULL;
   509 
   510     sqlite3_stmt **stmts = (sqlite3_stmt **) &session->sq_sql;
   511     for (int i = 0; i < sizeof(session->sq_sql) / sizeof(*stmts); i ++)
   512         if (stmts[i]) {
   513             sqlite3_finalize(stmts[i]);
   514             stmts[i] = NULL;
   515         }
   516 
   517     if (session->key_db) {
   518         int result = sqlite3_close_v2(session->key_db);
   519         if (result != 0)
   520             DUMP_ERR(NULL, PEP_UNKNOWN_ERROR,
   521                      "Closing key DB: sqlite3_close_v2: %s",
   522                      sqlite3_errstr(result));
   523         session->key_db = NULL;
   524     }
   525 }
   526 
   527 // Ensures that a fingerprint is in canonical form.  A canonical
   528 // fingerprint doesn't contain any white space.
   529 //
   530 // This function does *not* consume fpr.
   531 static char *pgp_fingerprint_canonicalize(const char *) __attribute__((nonnull));
   532 static char *pgp_fingerprint_canonicalize(const char *fpr)
   533 {
   534     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
   535     char *fpr_canonicalized = pgp_fingerprint_to_hex(pgp_fpr);
   536     pgp_fingerprint_free(pgp_fpr);
   537 
   538     return fpr_canonicalized;
   539 }
   540 
   541 // step statement and load the certificate and secret.
   542 static PEP_STATUS key_load(PEP_SESSION, sqlite3_stmt *, pgp_cert_t *, int *)
   543     __attribute__((nonnull(1, 2)));
   544 static PEP_STATUS key_load(PEP_SESSION session, sqlite3_stmt *stmt,
   545                            pgp_cert_t *certp, int *secretp)
   546 {
   547     PEP_STATUS status = PEP_STATUS_OK;
   548     int sqlite_result = sqlite3_step(stmt);
   549     switch (sqlite_result) {
   550     case SQLITE_ROW:
   551         if (certp) {
   552             int data_len = sqlite3_column_bytes(stmt, 0);
   553             const void *data = sqlite3_column_blob(stmt, 0);
   554 
   555             pgp_error_t err = NULL;
   556             *certp = pgp_cert_from_bytes(&err, data, data_len);
   557             if (!*certp)
   558                 ERROR_OUT(err, PEP_GET_KEY_FAILED, "parsing certificate");
   559         }
   560 
   561         if (secretp)
   562             *secretp = sqlite3_column_int(stmt, 1);
   563 
   564         break;
   565     case SQLITE_DONE:
   566         // Got nothing.
   567         status = PEP_KEY_NOT_FOUND;
   568         break;
   569     default:
   570         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   571                   "stepping: %s", sqlite3_errmsg(session->key_db));
   572     }
   573 
   574  out:
   575     T(" -> %s", pEp_status_to_string(status));
   576     return status;
   577 }
   578 
   579 // step statement until exhausted and load the certificates.
   580 static PEP_STATUS key_loadn(PEP_SESSION, sqlite3_stmt *, pgp_cert_t **, int *)
   581     __attribute__((nonnull));
   582 static PEP_STATUS key_loadn(PEP_SESSION session, sqlite3_stmt *stmt,
   583                             pgp_cert_t **certsp, int *certs_countp)
   584 {
   585     PEP_STATUS status = PEP_STATUS_OK;
   586     int certs_count = 0;
   587     int certs_capacity = 8;
   588     pgp_cert_t *certs = calloc(certs_capacity, sizeof(pgp_cert_t));
   589     if (!certs)
   590         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
   591 
   592     for (;;) {
   593         pgp_cert_t cert = NULL;
   594         status = key_load(session, stmt, &cert, NULL);
   595         if (status == PEP_KEY_NOT_FOUND) {
   596             status = PEP_STATUS_OK;
   597             break;
   598         }
   599         ERROR_OUT(NULL, status, "loading certificate");
   600 
   601         if (certs_count == certs_capacity) {
   602             certs_capacity *= 2;
   603             certs = realloc(certs, sizeof(certs[0]) * certs_capacity);
   604             if (!certs)
   605                 ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "certs");
   606         }
   607         certs[certs_count ++] = cert;
   608     }
   609 
   610  out:
   611     if (status != PEP_STATUS_OK) {
   612         for (int i = 0; i < certs_count; i ++)
   613             pgp_cert_free(certs[i]);
   614         free(certs);
   615     } else {
   616         *certsp = certs;
   617         *certs_countp = certs_count;
   618     }
   619 
   620     T(" -> %s (%d certs)", pEp_status_to_string(status), *certs_countp);
   621     return status;
   622 }
   623 
   624 // Returns the certificate identified by the provided fingerprint.
   625 //
   626 // This function only matches on the primary key!
   627 static PEP_STATUS cert_find(PEP_SESSION, pgp_fingerprint_t, int, pgp_cert_t *, int *)
   628     __attribute__((nonnull(1, 2)));
   629 static PEP_STATUS cert_find(PEP_SESSION session,
   630                            pgp_fingerprint_t fpr, int private_only,
   631                            pgp_cert_t *cert, int *secret)
   632 {
   633     PEP_STATUS status = PEP_STATUS_OK;
   634     char *fpr_str = pgp_fingerprint_to_hex(fpr);
   635 
   636     T("(%s, %d)", fpr_str, private_only);
   637 
   638     sqlite3_stmt *stmt
   639         = private_only ? session->sq_sql.tsk_find : session->sq_sql.cert_find;
   640     sqlite3_bind_text(stmt, 1, fpr_str, -1, SQLITE_STATIC);
   641 
   642     status = key_load(session, stmt, cert, secret);
   643     ERROR_OUT(NULL, status, "Looking up %s", fpr_str);
   644 
   645  out:
   646     sqlite3_reset(stmt);
   647     T("(%s, %d) -> %s", fpr_str, private_only, pEp_status_to_string(status));
   648     free(fpr_str);
   649     return status;
   650 }
   651 
   652 // Returns the certificate identified by the provided keyid.
   653 //
   654 // This function matches on both primary keys and subkeys!
   655 //
   656 // Note: There can be multiple certificates for a given keyid.  This can
   657 // occur, because an encryption subkey can be bound to multiple certificates.
   658 // Also, it is possible to collide key ids.  If there are multiple key
   659 // ids for a given key, this just returns one of them.
   660 //
   661 // If private_only is set, this will only consider certificates with some
   662 // secret key material.
   663 static PEP_STATUS cert_find_by_keyid_hex(PEP_SESSION, const char *, int, pgp_cert_t *, int *)
   664   __attribute__((nonnull(1, 2)));
   665 static PEP_STATUS cert_find_by_keyid_hex(
   666         PEP_SESSION session, const char *keyid_hex, int private_only,
   667         pgp_cert_t *certp, int *secretp)
   668 {
   669     PEP_STATUS status = PEP_STATUS_OK;
   670     T("(%s, %d)", keyid_hex, private_only);
   671 
   672     sqlite3_stmt *stmt
   673         = private_only ? session->sq_sql.tsk_find_by_keyid : session->sq_sql.cert_find_by_keyid;
   674     sqlite3_bind_text(stmt, 1, keyid_hex, -1, SQLITE_STATIC);
   675 
   676     status = key_load(session, stmt, certp, secretp);
   677     ERROR_OUT(NULL, status, "Looking up %s", keyid_hex);
   678 
   679  out:
   680     sqlite3_reset(stmt);
   681     T("(%s, %d) -> %s", keyid_hex, private_only, pEp_status_to_string(status));
   682     return status;
   683 }
   684 
   685 // See cert_find_by_keyid_hex.
   686 PEP_STATUS cert_find_by_keyid(PEP_SESSION, pgp_keyid_t, int, pgp_cert_t *, int *)
   687     __attribute__((nonnull(1, 2)));
   688 PEP_STATUS cert_find_by_keyid(PEP_SESSION session,
   689                              pgp_keyid_t keyid, int private_only,
   690                              pgp_cert_t *certp, int *secretp)
   691 {
   692     char *keyid_hex = pgp_keyid_to_hex(keyid);
   693     if (! keyid_hex)
   694         return PEP_OUT_OF_MEMORY;
   695     PEP_STATUS status
   696         = cert_find_by_keyid_hex(session, keyid_hex, private_only, certp, secretp);
   697     free(keyid_hex);
   698     return status;
   699 }
   700 
   701 // See cert_find_by_keyid_hex.
   702 static PEP_STATUS cert_find_by_fpr(PEP_SESSION, pgp_fingerprint_t, int,
   703                                   pgp_cert_t *, int *)
   704     __attribute__((nonnull(1, 2)));
   705 static PEP_STATUS cert_find_by_fpr(
   706     PEP_SESSION session, pgp_fingerprint_t fpr, int private_only,
   707     pgp_cert_t *certp, int *secretp)
   708 {
   709     pgp_keyid_t keyid = pgp_fingerprint_to_keyid(fpr);
   710     if (! keyid)
   711         return PEP_OUT_OF_MEMORY;
   712     PEP_STATUS status
   713         = cert_find_by_keyid(session, keyid, private_only, certp, secretp);
   714     pgp_keyid_free(keyid);
   715     return status;
   716 }
   717 
   718 // See cert_find_by_keyid_hex.
   719 static PEP_STATUS cert_find_by_fpr_hex(PEP_SESSION, const char *, int, pgp_cert_t *, int *secret)
   720     __attribute__((nonnull(1, 2)));
   721 static PEP_STATUS cert_find_by_fpr_hex(
   722     PEP_SESSION session, const char *fpr, int private_only,
   723     pgp_cert_t *certp, int *secretp)
   724 {
   725     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
   726     if (! pgp_fpr)
   727         return PEP_OUT_OF_MEMORY;
   728     PEP_STATUS status
   729         = cert_find_by_fpr(session, pgp_fpr, private_only, certp, secretp);
   730     pgp_fingerprint_free(pgp_fpr);
   731     return status;
   732 }
   733 
   734 // Returns all known certificates.
   735 static PEP_STATUS cert_all(PEP_SESSION, int, pgp_cert_t **, int *) __attribute__((nonnull));
   736 static PEP_STATUS cert_all(PEP_SESSION session, int private_only,
   737                           pgp_cert_t **certsp, int *certs_countp) {
   738     PEP_STATUS status = PEP_STATUS_OK;
   739     sqlite3_stmt *stmt = private_only ? session->sq_sql.tsk_all : session->sq_sql.cert_all;
   740     status = key_loadn(session, stmt, certsp, certs_countp);
   741     ERROR_OUT(NULL, status, "loading certificates");
   742  out:
   743     sqlite3_reset(stmt);
   744     return status;
   745 }
   746 
   747 // Returns keys that have a user id that matches the specified pattern.
   748 //
   749 // The keys returned must be freed using pgp_cert_free.
   750 static PEP_STATUS cert_find_by_email(PEP_SESSION, const char *, int, pgp_cert_t **, int *)
   751     __attribute__((nonnull));
   752 static PEP_STATUS cert_find_by_email(PEP_SESSION session,
   753                                     const char *pattern, int private_only,
   754                                     pgp_cert_t **certsp, int *countp)
   755 {
   756     PEP_STATUS status = PEP_STATUS_OK;
   757     T("(%s)", pattern);
   758 
   759     sqlite3_stmt *stmt
   760         = private_only ? session->sq_sql.tsk_find_by_email : session->sq_sql.cert_find_by_email;
   761     sqlite3_bind_text(stmt, 1, pattern, -1, SQLITE_STATIC);
   762 
   763     status = key_loadn(session, stmt, certsp, countp);
   764     ERROR_OUT(NULL, status, "Searching for '%s'", pattern);
   765 
   766  out:
   767     sqlite3_reset(stmt);
   768     T("(%s) -> %s (%d results)", pattern, pEp_status_to_string(status), *countp);
   769     return status;
   770 }
   771 
   772 
   773 // Saves the specified certificates.
   774 //
   775 // This function takes ownership of CERT.
   776 static PEP_STATUS cert_save(PEP_SESSION, pgp_cert_t, identity_list **)
   777     __attribute__((nonnull(1, 2)));
   778 static PEP_STATUS cert_save(PEP_SESSION session, pgp_cert_t cert,
   779                            identity_list **private_idents)
   780 {
   781     PEP_STATUS status = PEP_STATUS_OK;
   782     pgp_error_t err = NULL;
   783     pgp_fingerprint_t pgp_fpr = NULL;
   784     char *fpr = NULL;
   785     void *tsk_buffer = NULL;
   786     size_t tsk_buffer_len = 0;
   787     int tried_commit = 0;
   788     pgp_cert_key_iter_t key_iter = NULL;
   789     pgp_user_id_bundle_iter_t user_id_iter = NULL;
   790     char *email = NULL;
   791     char *name = NULL;
   792 
   793     sqlite3_stmt *stmt = session->sq_sql.begin_transaction;
   794     int sqlite_result = sqlite3_step(stmt);
   795     sqlite3_reset(stmt);
   796     if (sqlite_result != SQLITE_DONE)
   797         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   798                   "begin transaction failed: %s",
   799                   sqlite3_errmsg(session->key_db));
   800 
   801     pgp_fpr = pgp_cert_fingerprint(cert);
   802     fpr = pgp_fingerprint_to_hex(pgp_fpr);
   803     T("(%s, private_idents: %s)", fpr, private_idents ? "yes" : "no");
   804 
   805     // Merge any existing data into certificate.
   806     pgp_cert_t current = NULL;
   807     status = cert_find(session, pgp_fpr, false, &current, NULL);
   808     if (status == PEP_KEY_NOT_FOUND)
   809         status = PEP_STATUS_OK;
   810     else
   811         ERROR_OUT(NULL, status, "Looking up %s", fpr);
   812     if (current) {
   813         cert = pgp_cert_merge(&err, cert, current);
   814         if (! cert)
   815             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Merging certificates");
   816     }
   817 
   818     int is_tsk = pgp_cert_is_tsk(cert);
   819 
   820     // Serialize it.
   821     pgp_writer_t writer = pgp_writer_alloc(&tsk_buffer, &tsk_buffer_len);
   822     if (! writer)
   823         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
   824 
   825     pgp_status_t pgp_status;
   826     pgp_tsk_t tsk = pgp_cert_as_tsk(cert);
   827     pgp_status = pgp_tsk_serialize(&err, tsk, writer);
   828     pgp_tsk_free(tsk);
   829     pgp_writer_free(writer);
   830     if (pgp_status != 0)
   831         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Serializing certificates");
   832 
   833 
   834     // Insert the TSK into the DB.
   835     stmt = session->sq_sql.cert_save_insert_primary;
   836     sqlite3_bind_text(stmt, 1, fpr, -1, SQLITE_STATIC);
   837     sqlite3_bind_int(stmt, 2, is_tsk);
   838     sqlite3_bind_blob(stmt, 3, tsk_buffer, tsk_buffer_len, SQLITE_STATIC);
   839 
   840     sqlite_result = sqlite3_step(stmt);
   841     sqlite3_reset(stmt);
   842     if (sqlite_result != SQLITE_DONE)
   843         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   844                   "Saving certificate: %s", sqlite3_errmsg(session->key_db));
   845 
   846     // Insert the "subkeys" (the primary key and the subkeys).
   847     stmt = session->sq_sql.cert_save_insert_subkeys;
   848     // This inserts all of the keys in the certificate, i.e.,
   849     // including revoked and expired keys, which is what we want.
   850     key_iter = pgp_cert_key_iter(cert);
   851     pgp_key_amalgamation_t ka;
   852     while ((ka = pgp_cert_key_iter_next(key_iter))) {
   853         pgp_key_t key = pgp_key_amalgamation_key (ka);
   854 
   855         pgp_keyid_t keyid = pgp_key_keyid(key);
   856         char *keyid_hex = pgp_keyid_to_hex(keyid);
   857         sqlite3_bind_text(stmt, 1, keyid_hex, -1, SQLITE_STATIC);
   858         sqlite3_bind_text(stmt, 2, fpr, -1, SQLITE_STATIC);
   859 
   860         pgp_key_free (key);
   861         pgp_key_amalgamation_free (ka);
   862 
   863         sqlite_result = sqlite3_step(stmt);
   864         sqlite3_reset(stmt);
   865         free(keyid_hex);
   866         pgp_keyid_free(keyid);
   867         if (sqlite_result != SQLITE_DONE) {
   868             pgp_cert_key_iter_free(key_iter);
   869             ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   870                       "Updating subkeys: %s", sqlite3_errmsg(session->key_db));
   871         }
   872     }
   873     pgp_cert_key_iter_free(key_iter);
   874     key_iter = NULL;
   875 
   876     // Insert the "userids".
   877     stmt = session->sq_sql.cert_save_insert_userids;
   878     user_id_iter = pgp_cert_user_id_bundle_iter(cert);
   879     pgp_user_id_bundle_t bundle;
   880     int first = 1;
   881     while ((bundle = pgp_user_id_bundle_iter_next(user_id_iter))) {
   882         char *user_id_value = pgp_user_id_bundle_user_id(bundle);
   883         if (!user_id_value || !*user_id_value)
   884             continue;
   885 
   886         // Ignore user ids with a self-revocation certificate, but no
   887         // self-signature.
   888         if (!pgp_user_id_bundle_selfsig(bundle, session->policy)) {
   889             free(user_id_value);
   890             continue;
   891         }
   892 
   893         free(name);
   894         name = NULL;
   895         free(email);
   896         email = NULL;
   897 
   898         pgp_packet_t userid = pgp_user_id_new (user_id_value);
   899         pgp_user_id_name(NULL, userid, &name);
   900         // Try to get the normalized address.
   901         pgp_user_id_email_normalized(NULL, userid, &email);
   902         if (! email)
   903             // Ok, it's not a proper RFC 2822 name-addr.  Perhaps it
   904             // is a URI.
   905             pgp_user_id_uri(NULL, userid, &email);
   906         pgp_packet_free(userid);
   907         free(user_id_value);
   908 
   909         if (email) {
   910             T("  userid: %s", email);
   911 
   912             sqlite3_bind_text(stmt, 1, email, -1, SQLITE_STATIC);
   913             sqlite3_bind_text(stmt, 2, fpr, -1, SQLITE_STATIC);
   914 
   915             sqlite_result = sqlite3_step(stmt);
   916             sqlite3_reset(stmt);
   917 
   918             if (sqlite_result != SQLITE_DONE) {
   919                 pgp_user_id_bundle_iter_free(user_id_iter);
   920                 ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   921                           "Updating userids: %s", sqlite3_errmsg(session->key_db));
   922             }
   923         }
   924 
   925         if (first && private_idents && is_tsk) {
   926             first = 0;
   927 
   928             // Create an identity for the primary user id.
   929             pEp_identity *ident = new_identity(email, fpr, NULL, name);
   930             if (ident == NULL)
   931                 ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "new_identity");
   932 
   933             *private_idents = identity_list_add(*private_idents, ident);
   934             if (*private_idents == NULL)
   935                 ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "identity_list_add");
   936         }
   937 
   938     }
   939     pgp_user_id_bundle_iter_free(user_id_iter);
   940     user_id_iter = NULL;
   941 
   942  out:
   943     // Prevent ERROR_OUT from causing an infinite loop.
   944     if (! tried_commit) {
   945         tried_commit = 1;
   946         stmt = status == PEP_STATUS_OK
   947             ? session->sq_sql.commit_transaction
   948             : session->sq_sql.rollback_transaction;
   949         int sqlite_result = sqlite3_step(stmt);
   950         sqlite3_reset(stmt);
   951         if (sqlite_result != SQLITE_DONE)
   952             ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
   953                       status == PEP_STATUS_OK
   954                       ? "commit failed: %s" : "rollback failed: %s",
   955                       sqlite3_errmsg(session->key_db));
   956     }
   957 
   958     T("(%s) -> %s", fpr, pEp_status_to_string(status));
   959 
   960     free(email);
   961     free(name);
   962     pgp_user_id_bundle_iter_free(user_id_iter);
   963     pgp_cert_key_iter_free(key_iter);
   964     if (stmt)
   965       sqlite3_reset(stmt);
   966     free(tsk_buffer);
   967     pgp_cert_free(cert);
   968     free(fpr);
   969     pgp_fingerprint_free(pgp_fpr);
   970 
   971     return status;
   972 }
   973 
   974 struct decrypt_cookie {
   975     PEP_SESSION session;
   976     int get_secret_keys_called;
   977     stringlist_t *recipient_keylist;
   978     stringlist_t *signer_keylist;
   979 
   980     int good_checksums;
   981     int malformed_signature;
   982     int missing_keys;
   983     int unbound_key;
   984     int revoked_key;
   985     int expired_key;
   986     int bad_key;
   987     int bad_checksums;
   988 
   989     // Whether we decrypted anything.
   990     int decrypted;
   991 
   992     // The filename stored in the literal data packet.  Note: this is
   993     // *not* protected by the signature and should not be trusted!!!
   994     char *filename;
   995 };
   996 
   997 static pgp_status_t
   998 get_public_keys_cb(void *cookie_raw,
   999                    pgp_keyid_t *keyids, size_t keyids_len,
  1000                    pgp_cert_t **certs, size_t *certs_len,
  1001                    void (**our_free)(void *))
  1002 {
  1003     struct decrypt_cookie *cookie = cookie_raw;
  1004     PEP_SESSION session = cookie->session;
  1005 
  1006     *certs = calloc(keyids_len, sizeof(*certs));
  1007     if (!*certs)
  1008         return PGP_STATUS_UNKNOWN_ERROR;
  1009     *our_free = free;
  1010 
  1011     size_t i;
  1012     int j = 0;
  1013     for (i = 0; i < keyids_len; i ++) {
  1014         pgp_cert_t cert = NULL;
  1015         PEP_STATUS status
  1016             = cert_find_by_keyid(session, keyids[i], false, &cert, NULL);
  1017         if (status == PEP_STATUS_OK)
  1018             (*certs)[j ++] = cert;
  1019     }
  1020     *certs_len = j;
  1021     return PGP_STATUS_SUCCESS;
  1022 }
  1023 
  1024 static pgp_status_t
  1025 decrypt_cb(void *cookie_opaque,
  1026            pgp_pkesk_t *pkesks, size_t pkesk_count,
  1027            pgp_skesk_t *skesks, size_t skesk_count,
  1028            uint8_t symmetric_algo,
  1029            pgp_decryptor_do_decrypt_cb_t *decrypt,
  1030            void *decrypt_cookie,
  1031            pgp_fingerprint_t *identity_out)
  1032 {
  1033     pgp_error_t err = NULL;
  1034     struct decrypt_cookie *cookie = cookie_opaque;
  1035     PEP_SESSION session = cookie->session;
  1036     pgp_cert_t *tsks = NULL;
  1037     int tsks_count = 0;
  1038     int wildcards = 0;
  1039 
  1040     if (cookie->get_secret_keys_called)
  1041         // Prevent iterations, which isn't needed since we don't
  1042         // support SKESKs.
  1043         return PGP_STATUS_UNKNOWN_ERROR;
  1044     cookie->get_secret_keys_called = 1;
  1045 
  1046     T("%zd PKESKs", pkesk_count);
  1047 
  1048     for (size_t i = 0; i < pkesk_count; i ++) {
  1049         pgp_pkesk_t pkesk = pkesks[i];
  1050         pgp_keyid_t keyid = pgp_pkesk_recipient(pkesk); /* Reference. */
  1051         char *keyid_str = pgp_keyid_to_hex(keyid);
  1052         pgp_cert_key_iter_t key_iter = NULL;
  1053         pgp_key_amalgamation_t ka = NULL;
  1054         pgp_key_t key = NULL;
  1055         pgp_session_key_t sk = NULL;
  1056 
  1057         T("Considering PKESK for %s", keyid_str);
  1058 
  1059         if (strcmp(keyid_str, "0000000000000000") == 0) {
  1060             // Initially ignore wildcards.
  1061             wildcards = 1;
  1062             goto eol;
  1063         }
  1064 
  1065         // Collect the recipients.  Note: we must return the primary
  1066         // key's fingerprint.
  1067         pgp_cert_t cert = NULL;
  1068         int is_tsk = 0;
  1069         if (cert_find_by_keyid(session, keyid, false, &cert, &is_tsk) != PEP_STATUS_OK)
  1070             goto eol;
  1071 
  1072         pgp_fingerprint_t fp = pgp_cert_fingerprint(cert);
  1073         char *fp_string = pgp_fingerprint_to_hex(fp);
  1074         stringlist_add_unique(cookie->recipient_keylist, fp_string);
  1075         free(fp_string);
  1076         pgp_fingerprint_free(fp);
  1077 
  1078         if (cookie->decrypted)
  1079             goto eol;
  1080 
  1081         // See if we have the secret key.
  1082         assert(is_tsk == pgp_cert_is_tsk(cert));
  1083         if (! is_tsk)
  1084             goto eol;
  1085 
  1086         key_iter = pgp_cert_key_iter(cert);
  1087         while (key = NULL, (ka = pgp_cert_key_iter_next(key_iter))) {
  1088             key = pgp_key_amalgamation_key (ka);
  1089             pgp_keyid_t this_keyid = pgp_key_keyid(key);
  1090             char *this_keyid_hex = pgp_keyid_to_hex(this_keyid);
  1091             pgp_keyid_free(this_keyid);
  1092 
  1093             int match = strcmp(keyid_str, this_keyid_hex) == 0;
  1094             free(this_keyid_hex);
  1095             if (match)
  1096                 break;
  1097 
  1098             pgp_key_free (key);
  1099             pgp_key_amalgamation_free (ka);
  1100         }
  1101 
  1102         if (key == NULL) {
  1103             assert(!"Inconsistent DB: key doesn't contain a subkey with keyid!");
  1104             goto eol;
  1105         }
  1106 
  1107         uint8_t algo;
  1108         uint8_t session_key[1024];
  1109         size_t session_key_len = sizeof(session_key);
  1110         if (pgp_pkesk_decrypt(&err, pkesk, key, &algo,
  1111                               session_key, &session_key_len) != 0) {
  1112             DUMP_ERR(err, PEP_UNKNOWN_ERROR, "pgp_pkesk_decrypt");
  1113             goto eol;
  1114         }
  1115 
  1116         sk = pgp_session_key_from_bytes (session_key, session_key_len);
  1117         pgp_status_t status;
  1118         if ((status = decrypt (decrypt_cookie, algo, sk))) {
  1119             DUMP_STATUS(status, PEP_UNKNOWN_ERROR, "decrypt_cb");
  1120             goto eol;
  1121         }
  1122 
  1123         T("Decrypted PKESK for %s", keyid_str);
  1124 
  1125         *identity_out = pgp_cert_fingerprint(cert);
  1126         cookie->decrypted = 1;
  1127 
  1128     eol:
  1129         pgp_session_key_free (sk);
  1130         free(keyid_str);
  1131         pgp_key_free (key);
  1132         pgp_key_amalgamation_free (ka);
  1133         pgp_cert_key_iter_free(key_iter);
  1134         pgp_cert_free(cert);
  1135     }
  1136 
  1137     // Consider wildcard recipients.
  1138     if (wildcards) for (size_t i = 0; i < pkesk_count && !cookie->decrypted; i ++) {
  1139         pgp_pkesk_t pkesk = pkesks[i];
  1140         pgp_keyid_t keyid = pgp_pkesk_recipient(pkesk); /* Reference. */
  1141         char *keyid_str = pgp_keyid_to_hex(keyid);
  1142         pgp_cert_key_iter_t key_iter = NULL;
  1143         pgp_key_amalgamation_t ka = NULL;
  1144         pgp_key_t key = NULL;
  1145         pgp_session_key_t sk = NULL;
  1146 
  1147         if (strcmp(keyid_str, "0000000000000000") != 0)
  1148             goto eol2;
  1149 
  1150         if (!tsks) {
  1151             if (cert_all(session, true, &tsks, &tsks_count) != PEP_STATUS_OK) {
  1152                 DUMP_ERR(NULL, PEP_UNKNOWN_ERROR, "Getting all tsks");
  1153             }
  1154         }
  1155 
  1156         for (int j = 0; j < tsks_count; j ++) {
  1157             pgp_cert_t tsk = tsks[j];
  1158 
  1159             key_iter = pgp_cert_key_iter(tsk);
  1160 
  1161             while (key = NULL, (ka = pgp_cert_key_iter_next(key_iter))) {
  1162                 key = pgp_key_amalgamation_key (ka);
  1163 
  1164                 // Note: for decryption to appear to succeed, we must
  1165                 // get a valid algorithm (8 of 256 values) and a
  1166                 // 16-bit checksum must match.  Thus, we have about a
  1167                 // 1 in 2**21 chance of having a false positive here.
  1168                 uint8_t algo;
  1169                 uint8_t session_key[1024];
  1170                 size_t session_key_len = sizeof(session_key);
  1171                 if (pgp_pkesk_decrypt(&err, pkesk, key,
  1172                                       &algo, session_key, &session_key_len)) {
  1173                     pgp_error_free(err);
  1174                     err = NULL;
  1175                     pgp_key_free (key);
  1176                     pgp_key_amalgamation_free (ka);
  1177                     continue;
  1178                 }
  1179 
  1180                 // Add it to the recipient list.
  1181                 pgp_fingerprint_t fp = pgp_cert_fingerprint(tsk);
  1182                 char *fp_string = pgp_fingerprint_to_hex(fp);
  1183                 T("wildcard recipient appears to be %s", fp_string);
  1184                 stringlist_add_unique(cookie->recipient_keylist, fp_string);
  1185                 free(fp_string);
  1186                 pgp_fingerprint_free(fp);
  1187 
  1188                 pgp_session_key_t sk = pgp_session_key_from_bytes (session_key,
  1189                                                                    session_key_len);
  1190                 pgp_status_t status;
  1191                 if ((status = decrypt (decrypt_cookie, algo, sk))) {
  1192                     DUMP_STATUS(status, PEP_UNKNOWN_ERROR, "decrypt_cb");
  1193                     goto eol2;
  1194                 }
  1195 
  1196                 *identity_out = pgp_cert_fingerprint(tsk);
  1197                 cookie->decrypted = 1;
  1198 
  1199                 break;
  1200             }
  1201 
  1202             pgp_key_free (key);
  1203             key = NULL;
  1204             pgp_key_amalgamation_free (ka);
  1205             ka = NULL;
  1206             pgp_cert_key_iter_free(key_iter);
  1207             key_iter = NULL;
  1208         }
  1209     eol2:
  1210         pgp_session_key_free (sk);
  1211         free(keyid_str);
  1212         pgp_key_free (key);
  1213         pgp_key_amalgamation_free (ka);
  1214         pgp_cert_key_iter_free(key_iter);
  1215     }
  1216 
  1217     if (tsks) {
  1218         for (int i = 0; i < tsks_count; i ++)
  1219             pgp_cert_free(tsks[i]);
  1220         free(tsks);
  1221     }
  1222 
  1223     return cookie->decrypted ? PGP_STATUS_SUCCESS : PGP_STATUS_UNKNOWN_ERROR;
  1224 }
  1225 
  1226 static pgp_status_t
  1227 check_signatures_cb(void *cookie_opaque, pgp_message_structure_t structure)
  1228 {
  1229     struct decrypt_cookie *cookie = cookie_opaque;
  1230 
  1231     pgp_message_structure_iter_t iter
  1232         = pgp_message_structure_iter (structure);
  1233     for (pgp_message_layer_t layer = pgp_message_structure_iter_next (iter);
  1234          layer;
  1235          layer = pgp_message_structure_iter_next (iter)) {
  1236         pgp_verification_result_iter_t results;
  1237 
  1238         switch (pgp_message_layer_variant (layer)) {
  1239         case PGP_MESSAGE_LAYER_COMPRESSION:
  1240         case PGP_MESSAGE_LAYER_ENCRYPTION:
  1241             break;
  1242 
  1243         case PGP_MESSAGE_LAYER_SIGNATURE_GROUP:
  1244             pgp_message_layer_signature_group(layer, &results);
  1245             pgp_verification_result_t result;
  1246             while ((result = pgp_verification_result_iter_next (results))) {
  1247                 pgp_signature_t sig = NULL;
  1248                 pgp_keyid_t keyid = NULL;
  1249                 char *keyid_str = NULL;
  1250                 pgp_error_t error = NULL;
  1251                 char *error_str = NULL;
  1252 
  1253                 switch (pgp_verification_result_variant (result)) {
  1254                 case PGP_VERIFICATION_RESULT_GOOD_CHECKSUM: {
  1255                     // We need to add the fingerprint of the primary
  1256                     // key to cookie->signer_keylist.
  1257 
  1258                     pgp_cert_t cert = NULL;
  1259                     pgp_verification_result_good_checksum (result, &sig,
  1260                                                            &cert,
  1261                                                            NULL, // key
  1262                                                            NULL, // binding
  1263                                                            NULL); // revocation
  1264 
  1265                     // We need the primary key's fingerprint.
  1266                     pgp_fingerprint_t primary_fpr
  1267                         = pgp_cert_fingerprint(cert);
  1268                     char *primary_fpr_str
  1269                         = pgp_fingerprint_to_hex(primary_fpr);
  1270 
  1271                     stringlist_add_unique(cookie->signer_keylist,
  1272                                           primary_fpr_str);
  1273 
  1274                     T("Good signature from %s", primary_fpr_str);
  1275 
  1276                     free (primary_fpr_str);
  1277                     pgp_fingerprint_free (primary_fpr);
  1278                     pgp_cert_free (cert);
  1279 
  1280                     cookie->good_checksums ++;
  1281                     break;
  1282                 }
  1283 
  1284                 case PGP_VERIFICATION_RESULT_MALFORMED_SIGNATURE:
  1285                     if (TRACING) {
  1286                         pgp_verification_result_malformed_signature (result,
  1287                                                                      &sig,
  1288                                                                      &error);
  1289 
  1290                         error_str = pgp_error_to_string(error);
  1291                         keyid = pgp_signature_issuer (sig);
  1292                         keyid_str = pgp_keyid_to_string (keyid);
  1293                         T("Malformed signature from %s: %s",
  1294                           keyid_str, error_str);
  1295                     }
  1296 
  1297                     cookie->malformed_signature ++;
  1298                     break;
  1299 
  1300                 case PGP_VERIFICATION_RESULT_MISSING_KEY:
  1301                     if (TRACING) {
  1302                         pgp_verification_result_missing_key (result, &sig);
  1303                         keyid = pgp_signature_issuer (sig);
  1304                         keyid_str = pgp_keyid_to_string (keyid);
  1305                         T("No key to check signature from %s", keyid_str);
  1306                     }
  1307 
  1308                     cookie->missing_keys ++;
  1309                     break;
  1310 
  1311                 case PGP_VERIFICATION_RESULT_UNBOUND_KEY:
  1312                     // This happens if the key doesn't have a binding
  1313                     // signature.
  1314 
  1315                     if (TRACING) {
  1316                         pgp_verification_result_unbound_key (result,
  1317                                                              &sig,
  1318                                                              NULL,
  1319                                                              &error);
  1320 
  1321                         error_str = pgp_error_to_string(error);
  1322                         keyid = pgp_signature_issuer (sig);
  1323                         keyid_str = pgp_keyid_to_string (keyid);
  1324                         T("key %s has no valid self-signature: %s",
  1325                           keyid_str ? keyid_str : "(missing issuer)",
  1326                           error_str);
  1327                     }
  1328 
  1329                     cookie->unbound_key ++;
  1330                     break;
  1331 
  1332                 case PGP_VERIFICATION_RESULT_BAD_KEY: {
  1333                     // This happens if the certificate is not alive or
  1334                     // revoked, if the key is not alive or revoked, of
  1335                     // if the key is not signing capable.
  1336 
  1337                     pgp_cert_t cert = NULL;
  1338                     pgp_key_t key = NULL;
  1339                     pgp_signature_t selfsig = NULL;
  1340                     pgp_revocation_status_t rs = NULL;
  1341 
  1342                     pgp_verification_result_bad_key (result,
  1343                                                      &sig,
  1344                                                      &cert, // cert
  1345                                                      &key, // key
  1346                                                      &selfsig, // binding
  1347                                                      &rs, // key revocation
  1348                                                      &error);
  1349 
  1350                     if (TRACING) {
  1351                         error_str = pgp_error_to_string(error);
  1352                         keyid = pgp_signature_issuer (sig);
  1353                         keyid_str = pgp_keyid_to_string (keyid);
  1354                         T("key %s is bad: %s",
  1355                           keyid_str ? keyid_str : "(missing issuer)",
  1356                           error_str);
  1357                     }
  1358 
  1359                     // Check if the key or certificate is revoked.
  1360                     if (pgp_revocation_status_variant(rs)
  1361                         == PGP_REVOCATION_STATUS_REVOKED) {
  1362                         // Key is revoked.
  1363                         cookie->revoked_key ++;
  1364                     } else {
  1365                         pgp_revocation_status_free (rs);
  1366                         rs = pgp_cert_revoked (cert, cookie->session->policy, 0);
  1367                         if (pgp_revocation_status_variant(rs)
  1368                             == PGP_REVOCATION_STATUS_REVOKED) {
  1369                             // Cert is revoked.
  1370                             cookie->revoked_key ++;
  1371                         }
  1372                         // Check if the key or certificate is expired.
  1373                         else if (pgp_cert_alive(NULL, cert,
  1374                                                 cookie->session->policy, 0)
  1375                                  != PGP_STATUS_SUCCESS) {
  1376                             // Certificate is expired.
  1377                             cookie->expired_key ++;
  1378                             goto out;
  1379                         } else if (pgp_signature_key_alive (NULL, selfsig, key, 0)
  1380                                    != PGP_STATUS_SUCCESS) {
  1381                             // Key is expired.
  1382                             cookie->expired_key ++;
  1383                             goto out;
  1384                         }
  1385                         // Wrong key flags or something similar.
  1386                         else {
  1387                             cookie->bad_key ++;
  1388                         }
  1389                     }
  1390 
  1391                 out:
  1392                     pgp_revocation_status_free (rs);
  1393                     pgp_signature_free (selfsig);
  1394                     pgp_key_free (key);
  1395                     pgp_cert_free (cert);
  1396 
  1397                     break;
  1398                 }
  1399 
  1400                 case PGP_VERIFICATION_RESULT_BAD_SIGNATURE:
  1401                     if (TRACING) {
  1402                         pgp_verification_result_bad_signature
  1403                             (result, &sig, NULL, NULL, NULL, NULL, &error);
  1404                         error_str = pgp_error_to_string(error);
  1405                         keyid = pgp_signature_issuer (sig);
  1406                         if (keyid) {
  1407                             keyid_str = pgp_keyid_to_string (keyid);
  1408                             T("Bad signature from %s: %s",
  1409                               keyid_str, error_str);
  1410                         } else {
  1411                             T("Bad signature without issuer information: %s",
  1412                               error_str);
  1413                         }
  1414                     }
  1415 
  1416                     cookie->bad_checksums ++;
  1417                     break;
  1418 
  1419                 default:
  1420                     assert (! "reachable");
  1421                 }
  1422 
  1423                 free (keyid_str);
  1424                 pgp_signature_free (sig);
  1425                 free (error_str);
  1426                 pgp_error_free (error);
  1427                 pgp_verification_result_free (result);
  1428             }
  1429             pgp_verification_result_iter_free (results);
  1430             break;
  1431 
  1432         default:
  1433             assert (! "reachable");
  1434         }
  1435 
  1436         pgp_message_layer_free (layer);
  1437     }
  1438 
  1439     pgp_message_structure_iter_free (iter);
  1440     pgp_message_structure_free (structure);
  1441 
  1442     return PGP_STATUS_SUCCESS;
  1443 }
  1444 
  1445 static pgp_status_t inspect_cb(
  1446     void *cookie_opaque, pgp_packet_parser_t pp)
  1447 {
  1448     struct decrypt_cookie *cookie = cookie_opaque;
  1449 
  1450     pgp_packet_t packet = pgp_packet_parser_packet(pp);
  1451     assert(packet);
  1452 
  1453     pgp_tag_t tag = pgp_packet_tag(packet);
  1454 
  1455     T("%s", pgp_tag_to_string(tag));
  1456 
  1457     if (tag == PGP_TAG_LITERAL) {
  1458         pgp_literal_t literal = pgp_packet_ref_literal(packet);
  1459         cookie->filename = pgp_literal_filename(literal);
  1460         pgp_literal_free(literal);
  1461     }
  1462 
  1463     pgp_packet_free(packet);
  1464 
  1465     return 0;
  1466 }
  1467 
  1468 PEP_STATUS pgp_decrypt_and_verify(
  1469     PEP_SESSION session, const char *ctext, size_t csize,
  1470     const char *dsigtext, size_t dsigsize,
  1471     char **ptext, size_t *psize, stringlist_t **keylist,
  1472     char** filename_ptr)
  1473 {
  1474     PEP_STATUS status = PEP_STATUS_OK;
  1475     struct decrypt_cookie cookie = { session, 0, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL };
  1476     pgp_reader_t reader = NULL;
  1477     pgp_writer_t writer = NULL;
  1478     pgp_reader_t decryptor = NULL;
  1479     *ptext = NULL;
  1480     *psize = 0;
  1481 
  1482     // XXX: We don't yet handle detached signatures over encrypted
  1483     // messages.
  1484     assert(!dsigtext);
  1485 
  1486     cookie.recipient_keylist = new_stringlist(NULL);
  1487     if (!cookie.recipient_keylist)
  1488         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "recipient_keylist");
  1489 
  1490     cookie.signer_keylist = new_stringlist(NULL);
  1491     if (!cookie.signer_keylist)
  1492         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "signer_keylist");
  1493 
  1494     reader = pgp_reader_from_bytes((const uint8_t *) ctext, csize);
  1495     if (! reader)
  1496         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "Creating reader");
  1497 
  1498     writer = pgp_writer_alloc((void **) ptext, psize);
  1499     if (! writer)
  1500         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR, "Creating writer");
  1501 
  1502     pgp_error_t err = NULL;
  1503     decryptor = pgp_decryptor_new(&err, session->policy, reader,
  1504                                   get_public_keys_cb, decrypt_cb,
  1505                                   check_signatures_cb, inspect_cb,
  1506                                   &cookie, 0);
  1507     if (! decryptor)
  1508         ERROR_OUT(err, PEP_DECRYPT_NO_KEY, "pgp_decryptor_new");
  1509 
  1510     // Copy 128 MB at a time.
  1511     ssize_t nread;
  1512     while ((nread = pgp_reader_copy (&err, decryptor, writer,
  1513                                      128 * 1024 * 1024) > 0))
  1514         ;
  1515     if (nread < 0)
  1516         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "pgp_reader_read");
  1517 
  1518     // Add a terminating NUL for naive users
  1519     pgp_writer_write(&err, writer, (const uint8_t *) &""[0], 1);
  1520 
  1521     if (! cookie.decrypted)
  1522         ERROR_OUT(err, PEP_DECRYPT_NO_KEY, "Decryption failed");
  1523 
  1524     if (! cookie.signer_keylist) {
  1525         cookie.signer_keylist = new_stringlist("");
  1526         if (! cookie.signer_keylist)
  1527             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "cookie.signer_keylist");
  1528     }
  1529     if (!cookie.signer_keylist->value)
  1530         stringlist_add(cookie.signer_keylist, "");
  1531 
  1532     *keylist = cookie.signer_keylist;
  1533     stringlist_append(*keylist, cookie.recipient_keylist);
  1534 
  1535     if (filename_ptr)
  1536         *filename_ptr = cookie.filename;
  1537 
  1538  out:
  1539     if (status == PEP_STATUS_OK) {
  1540         // **********************************
  1541         // Sync changes with pgp_verify_text.
  1542         // **********************************
  1543 
  1544         if (cookie.good_checksums) {
  1545             // If there is at least one signature that we can verify,
  1546             // succeed.
  1547             status = PEP_DECRYPTED_AND_VERIFIED;
  1548         } else if (cookie.revoked_key) {
  1549             // If there are any signatures from revoked keys, fail.
  1550             status = PEP_VERIFY_SIGNER_KEY_REVOKED;
  1551         } else if (cookie.expired_key) {
  1552             // If there are any signatures from expired keys, fail.
  1553             status = PEP_DECRYPTED;
  1554         } else if (cookie.bad_key) {
  1555             // If there are any signatures from invalid keys (keys
  1556             // that are not signing capable), fail.
  1557             status = PEP_DECRYPTED;
  1558         } else if (cookie.bad_checksums) {
  1559             // If there are any bad signatures, fail.
  1560             status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  1561         } else {
  1562             // We couldn't verify any signatures (possibly because we
  1563             // don't have the keys).
  1564             status = PEP_DECRYPTED;
  1565         }
  1566     } else {
  1567         free_stringlist(cookie.recipient_keylist);
  1568         free_stringlist(cookie.signer_keylist);
  1569         free(cookie.filename);
  1570         free(*ptext);
  1571     }
  1572 
  1573     pgp_reader_free(reader);
  1574     pgp_reader_free(decryptor);
  1575     pgp_writer_free(writer);
  1576 
  1577     T("-> %s", pEp_status_to_string(status));
  1578     return status;
  1579 }
  1580 
  1581 PEP_STATUS pgp_verify_text(
  1582     PEP_SESSION session, const char *text, size_t size,
  1583     const char *signature, size_t sig_size, stringlist_t **keylist)
  1584 {
  1585     PEP_STATUS status = PEP_STATUS_OK;
  1586     pgp_error_t err = NULL;
  1587     struct decrypt_cookie cookie = { session, 0, NULL, NULL, 0, 0, 0, };
  1588     pgp_reader_t reader = NULL;
  1589     pgp_reader_t dsig_reader = NULL;
  1590     pgp_reader_t verifier = NULL;
  1591 
  1592     if (size == 0 || sig_size == 0)
  1593         return PEP_DECRYPT_WRONG_FORMAT;
  1594 
  1595 #if TRACING > 0
  1596     {
  1597         int cr = 0;
  1598         int crlf = 0;
  1599         int lf = 0;
  1600 
  1601         for (int i = 0; i < size; i ++) {
  1602             // CR
  1603             if (text[i] == '\r') {
  1604                 cr ++;
  1605             }
  1606             // LF
  1607             if (text[i] == '\n') {
  1608                 if (i > 0 && text[i - 1] == '\r') {
  1609                     cr --;
  1610                     crlf ++;
  1611                 } else {
  1612                     lf ++;
  1613                 }
  1614             }
  1615         }
  1616 
  1617         T("Text to verify: %zd bytes with %d crlfs, %d bare crs and %d bare lfs",
  1618           size, crlf, cr, lf);
  1619     }
  1620 #endif
  1621 
  1622     cookie.recipient_keylist = new_stringlist(NULL);
  1623     if (!cookie.recipient_keylist)
  1624         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1625 
  1626     cookie.signer_keylist = new_stringlist(NULL);
  1627     if (!cookie.signer_keylist)
  1628         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1629 
  1630     reader = pgp_reader_from_bytes((const uint8_t *) text, size);
  1631     if (! reader)
  1632         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "Creating reader");
  1633 
  1634     dsig_reader = NULL;
  1635     if (signature) {
  1636         dsig_reader = pgp_reader_from_bytes((uint8_t *) signature, sig_size);
  1637         if (! dsig_reader)
  1638             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "Creating signature reader");
  1639     }
  1640 
  1641     if (dsig_reader)
  1642         verifier = pgp_detached_verifier_new(&err, session->policy,
  1643                                              dsig_reader, reader,
  1644                                              get_public_keys_cb,
  1645                                              check_signatures_cb,
  1646                                              &cookie, 0);
  1647     else
  1648         verifier = pgp_verifier_new(&err, session->policy, reader,
  1649                                     get_public_keys_cb,
  1650                                     check_signatures_cb,
  1651                                     &cookie, 0);
  1652     if (! verifier)
  1653         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Creating verifier");
  1654     if (pgp_reader_discard(&err, verifier) < 0)
  1655         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "verifier");
  1656 
  1657     if (! cookie.signer_keylist) {
  1658         cookie.signer_keylist = new_stringlist("");
  1659         if (! cookie.signer_keylist)
  1660             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "cookie.signer_keylist");
  1661     }
  1662     if (!cookie.signer_keylist->value)
  1663         stringlist_add(cookie.signer_keylist, "");
  1664 
  1665     *keylist = cookie.signer_keylist;
  1666     stringlist_append(*keylist, cookie.recipient_keylist);
  1667 
  1668  out:
  1669     if (status == PEP_STATUS_OK) {
  1670         // *****************************************
  1671         // Sync changes with pgp_decrypt_and_verify.
  1672         // *****************************************
  1673 
  1674         if (cookie.good_checksums) {
  1675             // If there is at least one signature that we can verify,
  1676             // succeed.
  1677             status = PEP_VERIFIED;
  1678         } else if (cookie.revoked_key) {
  1679             // If there are any signatures from revoked keys, fail.
  1680             status = PEP_VERIFY_SIGNER_KEY_REVOKED;
  1681         } else if (cookie.expired_key) {
  1682             // If there are any signatures from expired keys, fail.
  1683             status = PEP_DECRYPTED;
  1684         } else if (cookie.bad_key) {
  1685             // If there are any signatures from invalid keys (keys
  1686             // that are not signing capable), fail.
  1687             status = PEP_DECRYPTED;
  1688         } else if (cookie.bad_checksums) {
  1689             // If there are any bad signatures, fail.
  1690             status = PEP_DECRYPT_SIGNATURE_DOES_NOT_MATCH;
  1691         } else {
  1692             // We couldn't verify any signatures (possibly because we
  1693             // don't have the keys).
  1694             status = PEP_UNENCRYPTED;
  1695         }
  1696     } else {
  1697         free_stringlist(cookie.recipient_keylist);
  1698         free_stringlist(cookie.signer_keylist);
  1699     }
  1700 
  1701     pgp_reader_free(verifier);
  1702     pgp_reader_free(reader);
  1703     pgp_reader_free(dsig_reader);
  1704 
  1705     T("-> %s", pEp_status_to_string(status));
  1706     return status;
  1707 }
  1708 
  1709 
  1710 PEP_STATUS pgp_sign_only(
  1711     PEP_SESSION session, const char* fpr, const char *ptext,
  1712     size_t psize, char **stext, size_t *ssize)
  1713 {
  1714     assert(session);
  1715     assert(fpr && fpr[0]);
  1716     assert(ptext);
  1717     assert(psize);
  1718     assert(stext);
  1719     assert(ssize);
  1720     *stext = NULL;
  1721     *ssize = 0;
  1722 
  1723     PEP_STATUS status = PEP_STATUS_OK;
  1724     pgp_error_t err = NULL;
  1725     pgp_cert_t signer_cert = NULL;
  1726     pgp_cert_valid_key_iter_t iter = NULL;
  1727     pgp_valid_key_amalgamation_t ka = NULL;
  1728     pgp_key_pair_t signing_keypair = NULL;
  1729     pgp_signer_t signer = NULL;
  1730     pgp_writer_stack_t ws = NULL;
  1731 
  1732     status = cert_find_by_fpr_hex(session, fpr, true, &signer_cert, NULL);
  1733     ERROR_OUT(NULL, status, "Looking up key '%s'", fpr);
  1734 
  1735     iter = pgp_cert_valid_key_iter(signer_cert, session->policy, 0);
  1736     pgp_cert_valid_key_iter_alive(iter);
  1737     pgp_cert_valid_key_iter_revoked(iter, false);
  1738     pgp_cert_valid_key_iter_for_signing (iter);
  1739     pgp_cert_valid_key_iter_unencrypted_secret (iter);
  1740 
  1741     // If there are multiple signing capable subkeys, we just take
  1742     // the first one, whichever one that happens to be.
  1743     ka = pgp_cert_valid_key_iter_next (iter, NULL, NULL);
  1744     if (! ka)
  1745         ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  1746                    "%s has no signing capable key", fpr);
  1747 
  1748     // pgp_key_into_key_pair needs to own the key, but here we
  1749     // only get a reference (which we still need to free).
  1750     pgp_key_t key = pgp_valid_key_amalgamation_key (ka);
  1751     signing_keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  1752     pgp_key_free (key);
  1753     if (! signing_keypair)
  1754         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  1755 
  1756     signer = pgp_key_pair_as_signer (signing_keypair);
  1757     if (! signer)
  1758         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  1759 
  1760 
  1761     pgp_writer_t writer = pgp_writer_alloc((void **) stext, ssize);
  1762     writer = pgp_armor_writer_new(&err, writer,
  1763                                   PGP_ARMOR_KIND_MESSAGE, NULL, 0);
  1764     if (!writer)
  1765         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up armor writer");
  1766 
  1767     ws = pgp_writer_stack_message(writer);
  1768 
  1769     ws = pgp_signer_new_detached(&err, ws, &signer, 1, 0);
  1770     if (!ws)
  1771         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up signer");
  1772     // pgp_signer_new_detached consumes signer.
  1773     signer = NULL;
  1774 
  1775     pgp_status_t write_status =
  1776         pgp_writer_stack_write_all (&err, ws,
  1777                                     (uint8_t *) ptext, psize);
  1778     if (write_status != 0)
  1779         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Encrypting message");
  1780 
  1781     pgp_status_t pgp_status = pgp_writer_stack_finalize (&err, ws);
  1782     ws = NULL;
  1783     if (pgp_status != 0)
  1784         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Flushing writer");
  1785 
  1786     pgp_status = pgp_armor_writer_finalize (&err, writer);
  1787     if (pgp_status != 0)
  1788         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Flushing armor writer");
  1789 
  1790     // Add a terminating NUL for naive users
  1791     void *t = realloc(*stext, *ssize + 1);
  1792     if (! t)
  1793         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1794     *stext = t;
  1795     (*stext)[*ssize] = 0;
  1796 
  1797  out:
  1798     pgp_signer_free (signer);
  1799     // XXX: pgp_key_pair_as_signer is only supposed to reference
  1800     // signing_keypair, but it consumes it.  If this is fixed, this
  1801     // will become a leak.
  1802     //
  1803     //pgp_key_pair_free (signing_keypair);
  1804     pgp_valid_key_amalgamation_free (ka);
  1805     pgp_cert_valid_key_iter_free (iter);
  1806     pgp_cert_free(signer_cert);
  1807 
  1808     T("(%s)-> %s", fpr, pEp_status_to_string(status));
  1809     return status;
  1810 }
  1811 
  1812 static PEP_STATUS pgp_encrypt_sign_optional(
  1813     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1814     size_t psize, char **ctext, size_t *csize, bool sign)
  1815 {
  1816     PEP_STATUS status = PEP_STATUS_OK;
  1817     pgp_error_t err = NULL;
  1818 
  1819     int recipient_cert_count = 0;
  1820     pgp_cert_t *recipient_certs = NULL;
  1821 
  1822     int recipient_count = 0;
  1823     int recipient_alloc = 0;
  1824     pgp_recipient_t *recipients = NULL;
  1825     int recipient_keys_count = 0;
  1826     pgp_key_t *recipient_keys = NULL;
  1827 
  1828     pgp_cert_t signer_cert = NULL;
  1829     pgp_writer_stack_t ws = NULL;
  1830     pgp_cert_valid_key_iter_t iter = NULL;
  1831     pgp_valid_key_amalgamation_t ka = NULL;
  1832     pgp_key_pair_t signing_keypair = NULL;
  1833     pgp_signer_t signer = NULL;
  1834 
  1835     assert(session);
  1836     assert(keylist);
  1837     assert(ptext);
  1838     assert(psize);
  1839     assert(ctext);
  1840     assert(csize);
  1841 
  1842     *ctext = NULL;
  1843     *csize = 0;
  1844 
  1845     int keylist_len = stringlist_length(keylist);
  1846 
  1847     // We don't need to worry about extending recipient_certs, because
  1848     // there will be at most KEYLIST_LEN certs, which we allocate up
  1849     // front.
  1850     recipient_certs = calloc(keylist_len, sizeof(*recipient_certs));
  1851     if (recipient_certs == NULL)
  1852         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1853 
  1854     // Because there may be multiple encryption keys per certificate, we may
  1855     // need to extend recipient_keys and recipients.
  1856     recipient_alloc = keylist_len;
  1857     recipient_keys = calloc(recipient_alloc, sizeof(*recipient_keys));
  1858     if (recipient_keys == NULL)
  1859         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1860 
  1861     recipients = calloc(recipient_alloc, sizeof(*recipients));
  1862     if (recipients == NULL)
  1863         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1864 
  1865 
  1866     // Get the keys for the recipients.
  1867     const stringlist_t *_keylist;
  1868     for (_keylist = keylist; _keylist != NULL; _keylist = _keylist->next) {
  1869         assert(_keylist->value);
  1870 
  1871         pgp_cert_t cert;
  1872         status = cert_find_by_fpr_hex(session, _keylist->value,
  1873                                      false, &cert, NULL);
  1874         // We couldn't find a key for this recipient.
  1875         ERROR_OUT(NULL, status,
  1876                   "Looking up key for recipient '%s'", _keylist->value);
  1877 
  1878         recipient_certs[recipient_cert_count ++] = cert;
  1879 
  1880         // Collect all of the keys that have the encryption for
  1881         // transport capability.
  1882         iter = pgp_cert_valid_key_iter(cert, session->policy, 0);
  1883         if (! iter)
  1884             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1885         pgp_cert_valid_key_iter_alive(iter);
  1886         pgp_cert_valid_key_iter_revoked(iter, false);
  1887         pgp_cert_valid_key_iter_for_transport_encryption(iter);
  1888 
  1889         while ((ka = pgp_cert_valid_key_iter_next (iter, NULL, NULL))) {
  1890             assert(recipient_count == recipient_keys_count);
  1891             if (recipient_count == recipient_alloc) {
  1892                 assert(recipient_alloc > 0);
  1893                 recipient_alloc *= 2;
  1894 
  1895                 void *t = _pEp_reallocarray(recipient_keys, recipient_alloc,
  1896                                             sizeof(*recipient_keys));
  1897                 if (! t)
  1898                     ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1899                 recipient_keys = t;
  1900 
  1901                 t = _pEp_reallocarray(recipients, recipient_alloc,
  1902                                       sizeof(*recipients));
  1903                 if (! t)
  1904                     ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1905                 recipients = t;
  1906             }
  1907 
  1908             // pgp_valid_key_amalgamation_key returns a reference to
  1909             // ka.  We need to keep it around after this iteration.
  1910             // So, we clone it.  Unfortunately, although
  1911             // pgp_recipient_new consumes the passed key id, it only
  1912             // references the key.  So, we need to remember to free it
  1913             // at the end.
  1914             pgp_key_t key = pgp_valid_key_amalgamation_key (ka);
  1915             recipient_keys[recipient_keys_count ++] = pgp_key_clone (key);
  1916             pgp_key_free (key);
  1917 
  1918             pgp_keyid_t keyid = pgp_key_keyid(recipient_keys[recipient_keys_count - 1]);
  1919             if (! keyid)
  1920                 ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  1921 
  1922             recipients[recipient_count++] = pgp_recipient_new(keyid, recipient_keys[recipient_keys_count - 1]);
  1923 
  1924             pgp_valid_key_amalgamation_free (ka);
  1925         }
  1926         pgp_cert_valid_key_iter_free(iter);
  1927         iter = NULL;
  1928     }
  1929 
  1930     if (sign) {
  1931         // The first key in the keylist is the signer.
  1932         status = cert_find_by_fpr_hex(session, keylist->value, true, &signer_cert, NULL);
  1933         ERROR_OUT(NULL, status, "Looking up key for signing '%s'", keylist->value);
  1934     }
  1935 
  1936     pgp_writer_t writer_alloc = pgp_writer_alloc((void **) ctext, csize);
  1937     pgp_writer_t writer = pgp_armor_writer_new(&err, writer_alloc,
  1938                                   PGP_ARMOR_KIND_MESSAGE, NULL, 0);
  1939     if (!writer)
  1940         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up armor writer");
  1941 
  1942     ws = pgp_writer_stack_message(writer);
  1943     ws = pgp_encryptor_new (&err, ws,
  1944                             NULL, 0, recipients, recipient_count,
  1945                             0, 0);
  1946     if (!ws)
  1947         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up encryptor");
  1948 
  1949     // pgp_encrypt_new consumes the recipients (but not the keys).
  1950     recipient_count = 0;
  1951 
  1952     if (sign) {
  1953         iter = pgp_cert_valid_key_iter(signer_cert, session->policy, 0);
  1954         pgp_cert_valid_key_iter_alive(iter);
  1955         pgp_cert_valid_key_iter_revoked(iter, false);
  1956         pgp_cert_valid_key_iter_for_signing (iter);
  1957         pgp_cert_valid_key_iter_unencrypted_secret (iter);
  1958 
  1959         // If there are multiple signing capable subkeys, we just take
  1960         // the first one, whichever one that happens to be.
  1961         ka = pgp_cert_valid_key_iter_next (iter, NULL, NULL);
  1962         if (! ka)
  1963             ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  1964                        "%s has no signing capable key", keylist->value);
  1965 
  1966         // pgp_key_into_key_pair needs to own the key, but here we
  1967         // only get a reference (which we still need to free).
  1968         pgp_key_t key = pgp_valid_key_amalgamation_key (ka);
  1969         signing_keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  1970         pgp_key_free (key);
  1971         if (! signing_keypair)
  1972             ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  1973 
  1974         signer = pgp_key_pair_as_signer (signing_keypair);
  1975         if (! signer)
  1976             ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  1977 
  1978         ws = pgp_signer_new(&err, ws, &signer, 1, 0);
  1979         if (!ws)
  1980             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up signer");
  1981         // pgp_signer_new consumes signer.
  1982         signer = NULL;
  1983     }
  1984 
  1985     ws = pgp_literal_writer_new (&err, ws);
  1986     if (!ws)
  1987         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Setting up literal writer");
  1988 
  1989     pgp_status_t write_status =
  1990         pgp_writer_stack_write_all (&err, ws,
  1991                                     (uint8_t *) ptext, psize);
  1992     if (write_status != 0)
  1993         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Encrypting message");
  1994 
  1995     pgp_status_t pgp_status = pgp_writer_stack_finalize (&err, ws);
  1996     ws = NULL;
  1997     if (pgp_status != 0)
  1998         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Flushing writer");
  1999 
  2000     pgp_status = pgp_armor_writer_finalize (&err, writer);
  2001     if (pgp_status != 0)
  2002         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Flushing armor writer");
  2003 
  2004     pgp_writer_free (writer_alloc);
  2005 
  2006     // Add a terminating NUL for naive users
  2007     void *t = realloc(*ctext, *csize + 1);
  2008     if (! t) {
  2009         free(*ctext);
  2010         *ctext = NULL;
  2011         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  2012     }
  2013     *ctext = t;
  2014     (*ctext)[*csize] = 0;
  2015 
  2016  out:
  2017     pgp_signer_free (signer);
  2018     // XXX: pgp_key_pair_as_signer is only supposed to reference
  2019     // signing_keypair, but it consumes it.  If this is fixed, this
  2020     // will become a leak.
  2021     //
  2022     // pgp_key_pair_free (signing_keypair);
  2023     pgp_valid_key_amalgamation_free (ka);
  2024     pgp_cert_valid_key_iter_free (iter);
  2025     pgp_cert_free(signer_cert);
  2026 
  2027     for (int i = 0; i < recipient_count; i ++)
  2028         pgp_recipient_free(recipients[i]);
  2029     free(recipients);
  2030     for (int i = 0; i < recipient_keys_count; i ++)
  2031         pgp_key_free(recipient_keys[i]);
  2032     free(recipient_keys);
  2033     for (int i = 0; i < recipient_cert_count; i ++)
  2034         pgp_cert_free(recipient_certs[i]);
  2035     free(recipient_certs);
  2036 
  2037     T("-> %s", pEp_status_to_string(status));
  2038     return status;
  2039 }
  2040 
  2041 PEP_STATUS pgp_encrypt_only(
  2042     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  2043     size_t psize, char **ctext, size_t *csize)
  2044 {
  2045     return pgp_encrypt_sign_optional(session, keylist, ptext,
  2046         psize, ctext, csize, false);
  2047 }
  2048 
  2049 PEP_STATUS pgp_encrypt_and_sign(
  2050     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  2051     size_t psize, char **ctext, size_t *csize)
  2052 {
  2053     return pgp_encrypt_sign_optional(session, keylist, ptext,
  2054         psize, ctext, csize, true);
  2055 }
  2056 
  2057 static char* _filter_parentheses(const char* input) {
  2058     if (!input)
  2059         return NULL;
  2060     
  2061     int input_len = strlen(input) + 1;
  2062     char* retval = calloc(input_len, 1);
  2063     strlcpy(retval, input, input_len);
  2064 
  2065     char* curr_c;
  2066     
  2067     for (curr_c = retval; curr_c && *curr_c != '\0'; curr_c++) {
  2068         switch(*curr_c) {
  2069             case '(':
  2070                 *curr_c = '[';
  2071                 break;
  2072             case ')':
  2073                 *curr_c = ']';
  2074                 break;
  2075             default:
  2076                 break;
  2077         }
  2078     }  
  2079     
  2080     return retval;
  2081 }
  2082 
  2083 static char* _flatten_to_alphanum(const char* input) {
  2084     if (!input)
  2085         return NULL;
  2086     
  2087     int input_len = strlen(input) + 1;
  2088     char* retval = calloc(input_len, 1);
  2089     strlcpy(retval, input, input_len);
  2090 
  2091     char* curr_c;
  2092     
  2093     for (curr_c = retval; curr_c && *curr_c != '\0'; curr_c++) {
  2094         char c = *curr_c;
  2095 
  2096         if (c == ' ' || (c >= 'A' && c <= 'Z') || 
  2097                         (c >= 'a' && c <= 'z') ||
  2098                         (c >= '0' && c <= '9'))
  2099             continue;           
  2100 
  2101         *curr_c = '_';
  2102     }  
  2103     
  2104     return retval;
  2105 }
  2106 
  2107 PEP_STATUS _pgp_generate_keypair(PEP_SESSION session, pEp_identity *identity, time_t when)
  2108 {
  2109     PEP_STATUS status = PEP_STATUS_OK;
  2110     pgp_error_t err = NULL;
  2111     pgp_packet_t userid_packet = NULL;
  2112     char *userid = NULL;
  2113     pgp_cert_t cert = NULL;
  2114     pgp_fingerprint_t pgp_fpr = NULL;
  2115     char *fpr = NULL;
  2116 
  2117     assert(session);
  2118     assert(identity);
  2119     assert(identity->address);
  2120     assert(identity->fpr == NULL || identity->fpr[0] == 0);
  2121 //    assert(identity->username);
  2122 
  2123     char* cached_username = identity->username;
  2124     
  2125     if (identity->username && strcmp(identity->address, identity->username) == 0) {
  2126         cached_username = identity->username;
  2127         identity->username = NULL;
  2128     }
  2129     
  2130 
  2131     userid_packet = pgp_user_id_from_unchecked_address(&err,
  2132                                                        identity->username, NULL,
  2133                                                        identity->address);           
  2134                                                    
  2135     if (!userid_packet) {
  2136         char* tmpname = _filter_parentheses(identity->username);
  2137         userid_packet = pgp_user_id_from_unchecked_address(&err,
  2138                                                            tmpname, NULL,
  2139                                                            identity->address);               
  2140         free(tmpname);                                                   
  2141     }
  2142 
  2143     if (!userid_packet) {
  2144         char* tmpname = _flatten_to_alphanum(identity->username);
  2145         userid_packet = pgp_user_id_from_unchecked_address(&err,
  2146                                                            tmpname, NULL,
  2147                                                            identity->address);               
  2148         free(tmpname);                                                           
  2149     }
  2150                                             
  2151     identity->username = cached_username;                                                   
  2152     
  2153     if (!userid_packet)
  2154         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "pgp_user_id_from_unchecked_address");
  2155 
  2156     size_t userid_len = 0;
  2157     const uint8_t *raw = pgp_user_id_value(userid_packet, &userid_len);
  2158 
  2159     // NUL terminate it.
  2160     userid = malloc(userid_len + 1);
  2161     if (!userid)
  2162         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  2163 
  2164     memcpy(userid, raw, userid_len);
  2165     userid[userid_len] = 0;
  2166 
  2167     T("(%s)", userid);
  2168 
  2169     // Generate a key.
  2170     pgp_cert_builder_t certb = pgp_cert_builder_general_purpose(
  2171         cipher_suite(session->cipher_suite), userid);
  2172 
  2173     pgp_cert_builder_set_creation_time(&certb, when);
  2174 
  2175     pgp_signature_t rev;
  2176     if (pgp_cert_builder_generate(&err, certb, &cert, &rev))
  2177         ERROR_OUT(err, PEP_CANNOT_CREATE_KEY, "Generating a key pair");
  2178 
  2179     // XXX: We should return this.
  2180     pgp_signature_free(rev);
  2181 
  2182     // Get the fingerprint.
  2183     pgp_fpr = pgp_cert_fingerprint(cert);
  2184     fpr = pgp_fingerprint_to_hex(pgp_fpr);
  2185 
  2186     status = cert_save(session, cert, NULL);
  2187     cert = NULL;
  2188     if (status != 0)
  2189         ERROR_OUT(NULL, PEP_CANNOT_CREATE_KEY, "saving TSK");
  2190 
  2191     free(identity->fpr);
  2192     identity->fpr = fpr;
  2193     fpr = NULL;
  2194 
  2195  out:
  2196     pgp_fingerprint_free(pgp_fpr);
  2197     free(fpr);
  2198     pgp_cert_free(cert);
  2199     free(userid);
  2200     pgp_packet_free(userid_packet);
  2201 
  2202     T("-> %s", pEp_status_to_string(status));
  2203     return status;
  2204 }
  2205 
  2206 PEP_STATUS pgp_generate_keypair(PEP_SESSION session, pEp_identity *identity)
  2207 {
  2208     return _pgp_generate_keypair(session, identity, 0);
  2209 }
  2210 
  2211 PEP_STATUS pgp_delete_keypair(PEP_SESSION session, const char *fpr_raw)
  2212 {
  2213     PEP_STATUS status = PEP_STATUS_OK;
  2214 
  2215     assert(session && fpr_raw && fpr_raw[0]);
  2216     if (!(session && fpr_raw && fpr_raw[0]))
  2217         ERROR_OUT(NULL, PEP_ILLEGAL_VALUE, "invalid arguments");
  2218 
  2219     char *fpr = pgp_fingerprint_canonicalize(fpr_raw);
  2220     if (! fpr)
  2221         ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "out of memory");
  2222 
  2223     T("Deleting %s", fpr);
  2224 
  2225     sqlite3_stmt *stmt = session->sq_sql.delete_keypair;
  2226     sqlite3_bind_text(stmt, 1, fpr, -1, free);
  2227 
  2228     int sqlite_result = sqlite3_step(stmt);
  2229     sqlite3_reset(stmt);
  2230     if (sqlite_result != SQLITE_DONE)
  2231         ERROR_OUT(NULL, PEP_CANNOT_DELETE_KEY,
  2232                   "deletion failed: %s", sqlite3_errmsg(session->key_db));
  2233 
  2234     sqlite_result = sqlite3_changes(session->key_db);
  2235     assert(sqlite_result >= 0 && sqlite_result < 2);
  2236     if (sqlite_result < 1)
  2237         ERROR_OUT(NULL, PEP_KEY_NOT_FOUND,
  2238                   "attempt to delete non-existent key: %s", fpr_raw);
  2239 
  2240  out:
  2241     return status;
  2242 }
  2243 
  2244 static unsigned int count_keydata_parts(const char* key_data, size_t size) {
  2245     unsigned int retval = 0;
  2246 
  2247     const char* pgp_begin = "-----BEGIN PGP";
  2248     size_t prefix_len = strlen(pgp_begin);
  2249     size_t size_remaining = size;
  2250 
  2251     while (key_data) {
  2252         if (size_remaining <= prefix_len || key_data[0] == '\0')
  2253             break;
  2254         key_data = strnstr(key_data, pgp_begin, size_remaining);
  2255         if (key_data) {
  2256             retval++;
  2257             key_data += prefix_len;
  2258             size_remaining -= prefix_len;
  2259         }
  2260     }
  2261     return retval;
  2262  }
  2263 
  2264 PEP_STATUS _pgp_import_keydata(PEP_SESSION session, const char *key_data,
  2265                               size_t size, identity_list **private_idents)
  2266 {
  2267     PEP_STATUS status = PEP_NO_KEY_IMPORTED;
  2268     pgp_error_t err;
  2269     pgp_cert_parser_t parser = NULL;
  2270 
  2271     if (private_idents)
  2272         *private_idents = NULL;
  2273         
  2274     T("parsing %zd bytes", size);
  2275 
  2276     pgp_packet_parser_result_t ppr
  2277         = pgp_packet_parser_from_bytes(&err, (uint8_t *) key_data, size);
  2278     if (! ppr)
  2279         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Creating packet parser");
  2280 
  2281     pgp_tag_t tag = pgp_packet_parser_result_tag(ppr);
  2282     switch (tag) {
  2283     case PGP_TAG_SIGNATURE: {
  2284         // The following asserts can't fail, because
  2285         // pgp_packet_parser_result_tag succeeded and the tag is
  2286         // right.
  2287         pgp_packet_parser_t pp = pgp_packet_parser_result_packet_parser (ppr);
  2288         assert(pp);
  2289 
  2290         pgp_packet_t packet = NULL;
  2291         if (pgp_packet_parser_next(&err, pp, &packet, &ppr))
  2292             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Getting signature packet");
  2293 
  2294         pgp_signature_t sig = pgp_packet_ref_signature (packet);
  2295         assert(sig);
  2296 
  2297         pgp_cert_t cert = NULL;
  2298 
  2299         pgp_fingerprint_t issuer_fpr = pgp_signature_issuer_fingerprint(sig);
  2300         if (issuer_fpr) {
  2301             char *issuer_fpr_hex = pgp_fingerprint_to_hex(issuer_fpr);
  2302             T("Importing a signature issued by %s", issuer_fpr_hex);
  2303 
  2304             status = cert_find_by_fpr_hex(session, issuer_fpr_hex,
  2305                                          false, &cert, NULL);
  2306             if (status && status != PEP_KEY_NOT_FOUND)
  2307                 DUMP_ERR(NULL, status, "Looking up %s", issuer_fpr_hex);
  2308 
  2309             free(issuer_fpr_hex);
  2310             pgp_fingerprint_free(issuer_fpr);
  2311         }
  2312 
  2313         if (! cert) {
  2314             pgp_keyid_t issuer = pgp_signature_issuer(sig);
  2315             if (issuer) {
  2316                 char *issuer_hex = pgp_keyid_to_hex(issuer);
  2317                 T("Importing a signature issued by %s", issuer_hex);
  2318 
  2319                 status = cert_find_by_keyid_hex(session, issuer_hex,
  2320                                                false, &cert, NULL);
  2321                 if (status && status != PEP_KEY_NOT_FOUND)
  2322                     DUMP_ERR(NULL, status, "Looking up %s", issuer_hex);
  2323 
  2324                 free(issuer_hex);
  2325                 pgp_keyid_free(issuer);
  2326             }
  2327         }
  2328 
  2329         // We need a packet.  sig is only a reference, so we just need
  2330         // to free it.
  2331         pgp_signature_free(sig);
  2332 
  2333         if (cert) {
  2334             T("Merging packet: %s", pgp_packet_debug(packet));
  2335 
  2336             cert = pgp_cert_merge_packets (&err, cert, &packet, 1);
  2337             if (! cert)
  2338                 ERROR_OUT(err, PEP_UNKNOWN_ERROR, "Merging signature");
  2339 
  2340             status = cert_save(session, cert, NULL);
  2341             if (status)
  2342                 ERROR_OUT(NULL, status, "saving merged CERT");
  2343             status = PEP_KEY_IMPORTED;
  2344         }
  2345         break;
  2346     }
  2347     case PGP_TAG_PUBLIC_KEY:
  2348     case PGP_TAG_SECRET_KEY: {
  2349         parser = pgp_cert_parser_from_packet_parser(ppr);
  2350         pgp_cert_t cert;
  2351         int count = 0;
  2352         err = NULL;
  2353         while ((cert = pgp_cert_parser_next(&err, parser))) {
  2354             count ++;
  2355 
  2356             T("#%d. CERT for %s, %s",
  2357               count, pgp_cert_primary_user_id(cert, session->policy, 0),
  2358               pgp_fingerprint_to_hex(pgp_cert_fingerprint(cert)));
  2359 
  2360             // If private_idents is not NULL and there is any private key
  2361             // material, it will be saved.
  2362             status = cert_save(session, cert, private_idents);
  2363             if (status == PEP_STATUS_OK)
  2364                 status = PEP_KEY_IMPORTED;
  2365             else
  2366                 ERROR_OUT(NULL, status, "saving certificate");
  2367         }
  2368         if (err || count == 0)
  2369             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "parsing key data");
  2370         break;
  2371     }
  2372     default:
  2373         ERROR_OUT(NULL, PEP_NO_KEY_IMPORTED,
  2374                   "Can't import %s", pgp_tag_to_string(tag));
  2375         break;
  2376     }
  2377 
  2378     int int_result = sqlite3_exec(
  2379         session->key_db,
  2380         "PRAGMA wal_checkpoint(FULL);\n"
  2381         ,
  2382         NULL,
  2383         NULL,
  2384         NULL
  2385     );
  2386     if (int_result != SQLITE_OK)
  2387         status = PEP_UNKNOWN_DB_ERROR;
  2388 
  2389  out:
  2390     pgp_cert_parser_free(parser);
  2391 
  2392     T("-> %s", pEp_status_to_string(status));
  2393     return status;
  2394 }
  2395 
  2396 PEP_STATUS pgp_import_keydata(PEP_SESSION session, const char *key_data,
  2397                               size_t size, identity_list **private_idents)
  2398 {
  2399 
  2400     const char* pgp_begin = "-----BEGIN PGP";
  2401     size_t prefix_len = strlen(pgp_begin);
  2402 
  2403     // Because we also import binary keys we have to be careful with this.
  2404     // 
  2405     if (strlen(key_data + prefix_len) > prefix_len) {
  2406         const char* subtract_junk = strnstr(key_data, pgp_begin, size);
  2407         // If it's not in there, we just try to import it as is...
  2408         if (subtract_junk) {
  2409             size -= (subtract_junk - key_data);
  2410             key_data = subtract_junk;
  2411         }    
  2412     }
  2413 
  2414     unsigned int keycount = count_keydata_parts(key_data, size);
  2415     if (keycount < 2)
  2416         return(_pgp_import_keydata(session, key_data, size, private_idents));
  2417 
  2418     unsigned int i;
  2419     const char* curr_begin;
  2420     size_t curr_size;
  2421 
  2422     identity_list* collected_idents = NULL;
  2423 
  2424     PEP_STATUS retval = PEP_KEY_IMPORTED;
  2425             
  2426     for (i = 0, curr_begin = key_data; i < keycount; i++) {
  2427         const char* next_begin = NULL;
  2428 
  2429         // This is assured to be OK because the count function above
  2430         // made sure that THIS round contains at least prefix_len chars
  2431         // We used strnstr to count, so we know that strstr will be ok.
  2432         if (strlen(curr_begin + prefix_len) > prefix_len)
  2433             next_begin = strstr(curr_begin + prefix_len, pgp_begin);
  2434 
  2435         if (next_begin)
  2436             curr_size = next_begin - curr_begin;
  2437         else
  2438             curr_size = (key_data + size) - curr_begin;
  2439 
  2440         PEP_STATUS curr_status = _pgp_import_keydata(session, curr_begin, curr_size, private_idents);
  2441         if (private_idents && *private_idents) {
  2442             if (!collected_idents)
  2443                 collected_idents = *private_idents;
  2444             else
  2445                 identity_list_join(collected_idents, *private_idents);
  2446             *private_idents = NULL;
  2447         }
  2448 
  2449         if (curr_status != retval) {
  2450             switch (curr_status) {
  2451                 case PEP_NO_KEY_IMPORTED:
  2452                 case PEP_KEY_NOT_FOUND:
  2453                 case PEP_UNKNOWN_ERROR:
  2454                     switch (retval) {
  2455                         case PEP_KEY_IMPORTED:
  2456                             retval = PEP_SOME_KEYS_IMPORTED;
  2457                             break;
  2458                         case PEP_UNKNOWN_ERROR:
  2459                             retval = curr_status;
  2460                             break;
  2461                         default:
  2462                             break;
  2463                     }
  2464                     break;
  2465                 case PEP_KEY_IMPORTED:
  2466                     retval = PEP_SOME_KEYS_IMPORTED;
  2467                 default:
  2468                     break;
  2469             }
  2470         }
  2471         curr_begin = next_begin;
  2472     }
  2473 
  2474     if (private_idents)
  2475         *private_idents = collected_idents;
  2476 
  2477     return retval;
  2478 }
  2479 
  2480 PEP_STATUS pgp_export_keydata(
  2481         PEP_SESSION session, const char *fpr, char **key_data, size_t *size,
  2482         bool secret)
  2483 {
  2484     PEP_STATUS status = PEP_STATUS_OK;
  2485     pgp_error_t err = NULL;
  2486     pgp_cert_t cert = NULL;
  2487     pgp_writer_t armor_writer = NULL;
  2488     pgp_writer_t memory_writer = NULL;
  2489 
  2490     assert(session);
  2491     assert(fpr);
  2492     assert(key_data);
  2493     assert(*key_data == NULL);
  2494     assert(size);
  2495 
  2496     *size = 0;
  2497 
  2498     T("(%s, %s)", fpr, secret ? "secret" : "public");
  2499 
  2500     // If the caller asks for a secret key and we only have a
  2501     // public key, then we return an error.
  2502     status = cert_find_by_fpr_hex(session, fpr, secret, &cert, NULL);
  2503     ERROR_OUT(NULL, status, "Looking up TSK for %s", fpr);
  2504 
  2505     memory_writer = pgp_writer_alloc((void **) key_data, size);
  2506     if (! memory_writer)
  2507         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR, "creating memory writer");
  2508     armor_writer = pgp_armor_writer_new(&err, memory_writer,
  2509                                         PGP_ARMOR_KIND_PUBLICKEY, NULL, 0);
  2510     if (! armor_writer) {
  2511         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "creating armored writer");
  2512     }
  2513 
  2514     if (secret) {
  2515         pgp_tsk_t tsk = pgp_cert_as_tsk(cert);
  2516         if (pgp_tsk_serialize(&err, tsk, armor_writer))
  2517             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "serializing TSK");
  2518         pgp_tsk_free(tsk);
  2519     } else {
  2520         if (pgp_cert_serialize(&err, cert, armor_writer))
  2521             ERROR_OUT(err, PEP_UNKNOWN_ERROR, "serializing certificate");
  2522     }
  2523 
  2524     if (pgp_armor_writer_finalize(&err, armor_writer))
  2525         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR, "flushing armored data");
  2526 
  2527 
  2528  out:
  2529     if (memory_writer) {
  2530         if (status == PEP_STATUS_OK) {
  2531             // Add a trailing NUL.
  2532             pgp_writer_write(NULL, memory_writer, (const uint8_t *) "", 1);
  2533         }
  2534 
  2535         pgp_writer_free(memory_writer);
  2536     }
  2537 
  2538     if (cert)
  2539         pgp_cert_free(cert);
  2540 
  2541     (*size)--;  // Sequoia is delivering the 0 byte at the end with size, but
  2542                 // pEp is expecting it without
  2543     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2544     return status;
  2545 }
  2546 
  2547 static char *_undot_address(const char* address) {
  2548     if (!address)
  2549         return NULL;
  2550 
  2551     int addr_len = strlen(address);
  2552     const char* at = memchr(address, '@', addr_len);
  2553 
  2554     if (!at)
  2555         at = address + addr_len;
  2556 
  2557     char* retval = calloc(1, addr_len + 1);
  2558 
  2559     const char* addr_curr = address;
  2560     char* retval_curr = retval;
  2561 
  2562     while (addr_curr < at) {
  2563         if (*addr_curr == '.') {
  2564             addr_curr++;
  2565             continue;
  2566         }
  2567         *retval_curr = *addr_curr;
  2568         retval_curr++;
  2569         addr_curr++;
  2570     }
  2571     if (*addr_curr == '@')
  2572         strcat(retval_curr, addr_curr);
  2573 
  2574     return retval;
  2575 }
  2576 
  2577 static stringpair_list_t *add_key(PEP_SESSION session,
  2578                                   stringpair_list_t *keyinfo_list,
  2579                                   stringlist_t* keylist,
  2580                                   pgp_cert_t cert, pgp_fingerprint_t fpr) {
  2581     bool revoked = false;
  2582     // Don't add revoked keys to the keyinfo_list.
  2583     if (keyinfo_list) {
  2584         pgp_revocation_status_t rs = pgp_cert_revoked(cert, session->policy, 0);
  2585         pgp_revocation_status_variant_t rsv = pgp_revocation_status_variant(rs);
  2586         pgp_revocation_status_free(rs);
  2587         if (rsv == PGP_REVOCATION_STATUS_REVOKED)
  2588             revoked = true;
  2589     }
  2590 
  2591     if (revoked && ! keylist)
  2592         return keyinfo_list;
  2593 
  2594     int dealloc_fpr = 0;
  2595     if (!fpr) {
  2596         dealloc_fpr = 1;
  2597         fpr = pgp_cert_fingerprint(cert);
  2598     }
  2599     char *fpr_str = pgp_fingerprint_to_hex(fpr);
  2600 
  2601     if (!revoked && keyinfo_list) {
  2602         char *user_id = pgp_cert_primary_user_id(cert, session->policy, 0);
  2603         if (user_id)
  2604             keyinfo_list = stringpair_list_add(keyinfo_list,
  2605                                                new_stringpair(fpr_str, user_id));
  2606         free(user_id);
  2607     }
  2608 
  2609     if (keylist)
  2610         keylist = stringlist_add(keylist, fpr_str);
  2611 
  2612     free(fpr_str);
  2613     if (dealloc_fpr)
  2614         pgp_fingerprint_free(fpr);
  2615 
  2616     return keyinfo_list;
  2617 }
  2618 
  2619 static PEP_STATUS list_keys(PEP_SESSION session,
  2620                             const char* pattern, int private_only,
  2621                             stringpair_list_t** keyinfo_list, stringlist_t** keylist)
  2622 {
  2623     PEP_STATUS status = PEP_STATUS_OK;
  2624     pgp_cert_t cert = NULL;
  2625     pgp_fingerprint_t fpr = NULL;
  2626 
  2627     T("('%s', private: %d)", pattern, private_only);
  2628 
  2629     stringpair_list_t* _keyinfo_list = NULL;
  2630     if (keyinfo_list) {
  2631         _keyinfo_list = new_stringpair_list(NULL);
  2632         if (!_keyinfo_list)
  2633             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "new_stringpair_list");
  2634     }
  2635     stringlist_t* _keylist = NULL;
  2636     if (keylist) {
  2637         _keylist = new_stringlist(NULL);
  2638         if (!_keylist)
  2639             ERROR_OUT(NULL, PEP_OUT_OF_MEMORY, "new_string_list");
  2640     }
  2641 
  2642     // Trim any leading space.  This also makes it easier to recognize
  2643     // a string that is only whitespace.
  2644     while (*pattern == ' ')
  2645         pattern ++;
  2646 
  2647     if (strchr(pattern, '@') || strchr(pattern, ':')) {
  2648         // Looks like a mailbox or URI.
  2649         pgp_cert_t *certs = NULL;
  2650         int count = 0;
  2651         status = cert_find_by_email(session, pattern, private_only, &certs, &count);
  2652         ERROR_OUT(NULL, status, "Looking up '%s'", pattern);
  2653         for (int i = 0; i < count; i ++) {
  2654             add_key(session, _keyinfo_list, _keylist, certs[i], NULL);
  2655             pgp_cert_free(certs[i]);
  2656         }
  2657         free(certs);
  2658 
  2659         if (count == 0) {
  2660             // If match failed, check to see if we've got a dotted
  2661             // address in the pattern.  If so, try again without dots.
  2662             const char* dotpos = strstr(pattern, ".");
  2663             const char* atpos = strstr(pattern, "@");
  2664             if (dotpos && atpos && (dotpos < atpos)) {
  2665                 char* undotted = _undot_address(pattern);
  2666                 if (undotted) {
  2667                     PEP_STATUS status = list_keys(session, undotted, private_only,
  2668                                                   keyinfo_list, keylist);
  2669                     free(undotted);
  2670                     return status;
  2671                 }
  2672             }
  2673         }
  2674     } else if (// Only hex characters and spaces
  2675                pattern[strspn(pattern, "0123456789aAbBcCdDeEfF ")] == 0
  2676                // And a fair amount of them.
  2677                && strlen(pattern) >= 16) {
  2678         // Fingerprint.  Note: the pep engine never looks keys up by
  2679         // keyid, so we don't handle them.
  2680         fpr = pgp_fingerprint_from_hex(pattern);
  2681         status = cert_find_by_fpr(session, fpr, false, &cert, NULL);
  2682         ERROR_OUT(NULL, status, "Looking up key");
  2683         add_key(session, _keyinfo_list, _keylist, cert, fpr);
  2684     } else if (pattern[0] == 0) {
  2685         // Empty string.
  2686 
  2687         pgp_cert_t *certs = NULL;
  2688         int count = 0;
  2689         status = cert_all(session, private_only, &certs, &count);
  2690         ERROR_OUT(NULL, status, "Looking up '%s'", pattern);
  2691         for (int i = 0; i < count; i ++) {
  2692             add_key(session, _keyinfo_list, _keylist, certs[i], NULL);
  2693             pgp_cert_free(certs[i]);
  2694         }
  2695         free(certs);
  2696     } else {
  2697         T("unsupported pattern '%s'", pattern);
  2698     }
  2699 
  2700  out:
  2701     pgp_cert_free(cert);
  2702     pgp_fingerprint_free(fpr);
  2703 
  2704     if (status == PEP_KEY_NOT_FOUND)
  2705         status = PEP_STATUS_OK;
  2706 
  2707     if (status != PEP_STATUS_OK || (_keyinfo_list && !_keyinfo_list->value)) {
  2708         free_stringpair_list(_keyinfo_list);
  2709         _keyinfo_list = NULL;
  2710     }
  2711     if (keyinfo_list)
  2712         *keyinfo_list = _keyinfo_list;
  2713 
  2714     if (status != PEP_STATUS_OK || (_keylist && !_keylist->value)) {
  2715         free_stringlist(_keylist);
  2716         _keylist = NULL;
  2717     }
  2718     if (keylist)
  2719         *keylist = _keylist;
  2720 
  2721     int len = -1;
  2722     if (keylist)
  2723         len = stringlist_length(*keylist);
  2724     else if (keyinfo_list)
  2725         len = stringpair_list_length(*keyinfo_list);
  2726     T("(%s) -> %s (%d keys)", pattern, pEp_status_to_string(status), len);
  2727     return status;
  2728 }
  2729 
  2730 // pattern could be empty, an fpr, or a mailbox.
  2731 //
  2732 // keyinfo_list is a list of <fpr, openpgp userid> tuples for the
  2733 // matching keys.
  2734 //
  2735 // This function filters out revoked key, but not expired keys.
  2736 PEP_STATUS pgp_list_keyinfo(PEP_SESSION session,
  2737                             const char* pattern,
  2738                             stringpair_list_t** keyinfo_list)
  2739 {
  2740     return list_keys(session, pattern, false, keyinfo_list, NULL);
  2741 }
  2742 
  2743 PEP_STATUS pgp_recv_key(PEP_SESSION session, const char *pattern)
  2744 {
  2745     assert(!"pgp_recv_key not implemented");
  2746     return PEP_UNKNOWN_ERROR;
  2747 }
  2748 
  2749 // Unlike pgp_list_keyinfo, this function returns revoked keys.
  2750 PEP_STATUS pgp_find_keys(
  2751     PEP_SESSION session, const char *pattern, stringlist_t **keylist)
  2752 {
  2753     return list_keys(session, pattern, false, NULL, keylist);
  2754 }
  2755 
  2756 // Unlike pgp_list_keyinfo, this function returns revoked keys.
  2757 PEP_STATUS pgp_find_private_keys(
  2758     PEP_SESSION session, const char *pattern, stringlist_t **keylist)
  2759 {
  2760     return list_keys(session, pattern, true, NULL, keylist);
  2761 }
  2762 
  2763 PEP_STATUS pgp_send_key(PEP_SESSION session, const char *pattern)
  2764 {
  2765     assert(!"pgp_send_key not implemented");
  2766     return PEP_UNKNOWN_ERROR;
  2767 }
  2768 
  2769 
  2770 PEP_STATUS pgp_renew_key(
  2771     PEP_SESSION session, const char *fpr, const timestamp *ts)
  2772 {
  2773     PEP_STATUS status = PEP_STATUS_OK;
  2774     pgp_error_t err = NULL;
  2775     pgp_cert_t cert = NULL;
  2776     pgp_cert_valid_key_iter_t iter = NULL;
  2777     pgp_valid_key_amalgamation_t primary = NULL;
  2778     pgp_key_pair_t keypair = NULL;
  2779     pgp_signer_t signer = NULL;
  2780     time_t t = timegm((struct tm *) ts);
  2781     pgp_cert_valid_key_iter_t key_iter = NULL;
  2782     pgp_valid_key_amalgamation_t ka = NULL;
  2783     pgp_packet_t *packets = NULL;
  2784     size_t packet_count = 0;
  2785     size_t packet_capacity = 0;
  2786 
  2787     T("(%s)", fpr);
  2788 
  2789     status = cert_find_by_fpr_hex(session, fpr, true, &cert, NULL);
  2790     ERROR_OUT(NULL, status, "Looking up '%s'", fpr);
  2791 
  2792     time_t creation_time = pgp_key_creation_time(pgp_cert_primary_key(cert));
  2793     if (creation_time > t)
  2794         // The creation time is after the expiration time!
  2795         ERROR_OUT(NULL, PEP_UNKNOWN_ERROR,
  2796                   "creation time can't be after expiration time");
  2797 
  2798     iter = pgp_cert_valid_key_iter(cert, session->policy, 0);
  2799     pgp_cert_valid_key_iter_for_certification (iter);
  2800     pgp_cert_valid_key_iter_unencrypted_secret (iter);
  2801     pgp_cert_valid_key_iter_revoked(iter, false);
  2802 
  2803     // If there are multiple certification capable subkeys, we just
  2804     // take the first one, whichever one that happens to be.
  2805     primary = pgp_cert_valid_key_iter_next (iter, NULL, NULL);
  2806     if (! primary)
  2807         ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  2808                    "%s has no usable certification capable key", fpr);
  2809 
  2810     // pgp_key_into_key_pair needs to own the key, but here we
  2811     // only get a reference (which we still need to free).
  2812     pgp_key_t key = pgp_valid_key_amalgamation_key (primary);
  2813     keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  2814     pgp_key_free (key);
  2815     if (! keypair)
  2816         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  2817 
  2818     signer = pgp_key_pair_as_signer (keypair);
  2819     if (! signer)
  2820         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  2821 
  2822     // Set the expiration for all non-revoked keys.
  2823     key_iter = pgp_cert_valid_key_iter(cert, session->policy, 0);
  2824     pgp_cert_valid_key_iter_revoked(key_iter, false);
  2825 
  2826     while ((ka = pgp_cert_valid_key_iter_next(key_iter, NULL, NULL))) {
  2827         pgp_status_t sq_status;
  2828         pgp_error_t err;
  2829         pgp_packet_t *packets_tmp = NULL;
  2830         size_t packet_count_tmp = 0;
  2831 
  2832         sq_status = pgp_valid_key_amalgamation_set_expiration_time
  2833             (&err, ka, signer, t, &packets_tmp, &packet_count_tmp);
  2834         if (sq_status)
  2835             ERROR_OUT(err, PEP_UNKNOWN_ERROR,
  2836                       "setting expiration (generating self signatures)");
  2837 
  2838         if (! packets) {
  2839             assert(packet_count == 0);
  2840             assert(packet_capacity == 0);
  2841 
  2842             packets = packets_tmp;
  2843             packet_count = packet_count_tmp;
  2844             packet_capacity = packet_count_tmp;
  2845         } else {
  2846             assert(packet_capacity > 0);
  2847             if (packet_capacity - packet_count < packet_count_tmp) {
  2848                 // Grow the array.
  2849                 int c = packet_capacity;
  2850                 while (c < packet_count + packet_count_tmp) {
  2851                     c *= 2;
  2852                 }
  2853 
  2854                 void * tmp = _pEp_reallocarray(packets, c, sizeof (*packets));
  2855                 if (! tmp)
  2856                     ERROR_OUT(NULL, PEP_OUT_OF_MEMORY,
  2857                               "setting expiration (resizing buffer)");
  2858 
  2859                 packets = tmp;
  2860                 packet_capacity = c;
  2861             }
  2862 
  2863             int i;
  2864             for (i = 0; i < packet_count_tmp; i ++) {
  2865                 packets[packet_count + i] = packets_tmp[i];
  2866             }
  2867             packet_count += packet_count_tmp;
  2868         }
  2869 
  2870         pgp_valid_key_amalgamation_free (ka);
  2871     }
  2872 
  2873     // We're going to mutate cert, which key_iter references.
  2874     // Deallocate it first.
  2875     pgp_cert_valid_key_iter_free (key_iter);
  2876     key_iter = NULL;
  2877 
  2878     cert = pgp_cert_merge_packets (&err, cert, packets, packet_count);
  2879     // The packets (but not the array) are now owned by cert.
  2880     packet_count = 0;
  2881     if (! cert)
  2882         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "setting expiration (updating cert)");
  2883 
  2884     status = cert_save(session, cert, NULL);
  2885     cert = NULL;
  2886     ERROR_OUT(NULL, status, "Saving %s", fpr);
  2887 
  2888  out:
  2889     if (packets) {
  2890         for (int i = 0; i < packet_count; i ++) {
  2891             pgp_packet_free (packets[i]);
  2892         }
  2893         free (packets);
  2894     }
  2895 
  2896     pgp_valid_key_amalgamation_free (ka);
  2897     pgp_cert_valid_key_iter_free (key_iter);
  2898     pgp_signer_free (signer);
  2899     // XXX: pgp_key_pair_as_signer is only supposed to reference
  2900     // signing_keypair, but it consumes it.  If this is fixed, this
  2901     // will become a leak.
  2902     //
  2903     pgp_key_pair_free (keypair);
  2904     pgp_valid_key_amalgamation_free (primary);
  2905     pgp_cert_valid_key_iter_free (iter);
  2906     pgp_cert_free(cert);
  2907 
  2908     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2909     return status;
  2910 }
  2911 
  2912 PEP_STATUS pgp_revoke_key(
  2913     PEP_SESSION session, const char *fpr, const char *reason)
  2914 {
  2915     PEP_STATUS status = PEP_STATUS_OK;
  2916     pgp_error_t err = NULL;
  2917     pgp_cert_t cert = NULL;
  2918     pgp_cert_valid_key_iter_t iter = NULL;
  2919     pgp_valid_key_amalgamation_t ka = NULL;
  2920     pgp_key_pair_t keypair = NULL;
  2921     pgp_signer_t signer = NULL;
  2922 
  2923     T("(%s)", fpr);
  2924 
  2925     status = cert_find_by_fpr_hex(session, fpr, true, &cert, NULL);
  2926     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  2927 
  2928     iter = pgp_cert_valid_key_iter(cert, session->policy, 0);
  2929     pgp_cert_valid_key_iter_alive(iter);
  2930     pgp_cert_valid_key_iter_revoked(iter, false);
  2931     pgp_cert_valid_key_iter_for_certification (iter);
  2932     pgp_cert_valid_key_iter_unencrypted_secret (iter);
  2933 
  2934     // If there are multiple certification capable subkeys, we just
  2935     // take the first one, whichever one that happens to be.
  2936     ka = pgp_cert_valid_key_iter_next (iter, NULL, NULL);
  2937     if (! ka)
  2938         ERROR_OUT (err, PEP_UNKNOWN_ERROR,
  2939                    "%s has no usable certification capable key", fpr);
  2940 
  2941     // pgp_key_into_key_pair needs to own the key, but here we
  2942     // only get a reference (which we still need to free).
  2943     pgp_key_t key = pgp_valid_key_amalgamation_key (ka);
  2944     keypair = pgp_key_into_key_pair (NULL, pgp_key_clone (key));
  2945     pgp_key_free (key);
  2946     if (! keypair)
  2947         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a keypair");
  2948 
  2949     signer = pgp_key_pair_as_signer (keypair);
  2950     if (! signer)
  2951         ERROR_OUT (err, PEP_UNKNOWN_ERROR, "Creating a signer");
  2952 
  2953     cert = pgp_cert_revoke_in_place(&err, cert, signer,
  2954                                     PGP_REASON_FOR_REVOCATION_UNSPECIFIED,
  2955                                     reason);
  2956     if (! cert)
  2957         ERROR_OUT(err, PEP_UNKNOWN_ERROR, "setting expiration");
  2958 
  2959     assert(pgp_revocation_status_variant(pgp_cert_revoked(cert, session->policy, 0))
  2960            == PGP_REVOCATION_STATUS_REVOKED);
  2961 
  2962     status = cert_save(session, cert, NULL);
  2963     cert = NULL;
  2964     ERROR_OUT(NULL, status, "Saving %s", fpr);
  2965 
  2966  out:
  2967     pgp_signer_free (signer);
  2968     pgp_key_pair_free (keypair);
  2969     pgp_valid_key_amalgamation_free (ka);
  2970     pgp_cert_valid_key_iter_free (iter);
  2971     pgp_cert_free(cert);
  2972 
  2973     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  2974     return status;
  2975 }
  2976 
  2977 // NOTE: Doesn't check the *validity* of these subkeys. Just checks to see 
  2978 // if they exist.
  2979 static void _pgp_contains_encryption_subkey(PEP_SESSION session, pgp_cert_t cert, bool* has_subkey) {
  2980     pgp_cert_valid_key_iter_t key_iter
  2981         = pgp_cert_valid_key_iter(cert, session->policy, 0);
  2982 
  2983     // Calling these two allegedly gives the union, I think? :)
  2984     pgp_cert_valid_key_iter_for_transport_encryption(key_iter);
  2985     pgp_cert_valid_key_iter_for_storage_encryption(key_iter);
  2986 
  2987     pgp_valid_key_amalgamation_t ka
  2988         = pgp_cert_valid_key_iter_next(key_iter, NULL, NULL);
  2989     *has_subkey = ka != NULL;
  2990     pgp_valid_key_amalgamation_free (ka);
  2991     pgp_cert_valid_key_iter_free(key_iter);
  2992 }
  2993 
  2994 // NOTE: Doesn't check the *validity* of these subkeys. Just checks to see 
  2995 // if they exist.
  2996 static void _pgp_contains_sig_subkey(PEP_SESSION session, pgp_cert_t cert, bool* has_subkey) {
  2997     pgp_cert_valid_key_iter_t key_iter
  2998         = pgp_cert_valid_key_iter(cert, session->policy, 0);
  2999 
  3000     pgp_cert_valid_key_iter_for_signing(key_iter);
  3001 
  3002     pgp_valid_key_amalgamation_t ka
  3003         = pgp_cert_valid_key_iter_next(key_iter, NULL, NULL);
  3004     *has_subkey = ka != NULL;
  3005     pgp_valid_key_amalgamation_free (ka);
  3006     pgp_cert_valid_key_iter_free(key_iter);
  3007 }
  3008 
  3009 // Check to see that key, at a minimum, even contains encryption or signing subkeys
  3010 static void _pgp_key_broken(PEP_SESSION session, pgp_cert_t cert, bool* is_broken) {
  3011     *is_broken = false;
  3012     bool unbroken = false;
  3013     _pgp_contains_sig_subkey(session, cert, &unbroken);
  3014     if (!unbroken)
  3015         *is_broken = true;
  3016     else {
  3017         _pgp_contains_encryption_subkey(session, cert, &unbroken);
  3018         if (!unbroken)
  3019             *is_broken = true;
  3020     }
  3021 }
  3022 
  3023 static void _pgp_key_expired(PEP_SESSION session, pgp_cert_t cert, const time_t when, bool* expired)
  3024 {
  3025     // Is the certificate live?
  3026     *expired = pgp_cert_alive(NULL, cert, session->policy, when) != PGP_STATUS_SUCCESS;
  3027 
  3028     if (TRACING) {
  3029         char buffer[26];
  3030         time_t now = time(NULL);
  3031 
  3032         if (when == now || when == now - 1) {
  3033             sprintf(buffer, "now");
  3034         } else {
  3035             struct tm tm;
  3036             gmtime_r(&when, &tm);
  3037             strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tm);
  3038         }
  3039 
  3040         T("certificate is %slive as of %s", *expired ? "not " : "", buffer);
  3041     }
  3042     if (*expired)
  3043         goto out;
  3044 
  3045     // Check to see if the key is broken. Ideally, we'd do this in one pass below, but 
  3046     // givem the choice for how to check for expiry, this is the simplest solutiom.
  3047     bool broken = false;
  3048     _pgp_key_broken(session, cert, &broken);
  3049     if (broken)
  3050         goto out; // still isn't expired. is broken. there's a difference and a different check.    
  3051         
  3052     // Why is this an indicator of just an expired key and not a broken one?
  3053     // This will also reject keys that are not expired, but rather missing 
  3054     // subkeys.
  3055     //    
  3056     // Are there at least one certification subkey, one signing subkey
  3057     // and one encryption subkey that are live?
  3058     //    int can_certify = 0, can_encrypt = 0, can_sign = 0;
  3059     int can_encrypt = 0, can_sign = 0;
  3060 
  3061     pgp_cert_valid_key_iter_t key_iter
  3062         = pgp_cert_valid_key_iter(cert, session->policy, 0);
  3063     pgp_cert_valid_key_iter_alive(key_iter);
  3064     pgp_cert_valid_key_iter_revoked(key_iter, false);
  3065 
  3066     pgp_valid_key_amalgamation_t ka;
  3067     pgp_signature_t sig;
  3068     while ((ka = pgp_cert_valid_key_iter_next(key_iter, &sig, NULL))) {
  3069         if (pgp_signature_for_transport_encryption(sig)
  3070             || pgp_signature_for_storage_encryption(sig))
  3071             can_encrypt = 1;
  3072         if (pgp_signature_for_signing(sig))
  3073             can_sign = 1;
  3074         // if (pgp_signature_for_certification(sig))
  3075         //     can_certify = 1;
  3076 
  3077         pgp_signature_free (sig);
  3078         pgp_valid_key_amalgamation_free (ka);
  3079 
  3080 //        if (can_encrypt && can_sign && can_certify)
  3081         if (can_encrypt && can_sign)
  3082             break;
  3083     }
  3084     pgp_cert_valid_key_iter_free(key_iter);
  3085 
  3086 //    *expired = !(can_encrypt && can_sign && can_certify);
  3087     *expired = !(can_encrypt && can_sign);
  3088 
  3089     T("Key can%s encrypt, can%s sign => %s expired",
  3090       can_encrypt ? "" : "not",
  3091       can_sign ? "" : "not",
  3092       *expired ? "" : "not");
  3093 
  3094 out:
  3095     // Er, this might be problematic in terms of internal vs. external in log. FIXME?
  3096     T(" -> expired: %d", *expired);
  3097     return;
  3098 }
  3099 
  3100 PEP_STATUS pgp_key_expired(PEP_SESSION session, const char *fpr,
  3101                            const time_t when, bool *expired)
  3102 {
  3103     PEP_STATUS status = PEP_STATUS_OK;
  3104     pgp_cert_t cert = NULL;
  3105     T("(%s)", fpr);
  3106 
  3107     assert(session);
  3108     assert(fpr);
  3109     assert(expired);
  3110 
  3111     *expired = false;
  3112 
  3113     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  3114     status = cert_find_by_fpr(session, pgp_fpr, false, &cert, NULL);
  3115     pgp_fingerprint_free(pgp_fpr);
  3116     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  3117 
  3118     _pgp_key_expired(session, cert, when, expired);
  3119  out:
  3120     pgp_cert_free(cert);
  3121     T("(%s) -> %s (expired: %d)", fpr, pEp_status_to_string(status), *expired);
  3122     return status;
  3123 }
  3124 
  3125 static void _pgp_key_revoked(PEP_SESSION session, pgp_cert_t cert, bool* revoked) {
  3126     pgp_revocation_status_t rs = pgp_cert_revoked(cert, session->policy, 0);
  3127     *revoked = pgp_revocation_status_variant(rs) == PGP_REVOCATION_STATUS_REVOKED;
  3128     pgp_revocation_status_free (rs); 
  3129     
  3130     if (*revoked)
  3131         return;
  3132         
  3133     // Ok, at this point, we need to know if for signing or encryption there is
  3134     // ONLY a revoked key available. If so, this key is also considered revoked 
  3135     pgp_cert_valid_key_iter_t key_iter
  3136         = pgp_cert_valid_key_iter(cert, session->policy, 0);
  3137     pgp_cert_valid_key_iter_for_signing(key_iter);
  3138 
  3139     bool has_non_revoked_sig_key = false;
  3140     bool has_revoked_sig_key = false;
  3141 
  3142     pgp_valid_key_amalgamation_t ka;
  3143     while (!has_non_revoked_sig_key
  3144            && (ka = pgp_cert_valid_key_iter_next(key_iter, NULL, &rs))) {
  3145         if (pgp_revocation_status_variant(rs) == PGP_REVOCATION_STATUS_REVOKED)
  3146             has_revoked_sig_key = true;
  3147         else
  3148             has_non_revoked_sig_key = true;
  3149 
  3150         pgp_revocation_status_free(rs);
  3151         pgp_valid_key_amalgamation_free (ka);
  3152     }
  3153     pgp_cert_valid_key_iter_free(key_iter);
  3154 
  3155     if (has_non_revoked_sig_key) {
  3156         key_iter = pgp_cert_valid_key_iter(cert, session->policy, 0);
  3157         pgp_cert_valid_key_iter_for_transport_encryption(key_iter);
  3158         pgp_cert_valid_key_iter_for_storage_encryption(key_iter);
  3159 
  3160         bool has_non_revoked_enc_key = false;
  3161         bool has_revoked_enc_key = false;
  3162 
  3163         pgp_valid_key_amalgamation_t ka;
  3164         while (!has_non_revoked_enc_key
  3165                && (ka = pgp_cert_valid_key_iter_next(key_iter, NULL, &rs))) {
  3166             if (pgp_revocation_status_variant(rs) == PGP_REVOCATION_STATUS_REVOKED)
  3167                 has_revoked_enc_key = true;
  3168             else
  3169                 has_non_revoked_enc_key = true;
  3170 
  3171             pgp_revocation_status_free(rs);
  3172             pgp_valid_key_amalgamation_free (ka);
  3173         }
  3174         if (!has_non_revoked_enc_key) { // this does NOT mean revoked. it MAY mean broken.
  3175             if (has_revoked_enc_key)
  3176                 *revoked = true;
  3177         }
  3178         pgp_cert_valid_key_iter_free (key_iter);
  3179     }
  3180     else if (has_revoked_sig_key) {
  3181         *revoked = true;
  3182     }
  3183 }
  3184 
  3185 PEP_STATUS pgp_key_revoked(PEP_SESSION session, const char *fpr, bool *revoked)
  3186 {
  3187     PEP_STATUS status = PEP_STATUS_OK;
  3188     pgp_cert_t cert;
  3189 
  3190     T("(%s)", fpr);
  3191 
  3192     assert(session);
  3193     assert(fpr);
  3194     assert(revoked);
  3195 
  3196     *revoked = false;
  3197 
  3198     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  3199     status = cert_find_by_fpr(session, pgp_fpr, false, &cert, NULL);
  3200     pgp_fingerprint_free(pgp_fpr);
  3201     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  3202 
  3203     // pgp_revocation_status_t rs = pgp_cert_revoked(cert, 0);
  3204     // *revoked = pgp_revocation_status_variant(rs) == PGP_REVOCATION_STATUS_REVOKED;
  3205     // pgp_revocation_status_free (rs);
  3206     _pgp_key_revoked(session, cert, revoked);
  3207     pgp_cert_free(cert);
  3208 
  3209  out:
  3210     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  3211     return status;
  3212 }
  3213 
  3214 PEP_STATUS pgp_get_key_rating(
  3215     PEP_SESSION session, const char *fpr, PEP_comm_type *comm_type)
  3216 {
  3217     PEP_STATUS status = PEP_STATUS_OK;
  3218     pgp_cert_t cert = NULL;
  3219 
  3220     assert(session);
  3221     assert(fpr);
  3222     assert(comm_type);
  3223 
  3224     *comm_type = PEP_ct_unknown;
  3225 
  3226     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  3227     status = cert_find_by_fpr(session, pgp_fpr, false, &cert, NULL);
  3228     pgp_fingerprint_free(pgp_fpr);
  3229     ERROR_OUT(NULL, status, "Looking up key: %s", fpr);
  3230 
  3231     *comm_type = PEP_ct_OpenPGP_unconfirmed;
  3232 
  3233     // pgp_revocation_status_t rs = pgp_cert_revoked(cert, 0);
  3234     // pgp_revocation_status_variant_t rsv = pgp_revocation_status_variant(rs);
  3235     // pgp_revocation_status_free(rs);
  3236     // if (rsv == PGP_REVOCATION_STATUS_REVOKED) {
  3237     //     *comm_type = PEP_ct_key_revoked;
  3238     //     goto out;
  3239     // }
  3240 
  3241     bool revoked = false;
  3242     _pgp_key_revoked(session, cert, &revoked);
  3243     
  3244     if (revoked) {
  3245         *comm_type = PEP_ct_key_revoked;
  3246         goto out;
  3247     }    
  3248 
  3249     bool broken = false;
  3250     _pgp_key_broken(session, cert, &broken);
  3251     if (broken) {
  3252         *comm_type = PEP_ct_key_b0rken;
  3253         goto out;
  3254     }
  3255             
  3256     bool expired = false;
  3257     // MUST guarantee the same behaviour.
  3258     _pgp_key_expired(session, cert, time(NULL), &expired);
  3259 
  3260     if (expired) {
  3261         *comm_type = PEP_ct_key_expired;
  3262         goto out;
  3263     }
  3264 
  3265     PEP_comm_type worst_enc = PEP_ct_no_encryption, worst_sign = PEP_ct_no_encryption;
  3266     pgp_cert_valid_key_iter_t key_iter
  3267         = pgp_cert_valid_key_iter(cert, session->policy, 0);
  3268     pgp_cert_valid_key_iter_alive(key_iter);
  3269     pgp_cert_valid_key_iter_revoked(key_iter, false);
  3270 
  3271     pgp_valid_key_amalgamation_t ka;
  3272     pgp_signature_t sig;
  3273     while ((ka = pgp_cert_valid_key_iter_next(key_iter, &sig, NULL))) {
  3274         pgp_key_t key = pgp_valid_key_amalgamation_key (ka);
  3275 
  3276         PEP_comm_type curr = PEP_ct_no_encryption;
  3277 
  3278         int can_enc = pgp_signature_for_transport_encryption(sig)
  3279             || pgp_signature_for_storage_encryption(sig);
  3280         int can_sign = pgp_signature_for_signing(sig);
  3281 
  3282         pgp_public_key_algo_t pk_algo = pgp_key_public_key_algo(key);
  3283 
  3284         if (pk_algo == PGP_PUBLIC_KEY_ALGO_RSA_ENCRYPT_SIGN
  3285             || pk_algo == PGP_PUBLIC_KEY_ALGO_RSA_ENCRYPT
  3286             || pk_algo == PGP_PUBLIC_KEY_ALGO_RSA_SIGN) {
  3287             int bits = pgp_key_public_key_bits(key);
  3288             if (bits < 1024)
  3289                 curr = PEP_ct_key_too_short;
  3290             else if (bits == 1024)
  3291                 curr = PEP_ct_OpenPGP_weak_unconfirmed;
  3292             else
  3293                 curr = PEP_ct_OpenPGP_unconfirmed;
  3294         } else {
  3295             curr = PEP_ct_OpenPGP_unconfirmed;
  3296         }
  3297 
  3298         if (can_enc)
  3299             worst_enc = (worst_enc == PEP_ct_no_encryption ? curr : _MIN(worst_enc, curr));
  3300             
  3301         if (can_sign)
  3302             worst_sign = (worst_sign == PEP_ct_no_encryption ? curr : _MIN(worst_sign, curr));
  3303 
  3304         pgp_key_free (key);
  3305         pgp_signature_free (sig);
  3306         pgp_valid_key_amalgamation_free (ka);
  3307     }
  3308     pgp_cert_valid_key_iter_free(key_iter);
  3309 
  3310     // This may be redundant because of the broken check above; we should revisit later.
  3311     // But because this case was falling under expired because of how that is written, this 
  3312     // was probably never hiit here
  3313     if (worst_enc == PEP_ct_no_encryption || worst_sign == PEP_ct_no_encryption) {
  3314         *comm_type = PEP_ct_key_b0rken;
  3315         goto out;
  3316     } else {
  3317         *comm_type = _MIN(worst_enc, worst_sign);
  3318     }
  3319 
  3320  out:
  3321     pgp_cert_free(cert);
  3322 
  3323     T("(%s) -> %s", fpr, pEp_comm_type_to_string(*comm_type));
  3324     return status;
  3325 }
  3326 
  3327 
  3328 PEP_STATUS pgp_key_created(PEP_SESSION session, const char *fpr, time_t *created)
  3329 {
  3330     PEP_STATUS status = PEP_STATUS_OK;
  3331     pgp_cert_t cert = NULL;
  3332     T("(%s)", fpr);
  3333 
  3334     *created = 0;
  3335 
  3336     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  3337     status = cert_find_by_fpr(session, pgp_fpr, false, &cert, NULL);
  3338     pgp_fingerprint_free(pgp_fpr);
  3339     ERROR_OUT(NULL, status, "Looking up %s", fpr);
  3340 
  3341     pgp_key_t k = pgp_cert_primary_key(cert);
  3342     *created = pgp_key_creation_time(k);
  3343     pgp_cert_free(cert);
  3344 
  3345  out:
  3346     T("(%s) -> %s", fpr, pEp_status_to_string(status));
  3347     return status;
  3348 }
  3349 
  3350 PEP_STATUS pgp_binary(const char **path)
  3351 {
  3352     *path = NULL;
  3353     return PEP_STATUS_OK;
  3354 }
  3355 
  3356 PEP_STATUS pgp_contains_priv_key(PEP_SESSION session, const char *fpr,
  3357                                  bool *has_private)
  3358 {
  3359     T("(%s)", fpr);
  3360     pgp_fingerprint_t pgp_fpr = pgp_fingerprint_from_hex(fpr);
  3361     PEP_STATUS status = cert_find_by_fpr(session, pgp_fpr, true, NULL, NULL);
  3362     pgp_fingerprint_free(pgp_fpr);
  3363     if (status == PEP_STATUS_OK) {
  3364         *has_private = 1;
  3365     } else if (status == PEP_KEY_NOT_FOUND) {
  3366         *has_private = 0;
  3367         status = PEP_STATUS_OK;
  3368     }
  3369     T("(%s) -> %s, %s",
  3370       fpr, *has_private ? "priv" : "pub", pEp_status_to_string(status));
  3371     return status;
  3372 }