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