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