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