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