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