src/pEpEngine.c
author Volker Birk <vb@pep-project.org>
Tue, 21 May 2019 07:04:51 +0200
branchsync
changeset 3739 523fb9710660
parent 3720 9ed76a79d784
child 3740 248166aa4ab2
child 3747 82fe58af7b53
child 3750 318c86bc30b0
permissions -rw-r--r--
spinlock implementation for dealing with write locks
     1 // This file is under GNU General Public License 3.0
     2 // see LICENSE.txt
     3 
     4 #include "pEp_internal.h"
     5 #include "dynamic_api.h"
     6 #include "cryptotech.h"
     7 #include "transport.h"
     8 #include "blacklist.h"
     9 #include "KeySync_fsm.h"
    10 
    11 #include <time.h>
    12 #include <stdlib.h>
    13 
    14 #define _PEP_SQLITE_DEBUG 0
    15 #if _PEP_SQLITE_DEBUG
    16 #include <sqlite3.h>
    17 #endif
    18 
    19 static volatile int init_count = -1;
    20 
    21 // sql overloaded functions - modified from sqlite3.c
    22 static void _sql_lower(sqlite3_context* ctx, int argc, sqlite3_value** argv) {
    23     const char *z2;
    24     int n;
    25     z2 = (char*)sqlite3_value_text(argv[0]);
    26     n = sqlite3_value_bytes(argv[0]);
    27     /* Verify that the call to _bytes() does not invalidate the _text() pointer */
    28     assert( z2==(char*)sqlite3_value_text(argv[0]) );
    29     if( z2 ){
    30         char *z1 = (char*)sqlite3_malloc(n+1);
    31         if( z1 ){
    32             for(int i=0; i<n; i++){
    33                 char c = z2[i];
    34                 char c_mod = c | 0x20;
    35                 if (c_mod < 0x61 || c_mod > 0x7a)
    36                     c_mod = c;
    37                 z1[i] = c_mod;
    38             }
    39             z1[n] = '\0';
    40             sqlite3_result_text(ctx, z1, n, sqlite3_free);
    41         }
    42     }
    43 }
    44 
    45 #if _PEP_SQLITE_DEBUG
    46 int sql_trace_callback (unsigned trace_constant, 
    47                         void* context_ptr,
    48                         void* P,
    49                         void* X) {
    50     switch (trace_constant) {
    51         case SQLITE_TRACE_STMT:
    52             fprintf(stderr, "SQL_DEBUG: STMT - ");
    53             const char* X_str = (const char*) X;
    54             if (!EMPTYSTR(X_str) && X_str[0] == '-' && X_str[1] == '-')
    55                 fprintf(stderr, "%s\n", X_str);
    56             else
    57                 fprintf(stderr, "%s\n", sqlite3_expanded_sql((sqlite3_stmt*)P));
    58             break;
    59         case SQLITE_TRACE_ROW:
    60             fprintf(stderr, "SQL_DEBUG: ROW - ");
    61             fprintf(stderr, "%s\n", sqlite3_expanded_sql((sqlite3_stmt*)P));
    62             break;            
    63         case SQLITE_TRACE_CLOSE:
    64             fprintf(stderr, "SQL_DEBUG: CLOSE - ");
    65             break;
    66         default:
    67             break;
    68     }
    69     return 0;
    70 }
    71 #endif
    72 
    73 // sql manipulation statements
    74 static const char *sql_log = 
    75     "insert into log (title, entity, description, comment)"
    76      "values (?1, ?2, ?3, ?4);";
    77 
    78 static const char *sql_trustword = 
    79     "select id, word from wordlist where lang = lower(?1) "
    80     "and id = ?2 ;";
    81 
    82 // FIXME?: problems if we don't have a key for the user - we get nothing
    83 static const char *sql_get_identity =  
    84     "select fpr, username, comm_type, lang,"
    85     "   identity.flags | pgp_keypair.flags,"
    86     "   is_own"
    87     "   from identity"
    88     "   join person on id = identity.user_id"
    89     "   join pgp_keypair on fpr = identity.main_key_id"
    90     "   join trust on id = trust.user_id"
    91     "       and pgp_keypair_fpr = identity.main_key_id"    
    92     "   where (case when (address = ?1) then (1)"
    93     "               when (lower(address) = lower(?1)) then (1)"
    94     "               when (replace(lower(address),'.','') = replace(lower(?1),'.','')) then (1)"
    95     "               else 0"
    96     "          end) = 1"
    97     "   and identity.user_id = ?2" 
    98     "   order by is_own desc, "
    99     "   timestamp desc; ";
   100 
   101 static const char *sql_get_identities_by_main_key_id =  
   102     "select address, identity.user_id, username, comm_type, lang,"
   103     "   identity.flags | pgp_keypair.flags,"
   104     "   is_own"
   105     "   from identity"
   106     "   join person on id = identity.user_id"
   107     "   join pgp_keypair on fpr = identity.main_key_id"
   108     "   join trust on id = trust.user_id"
   109     "       and pgp_keypair_fpr = identity.main_key_id"    
   110     "   where identity.main_key_id = ?1" 
   111     "   order by is_own desc, "
   112     "   timestamp desc; ";
   113 
   114 static const char *sql_get_identity_without_trust_check =  
   115     "select identity.main_key_id, username, lang,"
   116     "   identity.flags, is_own"
   117     "   from identity"
   118     "   join person on id = identity.user_id"
   119     "   where (case when (address = ?1) then (1)"
   120     "               when (lower(address) = lower(?1)) then (1)"
   121     "               when (replace(lower(address),'.','') = replace(lower(?1),'.','')) then (1)"
   122     "               else 0"
   123     "          end) = 1"
   124     "   and identity.user_id = ?2 "
   125     "   order by is_own desc, "
   126     "   timestamp desc; ";
   127 
   128 static const char *sql_get_identities_by_address =  
   129     "select user_id, identity.main_key_id, username, lang,"
   130     "   identity.flags, is_own"
   131     "   from identity"
   132     "   join person on id = identity.user_id"
   133     "   where (case when (address = ?1) then (1)"
   134     "               when (lower(address) = lower(?1)) then (1)"
   135     "               when (replace(lower(address),'.','') = replace(lower(?1),'.','')) then (1)"
   136     "               else 0"
   137     "          end) = 1 "
   138     "   order by is_own desc, "
   139     "   timestamp desc; ";
   140     
   141 static const char *sql_get_identities_by_userid =  
   142     "select address, fpr, username, comm_type, lang,"
   143     "   identity.flags | pgp_keypair.flags,"
   144     "   is_own"
   145     "   from identity"
   146     "   join person on id = identity.user_id"
   147     "   join pgp_keypair on fpr = identity.main_key_id"
   148     "   join trust on id = trust.user_id"
   149     "       and pgp_keypair_fpr = identity.main_key_id"    
   150     "   where identity.user_id = ?1" 
   151     "   order by is_own desc, "
   152     "   timestamp desc; ";
   153 
   154 static const char *sql_replace_identities_fpr =  
   155     "update identity"
   156     "   set main_key_id = ?1 "
   157     "   where main_key_id = ?2 ;";
   158     
   159 static const char *sql_remove_fpr_as_default =
   160     "update person set main_key_id = NULL where main_key_id = ?1 ;"
   161     "update identity set main_key_id = NULL where main_key_id = ?1 ;";
   162 
   163 // Set person, but if already exist, only update.
   164 // if main_key_id already set, don't touch.
   165 static const char *sql_set_person = 
   166      "insert into person (id, username, lang, main_key_id)"
   167      "  values (?1, ?2, ?3, ?4) ;";
   168 
   169 static const char *sql_update_person = 
   170     "update person "
   171     "   set username = ?2, "
   172     "       lang = ?3, "
   173     "       main_key_id =  "
   174     "           (select coalesce( "
   175     "               (select main_key_id from person where id = ?1), " 
   176     "                upper(replace(?4,' ',''))))"         
   177     "   where id = ?1 ;";
   178 
   179 // Will cascade.
   180 static const char *sql_delete_person = 
   181      "delete from person where id = ?1 ;";
   182 
   183 static const char *sql_set_as_pEp_user =
   184     "update person set is_pEp_user = 1 "
   185     "   where id = ?1 ; ";
   186 
   187 static const char *sql_is_pEp_user =
   188     "select is_pEp_user from person "
   189     "   where id = ?1 ; ";
   190 
   191 static const char* sql_exists_person = 
   192     "select count(*) from person "
   193     "   where id = ?1 ;";
   194 
   195 // This will cascade to identity and trust
   196 static const char* sql_replace_userid =
   197     "update person set id = ?1 " 
   198     "   where id = ?2;";
   199 
   200 // Hopefully this cascades and removes trust entries...
   201 static const char *sql_delete_key =
   202     "delete from pgp_keypair "
   203     "   where fpr = ?1 ; ";
   204 
   205 static const char *sql_replace_main_user_fpr =  
   206     "update person "
   207     "   set main_key_id = ?1 "
   208     "   where id = ?2 ;";
   209 
   210 static const char *sql_get_main_user_fpr =  
   211     "select main_key_id from person"
   212     "   where id = ?1 ;";
   213 
   214 static const char *sql_refresh_userid_default_key =
   215     "update person "
   216     "   set main_key_id = "
   217     "       (select identity.main_key_id from identity "
   218     "           join trust on trust.user_id = identity.user_id "
   219     "               and trust.pgp_keypair_fpr = identity.main_key_id "
   220     "           join person on identity.user_id = identity.user_id "
   221     "       where identity.user_id = ?1 "
   222     "       order by trust.comm_type desc "
   223     "       limit 1) "
   224     "where id = ?1 ; ";
   225 
   226 static const char *sql_set_pgp_keypair = 
   227     "insert or ignore into pgp_keypair (fpr) "
   228     "values (upper(replace(?1,' ',''))) ;";
   229 
   230 static const char* sql_exists_identity_entry = 
   231     "select count(*) from identity "
   232     "   where (case when (address = ?1) then (1)"
   233     "               when (lower(address) = lower(?1)) then (1)"
   234     "               when (replace(lower(address),'.','') = replace(lower(?1),'.','')) then (1)"
   235     "               else 0"
   236     "          end) = 1"
   237     "    and user_id = ?2;";
   238  
   239 static const char *sql_set_identity_entry = 
   240     "insert into identity ("
   241     "       address, main_key_id, "
   242     "       user_id, flags, is_own"
   243     "   ) values ("
   244     "       ?1,"
   245     "       upper(replace(?2,' ','')),"
   246     "       ?3,"
   247     "       ?4,"
   248     "       ?5"
   249     "   );";
   250     
   251 static const char* sql_update_identity_entry =    
   252     "update identity "
   253     "   set main_key_id = upper(replace(?2,' ','')), "
   254     "       flags = ?4, " 
   255     "       is_own = ?5 "
   256     "   where (case when (address = ?1) then (1)"
   257     "               when (lower(address) = lower(?1)) then (1)"
   258     "               when (replace(lower(address),'.','') = replace(lower(?1),'.','')) then (1) "
   259     "               else 0 "
   260     "          end) = 1 "
   261     "          and user_id = ?3 ;";
   262 
   263     // " (select"
   264     // "   coalesce("
   265     // "    (select flags from identity"
   266     // "     where address = ?1 and"
   267     // "           user_id = ?3),"
   268     // "    0)"
   269     // " ) | (?4 & 255)"
   270     /* set_identity ignores previous flags, and doesn't filter machine flags */
   271         
   272 static const char *sql_set_identity_flags = 
   273     "update identity set flags = "
   274     "    ((?1 & 65535) | (select flags from identity"
   275     "                    where (case when (address = ?2) then (1)"
   276     "                                when (lower(address) = lower(?2)) then (1)"
   277     "                                when (replace(lower(address),'.','') = replace(lower(?2),'.','')) then (1)"
   278     "                                else 0 "    
   279     "                           end) = 1 "
   280     "                           and user_id = ?3)) "
   281     "   where (case when (address = ?2) then (1)"
   282     "               when (lower(address) = lower(?2)) then (1)"
   283     "               when (replace(lower(address),'.','') = replace(lower(?2),'.','')) then (1)"
   284     "               else 0"
   285     "          end) = 1"
   286     "          and user_id = ?3 ;";
   287 
   288 static const char *sql_unset_identity_flags = 
   289     "update identity set flags = "
   290     "    ( ~(?1 & 65535) & (select flags from identity"
   291     "                    where (case when (address = ?2) then (1)"
   292     "                                when (lower(address) = lower(?2)) then (1)"
   293     "                                when (replace(lower(address),'.','') = replace(lower(?2),'.','')) then (1)"
   294     "                                else 0 "    
   295     "                           end) = 1 "
   296     "                           and user_id = ?3)) "
   297     "   where (case when (address = ?2) then (1)"
   298     "               when (lower(address) = lower(?2)) then (1)"
   299     "               when (replace(lower(address),'.','') = replace(lower(?2),'.','')) then (1)"
   300     "               else 0"
   301     "          end) = 1"
   302     "          and user_id = ?3 ;";
   303 
   304 static const char *sql_set_trust =
   305     "insert into trust (user_id, pgp_keypair_fpr, comm_type) "
   306     "values (?1, upper(replace(?2,' ','')), ?3) ;";
   307 
   308 static const char *sql_update_trust =
   309     "update trust set comm_type = ?3 " 
   310     "   where user_id = ?1 and pgp_keypair_fpr = upper(replace(?2,' ',''));";
   311 
   312 static const char *sql_update_trust_to_pEp =
   313     "update trust set comm_type = comm_type + 71 "
   314     "   where (user_id = ?1 "
   315     "          and (case when (comm_type = 56) then (1) "
   316     "                    when (comm_type = 184) then (1) "
   317     "                    else 0"
   318     "               end) = 1); ";
   319 
   320 static const char* sql_exists_trust_entry = 
   321     "select count(*) from trust "
   322     "   where user_id = ?1 and pgp_keypair_fpr = upper(replace(?2,' ',''));";
   323     
   324 static const char *sql_update_trust_for_fpr =
   325     "update trust "
   326     "set comm_type = ?1 "
   327     "where pgp_keypair_fpr = upper(replace(?2,' ','')) ;";
   328 
   329 static const char *sql_get_trust = 
   330     "select comm_type from trust where user_id = ?1 "
   331     "and pgp_keypair_fpr = upper(replace(?2,' ','')) ;";
   332 
   333 static const char *sql_get_trust_by_userid = 
   334     "select pgp_keypair_fpr, comm_type from trust where user_id = ?1 ";
   335 
   336 static const char *sql_least_trust = 
   337     "select min(comm_type) from trust where"
   338     " pgp_keypair_fpr = upper(replace(?1,' ',''))"
   339     " and comm_type != 0;"; // ignores PEP_ct_unknown
   340     // returns PEP_ct_unknown only when no known trust is recorded
   341 
   342 static const char *sql_mark_as_compromised = 
   343     "update trust not indexed set comm_type = 15"
   344     " where pgp_keypair_fpr = upper(replace(?1,' ','')) ;";
   345     
   346 static const char *sql_crashdump = 
   347     "select timestamp, title, entity, description, comment"
   348     " from log order by timestamp desc limit ?1 ;";
   349 
   350 static const char *sql_languagelist = 
   351     "select i18n_language.lang, name, phrase" 
   352     " from i18n_language join i18n_token using (lang) where i18n_token.id = 1000;" ;
   353 
   354 static const char *sql_i18n_token = 
   355     "select phrase from i18n_token where lang = lower(?1) and id = ?2 ;";
   356 
   357 // blacklist
   358 static const char *sql_blacklist_add = 
   359     "insert or ignore into blacklist_keys (fpr) values (upper(replace(?1,' ',''))) ;"
   360     "delete from identity where main_key_id = upper(replace(?1,' ','')) ;"
   361     "delete from pgp_keypair where fpr = upper(replace(?1,' ','')) ;";
   362 
   363 static const char *sql_blacklist_delete =
   364     "delete from blacklist_keys where fpr = upper(replace(?1,' ','')) ;";
   365 
   366 static const char *sql_blacklist_is_listed = 
   367     "select count(*) from blacklist_keys where fpr = upper(replace(?1,' ','')) ;";
   368 
   369 static const char *sql_blacklist_retrieve = 
   370     "select * from blacklist_keys ;";
   371                 
   372 
   373 // Own keys
   374 // We only care if it's 0 or non-zero
   375 static const char *sql_own_key_is_listed = 
   376     "select count(*) from ("
   377     "   select pgp_keypair_fpr from trust"
   378     "      join identity on trust.user_id = identity.user_id"
   379     "      where pgp_keypair_fpr = upper(replace(?1,' ',''))"
   380     "           and identity.is_own = 1"
   381     ");";
   382     
   383 static const char *sql_is_own_address =
   384     "select count(*) from ("
   385     "   select address from identity"
   386     "       where (case when (address = ?1) then (1)"
   387     "                   when (lower(address) = lower(?1)) then (1)"
   388     "                   when (replace(lower(address),'.','') = replace(lower(?1),'.','')) then (1)"
   389     "                   else 0"
   390     "           end) = 1 "
   391     "           and identity.is_own = 1"
   392     ");";
   393 
   394 static const char *sql_own_identities_retrieve =  
   395     "select address, fpr, identity.user_id, username,"
   396     "   lang, identity.flags | pgp_keypair.flags"
   397     "   from identity"
   398     "   join person on id = identity.user_id"
   399     "   join pgp_keypair on fpr = identity.main_key_id"
   400     "   join trust on id = trust.user_id"
   401     "       and pgp_keypair_fpr = identity.main_key_id"
   402     "   where identity.is_own = 1"
   403     "       and (identity.flags & ?1) = 0;";
   404 
   405 static const char *sql_own_keys_retrieve = 
   406     "select pgp_keypair_fpr from trust"
   407     "   join identity on trust.user_id = identity.user_id"
   408     "   where identity.is_own = 1";
   409 
   410 static const char* sql_get_user_default_key =
   411     "select main_key_id from person" 
   412     "   where id = ?1;";
   413 
   414 static const char* sql_get_all_keys_for_user =
   415     "select pgp_keypair_fpr from trust"
   416     "   where user_id = ?1; ";
   417 
   418 static const char* sql_get_default_own_userid =
   419     "select id from person"
   420     "   join identity on id = identity.user_id"
   421     "   where identity.is_own = 1";
   422 
   423 // Sequence
   424 static const char *sql_sequence_value1 = 
   425     "insert or replace into sequences (name, value) "
   426     "values (?1, "
   427     "       (select coalesce((select value + 1 from sequences "
   428     "           where name = ?1), 1 ))); ";
   429 
   430 static const char *sql_sequence_value2 = 
   431     "select value from sequences where name = ?1 ;";
   432 
   433 // Revocation tracking
   434 static const char *sql_set_revoked =
   435     "insert or replace into revoked_keys ("
   436     "    revoked_fpr, replacement_fpr, revocation_date) "
   437     "values (upper(replace(?1,' ','')),"
   438     "        upper(replace(?2,' ','')),"
   439     "        ?3) ;";
   440         
   441 static const char *sql_get_revoked = 
   442     "select revoked_fpr, revocation_date from revoked_keys"
   443     "    where replacement_fpr = upper(replace(?1,' ','')) ;";
   444 
   445 static const char *sql_get_replacement_fpr = 
   446     "select replacement_fpr, revocation_date from revoked_keys"
   447     "    where revoked_fpr = upper(replace(?1,' ','')) ;";
   448 
   449 static const char *sql_get_userid_alias_default =
   450     "select default_id from alternate_user_id "
   451     "   where alternate_id = ?1 ; ";
   452 
   453 // Revocation tracking
   454 static const char *sql_add_mistrusted_key =
   455     "insert or replace into mistrusted_keys (fpr) "
   456     "   values (upper(replace(?1,' ',''))) ;";
   457         
   458 static const char *sql_delete_mistrusted_key = 
   459     "delete from mistrusted_keys where fpr = upper(replace(?1,' ','')) ;";
   460 
   461 static const char *sql_is_mistrusted_key = 
   462     "select count(*) from mistrusted_keys where fpr = upper(replace(?1,' ','')) ;";
   463 
   464 static const char *sql_add_userid_alias =
   465     "insert or replace into alternate_user_id (alternate_id, default_id) "
   466     "values (?2, ?1) ;";
   467 
   468 static const char *sql_add_into_social_graph =
   469     "insert or replace into social_graph(own_userid, own_address, contact_userid) "
   470     "values (?1, ?2, ?3) ;";
   471 
   472 static const char *sql_get_own_address_binding_from_contact =
   473     "select own_address from social_graph where own_userid = ?1 and contact_userid = ?2 ;";
   474 
   475 static const char *sql_set_revoke_contact_as_notified =
   476     "insert or replace into revocation_contact_list(fpr, contact_id) values (?1, ?2) ;";
   477     
   478 static const char *sql_get_contacted_ids_from_revoke_fpr =
   479     "select * from revocation_contact_list where fpr = ?1 ;";
   480 
   481 static const char *sql_was_id_for_revoke_contacted = 
   482     "select count(*) from revocation_contact_list where fpr = ?1 and contact_id = ?2 ;";
   483 
   484 // We only need user_id and address, since in the main usage, we'll call update_identity
   485 // on this anyway when sending out messages.
   486 static const char *sql_get_last_contacted =
   487     "select user_id, address from identity where datetime('now') < datetime(timestamp, '+14 days') ; ";
   488     
   489 static int user_version(void *_version, int count, char **text, char **name)
   490 {
   491     assert(_version);
   492     assert(count == 1);
   493     assert(text && text[0]);
   494     if (!(_version && count == 1 && text && text[0]))
   495         return -1;
   496 
   497     int *version = (int *) _version;
   498     *version = atoi(text[0]);
   499     return 0;
   500 }
   501 
   502 // TODO: refactor and generalise these two functions if possible.
   503 static int db_contains_table(PEP_SESSION session, const char* table_name) {
   504     if (!session || !table_name)
   505         return -1;
   506     
   507     // Table names can't be SQL parameters, so we do it this way.
   508     
   509     // these two must be the same number.
   510     char sql_buf[500];
   511     const size_t max_q_len = 500;
   512     
   513     size_t t_size, q_size;
   514     
   515     const char* q1 = "SELECT name FROM sqlite_master WHERE type='table' AND name='{"; // 61
   516     const char* q2 = "}';";       // 3
   517     
   518     q_size = 64;
   519     t_size = strlen(table_name);
   520     
   521     size_t query_len = q_size + t_size + 1;
   522 
   523     if (query_len > max_q_len)
   524         return -1;
   525 
   526     strlcpy(sql_buf, q1, max_q_len);
   527     strlcat(sql_buf, table_name, max_q_len);
   528     strlcat(sql_buf, q2, max_q_len);
   529 
   530     sqlite3_stmt *stmt; 
   531 
   532     sqlite3_prepare_v2(session->db, sql_buf, -1, &stmt, NULL);
   533 
   534     int retval = 0;
   535 
   536     int rc = Sqlite3_step(stmt);  
   537     if (rc == SQLITE_DONE || rc == SQLITE_OK || rc == SQLITE_ROW) {
   538         retval = 1;
   539     }
   540 
   541     sqlite3_finalize(stmt);      
   542         
   543     return retval;
   544         
   545 }
   546 
   547 static int table_contains_column(PEP_SESSION session, const char* table_name,
   548                                                       const char* col_name) {
   549 
   550 
   551     if (!session || !table_name || !col_name)
   552         return -1;
   553         
   554     // Table names can't be SQL parameters, so we do it this way.
   555     
   556     // these two must be the same number.
   557     char sql_buf[500];
   558     const size_t max_q_len = 500;
   559     
   560     size_t t_size, c_size, q_size;
   561     
   562     const char* q1 = "SELECT "; // 7
   563     const char* q2 = " from "; // 6
   564     const char* q3 = ";";       // 1
   565     
   566     q_size = 14;
   567     t_size = strlen(table_name);
   568     c_size = strlen(col_name);
   569     
   570     size_t query_len = q_size + c_size + t_size + 1;
   571     
   572     if (query_len > max_q_len)
   573         return -1;
   574 
   575     strlcpy(sql_buf, q1, max_q_len);
   576     strlcat(sql_buf, col_name, max_q_len);
   577     strlcat(sql_buf, q2, max_q_len);
   578     strlcat(sql_buf, table_name, max_q_len);
   579     strlcat(sql_buf, q3, max_q_len);
   580 
   581     sqlite3_stmt *stmt; 
   582 
   583     sqlite3_prepare_v2(session->db, sql_buf, -1, &stmt, NULL);
   584 
   585     int retval = 0;
   586 
   587     int rc = Sqlite3_step(stmt);  
   588     if (rc == SQLITE_DONE || rc == SQLITE_OK || rc == SQLITE_ROW) {
   589         retval = 1;
   590     }
   591 
   592     sqlite3_finalize(stmt);      
   593         
   594     return retval;
   595 }
   596 
   597 PEP_STATUS repair_altered_tables(PEP_SESSION session) {
   598     PEP_STATUS status = PEP_STATUS_OK;
   599     
   600     const unsigned int _PEP_MAX_AFFECTED = 5;
   601     char** table_names = calloc(_PEP_MAX_AFFECTED, sizeof(char*));
   602     if (!table_names)
   603         return PEP_OUT_OF_MEMORY;
   604 
   605     const char* sql_query = "select tbl_name from sqlite_master WHERE sql LIKE '%REFERENCES%' AND sql LIKE '%_old%';";
   606     sqlite3_stmt *stmt; 
   607     sqlite3_prepare_v2(session->db, sql_query, -1, &stmt, NULL);
   608     int i = 0;
   609     int int_result = 0;
   610     while ((int_result = Sqlite3_step(stmt)) == SQLITE_ROW && i < _PEP_MAX_AFFECTED) {
   611         table_names[i++] = strdup((const char*)(sqlite3_column_text(stmt, 0)));
   612     }
   613     
   614     sqlite3_finalize(stmt);      
   615 
   616     if ((int_result != SQLITE_DONE && int_result != SQLITE_OK) || i > (_PEP_MAX_AFFECTED + 1)) {
   617         status = PEP_UNKNOWN_DB_ERROR;
   618         goto pEp_free;
   619     }
   620         
   621     for (i = 0; i < _PEP_MAX_AFFECTED; i++) {
   622         const char* table_name = table_names[i];
   623         if (!table_name)
   624             break;
   625             
   626         if (strcmp(table_name, "identity") == 0) {
   627             int_result = sqlite3_exec(session->db,
   628                 "PRAGMA foreign_keys=off;\n"
   629                 "BEGIN TRANSACTION;\n"
   630                 "create table _identity_new (\n"
   631                 "   address text,\n"
   632                 "   user_id text\n"
   633                 "       references person (id)\n"
   634                 "       on delete cascade on update cascade,\n"
   635                 "   main_key_id text\n"
   636                 "       references pgp_keypair (fpr)\n"
   637                 "       on delete set null,\n"
   638                 "   comment text,\n"
   639                 "   flags integer default 0,\n"
   640                 "   is_own integer default 0,\n"
   641                 "   timestamp integer default (datetime('now')),\n"
   642                 "   primary key (address, user_id)\n"
   643                 ");\n"
   644                 "INSERT INTO _identity_new SELECT * from identity;\n"
   645                 "DROP TABLE identity;\n"
   646                 "ALTER TABLE _identity_new RENAME TO identity;\n"
   647                 "COMMIT;\n"
   648                 "PRAGMA foreign_keys=on;"
   649                 ,
   650                 NULL,
   651                 NULL,
   652                 NULL
   653             );
   654             assert(int_result == PEP_STATUS_OK);
   655         }
   656         else if (strcmp(table_name, "trust") == 0) {
   657             int_result = sqlite3_exec(session->db,
   658                 "PRAGMA foreign_keys=off;\n"
   659                 "BEGIN TRANSACTION;\n"
   660                 "create table _trust_new (\n"
   661                 "   user_id text not null\n"
   662                 "       references person (id)\n"
   663                 "       on delete cascade on update cascade,\n"
   664                 "   pgp_keypair_fpr text not null\n"
   665                 "       references pgp_keypair (fpr)\n"
   666                 "       on delete cascade,\n"
   667                 "   comm_type integer not null,\n"
   668                 "   comment text,\n"
   669                 "   primary key (user_id, pgp_keypair_fpr)\n"                
   670                 ");\n"
   671                 "INSERT INTO _trust_new SELECT * from trust;\n"
   672                 "DROP TABLE trust;\n"
   673                 "ALTER TABLE _trust_new RENAME TO trust;\n"
   674                 "COMMIT;\n"
   675                 "PRAGMA foreign_keys=on;"
   676                 ,
   677                 NULL,
   678                 NULL,
   679                 NULL
   680             );             
   681             assert(int_result == PEP_STATUS_OK);                       
   682         }
   683         else if (strcmp(table_name, "alternate_user_id") == 0) {
   684             int_result = sqlite3_exec(session->db,
   685                 "PRAGMA foreign_keys=off;\n"
   686                 "BEGIN TRANSACTION;\n"
   687                 "create table _alternate_user_id_new (\n"
   688                 "    default_id text references person (id)\n"
   689                 "       on delete cascade on update cascade,\n"
   690                 "    alternate_id text primary key\n"
   691                 ");\n"
   692                 "INSERT INTO _alternate_user_id_new SELECT * from alternate_user_id;\n"
   693                 "DROP TABLE alternate_user_id;\n"
   694                 "ALTER TABLE _alternate_user_id_new RENAME TO alternate_user_id;\n"
   695                 "COMMIT;\n"
   696                 "PRAGMA foreign_keys=on;"                
   697                 ,
   698                 NULL,
   699                 NULL,
   700                 NULL
   701             );
   702             assert(int_result == PEP_STATUS_OK);
   703         }
   704         else if (strcmp(table_name, "revocation_contact_list") == 0) {
   705             int_result = sqlite3_exec(session->db,
   706                 "PRAGMA foreign_keys=off;\n"
   707                 "BEGIN TRANSACTION;\n"
   708                 "create table _revocation_contact_list_new (\n"
   709                 "   fpr text not null references pgp_keypair (fpr)\n"
   710                 "       on delete cascade,\n"
   711                 "   contact_id text not null references person (id)\n"
   712                 "       on delete cascade on update cascade,\n"
   713                 "   timestamp integer default (datetime('now')),\n"
   714                 "   PRIMARY KEY(fpr, contact_id)\n"            
   715                 ");\n"
   716                 "INSERT INTO _revocation_contact_list_new SELECT * from revocation_contact_list;\n"
   717                 "DROP TABLE revocation_contact_list;\n"
   718                 "ALTER TABLE _revocation_contact_list_new RENAME TO revocation_contact_list;\n"
   719                 "COMMIT;\n"
   720                 "PRAGMA foreign_keys=on;"                
   721                 ,
   722                 NULL,
   723                 NULL,
   724                 NULL
   725             );      
   726             assert(int_result == PEP_STATUS_OK);                              
   727         }
   728         else if (strcmp(table_name, "social_graph")) {
   729             int_result = sqlite3_exec(session->db,
   730                 "PRAGMA foreign_keys=off;\n"
   731                 "BEGIN TRANSACTION;\n"
   732                 "create table _social_new (\n"
   733                 "    own_userid text,\n"
   734                 "    own_address text,\n"
   735                 "    contact_userid text,\n"
   736                 "    CONSTRAINT fk_own_identity\n"
   737                 "       FOREIGN KEY(own_address, own_userid)\n" 
   738                 "       REFERENCES identity(address, user_id)\n"
   739                 "       ON DELETE CASCADE ON UPDATE CASCADE\n"
   740                 ");\n"
   741                 "INSERT INTO _social_graph_new SELECT * from social_graph;\n"
   742                 "DROP TABLE social_graph;\n"
   743                 "ALTER TABLE _social_graph_new RENAME TO social_graph;\n"
   744                 "COMMIT;\n"
   745                 "PRAGMA foreign_keys=on;"                
   746                 ,
   747                 NULL,
   748                 NULL,
   749                 NULL
   750             );
   751             assert(int_result == PEP_STATUS_OK);                                    
   752         }        
   753     }
   754     
   755     int_result = sqlite3_exec(
   756         session->db,
   757         "PRAGMA foreign_key_check;\n"
   758         ,
   759         NULL,
   760         NULL,
   761         NULL
   762     );
   763     assert(int_result == SQLITE_OK);
   764 
   765 pEp_free:
   766     for (i = 0; i < _PEP_MAX_AFFECTED; i++) {
   767         if (table_names[i])
   768             free(table_names[i]);
   769         else
   770             break;
   771     }
   772     free(table_names);
   773     return status;
   774 }
   775 void errorLogCallback(void *pArg, int iErrCode, const char *zMsg){
   776   fprintf(stderr, "(%d) %s\n", iErrCode, zMsg);
   777 }
   778 
   779 #ifdef USE_GPG
   780 PEP_STATUS pgp_import_ultimately_trusted_keypairs(PEP_SESSION session);
   781 #endif // USE_GPG
   782 
   783 DYNAMIC_API PEP_STATUS init(
   784         PEP_SESSION *session,
   785         messageToSend_t messageToSend,
   786         inject_sync_event_t inject_sync_event
   787     )
   788 {
   789     PEP_STATUS status = PEP_STATUS_OK;
   790     int int_result;
   791     
   792     bool in_first = false;
   793     bool very_first = false;
   794 
   795     assert(sqlite3_threadsafe());
   796     if (!sqlite3_threadsafe())
   797         return PEP_INIT_SQLITE3_WITHOUT_MUTEX;
   798 
   799     // a little race condition - but still a race condition
   800     // mitigated by calling caveat (see documentation)
   801 
   802     // this increment is made atomic IN THE ADAPTERS by
   803     // guarding the call to init with the appropriate mutex.
   804     int _count = ++init_count;
   805     if (_count == 0)
   806         in_first = true;
   807     
   808     // Race condition mitigated by calling caveat starts here :
   809     // If another call to init() preempts right now, then preemptive call
   810     // will have in_first false, will not create SQL tables, and following
   811     // calls relying on those tables will fail.
   812     //
   813     // Therefore, as above, adapters MUST guard init() with a mutex.
   814     // 
   815     // Therefore, first session
   816     // is to be created and last session to be deleted alone, and not
   817     // concurently to other sessions creation or deletion.
   818     // We expect adapters to enforce this either by implicitely creating a
   819     // client session, or by using synchronization primitive to protect
   820     // creation/deletion of first/last session from the app.
   821 
   822     assert(session);
   823     if (session == NULL)
   824         return PEP_ILLEGAL_VALUE;
   825 
   826     *session = NULL;
   827 
   828     pEpSession *_session = calloc(1, sizeof(pEpSession));
   829     assert(_session);
   830     if (_session == NULL)
   831         goto enomem;
   832 
   833     _session->version = PEP_ENGINE_VERSION;
   834     _session->messageToSend = messageToSend;
   835     _session->inject_sync_event = inject_sync_event;
   836 
   837 #ifdef DEBUG_ERRORSTACK
   838     _session->errorstack = new_stringlist("init()");
   839 #endif
   840 
   841     assert(LOCAL_DB);
   842     if (LOCAL_DB == NULL) {
   843         status = PEP_INIT_CANNOT_OPEN_DB;
   844         goto pEp_error;
   845     }
   846     
   847 #if _PEP_SQLITE_DEBUG    
   848     sqlite3_config(SQLITE_CONFIG_LOG, errorLogCallback, NULL);
   849 #endif
   850 
   851     int_result = sqlite3_open_v2(
   852             LOCAL_DB,
   853             &_session->db,
   854             SQLITE_OPEN_READWRITE
   855                 | SQLITE_OPEN_CREATE
   856                 | SQLITE_OPEN_FULLMUTEX
   857                 | SQLITE_OPEN_PRIVATECACHE,
   858             NULL 
   859         );
   860 
   861     if (int_result != SQLITE_OK) {
   862         status = PEP_INIT_CANNOT_OPEN_DB;
   863         goto pEp_error;
   864     }
   865 
   866     int_result = sqlite3_exec(
   867             _session->db,
   868             "PRAGMA locking_mode=NORMAL;\n"
   869             "PRAGMA journal_mode=WAL;\n",
   870             NULL,
   871             NULL,
   872             NULL
   873         );
   874 
   875 
   876     sqlite3_busy_timeout(_session->db, BUSY_WAIT_TIME);
   877 
   878 #if _PEP_SQLITE_DEBUG
   879     sqlite3_trace_v2(_session->db, 
   880         SQLITE_TRACE_STMT | SQLITE_TRACE_ROW | SQLITE_TRACE_CLOSE,
   881         sql_trace_callback,
   882         NULL);
   883 #endif
   884 
   885     assert(SYSTEM_DB);
   886     if (SYSTEM_DB == NULL) {
   887         status = PEP_INIT_CANNOT_OPEN_SYSTEM_DB;
   888         goto pEp_error;
   889     }
   890 
   891     int_result = sqlite3_open_v2(
   892             SYSTEM_DB, &_session->system_db,
   893             SQLITE_OPEN_READONLY
   894                 | SQLITE_OPEN_FULLMUTEX
   895                 | SQLITE_OPEN_SHAREDCACHE,
   896             NULL
   897         );
   898 
   899     if (int_result != SQLITE_OK) {
   900         status = PEP_INIT_CANNOT_OPEN_SYSTEM_DB;
   901         goto pEp_error;
   902     }
   903 
   904     sqlite3_busy_timeout(_session->system_db, 1000);
   905 
   906 // increment this when patching DDL
   907 #define _DDL_USER_VERSION "11"
   908 
   909     if (in_first) {
   910 
   911         int_result = sqlite3_exec(
   912             _session->db,
   913                 "create table if not exists version_info (\n"
   914                 "   id integer primary key,\n"
   915                 "   timestamp integer default (datetime('now')),\n"
   916                 "   version text,\n"
   917                 "   comment text\n"
   918                 ");\n",
   919                 NULL,
   920                 NULL,
   921                 NULL
   922         );
   923         int_result = sqlite3_exec(
   924             _session->db,
   925                 "PRAGMA application_id = 0x23423423;\n"
   926                 "create table if not exists log (\n"
   927                 "   timestamp integer default (datetime('now')),\n"
   928                 "   title text not null,\n"
   929                 "   description text,\n"
   930                 "   entity text not null,\n"
   931                 "   comment text\n"
   932                 ");\n"
   933                 "create index if not exists log_timestamp on log (\n"
   934                 "   timestamp\n"
   935                 ");\n"
   936                 "create table if not exists pgp_keypair (\n"
   937                 "   fpr text primary key,\n"
   938                 "   created integer,\n"
   939                 "   expires integer,\n"
   940                 "   comment text,\n"
   941                 "   flags integer default 0\n"
   942                 ");\n"
   943                 "create index if not exists pgp_keypair_expires on pgp_keypair (\n"
   944                 "   expires\n"
   945                 ");\n"
   946                 "create table if not exists person (\n"
   947                 "   id text primary key,\n"
   948                 "   username text not null,\n"
   949                 "   main_key_id text\n"
   950                 "       references pgp_keypair (fpr)\n"
   951                 "       on delete set null,\n"
   952                 "   lang text,\n"
   953                 "   comment text,\n"
   954 //                "   device_group text,\n"
   955                 "   is_pEp_user integer default 0\n"
   956                 ");\n"
   957                 "create table if not exists identity (\n"
   958                 "   address text,\n"
   959                 "   user_id text\n"
   960                 "       references person (id)\n"
   961                 "       on delete cascade on update cascade,\n"
   962                 "   main_key_id text\n"
   963                 "       references pgp_keypair (fpr)\n"
   964                 "       on delete set null,\n"
   965                 "   comment text,\n"
   966                 "   flags integer default 0,\n"
   967                 "   is_own integer default 0,\n"
   968                 "   timestamp integer default (datetime('now')),\n"
   969                 "   primary key (address, user_id)\n"
   970                 ");\n"
   971                 "create table if not exists trust (\n"
   972                 "   user_id text not null\n"
   973                 "       references person (id)\n"
   974                 "       on delete cascade on update cascade,\n"
   975                 "   pgp_keypair_fpr text not null\n"
   976                 "       references pgp_keypair (fpr)\n"
   977                 "       on delete cascade,\n"
   978                 "   comm_type integer not null,\n"
   979                 "   comment text,\n"
   980                 "   primary key (user_id, pgp_keypair_fpr)\n"
   981                 ");\n"
   982                 // blacklist
   983                 "create table if not exists blacklist_keys (\n"
   984                 "   fpr text primary key\n"
   985                 ");\n"
   986                 // sequences
   987                 "create table if not exists sequences(\n"
   988                 "   name text primary key,\n"
   989                 "   value integer default 0\n"
   990                 ");\n"
   991                 "create table if not exists revoked_keys (\n"
   992                 "   revoked_fpr text primary key,\n"
   993                 "   replacement_fpr text not null\n"
   994                 "       references pgp_keypair (fpr)\n"
   995                 "       on delete cascade,\n"
   996                 "   revocation_date integer\n"
   997                 ");\n"
   998                 // user id aliases
   999                 "create table if not exists alternate_user_id (\n"
  1000                 "    default_id text references person (id)\n"
  1001                 "       on delete cascade on update cascade,\n"
  1002                 "    alternate_id text primary key\n"
  1003                 ");\n"
  1004                 // mistrusted keys
  1005                 "create table if not exists mistrusted_keys (\n"
  1006                 "    fpr text primary key\n"
  1007                 ");\n"
  1008                 // social graph for key resets
  1009                 "create table if not exists social_graph (\n"
  1010                 "    own_userid text,\n"
  1011                 "    own_address text,\n"
  1012                 "    contact_userid text,\n"
  1013                 "    CONSTRAINT fk_own_identity\n"
  1014                 "       FOREIGN KEY(own_address, own_userid)\n" 
  1015                 "       REFERENCES identity(address, user_id)\n"
  1016                 "       ON DELETE CASCADE ON UPDATE CASCADE\n"
  1017                 ");\n"
  1018                 // list of user_ids sent revocation
  1019                 "create table if not exists revocation_contact_list (\n"
  1020                 "   fpr text not null references pgp_keypair (fpr)\n"
  1021                 "       on delete cascade,\n"
  1022                 "   contact_id text not null references person (id)\n"
  1023                 "       on delete cascade on update cascade,\n"
  1024                 "   timestamp integer default (datetime('now')),\n"
  1025                 "   PRIMARY KEY(fpr, contact_id)\n"
  1026                 ");\n"
  1027                 ,
  1028             NULL,
  1029             NULL,
  1030             NULL
  1031         );
  1032         assert(int_result == SQLITE_OK);
  1033 
  1034         int version;
  1035         int_result = sqlite3_exec(
  1036             _session->db,
  1037             "pragma user_version;",
  1038             user_version,
  1039             &version,
  1040             NULL
  1041         );
  1042 
  1043         assert(int_result == SQLITE_OK);
  1044         
  1045         void (*xFunc_lower)(sqlite3_context*,int,sqlite3_value**) = &_sql_lower;
  1046         
  1047         int_result = sqlite3_create_function_v2(
  1048             _session->db,
  1049             "lower",
  1050             1,
  1051             SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  1052             NULL,
  1053             xFunc_lower,
  1054             NULL,
  1055             NULL,
  1056             NULL);
  1057         assert(int_result == SQLITE_OK);
  1058 
  1059         int_result = sqlite3_exec(
  1060             _session->db,
  1061             "pragma foreign_keys=ON;\n",
  1062             NULL,
  1063             NULL,
  1064             NULL
  1065         );
  1066 
  1067         assert(int_result == SQLITE_OK);
  1068 
  1069         
  1070         // Sometimes the user_version wasn't set correctly. 
  1071         if (version == 1) {
  1072             bool version_changed = true;
  1073             if (db_contains_table(_session, "social_graph") > 0) {
  1074                 if (!table_contains_column(_session, "person", "device_group"))
  1075                     version = 10;
  1076                 else
  1077                     version = 9;
  1078             }            
  1079             else if (table_contains_column(_session, "identity", "timestamp") > 0) {
  1080                 version = 8;
  1081             }            
  1082             else if (table_contains_column(_session, "person", "is_pEp_user") > 0) {
  1083                 version = 7;
  1084             }            
  1085             else if (table_contains_column(_session, "identity", "is_own") > 0) {
  1086                 version = 6;
  1087             }
  1088             else if (table_contains_column(_session, "pgp_keypair", "flags") > 0) {
  1089                 version = 2;
  1090             }
  1091             else {
  1092                 version_changed = false;
  1093             }
  1094             
  1095             if (version_changed) {
  1096                 // set it in the DB, finally. Yeesh.
  1097                 char verbuf[21]; // enough digits for a max-sized 64 bit int, cmon. 
  1098                 sprintf(verbuf,"%d",version);
  1099                 
  1100                 size_t query_size = strlen(verbuf) + 25;
  1101                 char* query = calloc(query_size, 1);
  1102                 
  1103                 strlcpy(query, "pragma user_version = ", query_size);
  1104                 strlcat(query, verbuf, query_size);
  1105                 strlcat(query, ";", query_size);
  1106                 
  1107                 int_result = sqlite3_exec(
  1108                     _session->db,
  1109                     query,
  1110                     user_version,
  1111                     &version,
  1112                     NULL
  1113                 );
  1114                 free(query);
  1115             }
  1116         }
  1117 
  1118 
  1119         if(version != 0) { 
  1120             // Version has been already set
  1121 
  1122             // Early mistake : version 0 shouldn't have existed.
  1123             // Numbering should have started at 1 to detect newly created DB.
  1124             // Version 0 DBs are not anymore compatible.
  1125 
  1126             // // Was version 0 compat code.
  1127             // if (version < 1) {
  1128             //     int_result = sqlite3_exec(
  1129             //         _session->db,
  1130             //         "alter table identity\n"
  1131             //         "   add column flags integer default 0;\n",
  1132             //         NULL,
  1133             //         NULL,
  1134             //         NULL
  1135             //     );
  1136             //     assert(int_result == SQLITE_OK);
  1137             // }
  1138             
  1139             if (version < 2) {
  1140                 // N.B. addition of device_group column removed in DDL v10
  1141                 int_result = sqlite3_exec(
  1142                     _session->db,
  1143                     "alter table pgp_keypair\n"
  1144                     "   add column flags integer default 0;\n",
  1145                     // "alter table person\n"
  1146                     // "   add column device_group text;\n",
  1147                     NULL,
  1148                     NULL,
  1149                     NULL
  1150                 );
  1151                 assert(int_result == SQLITE_OK);
  1152             }
  1153 
  1154             if (version < 5) {
  1155                 int_result = sqlite3_exec(
  1156                     _session->db,
  1157                     "delete from pgp_keypair where fpr = '';",
  1158                     NULL,
  1159                     NULL,
  1160                     NULL
  1161                 );
  1162                 assert(int_result == SQLITE_OK);
  1163                 int_result = sqlite3_exec(
  1164                     _session->db,
  1165                     "delete from trust where pgp_keypair_fpr = '';",
  1166                     NULL,
  1167                     NULL,
  1168                     NULL
  1169                 );
  1170                 assert(int_result == SQLITE_OK);
  1171             }
  1172             
  1173             if (version < 6) {
  1174                 int_result = sqlite3_exec(
  1175                     _session->db,
  1176                     "alter table identity\n"
  1177                     "   add column is_own integer default 0;\n",
  1178                     NULL,
  1179                     NULL,
  1180                     NULL
  1181                 );
  1182                 assert(int_result == SQLITE_OK);                
  1183                 int_result = sqlite3_exec(
  1184                     _session->db,
  1185                     "update identity\n"
  1186                     "   set is_own = 1\n"
  1187                     "   where (user_id = '" PEP_OWN_USERID "');\n",
  1188                     NULL,
  1189                     NULL,
  1190                     NULL
  1191                 );
  1192                 assert(int_result == SQLITE_OK);    
  1193 
  1194                 // Turns out that just adding "on update cascade" in
  1195                 // sqlite is a PITA. We need to be able to cascade
  1196                 // person->id replacements (for temp ids like "TOFU_")
  1197                 // so here we go...
  1198                 int_result = sqlite3_exec(
  1199                     _session->db,
  1200                     "PRAGMA foreign_keys=off;\n"
  1201                     "BEGIN TRANSACTION;\n"
  1202                     "create table _identity_new (\n"
  1203                     "   address text,\n"
  1204                     "   user_id text\n"
  1205                     "       references person (id)\n"
  1206                     "       on delete cascade on update cascade,\n"
  1207                     "   main_key_id text\n"
  1208                     "       references pgp_keypair (fpr)\n"
  1209                     "       on delete set null,\n"
  1210                     "   comment text,\n"
  1211                     "   flags integer default 0,\n"
  1212                     "   is_own integer default 0,\n"
  1213                     "   primary key (address, user_id)\n"
  1214                     ");\n"                    
  1215                     "INSERT INTO _identity_new SELECT * FROM identity;\n"
  1216                     "DROP TABLE identity;\n"
  1217                     "ALTER TABLE _identity_new RENAME TO identity;\n"
  1218                     "COMMIT;\n"
  1219                     "\n"
  1220                     "BEGIN TRANSACTION;\n"
  1221                     "create table _trust_new (\n"
  1222                     "   user_id text not null\n"
  1223                     "       references person (id)\n"
  1224                     "       on delete cascade on update cascade,\n"
  1225                     "   pgp_keypair_fpr text not null\n"
  1226                     "       references pgp_keypair (fpr)\n"
  1227                     "       on delete cascade,\n"
  1228                     "   comm_type integer not null,\n"
  1229                     "   comment text,\n"
  1230                     "   primary key (user_id, pgp_keypair_fpr)\n"
  1231                     ");\n"
  1232                     "INSERT INTO _trust_new SELECT * FROM trust;\n"
  1233                     "DROP TABLE trust;\n"
  1234                     "ALTER TABLE _trust_new RENAME TO trust;\n"
  1235                     "COMMIT;\n"
  1236                     "\n"
  1237                     "PRAGMA foreign_keys=on;\n"
  1238                     "create table if not exists alternate_user_id (\n"
  1239                     "    default_id text references person (id)\n"
  1240                     "       on delete cascade on update cascade,\n"
  1241                     "    alternate_id text primary key\n"
  1242                     ");\n"
  1243                     ,
  1244                     NULL,
  1245                     NULL,
  1246                     NULL
  1247                 );
  1248                 assert(int_result == SQLITE_OK);   
  1249                 
  1250                 int_result = sqlite3_exec(
  1251                     _session->db,
  1252                     "PRAGMA foreign_key_check;\n"
  1253                     ,
  1254                     NULL,
  1255                     NULL,
  1256                     NULL
  1257                 );
  1258                 assert(int_result == SQLITE_OK);
  1259 
  1260                 // FIXME: foreign key check here 
  1261             }
  1262             if (version < 7) {
  1263                 int_result = sqlite3_exec(
  1264                     _session->db,
  1265                     "alter table person\n"
  1266                     "   add column is_pEp_user integer default 0;\n",
  1267                     NULL,
  1268                     NULL,
  1269                     NULL
  1270                 );
  1271                 assert(int_result == SQLITE_OK);
  1272                 int_result = sqlite3_exec(
  1273                     _session->db,
  1274                     "update person\n"
  1275                     "   set is_pEp_user = 1\n"
  1276                     "   where id = "
  1277                     "       (select distinct id from person "
  1278                     "               join trust on id = user_id "
  1279                     "               where (case when (comm_type = 127) then (id) "
  1280                     "                           when (comm_type = 255) then (id) "
  1281                     "                           else 0"
  1282                     "                      end) = id );\n",
  1283                     NULL,
  1284                     NULL,
  1285                     NULL
  1286                 );
  1287                 assert(int_result == SQLITE_OK);
  1288                 
  1289                 int_result = sqlite3_exec(
  1290                     _session->db,
  1291                     "create table if not exists mistrusted_keys (\n"
  1292                     "    fpr text primary key\n"
  1293                     ");\n",            
  1294                     NULL,
  1295                     NULL,
  1296                     NULL
  1297                 );
  1298                 assert(int_result == SQLITE_OK);    
  1299             }
  1300             if (version < 8) {
  1301                 int_result = sqlite3_exec(
  1302                     _session->db,
  1303                     "PRAGMA foreign_keys=off;\n"
  1304                     "BEGIN TRANSACTION;\n"
  1305                     "create table _identity_new (\n"
  1306                     "   address text,\n"
  1307                     "   user_id text\n"
  1308                     "       references person (id)\n"
  1309                     "       on delete cascade on update cascade,\n"
  1310                     "   main_key_id text\n"
  1311                     "       references pgp_keypair (fpr)\n"
  1312                     "       on delete set null,\n"
  1313                     "   comment text,\n"
  1314                     "   flags integer default 0,\n"
  1315                     "   is_own integer default 0,\n"
  1316                     "   timestamp integer default (datetime('now')),\n"
  1317                     "   primary key (address, user_id)\n"
  1318                     ");\n"
  1319                     "INSERT INTO _identity_new (address, user_id, main_key_id, "
  1320                     "                      comment, flags, is_own) "
  1321                     "   SELECT identity.address, identity.user_id, "
  1322                     "          identity.main_key_id, identity.comment, "
  1323                     "          identity.flags, identity.is_own "
  1324                     "   FROM identity "
  1325                     "   WHERE 1;\n"
  1326                     "DROP TABLE identity;\n"
  1327                     "ALTER TABLE _identity_new RENAME TO identity;\n"
  1328                     "COMMIT;\n"
  1329                     "\n"
  1330                     "PRAGMA foreign_keys=on;\n"
  1331                     ,
  1332                     NULL,
  1333                     NULL,
  1334                     NULL
  1335                 );
  1336                 assert(int_result == SQLITE_OK);    
  1337                 
  1338                 int_result = sqlite3_exec(
  1339                     _session->db,
  1340                     "PRAGMA foreign_key_check;\n"
  1341                     ,
  1342                     NULL,
  1343                     NULL,
  1344                     NULL
  1345                 );
  1346                 assert(int_result == SQLITE_OK);
  1347 
  1348                 // FIXME: foreign key check
  1349             }
  1350             if (version < 9) {
  1351                 int_result = sqlite3_exec(
  1352                     _session->db,
  1353                     "create table if not exists social_graph (\n"
  1354                     "    own_userid text,\n"
  1355                     "    own_address text,\n"
  1356                     "    contact_userid text,\n"
  1357                     "    CONSTRAINT fk_own_identity\n"
  1358                     "       FOREIGN KEY(own_address, own_userid)\n" 
  1359                     "       REFERENCES identity(address, user_id)\n"
  1360                     "       ON DELETE CASCADE ON UPDATE CASCADE\n"
  1361                     ");\n"
  1362                     "create table if not exists revocation_contact_list (\n"
  1363                     "   fpr text not null references pgp_keypair (fpr)\n"
  1364                     "       on delete cascade,\n"
  1365                     "   contact_id text not null references person (id)\n"
  1366                     "       on delete cascade on update cascade,\n"
  1367                     "   timestamp integer default (datetime('now')),\n"
  1368                     "   PRIMARY KEY(fpr, contact_id)\n"
  1369                     ");\n"
  1370                     ,
  1371                     NULL,
  1372                     NULL,
  1373                     NULL
  1374                 );
  1375                 assert(int_result == SQLITE_OK);    
  1376             }
  1377             if (version < 10 && version > 1) {
  1378                 int_result = sqlite3_exec(
  1379                     _session->db,
  1380                     "PRAGMA foreign_keys=off;\n"
  1381                     "BEGIN TRANSACTION;\n"
  1382                     "create table _person_new (\n"
  1383                     "   id text primary key,\n"
  1384                     "   username text not null,\n"
  1385                     "   main_key_id text\n"
  1386                     "       references pgp_keypair (fpr)\n"
  1387                     "       on delete set null,\n"
  1388                     "   lang text,\n"
  1389                     "   comment text,\n"
  1390                     "   is_pEp_user integer default 0\n"
  1391                     ");\n"
  1392                     "INSERT INTO _person_new (id, username, main_key_id, "
  1393                     "                    lang, comment, is_pEp_user) "
  1394                     "   SELECT person.id, person.username, "
  1395                     "          person.main_key_id, person.lang, "
  1396                     "          person.comment, person.is_pEp_user "
  1397                     "   FROM person "
  1398                     "   WHERE 1;\n"
  1399                     "DROP TABLE person;\n"
  1400                     "ALTER TABLE _person_new RENAME TO person;\n"
  1401                     "COMMIT;\n"
  1402                     "\n"
  1403                     "PRAGMA foreign_keys=on;\n"
  1404                     ,
  1405                     NULL,
  1406                     NULL,
  1407                     NULL
  1408                 );
  1409                 assert(int_result == SQLITE_OK);    
  1410                 int_result = sqlite3_exec(
  1411                     _session->db,
  1412                     "PRAGMA foreign_key_check;\n"
  1413                     ,
  1414                     NULL,
  1415                     NULL,
  1416                     NULL
  1417                 );
  1418                 assert(int_result == SQLITE_OK);
  1419             }
  1420             if (version < 11) {
  1421                 status = repair_altered_tables(_session);
  1422                 assert(status == PEP_STATUS_OK);
  1423                 if (status != PEP_STATUS_OK)
  1424                     return status;
  1425             }
  1426         }        
  1427         else { 
  1428             // Version from DB was 0, it means this is initial setup.
  1429             // DB has just been created, and all tables are empty.
  1430             very_first = true;
  1431         }
  1432 
  1433         if (version < atoi(_DDL_USER_VERSION)) {
  1434             int_result = sqlite3_exec(
  1435                 _session->db,
  1436                 "pragma user_version = "_DDL_USER_VERSION";\n"
  1437                 "insert or replace into version_info (id, version)"
  1438                     "values (1, '" PEP_ENGINE_VERSION "');",
  1439                 NULL,
  1440                 NULL,
  1441                 NULL
  1442             );
  1443             assert(int_result == SQLITE_OK);
  1444         }
  1445         
  1446         // We need to init a few globals for message id that we'd rather not
  1447         // calculate more than once.
  1448         _init_globals();
  1449     }
  1450 
  1451     int_result = sqlite3_prepare_v2(_session->db, sql_log,
  1452             (int)strlen(sql_log), &_session->log, NULL);
  1453     assert(int_result == SQLITE_OK);
  1454 
  1455     int_result = sqlite3_prepare_v2(_session->system_db, sql_trustword,
  1456             (int)strlen(sql_trustword), &_session->trustword, NULL);
  1457     assert(int_result == SQLITE_OK);
  1458 
  1459     int_result = sqlite3_prepare_v2(_session->db, sql_get_identity,
  1460             (int)strlen(sql_get_identity), &_session->get_identity, NULL);
  1461     assert(int_result == SQLITE_OK);
  1462 
  1463     int_result = sqlite3_prepare_v2(_session->db, sql_get_identity_without_trust_check,
  1464             (int)strlen(sql_get_identity_without_trust_check), 
  1465             &_session->get_identity_without_trust_check, NULL);
  1466     assert(int_result == SQLITE_OK);
  1467 
  1468     int_result = sqlite3_prepare_v2(_session->db, sql_get_identities_by_address,
  1469             (int)strlen(sql_get_identities_by_address), 
  1470             &_session->get_identities_by_address, NULL);
  1471     assert(int_result == SQLITE_OK);
  1472     
  1473     int_result = sqlite3_prepare_v2(_session->db, sql_get_identities_by_userid,
  1474             (int)strlen(sql_get_identities_by_userid), 
  1475             &_session->get_identities_by_userid, NULL);
  1476     assert(int_result == SQLITE_OK);
  1477 
  1478     int_result = sqlite3_prepare_v2(_session->db, sql_get_identities_by_main_key_id,
  1479             (int)strlen(sql_get_identities_by_main_key_id), 
  1480             &_session->get_identities_by_main_key_id, NULL);
  1481     assert(int_result == SQLITE_OK);
  1482 
  1483     int_result = sqlite3_prepare_v2(_session->db, sql_get_user_default_key,
  1484             (int)strlen(sql_get_user_default_key), &_session->get_user_default_key, NULL);
  1485     assert(int_result == SQLITE_OK);
  1486 
  1487     int_result = sqlite3_prepare_v2(_session->db, sql_get_all_keys_for_user,
  1488             (int)strlen(sql_get_all_keys_for_user), &_session->get_all_keys_for_user, NULL);
  1489     assert(int_result == SQLITE_OK);
  1490 
  1491     int_result = sqlite3_prepare_v2(_session->db, sql_get_default_own_userid,
  1492             (int)strlen(sql_get_default_own_userid), &_session->get_default_own_userid, NULL);
  1493     assert(int_result == SQLITE_OK);
  1494     
  1495     int_result = sqlite3_prepare_v2(_session->db, sql_get_userid_alias_default,
  1496             (int)strlen(sql_get_userid_alias_default), &_session->get_userid_alias_default, NULL);
  1497     assert(int_result == SQLITE_OK);
  1498 
  1499     int_result = sqlite3_prepare_v2(_session->db, sql_add_userid_alias,
  1500             (int)strlen(sql_add_userid_alias), &_session->add_userid_alias, NULL);
  1501     assert(int_result == SQLITE_OK);
  1502 
  1503     int_result = sqlite3_prepare_v2(_session->db, sql_replace_userid,
  1504             (int)strlen(sql_replace_userid), &_session->replace_userid, NULL);
  1505     assert(int_result == SQLITE_OK);
  1506 
  1507     int_result = sqlite3_prepare_v2(_session->db, sql_delete_key,
  1508             (int)strlen(sql_delete_key), &_session->delete_key, NULL);
  1509     assert(int_result == SQLITE_OK);
  1510 
  1511     int_result = sqlite3_prepare_v2(_session->db, sql_replace_main_user_fpr,
  1512             (int)strlen(sql_replace_main_user_fpr), &_session->replace_main_user_fpr, NULL);
  1513     assert(int_result == SQLITE_OK);
  1514 
  1515     int_result = sqlite3_prepare_v2(_session->db, sql_get_main_user_fpr,
  1516             (int)strlen(sql_get_main_user_fpr), &_session->get_main_user_fpr, NULL);
  1517     assert(int_result == SQLITE_OK);
  1518 
  1519     int_result = sqlite3_prepare_v2(_session->db, sql_refresh_userid_default_key,
  1520             (int)strlen(sql_refresh_userid_default_key), &_session->refresh_userid_default_key, NULL);
  1521     assert(int_result == SQLITE_OK);
  1522 
  1523     int_result = sqlite3_prepare_v2(_session->db, sql_replace_identities_fpr,
  1524             (int)strlen(sql_replace_identities_fpr), 
  1525             &_session->replace_identities_fpr, NULL);
  1526     assert(int_result == SQLITE_OK);
  1527     
  1528     int_result = sqlite3_prepare_v2(_session->db, sql_remove_fpr_as_default,
  1529             (int)strlen(sql_remove_fpr_as_default), 
  1530             &_session->remove_fpr_as_default, NULL);
  1531     assert(int_result == SQLITE_OK);
  1532 
  1533     int_result = sqlite3_prepare_v2(_session->db, sql_set_person,
  1534             (int)strlen(sql_set_person), &_session->set_person, NULL);
  1535     assert(int_result == SQLITE_OK);
  1536 
  1537     int_result = sqlite3_prepare_v2(_session->db, sql_update_person,
  1538             (int)strlen(sql_update_person), &_session->update_person, NULL);
  1539     assert(int_result == SQLITE_OK);
  1540 
  1541     int_result = sqlite3_prepare_v2(_session->db, sql_delete_person,
  1542             (int)strlen(sql_delete_person), &_session->delete_person, NULL);
  1543     assert(int_result == SQLITE_OK);
  1544 
  1545     int_result = sqlite3_prepare_v2(_session->db, sql_exists_person,
  1546             (int)strlen(sql_exists_person), &_session->exists_person, NULL);
  1547     assert(int_result == SQLITE_OK);
  1548 
  1549     int_result = sqlite3_prepare_v2(_session->db, sql_set_as_pEp_user,
  1550             (int)strlen(sql_set_as_pEp_user), &_session->set_as_pEp_user, NULL);
  1551     assert(int_result == SQLITE_OK);
  1552     
  1553     int_result = sqlite3_prepare_v2(_session->db, sql_is_pEp_user,
  1554             (int)strlen(sql_is_pEp_user), &_session->is_pEp_user, NULL);
  1555     assert(int_result == SQLITE_OK);
  1556 
  1557     int_result = sqlite3_prepare_v2(_session->db, sql_add_into_social_graph,
  1558             (int)strlen(sql_add_into_social_graph), &_session->add_into_social_graph, NULL);
  1559     assert(int_result == SQLITE_OK);
  1560 
  1561     int_result = sqlite3_prepare_v2(_session->db, 
  1562             sql_get_own_address_binding_from_contact,
  1563             (int)strlen(sql_get_own_address_binding_from_contact), 
  1564             &_session->get_own_address_binding_from_contact, NULL);
  1565     assert(int_result == SQLITE_OK);
  1566 
  1567     int_result = sqlite3_prepare_v2(_session->db, 
  1568             sql_set_revoke_contact_as_notified,
  1569             (int)strlen(sql_set_revoke_contact_as_notified), 
  1570             &_session->set_revoke_contact_as_notified, NULL);
  1571     assert(int_result == SQLITE_OK);
  1572 
  1573     int_result = sqlite3_prepare_v2(_session->db, 
  1574             sql_get_contacted_ids_from_revoke_fpr,
  1575             (int)strlen(sql_get_contacted_ids_from_revoke_fpr), 
  1576             &_session->get_contacted_ids_from_revoke_fpr, NULL);
  1577     assert(int_result == SQLITE_OK);
  1578 
  1579     int_result = sqlite3_prepare_v2(_session->db, 
  1580             sql_was_id_for_revoke_contacted,
  1581             (int)strlen(sql_was_id_for_revoke_contacted), 
  1582             &_session->was_id_for_revoke_contacted, NULL);
  1583     assert(int_result == SQLITE_OK);
  1584 
  1585     int_result = sqlite3_prepare_v2(_session->db, 
  1586             sql_get_last_contacted,
  1587             (int)strlen(sql_get_last_contacted), 
  1588             &_session->get_last_contacted, NULL);
  1589     assert(int_result == SQLITE_OK);
  1590 
  1591     int_result = sqlite3_prepare_v2(_session->db, 
  1592             sql_get_own_address_binding_from_contact,
  1593             (int)strlen(sql_get_own_address_binding_from_contact), 
  1594             &_session->get_own_address_binding_from_contact, NULL);
  1595     assert(int_result == SQLITE_OK);
  1596 
  1597     int_result = sqlite3_prepare_v2(_session->db, sql_set_pgp_keypair,
  1598             (int)strlen(sql_set_pgp_keypair), &_session->set_pgp_keypair,
  1599             NULL);
  1600     assert(int_result == SQLITE_OK);
  1601 
  1602     int_result = sqlite3_prepare_v2(_session->db, sql_set_identity_entry,
  1603             (int)strlen(sql_set_identity_entry), &_session->set_identity_entry, NULL);
  1604     assert(int_result == SQLITE_OK);
  1605 
  1606     int_result = sqlite3_prepare_v2(_session->db, sql_update_identity_entry,
  1607             (int)strlen(sql_update_identity_entry), &_session->update_identity_entry, NULL);
  1608     assert(int_result == SQLITE_OK);
  1609 
  1610     int_result = sqlite3_prepare_v2(_session->db, sql_exists_identity_entry,
  1611             (int)strlen(sql_exists_identity_entry), &_session->exists_identity_entry, NULL);
  1612     assert(int_result == SQLITE_OK);
  1613 
  1614     int_result = sqlite3_prepare_v2(_session->db, sql_set_identity_flags,
  1615             (int)strlen(sql_set_identity_flags), &_session->set_identity_flags,
  1616             NULL);
  1617     assert(int_result == SQLITE_OK);
  1618 
  1619     int_result = sqlite3_prepare_v2(_session->db, sql_unset_identity_flags,
  1620             (int)strlen(sql_unset_identity_flags), &_session->unset_identity_flags,
  1621             NULL);
  1622     assert(int_result == SQLITE_OK);
  1623 
  1624     int_result = sqlite3_prepare_v2(_session->db, sql_set_trust,
  1625             (int)strlen(sql_set_trust), &_session->set_trust, NULL);
  1626     assert(int_result == SQLITE_OK);
  1627 
  1628     int_result = sqlite3_prepare_v2(_session->db, sql_update_trust,
  1629             (int)strlen(sql_update_trust), &_session->update_trust, NULL);
  1630     assert(int_result == SQLITE_OK);
  1631 
  1632     int_result = sqlite3_prepare_v2(_session->db, sql_update_trust_to_pEp,
  1633             (int)strlen(sql_update_trust_to_pEp), &_session->update_trust_to_pEp, NULL);
  1634     assert(int_result == SQLITE_OK);
  1635 
  1636     int_result = sqlite3_prepare_v2(_session->db, sql_exists_trust_entry,
  1637                  (int)strlen(sql_exists_trust_entry), &_session->exists_trust_entry, NULL);
  1638     assert(int_result == SQLITE_OK);
  1639 
  1640     int_result = sqlite3_prepare_v2(_session->db, sql_update_trust_for_fpr,
  1641             (int)strlen(sql_update_trust_for_fpr), &_session->update_trust_for_fpr, NULL);
  1642     assert(int_result == SQLITE_OK);
  1643 
  1644     int_result = sqlite3_prepare_v2(_session->db, sql_get_trust,
  1645             (int)strlen(sql_get_trust), &_session->get_trust, NULL);
  1646     assert(int_result == SQLITE_OK);
  1647 
  1648     int_result = sqlite3_prepare_v2(_session->db, sql_get_trust_by_userid,
  1649             (int)strlen(sql_get_trust_by_userid), &_session->get_trust_by_userid, NULL);
  1650     assert(int_result == SQLITE_OK);
  1651 
  1652     int_result = sqlite3_prepare_v2(_session->db, sql_least_trust,
  1653             (int)strlen(sql_least_trust), &_session->least_trust, NULL);
  1654     assert(int_result == SQLITE_OK);
  1655 
  1656     int_result = sqlite3_prepare_v2(_session->db, sql_mark_as_compromised,
  1657             (int)strlen(sql_mark_as_compromised), &_session->mark_compromised,
  1658             NULL);
  1659     assert(int_result == SQLITE_OK);
  1660 
  1661     int_result = sqlite3_prepare_v2(_session->db, sql_crashdump,
  1662             (int)strlen(sql_crashdump), &_session->crashdump, NULL);
  1663     assert(int_result == SQLITE_OK);
  1664 
  1665     int_result = sqlite3_prepare_v2(_session->system_db, sql_languagelist,
  1666             (int)strlen(sql_languagelist), &_session->languagelist, NULL);
  1667     assert(int_result == SQLITE_OK);
  1668 
  1669     int_result = sqlite3_prepare_v2(_session->system_db, sql_i18n_token,
  1670             (int)strlen(sql_i18n_token), &_session->i18n_token, NULL);
  1671     assert(int_result == SQLITE_OK);
  1672     
  1673     // blacklist
  1674 
  1675     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_add,
  1676             (int)strlen(sql_blacklist_add), &_session->blacklist_add, NULL);
  1677     assert(int_result == SQLITE_OK);
  1678 
  1679     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_delete,
  1680             (int)strlen(sql_blacklist_delete), &_session->blacklist_delete,
  1681             NULL);
  1682     assert(int_result == SQLITE_OK);
  1683 
  1684     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_is_listed,
  1685             (int)strlen(sql_blacklist_is_listed),
  1686             &_session->blacklist_is_listed, NULL);
  1687     assert(int_result == SQLITE_OK);
  1688 
  1689     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_retrieve,
  1690             (int)strlen(sql_blacklist_retrieve), &_session->blacklist_retrieve,
  1691             NULL);
  1692     assert(int_result == SQLITE_OK);
  1693     
  1694     // Own keys
  1695     
  1696     int_result = sqlite3_prepare_v2(_session->db, sql_own_key_is_listed,
  1697             (int)strlen(sql_own_key_is_listed), &_session->own_key_is_listed,
  1698             NULL);
  1699     assert(int_result == SQLITE_OK);
  1700 
  1701     int_result = sqlite3_prepare_v2(_session->db, sql_is_own_address,
  1702             (int)strlen(sql_is_own_address), &_session->is_own_address,
  1703             NULL);
  1704     assert(int_result == SQLITE_OK);
  1705     
  1706     int_result = sqlite3_prepare_v2(_session->db, sql_own_identities_retrieve,
  1707             (int)strlen(sql_own_identities_retrieve),
  1708             &_session->own_identities_retrieve, NULL);
  1709     assert(int_result == SQLITE_OK);
  1710  
  1711     int_result = sqlite3_prepare_v2(_session->db, sql_own_keys_retrieve,
  1712             (int)strlen(sql_own_keys_retrieve),
  1713             &_session->own_keys_retrieve, NULL);
  1714     assert(int_result == SQLITE_OK);
  1715  
  1716     // int_result = sqlite3_prepare_v2(_session->db, sql_set_own_key,
  1717     //         (int)strlen(sql_set_own_key),
  1718     //         &_session->set_own_key, NULL);
  1719     // assert(int_result == SQLITE_OK);
  1720  
  1721     // Sequence
  1722 
  1723     int_result = sqlite3_prepare_v2(_session->db, sql_sequence_value1,
  1724             (int)strlen(sql_sequence_value1), &_session->sequence_value1,
  1725             NULL);
  1726     assert(int_result == SQLITE_OK);
  1727 
  1728     int_result = sqlite3_prepare_v2(_session->db, sql_sequence_value2,
  1729             (int)strlen(sql_sequence_value2), &_session->sequence_value2,
  1730             NULL);
  1731     assert(int_result == SQLITE_OK);
  1732 
  1733     // Revocation tracking
  1734     
  1735     int_result = sqlite3_prepare_v2(_session->db, sql_set_revoked,
  1736             (int)strlen(sql_set_revoked), &_session->set_revoked, NULL);
  1737     assert(int_result == SQLITE_OK);
  1738     
  1739     int_result = sqlite3_prepare_v2(_session->db, sql_get_revoked,
  1740             (int)strlen(sql_get_revoked), &_session->get_revoked, NULL);
  1741     assert(int_result == SQLITE_OK);
  1742     
  1743     int_result = sqlite3_prepare_v2(_session->db, sql_get_replacement_fpr,
  1744             (int)strlen(sql_get_replacement_fpr), &_session->get_replacement_fpr, NULL);
  1745     assert(int_result == SQLITE_OK);
  1746 
  1747     int_result = sqlite3_prepare_v2(_session->db, sql_add_mistrusted_key,
  1748             (int)strlen(sql_add_mistrusted_key), &_session->add_mistrusted_key, NULL);
  1749     assert(int_result == SQLITE_OK);
  1750 
  1751     int_result = sqlite3_prepare_v2(_session->db, sql_delete_mistrusted_key,
  1752             (int)strlen(sql_delete_mistrusted_key), &_session->delete_mistrusted_key, NULL);
  1753     assert(int_result == SQLITE_OK);
  1754 
  1755     int_result = sqlite3_prepare_v2(_session->db, sql_is_mistrusted_key,
  1756             (int)strlen(sql_is_mistrusted_key), &_session->is_mistrusted_key, NULL);
  1757     assert(int_result == SQLITE_OK);
  1758     
  1759     status = init_cryptotech(_session, in_first);
  1760     if (status != PEP_STATUS_OK)
  1761         goto pEp_error;
  1762 
  1763     status = init_transport_system(_session, in_first);
  1764     if (status != PEP_STATUS_OK)
  1765         goto pEp_error;
  1766 
  1767     status = log_event(_session, "init", "pEp " PEP_ENGINE_VERSION, NULL, NULL);
  1768     if (status != PEP_STATUS_OK)
  1769         goto pEp_error;
  1770 
  1771     // runtime config
  1772 
  1773     if (very_first)
  1774     {
  1775 #ifdef USE_GPG
  1776         // On first run, all private keys already present in PGP keyring 
  1777         // are taken as own in order to seamlessly integrate with
  1778         // pre-existing GPG setup.
  1779 
  1780         // Note: earlier fears about danger because of DB reinitialisation should
  1781         // be a non-issue here, as we ONLY take the ultimately trusted keys now.
  1782         // Thus, unless the user has assigned ultimate trust through PGP, there is
  1783         // no chance of automatically imported pEp keys from a previous run making
  1784         // their way into PEP trusted status without explicit action (Bare imported
  1785         // private keys have an 'unknown' trust designation in PGP).
  1786 
  1787         // We don't really worry about the status here.
  1788         status = pgp_import_ultimately_trusted_keypairs(_session);        
  1789 #endif // USE_GPG
  1790     }
  1791 
  1792     *session = _session;
  1793     
  1794     // Note: Following statement is NOT for any cryptographic/secure functionality; it is
  1795     //       ONLY used for some randomness in generated outer message ID, which are
  1796     //       required by the RFC to be globally unique!
  1797     srand((unsigned int) time(NULL));
  1798     
  1799     return PEP_STATUS_OK;
  1800 
  1801 enomem:
  1802     status = PEP_OUT_OF_MEMORY;
  1803 
  1804 pEp_error:
  1805     release(_session);
  1806     return status;
  1807 }
  1808 
  1809 DYNAMIC_API void release(PEP_SESSION session)
  1810 {
  1811     bool out_last = false;
  1812     int _count = --init_count;
  1813     
  1814     assert(_count >= -1);
  1815     assert(session);
  1816 
  1817     if (!((_count >= -1) && session))
  1818         return;
  1819 
  1820     // a small race condition but still a race condition
  1821     // mitigated by calling caveat (see documentation)
  1822     // (release() is to be guarded by a mutex by the caller)
  1823     if (_count == -1)
  1824         out_last = true;
  1825 
  1826     if (session) {
  1827         free_Sync_state(session);
  1828 
  1829         if (session->db) {
  1830             if (session->log)
  1831                 sqlite3_finalize(session->log);
  1832             if (session->trustword)
  1833                 sqlite3_finalize(session->trustword);
  1834             if (session->get_identity)
  1835                 sqlite3_finalize(session->get_identity);
  1836             if (session->get_identity_without_trust_check)
  1837                 sqlite3_finalize(session->get_identity_without_trust_check);
  1838             if (session->get_identities_by_address)
  1839                 sqlite3_finalize(session->get_identities_by_address);            
  1840             if (session->get_identities_by_userid)
  1841                 sqlite3_finalize(session->get_identities_by_userid);                
  1842             if (session->get_identities_by_main_key_id)
  1843                 sqlite3_finalize(session->get_identities_by_main_key_id);                                
  1844             if (session->get_user_default_key)
  1845                 sqlite3_finalize(session->get_user_default_key);
  1846             if (session->get_all_keys_for_user)
  1847                 sqlite3_finalize(session->get_all_keys_for_user);                        
  1848             if (session->get_default_own_userid)
  1849                 sqlite3_finalize(session->get_default_own_userid);
  1850             if (session->get_userid_alias_default)
  1851                 sqlite3_finalize(session->get_userid_alias_default);
  1852             if (session->add_userid_alias)
  1853                 sqlite3_finalize(session->add_userid_alias);
  1854             if (session->replace_identities_fpr)
  1855                 sqlite3_finalize(session->replace_identities_fpr);        
  1856             if (session->remove_fpr_as_default)
  1857                 sqlite3_finalize(session->remove_fpr_as_default);            
  1858             if (session->set_person)
  1859                 sqlite3_finalize(session->set_person);
  1860             if (session->delete_person)
  1861                 sqlite3_finalize(session->delete_person);                
  1862             if (session->set_as_pEp_user)
  1863                 sqlite3_finalize(session->set_as_pEp_user);
  1864             if (session->is_pEp_user)
  1865                 sqlite3_finalize(session->is_pEp_user);
  1866             if (session->exists_person)
  1867                 sqlite3_finalize(session->exists_person);
  1868             if (session->add_into_social_graph)
  1869                 sqlite3_finalize(session->add_into_social_graph);  
  1870             if (session->get_own_address_binding_from_contact)
  1871                 sqlite3_finalize(session->get_own_address_binding_from_contact);  
  1872             if (session->set_revoke_contact_as_notified)
  1873                 sqlite3_finalize(session->set_revoke_contact_as_notified);  
  1874             if (session->get_contacted_ids_from_revoke_fpr)
  1875                 sqlite3_finalize(session->get_contacted_ids_from_revoke_fpr);  
  1876             if (session->was_id_for_revoke_contacted)
  1877                 sqlite3_finalize(session->was_id_for_revoke_contacted);   
  1878             if (session->get_last_contacted)
  1879                 sqlite3_finalize(session->get_last_contacted);                                       
  1880             if (session->set_pgp_keypair)
  1881                 sqlite3_finalize(session->set_pgp_keypair);
  1882             if (session->exists_identity_entry)
  1883                 sqlite3_finalize(session->exists_identity_entry);                
  1884             if (session->set_identity_entry)
  1885                 sqlite3_finalize(session->set_identity_entry);
  1886             if (session->update_identity_entry)
  1887                 sqlite3_finalize(session->update_identity_entry);    
  1888             if (session->set_identity_flags)
  1889                 sqlite3_finalize(session->set_identity_flags);
  1890             if (session->unset_identity_flags)
  1891                 sqlite3_finalize(session->unset_identity_flags);
  1892             if (session->exists_trust_entry)
  1893                 sqlite3_finalize(session->exists_trust_entry);                                
  1894             if (session->set_trust)
  1895                 sqlite3_finalize(session->set_trust);
  1896             if (session->update_trust)
  1897                 sqlite3_finalize(session->update_trust);
  1898             if (session->update_trust_to_pEp)
  1899                 sqlite3_finalize(session->update_trust_to_pEp);                                                
  1900             if (session->update_trust_for_fpr)
  1901                 sqlite3_finalize(session->update_trust_for_fpr);
  1902             if (session->get_trust)
  1903                 sqlite3_finalize(session->get_trust);
  1904             if (session->get_trust_by_userid)
  1905                 sqlite3_finalize(session->get_trust_by_userid);                
  1906             if (session->least_trust)
  1907                 sqlite3_finalize(session->least_trust);
  1908             if (session->mark_compromised)
  1909                 sqlite3_finalize(session->mark_compromised);
  1910             if (session->crashdump)
  1911                 sqlite3_finalize(session->crashdump);
  1912             if (session->languagelist)
  1913                 sqlite3_finalize(session->languagelist);
  1914             if (session->i18n_token)
  1915                 sqlite3_finalize(session->i18n_token);
  1916             if (session->replace_userid)
  1917                 sqlite3_finalize(session->replace_userid);
  1918             if (session->delete_key)
  1919                 sqlite3_finalize(session->delete_key);                
  1920             if (session->replace_main_user_fpr)
  1921                 sqlite3_finalize(session->replace_main_user_fpr);                
  1922             if (session->get_main_user_fpr)
  1923                 sqlite3_finalize(session->get_main_user_fpr);
  1924             if (session->refresh_userid_default_key)
  1925                 sqlite3_finalize(session->refresh_userid_default_key);
  1926             if (session->blacklist_add)
  1927                 sqlite3_finalize(session->blacklist_add);
  1928             if (session->blacklist_delete)
  1929                 sqlite3_finalize(session->blacklist_delete);
  1930             if (session->blacklist_is_listed)
  1931                 sqlite3_finalize(session->blacklist_is_listed);
  1932             if (session->blacklist_retrieve)
  1933                 sqlite3_finalize(session->blacklist_retrieve);
  1934             if (session->own_key_is_listed)
  1935                 sqlite3_finalize(session->own_key_is_listed);
  1936             if (session->is_own_address)
  1937                 sqlite3_finalize(session->is_own_address);
  1938             if (session->own_identities_retrieve)
  1939                 sqlite3_finalize(session->own_identities_retrieve);
  1940             if (session->own_keys_retrieve)
  1941                 sqlite3_finalize(session->own_keys_retrieve);
  1942             // if (session->set_own_key)
  1943             //     sqlite3_finalize(session->set_own_key);
  1944             if (session->sequence_value1)
  1945                 sqlite3_finalize(session->sequence_value1);
  1946             if (session->sequence_value2)
  1947                 sqlite3_finalize(session->sequence_value2);
  1948             if (session->set_revoked)
  1949                 sqlite3_finalize(session->set_revoked);
  1950             if (session->get_revoked)
  1951                 sqlite3_finalize(session->get_revoked);
  1952             if (session->get_replacement_fpr)
  1953                 sqlite3_finalize(session->get_replacement_fpr);                
  1954             if (session->add_mistrusted_key)
  1955                 sqlite3_finalize(session->add_mistrusted_key);
  1956             if (session->delete_mistrusted_key)
  1957                 sqlite3_finalize(session->delete_mistrusted_key);
  1958             if (session->is_mistrusted_key)
  1959                 sqlite3_finalize(session->is_mistrusted_key);
  1960                 
  1961             if (session->db) {
  1962                 sqlite3_exec(        
  1963                     session->db,
  1964                     "PRAGMA optimize;\n",
  1965                     NULL,
  1966                     NULL,
  1967                     NULL
  1968                 );
  1969                 sqlite3_close_v2(session->db);
  1970             }
  1971             if (session->system_db)
  1972                 sqlite3_close_v2(session->system_db);
  1973         }
  1974 
  1975         release_transport_system(session, out_last);
  1976         release_cryptotech(session, out_last);
  1977 
  1978 #ifdef DEBUG_ERRORSTACK
  1979         free_stringlist(session->errorstack);
  1980 #endif
  1981         free(session);
  1982     }
  1983 }
  1984 
  1985 DYNAMIC_API void config_passive_mode(PEP_SESSION session, bool enable)
  1986 {
  1987     assert(session);
  1988     if (session)
  1989         session->passive_mode = enable;
  1990 }
  1991 
  1992 DYNAMIC_API void config_unencrypted_subject(PEP_SESSION session, bool enable)
  1993 {
  1994     assert(session);
  1995     if (session)
  1996         session->unencrypted_subject = enable;
  1997 }
  1998 
  1999 DYNAMIC_API void config_service_log(PEP_SESSION session, bool enable)
  2000 {
  2001     assert(session);
  2002     if (session)
  2003         session->service_log = enable;
  2004 }
  2005 
  2006 DYNAMIC_API PEP_STATUS log_event(
  2007         PEP_SESSION session,
  2008         const char *title,
  2009         const char *entity,
  2010         const char *description,
  2011         const char *comment
  2012     )
  2013 {
  2014 
  2015 // N.B. If testing (so NDEBUG not defined) but this message is spam,
  2016 //      put -D_PEP_SERVICE_LOG_OFF into CFLAGS/CXXFLAGS     
  2017 #if !defined(NDEBUG) && !defined(_PEP_SERVICE_LOG_OFF)
  2018     fprintf(stdout, "\n*** %s %s %s %s\n", title, entity, description, comment);
  2019     session->service_log = true;
  2020 #endif
  2021 
  2022     // PEP_STATUS status = PEP_STATUS_OK;
  2023     // int result;
  2024     // 
  2025     // assert(session);
  2026     // assert(title);
  2027     // assert(entity);
  2028     // 
  2029     // if (!(session && title && entity))
  2030     //     return PEP_ILLEGAL_VALUE;
  2031     // 
  2032     // sqlite3_reset(session->log);
  2033     // sqlite3_bind_text(session->log, 1, title, -1, SQLITE_STATIC);
  2034     // sqlite3_bind_text(session->log, 2, entity, -1, SQLITE_STATIC);
  2035     // if (description)
  2036     //     sqlite3_bind_text(session->log, 3, description, -1, SQLITE_STATIC);
  2037     // else
  2038     //     sqlite3_bind_null(session->log, 3);
  2039     // if (comment)
  2040     //     sqlite3_bind_text(session->log, 4, comment, -1, SQLITE_STATIC);
  2041     // else
  2042     //     sqlite3_bind_null(session->log, 4);
  2043     // result = Sqlite3_step(session->log);
  2044     // sqlite3_reset(session->log);
  2045     // 
  2046     return PEP_STATUS_OK; // We ignore errors for this function.
  2047 }
  2048 
  2049 DYNAMIC_API PEP_STATUS log_service(
  2050         PEP_SESSION session,
  2051         const char *title,
  2052         const char *entity,
  2053         const char *description,
  2054         const char *comment
  2055     )
  2056 {
  2057     assert(session);
  2058     if (!session)
  2059         return PEP_ILLEGAL_VALUE;
  2060 
  2061     if (session->service_log)
  2062         return log_event(session, title, entity, description, comment);
  2063     else
  2064         return PEP_STATUS_OK;
  2065 }
  2066 
  2067 DYNAMIC_API PEP_STATUS trustword(
  2068             PEP_SESSION session, uint16_t value, const char *lang,
  2069             char **word, size_t *wsize
  2070         )
  2071 {
  2072     PEP_STATUS status = PEP_STATUS_OK;
  2073 
  2074     assert(session);
  2075     assert(word);
  2076     assert(wsize);
  2077 
  2078     if (!(session && word && wsize))
  2079         return PEP_ILLEGAL_VALUE;
  2080 
  2081     *word = NULL;
  2082     *wsize = 0;
  2083 
  2084     if (lang == NULL)
  2085         lang = "en";
  2086 
  2087     assert((lang[0] >= 'A' && lang[0] <= 'Z')
  2088             || (lang[0] >= 'a' && lang[0] <= 'z'));
  2089     assert((lang[1] >= 'A' && lang[1] <= 'Z')
  2090             || (lang[1] >= 'a' && lang[1] <= 'z'));
  2091     assert(lang[2] == 0);
  2092 
  2093     sqlite3_reset(session->trustword);
  2094     sqlite3_bind_text(session->trustword, 1, lang, -1, SQLITE_STATIC);
  2095     sqlite3_bind_int(session->trustword, 2, value);
  2096 
  2097     const int result = Sqlite3_step(session->trustword);
  2098     if (result == SQLITE_ROW) {
  2099         *word = strdup((const char *) sqlite3_column_text(session->trustword,
  2100                     1));
  2101         if (*word)
  2102             *wsize = sqlite3_column_bytes(session->trustword, 1);
  2103         else
  2104             status = PEP_OUT_OF_MEMORY;
  2105     } else
  2106         status = PEP_TRUSTWORD_NOT_FOUND;
  2107 
  2108     sqlite3_reset(session->trustword);
  2109     return status;
  2110 }
  2111 
  2112 DYNAMIC_API PEP_STATUS trustwords(
  2113         PEP_SESSION session, const char *fingerprint, const char *lang,
  2114         char **words, size_t *wsize, int max_words
  2115     )
  2116 {
  2117     const char *source = fingerprint;
  2118 
  2119     assert(session);
  2120     assert(fingerprint);
  2121     assert(words);
  2122     assert(wsize);
  2123     assert(max_words >= 0);
  2124 
  2125     if (!(session && fingerprint && words && wsize && max_words >= 0))
  2126         return PEP_ILLEGAL_VALUE;
  2127 
  2128     *words = NULL;
  2129     *wsize = 0;
  2130 
  2131     char *buffer = calloc(1, MAX_TRUSTWORDS_SPACE);
  2132     assert(buffer);
  2133     if (buffer == NULL)
  2134         return PEP_OUT_OF_MEMORY;
  2135     char *dest = buffer;
  2136 
  2137     const size_t fsize = strlen(fingerprint);
  2138 
  2139     if (!lang || !lang[0])
  2140         lang = "en";
  2141 
  2142     assert((lang[0] >= 'A' && lang[0] <= 'Z')
  2143             || (lang[0] >= 'a' && lang[0] <= 'z'));
  2144     assert((lang[1] >= 'A' && lang[1] <= 'Z')
  2145             || (lang[1] >= 'a' && lang[1] <= 'z'));
  2146     assert(lang[2] == 0);
  2147 
  2148     int n_words = 0;
  2149     while (source < fingerprint + fsize) {
  2150         PEP_STATUS _status;
  2151         uint16_t value;
  2152         char *word = NULL;
  2153         size_t _wsize = 0;
  2154         int j;
  2155 
  2156         for (value=0, j=0; j < 4 && source < fingerprint + fsize; ) {
  2157             if (*source >= 'a' && *source <= 'f')
  2158                 value += (*source - 'a' + 10) << (3 - j++) * 4;
  2159             else if (*source >= 'A' && *source <= 'F')
  2160                 value += (*source - 'A' + 10) << (3 - j++) * 4;
  2161             else if (*source >= '0' && *source <= '9')
  2162                 value += (*source - '0') << (3 - j++) * 4;
  2163             
  2164             source++;
  2165         }
  2166 
  2167         _status = trustword(session, value, lang, &word, &_wsize);
  2168         if (_status == PEP_OUT_OF_MEMORY) {
  2169             free(buffer);
  2170             return PEP_OUT_OF_MEMORY;
  2171         }
  2172         if (word == NULL) {
  2173             free(buffer);
  2174             return PEP_TRUSTWORD_NOT_FOUND;
  2175         }
  2176 
  2177         if (dest + _wsize < buffer + MAX_TRUSTWORDS_SPACE - 1) {
  2178             strncpy(dest, word, _wsize);
  2179             free(word);
  2180             dest += _wsize;
  2181         }
  2182         else {
  2183             free(word);
  2184             break; // buffer full
  2185         }
  2186 
  2187         if (source < fingerprint + fsize
  2188                 && dest + _wsize < buffer + MAX_TRUSTWORDS_SPACE - 1)
  2189             *dest++ = ' ';
  2190 
  2191         ++n_words;
  2192         if (max_words && n_words >= max_words)
  2193             break;
  2194     }
  2195 
  2196     *words = buffer;
  2197     *wsize = dest - buffer;
  2198     return PEP_STATUS_OK;
  2199 }
  2200 
  2201 pEp_identity *new_identity(
  2202         const char *address, const char *fpr, const char *user_id,
  2203         const char *username
  2204     )
  2205 {
  2206     pEp_identity *result = calloc(1, sizeof(pEp_identity));
  2207     assert(result);
  2208     if (result) {
  2209         if (address) {
  2210             result->address = strdup(address);
  2211             assert(result->address);
  2212             if (result->address == NULL) {
  2213                 free(result);
  2214                 return NULL;
  2215             }
  2216         }
  2217         if (fpr) {
  2218             result->fpr = strdup(fpr);
  2219             assert(result->fpr);
  2220             if (result->fpr == NULL) {
  2221                 free_identity(result);
  2222                 return NULL;
  2223             }
  2224         }
  2225         if (user_id) {
  2226             result->user_id = strdup(user_id);
  2227             assert(result->user_id);
  2228             if (result->user_id == NULL) {
  2229                 free_identity(result);
  2230                 return NULL;
  2231             }
  2232         }
  2233         if (username) {
  2234             result->username = strdup(username);
  2235             assert(result->username);
  2236             if (result->username == NULL) {
  2237                 free_identity(result);
  2238                 return NULL;
  2239             }
  2240         }
  2241     }
  2242     return result;
  2243 }
  2244 
  2245 pEp_identity *identity_dup(const pEp_identity *src)
  2246 {
  2247     assert(src);
  2248 
  2249     pEp_identity *dup = new_identity(src->address, src->fpr, src->user_id,
  2250             src->username);
  2251     assert(dup);
  2252     if (dup == NULL)
  2253         return NULL;
  2254     
  2255     dup->comm_type = src->comm_type;
  2256     dup->lang[0] = src->lang[0];
  2257     dup->lang[1] = src->lang[1];
  2258     dup->lang[2] = 0;
  2259     dup->flags = src->flags;
  2260     dup->me = src->me;
  2261     
  2262     return dup;
  2263 }
  2264 
  2265 void free_identity(pEp_identity *identity)
  2266 {
  2267     if (identity) {
  2268         free(identity->address);
  2269         free(identity->fpr);
  2270         free(identity->user_id);
  2271         free(identity->username);
  2272         free(identity);
  2273     }
  2274 }
  2275 
  2276 DYNAMIC_API PEP_STATUS get_default_own_userid(
  2277         PEP_SESSION session, 
  2278         char** userid
  2279     )
  2280 {
  2281     assert(session);
  2282     assert(userid);
  2283     
  2284     if (!session || !userid)
  2285         return PEP_ILLEGAL_VALUE;
  2286         
  2287     PEP_STATUS status = PEP_STATUS_OK;
  2288     char* retval = NULL;
  2289     
  2290     sqlite3_reset(session->get_default_own_userid);
  2291 
  2292     const int result = Sqlite3_step(session->get_default_own_userid);
  2293     const char* id;
  2294     
  2295     switch (result) {
  2296         case SQLITE_ROW:
  2297             id = (const char *) sqlite3_column_text(session->get_default_own_userid, 0);
  2298             if (!id) {
  2299                 // Shouldn't happen.
  2300                 status = PEP_UNKNOWN_ERROR;
  2301             }
  2302             else {
  2303                 retval = strdup(id);
  2304                 if (!retval)
  2305                     status = PEP_OUT_OF_MEMORY;
  2306             }
  2307             break;
  2308         default:
  2309             // Technically true, given how we find it, but FIXME we need a more descriptive error
  2310             status = PEP_CANNOT_FIND_IDENTITY;
  2311     }
  2312 
  2313     *userid = retval;
  2314 
  2315     sqlite3_reset(session->get_default_own_userid);
  2316     
  2317     return status;
  2318 }
  2319 
  2320 DYNAMIC_API PEP_STATUS get_userid_alias_default(
  2321         PEP_SESSION session, 
  2322         const char* alias_id,
  2323         char** default_id) {
  2324             
  2325     assert(session);
  2326     assert(alias_id);
  2327     assert(alias_id[0]);
  2328     assert(default_id);
  2329 
  2330     if (!(session && alias_id && alias_id[0] && default_id))
  2331         return PEP_ILLEGAL_VALUE;
  2332 
  2333     PEP_STATUS status = PEP_STATUS_OK;
  2334     char* retval = NULL;
  2335 
  2336     sqlite3_reset(session->get_userid_alias_default);
  2337     sqlite3_bind_text(session->get_userid_alias_default, 1, alias_id, -1, SQLITE_STATIC);
  2338 
  2339     const char* tempid;
  2340     
  2341     const int result = Sqlite3_step(session->get_userid_alias_default);
  2342     switch (result) {
  2343     case SQLITE_ROW:
  2344         tempid = (const char *) sqlite3_column_text(session->get_userid_alias_default, 0);
  2345         if (tempid) {
  2346             retval = strdup(tempid);
  2347             assert(retval);
  2348             if (retval == NULL)
  2349                 return PEP_OUT_OF_MEMORY;
  2350         }
  2351     
  2352         *default_id = retval;
  2353         break;
  2354     default:
  2355         status = PEP_CANNOT_FIND_ALIAS;
  2356         *default_id = NULL;
  2357     }
  2358 
  2359     sqlite3_reset(session->get_userid_alias_default);
  2360     return status;            
  2361 }
  2362 
  2363 DYNAMIC_API PEP_STATUS set_userid_alias (
  2364         PEP_SESSION session, 
  2365         const char* default_id,
  2366         const char* alias_id) {
  2367             
  2368     int result;
  2369 
  2370     assert(session);
  2371     assert(default_id);
  2372     assert(alias_id);
  2373 
  2374     if (!(session && default_id && alias_id && 
  2375           default_id[0] != '\0' && alias_id[0] != '\0'))
  2376         return PEP_ILLEGAL_VALUE;
  2377     
  2378     sqlite3_exec(session->db, "BEGIN TRANSACTION ;", NULL, NULL, NULL);
  2379 
  2380     sqlite3_reset(session->add_userid_alias);
  2381     sqlite3_bind_text(session->add_userid_alias, 1, default_id, -1,
  2382             SQLITE_STATIC);
  2383     sqlite3_bind_text(session->add_userid_alias, 2, alias_id, -1,
  2384             SQLITE_STATIC);
  2385         
  2386     result = Sqlite3_step(session->add_userid_alias);
  2387 
  2388     sqlite3_reset(session->add_userid_alias);
  2389     if (result != SQLITE_DONE) {
  2390         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);        
  2391         return PEP_CANNOT_SET_ALIAS;
  2392     }
  2393     sqlite3_exec(session->db, "COMMIT ;", NULL, NULL, NULL);
  2394         
  2395 
  2396     return PEP_STATUS_OK;
  2397 }
  2398 
  2399 DYNAMIC_API PEP_STATUS get_identity(
  2400         PEP_SESSION session,
  2401         const char *address,
  2402         const char *user_id,
  2403         pEp_identity **identity
  2404     )
  2405 {
  2406     PEP_STATUS status = PEP_STATUS_OK;
  2407     static pEp_identity *_identity;
  2408 
  2409     assert(session);
  2410     assert(address);
  2411     assert(address[0]);
  2412     assert(identity);
  2413 
  2414     if (!(session && address && address[0] && identity))
  2415         return PEP_ILLEGAL_VALUE;
  2416 
  2417     *identity = NULL;
  2418 
  2419     sqlite3_reset(session->get_identity);
  2420     sqlite3_bind_text(session->get_identity, 1, address, -1, SQLITE_STATIC);
  2421     sqlite3_bind_text(session->get_identity, 2, user_id, -1, SQLITE_STATIC);
  2422 
  2423     const int result = Sqlite3_step(session->get_identity);
  2424     switch (result) {
  2425     case SQLITE_ROW:
  2426         _identity = new_identity(
  2427                 address,
  2428                 (const char *) sqlite3_column_text(session->get_identity, 0),
  2429                 user_id,
  2430                 (const char *) sqlite3_column_text(session->get_identity, 1)
  2431                 );
  2432         assert(_identity);
  2433         if (_identity == NULL) {
  2434             sqlite3_reset(session->get_identity);
  2435             return PEP_OUT_OF_MEMORY;
  2436         }
  2437 
  2438         _identity->comm_type = (PEP_comm_type)
  2439             sqlite3_column_int(session->get_identity, 2);
  2440         const char* const _lang = (const char *)
  2441             sqlite3_column_text(session->get_identity, 3);
  2442         if (_lang && _lang[0]) {
  2443             assert(_lang[0] >= 'a' && _lang[0] <= 'z');
  2444             assert(_lang[1] >= 'a' && _lang[1] <= 'z');
  2445             assert(_lang[2] == 0);
  2446             _identity->lang[0] = _lang[0];
  2447             _identity->lang[1] = _lang[1];
  2448             _identity->lang[2] = 0;
  2449         }
  2450         _identity->flags = (unsigned int)
  2451             sqlite3_column_int(session->get_identity, 4);
  2452         _identity->me = (unsigned int)
  2453             sqlite3_column_int(session->get_identity, 5);
  2454     
  2455         *identity = _identity;
  2456         break;
  2457     default:
  2458         sqlite3_reset(session->get_identity);
  2459         status = PEP_CANNOT_FIND_IDENTITY;
  2460         *identity = NULL;
  2461     }
  2462 
  2463     sqlite3_reset(session->get_identity);
  2464     return status;
  2465 }
  2466 
  2467 PEP_STATUS get_identities_by_userid(
  2468         PEP_SESSION session,
  2469         const char *user_id,
  2470         identity_list **identities
  2471     )
  2472 {
  2473     if (!session || !identities || EMPTYSTR(user_id))
  2474         return PEP_ILLEGAL_VALUE;
  2475 
  2476     PEP_STATUS status = PEP_STATUS_OK;
  2477     
  2478     pEp_identity* ident = NULL;
  2479 
  2480     *identities = new_identity_list(NULL);
  2481 
  2482     sqlite3_reset(session->get_identities_by_userid);
  2483     sqlite3_bind_text(session->get_identities_by_userid, 1, user_id, -1, SQLITE_STATIC);
  2484 
  2485     int result = -1;
  2486     while ((result = Sqlite3_step(session->get_identities_by_userid)) == SQLITE_ROW) {
  2487             // "select address, fpr, username, comm_type, lang,"
  2488             // "   identity.flags | pgp_keypair.flags,"
  2489             // "   is_own"
  2490             // "   from identity"
  2491             // "   join person on id = identity.user_id"
  2492             // "   join pgp_keypair on fpr = identity.main_key_id"
  2493             // "   join trust on id = trust.user_id"
  2494             // "       and pgp_keypair_fpr = identity.main_key_id"    
  2495             // "   where identity.user_id = ?1" 
  2496             // "   order by is_own desc, "
  2497             // "   timestamp desc; ";
  2498 
  2499         ident = new_identity(
  2500                     (const char *) sqlite3_column_text(session->get_identities_by_userid, 0),
  2501                     (const char *) sqlite3_column_text(session->get_identities_by_userid, 1),                
  2502                     user_id,
  2503                     (const char *) sqlite3_column_text(session->get_identities_by_userid, 2)
  2504                 );
  2505                 
  2506         assert(ident);
  2507         if (ident == NULL) {
  2508             sqlite3_reset(session->get_identities_by_userid);
  2509             return PEP_OUT_OF_MEMORY;
  2510         }
  2511 
  2512         ident->comm_type = (PEP_comm_type)
  2513             sqlite3_column_int(session->get_identities_by_userid, 3);
  2514         const char* const _lang = (const char *)
  2515             sqlite3_column_text(session->get_identities_by_userid, 4);
  2516         if (_lang && _lang[0]) {
  2517             assert(_lang[0] >= 'a' && _lang[0] <= 'z');
  2518             assert(_lang[1] >= 'a' && _lang[1] <= 'z');
  2519             assert(_lang[2] == 0);
  2520             ident->lang[0] = _lang[0];
  2521             ident->lang[1] = _lang[1];
  2522             ident->lang[2] = 0;
  2523         }
  2524         ident->flags = (unsigned int)
  2525             sqlite3_column_int(session->get_identities_by_userid, 5);
  2526         ident->me = (unsigned int)
  2527             sqlite3_column_int(session->get_identities_by_userid, 6);
  2528     
  2529         identity_list_add(*identities, ident);
  2530         ident = NULL;
  2531     }
  2532 
  2533     if ((*identities)->ident == NULL) {
  2534         free_identity_list(*identities);
  2535         *identities = NULL;
  2536         status = PEP_CANNOT_FIND_IDENTITY;
  2537     }
  2538             
  2539     sqlite3_reset(session->get_identities_by_userid);
  2540 
  2541     return status;
  2542 }
  2543 
  2544 PEP_STATUS get_identities_by_main_key_id(
  2545         PEP_SESSION session,
  2546         const char *fpr,
  2547         identity_list **identities
  2548     )
  2549 {
  2550     if (!session || !identities || EMPTYSTR(fpr))
  2551         return PEP_ILLEGAL_VALUE;
  2552 
  2553     PEP_STATUS status = PEP_STATUS_OK;
  2554     
  2555     pEp_identity* ident = NULL;
  2556 
  2557     *identities = new_identity_list(NULL);
  2558 
  2559     sqlite3_reset(session->get_identities_by_main_key_id);
  2560     sqlite3_bind_text(session->get_identities_by_main_key_id, 1, fpr, -1, SQLITE_STATIC);
  2561 
  2562     int result = -1;
  2563     
  2564     while ((result = Sqlite3_step(session->get_identities_by_main_key_id)) == SQLITE_ROW) {
  2565         ident = new_identity(
  2566                     (const char *) sqlite3_column_text(session->get_identities_by_main_key_id, 0),
  2567                     fpr,
  2568                     (const char *) sqlite3_column_text(session->get_identities_by_main_key_id, 1),                
  2569                     (const char *) sqlite3_column_text(session->get_identities_by_main_key_id, 2)
  2570                 );
  2571                 
  2572         assert(ident);
  2573         if (ident == NULL) {
  2574             sqlite3_reset(session->get_identities_by_main_key_id);
  2575             return PEP_OUT_OF_MEMORY;
  2576         }
  2577 
  2578         ident->comm_type = (PEP_comm_type)
  2579             sqlite3_column_int(session->get_identities_by_main_key_id, 3);
  2580         const char* const _lang = (const char *)
  2581             sqlite3_column_text(session->get_identities_by_main_key_id, 4);
  2582         if (_lang && _lang[0]) {
  2583             assert(_lang[0] >= 'a' && _lang[0] <= 'z');
  2584             assert(_lang[1] >= 'a' && _lang[1] <= 'z');
  2585             assert(_lang[2] == 0);
  2586             ident->lang[0] = _lang[0];
  2587             ident->lang[1] = _lang[1];
  2588             ident->lang[2] = 0;
  2589         }
  2590         ident->flags = (unsigned int)
  2591             sqlite3_column_int(session->get_identities_by_main_key_id, 5);
  2592         ident->me = (unsigned int)
  2593             sqlite3_column_int(session->get_identities_by_main_key_id, 6);
  2594     
  2595         identity_list_add(*identities, ident);
  2596         ident = NULL;
  2597     }
  2598 
  2599     if ((*identities)->ident == NULL) {
  2600         free_identity_list(*identities);
  2601         *identities = NULL;
  2602         status = PEP_CANNOT_FIND_IDENTITY;
  2603     }
  2604             
  2605     sqlite3_reset(session->get_identities_by_main_key_id);
  2606 
  2607     return status;
  2608 }
  2609 
  2610 PEP_STATUS get_identity_without_trust_check(
  2611         PEP_SESSION session,
  2612         const char *address,
  2613         const char *user_id,
  2614         pEp_identity **identity
  2615     )
  2616 {
  2617     PEP_STATUS status = PEP_STATUS_OK;
  2618     static pEp_identity *_identity;
  2619 
  2620     assert(session);
  2621     assert(address);
  2622     assert(address[0]);
  2623     assert(identity);
  2624 
  2625     if (!(session && address && address[0] && identity))
  2626         return PEP_ILLEGAL_VALUE;
  2627 
  2628     *identity = NULL;
  2629 
  2630     sqlite3_reset(session->get_identity_without_trust_check);
  2631     sqlite3_bind_text(session->get_identity_without_trust_check, 1, address, -1, SQLITE_STATIC);
  2632     sqlite3_bind_text(session->get_identity_without_trust_check, 2, user_id, -1, SQLITE_STATIC);
  2633 
  2634     const int result = Sqlite3_step(session->get_identity_without_trust_check);
  2635     switch (result) {
  2636     case SQLITE_ROW:
  2637         _identity = new_identity(
  2638                 address,
  2639                 (const char *) sqlite3_column_text(session->get_identity_without_trust_check, 0),
  2640                 user_id,
  2641                 (const char *) sqlite3_column_text(session->get_identity_without_trust_check, 1)
  2642                 );
  2643         assert(_identity);
  2644         if (_identity == NULL) {
  2645             sqlite3_reset(session->get_identity_without_trust_check);
  2646             return PEP_OUT_OF_MEMORY;
  2647         }
  2648 
  2649         _identity->comm_type = PEP_ct_unknown;
  2650         const char* const _lang = (const char *)
  2651             sqlite3_column_text(session->get_identity_without_trust_check, 2);
  2652         if (_lang && _lang[0]) {
  2653             assert(_lang[0] >= 'a' && _lang[0] <= 'z');
  2654             assert(_lang[1] >= 'a' && _lang[1] <= 'z');
  2655             assert(_lang[2] == 0);
  2656             _identity->lang[0] = _lang[0];
  2657             _identity->lang[1] = _lang[1];
  2658             _identity->lang[2] = 0;
  2659         }
  2660         _identity->flags = (unsigned int)
  2661             sqlite3_column_int(session->get_identity_without_trust_check, 3);
  2662         _identity->me = (unsigned int)
  2663             sqlite3_column_int(session->get_identity_without_trust_check, 4);
  2664     
  2665         *identity = _identity;
  2666         break;
  2667     default:
  2668         status = PEP_CANNOT_FIND_IDENTITY;
  2669         *identity = NULL;
  2670     }
  2671 
  2672     sqlite3_reset(session->get_identity_without_trust_check);
  2673     return status;
  2674 }
  2675 
  2676 
  2677 PEP_STATUS get_identities_by_address(
  2678         PEP_SESSION session,
  2679         const char *address,
  2680         identity_list** id_list
  2681     )
  2682 {
  2683     assert(session);
  2684     assert(address);
  2685     assert(address[0]);
  2686     assert(id_list);
  2687 
  2688     if (!(session && address && address[0] && id_list))
  2689         return PEP_ILLEGAL_VALUE;
  2690 
  2691     *id_list = NULL;
  2692     identity_list* ident_list = NULL;
  2693 
  2694     sqlite3_reset(session->get_identities_by_address);
  2695     sqlite3_bind_text(session->get_identities_by_address, 1, address, -1, SQLITE_STATIC);
  2696     int result;
  2697 
  2698     while ((result = Sqlite3_step(session->get_identities_by_address)) == SQLITE_ROW) {
  2699         //"select user_id, main_key_id, username, comm_type, lang,"
  2700         //"   identity.flags, is_own"
  2701         pEp_identity *ident = new_identity(
  2702                 address,
  2703                 (const char *) sqlite3_column_text(session->get_identities_by_address, 1),
  2704                 (const char *) sqlite3_column_text(session->get_identities_by_address, 0),
  2705                 (const char *) sqlite3_column_text(session->get_identities_by_address, 2)
  2706                 );
  2707         assert(ident);
  2708         if (ident == NULL) {
  2709             sqlite3_reset(session->get_identities_by_address);
  2710             return PEP_OUT_OF_MEMORY;
  2711         }
  2712 
  2713         ident->comm_type = PEP_ct_unknown;
  2714         
  2715         const char* const _lang = (const char *)
  2716             sqlite3_column_text(session->get_identities_by_address, 3);
  2717         if (_lang && _lang[0]) {
  2718             assert(_lang[0] >= 'a' && _lang[0] <= 'z');
  2719             assert(_lang[1] >= 'a' && _lang[1] <= 'z');
  2720             assert(_lang[2] == 0);
  2721             ident->lang[0] = _lang[0];
  2722             ident->lang[1] = _lang[1];
  2723             ident->lang[2] = 0;
  2724         }
  2725         ident->flags = (unsigned int)
  2726             sqlite3_column_int(session->get_identities_by_address, 4);
  2727         ident->me = (unsigned int)
  2728             sqlite3_column_int(session->get_identities_by_address, 5);
  2729     
  2730         if (ident_list)
  2731             identity_list_add(ident_list, ident);
  2732         else
  2733             ident_list = new_identity_list(ident);
  2734     }
  2735 
  2736     sqlite3_reset(session->get_identities_by_address);
  2737     
  2738     *id_list = ident_list;
  2739     
  2740     if (!ident_list)
  2741         return PEP_CANNOT_FIND_IDENTITY;
  2742     
  2743     return PEP_STATUS_OK;
  2744 }
  2745 
  2746 PEP_STATUS exists_identity_entry(PEP_SESSION session, pEp_identity* identity,
  2747                                  bool* exists) {
  2748     assert(session);
  2749     assert(identity);
  2750     assert(!EMPTYSTR(identity->user_id));        
  2751     assert(!EMPTYSTR(identity->address));
  2752     if (!session || !exists || EMPTYSTR(identity->user_id) || EMPTYSTR(identity->address))
  2753         return PEP_ILLEGAL_VALUE;
  2754     
  2755     *exists = false;
  2756     
  2757     PEP_STATUS status = PEP_STATUS_OK;
  2758     
  2759     sqlite3_reset(session->exists_identity_entry);
  2760     sqlite3_bind_text(session->exists_identity_entry, 1, identity->address, -1,
  2761                       SQLITE_STATIC);
  2762     sqlite3_bind_text(session->exists_identity_entry, 2, identity->user_id, -1,
  2763                       SQLITE_STATIC);
  2764                   
  2765     int result = Sqlite3_step(session->exists_identity_entry);
  2766 
  2767     switch (result) {
  2768         case SQLITE_ROW: {
  2769             // yeah yeah, I know, we could be lazy here, but it looks bad.
  2770             *exists = (sqlite3_column_int(session->exists_identity_entry, 0) != 0);
  2771             break;
  2772         }
  2773         default: 
  2774             status = PEP_UNKNOWN_DB_ERROR;
  2775     }
  2776 
  2777     sqlite3_reset(session->exists_identity_entry);
  2778     return status;
  2779 }
  2780 
  2781 PEP_STATUS exists_trust_entry(PEP_SESSION session, pEp_identity* identity,
  2782                               bool* exists) {
  2783     assert(session);
  2784     assert(identity);
  2785     assert(!EMPTYSTR(identity->user_id));        
  2786     assert(!EMPTYSTR(identity->fpr));
  2787     if (!session || !exists || EMPTYSTR(identity->user_id) || EMPTYSTR(identity->fpr))
  2788         return PEP_ILLEGAL_VALUE;
  2789     
  2790     *exists = false;
  2791     
  2792     PEP_STATUS status = PEP_STATUS_OK;
  2793     
  2794     sqlite3_reset(session->exists_trust_entry);
  2795     sqlite3_bind_text(session->exists_trust_entry, 1, identity->user_id, -1,
  2796                       SQLITE_STATIC);
  2797     sqlite3_bind_text(session->exists_trust_entry, 2, identity->fpr, -1,
  2798                       SQLITE_STATIC);
  2799                   
  2800     int result = Sqlite3_step(session->exists_trust_entry);
  2801     switch (result) {
  2802         case SQLITE_ROW: {
  2803             // yeah yeah, I know, we could be lazy here, but it looks bad.
  2804             *exists = (sqlite3_column_int(session->exists_trust_entry, 0) != 0);
  2805             break;
  2806         }
  2807         default:
  2808             status = PEP_UNKNOWN_DB_ERROR;
  2809     }
  2810     
  2811     sqlite3_reset(session->exists_trust_entry);
  2812     return status;
  2813 }
  2814 
  2815 PEP_STATUS set_pgp_keypair(PEP_SESSION session, const char* fpr) {
  2816     if (!session || EMPTYSTR(fpr))
  2817         return PEP_ILLEGAL_VALUE;
  2818         
  2819     int result;
  2820     
  2821     sqlite3_reset(session->set_pgp_keypair);
  2822     sqlite3_bind_text(session->set_pgp_keypair, 1, fpr, -1,
  2823             SQLITE_STATIC);
  2824     result = Sqlite3_step(session->set_pgp_keypair);
  2825     sqlite3_reset(session->set_pgp_keypair);
  2826     if (result != SQLITE_DONE) {
  2827         return PEP_CANNOT_SET_PGP_KEYPAIR;
  2828     }
  2829     
  2830     return PEP_STATUS_OK;
  2831 }
  2832 
  2833 static PEP_STATUS _set_or_update_trust(PEP_SESSION session,
  2834                                        pEp_identity* identity,
  2835                                        sqlite3_stmt* set_or_update) {
  2836 
  2837     assert(session);
  2838     assert(identity);
  2839     assert(identity->user_id);
  2840     assert(identity->fpr);
  2841     
  2842     if (!session || !identity || EMPTYSTR(identity->user_id) || EMPTYSTR(identity->fpr))
  2843         return PEP_ILLEGAL_VALUE;
  2844         
  2845     PEP_STATUS status = set_pgp_keypair(session, identity->fpr);
  2846     if (status != PEP_STATUS_OK)
  2847         return status;
  2848         
  2849     int result;
  2850                 
  2851     sqlite3_reset(set_or_update);
  2852     sqlite3_bind_text(set_or_update, 1, identity->user_id, -1,
  2853             SQLITE_STATIC);
  2854     sqlite3_bind_text(set_or_update, 2, identity->fpr, -1,
  2855             SQLITE_STATIC);
  2856     sqlite3_bind_int(set_or_update, 3, identity->comm_type);
  2857     result = Sqlite3_step(set_or_update);
  2858     assert(result == SQLITE_DONE);
  2859     sqlite3_reset(set_or_update);
  2860     if (result != SQLITE_DONE)
  2861         return PEP_CANNOT_SET_TRUST;
  2862 
  2863     return PEP_STATUS_OK;
  2864 }
  2865 
  2866 static PEP_STATUS _set_or_update_identity_entry(PEP_SESSION session,
  2867                                                 pEp_identity* identity,
  2868                                                 sqlite3_stmt* set_or_update) {
  2869     assert(session);
  2870     assert(identity);
  2871     assert(set_or_update);
  2872                       
  2873     if (!session || !identity || !identity->user_id || !identity->address)
  2874         return PEP_ILLEGAL_VALUE;
  2875                                               
  2876     sqlite3_reset(set_or_update);
  2877     sqlite3_bind_text(set_or_update, 1, identity->address, -1,
  2878             SQLITE_STATIC);
  2879     sqlite3_bind_text(set_or_update, 2, identity->fpr, -1,
  2880             SQLITE_STATIC);
  2881     sqlite3_bind_text(set_or_update, 3, identity->user_id, -1,
  2882             SQLITE_STATIC);
  2883     sqlite3_bind_int(set_or_update, 4, identity->flags);
  2884     sqlite3_bind_int(set_or_update, 5, identity->me);
  2885     int result = Sqlite3_step(set_or_update);
  2886     sqlite3_reset(set_or_update);
  2887     if (result != SQLITE_DONE)
  2888         return PEP_CANNOT_SET_IDENTITY;
  2889     
  2890     return PEP_STATUS_OK;
  2891 }
  2892 
  2893 static PEP_STATUS _set_or_update_person(PEP_SESSION session, 
  2894                                         pEp_identity* identity,
  2895                                         sqlite3_stmt* set_or_update) {
  2896     assert(session);
  2897     assert(identity);
  2898     assert(set_or_update);
  2899                         
  2900     if (!session || !identity || !identity->user_id || !identity->username)
  2901         return PEP_ILLEGAL_VALUE;
  2902         
  2903     sqlite3_reset(set_or_update);
  2904     sqlite3_bind_text(set_or_update, 1, identity->user_id, -1,
  2905             SQLITE_STATIC);
  2906     sqlite3_bind_text(set_or_update, 2, identity->username, -1,
  2907             SQLITE_STATIC);
  2908     if (identity->lang[0])
  2909         sqlite3_bind_text(set_or_update, 3, identity->lang, 2,
  2910                 SQLITE_STATIC);
  2911     else
  2912         sqlite3_bind_null(set_or_update, 3);
  2913     sqlite3_bind_text(set_or_update, 4, identity->fpr, -1,
  2914                       SQLITE_STATIC);
  2915     int result = Sqlite3_step(set_or_update);
  2916     sqlite3_reset(set_or_update);
  2917     
  2918     if (result != SQLITE_DONE)
  2919         return PEP_CANNOT_SET_PERSON;
  2920     
  2921     return PEP_STATUS_OK;                                         
  2922 }
  2923 
  2924 PEP_STATUS set_or_update_with_identity(PEP_SESSION session,
  2925                                        pEp_identity* identity,
  2926                                        PEP_STATUS (* set_function)(PEP_SESSION, pEp_identity*, sqlite3_stmt*),
  2927                                        PEP_STATUS (* exists_function)(PEP_SESSION, pEp_identity*, bool*),                                       
  2928                                        sqlite3_stmt* update_query,
  2929                                        sqlite3_stmt* set_query,
  2930                                        bool guard_transaction) {
  2931 
  2932     if (guard_transaction) {
  2933         sqlite3_exec(session->db, "BEGIN TRANSACTION ;", NULL, NULL, NULL);
  2934     }
  2935     bool exists = false;
  2936     PEP_STATUS status = exists_function(session, identity, &exists);
  2937     
  2938     if (status == PEP_STATUS_OK) {
  2939         if (exists) {
  2940             status = set_function(session, identity, update_query);
  2941         }
  2942         else {
  2943             status = set_function(session, identity, set_query);                                              
  2944         }                    
  2945     }   
  2946     if (guard_transaction) {        
  2947         if (status != PEP_STATUS_OK)
  2948             sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  2949         else 
  2950             sqlite3_exec(session->db, "COMMIT ;", NULL, NULL, NULL);
  2951     }                      
  2952     return status;
  2953 }
  2954 
  2955 PEP_STATUS _set_trust_internal(PEP_SESSION session, pEp_identity* identity,
  2956                                bool guard_transaction) {
  2957     return set_or_update_with_identity(session, identity,
  2958                                        _set_or_update_trust,
  2959                                         exists_trust_entry,
  2960                                         session->update_trust,
  2961                                         session->set_trust,
  2962                                         guard_transaction);
  2963 }
  2964 
  2965 // This is the TOP-LEVEL function. If you're calling from set_identity,
  2966 // you can't use this one.
  2967 PEP_STATUS set_trust(PEP_SESSION session, pEp_identity* identity) {
  2968     PEP_STATUS status = PEP_STATUS_OK;
  2969     
  2970     status = _set_trust_internal(session, identity, true);
  2971     if (status == PEP_STATUS_OK) {
  2972         if ((identity->comm_type | PEP_ct_confirmed) == PEP_ct_pEp)
  2973             status = set_as_pEp_user(session, identity);
  2974     }
  2975     return status;
  2976 }
  2977 
  2978 PEP_STATUS set_person(PEP_SESSION session, pEp_identity* identity,
  2979                       bool guard_transaction) {
  2980     return set_or_update_with_identity(session, identity,
  2981                                        _set_or_update_person,
  2982                                        exists_person,
  2983                                        session->update_person,
  2984                                        session->set_person,
  2985                                        guard_transaction);
  2986 }
  2987 
  2988 PEP_STATUS set_identity_entry(PEP_SESSION session, pEp_identity* identity,
  2989                               bool guard_transaction) {
  2990     return set_or_update_with_identity(session, identity,
  2991                                        _set_or_update_identity_entry,
  2992                                        exists_identity_entry,
  2993                                        session->update_identity_entry,
  2994                                        session->set_identity_entry,
  2995                                        guard_transaction);
  2996 }
  2997 
  2998 // This will NOT call set_as_pEp_user; you have to do that separately.
  2999 DYNAMIC_API PEP_STATUS set_identity(
  3000         PEP_SESSION session, const pEp_identity *identity
  3001     )
  3002 {
  3003     int result;
  3004 
  3005     assert(session);
  3006     assert(identity);
  3007     assert(identity->address);
  3008     assert(identity->user_id);
  3009     assert(identity->username);
  3010 
  3011     if (!(session && identity && identity->address &&
  3012                 identity->user_id && identity->username))
  3013         return PEP_ILLEGAL_VALUE;
  3014 
  3015     PEP_STATUS status = PEP_STATUS_OK;
  3016     
  3017     bool has_fpr = (!EMPTYSTR(identity->fpr));
  3018     
  3019     sqlite3_exec(session->db, "BEGIN TRANSACTION ;", NULL, NULL, NULL);
  3020 
  3021     if (identity->lang[0]) {
  3022         assert(identity->lang[0] >= 'a' && identity->lang[0] <= 'z');
  3023         assert(identity->lang[1] >= 'a' && identity->lang[1] <= 'z');
  3024         assert(identity->lang[2] == 0);
  3025     }
  3026 
  3027     if (has_fpr) {
  3028         sqlite3_reset(session->set_pgp_keypair);
  3029         sqlite3_bind_text(session->set_pgp_keypair, 1, identity->fpr, -1,
  3030                 SQLITE_STATIC);
  3031         result = Sqlite3_step(session->set_pgp_keypair);
  3032         sqlite3_reset(session->set_pgp_keypair);
  3033         if (result != SQLITE_DONE) {
  3034             sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  3035             return PEP_CANNOT_SET_PGP_KEYPAIR;
  3036         }
  3037     }
  3038 
  3039     // We do this because there are checks in set_person for
  3040     // aliases, which modify the identity object on return.
  3041     pEp_identity* ident_copy = identity_dup(identity); 
  3042     if (!ident_copy)
  3043         return PEP_OUT_OF_MEMORY;
  3044 
  3045     status = set_person(session, ident_copy, false);
  3046     if (status != PEP_STATUS_OK) {
  3047         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  3048         goto pEp_free;
  3049     }
  3050 
  3051     status = set_identity_entry(session, ident_copy, false);
  3052     if (status != PEP_STATUS_OK) {
  3053         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  3054         goto pEp_free;
  3055     }
  3056 
  3057     if (has_fpr) {
  3058         status = _set_trust_internal(session, ident_copy, false);
  3059         if (status != PEP_STATUS_OK) {
  3060             sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  3061             goto pEp_free;
  3062         }
  3063     }
  3064     
  3065     result = sqlite3_exec(session->db, "COMMIT ;", NULL, NULL, NULL);
  3066     if (result == SQLITE_OK)
  3067         status = PEP_STATUS_OK;
  3068     else
  3069         status = PEP_COMMIT_FAILED;
  3070 
  3071 pEp_free:
  3072     free_identity(ident_copy);
  3073     return status;
  3074 }
  3075 
  3076 PEP_STATUS update_pEp_user_trust_vals(PEP_SESSION session,
  3077                                       pEp_identity* user) {
  3078     if (!user->user_id)
  3079         return PEP_ILLEGAL_VALUE;
  3080     
  3081     sqlite3_reset(session->update_trust_to_pEp);
  3082     sqlite3_bind_text(session->update_trust_to_pEp, 1, user->user_id, -1,
  3083             SQLITE_STATIC);
  3084     int result = Sqlite3_step(session->update_trust_to_pEp);
  3085     sqlite3_reset(session->update_trust_to_pEp);
  3086     if (result != SQLITE_DONE)
  3087         return PEP_CANNOT_SET_TRUST;
  3088 
  3089     return PEP_STATUS_OK;
  3090 }
  3091 
  3092 
  3093 // This ONLY sets the user flag. Must be called outside of a transaction.
  3094 DYNAMIC_API PEP_STATUS set_as_pEp_user(PEP_SESSION session, pEp_identity* user) {
  3095 
  3096     assert(session);
  3097     assert(user);
  3098     assert(!EMPTYSTR(user->user_id));
  3099         
  3100     if (!session || !user || EMPTYSTR(user->user_id))
  3101         return PEP_ILLEGAL_VALUE;
  3102             
  3103     PEP_STATUS status = PEP_STATUS_OK;
  3104     
  3105     bool person_exists = false;
  3106     
  3107     status = exists_person(session, user, &person_exists);
  3108     
  3109     if (status != PEP_STATUS_OK)
  3110         return status;
  3111         
  3112     if (!person_exists)
  3113         status = set_person(session, user, true);
  3114         
  3115     // Ok, let's set it.
  3116     sqlite3_reset(session->set_as_pEp_user);
  3117     sqlite3_bind_text(session->set_as_pEp_user, 1, user->user_id, -1,
  3118             SQLITE_STATIC);
  3119     int result = Sqlite3_step(session->set_as_pEp_user);
  3120     sqlite3_reset(session->set_as_pEp_user);
  3121     
  3122     if (result != SQLITE_DONE)
  3123         return PEP_CANNOT_SET_PERSON;
  3124 
  3125     status = update_pEp_user_trust_vals(session, user);
  3126         
  3127     return status;
  3128 }
  3129 
  3130 PEP_STATUS exists_person(PEP_SESSION session, pEp_identity* identity,
  3131                          bool* exists) {            
  3132     
  3133     // const char* user_id,
  3134     //                      char** default_id, bool* exists) {
  3135     assert(session);
  3136     assert(exists);
  3137     assert(identity);
  3138     assert(!EMPTYSTR(identity->user_id));
  3139         
  3140     if (!session || !exists || !identity || EMPTYSTR(identity->user_id))
  3141         return PEP_ILLEGAL_VALUE;
  3142     
  3143     *exists = false;
  3144 
  3145     const char* user_id = identity->user_id;
  3146     char* alias_default = NULL;
  3147     
  3148     PEP_STATUS status = get_userid_alias_default(session, user_id, &alias_default);
  3149     
  3150     if (status == PEP_CANNOT_FIND_ALIAS || EMPTYSTR(alias_default)) {
  3151         sqlite3_reset(session->exists_person);
  3152         sqlite3_bind_text(session->exists_person, 1, user_id, -1,
  3153                 SQLITE_STATIC);
  3154         int result = Sqlite3_step(session->exists_person);
  3155         switch (result) {
  3156             case SQLITE_ROW: {
  3157                 // yeah yeah, I know, we could be lazy here, but it looks bad.
  3158                 *exists = (sqlite3_column_int(session->exists_person, 0) != 0);
  3159                 status = PEP_STATUS_OK;
  3160                 break;
  3161             }
  3162             default:
  3163                 sqlite3_reset(session->exists_person);
  3164                 return PEP_UNKNOWN_DB_ERROR;
  3165         }
  3166         sqlite3_reset(session->exists_person);
  3167     }
  3168     else if (status == PEP_STATUS_OK) {
  3169         *exists = true; // thank you, delete on cascade!
  3170         // FIXME: Should we correct the userid default here? I think we should.
  3171         free(identity->user_id);
  3172         identity->user_id = alias_default; // ownership transfer
  3173     }
  3174     else
  3175         free(alias_default);
  3176             
  3177     return status;
  3178 }
  3179 
  3180 PEP_STATUS delete_person(PEP_SESSION session, const char* user_id) {
  3181     assert(session);
  3182     assert(!EMPTYSTR(user_id));        
  3183     if (!session || EMPTYSTR(user_id))
  3184         return PEP_ILLEGAL_VALUE;
  3185         
  3186     PEP_STATUS status = PEP_STATUS_OK;
  3187     
  3188     sqlite3_reset(session->delete_person);
  3189     sqlite3_bind_text(session->delete_person, 1, user_id, -1,
  3190                       SQLITE_STATIC);
  3191                       
  3192     int result = Sqlite3_step(session->delete_person);
  3193     
  3194     if (result != SQLITE_DONE)
  3195         status = PEP_UNKNOWN_ERROR;
  3196         
  3197     sqlite3_reset(session->delete_person);
  3198     return status;
  3199 }
  3200 
  3201 DYNAMIC_API PEP_STATUS is_pEp_user(PEP_SESSION session, pEp_identity *identity, bool* is_pEp)
  3202 {
  3203     assert(session);
  3204     assert(is_pEp);
  3205     assert(identity);
  3206     assert(!EMPTYSTR(identity->user_id));
  3207 
  3208     if (!session || !is_pEp || !identity || EMPTYSTR(identity->user_id))
  3209         return PEP_ILLEGAL_VALUE;
  3210     
  3211     *is_pEp = false;
  3212             
  3213     const char* user_id = identity->user_id;
  3214             
  3215     char* alias_default = NULL;
  3216     
  3217     PEP_STATUS status = get_userid_alias_default(session, user_id, &alias_default);
  3218     
  3219     if (status == PEP_CANNOT_FIND_ALIAS || EMPTYSTR(alias_default)) {
  3220         free(alias_default);
  3221         alias_default = strdup(user_id);
  3222     }
  3223     
  3224     sqlite3_reset(session->is_pEp_user);
  3225     sqlite3_bind_text(session->is_pEp_user, 1, user_id, -1,
  3226             SQLITE_STATIC);
  3227     int result = Sqlite3_step(session->is_pEp_user);
  3228     switch (result) {
  3229         case SQLITE_ROW: {
  3230             // yeah yeah, I know, we could be lazy here, but it looks bad.
  3231             *is_pEp = (sqlite3_column_int(session->is_pEp_user, 0) != 0);
  3232             break;
  3233         }
  3234         default:
  3235             sqlite3_reset(session->is_pEp_user);
  3236             free(alias_default);
  3237             return PEP_CANNOT_FIND_PERSON;
  3238     }
  3239 
  3240     sqlite3_reset(session->is_pEp_user);
  3241     
  3242     free(alias_default);
  3243     return PEP_STATUS_OK;
  3244 }
  3245 
  3246 PEP_STATUS is_own_address(PEP_SESSION session, const char* address, bool* is_own_addr)
  3247 {
  3248     assert(session);
  3249     assert(is_own_addr);
  3250     assert(!EMPTYSTR(address));
  3251 
  3252     if (!session || !is_own_addr || EMPTYSTR(address))
  3253         return PEP_ILLEGAL_VALUE;
  3254     
  3255     *is_own_addr = false;
  3256                 
  3257     if (!session || EMPTYSTR(address))
  3258         return PEP_ILLEGAL_VALUE;
  3259         
  3260     sqlite3_reset(session->is_own_address);
  3261     sqlite3_bind_text(session->is_own_address, 1, address, -1,
  3262             SQLITE_STATIC);
  3263     int result = Sqlite3_step(session->is_own_address);
  3264     switch (result) {
  3265         case SQLITE_ROW: {
  3266             // yeah yeah, I know, we could be lazy here, but it looks bad.
  3267             *is_own_addr = (sqlite3_column_int(session->is_own_address, 0) != 0);
  3268             break;
  3269         }
  3270         default:
  3271             sqlite3_reset(session->is_own_address);
  3272             return PEP_RECORD_NOT_FOUND;
  3273     }
  3274 
  3275     sqlite3_reset(session->is_own_address);
  3276     
  3277     return PEP_STATUS_OK;
  3278 }
  3279 
  3280 PEP_STATUS bind_own_ident_with_contact_ident(PEP_SESSION session,
  3281                                              pEp_identity* own_ident, 
  3282                                              pEp_identity* contact_ident) {
  3283     if (!own_ident || !contact_ident || 
  3284         !own_ident->address || !own_ident->user_id || !contact_ident->user_id)
  3285         return PEP_ILLEGAL_VALUE;
  3286         
  3287     sqlite3_reset(session->add_into_social_graph);
  3288     sqlite3_bind_text(session->add_into_social_graph, 1, own_ident->user_id, -1,
  3289             SQLITE_STATIC);
  3290     sqlite3_bind_text(session->add_into_social_graph, 2, own_ident->address, -1,
  3291             SQLITE_STATIC);
  3292     sqlite3_bind_text(session->add_into_social_graph, 3, contact_ident->user_id, -1,
  3293             SQLITE_STATIC);
  3294         
  3295     int result = Sqlite3_step(session->add_into_social_graph);
  3296     sqlite3_reset(session->add_into_social_graph);
  3297     
  3298     if (result != SQLITE_DONE)
  3299         return PEP_CANNOT_SET_PERSON;
  3300 
  3301     return PEP_STATUS_OK;
  3302 }
  3303 
  3304 PEP_STATUS get_own_ident_for_contact_id(PEP_SESSION session,
  3305                                           const pEp_identity* contact,
  3306                                           pEp_identity** own_ident) {
  3307                                               
  3308     if (!contact || !contact->user_id || !own_ident)
  3309         return PEP_ILLEGAL_VALUE;
  3310         
  3311     char* own_user_id = NULL;
  3312     *own_ident = NULL;
  3313     PEP_STATUS status = get_default_own_userid(session, &own_user_id);
  3314     
  3315     if (status != PEP_STATUS_OK)
  3316         return status;
  3317 
  3318     sqlite3_reset(session->get_own_address_binding_from_contact);
  3319     sqlite3_bind_text(session->get_own_address_binding_from_contact, 1, own_user_id, -1,
  3320             SQLITE_STATIC);
  3321     sqlite3_bind_text(session->get_own_address_binding_from_contact, 2, contact->user_id, -1,
  3322             SQLITE_STATIC);
  3323 
  3324     int result = Sqlite3_step(session->get_own_address_binding_from_contact);
  3325     
  3326     const char* own_address = NULL;
  3327     
  3328     switch (result) {
  3329         case SQLITE_ROW:
  3330             own_address = (const char *)
  3331                 sqlite3_column_text(session->get_own_address_binding_from_contact, 0);
  3332             if (own_address) {
  3333                 status = get_identity(session, own_address, own_user_id, own_ident);
  3334                 if (status == PEP_STATUS_OK) {
  3335                     if (!own_ident)
  3336                         status = PEP_CANNOT_FIND_IDENTITY;
  3337                 }
  3338             }
  3339             break;
  3340         default:
  3341             status = PEP_CANNOT_FIND_IDENTITY;
  3342     }
  3343     
  3344     free(own_user_id);
  3345     return status;
  3346 }
  3347 
  3348 PEP_STATUS remove_fpr_as_default(PEP_SESSION session, 
  3349                                  const char* fpr) 
  3350 {
  3351     assert(fpr);
  3352     
  3353     if (!session || !fpr)
  3354         return PEP_ILLEGAL_VALUE;
  3355             
  3356     sqlite3_reset(session->remove_fpr_as_default);
  3357     sqlite3_bind_text(session->remove_fpr_as_default, 1, fpr, -1,
  3358                       SQLITE_STATIC);
  3359 
  3360     int result = Sqlite3_step(session->remove_fpr_as_default);
  3361     sqlite3_reset(session->remove_fpr_as_default);
  3362     
  3363     if (result != SQLITE_DONE)
  3364         return PEP_CANNOT_SET_IDENTITY; // misleading - could also be person
  3365 
  3366     return PEP_STATUS_OK;
  3367 }
  3368 
  3369 
  3370 PEP_STATUS replace_identities_fpr(PEP_SESSION session, 
  3371                                  const char* old_fpr, 
  3372                                  const char* new_fpr) 
  3373 {
  3374     assert(old_fpr);
  3375     assert(new_fpr);
  3376     
  3377     if (!old_fpr || !new_fpr)
  3378         return PEP_ILLEGAL_VALUE;
  3379             
  3380     sqlite3_reset(session->replace_identities_fpr);
  3381     sqlite3_bind_text(session->replace_identities_fpr, 1, new_fpr, -1,
  3382                       SQLITE_STATIC);
  3383     sqlite3_bind_text(session->replace_identities_fpr, 2, old_fpr, -1,
  3384                       SQLITE_STATIC);
  3385 
  3386     int result = Sqlite3_step(session->replace_identities_fpr);
  3387     sqlite3_reset(session->replace_identities_fpr);
  3388     
  3389     if (result != SQLITE_DONE)
  3390         return PEP_CANNOT_SET_IDENTITY;
  3391 
  3392     return PEP_STATUS_OK;
  3393 }
  3394 
  3395 PEP_STATUS update_trust_for_fpr(PEP_SESSION session, 
  3396                                 const char* fpr, 
  3397                                 PEP_comm_type comm_type)
  3398 {
  3399     if (!fpr)
  3400         return PEP_ILLEGAL_VALUE;
  3401         
  3402     sqlite3_reset(session->update_trust_for_fpr);
  3403     sqlite3_bind_int(session->update_trust_for_fpr, 1, comm_type);
  3404     sqlite3_bind_text(session->update_trust_for_fpr, 2, fpr, -1,
  3405             SQLITE_STATIC);
  3406     int result = Sqlite3_step(session->update_trust_for_fpr);
  3407     sqlite3_reset(session->update_trust_for_fpr);
  3408     if (result != SQLITE_DONE) {
  3409         return PEP_CANNOT_SET_TRUST;
  3410     }
  3411     
  3412     return PEP_STATUS_OK;
  3413 }
  3414 
  3415 DYNAMIC_API PEP_STATUS set_identity_flags(
  3416         PEP_SESSION session,
  3417         pEp_identity *identity,
  3418         unsigned int flags
  3419     )
  3420 {
  3421     int result;
  3422 
  3423     assert(session);
  3424     assert(identity);
  3425     assert(identity->address);
  3426     assert(identity->user_id);
  3427 
  3428     if (!(session && identity && identity->address && identity->user_id))
  3429         return PEP_ILLEGAL_VALUE;
  3430 
  3431     sqlite3_reset(session->set_identity_flags);
  3432     sqlite3_bind_int(session->set_identity_flags, 1, flags);
  3433     sqlite3_bind_text(session->set_identity_flags, 2, identity->address, -1,
  3434             SQLITE_STATIC);
  3435     sqlite3_bind_text(session->set_identity_flags, 3, identity->user_id, -1,
  3436         SQLITE_STATIC);
  3437         
  3438     result = Sqlite3_step(session->set_identity_flags);
  3439 
  3440     sqlite3_reset(session->set_identity_flags);
  3441     if (result != SQLITE_DONE)
  3442         return PEP_CANNOT_SET_IDENTITY;
  3443 
  3444     identity->flags |= flags;
  3445     return PEP_STATUS_OK;
  3446 }
  3447 
  3448 DYNAMIC_API PEP_STATUS unset_identity_flags(
  3449         PEP_SESSION session,
  3450         pEp_identity *identity,
  3451         unsigned int flags
  3452     )
  3453 {
  3454     int result;
  3455 
  3456     assert(session);
  3457     assert(identity);
  3458     assert(identity->address);
  3459     assert(identity->user_id);
  3460 
  3461     if (!(session && identity && identity->address && identity->user_id))
  3462         return PEP_ILLEGAL_VALUE;
  3463 
  3464     sqlite3_reset(session->unset_identity_flags);
  3465     sqlite3_bind_int(session->unset_identity_flags, 1, flags);
  3466     sqlite3_bind_text(session->unset_identity_flags, 2, identity->address, -1,
  3467             SQLITE_STATIC);
  3468     sqlite3_bind_text(session->unset_identity_flags, 3, identity->user_id, -1,
  3469             SQLITE_STATIC);
  3470     result = Sqlite3_step(session->unset_identity_flags);
  3471     sqlite3_reset(session->unset_identity_flags);
  3472     if (result != SQLITE_DONE)
  3473         return PEP_CANNOT_SET_IDENTITY;
  3474 
  3475     identity->flags &= ~flags;
  3476 
  3477     return PEP_STATUS_OK;
  3478 }
  3479 
  3480 PEP_STATUS get_trust_by_userid(PEP_SESSION session, const char* user_id,
  3481                                            labeled_int_list_t** trust_list)
  3482 {
  3483     int result;
  3484 
  3485     if (!(session && user_id && user_id[0]))
  3486         return PEP_ILLEGAL_VALUE;
  3487 
  3488     *trust_list = NULL;
  3489     labeled_int_list_t* t_list = NULL;
  3490 
  3491     sqlite3_reset(session->get_trust_by_userid);
  3492     sqlite3_bind_text(session->get_trust_by_userid, 1, user_id, -1, SQLITE_STATIC);
  3493 
  3494     while ((result = Sqlite3_step(session->get_trust_by_userid)) == SQLITE_ROW) {
  3495         if (!t_list)
  3496             t_list = new_labeled_int_list(sqlite3_column_int(session->get_trust_by_userid, 1),
  3497                                          (const char *) sqlite3_column_text(session->get_trust_by_userid, 0));
  3498         else
  3499             labeled_int_list_add(t_list, sqlite3_column_int(session->get_trust_by_userid, 1),
  3500                                 (const char *) sqlite3_column_text(session->get_trust_by_userid, 0));
  3501     }
  3502 
  3503     sqlite3_reset(session->get_trust_by_userid);
  3504 
  3505     *trust_list = t_list;
  3506         
  3507     return PEP_STATUS_OK;
  3508 }
  3509 
  3510 PEP_comm_type reconcile_trust(PEP_comm_type t_old, PEP_comm_type t_new) {
  3511     switch (t_new) {
  3512         case PEP_ct_mistrusted:
  3513         case PEP_ct_key_revoked:
  3514         case PEP_ct_compromised:
  3515         case PEP_ct_key_b0rken:
  3516             return t_new;
  3517         default:
  3518             break;
  3519     }
  3520     switch (t_old) {
  3521         case PEP_ct_mistrusted:
  3522         case PEP_ct_key_revoked:
  3523         case PEP_ct_compromised:
  3524         case PEP_ct_key_b0rken:
  3525             return t_old;
  3526         default:
  3527             break;
  3528     }
  3529     if (t_old < PEP_ct_strong_but_unconfirmed && t_new >= PEP_ct_strong_but_unconfirmed)
  3530         return t_new;
  3531     
  3532     bool confirmed = (t_old & PEP_ct_confirmed) || (t_new & PEP_ct_confirmed);
  3533     PEP_comm_type result = _MAX(t_old, t_new);
  3534     if (confirmed)
  3535         result |= PEP_ct_confirmed;
  3536     return result;
  3537 }
  3538 
  3539 PEP_STATUS reconcile_pEp_status(PEP_SESSION session, const char* old_uid, 
  3540                                 const char* new_uid) {
  3541     PEP_STATUS status = PEP_STATUS_OK;
  3542     // We'll make this easy - if the old one has a pEp status, we set no matter
  3543     // what.
  3544     pEp_identity* ident = new_identity(NULL, NULL, old_uid, NULL);
  3545     bool is_pEp_peep = false;
  3546     status = is_pEp_user(session, ident, &is_pEp_peep);
  3547     if (is_pEp_peep) {
  3548         free(ident->user_id);
  3549         ident->user_id = strdup(new_uid);
  3550         if (!ident->user_id) {
  3551             status = PEP_OUT_OF_MEMORY;
  3552             goto pEp_free;
  3553         }
  3554         status = set_as_pEp_user(session, ident);
  3555     }
  3556 pEp_free:
  3557     free_identity(ident);
  3558     return status;
  3559 }
  3560 
  3561 const char* reconcile_usernames(const char* old_name, const char* new_name, 
  3562                                 const char* address) {
  3563     if (EMPTYSTR(old_name)) {
  3564         if (EMPTYSTR(new_name))
  3565             return address;
  3566         else
  3567             return new_name;
  3568     }
  3569     if (EMPTYSTR(new_name))
  3570         return old_name;        
  3571     if (strcmp(new_name, address) == 0)
  3572         return old_name;
  3573     return new_name;        
  3574 }
  3575 
  3576 PEP_STATUS reconcile_default_keys(PEP_SESSION session, pEp_identity* old_ident,
  3577                                   pEp_identity* new_ident) {
  3578     PEP_STATUS status = PEP_STATUS_OK;
  3579                                       
  3580     const char* old_fpr = old_ident->fpr;
  3581     const char* new_fpr = new_ident->fpr;
  3582     if (!old_fpr)
  3583         return status;
  3584 
  3585     PEP_comm_type old_ct = old_ident->comm_type;    
  3586     PEP_comm_type new_ct = new_ident->comm_type;
  3587     
  3588     if (!new_fpr) {
  3589         new_ident->fpr = strdup(old_fpr);
  3590         if (!new_ident->fpr)
  3591             status = PEP_OUT_OF_MEMORY;
  3592         else    
  3593             new_ident->comm_type = old_ct;
  3594         return status;
  3595     }        
  3596     
  3597     if (strcmp(old_fpr, new_fpr) == 0) {
  3598         new_ident->comm_type = reconcile_trust(old_ct, new_ct);
  3599         return status;
  3600     }
  3601     
  3602     bool old_confirmed = old_ct & PEP_ct_confirmed;
  3603     bool new_confirmed = new_ct & PEP_ct_confirmed;
  3604     
  3605     if (new_confirmed)
  3606         return status;
  3607     else if (old_confirmed) {
  3608         free(new_ident->fpr);
  3609         new_ident->fpr = strdup(old_fpr);
  3610         if (!new_ident->fpr)
  3611             status = PEP_OUT_OF_MEMORY;
  3612         else    
  3613             new_ident->comm_type = old_ct;
  3614         return status;
  3615     }
  3616     
  3617     if (old_ct > new_ct) {
  3618         free(new_ident->fpr);
  3619         new_ident->fpr = strdup(old_fpr);
  3620         if (!new_ident->fpr)
  3621             status = PEP_OUT_OF_MEMORY;
  3622         else    
  3623             new_ident->comm_type = old_ct;
  3624     }
  3625     return status;
  3626 }
  3627 
  3628 void reconcile_language(pEp_identity* old_ident,
  3629                         pEp_identity* new_ident) {
  3630     if (new_ident->lang[0] == 0) {
  3631         if (old_ident->lang[0] != 0) {
  3632             new_ident->lang[0] = old_ident->lang[0];
  3633             new_ident->lang[1] = old_ident->lang[1];
  3634             new_ident->lang[2] = old_ident->lang[2];
  3635         }
  3636     }
  3637 }
  3638 
  3639 // ONLY CALL THIS IF BOTH IDs ARE IN THE PERSON DB, FOOL! </Mr_T>
  3640 PEP_STATUS merge_records(PEP_SESSION session, const char* old_uid,
  3641                          const char* new_uid) {
  3642     PEP_STATUS status = PEP_STATUS_OK;
  3643     
  3644     pEp_identity* new_ident = NULL;
  3645     identity_list* old_identities = NULL;
  3646     labeled_int_list_t* trust_list = NULL;
  3647     stringlist_t* touched_keys = new_stringlist(NULL);
  3648     char* main_user_fpr = NULL;
  3649 
  3650     status = reconcile_pEp_status(session, old_uid, new_uid);
  3651     if (status != PEP_STATUS_OK)
  3652         goto pEp_free;
  3653                         
  3654     bool new_is_pEp = false;
  3655     new_ident = new_identity(NULL, NULL, new_uid, NULL);
  3656     status = is_pEp_user(session, new_ident, &new_is_pEp);
  3657     if (status != PEP_STATUS_OK)
  3658         goto pEp_free;
  3659     free(new_ident);
  3660     new_ident = NULL;
  3661         
  3662     status = get_identities_by_userid(session, old_uid, &old_identities);
  3663     if (status == PEP_STATUS_OK && old_identities) {
  3664         identity_list* curr_old = old_identities;
  3665         for (; curr_old && curr_old->ident; curr_old = curr_old->next) {
  3666             pEp_identity* old_ident = curr_old->ident;
  3667             const char* address = old_ident->address;
  3668             status = get_identity(session, address, new_uid, &new_ident);
  3669             if (status == PEP_CANNOT_FIND_IDENTITY) {
  3670                 // No new identity matching the old one, so we just set one w. new user_id
  3671                 free(old_ident->user_id);
  3672                 old_ident->user_id = strdup(new_uid);
  3673                 if (!old_ident->user_id) {
  3674                     status = PEP_OUT_OF_MEMORY;
  3675                     goto pEp_free;
  3676                 }
  3677                 if (new_is_pEp) {
  3678                     PEP_comm_type confirmed_bit = old_ident->comm_type & PEP_ct_confirmed;
  3679                     if ((old_ident->comm_type | PEP_ct_confirmed) == PEP_ct_OpenPGP)
  3680                         old_ident->comm_type = PEP_ct_pEp_unconfirmed | confirmed_bit;
  3681                 }
  3682                 
  3683                 status = set_identity(session, old_ident);
  3684                 if (status != PEP_STATUS_OK)
  3685                     goto pEp_free;
  3686             }
  3687             else if (status != PEP_STATUS_OK)
  3688                 goto pEp_free;
  3689             else {
  3690                 // Ok, so we have two idents which might be in conflict. Have to merge them.
  3691                 const char* username = reconcile_usernames(old_ident->username,
  3692                                                            new_ident->username,
  3693                                                            address);
  3694                                                            
  3695                 if (!new_ident->username || strcmp(username, new_ident->username) != 0) {
  3696                     free(new_ident->username);
  3697                     new_ident->username = strdup(username);
  3698                     if (!new_ident->username) {
  3699                         status = PEP_OUT_OF_MEMORY;
  3700                         goto pEp_free;
  3701                     }
  3702                 }
  3703         
  3704                 // Reconcile default keys if they differ, trust if they don't
  3705                 status = reconcile_default_keys(session, old_ident, new_ident);
  3706                 if (status != PEP_STATUS_OK)
  3707                     goto pEp_free;
  3708                     
  3709                 // reconcile languages
  3710                 reconcile_language(old_ident, new_ident);
  3711 
  3712                 // reconcile flags - FIXME - is this right?
  3713                 new_ident->flags |= old_ident->flags;
  3714                 
  3715                 // NOTE: In principle, this is only called from update_identity,
  3716                 // which would never have me flags set. So I am ignoring them here.
  3717                 // if this function is ever USED for that, though, you'll have
  3718                 // to go through making sure that the user ids are appropriately
  3719                 // aliased, etc. So be careful.
  3720                 
  3721                 // Set the reconciled record
  3722                     
  3723                 status = set_identity(session, new_ident);
  3724                 if (status != PEP_STATUS_OK)
  3725                     goto pEp_free;
  3726 
  3727                 if (new_ident->fpr)
  3728                     stringlist_add(touched_keys, new_ident->fpr);
  3729                         
  3730                 free_identity(new_ident);
  3731                 new_ident = NULL;    
  3732             }
  3733         }
  3734     }
  3735     // otherwise, no need to reconcile identity records. But maybe trust...    
  3736     new_ident = new_identity(NULL, NULL, new_uid, NULL);
  3737     if (!new_ident) {
  3738         status = PEP_OUT_OF_MEMORY;
  3739         goto pEp_free;
  3740     }
  3741     status = get_trust_by_userid(session, old_uid, &trust_list);
  3742 
  3743     labeled_int_list_t* trust_curr = trust_list;
  3744     for (; trust_curr && trust_curr->label; trust_curr = trust_curr->next) {
  3745         const char* curr_fpr = trust_curr->label;
  3746         new_ident->fpr = strdup(curr_fpr); 
  3747         status = get_trust(session, new_ident);
  3748         switch (status) {
  3749             case PEP_STATUS_OK:
  3750                 new_ident->comm_type = reconcile_trust(trust_curr->value,
  3751                                                        new_ident->comm_type);
  3752                 break;
  3753             case PEP_CANNOT_FIND_IDENTITY:
  3754                 new_ident->comm_type = trust_curr->value;
  3755                 break;
  3756             default:
  3757                 goto pEp_free;
  3758         }
  3759         new_ident->comm_type = reconcile_trust(trust_curr->value,
  3760                                                new_ident->comm_type);
  3761         if (new_is_pEp) {
  3762             PEP_comm_type confirmed_bit = new_ident->comm_type & PEP_ct_confirmed;
  3763             if ((new_ident->comm_type | PEP_ct_confirmed) == PEP_ct_OpenPGP)
  3764                 new_ident->comm_type = PEP_ct_pEp_unconfirmed | confirmed_bit;
  3765         }
  3766 
  3767         status = set_trust(session, new_ident);
  3768         if (status != PEP_STATUS_OK) {
  3769             goto pEp_free;
  3770         }                  
  3771                               
  3772         free(new_ident->fpr);
  3773         new_ident->fpr = NULL;
  3774         new_ident->comm_type = 0;
  3775     }
  3776 
  3777     // reconcile the default keys if the new id doesn't have one?
  3778     status = get_main_user_fpr(session, new_uid, &main_user_fpr);
  3779     if (status == PEP_KEY_NOT_FOUND || (status == PEP_STATUS_OK && !main_user_fpr)) {
  3780         status = get_main_user_fpr(session, old_uid, &main_user_fpr);
  3781         if (status == PEP_STATUS_OK && main_user_fpr)
  3782             status = replace_main_user_fpr(session, new_uid, main_user_fpr);
  3783         if (status != PEP_STATUS_OK)
  3784             goto pEp_free;
  3785     }
  3786     
  3787     // delete the old user
  3788     status = delete_person(session, old_uid);
  3789     
  3790 pEp_free:
  3791     free_identity(new_ident);
  3792     free_identity_list(old_identities);
  3793     free_labeled_int_list(trust_list);
  3794     free_stringlist(touched_keys);
  3795     free(main_user_fpr);
  3796     return status;
  3797 }
  3798 
  3799 PEP_STATUS replace_userid(PEP_SESSION session, const char* old_uid,
  3800                           const char* new_uid) {
  3801     assert(session);
  3802     assert(old_uid);
  3803     assert(new_uid);
  3804     
  3805     if (!session || !old_uid || !new_uid)
  3806         return PEP_ILLEGAL_VALUE;
  3807 
  3808     pEp_identity* temp_ident = new_identity(NULL, NULL, new_uid, NULL);
  3809     bool new_exists = false;
  3810     PEP_STATUS status = exists_person(session, temp_ident, &new_exists);
  3811     free_identity(temp_ident);
  3812     if (status != PEP_STATUS_OK) // DB error
  3813         return status;
  3814         
  3815     if (new_exists)
  3816         return merge_records(session, old_uid, new_uid);
  3817 
  3818     int result;
  3819 
  3820     sqlite3_reset(session->replace_userid);
  3821     sqlite3_bind_text(session->replace_userid, 1, new_uid, -1,
  3822             SQLITE_STATIC);
  3823     sqlite3_bind_text(session->replace_userid, 2, old_uid, -1,
  3824             SQLITE_STATIC);
  3825     result = Sqlite3_step(session->replace_userid);
  3826 #ifndef NDEBUG
  3827     if (result) {
  3828         const char *errmsg = sqlite3_errmsg(session->db);
  3829         log_event(session, "SQLite3 error", "replace_userid", errmsg, NULL);
  3830     }
  3831 #endif // !NDEBUG
  3832     sqlite3_reset(session->replace_userid);
  3833     if (result != SQLITE_DONE)
  3834         return PEP_CANNOT_SET_PERSON; // May need clearer retval
  3835 
  3836     return PEP_STATUS_OK;
  3837 }
  3838 
  3839 PEP_STATUS remove_key(PEP_SESSION session, const char* fpr) {
  3840     assert(session);
  3841     assert(fpr);
  3842     
  3843     if (!session || EMPTYSTR(fpr))
  3844         return PEP_ILLEGAL_VALUE;
  3845 
  3846     int result;
  3847 
  3848     sqlite3_reset(session->delete_key);
  3849     sqlite3_bind_text(session->delete_key, 1, fpr, -1,
  3850             SQLITE_STATIC);
  3851     result = Sqlite3_step(session->delete_key);
  3852     sqlite3_reset(session->delete_key);
  3853     if (result != SQLITE_DONE)
  3854         return PEP_CANNOT_SET_PGP_KEYPAIR;
  3855 
  3856     return PEP_STATUS_OK;
  3857 }
  3858 
  3859 
  3860 PEP_STATUS refresh_userid_default_key(PEP_SESSION session, const char* user_id) {
  3861     assert(session);
  3862     assert(user_id);
  3863     
  3864     if (!session || !user_id)
  3865         return PEP_ILLEGAL_VALUE;
  3866 
  3867     int result;
  3868 
  3869     sqlite3_reset(session->refresh_userid_default_key);
  3870     sqlite3_bind_text(session->refresh_userid_default_key, 1, user_id, -1,
  3871             SQLITE_STATIC);
  3872     result = Sqlite3_step(session->refresh_userid_default_key);
  3873     sqlite3_reset(session->refresh_userid_default_key);
  3874     if (result != SQLITE_DONE)
  3875         return PEP_CANNOT_SET_PERSON;
  3876 
  3877     return PEP_STATUS_OK;    
  3878 }
  3879 
  3880 PEP_STATUS replace_main_user_fpr(PEP_SESSION session, const char* user_id,
  3881                                  const char* new_fpr) {
  3882     assert(session);
  3883     assert(user_id);
  3884     assert(new_fpr);
  3885     
  3886     if (!session || !user_id || !new_fpr)
  3887         return PEP_ILLEGAL_VALUE;
  3888 
  3889     int result;
  3890 
  3891     sqlite3_reset(session->replace_main_user_fpr);
  3892     sqlite3_bind_text(session->replace_main_user_fpr, 1, new_fpr, -1,
  3893             SQLITE_STATIC);
  3894     sqlite3_bind_text(session->replace_main_user_fpr, 2, user_id, -1,
  3895             SQLITE_STATIC);
  3896     result = Sqlite3_step(session->replace_main_user_fpr);
  3897     sqlite3_reset(session->replace_main_user_fpr);
  3898     if (result != SQLITE_DONE)
  3899         return PEP_CANNOT_SET_PERSON;
  3900 
  3901     return PEP_STATUS_OK;
  3902 }
  3903 
  3904 PEP_STATUS get_main_user_fpr(PEP_SESSION session, 
  3905                              const char* user_id,
  3906                              char** main_fpr)
  3907 {
  3908     PEP_STATUS status = PEP_STATUS_OK;
  3909     int result;
  3910     
  3911     assert(session);
  3912     assert(user_id);
  3913     assert(main_fpr);
  3914     
  3915     if (!(session && user_id && user_id[0] && main_fpr))
  3916         return PEP_ILLEGAL_VALUE;
  3917         
  3918     *main_fpr = NULL;
  3919     
  3920     sqlite3_reset(session->get_main_user_fpr);
  3921     sqlite3_bind_text(session->get_main_user_fpr, 1, user_id, -1,
  3922                       SQLITE_STATIC);
  3923     result = Sqlite3_step(session->get_main_user_fpr);
  3924     switch (result) {
  3925     case SQLITE_ROW: {
  3926         const char* _fpr = 
  3927             (const char *) sqlite3_column_text(session->get_main_user_fpr, 0);
  3928         if (_fpr) {
  3929             *main_fpr = strdup(_fpr);
  3930             if (!(*main_fpr))
  3931                 status = PEP_OUT_OF_MEMORY;
  3932         }
  3933         else {
  3934             status = PEP_KEY_NOT_FOUND;
  3935         }
  3936         break;
  3937     }
  3938     default:
  3939         status = PEP_CANNOT_FIND_PERSON;
  3940     }
  3941 
  3942     sqlite3_reset(session->get_main_user_fpr);
  3943     return status;
  3944 }
  3945 
  3946 // Deprecated
  3947 DYNAMIC_API PEP_STATUS mark_as_compromized(
  3948         PEP_SESSION session,
  3949         const char *fpr
  3950     )
  3951 {
  3952     return mark_as_compromised(session, fpr);
  3953 }
  3954 
  3955 DYNAMIC_API PEP_STATUS mark_as_compromised(
  3956         PEP_SESSION session,
  3957         const char *fpr
  3958     )
  3959 {
  3960     int result;
  3961 
  3962     assert(session);
  3963     assert(fpr && fpr[0]);
  3964 
  3965     if (!(session && fpr && fpr[0]))
  3966         return PEP_ILLEGAL_VALUE;
  3967 
  3968     sqlite3_reset(session->mark_compromised);
  3969     sqlite3_bind_text(session->mark_compromised, 1, fpr, -1,
  3970             SQLITE_STATIC);
  3971     result = Sqlite3_step(session->mark_compromised);
  3972     sqlite3_reset(session->mark_compromised);
  3973 
  3974     if (result != SQLITE_DONE)
  3975         return PEP_CANNOT_SET_TRUST;
  3976 
  3977     return PEP_STATUS_OK;
  3978 }
  3979 
  3980 void pEp_free(void *p)
  3981 {
  3982     free(p);
  3983 }
  3984 
  3985 
  3986 DYNAMIC_API PEP_STATUS get_trust(PEP_SESSION session, pEp_identity *identity)
  3987 {
  3988     PEP_STATUS status = PEP_STATUS_OK;
  3989     int result;
  3990 
  3991     // We need to be able to test that we break correctly without shutting
  3992     // asserts off everywhere.
  3993     // assert(session);
  3994     // assert(identity);
  3995     // assert(identity->user_id);
  3996     // assert(identity->user_id[0]);
  3997     // assert(identity->fpr);
  3998     // assert(identity->fpr[0]);
  3999 
  4000     if (!(session && identity && identity->user_id && identity->user_id[0] &&
  4001                 identity->fpr && identity->fpr[0]))
  4002         return PEP_ILLEGAL_VALUE;
  4003 
  4004     identity->comm_type = PEP_ct_unknown;
  4005     sqlite3_reset(session->get_trust);
  4006 
  4007     sqlite3_bind_text(session->get_trust, 1, identity->user_id, -1,
  4008             SQLITE_STATIC);
  4009     sqlite3_bind_text(session->get_trust, 2, identity->fpr, -1, SQLITE_STATIC);
  4010 
  4011     result = Sqlite3_step(session->get_trust);
  4012     switch (result) {
  4013     case SQLITE_ROW: {
  4014         int comm_type = (PEP_comm_type) sqlite3_column_int(session->get_trust,
  4015                 0);
  4016         identity->comm_type = comm_type;
  4017         break;
  4018     }
  4019  
  4020     default:
  4021         status = PEP_CANNOT_FIND_IDENTITY;
  4022     }
  4023 
  4024     sqlite3_reset(session->get_trust);
  4025     return status;
  4026 }
  4027 
  4028 
  4029 DYNAMIC_API PEP_STATUS least_trust(
  4030         PEP_SESSION session,
  4031         const char *fpr,
  4032         PEP_comm_type *comm_type
  4033     )
  4034 {
  4035     PEP_STATUS status = PEP_STATUS_OK;
  4036     int result;
  4037 
  4038     assert(session);
  4039     assert(fpr);
  4040     assert(comm_type);
  4041 
  4042     if (!(session && fpr && comm_type))
  4043         return PEP_ILLEGAL_VALUE;
  4044 
  4045     *comm_type = PEP_ct_unknown;
  4046 
  4047     sqlite3_reset(session->least_trust);
  4048     sqlite3_bind_text(session->least_trust, 1, fpr, -1, SQLITE_STATIC);
  4049 
  4050     result = Sqlite3_step(session->least_trust);
  4051     switch (result) {
  4052         case SQLITE_ROW: {
  4053             int _comm_type = sqlite3_column_int(session->least_trust, 0);
  4054             *comm_type = (PEP_comm_type) _comm_type;
  4055             break;
  4056         }
  4057         default:
  4058             // never reached because of sql min()
  4059             status = PEP_CANNOT_FIND_IDENTITY;
  4060     }
  4061 
  4062     sqlite3_reset(session->least_trust);
  4063     return status;
  4064 }
  4065 
  4066 DYNAMIC_API PEP_STATUS decrypt_and_verify(
  4067     PEP_SESSION session, const char *ctext, size_t csize,
  4068     const char *dsigtext, size_t dsigsize,
  4069     char **ptext, size_t *psize, stringlist_t **keylist,
  4070     char** filename_ptr
  4071     )
  4072 {
  4073     assert(session);
  4074     assert(ctext);
  4075     assert(csize);
  4076     assert(ptext);
  4077     assert(psize);
  4078     assert(keylist);
  4079 
  4080     if (!(session && ctext && csize && ptext && psize && keylist))
  4081         return PEP_ILLEGAL_VALUE;
  4082 
  4083     PEP_STATUS status = session->cryptotech[PEP_crypt_OpenPGP].decrypt_and_verify(
  4084             session, ctext, csize, dsigtext, dsigsize, ptext, psize, keylist,
  4085             filename_ptr);
  4086 
  4087     if (status == PEP_DECRYPT_NO_KEY)
  4088         signal_Sync_event(session, Sync_PR_keysync, CannotDecrypt, NULL);
  4089 
  4090     return status;
  4091 }
  4092 
  4093 DYNAMIC_API PEP_STATUS encrypt_and_sign(
  4094     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  4095     size_t psize, char **ctext, size_t *csize
  4096     )
  4097 {
  4098     assert(session);
  4099     assert(keylist);
  4100     assert(ptext);
  4101     assert(psize);
  4102     assert(ctext);
  4103     assert(csize);
  4104 
  4105     if (!(session && keylist && ptext && psize && ctext && csize))
  4106         return PEP_ILLEGAL_VALUE;
  4107 
  4108     return session->cryptotech[PEP_crypt_OpenPGP].encrypt_and_sign(session,
  4109             keylist, ptext, psize, ctext, csize);
  4110 }
  4111 
  4112 PEP_STATUS encrypt_only(
  4113     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  4114     size_t psize, char **ctext, size_t *csize
  4115     )
  4116 {
  4117     assert(session);
  4118     assert(keylist);
  4119     assert(ptext);
  4120     assert(psize);
  4121     assert(ctext);
  4122     assert(csize);
  4123 
  4124     if (!(session && keylist && ptext && psize && ctext && csize))
  4125         return PEP_ILLEGAL_VALUE;
  4126 
  4127     return session->cryptotech[PEP_crypt_OpenPGP].encrypt_only(session,
  4128             keylist, ptext, psize, ctext, csize);
  4129 }
  4130 
  4131 PEP_STATUS sign_only(PEP_SESSION session, 
  4132                      const char *data, 
  4133                      size_t data_size, 
  4134                      const char *fpr, 
  4135                      char **sign, 
  4136                      size_t *sign_size) {
  4137     assert(session);
  4138     assert(fpr);
  4139     assert(data);
  4140     assert(data_size);
  4141     assert(sign);
  4142     assert(sign_size);
  4143 
  4144     if (!(session && fpr && data && data_size && sign && sign_size))
  4145         return PEP_ILLEGAL_VALUE;
  4146 
  4147     return session->cryptotech[PEP_crypt_OpenPGP].sign_only(session,
  4148                                 fpr, data, data_size, sign, sign_size);
  4149                          
  4150 }
  4151 
  4152 
  4153 
  4154 DYNAMIC_API PEP_STATUS verify_text(
  4155     PEP_SESSION session, const char *text, size_t size,
  4156     const char *signature, size_t sig_size, stringlist_t **keylist
  4157     )
  4158 {
  4159     assert(session);
  4160     assert(text);
  4161     assert(size);
  4162     assert(signature);
  4163     assert(sig_size);
  4164     assert(keylist);
  4165 
  4166     if (!(session && text && size && signature && sig_size && keylist))
  4167         return PEP_ILLEGAL_VALUE;
  4168 
  4169     return session->cryptotech[PEP_crypt_OpenPGP].verify_text(session, text,
  4170             size, signature, sig_size, keylist);
  4171 }
  4172 
  4173 DYNAMIC_API PEP_STATUS delete_keypair(PEP_SESSION session, const char *fpr)
  4174 {
  4175     assert(session);
  4176     assert(fpr);
  4177 
  4178     if (!(session && fpr))
  4179         return PEP_ILLEGAL_VALUE;
  4180 
  4181     return session->cryptotech[PEP_crypt_OpenPGP].delete_keypair(session, fpr);
  4182 }
  4183 
  4184 DYNAMIC_API PEP_STATUS export_key(
  4185         PEP_SESSION session, const char *fpr, char **key_data, size_t *size
  4186     )
  4187 {
  4188     assert(session);
  4189     assert(fpr);
  4190     assert(key_data);
  4191     assert(size);
  4192 
  4193     if (!(session && fpr && key_data && size))
  4194         return PEP_ILLEGAL_VALUE;
  4195 
  4196     return session->cryptotech[PEP_crypt_OpenPGP].export_key(session, fpr,
  4197             key_data, size, false);
  4198 }
  4199 
  4200 DYNAMIC_API PEP_STATUS export_secret_key(
  4201         PEP_SESSION session, const char *fpr, char **key_data, size_t *size
  4202     )
  4203 {
  4204     assert(session);
  4205     assert(fpr);
  4206     assert(key_data);
  4207     assert(size);
  4208 
  4209     if (!(session && fpr && key_data && size))
  4210         return PEP_ILLEGAL_VALUE;
  4211 
  4212     // don't accept key IDs but full fingerprints only
  4213     if (strlen(fpr) < 16)
  4214         return PEP_ILLEGAL_VALUE;
  4215 
  4216     return session->cryptotech[PEP_crypt_OpenPGP].export_key(session, fpr,
  4217             key_data, size, true);
  4218 }
  4219 
  4220 // Deprecated
  4221 DYNAMIC_API PEP_STATUS export_secrect_key(
  4222         PEP_SESSION session, const char *fpr, char **key_data, size_t *size
  4223     )
  4224 {
  4225     return export_secret_key(session, fpr, key_data, size);
  4226 }
  4227 
  4228 DYNAMIC_API PEP_STATUS find_keys(
  4229         PEP_SESSION session, const char *pattern, stringlist_t **keylist
  4230     )
  4231 {
  4232     assert(session);
  4233     assert(pattern);
  4234     assert(keylist);
  4235 
  4236     if (!(session && pattern && keylist))
  4237         return PEP_ILLEGAL_VALUE;
  4238 
  4239     return session->cryptotech[PEP_crypt_OpenPGP].find_keys(session, pattern,
  4240             keylist);
  4241 }
  4242 
  4243 
  4244 DYNAMIC_API PEP_STATUS generate_keypair(
  4245         PEP_SESSION session, pEp_identity *identity
  4246     )
  4247 {
  4248     assert(session);
  4249     assert(identity);
  4250     assert(identity->address);
  4251     assert(identity->fpr == NULL || identity->fpr[0] == 0);
  4252     assert(identity->username);
  4253 
  4254     if (!(session && identity && identity->address &&
  4255             (identity->fpr == NULL || identity->fpr[0] == 0) &&
  4256             identity->username))
  4257         return PEP_ILLEGAL_VALUE;
  4258 
  4259     PEP_STATUS status =
  4260         session->cryptotech[PEP_crypt_OpenPGP].generate_keypair(session,
  4261                 identity);
  4262     if (status != PEP_STATUS_OK)
  4263         return status;
  4264 
  4265     if (identity->fpr)
  4266         status = set_pgp_keypair(session, identity->fpr);
  4267 
  4268     signal_Sync_event(session, Sync_PR_keysync, KeyGen, NULL);
  4269 
  4270     // add to known keypair DB, as this might not end up being a default
  4271     return status;
  4272 }
  4273 
  4274 DYNAMIC_API PEP_STATUS get_key_rating(
  4275         PEP_SESSION session,
  4276         const char *fpr,
  4277         PEP_comm_type *comm_type
  4278     )
  4279 {
  4280     assert(session);
  4281     assert(fpr);
  4282     assert(comm_type);
  4283 
  4284     if (!(session && fpr && comm_type))
  4285         return PEP_ILLEGAL_VALUE;
  4286 
  4287     return session->cryptotech[PEP_crypt_OpenPGP].get_key_rating(session, fpr,
  4288             comm_type);
  4289 }
  4290 
  4291 DYNAMIC_API PEP_STATUS import_key(
  4292         PEP_SESSION session,
  4293         const char *key_data,
  4294         size_t size,
  4295         identity_list **private_keys
  4296     )
  4297 {
  4298     assert(session);
  4299     assert(key_data);
  4300 
  4301     if (!(session && key_data))
  4302         return PEP_ILLEGAL_VALUE;
  4303 
  4304     return session->cryptotech[PEP_crypt_OpenPGP].import_key(session, key_data,
  4305             size, private_keys);
  4306 }
  4307 
  4308 DYNAMIC_API PEP_STATUS recv_key(PEP_SESSION session, const char *pattern)
  4309 {
  4310     assert(session);
  4311     assert(pattern);
  4312 
  4313     if (!(session && pattern))
  4314         return PEP_ILLEGAL_VALUE;
  4315 
  4316     return session->cryptotech[PEP_crypt_OpenPGP].recv_key(session, pattern);
  4317 }
  4318 
  4319 DYNAMIC_API PEP_STATUS send_key(PEP_SESSION session, const char *pattern)
  4320 {
  4321     assert(session);
  4322     assert(pattern);
  4323 
  4324     if (!(session && pattern))
  4325         return PEP_ILLEGAL_VALUE;
  4326 
  4327     return session->cryptotech[PEP_crypt_OpenPGP].send_key(session, pattern);
  4328 }
  4329 
  4330 DYNAMIC_API PEP_STATUS renew_key(
  4331         PEP_SESSION session,
  4332         const char *fpr,
  4333         const timestamp *ts
  4334     )
  4335 {
  4336     assert(session);
  4337     assert(fpr);
  4338 
  4339     if (!(session && fpr))
  4340         return PEP_ILLEGAL_VALUE;
  4341 
  4342     return session->cryptotech[PEP_crypt_OpenPGP].renew_key(session, fpr, ts);
  4343 }
  4344 
  4345 DYNAMIC_API PEP_STATUS revoke_key(
  4346         PEP_SESSION session,
  4347         const char *fpr,
  4348         const char *reason
  4349     )
  4350 {
  4351     assert(session);
  4352     assert(fpr);
  4353 
  4354     if (!(session && fpr))
  4355         return PEP_ILLEGAL_VALUE;
  4356 
  4357     // Check to see first if it is revoked
  4358     bool revoked = false;
  4359     PEP_STATUS status = key_revoked(session, fpr, &revoked);
  4360     if (status != PEP_STATUS_OK)
  4361         return status;
  4362         
  4363     if (revoked)
  4364         return PEP_STATUS_OK;
  4365 
  4366     return session->cryptotech[PEP_crypt_OpenPGP].revoke_key(session, fpr,
  4367             reason);
  4368 }
  4369 
  4370 DYNAMIC_API PEP_STATUS key_expired(
  4371         PEP_SESSION session,
  4372         const char *fpr,
  4373         const time_t when,
  4374         bool *expired
  4375     )
  4376 {
  4377     assert(session);
  4378     assert(fpr);
  4379     assert(expired);
  4380 
  4381     if (!(session && fpr && expired))
  4382         return PEP_ILLEGAL_VALUE;
  4383 
  4384     return session->cryptotech[PEP_crypt_OpenPGP].key_expired(session, fpr,
  4385             when, expired);
  4386 }
  4387 
  4388 DYNAMIC_API PEP_STATUS key_revoked(
  4389        PEP_SESSION session,
  4390        const char *fpr,
  4391        bool *revoked
  4392    )
  4393 {
  4394     assert(session);
  4395     assert(fpr);
  4396     assert(revoked);
  4397     
  4398     if (!(session && fpr && revoked))
  4399         return PEP_ILLEGAL_VALUE;
  4400     
  4401     return session->cryptotech[PEP_crypt_OpenPGP].key_revoked(session, fpr,
  4402             revoked);
  4403 }
  4404 
  4405 DYNAMIC_API PEP_STATUS config_cipher_suite(PEP_SESSION session,
  4406         PEP_CIPHER_SUITE suite)
  4407 {
  4408     assert(session);
  4409     if (!session)
  4410         return PEP_ILLEGAL_VALUE;
  4411 
  4412     return session->cryptotech[PEP_crypt_OpenPGP].config_cipher_suite(session, suite);
  4413 }
  4414 
  4415 static void _clean_log_value(char *text)
  4416 {
  4417     if (text) {
  4418         for (char *c = text; *c; c++) {
  4419             if (*c < 32 && *c != '\n')
  4420                 *c = 32;
  4421             else if (*c == '"')
  4422                 *c = '\'';
  4423         }
  4424     }
  4425 }
  4426 
  4427 static char *_concat_string(char *str1, const char *str2, char delim)
  4428 {
  4429     str2 = str2 ? str2 : "";
  4430     size_t len1 = str1 ? strlen(str1) : 0;
  4431     size_t len2 = strlen(str2);
  4432     size_t len = len1 + len2 + 3;
  4433     char * result = realloc(str1, len + 1);
  4434 
  4435     if (result) {
  4436         result[len1] = '"';
  4437         strcpy(result + len1 + 1, str2);
  4438         result[len - 2] = '"';
  4439         result[len - 1] = delim;
  4440         result[len] = 0;
  4441     }
  4442     else {
  4443         free(str1);
  4444     }
  4445 
  4446     return result;
  4447 }
  4448 
  4449 DYNAMIC_API PEP_STATUS get_crashdump_log(
  4450         PEP_SESSION session,
  4451         int maxlines,
  4452         char **logdata
  4453     )
  4454 {
  4455     PEP_STATUS status = PEP_STATUS_OK;
  4456     char *_logdata= NULL;
  4457 
  4458     assert(session);
  4459     assert(maxlines >= 0 && maxlines <= CRASHDUMP_MAX_LINES);
  4460     assert(logdata);
  4461 
  4462     if (!(session && logdata && maxlines >= 0 && maxlines <=
  4463             CRASHDUMP_MAX_LINES))
  4464         return PEP_ILLEGAL_VALUE;
  4465 
  4466     *logdata = NULL;
  4467 
  4468     int limit = maxlines ? maxlines : CRASHDUMP_DEFAULT_LINES;
  4469     const char *timestamp = NULL;
  4470     const char *title = NULL;
  4471     const char *entity = NULL;
  4472     const char *desc = NULL;
  4473     const char *comment = NULL;
  4474 
  4475     sqlite3_reset(session->crashdump);
  4476     sqlite3_bind_int(session->crashdump, 1, limit);
  4477 
  4478     int result;
  4479 
  4480     do {
  4481         result = Sqlite3_step(session->crashdump);
  4482         switch (result) {
  4483         case SQLITE_ROW:
  4484             timestamp = (const char *) sqlite3_column_text(session->crashdump,
  4485                     0);
  4486             title   = (const char *) sqlite3_column_text(session->crashdump,
  4487                     1);
  4488             entity  = (const char *) sqlite3_column_text(session->crashdump,
  4489                     2);
  4490             desc    = (const char *) sqlite3_column_text(session->crashdump,
  4491                     3);
  4492             comment = (const char *) sqlite3_column_text(session->crashdump,
  4493                     4);
  4494 
  4495             _logdata = _concat_string(_logdata, timestamp, ',');
  4496             if (_logdata == NULL)
  4497                 goto enomem;
  4498 
  4499             _logdata = _concat_string(_logdata, title, ',');
  4500             if (_logdata == NULL)
  4501                 goto enomem;
  4502 
  4503             _logdata = _concat_string(_logdata, entity, ',');
  4504             if (_logdata == NULL)
  4505                 goto enomem;
  4506 
  4507             _logdata = _concat_string(_logdata, desc, ',');
  4508             if (_logdata == NULL)
  4509                 goto enomem;
  4510 
  4511             _logdata = _concat_string(_logdata, comment, '\n');
  4512             if (_logdata == NULL)
  4513                 goto enomem;
  4514 
  4515             _clean_log_value(_logdata);
  4516             break;
  4517 
  4518         case SQLITE_DONE:
  4519             break;
  4520 
  4521         default:
  4522             status = PEP_UNKNOWN_ERROR;
  4523             result = SQLITE_DONE;
  4524         }
  4525     } while (result != SQLITE_DONE);
  4526 
  4527     sqlite3_reset(session->crashdump);
  4528     if (status == PEP_STATUS_OK) {
  4529         if (_logdata) {
  4530             *logdata = _logdata;
  4531         }
  4532         else {
  4533             *logdata = strdup("");
  4534             if (!*logdata)
  4535                 goto enomem;
  4536         }
  4537     }
  4538 
  4539     goto the_end;
  4540 
  4541 enomem:
  4542     status = PEP_OUT_OF_MEMORY;
  4543 
  4544 the_end:
  4545     return status;
  4546 }
  4547 
  4548 DYNAMIC_API PEP_STATUS get_languagelist(
  4549         PEP_SESSION session,
  4550         char **languages
  4551     )
  4552 {
  4553     PEP_STATUS status = PEP_STATUS_OK;
  4554     char *_languages= NULL;
  4555 
  4556     assert(session);
  4557     assert(languages);
  4558 
  4559     if (!(session && languages))
  4560         return PEP_ILLEGAL_VALUE;
  4561 
  4562     *languages = NULL;
  4563 
  4564     const char *lang = NULL;
  4565     const char *name = NULL;
  4566     const char *phrase = NULL;
  4567 
  4568     sqlite3_reset(session->languagelist);
  4569 
  4570     int result;
  4571 
  4572     do {
  4573         result = Sqlite3_step(session->languagelist);
  4574         switch (result) {
  4575         case SQLITE_ROW:
  4576             lang = (const char *) sqlite3_column_text(session->languagelist,
  4577                     0);
  4578             name = (const char *) sqlite3_column_text(session->languagelist,
  4579                     1);
  4580             phrase = (const char *) sqlite3_column_text(session->languagelist,
  4581                     2);
  4582 
  4583             _languages = _concat_string(_languages, lang, ',');
  4584             if (_languages == NULL)
  4585                 goto enomem;
  4586 
  4587             _languages = _concat_string(_languages, name, ',');
  4588             if (_languages == NULL)
  4589                 goto enomem;
  4590 
  4591             _languages = _concat_string(_languages, phrase, '\n');
  4592             if (_languages == NULL)
  4593                 goto enomem;
  4594 
  4595             break;
  4596 
  4597         case SQLITE_DONE:
  4598             break;
  4599 
  4600         default:
  4601             status = PEP_UNKNOWN_DB_ERROR;
  4602             result = SQLITE_DONE;
  4603         }
  4604     } while (result != SQLITE_DONE);
  4605 
  4606     sqlite3_reset(session->languagelist);
  4607     if (status == PEP_STATUS_OK)
  4608         *languages = _languages;
  4609 
  4610     goto the_end;
  4611 
  4612 enomem:
  4613     status = PEP_OUT_OF_MEMORY;
  4614 
  4615 the_end:
  4616     return status;
  4617 }
  4618 
  4619 DYNAMIC_API PEP_STATUS get_phrase(
  4620         PEP_SESSION session,
  4621         const char *lang,
  4622         int phrase_id,
  4623         char **phrase
  4624     )
  4625 {
  4626     PEP_STATUS status = PEP_STATUS_OK;
  4627 
  4628     assert(session && lang && lang[0] && lang[1] && lang[2] == 0 && phrase);
  4629     if (!(session && lang && lang[0] && lang[1] && lang[2] == 0 && phrase))
  4630         return PEP_ILLEGAL_VALUE;
  4631 
  4632     *phrase = NULL;
  4633 
  4634     sqlite3_reset(session->i18n_token);
  4635     sqlite3_bind_text(session->i18n_token, 1, lang, -1, SQLITE_STATIC);
  4636     sqlite3_bind_int(session->i18n_token, 2, phrase_id);
  4637 
  4638     const char *_phrase = NULL;
  4639     int result;
  4640 
  4641     result = Sqlite3_step(session->i18n_token);
  4642     switch (result) {
  4643     case SQLITE_ROW:
  4644         _phrase = (const char *) sqlite3_column_text(session->i18n_token, 0);
  4645         break;
  4646 
  4647     case SQLITE_DONE:
  4648         status = PEP_PHRASE_NOT_FOUND;
  4649         break;
  4650 
  4651     default:
  4652         status = PEP_UNKNOWN_DB_ERROR;
  4653     }
  4654 
  4655     if (status == PEP_STATUS_OK) {
  4656         *phrase = strdup(_phrase);
  4657         if (*phrase == NULL)
  4658             goto enomem;
  4659     }
  4660 
  4661     sqlite3_reset(session->i18n_token);
  4662     goto the_end;
  4663 
  4664 enomem:
  4665     status = PEP_OUT_OF_MEMORY;
  4666 
  4667 the_end:
  4668     return status;
  4669 }
  4670 
  4671 static PEP_STATUS _get_sequence_value(PEP_SESSION session, const char *name,
  4672         int32_t *value)
  4673 {
  4674     assert(session && name && value);
  4675     if (!(session && name && value))
  4676         return PEP_ILLEGAL_VALUE;
  4677 
  4678     PEP_STATUS status = PEP_STATUS_OK;
  4679 
  4680     sqlite3_reset(session->sequence_value2);
  4681     sqlite3_bind_text(session->sequence_value2, 1, name, -1,
  4682             SQLITE_STATIC);
  4683     int result = Sqlite3_step(session->sequence_value2);
  4684     switch (result) {
  4685         case SQLITE_ROW: {
  4686             int32_t _value = (int32_t)
  4687                     sqlite3_column_int(session->sequence_value2, 0);
  4688             *value = _value;
  4689             break;
  4690         }
  4691         case SQLITE_DONE:
  4692             status = PEP_RECORD_NOT_FOUND;
  4693             break;
  4694         default:
  4695             status = PEP_UNKNOWN_DB_ERROR;
  4696     }
  4697     sqlite3_reset(session->sequence_value2);
  4698 
  4699     return status;
  4700 }
  4701 
  4702 static PEP_STATUS _increment_sequence_value(PEP_SESSION session,
  4703         const char *name)
  4704 {
  4705     assert(session && name);
  4706     if (!(session && name))
  4707         return PEP_ILLEGAL_VALUE;
  4708 
  4709     sqlite3_reset(session->sequence_value1);
  4710     sqlite3_bind_text(session->sequence_value1, 1, name, -1, SQLITE_STATIC);
  4711     int result = Sqlite3_step(session->sequence_value1);
  4712     assert(result == SQLITE_DONE);
  4713     sqlite3_reset(session->sequence_value1);
  4714     if (result == SQLITE_DONE)
  4715         return PEP_STATUS_OK;
  4716     else
  4717         return PEP_CANNOT_INCREASE_SEQUENCE;
  4718 }
  4719 
  4720 DYNAMIC_API PEP_STATUS sequence_value(
  4721         PEP_SESSION session,
  4722         const char *name,
  4723         int32_t *value
  4724     )
  4725 {
  4726     PEP_STATUS status = PEP_STATUS_OK;
  4727 
  4728     assert(session);
  4729     assert(name && value);
  4730 
  4731     if (!(session && name && name[0] && value))
  4732         return PEP_ILLEGAL_VALUE;
  4733 
  4734     *value = 0;
  4735     sqlite3_exec(session->db, "BEGIN TRANSACTION ;", NULL, NULL, NULL);
  4736     status = _increment_sequence_value(session, name);
  4737     if (status == PEP_STATUS_OK)
  4738         status = _get_sequence_value(session, name, value);
  4739 
  4740     if (status == PEP_STATUS_OK) {
  4741         int result = sqlite3_exec(session->db, "COMMIT ;", NULL, NULL, NULL);
  4742         if (result == SQLITE_OK){
  4743             assert(*value < INT32_MAX);
  4744             if (*value == INT32_MAX){
  4745                 return PEP_CANNOT_INCREASE_SEQUENCE;
  4746             }
  4747             return status;
  4748         } else {
  4749             return PEP_COMMIT_FAILED;
  4750         }
  4751     } else {
  4752         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  4753         return status;
  4754     }
  4755 
  4756     return status;
  4757 }
  4758 
  4759 PEP_STATUS is_own_key(PEP_SESSION session, const char* fpr, bool* own_key) {
  4760     
  4761     assert(session);
  4762     assert(!EMPTYSTR(fpr));
  4763 
  4764     if (!session || EMPTYSTR(fpr))
  4765         return PEP_ILLEGAL_VALUE;
  4766     
  4767     *own_key = false;
  4768     sqlite3_reset(session->own_key_is_listed);
  4769     
  4770     sqlite3_bind_text(session->own_key_is_listed, 1, fpr, -1,
  4771             SQLITE_STATIC);
  4772     int result = Sqlite3_step(session->own_key_is_listed);
  4773     switch (result) {
  4774         case SQLITE_ROW: {
  4775             *own_key = (sqlite3_column_int(session->own_key_is_listed, 0) != 0);
  4776             break;
  4777         }
  4778         default:
  4779             sqlite3_reset(session->own_key_is_listed);
  4780             return PEP_UNKNOWN_DB_ERROR;
  4781     }
  4782 
  4783     sqlite3_reset(session->own_key_is_listed);
  4784     return PEP_STATUS_OK;
  4785 
  4786 }
  4787 
  4788 DYNAMIC_API PEP_STATUS set_revoked(
  4789        PEP_SESSION session,
  4790        const char *revoked_fpr,
  4791        const char *replacement_fpr,
  4792        const uint64_t revocation_date
  4793     )
  4794 {
  4795     PEP_STATUS status = PEP_STATUS_OK;
  4796     
  4797     assert(session &&
  4798            revoked_fpr && revoked_fpr[0] &&
  4799            replacement_fpr && replacement_fpr[0]
  4800           );
  4801     
  4802     if (!(session &&
  4803           revoked_fpr && revoked_fpr[0] &&
  4804           replacement_fpr && replacement_fpr[0]
  4805          ))
  4806         return PEP_ILLEGAL_VALUE;
  4807     
  4808     sqlite3_reset(session->set_revoked);
  4809     sqlite3_bind_text(session->set_revoked, 1, revoked_fpr, -1, SQLITE_STATIC);
  4810     sqlite3_bind_text(session->set_revoked, 2, replacement_fpr, -1,
  4811             SQLITE_STATIC);
  4812     sqlite3_bind_int64(session->set_revoked, 3, revocation_date);
  4813 
  4814     int result;
  4815     
  4816     result = Sqlite3_step(session->set_revoked);
  4817     switch (result) {
  4818         case SQLITE_DONE:
  4819             status = PEP_STATUS_OK;
  4820             break;
  4821             
  4822         default:
  4823             status = PEP_UNKNOWN_DB_ERROR;
  4824     }
  4825     
  4826     sqlite3_reset(session->set_revoked);
  4827     return status;
  4828 }
  4829 
  4830 DYNAMIC_API PEP_STATUS get_revoked(
  4831         PEP_SESSION session,
  4832         const char *fpr,
  4833         char **revoked_fpr,
  4834         uint64_t *revocation_date
  4835     )
  4836 {
  4837     PEP_STATUS status = PEP_STATUS_OK;
  4838 
  4839     assert(session &&
  4840            revoked_fpr &&
  4841            fpr && fpr[0]
  4842           );
  4843     
  4844     if (!(session &&
  4845            revoked_fpr &&
  4846            fpr && fpr[0]
  4847           ))
  4848         return PEP_ILLEGAL_VALUE;
  4849 
  4850     *revoked_fpr = NULL;
  4851     *revocation_date = 0;
  4852 
  4853     sqlite3_reset(session->get_revoked);
  4854     sqlite3_bind_text(session->get_revoked, 1, fpr, -1, SQLITE_STATIC);
  4855 
  4856     int result;
  4857     
  4858     result = Sqlite3_step(session->get_revoked);
  4859     switch (result) {
  4860         case SQLITE_ROW: {
  4861             *revoked_fpr = strdup((const char *)
  4862                     sqlite3_column_text(session->get_revoked, 0));
  4863             if(*revoked_fpr)
  4864                 *revocation_date = sqlite3_column_int64(session->get_revoked,
  4865                         1);
  4866             else
  4867                 status = PEP_OUT_OF_MEMORY;
  4868 
  4869             break;
  4870         }
  4871         default:
  4872             status = PEP_CANNOT_FIND_IDENTITY;
  4873     }
  4874 
  4875     sqlite3_reset(session->get_revoked);
  4876 
  4877     return status;
  4878 }
  4879 
  4880 DYNAMIC_API PEP_STATUS get_replacement_fpr(
  4881         PEP_SESSION session,
  4882         const char *fpr,
  4883         char **revoked_fpr,
  4884         uint64_t *revocation_date
  4885     )
  4886 {
  4887     PEP_STATUS status = PEP_STATUS_OK;
  4888 
  4889     assert(session && revoked_fpr && !EMPTYSTR(fpr) && revocation_date);
  4890     
  4891     if (!session || !revoked_fpr || EMPTYSTR(fpr) || !revocation_date)
  4892         return PEP_ILLEGAL_VALUE;
  4893 
  4894     *revoked_fpr = NULL;
  4895     *revocation_date = 0;
  4896 
  4897     sqlite3_reset(session->get_replacement_fpr);
  4898     sqlite3_bind_text(session->get_replacement_fpr, 1, fpr, -1, SQLITE_STATIC);
  4899 
  4900     int result;
  4901     
  4902     result = Sqlite3_step(session->get_replacement_fpr);
  4903     switch (result) {
  4904         case SQLITE_ROW: {
  4905             *revoked_fpr = strdup((const char *)
  4906                     sqlite3_column_text(session->get_replacement_fpr, 0));
  4907             if(*revoked_fpr)
  4908                 *revocation_date = sqlite3_column_int64(session->get_replacement_fpr,
  4909                         1);
  4910             else
  4911                 status = PEP_OUT_OF_MEMORY;
  4912 
  4913             break;
  4914         }
  4915         default:
  4916             status = PEP_CANNOT_FIND_IDENTITY;
  4917     }
  4918 
  4919     sqlite3_reset(session->get_replacement_fpr);
  4920 
  4921     return status;
  4922 }
  4923 
  4924 PEP_STATUS get_last_contacted(
  4925         PEP_SESSION session,
  4926         identity_list** id_list
  4927     )
  4928 {
  4929     assert(session);
  4930     assert(id_list);
  4931 
  4932     if (!(session && id_list))
  4933         return PEP_ILLEGAL_VALUE;
  4934 
  4935     *id_list = NULL;
  4936     identity_list* ident_list = NULL;
  4937 
  4938     sqlite3_reset(session->get_last_contacted);
  4939     int result;
  4940 
  4941     while ((result = Sqlite3_step(session->get_last_contacted)) == SQLITE_ROW) {
  4942         pEp_identity *ident = new_identity(
  4943                 (const char *) sqlite3_column_text(session->get_last_contacted, 1),
  4944                 NULL,
  4945                 (const char *) sqlite3_column_text(session->get_last_contacted, 0),
  4946                 NULL);
  4947                 
  4948         assert(ident);
  4949         if (ident == NULL) {
  4950             sqlite3_reset(session->get_last_contacted);
  4951             return PEP_OUT_OF_MEMORY;
  4952         }
  4953     
  4954         if (ident_list)
  4955             identity_list_add(ident_list, ident);
  4956         else
  4957             ident_list = new_identity_list(ident);
  4958     }
  4959 
  4960     sqlite3_reset(session->get_last_contacted);
  4961     
  4962     *id_list = ident_list;
  4963     
  4964     if (!ident_list)
  4965         return PEP_CANNOT_FIND_IDENTITY;
  4966     
  4967     return PEP_STATUS_OK;    
  4968 }
  4969 
  4970 
  4971 PEP_STATUS key_created(
  4972         PEP_SESSION session,
  4973         const char *fpr,
  4974         time_t *created
  4975     )
  4976 {
  4977     assert(session && fpr && created);
  4978     if (!(session && fpr && created))
  4979         return PEP_ILLEGAL_VALUE;
  4980 
  4981     return session->cryptotech[PEP_crypt_OpenPGP].key_created(session, fpr,
  4982             created);
  4983 }
  4984 
  4985 PEP_STATUS find_private_keys(PEP_SESSION session, const char* pattern,
  4986                              stringlist_t **keylist) {
  4987     assert(session && keylist);
  4988     if (!(session && keylist))
  4989         return PEP_ILLEGAL_VALUE;
  4990     
  4991     return session->cryptotech[PEP_crypt_OpenPGP].find_private_keys(session, pattern,
  4992                                                                     keylist);
  4993 }
  4994 
  4995 
  4996 DYNAMIC_API const char* get_engine_version() {
  4997     return PEP_ENGINE_VERSION;
  4998 }
  4999 
  5000 DYNAMIC_API const char* get_protocol_version() {
  5001     return PEP_VERSION;
  5002 }
  5003 
  5004 DYNAMIC_API PEP_STATUS reset_pEptest_hack(PEP_SESSION session)
  5005 {
  5006     assert(session);
  5007 
  5008     if (!session)
  5009         return PEP_ILLEGAL_VALUE;
  5010 
  5011     int int_result = sqlite3_exec(
  5012         session->db,
  5013         "delete from identity where address like '%@pEptest.ch' ;",
  5014         NULL,
  5015         NULL,
  5016         NULL
  5017     );
  5018     assert(int_result == SQLITE_OK);
  5019 
  5020     if (int_result != SQLITE_OK)
  5021         return PEP_UNKNOWN_DB_ERROR;
  5022 
  5023     return PEP_STATUS_OK;
  5024 }
  5025 
  5026 #ifdef DEBUG_ERRORSTACK
  5027 PEP_STATUS session_add_error(PEP_SESSION session, const char* file, unsigned line, PEP_STATUS status)
  5028 {
  5029     char logline[48];
  5030     if(status>0)
  5031     {
  5032         snprintf(logline,47, "%.24s:%u status=%u (0x%x)", file, line, status, status);
  5033     }else{
  5034         snprintf(logline,47, "%.24s:%u status=%i.", file, line, status);
  5035     }
  5036     stringlist_add(session->errorstack, logline); // logline is copied! :-)
  5037     return status;
  5038 }
  5039 
  5040 DYNAMIC_API const stringlist_t* get_errorstack(PEP_SESSION session)
  5041 {
  5042     return session->errorstack;
  5043 }
  5044 
  5045 DYNAMIC_API void clear_errorstack(PEP_SESSION session)
  5046 {
  5047     const int old_len = stringlist_length(session->errorstack);
  5048     char buf[48];
  5049     free_stringlist(session->errorstack);
  5050     snprintf(buf, 47, "(%i elements cleared)", old_len);
  5051     session->errorstack = new_stringlist(buf);
  5052 }
  5053 
  5054 #else
  5055 
  5056 static stringlist_t* dummy_errorstack = NULL;
  5057 
  5058 DYNAMIC_API const stringlist_t* get_errorstack(PEP_SESSION session)
  5059 {
  5060     if(dummy_errorstack == NULL)
  5061     {
  5062         dummy_errorstack = new_stringlist("( Please recompile pEpEngine with -DDEBUG_ERRORSTACK )");
  5063     }
  5064 
  5065     return dummy_errorstack;
  5066 }
  5067 
  5068 DYNAMIC_API void clear_errorstack(PEP_SESSION session)
  5069 {
  5070     // nothing to do here
  5071 }
  5072 
  5073 #endif