src/pEpEngine.c
author Krista Bennett <krista@pep-project.org>
Fri, 15 Jun 2018 20:17:49 +0200
branchENGINE-398
changeset 2752 713b65791080
parent 2747 f1158ffe70e2
child 2799 913e407519e2
permissions -rw-r--r--
shelving to debug other things
     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 
    10 #include <time.h>
    11 #include <stdlib.h>
    12 
    13 #define _PEP_SQLITE_DEBUG 0
    14 #if _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     char *z1;
    23     const char *z2;
    24     int i, n;
    25     z2 = (char*)sqlite3_value_text(argv[0]);
    26     n = sqlite3_value_bytes(argv[0]);
    27     /* Verify that the call to _bytes() does not invalidate the _text() pointer */
    28     assert( z2==(char*)sqlite3_value_text(argv[0]) );
    29     if( z2 ){
    30         z1 = (char*)sqlite3_malloc(n+1);
    31         if( z1 ){
    32             for(i=0; i<n; i++){
    33                 char c = z2[i];
    34                 char c_mod = c | 0x20;
    35                 if (c_mod < 0x61 || c_mod > 0x7a)
    36                     c_mod = c;
    37                 z1[i] = c_mod;
    38             }
    39             z1[n] = '\0';
    40             sqlite3_result_text(ctx, z1, n, sqlite3_free);
    41         }
    42     }
    43 }
    44 
    45 #if _PEP_SQLITE_DEBUG
    46 int sql_trace_callback (unsigned trace_constant, 
    47                         void* context_ptr,
    48                         void* P,
    49                         void* X) {
    50     switch (trace_constant) {
    51         case SQLITE_TRACE_STMT:
    52             fprintf(stderr, "SQL_DEBUG: STMT - ");
    53             const char* X_str = (const char*) X;
    54             if (!EMPTYSTR(X_str) && X_str[0] == '-' && X_str[1] == '-')
    55                 fprintf(stderr, "%s\n", X_str);
    56             else
    57                 fprintf(stderr, "%s\n", sqlite3_expanded_sql((sqlite3_stmt*)P));
    58             break;
    59         case SQLITE_TRACE_ROW:
    60             fprintf(stderr, "SQL_DEBUG: ROW - ");
    61             fprintf(stderr, "%s\n", sqlite3_expanded_sql((sqlite3_stmt*)P));
    62             break;            
    63         case SQLITE_TRACE_CLOSE:
    64             fprintf(stderr, "SQL_DEBUG: CLOSE - ");
    65             break;
    66         default:
    67             break;
    68     }
    69     return 0;
    70 }
    71 #endif
    72 
    73 // sql manipulation statements
    74 static const char *sql_log = 
    75     "insert into log (title, entity, description, comment)"
    76      "values (?1, ?2, ?3, ?4);";
    77 
    78 static const char *sql_trustword = 
    79     "select id, word from wordlist where lang = lower(?1) "
    80     "and id = ?2 ;";
    81 
    82 static const char *sql_get_identity =  
    83     "select fpr, username, comm_type, lang,"
    84     "   identity.flags | pgp_keypair.flags,"
    85     "   is_own"
    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_identity_without_trust_check =  
   101     "select identity.main_key_id, username, lang,"
   102     "   identity.flags, is_own"
   103     "   from identity"
   104     "   join person on id = identity.user_id"
   105     "   where (case when (address = ?1) then (1)"
   106     "               when (lower(address) = lower(?1)) then (1)"
   107     "               when (replace(lower(address),'.','') = replace(lower(?1),'.','')) then (1)"
   108     "               else 0"
   109     "          end) = 1"
   110     "   and identity.user_id = ?2 "
   111     "   order by is_own desc, "
   112     "   timestamp desc; ";
   113 
   114 static const char *sql_get_identities_by_address =  
   115     "select user_id, identity.main_key_id, username, lang,"
   116     "   identity.flags, is_own"
   117     "   from identity"
   118     "   join person on id = identity.user_id"
   119     "   where (case when (address = ?1) then (1)"
   120     "               when (lower(address) = lower(?1)) then (1)"
   121     "               when (replace(lower(address),'.','') = replace(lower(?1),'.','')) then (1)"
   122     "               else 0"
   123     "          end) = 1 "
   124     "   order by is_own desc, "
   125     "   timestamp desc; ";
   126 
   127 static const char *sql_replace_identities_fpr =  
   128     "update identity"
   129     "   set main_key_id = ?1 "
   130     "   where main_key_id = ?2 ;";
   131     
   132 static const char *sql_remove_fpr_as_default =
   133     "update person set main_key_id = NULL where main_key_id = ?1 ;"
   134     "update identity set main_key_id = NULL where main_key_id = ?1 ;";
   135 
   136 // Set person, but if already exist, only update.
   137 // if main_key_id already set, don't touch.
   138 static const char *sql_set_person = 
   139      "insert into person (id, username, lang, main_key_id, device_group)"
   140      "  values (?1, ?2, ?3, ?4, "
   141      "          (select device_group from person where id = ?1)) ;";
   142 
   143 static const char *sql_update_person = 
   144     "update person "
   145     "   set username = ?2, "
   146     "       lang = ?3, "
   147     "       main_key_id =  "
   148     "           (select coalesce( "
   149     "               (select main_key_id from person where id = ?1), " 
   150     "                upper(replace(?4,' ','')))),"         
   151     "       device_group = "
   152     "           (select device_group from person where id = ?1)"
   153     "   where id = ?1 ;";
   154     
   155 static const char *sql_set_as_pep_user =
   156     "update person set is_pep_user = 1 "
   157     "   where id = ?1 ; ";
   158 
   159 static const char *sql_is_pep_user =
   160     "select is_pep_user from person "
   161     "   where id = ?1 ; ";
   162 
   163 static const char* sql_exists_person = 
   164     "select count(*) from person "
   165     "   where id = ?1 ;";
   166 
   167 static const char *sql_set_device_group = 
   168     "update person set device_group = ?1 "
   169     "   where id = ?2;";
   170 
   171 // This will cascade to identity and trust
   172 static const char* sql_replace_userid =
   173     "update person set id = ?1 " 
   174     "   where id = ?2;";
   175 
   176 static const char *sql_replace_main_user_fpr =  
   177     "update person "
   178     "   set main_key_id = ?1 "
   179     "   where id = ?2 ;";
   180 
   181 static const char *sql_get_main_user_fpr =  
   182     "select main_key_id from person"
   183     "   where id = ?1 ;";
   184 
   185 static const char *sql_refresh_userid_default_key =
   186     "update person "
   187     "   set main_key_id = "
   188     "       (select identity.main_key_id from identity "
   189     "           join trust on trust.user_id = identity.user_id "
   190     "               and trust.pgp_keypair_fpr = identity.main_key_id "
   191     "           join person on identity.user_id = identity.user_id "
   192     "       where identity.user_id = ?1 "
   193     "       order by trust.comm_type desc "
   194     "       limit 1) "
   195     "where id = ?1 ; ";
   196 
   197 static const char *sql_get_device_group = 
   198     "select device_group from person "
   199     "where id = ?1;";
   200 
   201 static const char *sql_set_pgp_keypair = 
   202     "insert or ignore into pgp_keypair (fpr) "
   203     "values (upper(replace(?1,' ',''))) ;";
   204 
   205 static const char* sql_exists_identity_entry = 
   206     "select count(*) from identity "
   207     "   where (case when (address = ?1) then (1)"
   208     "               when (lower(address) = lower(?1)) then (1)"
   209     "               when (replace(lower(address),'.','') = replace(lower(?1),'.','')) then (1)"
   210     "               else 0"
   211     "          end) = 1"
   212     "    and user_id = ?2;";
   213  
   214 static const char *sql_set_identity_entry = 
   215     "insert into identity ("
   216     "       address, main_key_id, "
   217     "       user_id, flags, is_own"
   218     "   ) values ("
   219     "       ?1,"
   220     "       upper(replace(?2,' ','')),"
   221     "       ?3,"
   222     "       ?4,"
   223     "       ?5"
   224     "   );";
   225     
   226 static const char* sql_update_identity_entry =    
   227     "update identity "
   228     "   set main_key_id = upper(replace(?2,' ','')), "
   229     "       flags = ?4, " 
   230     "       is_own = ?5 "
   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 = ?3 ;";
   237 
   238     // " (select"
   239     // "   coalesce("
   240     // "    (select flags from identity"
   241     // "     where address = ?1 and"
   242     // "           user_id = ?3),"
   243     // "    0)"
   244     // " ) | (?4 & 255)"
   245     /* set_identity ignores previous flags, and doesn't filter machine flags */
   246         
   247 static const char *sql_set_identity_flags = 
   248     "update identity set flags = "
   249     "    ((?1 & 255) | (select flags from identity"
   250     "                    where (case when (address = ?2) then (1)"
   251     "                                when (lower(address) = lower(?2)) then (1)"
   252     "                                when (replace(lower(address),'.','') = replace(lower(?2),'.','')) then (1)"
   253     "                                else 0 "    
   254     "                           end) = 1 "
   255     "                           and user_id = ?3)) "
   256     "   where (case when (address = ?2) then (1)"
   257     "               when (lower(address) = lower(?2)) then (1)"
   258     "               when (replace(lower(address),'.','') = replace(lower(?2),'.','')) then (1)"
   259     "               else 0"
   260     "          end) = 1"
   261     "          and user_id = ?3 ;";
   262 
   263 static const char *sql_unset_identity_flags = 
   264     "update identity set flags = "
   265     "    ( ~(?1 & 255) & (select flags from identity"
   266     "                    where (case when (address = ?2) then (1)"
   267     "                                when (lower(address) = lower(?2)) then (1)"
   268     "                                when (replace(lower(address),'.','') = replace(lower(?2),'.','')) then (1)"
   269     "                                else 0 "    
   270     "                           end) = 1 "
   271     "                           and user_id = ?3)) "
   272     "   where (case when (address = ?2) then (1)"
   273     "               when (lower(address) = lower(?2)) then (1)"
   274     "               when (replace(lower(address),'.','') = replace(lower(?2),'.','')) then (1)"
   275     "               else 0"
   276     "          end) = 1"
   277     "          and user_id = ?3 ;";
   278 
   279 static const char *sql_set_trust =
   280     "insert into trust (user_id, pgp_keypair_fpr, comm_type) "
   281     "values (?1, upper(replace(?2,' ','')), ?3) ;";
   282 
   283 static const char *sql_update_trust =
   284     "update trust set comm_type = ?3 " 
   285     "   where user_id = ?1 and pgp_keypair_fpr = upper(replace(?2,' ',''));";
   286 
   287 static const char *sql_update_trust_to_pep =
   288     "update trust set comm_type = comm_type + 71 "
   289     "   where (user_id = ?1 "
   290     "          and (case when (comm_type = 56) then (1) "
   291     "                    when (comm_type = 184) then (1) "
   292     "                    else 0"
   293     "               end) = 1); ";
   294 
   295 static const char* sql_exists_trust_entry = 
   296     "select count(*) from trust "
   297     "   where user_id = ?1 and pgp_keypair_fpr = upper(replace(?2,' ',''));";
   298     
   299 static const char *sql_update_trust_for_fpr =
   300     "update trust "
   301     "set comm_type = ?1 "
   302     "where pgp_keypair_fpr = upper(replace(?2,' ','')) ;";
   303 
   304 static const char *sql_get_trust = 
   305     "select comm_type from trust where user_id = ?1 "
   306     "and pgp_keypair_fpr = upper(replace(?2,' ','')) ;";
   307 
   308 static const char *sql_least_trust = 
   309     "select min(comm_type) from trust where"
   310     " pgp_keypair_fpr = upper(replace(?1,' ',''))"
   311     " and comm_type != 0;"; // ignores PEP_ct_unknown
   312     // returns PEP_ct_unknown only when no known trust is recorded
   313 
   314 static const char *sql_mark_as_compromised = 
   315     "update trust not indexed set comm_type = 15"
   316     " where pgp_keypair_fpr = upper(replace(?1,' ','')) ;";
   317     
   318 static const char *sql_crashdump = 
   319     "select timestamp, title, entity, description, comment"
   320     " from log order by timestamp desc limit ?1 ;";
   321 
   322 static const char *sql_languagelist = 
   323     "select i18n_language.lang, name, phrase" 
   324     " from i18n_language join i18n_token using (lang) where i18n_token.id = 1000;" ;
   325 
   326 static const char *sql_i18n_token = 
   327     "select phrase from i18n_token where lang = lower(?1) and id = ?2 ;";
   328 
   329 // blacklist
   330 static const char *sql_blacklist_add = 
   331     "insert or ignore into blacklist_keys (fpr) values (upper(replace(?1,' ',''))) ;"
   332     "delete from identity where main_key_id = upper(replace(?1,' ','')) ;"
   333     "delete from pgp_keypair where fpr = upper(replace(?1,' ','')) ;";
   334 
   335 static const char *sql_blacklist_delete =
   336     "delete from blacklist_keys where fpr = upper(replace(?1,' ','')) ;";
   337 
   338 static const char *sql_blacklist_is_listed = 
   339     "select count(*) from blacklist_keys where fpr = upper(replace(?1,' ','')) ;";
   340 
   341 static const char *sql_blacklist_retrieve = 
   342     "select * from blacklist_keys ;";
   343                 
   344 
   345 // Own keys
   346 // We only care if it's 0 or non-zero
   347 static const char *sql_own_key_is_listed = 
   348     "select count(*) from ("
   349     "   select pgp_keypair_fpr from trust"
   350     "      join identity on trust.user_id = identity.user_id"
   351     "      where pgp_keypair_fpr = upper(replace(?1,' ',''))"
   352     "           and identity.is_own = 1"
   353     ");";
   354 
   355 static const char *sql_own_identities_retrieve =  
   356     "select address, fpr, username, identity.user_id, "
   357     "   lang, identity.flags | pgp_keypair.flags"
   358     "   from identity"
   359     "   join person on id = identity.user_id"
   360     "   join pgp_keypair on fpr = identity.main_key_id"
   361     "   join trust on id = trust.user_id"
   362     "       and pgp_keypair_fpr = identity.main_key_id"
   363     "   where identity.is_own = 1"
   364     "       and (identity.flags & ?1) = 0;";
   365 
   366 static const char *sql_own_keys_retrieve = 
   367     "select pgp_keypair_fpr from trust"
   368     "   join identity on trust.user_id = identity.user_id"
   369     "   where identity.is_own = 1";
   370 
   371 static const char* sql_get_user_default_key =
   372     "select main_key_id from person" 
   373     "   where id = ?1;";
   374 
   375 static const char* sql_get_default_own_userid =
   376     "select id from person"
   377     "   join identity on id = identity.user_id"
   378     "   where identity.is_own = 1";
   379 
   380 // Sequence
   381 static const char *sql_sequence_value1 = 
   382     "insert or replace into sequences (name, value, own) "
   383     "values (?1, "
   384     "       (select coalesce((select value + 1 from sequences "
   385     "           where name = ?1), 1 )), "
   386     "       (select coalesce((select own or ?2 from sequences "
   387     "           where name = ?1), ?2))) ; ";
   388 
   389 static const char *sql_sequence_value2 = 
   390     "select value, own from sequences where name = ?1 ;";
   391 
   392 static const char *sql_sequence_value3 = 
   393     "insert or replace into sequences (name, value, own) "
   394     "values (?1, "
   395     "        ?2, "
   396     "       (select coalesce((select own or ?3 from sequences "
   397     "           where name = ?1), ?3))) ; ";
   398         
   399 // Revocation tracking
   400 static const char *sql_set_revoked =
   401     "insert or replace into revoked_keys ("
   402     "    revoked_fpr, replacement_fpr, revocation_date) "
   403     "values (upper(replace(?1,' ','')),"
   404     "        upper(replace(?2,' ','')),"
   405     "        ?3) ;";
   406         
   407 static const char *sql_get_revoked = 
   408     "select revoked_fpr, revocation_date from revoked_keys"
   409     "    where replacement_fpr = upper(replace(?1,' ','')) ;";
   410 
   411 static const char *sql_get_replacement_fpr = 
   412     "select replacement_fpr, revocation_date from revoked_keys"
   413     "    where revoked_fpr = upper(replace(?1,' ','')) ;";
   414 
   415 static const char *sql_get_userid_alias_default =
   416     "select default_id from alternate_user_id "
   417     "   where alternate_id = ?1 ; ";
   418 
   419 // Revocation tracking
   420 static const char *sql_add_mistrusted_key =
   421     "insert or replace into mistrusted_keys (fpr) "
   422     "   values (upper(replace(?1,' ',''))) ;";
   423         
   424 static const char *sql_delete_mistrusted_key = 
   425     "delete from mistrusted_keys where fpr = upper(replace(?1,' ','')) ;";
   426 
   427 static const char *sql_is_mistrusted_key = 
   428     "select count(*) from mistrusted_keys where fpr = upper(replace(?1,' ','')) ;";
   429 
   430 static const char *sql_add_userid_alias =
   431     "insert or replace into alternate_user_id (alternate_id, default_id) "
   432     "values (?2, ?1) ;";
   433 
   434 static const char *sql_add_into_social_graph =
   435     "insert or replace into social_graph(own_userid, own_address, contact_userid) "
   436     "values (?1, ?2, ?3) ;";
   437 
   438 static const char *sql_get_own_address_binding_from_contact =
   439     "select own_address from social_graph where own_userid = ?1 and contact_userid = ?2 ;";
   440 
   441 static const char *sql_set_revoke_contact_as_notified =
   442     "insert or replace into revocation_contact_list(fpr, contact_id) values (?1, ?2) ;";
   443     
   444 static const char *sql_get_contacted_ids_from_revoke_fpr =
   445     "select * from revocation_contact_list where fpr = ?1 ;";
   446 
   447 static const char *sql_was_id_for_revoke_contacted = 
   448     "select count(*) from revocation_contact_list where fpr = ?1 and contact_id = ?2 ;";
   449     
   450 static int user_version(void *_version, int count, char **text, char **name)
   451 {
   452     assert(_version);
   453     assert(count == 1);
   454     assert(text && text[0]);
   455     if (!(_version && count == 1 && text && text[0]))
   456         return -1;
   457 
   458     int *version = (int *) _version;
   459     *version = atoi(text[0]);
   460     return 0;
   461 }
   462 
   463 static int table_contains_column(PEP_SESSION session, const char* table_name,
   464                                                       const char* col_name) {
   465 
   466 
   467     if (!session || !table_name || !col_name)
   468         return -1;
   469         
   470     // Table names can't be SQL parameters, so we do it this way.
   471     
   472     // these two must be the same number.
   473     char sql_buf[500];
   474     const size_t max_q_len = 500;
   475     
   476     size_t t_size, c_size, q_size;
   477     
   478     const char* q1 = "SELECT "; // 7
   479     const char* q2 = " from "; // 6
   480     const char* q3 = ";";       // 1
   481     
   482     q_size = 14;
   483     t_size = strlen(table_name);
   484     c_size = strlen(col_name);
   485     
   486     size_t query_len = q_size + c_size + t_size + 1;
   487     
   488     if (query_len > max_q_len)
   489         return -1;
   490 
   491     strlcpy(sql_buf, q1, max_q_len);
   492     strlcat(sql_buf, col_name, max_q_len);
   493     strlcat(sql_buf, q2, max_q_len);
   494     strlcat(sql_buf, table_name, max_q_len);
   495     strlcat(sql_buf, q3, max_q_len);
   496 
   497     sqlite3_stmt *stmt; 
   498 
   499     sqlite3_prepare_v2(session->db, sql_buf, -1, &stmt, NULL);
   500 
   501     int retval = 0;
   502 
   503     int rc = sqlite3_step(stmt);  
   504     if (rc == SQLITE_DONE || rc == SQLITE_OK || rc == SQLITE_ROW) {
   505         retval = 1;
   506     }
   507 
   508     sqlite3_finalize(stmt);      
   509         
   510     return retval;
   511 }
   512 
   513 void errorLogCallback(void *pArg, int iErrCode, const char *zMsg){
   514   fprintf(stderr, "(%d) %s\n", iErrCode, zMsg);
   515 }
   516 
   517 #ifdef USE_GPG
   518 PEP_STATUS pgp_import_ultimately_trusted_keypairs(PEP_SESSION session);
   519 #endif // USE_GPG
   520 
   521 DYNAMIC_API PEP_STATUS init(PEP_SESSION *session)
   522 {
   523     PEP_STATUS status = PEP_STATUS_OK;
   524     int int_result;
   525     
   526     bool in_first = false;
   527     bool very_first = false;
   528 
   529     assert(sqlite3_threadsafe());
   530     if (!sqlite3_threadsafe())
   531         return PEP_INIT_SQLITE3_WITHOUT_MUTEX;
   532 
   533     // a little race condition - but still a race condition
   534     // mitigated by calling caveat (see documentation)
   535 
   536     // this increment is made atomic IN THE ADAPTERS by
   537     // guarding the call to init with the appropriate mutex.
   538     int _count = ++init_count;
   539     if (_count == 0)
   540         in_first = true;
   541     
   542     // Race condition mitigated by calling caveat starts here :
   543     // If another call to init() preempts right now, then preemptive call
   544     // will have in_first false, will not create SQL tables, and following
   545     // calls relying on those tables will fail.
   546     //
   547     // Therefore, as above, adapters MUST guard init() with a mutex.
   548     // 
   549     // Therefore, first session
   550     // is to be created and last session to be deleted alone, and not
   551     // concurently to other sessions creation or deletion.
   552     // We expect adapters to enforce this either by implicitely creating a
   553     // client session, or by using synchronization primitive to protect
   554     // creation/deletion of first/last session from the app.
   555 
   556     assert(session);
   557     if (session == NULL)
   558         return PEP_ILLEGAL_VALUE;
   559 
   560     *session = NULL;
   561 
   562     pEpSession *_session = calloc(1, sizeof(pEpSession));
   563     assert(_session);
   564     if (_session == NULL)
   565         goto enomem;
   566 
   567     _session->version = PEP_ENGINE_VERSION;
   568 
   569 #ifdef DEBUG_ERRORSTACK
   570     _session->errorstack = new_stringlist("init()");
   571 #endif
   572 
   573     assert(LOCAL_DB);
   574     if (LOCAL_DB == NULL) {
   575         status = PEP_INIT_CANNOT_OPEN_DB;
   576         goto pep_error;
   577     }
   578     
   579 #if _PEP_SQLITE_DEBUG    
   580     sqlite3_config(SQLITE_CONFIG_LOG, errorLogCallback, NULL);
   581 #endif
   582 
   583     int_result = sqlite3_open_v2(
   584             LOCAL_DB,
   585             &_session->db,
   586             SQLITE_OPEN_READWRITE
   587                 | SQLITE_OPEN_CREATE
   588                 | SQLITE_OPEN_FULLMUTEX
   589                 | SQLITE_OPEN_PRIVATECACHE,
   590             NULL 
   591         );
   592 
   593     if (int_result != SQLITE_OK) {
   594         status = PEP_INIT_CANNOT_OPEN_DB;
   595         goto pep_error;
   596     }
   597 
   598     int_result = sqlite3_exec(
   599             _session->db,
   600             "PRAGMA locking_mode=NORMAL;\n"
   601             "PRAGMA journal_mode=WAL;\n",
   602             NULL,
   603             NULL,
   604             NULL
   605         );
   606 
   607 
   608     sqlite3_busy_timeout(_session->db, BUSY_WAIT_TIME);
   609 
   610 #if _PEP_SQLITE_DEBUG
   611     sqlite3_trace_v2(_session->db, 
   612         SQLITE_TRACE_STMT | SQLITE_TRACE_ROW | SQLITE_TRACE_CLOSE,
   613         sql_trace_callback,
   614         NULL);
   615 #endif
   616 
   617     assert(SYSTEM_DB);
   618     if (SYSTEM_DB == NULL) {
   619         status = PEP_INIT_CANNOT_OPEN_SYSTEM_DB;
   620         goto pep_error;
   621     }
   622 
   623     int_result = sqlite3_open_v2(
   624             SYSTEM_DB, &_session->system_db,
   625             SQLITE_OPEN_READONLY
   626                 | SQLITE_OPEN_FULLMUTEX
   627                 | SQLITE_OPEN_SHAREDCACHE,
   628             NULL
   629         );
   630 
   631     if (int_result != SQLITE_OK) {
   632         status = PEP_INIT_CANNOT_OPEN_SYSTEM_DB;
   633         goto pep_error;
   634     }
   635 
   636     sqlite3_busy_timeout(_session->system_db, 1000);
   637 
   638 // increment this when patching DDL
   639 #define _DDL_USER_VERSION "9"
   640 
   641     if (in_first) {
   642 
   643         int_result = sqlite3_exec(
   644             _session->db,
   645                 "create table if not exists version_info (\n"
   646                 "   id integer primary key,\n"
   647                 "   timestamp integer default (datetime('now')),\n"
   648                 "   version text,\n"
   649                 "   comment text\n"
   650                 ");\n",
   651                 NULL,
   652                 NULL,
   653                 NULL
   654         );
   655         int_result = sqlite3_exec(
   656             _session->db,
   657                 "PRAGMA application_id = 0x23423423;\n"
   658                 "create table if not exists log (\n"
   659                 "   timestamp integer default (datetime('now')),\n"
   660                 "   title text not null,\n"
   661                 "   description text,\n"
   662                 "   entity text not null,\n"
   663                 "   comment text\n"
   664                 ");\n"
   665                 "create index if not exists log_timestamp on log (\n"
   666                 "   timestamp\n"
   667                 ");\n"
   668                 "create table if not exists pgp_keypair (\n"
   669                 "   fpr text primary key,\n"
   670                 "   created integer,\n"
   671                 "   expires integer,\n"
   672                 "   comment text,\n"
   673                 "   flags integer default 0\n"
   674                 ");\n"
   675                 "create index if not exists pgp_keypair_expires on pgp_keypair (\n"
   676                 "   expires\n"
   677                 ");\n"
   678                 "create table if not exists person (\n"
   679                 "   id text primary key,\n"
   680                 "   username text not null,\n"
   681                 "   main_key_id text\n"
   682                 "       references pgp_keypair (fpr)\n"
   683                 "       on delete set null,\n"
   684                 "   lang text,\n"
   685                 "   comment text,\n"
   686                 "   device_group text,\n"
   687                 "   is_pep_user integer default 0\n"
   688                 ");\n"
   689                 "create table if not exists identity (\n"
   690                 "   address text,\n"
   691                 "   user_id text\n"
   692                 "       references person (id)\n"
   693                 "       on delete cascade on update cascade,\n"
   694                 "   main_key_id text\n"
   695                 "       references pgp_keypair (fpr)\n"
   696                 "       on delete set null,\n"
   697                 "   comment text,\n"
   698                 "   flags integer default 0,\n"
   699                 "   is_own integer default 0,\n"
   700                 "   timestamp integer default (datetime('now')),\n"
   701                 "   primary key (address, user_id)\n"
   702                 ");\n"
   703                 "create table if not exists trust (\n"
   704                 "   user_id text not null\n"
   705                 "       references person (id)\n"
   706                 "       on delete cascade on update cascade,\n"
   707                 "   pgp_keypair_fpr text not null\n"
   708                 "       references pgp_keypair (fpr)\n"
   709                 "       on delete cascade,\n"
   710                 "   comm_type integer not null,\n"
   711                 "   comment text,\n"
   712                 "   primary key (user_id, pgp_keypair_fpr)\n"
   713                 ");\n"
   714                 // blacklist
   715                 "create table if not exists blacklist_keys (\n"
   716                 "   fpr text primary key\n"
   717                 ");\n"
   718                 // sequences
   719                 "create table if not exists sequences(\n"
   720                 "   name text primary key,\n"
   721                 "   value integer default 0,\n"
   722                 "   own integer default 0\n"
   723                 ");\n"
   724                 "create table if not exists revoked_keys (\n"
   725                 "   revoked_fpr text primary key,\n"
   726                 "   replacement_fpr text not null\n"
   727                 "       references pgp_keypair (fpr)\n"
   728                 "       on delete cascade,\n"
   729                 "   revocation_date integer\n"
   730                 ");\n"
   731                 // user id aliases
   732                 "create table if not exists alternate_user_id (\n"
   733                 "    default_id text references person (id)\n"
   734                 "       on delete cascade on update cascade,\n"
   735                 "    alternate_id text primary key\n"
   736                 ");\n"
   737                 // mistrusted keys
   738                 "create table if not exists mistrusted_keys (\n"
   739                 "    fpr text primary key\n"
   740                 ");\n"
   741                 // social graph for key resets
   742                 "create table if not exists social_graph (\n"
   743                 "    own_userid text,\n"
   744                 "    own_address text,\n"
   745                 "    contact_userid text,\n"
   746                 "    CONSTRAINT fk_own_identity\n"
   747                 "       FOREIGN KEY(own_address, own_userid)\n" 
   748                 "       REFERENCES identity(address, user_id)\n"
   749                 "       ON DELETE CASCADE ON UPDATE CASCADE,\n"
   750                 ");\n"
   751                 // list of user_ids sent revocation
   752                 "create table if not exists revocation_contact_list (\n"
   753                 "   fpr text not null references pgp_keypair (fpr)\n"
   754                 "       on delete cascade,\n"
   755                 "   contact_id text not null references person (id)\n"
   756                 "       on delete cascade on update cascade,\n"
   757                 "   timestamp integer default (datetime('now')),\n"
   758                 "   PRIMARY KEY(fpr, contact_id)\n"
   759                 ");\n"
   760                 ,
   761             NULL,
   762             NULL,
   763             NULL
   764         );
   765         assert(int_result == SQLITE_OK);
   766 
   767         int version;
   768         int_result = sqlite3_exec(
   769             _session->db,
   770             "pragma user_version;",
   771             user_version,
   772             &version,
   773             NULL
   774         );
   775 
   776         assert(int_result == SQLITE_OK);
   777         
   778         void (*xFunc_lower)(sqlite3_context*,int,sqlite3_value**) = &_sql_lower;
   779         
   780         int_result = sqlite3_create_function_v2(
   781             _session->db,
   782             "lower",
   783             1,
   784             SQLITE_UTF8 | SQLITE_DETERMINISTIC,
   785             NULL,
   786             xFunc_lower,
   787             NULL,
   788             NULL,
   789             NULL);
   790         assert(int_result == SQLITE_OK);
   791 
   792         int_result = sqlite3_exec(
   793             _session->db,
   794             "pragma foreign_keys=ON;\n",
   795             NULL,
   796             NULL,
   797             NULL
   798         );
   799 
   800         assert(int_result == SQLITE_OK);
   801 
   802         
   803         // Sometimes the user_version wasn't set correctly. Check to see if this
   804         // is really necessary...
   805         if (version == 1) {
   806             bool version_changed = true;
   807             if (table_contains_column(_session, "identity", "timestamp") > 0) {
   808                 version = 8;
   809             }            
   810             if (table_contains_column(_session, "person", "is_pep_user") > 0) {
   811                 version = 7;
   812             }            
   813             else if (table_contains_column(_session, "identity", "is_own") > 0) {
   814                 version = 6;
   815             }
   816             else if (table_contains_column(_session, "sequences", "own") > 0) {
   817                 version = 3;
   818             }
   819             else if (table_contains_column(_session, "pgp_keypair", "flags") > 0) {
   820                 version = 2;
   821             }
   822             else {
   823                 version_changed = false;
   824             }
   825             
   826             if (version_changed) {
   827                 // set it in the DB, finally. Yeesh.
   828                 char verbuf[21]; // enough digits for a max-sized 64 bit int, cmon. 
   829                 sprintf(verbuf,"%d",version);
   830                 
   831                 size_t query_size = strlen(verbuf) + 25;
   832                 char* query = calloc(query_size, 1);
   833                 
   834                 strlcpy(query, "pragma user_version = ", query_size);
   835                 strlcat(query, verbuf, query_size);
   836                 strlcat(query, ";", query_size);
   837                 
   838                 int_result = sqlite3_exec(
   839                     _session->db,
   840                     query,
   841                     user_version,
   842                     &version,
   843                     NULL
   844                 );
   845                 free(query);
   846             }
   847         }
   848 
   849 
   850         if(version != 0) { 
   851             // Version has been already set
   852 
   853             // Early mistake : version 0 shouldn't have existed.
   854             // Numbering should have started at 1 to detect newly created DB.
   855             // Version 0 DBs are not anymore compatible.
   856 
   857             // // Was version 0 compat code.
   858             // if (version < 1) {
   859             //     int_result = sqlite3_exec(
   860             //         _session->db,
   861             //         "alter table identity\n"
   862             //         "   add column flags integer default 0;\n",
   863             //         NULL,
   864             //         NULL,
   865             //         NULL
   866             //     );
   867             //     assert(int_result == SQLITE_OK);
   868             // }
   869             
   870             if (version < 2) {
   871                 int_result = sqlite3_exec(
   872                     _session->db,
   873                     "alter table pgp_keypair\n"
   874                     "   add column flags integer default 0;\n"
   875                     "alter table person\n"
   876                     "   add column device_group text;\n",
   877                     NULL,
   878                     NULL,
   879                     NULL
   880                 );
   881                 assert(int_result == SQLITE_OK);
   882             }
   883 
   884             if (version < 3) {
   885                 int_result = sqlite3_exec(
   886                     _session->db,
   887                     "alter table sequences\n"
   888                     "   add column own integer default 0;\n",
   889                     NULL,
   890                     NULL,
   891                     NULL
   892                 );
   893                 assert(int_result == SQLITE_OK);
   894             }
   895 
   896             if (version < 5) {
   897                 int_result = sqlite3_exec(
   898                     _session->db,
   899                     "delete from pgp_keypair where fpr = '';",
   900                     NULL,
   901                     NULL,
   902                     NULL
   903                 );
   904                 assert(int_result == SQLITE_OK);
   905                 int_result = sqlite3_exec(
   906                     _session->db,
   907                     "delete from trust where pgp_keypair_fpr = '';",
   908                     NULL,
   909                     NULL,
   910                     NULL
   911                 );
   912                 assert(int_result == SQLITE_OK);
   913             }
   914             
   915             if (version < 6) {
   916                 int_result = sqlite3_exec(
   917                     _session->db,
   918                     "alter table identity\n"
   919                     "   add column is_own integer default 0;\n",
   920                     NULL,
   921                     NULL,
   922                     NULL
   923                 );
   924                 assert(int_result == SQLITE_OK);                
   925                 int_result = sqlite3_exec(
   926                     _session->db,
   927                     "update identity\n"
   928                     "   set is_own = 1\n"
   929                     "   where (user_id = '" PEP_OWN_USERID "');\n",
   930                     NULL,
   931                     NULL,
   932                     NULL
   933                 );
   934                 assert(int_result == SQLITE_OK);    
   935 
   936                 // Turns out that just adding "on update cascade" in
   937                 // sqlite is a PITA. We need to be able to cascade
   938                 // person->id replacements (for temp ids like "TOFU_")
   939                 // so here we go...
   940                 int_result = sqlite3_exec(
   941                     _session->db,
   942                     "PRAGMA foreign_keys=off;\n"
   943                     "BEGIN TRANSACTION;\n"
   944                     "ALTER TABLE identity RENAME TO _identity_old;\n"
   945                     "create table identity (\n"
   946                     "   address text,\n"
   947                     "   user_id text\n"
   948                     "       references person (id)\n"
   949                     "       on delete cascade on update cascade,\n"
   950                     "   main_key_id text\n"
   951                     "       references pgp_keypair (fpr)\n"
   952                     "       on delete set null,\n"
   953                     "   comment text,\n"
   954                     "   flags integer default 0,\n"
   955                     "   is_own integer default 0,\n"
   956                     "   primary key (address, user_id)\n"
   957                     ");\n"
   958                     "INSERT INTO identity SELECT * FROM _identity_old;\n"
   959                     "DROP TABLE _identity_old;\n"
   960                     "ALTER TABLE trust RENAME TO _trust_old;\n"
   961                     "create table trust (\n"
   962                     "   user_id text not null\n"
   963                     "       references person (id)\n"
   964                     "       on delete cascade on update cascade,\n"
   965                     "   pgp_keypair_fpr text not null\n"
   966                     "       references pgp_keypair (fpr)\n"
   967                     "       on delete cascade,\n"
   968                     "   comm_type integer not null,\n"
   969                     "   comment text,\n"
   970                     "   primary key (user_id, pgp_keypair_fpr)\n"
   971                     ");\n"
   972                     "INSERT INTO trust SELECT * FROM _trust_old;\n"
   973                     "DROP TABLE _trust_old;\n"
   974                     "COMMIT;\n"
   975                     "\n"
   976                     "PRAGMA foreign_keys=on;\n"
   977                     "create table if not exists alternate_user_id (\n"
   978                     "    default_id text references person (id)\n"
   979                     "       on delete cascade on update cascade,\n"
   980                     "    alternate_id text primary key\n"
   981                     ");\n"
   982                     ,
   983                     NULL,
   984                     NULL,
   985                     NULL
   986                 );
   987                 assert(int_result == SQLITE_OK);    
   988             }
   989             if (version < 7) {
   990                 int_result = sqlite3_exec(
   991                     _session->db,
   992                     "alter table person\n"
   993                     "   add column is_pep_user integer default 0;\n",
   994                     NULL,
   995                     NULL,
   996                     NULL
   997                 );
   998                 assert(int_result == SQLITE_OK);
   999                 int_result = sqlite3_exec(
  1000                     _session->db,
  1001                     "update person\n"
  1002                     "   set is_pep_user = 1\n"
  1003                     "   where id = "
  1004                     "       (select distinct id from person "
  1005                     "               join trust on id = user_id "
  1006                     "               where (case when (comm_type = 127) then (id) "
  1007                     "                           when (comm_type = 255) then (id) "
  1008                     "                           else 0"
  1009                     "                      end) = id );\n",
  1010                     NULL,
  1011                     NULL,
  1012                     NULL
  1013                 );
  1014                 assert(int_result == SQLITE_OK);
  1015                 
  1016                 int_result = sqlite3_exec(
  1017                     _session->db,
  1018                     "create table if not exists mistrusted_keys (\n"
  1019                     "    fpr text primary key\n"
  1020                     ");\n",            
  1021                     NULL,
  1022                     NULL,
  1023                     NULL
  1024                 );
  1025                 assert(int_result == SQLITE_OK);    
  1026             }
  1027             if (version < 8) {
  1028                 int_result = sqlite3_exec(
  1029                     _session->db,
  1030                     "PRAGMA foreign_keys=off;\n"
  1031                     "BEGIN TRANSACTION;\n"
  1032                     "ALTER TABLE identity RENAME TO _identity_old;\n"
  1033                     "create table identity (\n"
  1034                     "   address text,\n"
  1035                     "   user_id text\n"
  1036                     "       references person (id)\n"
  1037                     "       on delete cascade on update cascade,\n"
  1038                     "   main_key_id text\n"
  1039                     "       references pgp_keypair (fpr)\n"
  1040                     "       on delete set null,\n"
  1041                     "   comment text,\n"
  1042                     "   flags integer default 0,\n"
  1043                     "   is_own integer default 0,\n"
  1044                     "   timestamp integer default (datetime('now')),\n"
  1045                     "   primary key (address, user_id)\n"
  1046                     ");\n"
  1047                     "INSERT INTO identity (address, user_id, main_key_id, "
  1048                     "                      comment, flags, is_own) "
  1049                     "   SELECT _identity_old.address, _identity_old.user_id, "
  1050                     "          _identity_old.main_key_id, _identity_old.comment, "
  1051                     "          _identity_old.flags, _identity_old.is_own "
  1052                     "   FROM _identity_old "
  1053                     "   WHERE 1;\n"
  1054                     "DROP TABLE _identity_old;\n"
  1055                     "COMMIT;\n"
  1056                     "\n"
  1057                     "PRAGMA foreign_keys=on;\n"
  1058                     ,
  1059                     NULL,
  1060                     NULL,
  1061                     NULL
  1062                 );
  1063                 assert(int_result == SQLITE_OK);    
  1064             }
  1065             if (version < 9) {
  1066                 int_result = sqlite3_exec(
  1067                     _session->db,
  1068                     "create table if not exists social_graph (\n"
  1069                     "    own_userid text,\n"
  1070                     "    own_address text,\n"
  1071                     "    contact_userid text,\n"
  1072                     "    CONSTRAINT fk_own_identity\n"
  1073                     "       FOREIGN KEY(own_address, own_userid)\n" 
  1074                     "       REFERENCES identity(address, user_id)\n"
  1075                     "       ON DELETE CASCADE ON UPDATE CASCADE,\n"
  1076                     ");\n"
  1077                     "create table if not exists revocation_contact_list (\n"
  1078                     "   fpr text not null references pgp_keypair (fpr)\n"
  1079                     "       on delete cascade,\n"
  1080                     "   contact_id text not null references person (id)\n"
  1081                     "       on delete cascade on update cascade,\n"
  1082                     "   timestamp integer default (datetime('now')),\n"
  1083                     "   PRIMARY KEY(fpr, contact_id)\n"
  1084                     ");\n"
  1085                     ,
  1086                     NULL,
  1087                     NULL,
  1088                     NULL
  1089                 );
  1090                 assert(int_result == SQLITE_OK);    
  1091             }
  1092         }        
  1093         else { 
  1094             // Version from DB was 0, it means this is initial setup.
  1095             // DB has just been created, and all tables are empty.
  1096             very_first = true;
  1097         }
  1098 
  1099         if (version < atoi(_DDL_USER_VERSION)) {
  1100             int_result = sqlite3_exec(
  1101                 _session->db,
  1102                 "pragma user_version = "_DDL_USER_VERSION";\n"
  1103                 "insert or replace into version_info (id, version)"
  1104                     "values (1, '" PEP_ENGINE_VERSION "');",
  1105                 NULL,
  1106                 NULL,
  1107                 NULL
  1108             );
  1109             assert(int_result == SQLITE_OK);
  1110         }
  1111         
  1112         // We need to init a few globals for message id that we'd rather not
  1113         // calculate more than once.
  1114         _init_globals();
  1115     }
  1116 
  1117     int_result = sqlite3_prepare_v2(_session->db, sql_log,
  1118             (int)strlen(sql_log), &_session->log, NULL);
  1119     assert(int_result == SQLITE_OK);
  1120 
  1121     int_result = sqlite3_prepare_v2(_session->system_db, sql_trustword,
  1122             (int)strlen(sql_trustword), &_session->trustword, NULL);
  1123     assert(int_result == SQLITE_OK);
  1124 
  1125     int_result = sqlite3_prepare_v2(_session->db, sql_get_identity,
  1126             (int)strlen(sql_get_identity), &_session->get_identity, NULL);
  1127     assert(int_result == SQLITE_OK);
  1128 
  1129     int_result = sqlite3_prepare_v2(_session->db, sql_get_identity_without_trust_check,
  1130             (int)strlen(sql_get_identity_without_trust_check), 
  1131             &_session->get_identity_without_trust_check, NULL);
  1132     assert(int_result == SQLITE_OK);
  1133 
  1134     int_result = sqlite3_prepare_v2(_session->db, sql_get_identities_by_address,
  1135             (int)strlen(sql_get_identities_by_address), 
  1136             &_session->get_identities_by_address, NULL);
  1137     assert(int_result == SQLITE_OK);
  1138 
  1139     int_result = sqlite3_prepare_v2(_session->db, sql_get_user_default_key,
  1140             (int)strlen(sql_get_user_default_key), &_session->get_user_default_key, NULL);
  1141     assert(int_result == SQLITE_OK);
  1142 
  1143     int_result = sqlite3_prepare_v2(_session->db, sql_get_default_own_userid,
  1144             (int)strlen(sql_get_default_own_userid), &_session->get_default_own_userid, NULL);
  1145     assert(int_result == SQLITE_OK);
  1146     
  1147     int_result = sqlite3_prepare_v2(_session->db, sql_get_userid_alias_default,
  1148             (int)strlen(sql_get_userid_alias_default), &_session->get_userid_alias_default, NULL);
  1149     assert(int_result == SQLITE_OK);
  1150 
  1151     int_result = sqlite3_prepare_v2(_session->db, sql_add_userid_alias,
  1152             (int)strlen(sql_add_userid_alias), &_session->add_userid_alias, NULL);
  1153     assert(int_result == SQLITE_OK);
  1154 
  1155     int_result = sqlite3_prepare_v2(_session->db, sql_replace_userid,
  1156             (int)strlen(sql_replace_userid), &_session->replace_userid, NULL);
  1157     assert(int_result == SQLITE_OK);
  1158 
  1159     int_result = sqlite3_prepare_v2(_session->db, sql_replace_main_user_fpr,
  1160             (int)strlen(sql_replace_main_user_fpr), &_session->replace_main_user_fpr, NULL);
  1161     assert(int_result == SQLITE_OK);
  1162 
  1163     int_result = sqlite3_prepare_v2(_session->db, sql_get_main_user_fpr,
  1164             (int)strlen(sql_get_main_user_fpr), &_session->get_main_user_fpr, NULL);
  1165     assert(int_result == SQLITE_OK);
  1166 
  1167     int_result = sqlite3_prepare_v2(_session->db, sql_refresh_userid_default_key,
  1168             (int)strlen(sql_refresh_userid_default_key), &_session->refresh_userid_default_key, NULL);
  1169     assert(int_result == SQLITE_OK);
  1170 
  1171     int_result = sqlite3_prepare_v2(_session->db, sql_replace_identities_fpr,
  1172             (int)strlen(sql_replace_identities_fpr), 
  1173             &_session->replace_identities_fpr, NULL);
  1174     assert(int_result == SQLITE_OK);
  1175     
  1176     int_result = sqlite3_prepare_v2(_session->db, sql_remove_fpr_as_default,
  1177             (int)strlen(sql_remove_fpr_as_default), 
  1178             &_session->remove_fpr_as_default, NULL);
  1179     assert(int_result == SQLITE_OK);
  1180 
  1181     int_result = sqlite3_prepare_v2(_session->db, sql_set_person,
  1182             (int)strlen(sql_set_person), &_session->set_person, NULL);
  1183     assert(int_result == SQLITE_OK);
  1184 
  1185     int_result = sqlite3_prepare_v2(_session->db, sql_update_person,
  1186             (int)strlen(sql_update_person), &_session->update_person, NULL);
  1187     assert(int_result == SQLITE_OK);
  1188 
  1189     int_result = sqlite3_prepare_v2(_session->db, sql_exists_person,
  1190             (int)strlen(sql_exists_person), &_session->exists_person, NULL);
  1191     assert(int_result == SQLITE_OK);
  1192 
  1193     int_result = sqlite3_prepare_v2(_session->db, sql_set_as_pep_user,
  1194             (int)strlen(sql_set_as_pep_user), &_session->set_as_pep_user, NULL);
  1195     assert(int_result == SQLITE_OK);
  1196     
  1197     int_result = sqlite3_prepare_v2(_session->db, sql_is_pep_user,
  1198             (int)strlen(sql_is_pep_user), &_session->is_pep_user, NULL);
  1199     assert(int_result == SQLITE_OK);
  1200 
  1201     int_result = sqlite3_prepare_v2(_session->db, sql_add_into_social_graph,
  1202             (int)strlen(sql_add_into_social_graph), &_session->add_into_social_graph, NULL);
  1203     assert(int_result == SQLITE_OK);
  1204 
  1205     int_result = sqlite3_prepare_v2(_session->db, 
  1206             sql_get_own_address_binding_from_contact,
  1207             (int)strlen(sql_get_own_address_binding_from_contact), 
  1208             &_session->get_own_address_binding_from_contact, NULL);
  1209     assert(int_result == SQLITE_OK);
  1210 
  1211     int_result = sqlite3_prepare_v2(_session->db, 
  1212             sql_set_revoke_contact_as_notified,
  1213             (int)strlen(sql_set_revoke_contact_as_notified), 
  1214             &_session->set_revoke_contact_as_notified, NULL);
  1215     assert(int_result == SQLITE_OK);
  1216 
  1217     int_result = sqlite3_prepare_v2(_session->db, 
  1218             sql_get_contacted_ids_from_revoke_fpr,
  1219             (int)strlen(sql_get_contacted_ids_from_revoke_fpr), 
  1220             &_session->get_contacted_ids_from_revoke_fpr, NULL);
  1221     assert(int_result == SQLITE_OK);
  1222 
  1223     int_result = sqlite3_prepare_v2(_session->db, 
  1224             sql_get_own_address_binding_from_contact,
  1225             (int)strlen(sql_get_own_address_binding_from_contact), 
  1226             &_session->get_own_address_binding_from_contact, NULL);
  1227     assert(int_result == SQLITE_OK);
  1228 
  1229     int_result = sqlite3_prepare_v2(_session->db, sql_set_device_group,
  1230             (int)strlen(sql_set_device_group), &_session->set_device_group, NULL);
  1231     assert(int_result == SQLITE_OK);
  1232 
  1233     int_result = sqlite3_prepare_v2(_session->db, sql_get_device_group,
  1234             (int)strlen(sql_get_device_group), &_session->get_device_group, NULL);
  1235     assert(int_result == SQLITE_OK);
  1236 
  1237     int_result = sqlite3_prepare_v2(_session->db, sql_set_pgp_keypair,
  1238             (int)strlen(sql_set_pgp_keypair), &_session->set_pgp_keypair,
  1239             NULL);
  1240     assert(int_result == SQLITE_OK);
  1241 
  1242     int_result = sqlite3_prepare_v2(_session->db, sql_set_identity_entry,
  1243             (int)strlen(sql_set_identity_entry), &_session->set_identity_entry, NULL);
  1244     assert(int_result == SQLITE_OK);
  1245 
  1246     int_result = sqlite3_prepare_v2(_session->db, sql_update_identity_entry,
  1247             (int)strlen(sql_update_identity_entry), &_session->update_identity_entry, NULL);
  1248     assert(int_result == SQLITE_OK);
  1249 
  1250     int_result = sqlite3_prepare_v2(_session->db, sql_exists_identity_entry,
  1251             (int)strlen(sql_exists_identity_entry), &_session->exists_identity_entry, NULL);
  1252     assert(int_result == SQLITE_OK);
  1253 
  1254     int_result = sqlite3_prepare_v2(_session->db, sql_set_identity_flags,
  1255             (int)strlen(sql_set_identity_flags), &_session->set_identity_flags,
  1256             NULL);
  1257     assert(int_result == SQLITE_OK);
  1258 
  1259     int_result = sqlite3_prepare_v2(_session->db, sql_unset_identity_flags,
  1260             (int)strlen(sql_unset_identity_flags), &_session->unset_identity_flags,
  1261             NULL);
  1262     assert(int_result == SQLITE_OK);
  1263 
  1264     int_result = sqlite3_prepare_v2(_session->db, sql_set_trust,
  1265             (int)strlen(sql_set_trust), &_session->set_trust, NULL);
  1266     assert(int_result == SQLITE_OK);
  1267 
  1268     int_result = sqlite3_prepare_v2(_session->db, sql_update_trust,
  1269             (int)strlen(sql_update_trust), &_session->update_trust, NULL);
  1270     assert(int_result == SQLITE_OK);
  1271 
  1272     int_result = sqlite3_prepare_v2(_session->db, sql_update_trust_to_pep,
  1273             (int)strlen(sql_update_trust_to_pep), &_session->update_trust_to_pep, NULL);
  1274     assert(int_result == SQLITE_OK);
  1275 
  1276     int_result = sqlite3_prepare_v2(_session->db, sql_exists_trust_entry,
  1277                  (int)strlen(sql_exists_trust_entry), &_session->exists_trust_entry, NULL);
  1278     assert(int_result == SQLITE_OK);
  1279 
  1280     int_result = sqlite3_prepare_v2(_session->db, sql_update_trust_for_fpr,
  1281             (int)strlen(sql_update_trust_for_fpr), &_session->update_trust_for_fpr, NULL);
  1282     assert(int_result == SQLITE_OK);
  1283 
  1284     int_result = sqlite3_prepare_v2(_session->db, sql_get_trust,
  1285             (int)strlen(sql_get_trust), &_session->get_trust, NULL);
  1286     assert(int_result == SQLITE_OK);
  1287 
  1288     int_result = sqlite3_prepare_v2(_session->db, sql_least_trust,
  1289             (int)strlen(sql_least_trust), &_session->least_trust, NULL);
  1290     assert(int_result == SQLITE_OK);
  1291 
  1292     int_result = sqlite3_prepare_v2(_session->db, sql_mark_as_compromised,
  1293             (int)strlen(sql_mark_as_compromised), &_session->mark_compromised,
  1294             NULL);
  1295     assert(int_result == SQLITE_OK);
  1296 
  1297     int_result = sqlite3_prepare_v2(_session->db, sql_crashdump,
  1298             (int)strlen(sql_crashdump), &_session->crashdump, NULL);
  1299     assert(int_result == SQLITE_OK);
  1300 
  1301     int_result = sqlite3_prepare_v2(_session->system_db, sql_languagelist,
  1302             (int)strlen(sql_languagelist), &_session->languagelist, NULL);
  1303     assert(int_result == SQLITE_OK);
  1304 
  1305     int_result = sqlite3_prepare_v2(_session->system_db, sql_i18n_token,
  1306             (int)strlen(sql_i18n_token), &_session->i18n_token, NULL);
  1307     assert(int_result == SQLITE_OK);
  1308     
  1309     // blacklist
  1310 
  1311     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_add,
  1312             (int)strlen(sql_blacklist_add), &_session->blacklist_add, NULL);
  1313     assert(int_result == SQLITE_OK);
  1314 
  1315     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_delete,
  1316             (int)strlen(sql_blacklist_delete), &_session->blacklist_delete,
  1317             NULL);
  1318     assert(int_result == SQLITE_OK);
  1319 
  1320     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_is_listed,
  1321             (int)strlen(sql_blacklist_is_listed),
  1322             &_session->blacklist_is_listed, NULL);
  1323     assert(int_result == SQLITE_OK);
  1324 
  1325     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_retrieve,
  1326             (int)strlen(sql_blacklist_retrieve), &_session->blacklist_retrieve,
  1327             NULL);
  1328     assert(int_result == SQLITE_OK);
  1329     
  1330     // Own keys
  1331     
  1332     int_result = sqlite3_prepare_v2(_session->db, sql_own_key_is_listed,
  1333             (int)strlen(sql_own_key_is_listed), &_session->own_key_is_listed,
  1334             NULL);
  1335     assert(int_result == SQLITE_OK);
  1336     
  1337     int_result = sqlite3_prepare_v2(_session->db, sql_own_identities_retrieve,
  1338             (int)strlen(sql_own_identities_retrieve),
  1339             &_session->own_identities_retrieve, NULL);
  1340     assert(int_result == SQLITE_OK);
  1341  
  1342     int_result = sqlite3_prepare_v2(_session->db, sql_own_keys_retrieve,
  1343             (int)strlen(sql_own_keys_retrieve),
  1344             &_session->own_keys_retrieve, NULL);
  1345     assert(int_result == SQLITE_OK);
  1346  
  1347     // int_result = sqlite3_prepare_v2(_session->db, sql_set_own_key,
  1348     //         (int)strlen(sql_set_own_key),
  1349     //         &_session->set_own_key, NULL);
  1350     // assert(int_result == SQLITE_OK);
  1351  
  1352     // Sequence
  1353 
  1354     int_result = sqlite3_prepare_v2(_session->db, sql_sequence_value1,
  1355             (int)strlen(sql_sequence_value1), &_session->sequence_value1,
  1356             NULL);
  1357     assert(int_result == SQLITE_OK);
  1358 
  1359     int_result = sqlite3_prepare_v2(_session->db, sql_sequence_value2,
  1360             (int)strlen(sql_sequence_value2), &_session->sequence_value2,
  1361             NULL);
  1362     assert(int_result == SQLITE_OK);
  1363 
  1364     int_result = sqlite3_prepare_v2(_session->db, sql_sequence_value3,
  1365             (int)strlen(sql_sequence_value3), &_session->sequence_value3,
  1366             NULL);
  1367     assert(int_result == SQLITE_OK);
  1368 
  1369     // Revocation tracking
  1370     
  1371     int_result = sqlite3_prepare_v2(_session->db, sql_set_revoked,
  1372             (int)strlen(sql_set_revoked), &_session->set_revoked, NULL);
  1373     assert(int_result == SQLITE_OK);
  1374     
  1375     int_result = sqlite3_prepare_v2(_session->db, sql_get_revoked,
  1376             (int)strlen(sql_get_revoked), &_session->get_revoked, NULL);
  1377     assert(int_result == SQLITE_OK);
  1378     
  1379     int_result = sqlite3_prepare_v2(_session->db, sql_get_replacement_fpr,
  1380             (int)strlen(sql_get_replacement_fpr), &_session->get_replacement_fpr, NULL);
  1381     assert(int_result == SQLITE_OK);
  1382 
  1383     int_result = sqlite3_prepare_v2(_session->db, sql_add_mistrusted_key,
  1384             (int)strlen(sql_add_mistrusted_key), &_session->add_mistrusted_key, NULL);
  1385     assert(int_result == SQLITE_OK);
  1386 
  1387     int_result = sqlite3_prepare_v2(_session->db, sql_delete_mistrusted_key,
  1388             (int)strlen(sql_delete_mistrusted_key), &_session->delete_mistrusted_key, NULL);
  1389     assert(int_result == SQLITE_OK);
  1390 
  1391     int_result = sqlite3_prepare_v2(_session->db, sql_is_mistrusted_key,
  1392             (int)strlen(sql_is_mistrusted_key), &_session->is_mistrusted_key, NULL);
  1393     assert(int_result == SQLITE_OK);
  1394     
  1395     status = init_cryptotech(_session, in_first);
  1396     if (status != PEP_STATUS_OK)
  1397         goto pep_error;
  1398 
  1399     status = init_transport_system(_session, in_first);
  1400     if (status != PEP_STATUS_OK)
  1401         goto pep_error;
  1402 
  1403     status = log_event(_session, "init", "pEp " PEP_ENGINE_VERSION, NULL, NULL);
  1404     if (status != PEP_STATUS_OK)
  1405         goto pep_error;
  1406 
  1407     // runtime config
  1408 
  1409     if (very_first)
  1410     {
  1411 #ifdef USE_GPG
  1412         // On first run, all private keys already present in PGP keyring 
  1413         // are taken as own in order to seamlessly integrate with
  1414         // pre-existing GPG setup.
  1415 
  1416         // Note: earlier fears about danger because of DB reinitialisation should
  1417         // be a non-issue here, as we ONLY take the ultimately trusted keys now.
  1418         // Thus, unless the user has assigned ultimate trust through PGP, there is
  1419         // no chance of automatically imported pEp keys from a previous run making
  1420         // their way into PEP trusted status without explicit action (Bare imported
  1421         // private keys have an 'unknown' trust designation in PGP).
  1422 
  1423         // We don't really worry about the status here.
  1424         status = pgp_import_ultimately_trusted_keypairs(_session);        
  1425 #endif // USE_GPG
  1426     }
  1427 
  1428     // sync_session set to own session by default
  1429     // sync_session is then never null on a valid session
  1430     _session->sync_session = _session;
  1431 
  1432     *session = _session;
  1433     
  1434     // Note: Following statement is NOT for any cryptographic/secure functionality; it is
  1435     //       ONLY used for some randomness in generated outer message ID, which are
  1436     //       required by the RFC to be globally unique!
  1437     srand((unsigned int) time(NULL));
  1438     
  1439     return PEP_STATUS_OK;
  1440 
  1441 enomem:
  1442     status = PEP_OUT_OF_MEMORY;
  1443 
  1444 pep_error:
  1445     release(_session);
  1446     return status;
  1447 }
  1448 
  1449 DYNAMIC_API void release(PEP_SESSION session)
  1450 {
  1451     bool out_last = false;
  1452     int _count = --init_count;
  1453     
  1454     assert(_count >= -1);
  1455     assert(session);
  1456 
  1457     if (!((_count >= -1) && session))
  1458         return;
  1459 
  1460     // a small race condition but still a race condition
  1461     // mitigated by calling caveat (see documentation)
  1462     // (release() is to be guarded by a mutex by the caller)
  1463     if (_count == -1)
  1464         out_last = true;
  1465 
  1466     if (session) {
  1467 
  1468         if (session->db) {
  1469             if (session->log)
  1470                 sqlite3_finalize(session->log);
  1471             if (session->trustword)
  1472                 sqlite3_finalize(session->trustword);
  1473             if (session->get_identity)
  1474                 sqlite3_finalize(session->get_identity);
  1475             if (session->get_identity_without_trust_check)
  1476                 sqlite3_finalize(session->get_identity_without_trust_check);
  1477             if (session->get_identities_by_address)
  1478                 sqlite3_finalize(session->get_identities_by_address);            
  1479             if (session->get_user_default_key)
  1480                 sqlite3_finalize(session->get_user_default_key);    
  1481             if (session->get_default_own_userid)
  1482                 sqlite3_finalize(session->get_default_own_userid);
  1483             if (session->get_userid_alias_default)
  1484                 sqlite3_finalize(session->get_userid_alias_default);
  1485             if (session->add_userid_alias)
  1486                 sqlite3_finalize(session->add_userid_alias);
  1487             if (session->replace_identities_fpr)
  1488                 sqlite3_finalize(session->replace_identities_fpr);        
  1489             if (session->remove_fpr_as_default)
  1490                 sqlite3_finalize(session->remove_fpr_as_default);            
  1491             if (session->set_person)
  1492                 sqlite3_finalize(session->set_person);
  1493             if (session->set_as_pep_user)
  1494                 sqlite3_finalize(session->set_as_pep_user);
  1495             if (session->is_pep_user)
  1496                 sqlite3_finalize(session->is_pep_user);
  1497             if (session->exists_person)
  1498                 sqlite3_finalize(session->exists_person);
  1499             if (session->add_into_social_graph)
  1500                 sqlite3_finalize(session->add_into_social_graph);  
  1501             if (session->get_own_address_binding_from_contact)
  1502                 sqlite3_finalize(session->get_own_address_binding_from_contact);  
  1503             if (session->set_revoke_contact_as_notified)
  1504                 sqlite3_finalize(session->set_revoke_contact_as_notified);  
  1505             if (session->get_contacted_ids_from_revoke_fpr)
  1506                 sqlite3_finalize(session->get_contacted_ids_from_revoke_fpr);  
  1507             if (session->was_id_for_revoke_contacted)
  1508                 sqlite3_finalize(session->was_id_for_revoke_contacted);                                        
  1509             if (session->set_device_group)
  1510                 sqlite3_finalize(session->set_device_group);
  1511             if (session->get_device_group)
  1512                 sqlite3_finalize(session->get_device_group);
  1513             if (session->set_pgp_keypair)
  1514                 sqlite3_finalize(session->set_pgp_keypair);
  1515             if (session->exists_identity_entry)
  1516                 sqlite3_finalize(session->exists_identity_entry);                
  1517             if (session->set_identity_entry)
  1518                 sqlite3_finalize(session->set_identity_entry);
  1519             if (session->update_identity_entry)
  1520                 sqlite3_finalize(session->update_identity_entry);    
  1521             if (session->set_identity_flags)
  1522                 sqlite3_finalize(session->set_identity_flags);
  1523             if (session->unset_identity_flags)
  1524                 sqlite3_finalize(session->unset_identity_flags);
  1525             if (session->exists_trust_entry)
  1526                 sqlite3_finalize(session->exists_trust_entry);                                
  1527             if (session->set_trust)
  1528                 sqlite3_finalize(session->set_trust);
  1529             if (session->update_trust)
  1530                 sqlite3_finalize(session->update_trust);
  1531             if (session->update_trust_to_pep)
  1532                 sqlite3_finalize(session->update_trust_to_pep);                                                
  1533             if (session->update_trust_for_fpr)
  1534                 sqlite3_finalize(session->update_trust_for_fpr);
  1535             if (session->get_trust)
  1536                 sqlite3_finalize(session->get_trust);
  1537             if (session->least_trust)
  1538                 sqlite3_finalize(session->least_trust);
  1539             if (session->mark_compromised)
  1540                 sqlite3_finalize(session->mark_compromised);
  1541             if (session->crashdump)
  1542                 sqlite3_finalize(session->crashdump);
  1543             if (session->languagelist)
  1544                 sqlite3_finalize(session->languagelist);
  1545             if (session->i18n_token)
  1546                 sqlite3_finalize(session->i18n_token);
  1547             if (session->replace_userid)
  1548                 sqlite3_finalize(session->replace_userid);
  1549             if (session->replace_main_user_fpr)
  1550                 sqlite3_finalize(session->replace_main_user_fpr);                
  1551             if (session->get_main_user_fpr)
  1552                 sqlite3_finalize(session->get_main_user_fpr);
  1553             if (session->refresh_userid_default_key)
  1554                 sqlite3_finalize(session->refresh_userid_default_key);
  1555             if (session->blacklist_add)
  1556                 sqlite3_finalize(session->blacklist_add);
  1557             if (session->blacklist_delete)
  1558                 sqlite3_finalize(session->blacklist_delete);
  1559             if (session->blacklist_is_listed)
  1560                 sqlite3_finalize(session->blacklist_is_listed);
  1561             if (session->blacklist_retrieve)
  1562                 sqlite3_finalize(session->blacklist_retrieve);
  1563             if (session->own_key_is_listed)
  1564                 sqlite3_finalize(session->own_key_is_listed);
  1565             if (session->own_identities_retrieve)
  1566                 sqlite3_finalize(session->own_identities_retrieve);
  1567             if (session->own_keys_retrieve)
  1568                 sqlite3_finalize(session->own_keys_retrieve);
  1569             // if (session->set_own_key)
  1570             //     sqlite3_finalize(session->set_own_key);
  1571             if (session->sequence_value1)
  1572                 sqlite3_finalize(session->sequence_value1);
  1573             if (session->sequence_value2)
  1574                 sqlite3_finalize(session->sequence_value2);
  1575             if (session->sequence_value3)
  1576                 sqlite3_finalize(session->sequence_value3);
  1577             if (session->set_revoked)
  1578                 sqlite3_finalize(session->set_revoked);
  1579             if (session->get_revoked)
  1580                 sqlite3_finalize(session->get_revoked);
  1581             if (session->get_replacement_fpr)
  1582                 sqlite3_finalize(session->get_replacement_fpr);                
  1583             if (session->add_mistrusted_key)
  1584                 sqlite3_finalize(session->add_mistrusted_key);
  1585             if (session->delete_mistrusted_key)
  1586                 sqlite3_finalize(session->delete_mistrusted_key);
  1587             if (session->is_mistrusted_key)
  1588                 sqlite3_finalize(session->is_mistrusted_key);
  1589                 
  1590             if (session->db) {
  1591                 sqlite3_exec(        
  1592                     session->db,
  1593                     "PRAGMA optimize;\n",
  1594                     NULL,
  1595                     NULL,
  1596                     NULL
  1597                 );
  1598                 sqlite3_close_v2(session->db);
  1599             }
  1600             if (session->system_db)
  1601                 sqlite3_close_v2(session->system_db);
  1602         }
  1603 
  1604         release_transport_system(session, out_last);
  1605         release_cryptotech(session, out_last);
  1606 
  1607 #ifdef DEBUG_ERRORSTACK
  1608         free_stringlist(session->errorstack);
  1609 #endif
  1610         free(session);
  1611     }
  1612 }
  1613 
  1614 DYNAMIC_API void config_passive_mode(PEP_SESSION session, bool enable)
  1615 {
  1616     assert(session);
  1617     session->passive_mode = enable;
  1618 }
  1619 
  1620 DYNAMIC_API void config_unencrypted_subject(PEP_SESSION session, bool enable)
  1621 {
  1622     assert(session);
  1623     session->unencrypted_subject = enable;
  1624 }
  1625 
  1626 DYNAMIC_API void config_keep_sync_msg(PEP_SESSION session, bool enable)
  1627 {
  1628     assert(session);
  1629     session->keep_sync_msg = enable;
  1630 }
  1631 
  1632 DYNAMIC_API void config_service_log(PEP_SESSION session, bool enable)
  1633 {
  1634     assert(session);
  1635     session->service_log = enable;
  1636 }
  1637 
  1638 DYNAMIC_API PEP_STATUS log_event(
  1639         PEP_SESSION session,
  1640         const char *title,
  1641         const char *entity,
  1642         const char *description,
  1643         const char *comment
  1644     )
  1645 {
  1646 //    PEP_STATUS status = PEP_STATUS_OK;
  1647     // int result;
  1648     // 
  1649     // assert(session);
  1650     // assert(title);
  1651     // assert(entity);
  1652     // 
  1653     // if (!(session && title && entity))
  1654     //     return PEP_ILLEGAL_VALUE;
  1655     // 
  1656     // sqlite3_reset(session->log);
  1657     // sqlite3_bind_text(session->log, 1, title, -1, SQLITE_STATIC);
  1658     // sqlite3_bind_text(session->log, 2, entity, -1, SQLITE_STATIC);
  1659     // if (description)
  1660     //     sqlite3_bind_text(session->log, 3, description, -1, SQLITE_STATIC);
  1661     // else
  1662     //     sqlite3_bind_null(session->log, 3);
  1663     // if (comment)
  1664     //     sqlite3_bind_text(session->log, 4, comment, -1, SQLITE_STATIC);
  1665     // else
  1666     //     sqlite3_bind_null(session->log, 4);
  1667     // result = sqlite3_step(session->log);
  1668     // sqlite3_reset(session->log);
  1669     // 
  1670     return PEP_STATUS_OK; // We ignore errors for this function.
  1671 }
  1672 
  1673 DYNAMIC_API PEP_STATUS log_service(
  1674         PEP_SESSION session,
  1675         const char *title,
  1676         const char *entity,
  1677         const char *description,
  1678         const char *comment
  1679     )
  1680 {
  1681     assert(session);
  1682     if (!session)
  1683         return PEP_ILLEGAL_VALUE;
  1684 
  1685     if (session->service_log)
  1686         return log_event(session, title, entity, description, comment);
  1687     else
  1688         return PEP_STATUS_OK;
  1689 }
  1690 
  1691 DYNAMIC_API PEP_STATUS trustword(
  1692             PEP_SESSION session, uint16_t value, const char *lang,
  1693             char **word, size_t *wsize
  1694         )
  1695 {
  1696     PEP_STATUS status = PEP_STATUS_OK;
  1697 
  1698     assert(session);
  1699     assert(word);
  1700     assert(wsize);
  1701 
  1702     if (!(session && word && wsize))
  1703         return PEP_ILLEGAL_VALUE;
  1704 
  1705     *word = NULL;
  1706     *wsize = 0;
  1707 
  1708     if (lang == NULL)
  1709         lang = "en";
  1710 
  1711     assert((lang[0] >= 'A' && lang[0] <= 'Z')
  1712             || (lang[0] >= 'a' && lang[0] <= 'z'));
  1713     assert((lang[1] >= 'A' && lang[1] <= 'Z')
  1714             || (lang[1] >= 'a' && lang[1] <= 'z'));
  1715     assert(lang[2] == 0);
  1716 
  1717     sqlite3_reset(session->trustword);
  1718     sqlite3_bind_text(session->trustword, 1, lang, -1, SQLITE_STATIC);
  1719     sqlite3_bind_int(session->trustword, 2, value);
  1720 
  1721     const int result = sqlite3_step(session->trustword);
  1722     if (result == SQLITE_ROW) {
  1723         *word = strdup((const char *) sqlite3_column_text(session->trustword,
  1724                     1));
  1725         if (*word)
  1726             *wsize = sqlite3_column_bytes(session->trustword, 1);
  1727         else
  1728             status = PEP_OUT_OF_MEMORY;
  1729     } else
  1730         status = PEP_TRUSTWORD_NOT_FOUND;
  1731 
  1732     sqlite3_reset(session->trustword);
  1733     return status;
  1734 }
  1735 
  1736 DYNAMIC_API PEP_STATUS trustwords(
  1737         PEP_SESSION session, const char *fingerprint, const char *lang,
  1738         char **words, size_t *wsize, int max_words
  1739     )
  1740 {
  1741     const char *source = fingerprint;
  1742 
  1743     assert(session);
  1744     assert(fingerprint);
  1745     assert(words);
  1746     assert(wsize);
  1747     assert(max_words >= 0);
  1748 
  1749     if (!(session && fingerprint && words && wsize && max_words >= 0))
  1750         return PEP_ILLEGAL_VALUE;
  1751 
  1752     *words = NULL;
  1753     *wsize = 0;
  1754 
  1755     char *buffer = calloc(1, MAX_TRUSTWORDS_SPACE);
  1756     assert(buffer);
  1757     if (buffer == NULL)
  1758         return PEP_OUT_OF_MEMORY;
  1759     char *dest = buffer;
  1760 
  1761     const size_t fsize = strlen(fingerprint);
  1762 
  1763     if (!lang || !lang[0])
  1764         lang = "en";
  1765 
  1766     assert((lang[0] >= 'A' && lang[0] <= 'Z')
  1767             || (lang[0] >= 'a' && lang[0] <= 'z'));
  1768     assert((lang[1] >= 'A' && lang[1] <= 'Z')
  1769             || (lang[1] >= 'a' && lang[1] <= 'z'));
  1770     assert(lang[2] == 0);
  1771 
  1772     int n_words = 0;
  1773     while (source < fingerprint + fsize) {
  1774         PEP_STATUS _status;
  1775         uint16_t value;
  1776         char *word = NULL;
  1777         size_t _wsize = 0;
  1778         int j;
  1779 
  1780         for (value=0, j=0; j < 4 && source < fingerprint + fsize; ) {
  1781             if (*source >= 'a' && *source <= 'f')
  1782                 value += (*source - 'a' + 10) << (3 - j++) * 4;
  1783             else if (*source >= 'A' && *source <= 'F')
  1784                 value += (*source - 'A' + 10) << (3 - j++) * 4;
  1785             else if (*source >= '0' && *source <= '9')
  1786                 value += (*source - '0') << (3 - j++) * 4;
  1787             
  1788             source++;
  1789         }
  1790 
  1791         _status = trustword(session, value, lang, &word, &_wsize);
  1792         if (_status == PEP_OUT_OF_MEMORY) {
  1793             free(buffer);
  1794             return PEP_OUT_OF_MEMORY;
  1795         }
  1796         if (word == NULL) {
  1797             free(buffer);
  1798             return PEP_TRUSTWORD_NOT_FOUND;
  1799         }
  1800 
  1801         if (dest + _wsize < buffer + MAX_TRUSTWORDS_SPACE - 1) {
  1802             strncpy(dest, word, _wsize);
  1803             free(word);
  1804             dest += _wsize;
  1805         }
  1806         else {
  1807             free(word);
  1808             break; // buffer full
  1809         }
  1810 
  1811         if (source < fingerprint + fsize
  1812                 && dest + _wsize < buffer + MAX_TRUSTWORDS_SPACE - 1)
  1813             *dest++ = ' ';
  1814 
  1815         ++n_words;
  1816         if (max_words && n_words >= max_words)
  1817             break;
  1818     }
  1819 
  1820     *words = buffer;
  1821     *wsize = dest - buffer;
  1822     return PEP_STATUS_OK;
  1823 }
  1824 
  1825 pEp_identity *new_identity(
  1826         const char *address, const char *fpr, const char *user_id,
  1827         const char *username
  1828     )
  1829 {
  1830     pEp_identity *result = calloc(1, sizeof(pEp_identity));
  1831     assert(result);
  1832     if (result) {
  1833         if (address) {
  1834             result->address = strdup(address);
  1835             assert(result->address);
  1836             if (result->address == NULL) {
  1837                 free(result);
  1838                 return NULL;
  1839             }
  1840         }
  1841         if (fpr) {
  1842             result->fpr = strdup(fpr);
  1843             assert(result->fpr);
  1844             if (result->fpr == NULL) {
  1845                 free_identity(result);
  1846                 return NULL;
  1847             }
  1848         }
  1849         if (user_id) {
  1850             result->user_id = strdup(user_id);
  1851             assert(result->user_id);
  1852             if (result->user_id == NULL) {
  1853                 free_identity(result);
  1854                 return NULL;
  1855             }
  1856         }
  1857         if (username) {
  1858             result->username = strdup(username);
  1859             assert(result->username);
  1860             if (result->username == NULL) {
  1861                 free_identity(result);
  1862                 return NULL;
  1863             }
  1864         }
  1865     }
  1866     return result;
  1867 }
  1868 
  1869 pEp_identity *identity_dup(const pEp_identity *src)
  1870 {
  1871     assert(src);
  1872 
  1873     pEp_identity *dup = new_identity(src->address, src->fpr, src->user_id,
  1874             src->username);
  1875     assert(dup);
  1876     if (dup == NULL)
  1877         return NULL;
  1878     
  1879     dup->comm_type = src->comm_type;
  1880     dup->lang[0] = src->lang[0];
  1881     dup->lang[1] = src->lang[1];
  1882     dup->lang[2] = 0;
  1883     dup->flags = src->flags;
  1884     dup->me = src->me;
  1885     
  1886     return dup;
  1887 }
  1888 
  1889 void free_identity(pEp_identity *identity)
  1890 {
  1891     if (identity) {
  1892         free(identity->address);
  1893         free(identity->fpr);
  1894         free(identity->user_id);
  1895         free(identity->username);
  1896         free(identity);
  1897     }
  1898 }
  1899 
  1900 DYNAMIC_API PEP_STATUS get_default_own_userid(
  1901         PEP_SESSION session, 
  1902         char** userid
  1903     )
  1904 {
  1905     assert(session);
  1906     assert(userid);
  1907     
  1908     if (!session || !userid)
  1909         return PEP_ILLEGAL_VALUE;
  1910         
  1911     PEP_STATUS status = PEP_STATUS_OK;
  1912     char* retval = NULL;
  1913     
  1914     sqlite3_reset(session->get_default_own_userid);
  1915 
  1916     const int result = sqlite3_step(session->get_default_own_userid);
  1917     const char* id;
  1918     
  1919     switch (result) {
  1920         case SQLITE_ROW:
  1921             id = (const char *) sqlite3_column_text(session->get_default_own_userid, 0);
  1922             if (!id) {
  1923                 // Shouldn't happen.
  1924                 status = PEP_UNKNOWN_ERROR;
  1925             }
  1926             else {
  1927                 retval = strdup(id);
  1928                 if (!retval)
  1929                     status = PEP_OUT_OF_MEMORY;
  1930             }
  1931             break;
  1932         default:
  1933             // Technically true, given how we find it, but FIXME we need a more descriptive error
  1934             status = PEP_CANNOT_FIND_IDENTITY;
  1935             *userid = NULL;
  1936     }
  1937 
  1938     *userid = retval;
  1939 
  1940     sqlite3_reset(session->get_default_own_userid);
  1941     
  1942     return status;
  1943 }
  1944 
  1945 DYNAMIC_API PEP_STATUS get_userid_alias_default(
  1946         PEP_SESSION session, 
  1947         const char* alias_id,
  1948         char** default_id) {
  1949             
  1950     assert(session);
  1951     assert(alias_id);
  1952     assert(alias_id[0]);
  1953     assert(default_id);
  1954 
  1955     if (!(session && alias_id && alias_id[0] && default_id))
  1956         return PEP_ILLEGAL_VALUE;
  1957 
  1958     PEP_STATUS status = PEP_STATUS_OK;
  1959     char* retval = NULL;
  1960 
  1961     sqlite3_reset(session->get_userid_alias_default);
  1962     sqlite3_bind_text(session->get_userid_alias_default, 1, alias_id, -1, SQLITE_STATIC);
  1963 
  1964     const char* tempid;
  1965     
  1966     const int result = sqlite3_step(session->get_userid_alias_default);
  1967     switch (result) {
  1968     case SQLITE_ROW:
  1969         tempid = (const char *) sqlite3_column_text(session->get_userid_alias_default, 0);
  1970         if (tempid) {
  1971             retval = strdup(tempid);
  1972             assert(retval);
  1973             if (retval == NULL)
  1974                 return PEP_OUT_OF_MEMORY;
  1975         }
  1976     
  1977         *default_id = retval;
  1978         break;
  1979     default:
  1980         status = PEP_CANNOT_FIND_ALIAS;
  1981         *default_id = NULL;
  1982     }
  1983 
  1984     sqlite3_reset(session->get_userid_alias_default);
  1985     return status;            
  1986 }
  1987 
  1988 DYNAMIC_API PEP_STATUS set_userid_alias (
  1989         PEP_SESSION session, 
  1990         const char* default_id,
  1991         const char* alias_id) {
  1992             
  1993     int result;
  1994 
  1995     assert(session);
  1996     assert(default_id);
  1997     assert(alias_id);
  1998 
  1999     if (!(session && default_id && alias_id && 
  2000           default_id[0] != '\0' && alias_id[0] != '\0'))
  2001         return PEP_ILLEGAL_VALUE;
  2002     
  2003     sqlite3_exec(session->db, "BEGIN TRANSACTION ;", NULL, NULL, NULL);
  2004 
  2005     sqlite3_reset(session->add_userid_alias);
  2006     sqlite3_bind_text(session->add_userid_alias, 1, default_id, -1,
  2007             SQLITE_STATIC);
  2008     sqlite3_bind_text(session->add_userid_alias, 2, alias_id, -1,
  2009             SQLITE_STATIC);
  2010         
  2011     result = sqlite3_step(session->add_userid_alias);
  2012 
  2013     sqlite3_reset(session->add_userid_alias);
  2014     if (result != SQLITE_DONE) {
  2015         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);        
  2016         return PEP_CANNOT_SET_ALIAS;
  2017     }
  2018     sqlite3_exec(session->db, "COMMIT ;", NULL, NULL, NULL);
  2019         
  2020 
  2021     return PEP_STATUS_OK;
  2022 }
  2023 
  2024 DYNAMIC_API PEP_STATUS get_identity(
  2025         PEP_SESSION session,
  2026         const char *address,
  2027         const char *user_id,
  2028         pEp_identity **identity
  2029     )
  2030 {
  2031     PEP_STATUS status = PEP_STATUS_OK;
  2032     static pEp_identity *_identity;
  2033 
  2034     assert(session);
  2035     assert(address);
  2036     assert(address[0]);
  2037     assert(identity);
  2038 
  2039     if (!(session && address && address[0] && identity))
  2040         return PEP_ILLEGAL_VALUE;
  2041 
  2042     *identity = NULL;
  2043 
  2044     sqlite3_reset(session->get_identity);
  2045     sqlite3_bind_text(session->get_identity, 1, address, -1, SQLITE_STATIC);
  2046     sqlite3_bind_text(session->get_identity, 2, user_id, -1, SQLITE_STATIC);
  2047 
  2048     const int result = sqlite3_step(session->get_identity);
  2049     switch (result) {
  2050     case SQLITE_ROW:
  2051         _identity = new_identity(
  2052                 address,
  2053                 (const char *) sqlite3_column_text(session->get_identity, 0),
  2054                 user_id,
  2055                 (const char *) sqlite3_column_text(session->get_identity, 1)
  2056                 );
  2057         assert(_identity);
  2058         if (_identity == NULL) {
  2059             sqlite3_reset(session->get_identity);
  2060             return PEP_OUT_OF_MEMORY;
  2061         }
  2062 
  2063         _identity->comm_type = (PEP_comm_type)
  2064             sqlite3_column_int(session->get_identity, 2);
  2065         const char* const _lang = (const char *)
  2066             sqlite3_column_text(session->get_identity, 3);
  2067         if (_lang && _lang[0]) {
  2068             assert(_lang[0] >= 'a' && _lang[0] <= 'z');
  2069             assert(_lang[1] >= 'a' && _lang[1] <= 'z');
  2070             assert(_lang[2] == 0);
  2071             _identity->lang[0] = _lang[0];
  2072             _identity->lang[1] = _lang[1];
  2073             _identity->lang[2] = 0;
  2074         }
  2075         _identity->flags = (unsigned int)
  2076             sqlite3_column_int(session->get_identity, 4);
  2077         _identity->me = (unsigned int)
  2078             sqlite3_column_int(session->get_identity, 5);
  2079     
  2080         *identity = _identity;
  2081         break;
  2082     default:
  2083         sqlite3_reset(session->get_identity);
  2084         status = PEP_CANNOT_FIND_IDENTITY;
  2085         *identity = NULL;
  2086     }
  2087 
  2088     sqlite3_reset(session->get_identity);
  2089     return status;
  2090 }
  2091 
  2092 PEP_STATUS get_identity_without_trust_check(
  2093         PEP_SESSION session,
  2094         const char *address,
  2095         const char *user_id,
  2096         pEp_identity **identity
  2097     )
  2098 {
  2099     PEP_STATUS status = PEP_STATUS_OK;
  2100     static pEp_identity *_identity;
  2101 
  2102     assert(session);
  2103     assert(address);
  2104     assert(address[0]);
  2105     assert(identity);
  2106 
  2107     if (!(session && address && address[0] && identity))
  2108         return PEP_ILLEGAL_VALUE;
  2109 
  2110     *identity = NULL;
  2111 
  2112     sqlite3_reset(session->get_identity_without_trust_check);
  2113     sqlite3_bind_text(session->get_identity_without_trust_check, 1, address, -1, SQLITE_STATIC);
  2114     sqlite3_bind_text(session->get_identity_without_trust_check, 2, user_id, -1, SQLITE_STATIC);
  2115 
  2116     const int result = sqlite3_step(session->get_identity_without_trust_check);
  2117     switch (result) {
  2118     case SQLITE_ROW:
  2119         _identity = new_identity(
  2120                 address,
  2121                 (const char *) sqlite3_column_text(session->get_identity_without_trust_check, 0),
  2122                 user_id,
  2123                 (const char *) sqlite3_column_text(session->get_identity_without_trust_check, 1)
  2124                 );
  2125         assert(_identity);
  2126         if (_identity == NULL) {
  2127             sqlite3_reset(session->get_identity_without_trust_check);
  2128             return PEP_OUT_OF_MEMORY;
  2129         }
  2130 
  2131         _identity->comm_type = PEP_ct_unknown;
  2132         const char* const _lang = (const char *)
  2133             sqlite3_column_text(session->get_identity_without_trust_check, 2);
  2134         if (_lang && _lang[0]) {
  2135             assert(_lang[0] >= 'a' && _lang[0] <= 'z');
  2136             assert(_lang[1] >= 'a' && _lang[1] <= 'z');
  2137             assert(_lang[2] == 0);
  2138             _identity->lang[0] = _lang[0];
  2139             _identity->lang[1] = _lang[1];
  2140             _identity->lang[2] = 0;
  2141         }
  2142         _identity->flags = (unsigned int)
  2143             sqlite3_column_int(session->get_identity_without_trust_check, 3);
  2144         _identity->me = (unsigned int)
  2145             sqlite3_column_int(session->get_identity_without_trust_check, 4);
  2146     
  2147         *identity = _identity;
  2148         break;
  2149     default:
  2150         status = PEP_CANNOT_FIND_IDENTITY;
  2151         *identity = NULL;
  2152     }
  2153 
  2154     sqlite3_reset(session->get_identity_without_trust_check);
  2155     return status;
  2156 }
  2157 
  2158 PEP_STATUS get_identities_by_address(
  2159         PEP_SESSION session,
  2160         const char *address,
  2161         identity_list** id_list
  2162     )
  2163 {
  2164     pEp_identity* ident;
  2165 
  2166     assert(session);
  2167     assert(address);
  2168     assert(address[0]);
  2169     assert(id_list);
  2170 
  2171     if (!(session && address && address[0] && id_list))
  2172         return PEP_ILLEGAL_VALUE;
  2173 
  2174     *id_list = NULL;
  2175     identity_list* ident_list = NULL;
  2176 
  2177     sqlite3_reset(session->get_identities_by_address);
  2178     sqlite3_bind_text(session->get_identities_by_address, 1, address, -1, SQLITE_STATIC);
  2179     int result;
  2180 
  2181     while ((result = sqlite3_step(session->get_identities_by_address)) == SQLITE_ROW) {
  2182         //"select user_id, main_key_id, username, comm_type, lang,"
  2183         //"   identity.flags, is_own"
  2184         ident = new_identity(
  2185                 address,
  2186                 (const char *) sqlite3_column_text(session->get_identities_by_address, 1),
  2187                 (const char *) sqlite3_column_text(session->get_identities_by_address, 0),
  2188                 (const char *) sqlite3_column_text(session->get_identities_by_address, 2)
  2189                 );
  2190         assert(ident);
  2191         if (ident == NULL) {
  2192             sqlite3_reset(session->get_identities_by_address);
  2193             return PEP_OUT_OF_MEMORY;
  2194         }
  2195 
  2196         ident->comm_type = PEP_ct_unknown;
  2197         
  2198         const char* const _lang = (const char *)
  2199             sqlite3_column_text(session->get_identities_by_address, 3);
  2200         if (_lang && _lang[0]) {
  2201             assert(_lang[0] >= 'a' && _lang[0] <= 'z');
  2202             assert(_lang[1] >= 'a' && _lang[1] <= 'z');
  2203             assert(_lang[2] == 0);
  2204             ident->lang[0] = _lang[0];
  2205             ident->lang[1] = _lang[1];
  2206             ident->lang[2] = 0;
  2207         }
  2208         ident->flags = (unsigned int)
  2209             sqlite3_column_int(session->get_identities_by_address, 4);
  2210         ident->me = (unsigned int)
  2211             sqlite3_column_int(session->get_identities_by_address, 5);
  2212     
  2213         if (ident_list)
  2214             identity_list_add(ident_list, ident);
  2215         else
  2216             ident_list = new_identity_list(ident);
  2217     }
  2218 
  2219     sqlite3_reset(session->get_identities_by_address);
  2220     
  2221     *id_list = ident_list;
  2222     
  2223     if (!ident_list)
  2224         return PEP_CANNOT_FIND_IDENTITY;
  2225     
  2226     return PEP_STATUS_OK;
  2227 }
  2228 
  2229 PEP_STATUS exists_identity_entry(PEP_SESSION session, pEp_identity* identity,
  2230                                  bool* exists) {
  2231     assert(session);
  2232     assert(identity);
  2233     assert(!EMPTYSTR(identity->user_id));        
  2234     assert(!EMPTYSTR(identity->address));
  2235     if (!session || !exists || EMPTYSTR(identity->user_id) || EMPTYSTR(identity->address))
  2236         return PEP_ILLEGAL_VALUE;
  2237     
  2238     *exists = false;
  2239     
  2240     PEP_STATUS status = PEP_STATUS_OK;
  2241     
  2242     sqlite3_reset(session->exists_identity_entry);
  2243     sqlite3_bind_text(session->exists_identity_entry, 1, identity->address, -1,
  2244                       SQLITE_STATIC);
  2245     sqlite3_bind_text(session->exists_identity_entry, 2, identity->user_id, -1,
  2246                   
  2247     int result = sqlite3_step(session->exists_identity_entry);
  2248     SQLITE_STATIC);
  2249     switch (result) {
  2250         case SQLITE_ROW: {
  2251             // yeah yeah, I know, we could be lazy here, but it looks bad.
  2252             *exists = (sqlite3_column_int(session->exists_identity_entry, 0) != 0);
  2253             break;
  2254         }
  2255         default: 
  2256             status = PEP_UNKNOWN_ERROR;
  2257     }
  2258 
  2259     sqlite3_reset(session->exists_identity_entry);
  2260     return status;
  2261 }
  2262 
  2263 PEP_STATUS exists_trust_entry(PEP_SESSION session, pEp_identity* identity,
  2264                               bool* exists) {
  2265     assert(session);
  2266     assert(identity);
  2267     assert(!EMPTYSTR(identity->user_id));        
  2268     assert(!EMPTYSTR(identity->fpr));
  2269     if (!session || !exists || EMPTYSTR(identity->user_id) || EMPTYSTR(identity->fpr))
  2270         return PEP_ILLEGAL_VALUE;
  2271     
  2272     *exists = false;
  2273     
  2274     PEP_STATUS status = PEP_STATUS_OK;
  2275     
  2276     sqlite3_reset(session->exists_trust_entry);
  2277     sqlite3_bind_text(session->exists_trust_entry, 1, identity->user_id, -1,
  2278                       SQLITE_STATIC);
  2279     sqlite3_bind_text(session->exists_trust_entry, 2, identity->fpr, -1,
  2280                       SQLITE_STATIC);
  2281                   
  2282     int result = sqlite3_step(session->exists_trust_entry);
  2283     switch (result) {
  2284         case SQLITE_ROW: {
  2285             // yeah yeah, I know, we could be lazy here, but it looks bad.
  2286             *exists = (sqlite3_column_int(session->exists_trust_entry, 0) != 0);
  2287             break;
  2288         }
  2289         default:
  2290             status = PEP_UNKNOWN_ERROR;
  2291     }
  2292     
  2293     sqlite3_reset(session->exists_trust_entry);
  2294     return status;
  2295 }
  2296 
  2297 // FIXME: We can rollback in set_identity on the return status,
  2298 // so we should probably do that.
  2299 PEP_STATUS set_pgp_keypair(PEP_SESSION session, const char* fpr) {
  2300     if (!session || EMPTYSTR(fpr))
  2301         return PEP_ILLEGAL_VALUE;
  2302         
  2303     int result;
  2304     
  2305     sqlite3_reset(session->set_pgp_keypair);
  2306     sqlite3_bind_text(session->set_pgp_keypair, 1, fpr, -1,
  2307             SQLITE_STATIC);
  2308     result = sqlite3_step(session->set_pgp_keypair);
  2309     sqlite3_reset(session->set_pgp_keypair);
  2310     if (result != SQLITE_DONE) {
  2311         return PEP_CANNOT_SET_PGP_KEYPAIR;
  2312     }
  2313     
  2314     return PEP_STATUS_OK;
  2315 }
  2316 
  2317 static PEP_STATUS _set_or_update_trust(PEP_SESSION session,
  2318                                        pEp_identity* identity,
  2319                                        sqlite3_stmt* set_or_update) {
  2320 
  2321     assert(session);
  2322     assert(identity);
  2323     assert(identity->user_id);
  2324     assert(identity->fpr);
  2325     
  2326     if (!session || !identity || EMPTYSTR(identity->user_id) || EMPTYSTR(identity->fpr))
  2327         return PEP_ILLEGAL_VALUE;
  2328         
  2329     int result;
  2330                 
  2331     sqlite3_reset(set_or_update);
  2332     sqlite3_bind_text(set_or_update, 1, identity->user_id, -1,
  2333             SQLITE_STATIC);
  2334     sqlite3_bind_text(set_or_update, 2, identity->fpr, -1,
  2335             SQLITE_STATIC);
  2336     sqlite3_bind_int(set_or_update, 3, identity->comm_type);
  2337     result = sqlite3_step(set_or_update);
  2338     assert(result == SQLITE_DONE);
  2339     sqlite3_reset(set_or_update);
  2340     if (result != SQLITE_DONE)
  2341         return PEP_CANNOT_SET_TRUST;
  2342 
  2343     return PEP_STATUS_OK;
  2344 }
  2345 
  2346 static PEP_STATUS _set_or_update_identity_entry(PEP_SESSION session,
  2347                                                 pEp_identity* identity,
  2348                                                 sqlite3_stmt* set_or_update) {
  2349     assert(session);
  2350     assert(identity);
  2351     assert(set_or_update);
  2352                       
  2353     if (!session || !identity || !identity->user_id || !identity->address)
  2354         return PEP_ILLEGAL_VALUE;
  2355                                               
  2356     sqlite3_reset(set_or_update);
  2357     sqlite3_bind_text(set_or_update, 1, identity->address, -1,
  2358             SQLITE_STATIC);
  2359     sqlite3_bind_text(set_or_update, 2, identity->fpr, -1,
  2360             SQLITE_STATIC);
  2361     sqlite3_bind_text(set_or_update, 3, identity->user_id, -1,
  2362             SQLITE_STATIC);
  2363     sqlite3_bind_int(set_or_update, 4, identity->flags);
  2364     sqlite3_bind_int(set_or_update, 5, identity->me);
  2365     int result = sqlite3_step(set_or_update);
  2366     sqlite3_reset(set_or_update);
  2367     if (result != SQLITE_DONE)
  2368         return PEP_CANNOT_SET_IDENTITY;
  2369     
  2370     return PEP_STATUS_OK;
  2371 }
  2372 
  2373 static PEP_STATUS _set_or_update_person(PEP_SESSION session, 
  2374                                         pEp_identity* identity,
  2375                                         sqlite3_stmt* set_or_update) {
  2376     assert(session);
  2377     assert(identity);
  2378     assert(set_or_update);
  2379                         
  2380     if (!session || !identity || !identity->user_id || !identity->username)
  2381         return PEP_ILLEGAL_VALUE;
  2382         
  2383     sqlite3_reset(set_or_update);
  2384     sqlite3_bind_text(set_or_update, 1, identity->user_id, -1,
  2385             SQLITE_STATIC);
  2386     sqlite3_bind_text(set_or_update, 2, identity->username, -1,
  2387             SQLITE_STATIC);
  2388     if (identity->lang[0])
  2389         sqlite3_bind_text(set_or_update, 3, identity->lang, 2,
  2390                 SQLITE_STATIC);
  2391     else
  2392         sqlite3_bind_null(set_or_update, 3);
  2393     sqlite3_bind_text(set_or_update, 4, identity->fpr, -1,
  2394                       SQLITE_STATIC);
  2395     int result = sqlite3_step(set_or_update);
  2396     sqlite3_reset(set_or_update);
  2397     
  2398     if (result != SQLITE_DONE)
  2399         return PEP_CANNOT_SET_PERSON;
  2400     
  2401     return PEP_STATUS_OK;                                         
  2402 }
  2403 
  2404 PEP_STATUS set_or_update_with_identity(PEP_SESSION session,
  2405                                        pEp_identity* identity,
  2406                                        PEP_STATUS (* set_function)(PEP_SESSION, pEp_identity*, sqlite3_stmt*),
  2407                                        PEP_STATUS (* exists_function)(PEP_SESSION, pEp_identity*, bool*),                                       
  2408                                        sqlite3_stmt* update_query,
  2409                                        sqlite3_stmt* set_query,
  2410                                        bool guard_transaction) {
  2411 
  2412     if (guard_transaction) {
  2413         sqlite3_exec(session->db, "BEGIN TRANSACTION ;", NULL, NULL, NULL);
  2414     }
  2415     bool exists = false;
  2416     PEP_STATUS status = exists_function(session, identity, &exists);
  2417     
  2418     if (status == PEP_STATUS_OK) {
  2419         if (exists) {
  2420             status = set_function(session, identity, update_query);
  2421         }
  2422         else {
  2423             status = set_function(session, identity, set_query);                                              
  2424         }                    
  2425     }   
  2426     if (guard_transaction) {        
  2427         if (status != PEP_STATUS_OK)
  2428             sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  2429         else 
  2430             sqlite3_exec(session->db, "COMMIT ;", NULL, NULL, NULL);
  2431     }                      
  2432     return status;
  2433 }
  2434 
  2435 PEP_STATUS _set_trust_internal(PEP_SESSION session, pEp_identity* identity,
  2436                                bool guard_transaction) {
  2437     return set_or_update_with_identity(session, identity,
  2438                                        _set_or_update_trust,
  2439                                         exists_trust_entry,
  2440                                         session->update_trust,
  2441                                         session->set_trust,
  2442                                         guard_transaction);
  2443 }
  2444 
  2445 // This is the TOP-LEVEL function. If you're calling from set_identity,
  2446 // you can't use this one.
  2447 PEP_STATUS set_trust(PEP_SESSION session, pEp_identity* identity) {
  2448     PEP_STATUS status = PEP_STATUS_OK;
  2449     
  2450     status = _set_trust_internal(session, identity, true);
  2451     if (status == PEP_STATUS_OK) {
  2452         if ((identity->comm_type | PEP_ct_confirmed) == PEP_ct_pEp)
  2453             status = set_as_pep_user(session, identity);
  2454     }
  2455     return status;
  2456 }
  2457 
  2458 PEP_STATUS set_person(PEP_SESSION session, pEp_identity* identity,
  2459                       bool guard_transaction) {
  2460     return set_or_update_with_identity(session, identity,
  2461                                        _set_or_update_person,
  2462                                        exists_person,
  2463                                        session->update_person,
  2464                                        session->set_person,
  2465                                        guard_transaction);
  2466 }
  2467 
  2468 PEP_STATUS set_identity_entry(PEP_SESSION session, pEp_identity* identity,
  2469                               bool guard_transaction) {
  2470     return set_or_update_with_identity(session, identity,
  2471                                        _set_or_update_identity_entry,
  2472                                        exists_identity_entry,
  2473                                        session->update_identity_entry,
  2474                                        session->set_identity_entry,
  2475                                        guard_transaction);
  2476 }
  2477 
  2478 // This will NOT call set_as_pep_user; you have to do that separately.
  2479 DYNAMIC_API PEP_STATUS set_identity(
  2480         PEP_SESSION session, const pEp_identity *identity
  2481     )
  2482 {
  2483     int result;
  2484 
  2485     assert(session);
  2486     assert(identity);
  2487     assert(identity->address);
  2488     assert(identity->user_id);
  2489     assert(identity->username);
  2490 
  2491     if (!(session && identity && identity->address &&
  2492                 identity->user_id && identity->username))
  2493         return PEP_ILLEGAL_VALUE;
  2494 
  2495     PEP_STATUS status = PEP_STATUS_OK;
  2496     
  2497     bool has_fpr = (!EMPTYSTR(identity->fpr));
  2498     
  2499     sqlite3_exec(session->db, "BEGIN TRANSACTION ;", NULL, NULL, NULL);
  2500 
  2501     if (identity->lang[0]) {
  2502         assert(identity->lang[0] >= 'a' && identity->lang[0] <= 'z');
  2503         assert(identity->lang[1] >= 'a' && identity->lang[1] <= 'z');
  2504         assert(identity->lang[2] == 0);
  2505     }
  2506 
  2507     if (has_fpr) {
  2508         sqlite3_reset(session->set_pgp_keypair);
  2509         sqlite3_bind_text(session->set_pgp_keypair, 1, identity->fpr, -1,
  2510                 SQLITE_STATIC);
  2511         result = sqlite3_step(session->set_pgp_keypair);
  2512         sqlite3_reset(session->set_pgp_keypair);
  2513         if (result != SQLITE_DONE) {
  2514             sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  2515             return PEP_CANNOT_SET_PGP_KEYPAIR;
  2516         }
  2517     }
  2518 
  2519     // We do this because there are checks in set_person for
  2520     // aliases, which modify the identity object on return.
  2521     pEp_identity* ident_copy = identity_dup(identity); 
  2522     if (!ident_copy)
  2523         return PEP_OUT_OF_MEMORY;
  2524 
  2525     status = set_person(session, ident_copy, false);
  2526     if (status != PEP_STATUS_OK) {
  2527         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  2528         goto pep_free;
  2529     }
  2530 
  2531     status = set_identity_entry(session, ident_copy, false);
  2532     if (status != PEP_STATUS_OK) {
  2533         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  2534         goto pep_free;
  2535     }
  2536 
  2537     if (has_fpr) {
  2538         status = _set_trust_internal(session, ident_copy, false);
  2539         if (status != PEP_STATUS_OK) {
  2540             sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  2541             goto pep_free;
  2542         }
  2543     }
  2544     
  2545     result = sqlite3_exec(session->db, "COMMIT ;", NULL, NULL, NULL);
  2546     if (result == SQLITE_OK)
  2547         status = PEP_STATUS_OK;
  2548     else
  2549         status = PEP_COMMIT_FAILED;
  2550 
  2551 pep_free:
  2552     free_identity(ident_copy);
  2553     return status;
  2554 }
  2555 
  2556 PEP_STATUS update_pep_user_trust_vals(PEP_SESSION session,
  2557                                       pEp_identity* user) {
  2558     if (!user->user_id)
  2559         return PEP_ILLEGAL_VALUE;
  2560     
  2561     sqlite3_reset(session->update_trust_to_pep);
  2562     sqlite3_bind_text(session->update_trust_to_pep, 1, user->user_id, -1,
  2563             SQLITE_STATIC);
  2564     int result = sqlite3_step(session->update_trust_to_pep);
  2565     sqlite3_reset(session->update_trust_to_pep);
  2566     if (result != SQLITE_DONE)
  2567         return PEP_CANNOT_SET_TRUST;
  2568 
  2569     return PEP_STATUS_OK;
  2570 }
  2571 
  2572 
  2573 // This ONLY sets the user flag. Must be called outside of a transaction.
  2574 PEP_STATUS set_as_pep_user(PEP_SESSION session, pEp_identity* user) {
  2575 
  2576     assert(session);
  2577     assert(user);
  2578     assert(!EMPTYSTR(user->user_id));
  2579         
  2580     if (!session || !user || EMPTYSTR(user->user_id))
  2581         return PEP_ILLEGAL_VALUE;
  2582             
  2583     PEP_STATUS status = PEP_STATUS_OK;
  2584     
  2585     bool person_exists = false;
  2586     
  2587     status = exists_person(session, user, &person_exists);
  2588     
  2589     if (status != PEP_STATUS_OK)
  2590         return status;
  2591         
  2592     if (!person_exists)
  2593         status = set_person(session, user, true);
  2594         
  2595     // Ok, let's set it.
  2596     sqlite3_reset(session->set_as_pep_user);
  2597     sqlite3_bind_text(session->set_as_pep_user, 1, user->user_id, -1,
  2598             SQLITE_STATIC);
  2599     int result = sqlite3_step(session->set_as_pep_user);
  2600     sqlite3_reset(session->set_as_pep_user);
  2601     
  2602     if (result != SQLITE_DONE)
  2603         return PEP_CANNOT_SET_PERSON;
  2604 
  2605     status = update_pep_user_trust_vals(session, user);
  2606         
  2607     return status;
  2608 }
  2609 
  2610 PEP_STATUS exists_person(PEP_SESSION session, pEp_identity* identity,
  2611                          bool* exists) {            
  2612     
  2613     // const char* user_id,
  2614     //                      char** default_id, bool* exists) {
  2615     assert(session);
  2616     assert(exists);
  2617     assert(identity);
  2618     assert(!EMPTYSTR(identity->user_id));
  2619         
  2620     if (!session || !exists || !identity || EMPTYSTR(identity->user_id))
  2621         return PEP_ILLEGAL_VALUE;
  2622     
  2623     *exists = false;
  2624 
  2625     const char* user_id = identity->user_id;
  2626     char* alias_default = NULL;
  2627     
  2628     PEP_STATUS status = get_userid_alias_default(session, user_id, &alias_default);
  2629     
  2630     if (status == PEP_CANNOT_FIND_ALIAS || EMPTYSTR(alias_default)) {
  2631         sqlite3_reset(session->exists_person);
  2632         sqlite3_bind_text(session->exists_person, 1, user_id, -1,
  2633                 SQLITE_STATIC);
  2634         int result = sqlite3_step(session->exists_person);
  2635         switch (result) {
  2636             case SQLITE_ROW: {
  2637                 // yeah yeah, I know, we could be lazy here, but it looks bad.
  2638                 *exists = (sqlite3_column_int(session->exists_person, 0) != 0);
  2639                 status = PEP_STATUS_OK;
  2640                 break;
  2641             }
  2642             default:
  2643                 sqlite3_reset(session->exists_person);
  2644                 return PEP_UNKNOWN_ERROR;
  2645         }
  2646         sqlite3_reset(session->exists_person);
  2647     }
  2648     else if (status == PEP_STATUS_OK) {
  2649         *exists = true; // thank you, delete on cascade!
  2650         // FIXME: Should we correct the userid default here? I think we should.
  2651         free(identity->user_id);
  2652         identity->user_id = alias_default; // ownership transfer
  2653     }
  2654     else
  2655         free(alias_default);
  2656             
  2657     return status;
  2658 }
  2659 
  2660 DYNAMIC_API PEP_STATUS is_pep_user(PEP_SESSION session, pEp_identity *identity, bool* is_pep)
  2661 {
  2662     assert(session);
  2663     assert(is_pep);
  2664     assert(identity);
  2665     assert(!EMPTYSTR(identity->user_id));
  2666 
  2667     if (!session || !is_pep || !identity || EMPTYSTR(identity->user_id))
  2668         return PEP_ILLEGAL_VALUE;
  2669     
  2670     *is_pep = false;
  2671             
  2672     const char* user_id = identity->user_id;
  2673     
  2674     if (!session || EMPTYSTR(user_id))
  2675         return PEP_ILLEGAL_VALUE;
  2676         
  2677     char* alias_default = NULL;
  2678     
  2679     PEP_STATUS status = get_userid_alias_default(session, user_id, &alias_default);
  2680     
  2681     if (status == PEP_CANNOT_FIND_ALIAS || EMPTYSTR(alias_default)) {
  2682         free(alias_default);
  2683         alias_default = strdup(user_id);
  2684     }
  2685     
  2686     sqlite3_reset(session->is_pep_user);
  2687     sqlite3_bind_text(session->is_pep_user, 1, user_id, -1,
  2688             SQLITE_STATIC);
  2689     int result = sqlite3_step(session->is_pep_user);
  2690     switch (result) {
  2691         case SQLITE_ROW: {
  2692             // yeah yeah, I know, we could be lazy here, but it looks bad.
  2693             *is_pep = (sqlite3_column_int(session->is_pep_user, 0) != 0);
  2694             break;
  2695         }
  2696         default:
  2697             sqlite3_reset(session->is_pep_user);
  2698             free(alias_default);
  2699             return PEP_CANNOT_FIND_PERSON;
  2700     }
  2701 
  2702     sqlite3_reset(session->is_pep_user);
  2703     return PEP_STATUS_OK;
  2704 }
  2705 
  2706 PEP_STATUS bind_own_ident_with_contact_ident(PEP_SESSION session,
  2707                                              pEp_identity* own_ident, 
  2708                                              pEp_identity* contact_ident) {
  2709     if (!own_ident || !contact_ident || 
  2710         !own_ident->address || !own_ident->user_id || !contact_ident->user_id)
  2711         return PEP_ILLEGAL_VALUE;
  2712         
  2713     sqlite3_reset(session->add_into_social_graph);
  2714     sqlite3_bind_text(session->add_into_social_graph, 1, own_ident->user_id, -1,
  2715             SQLITE_STATIC);
  2716     sqlite3_bind_text(session->add_into_social_graph, 2, own_ident->address, -1,
  2717             SQLITE_STATIC);
  2718     sqlite3_bind_text(session->add_into_social_graph, 3, contact_ident->user_id, -1,
  2719             SQLITE_STATIC);
  2720         
  2721     int result = sqlite3_step(session->add_into_social_graph);
  2722     sqlite3_reset(session->add_into_social_graph);
  2723     
  2724     if (result != SQLITE_DONE)
  2725         return PEP_CANNOT_SET_PERSON;
  2726 
  2727     return PEP_STATUS_OK;
  2728 }
  2729 
  2730 PEP_STATUS get_own_ident_for_contact_id(PEP_SESSION session,
  2731                                           const pEp_identity* contact
  2732                                           pEp_identity** own_ident) {
  2733     if (!contact || !contact->user_id || !own_ident)
  2734         return PEP_ILLEGAL_VALUE;
  2735         
  2736     char* own_user_id = NULL;
  2737     *own_ident = NULL;
  2738     PEP_STATUS status = get_default_own_userid(session, &own_user_id);
  2739     
  2740     if (status != PEP_STATUS_OK)
  2741         return status;
  2742 
  2743     sqlite3_reset(session->get_own_address_binding_from_contact);
  2744     sqlite3_bind_text(session->get_own_address_binding_from_contact, 1, own_user_id, -1,
  2745             SQLITE_STATIC);
  2746     sqlite3_bind_text(session->get_own_address_binding_from_contact, 2, contact_ident->user_id, -1,
  2747             SQLITE_STATIC);
  2748 
  2749     result = sqlite3_step(session->get_own_address_binding_from_contact);
  2750     switch (result) {
  2751         case SQLITE_ROW:
  2752             const char* const own_address = (const char *)
  2753                 sqlite3_column_text(session->get_own_address_binding_from_contact, 0);
  2754             if (own_address) {
  2755                 status = get_identity(session, own_address, own_user_id, own_ident);
  2756                 if (status == PEP_STATUS_OK) {
  2757                     if (!own_ident)
  2758                         status = PEP_CANNOT_FIND_IDENTITY;
  2759                 }
  2760             }
  2761             break;
  2762         default:
  2763             status = PEP_CANNOT_FIND_IDENTITY;
  2764     }
  2765     
  2766     free(own_user_id);
  2767     return status;
  2768 }
  2769 
  2770 PEP_STATUS remove_fpr_as_default(PEP_SESSION session, 
  2771                                  const char* fpr) 
  2772 {
  2773     assert(fpr);
  2774     
  2775     if (!session || !fpr)
  2776         return PEP_ILLEGAL_VALUE;
  2777             
  2778     sqlite3_reset(session->remove_fpr_as_default);
  2779     sqlite3_bind_text(session->remove_fpr_as_default, 1, fpr, -1,
  2780                       SQLITE_STATIC);
  2781 
  2782     int result = sqlite3_step(session->remove_fpr_as_default);
  2783     sqlite3_reset(session->remove_fpr_as_default);
  2784     
  2785     if (result != SQLITE_DONE)
  2786         return PEP_CANNOT_SET_IDENTITY; // misleading - could also be person
  2787 
  2788     return PEP_STATUS_OK;
  2789 }
  2790 
  2791 
  2792 PEP_STATUS replace_identities_fpr(PEP_SESSION session, 
  2793                                  const char* old_fpr, 
  2794                                  const char* new_fpr) 
  2795 {
  2796     assert(old_fpr);
  2797     assert(new_fpr);
  2798     
  2799     if (!old_fpr || !new_fpr)
  2800         return PEP_ILLEGAL_VALUE;
  2801             
  2802     sqlite3_reset(session->replace_identities_fpr);
  2803     sqlite3_bind_text(session->replace_identities_fpr, 1, new_fpr, -1,
  2804                       SQLITE_STATIC);
  2805     sqlite3_bind_text(session->replace_identities_fpr, 2, old_fpr, -1,
  2806                       SQLITE_STATIC);
  2807 
  2808     int result = sqlite3_step(session->replace_identities_fpr);
  2809     sqlite3_reset(session->replace_identities_fpr);
  2810     
  2811     if (result != SQLITE_DONE)
  2812         return PEP_CANNOT_SET_IDENTITY;
  2813 
  2814     return PEP_STATUS_OK;
  2815 }
  2816 
  2817 PEP_STATUS update_trust_for_fpr(PEP_SESSION session, 
  2818                                 const char* fpr, 
  2819                                 PEP_comm_type comm_type)
  2820 {
  2821     if (!fpr)
  2822         return PEP_ILLEGAL_VALUE;
  2823         
  2824     sqlite3_reset(session->update_trust_for_fpr);
  2825     sqlite3_bind_int(session->update_trust_for_fpr, 1, comm_type);
  2826     sqlite3_bind_text(session->update_trust_for_fpr, 2, fpr, -1,
  2827             SQLITE_STATIC);
  2828     int result = sqlite3_step(session->update_trust_for_fpr);
  2829     sqlite3_reset(session->update_trust_for_fpr);
  2830     if (result != SQLITE_DONE) {
  2831         return PEP_CANNOT_SET_TRUST;
  2832     }
  2833     
  2834     return PEP_STATUS_OK;
  2835 }
  2836 
  2837 DYNAMIC_API PEP_STATUS set_device_group(
  2838         PEP_SESSION session,
  2839         const char *group_name
  2840     )
  2841 {
  2842     int result;
  2843 
  2844     assert(session);
  2845 
  2846     if (!(session && group_name))
  2847         return PEP_ILLEGAL_VALUE;
  2848 
  2849     // 1. Get own user_id
  2850     char* user_id = NULL;
  2851     PEP_STATUS status = get_default_own_userid(session, &user_id);
  2852     
  2853     // No user_id is returned in this case, no need to free;
  2854     if (status != PEP_STATUS_OK)
  2855         return status;
  2856         
  2857     // 2. Set device group
  2858     sqlite3_reset(session->set_device_group);
  2859     if(group_name){
  2860         sqlite3_bind_text(session->set_device_group, 1, group_name, -1,
  2861                 SQLITE_STATIC);
  2862     } else {
  2863         sqlite3_bind_null(session->set_device_group, 1);
  2864     }
  2865     
  2866     sqlite3_bind_text(session->set_device_group, 2, user_id, -1,
  2867             SQLITE_STATIC);
  2868 
  2869     result = sqlite3_step(session->set_device_group);
  2870     sqlite3_reset(session->set_device_group);
  2871     
  2872     free(user_id);
  2873     
  2874     if (result != SQLITE_DONE)
  2875         return PEP_CANNOT_SET_PERSON;
  2876 
  2877     return PEP_STATUS_OK;
  2878 }
  2879 
  2880 DYNAMIC_API PEP_STATUS get_device_group(PEP_SESSION session, char **group_name)
  2881 {
  2882     PEP_STATUS status = PEP_STATUS_OK;
  2883     int result;
  2884 
  2885     assert(session);
  2886     assert(group_name);
  2887 
  2888     if (!(session && group_name))
  2889         return PEP_ILLEGAL_VALUE;
  2890 
  2891     // 1. Get own user_id
  2892     char* user_id = NULL;
  2893     status = get_default_own_userid(session, &user_id);
  2894     
  2895     // No user_id is returned in this case, no need to free;
  2896     if (status != PEP_STATUS_OK)
  2897         return status;
  2898 
  2899     // 2. get device group
  2900     sqlite3_reset(session->get_device_group);
  2901     sqlite3_bind_text(session->get_device_group, 1, user_id, -1,
  2902             SQLITE_STATIC);
  2903 
  2904     result = sqlite3_step(session->get_device_group);
  2905     switch (result) {
  2906     case SQLITE_ROW: {
  2907         const char *_group_name = (const char *)sqlite3_column_text(session->get_device_group, 0);
  2908         if(_group_name){
  2909             *group_name = strdup(_group_name);
  2910                 if(*group_name == NULL)
  2911                     status = PEP_OUT_OF_MEMORY;
  2912         }
  2913         break;
  2914     }
  2915  
  2916     default:
  2917         status = PEP_RECORD_NOT_FOUND;
  2918     }
  2919 
  2920     free(user_id);
  2921     sqlite3_reset(session->get_device_group);
  2922     return status;
  2923 }
  2924 
  2925 DYNAMIC_API PEP_STATUS set_identity_flags(
  2926         PEP_SESSION session,
  2927         pEp_identity *identity,
  2928         unsigned int flags
  2929     )
  2930 {
  2931     int result;
  2932 
  2933     assert(session);
  2934     assert(identity);
  2935     assert(identity->address);
  2936     assert(identity->user_id);
  2937 
  2938     if (!(session && identity && identity->address && identity->user_id))
  2939         return PEP_ILLEGAL_VALUE;
  2940 
  2941     sqlite3_reset(session->set_identity_flags);
  2942     sqlite3_bind_int(session->set_identity_flags, 1, flags);
  2943     sqlite3_bind_text(session->set_identity_flags, 2, identity->address, -1,
  2944             SQLITE_STATIC);
  2945     sqlite3_bind_text(session->set_identity_flags, 3, identity->user_id, -1,
  2946         SQLITE_STATIC);
  2947         
  2948     result = sqlite3_step(session->set_identity_flags);
  2949 
  2950     sqlite3_reset(session->set_identity_flags);
  2951     if (result != SQLITE_DONE)
  2952         return PEP_CANNOT_SET_IDENTITY;
  2953 
  2954     identity->flags |= flags;
  2955     return PEP_STATUS_OK;
  2956 }
  2957 
  2958 DYNAMIC_API PEP_STATUS unset_identity_flags(
  2959         PEP_SESSION session,
  2960         pEp_identity *identity,
  2961         unsigned int flags
  2962     )
  2963 {
  2964     int result;
  2965 
  2966     assert(session);
  2967     assert(identity);
  2968     assert(identity->address);
  2969     assert(identity->user_id);
  2970 
  2971     if (!(session && identity && identity->address && identity->user_id))
  2972         return PEP_ILLEGAL_VALUE;
  2973 
  2974     sqlite3_reset(session->unset_identity_flags);
  2975     sqlite3_bind_int(session->unset_identity_flags, 1, flags);
  2976     sqlite3_bind_text(session->unset_identity_flags, 2, identity->address, -1,
  2977             SQLITE_STATIC);
  2978     sqlite3_bind_text(session->unset_identity_flags, 3, identity->user_id, -1,
  2979             SQLITE_STATIC);
  2980     result = sqlite3_step(session->unset_identity_flags);
  2981     sqlite3_reset(session->unset_identity_flags);
  2982     if (result != SQLITE_DONE)
  2983         return PEP_CANNOT_SET_IDENTITY;
  2984 
  2985     identity->flags &= ~flags;
  2986 
  2987     return PEP_STATUS_OK;
  2988 }
  2989 
  2990 
  2991 PEP_STATUS replace_userid(PEP_SESSION session, const char* old_uid,
  2992                               const char* new_uid) {
  2993     assert(session);
  2994     assert(old_uid);
  2995     assert(new_uid);
  2996     
  2997     if (!session || !old_uid || !new_uid)
  2998         return PEP_ILLEGAL_VALUE;
  2999 
  3000 
  3001     int result;
  3002 
  3003     sqlite3_reset(session->replace_userid);
  3004     sqlite3_bind_text(session->replace_userid, 1, new_uid, -1,
  3005             SQLITE_STATIC);
  3006     sqlite3_bind_text(session->replace_userid, 2, old_uid, -1,
  3007             SQLITE_STATIC);
  3008     result = sqlite3_step(session->replace_userid);
  3009     sqlite3_reset(session->replace_userid);
  3010     if (result != SQLITE_DONE)
  3011         return PEP_CANNOT_SET_PERSON; // May need clearer retval
  3012 
  3013     return PEP_STATUS_OK;
  3014 }
  3015 
  3016 PEP_STATUS refresh_userid_default_key(PEP_SESSION session, const char* user_id) {
  3017     assert(session);
  3018     assert(user_id);
  3019     
  3020     if (!session || !user_id)
  3021         return PEP_ILLEGAL_VALUE;
  3022 
  3023     int result;
  3024 
  3025     sqlite3_reset(session->refresh_userid_default_key);
  3026     sqlite3_bind_text(session->refresh_userid_default_key, 1, user_id, -1,
  3027             SQLITE_STATIC);
  3028     result = sqlite3_step(session->refresh_userid_default_key);
  3029     sqlite3_reset(session->refresh_userid_default_key);
  3030     if (result != SQLITE_DONE)
  3031         return PEP_CANNOT_SET_PERSON;
  3032 
  3033     return PEP_STATUS_OK;    
  3034 }
  3035 
  3036 PEP_STATUS replace_main_user_fpr(PEP_SESSION session, const char* user_id,
  3037                                  const char* new_fpr) {
  3038     assert(session);
  3039     assert(user_id);
  3040     assert(new_fpr);
  3041     
  3042     if (!session || !user_id || !new_fpr)
  3043         return PEP_ILLEGAL_VALUE;
  3044 
  3045     int result;
  3046 
  3047     sqlite3_reset(session->replace_main_user_fpr);
  3048     sqlite3_bind_text(session->replace_main_user_fpr, 1, new_fpr, -1,
  3049             SQLITE_STATIC);
  3050     sqlite3_bind_text(session->replace_main_user_fpr, 2, user_id, -1,
  3051             SQLITE_STATIC);
  3052     result = sqlite3_step(session->replace_main_user_fpr);
  3053     sqlite3_reset(session->replace_main_user_fpr);
  3054     if (result != SQLITE_DONE)
  3055         return PEP_CANNOT_SET_PERSON;
  3056 
  3057     return PEP_STATUS_OK;
  3058 }
  3059 
  3060 PEP_STATUS get_main_user_fpr(PEP_SESSION session, 
  3061                              const char* user_id,
  3062                              char** main_fpr)
  3063 {
  3064     PEP_STATUS status = PEP_STATUS_OK;
  3065     int result;
  3066     
  3067     assert(session);
  3068     assert(user_id);
  3069     assert(main_fpr);
  3070     
  3071     if (!(session && user_id && user_id[0] && main_fpr))
  3072         return PEP_ILLEGAL_VALUE;
  3073         
  3074     *main_fpr = NULL;
  3075     
  3076     sqlite3_reset(session->get_main_user_fpr);
  3077     sqlite3_bind_text(session->get_main_user_fpr, 1, user_id, -1,
  3078                       SQLITE_STATIC);
  3079     result = sqlite3_step(session->get_main_user_fpr);
  3080     switch (result) {
  3081     case SQLITE_ROW: {
  3082         const char* _fpr = 
  3083             (const char *) sqlite3_column_text(session->get_main_user_fpr, 0);
  3084         if (_fpr) {
  3085             *main_fpr = strdup(_fpr);
  3086             if (!(*main_fpr))
  3087                 status = PEP_OUT_OF_MEMORY;
  3088         }
  3089         else {
  3090             status = PEP_KEY_NOT_FOUND;
  3091         }
  3092         break;
  3093     }
  3094     default:
  3095         status = PEP_CANNOT_FIND_PERSON;
  3096     }
  3097 
  3098     sqlite3_reset(session->get_main_user_fpr);
  3099     return status;
  3100 }
  3101 
  3102 // Deprecated
  3103 DYNAMIC_API PEP_STATUS mark_as_compromized(
  3104         PEP_SESSION session,
  3105         const char *fpr
  3106     )
  3107 {
  3108     return mark_as_compromised(session, fpr);
  3109 }
  3110 
  3111 DYNAMIC_API PEP_STATUS mark_as_compromised(
  3112         PEP_SESSION session,
  3113         const char *fpr
  3114     )
  3115 {
  3116     int result;
  3117 
  3118     assert(session);
  3119     assert(fpr && fpr[0]);
  3120 
  3121     if (!(session && fpr && fpr[0]))
  3122         return PEP_ILLEGAL_VALUE;
  3123 
  3124     sqlite3_reset(session->mark_compromised);
  3125     sqlite3_bind_text(session->mark_compromised, 1, fpr, -1,
  3126             SQLITE_STATIC);
  3127     result = sqlite3_step(session->mark_compromised);
  3128     sqlite3_reset(session->mark_compromised);
  3129 
  3130     if (result != SQLITE_DONE)
  3131         return PEP_CANNOT_SET_TRUST;
  3132 
  3133     return PEP_STATUS_OK;
  3134 }
  3135 
  3136 void pEp_free(void *p)
  3137 {
  3138     free(p);
  3139 }
  3140 
  3141 
  3142 DYNAMIC_API PEP_STATUS get_trust(PEP_SESSION session, pEp_identity *identity)
  3143 {
  3144     PEP_STATUS status = PEP_STATUS_OK;
  3145     int result;
  3146 
  3147     // We need to be able to test that we break correctly without shutting
  3148     // asserts off everywhere.
  3149     // assert(session);
  3150     // assert(identity);
  3151     // assert(identity->user_id);
  3152     // assert(identity->user_id[0]);
  3153     // assert(identity->fpr);
  3154     // assert(identity->fpr[0]);
  3155 
  3156     if (!(session && identity && identity->user_id && identity->user_id[0] &&
  3157                 identity->fpr && identity->fpr[0]))
  3158         return PEP_ILLEGAL_VALUE;
  3159 
  3160     identity->comm_type = PEP_ct_unknown;
  3161 
  3162     sqlite3_reset(session->get_trust);
  3163     sqlite3_bind_text(session->get_trust, 1, identity->user_id, -1,
  3164             SQLITE_STATIC);
  3165     sqlite3_bind_text(session->get_trust, 2, identity->fpr, -1, SQLITE_STATIC);
  3166 
  3167     result = sqlite3_step(session->get_trust);
  3168     switch (result) {
  3169     case SQLITE_ROW: {
  3170         int comm_type = (PEP_comm_type) sqlite3_column_int(session->get_trust,
  3171                 0);
  3172         identity->comm_type = comm_type;
  3173         break;
  3174     }
  3175  
  3176     default:
  3177         status = PEP_CANNOT_FIND_IDENTITY;
  3178     }
  3179 
  3180     sqlite3_reset(session->get_trust);
  3181     return status;
  3182 }
  3183 
  3184 DYNAMIC_API PEP_STATUS least_trust(
  3185         PEP_SESSION session,
  3186         const char *fpr,
  3187         PEP_comm_type *comm_type
  3188     )
  3189 {
  3190     PEP_STATUS status = PEP_STATUS_OK;
  3191     int result;
  3192 
  3193     assert(session);
  3194     assert(fpr);
  3195     assert(comm_type);
  3196 
  3197     if (!(session && fpr && comm_type))
  3198         return PEP_ILLEGAL_VALUE;
  3199 
  3200     *comm_type = PEP_ct_unknown;
  3201 
  3202     sqlite3_reset(session->least_trust);
  3203     sqlite3_bind_text(session->least_trust, 1, fpr, -1, SQLITE_STATIC);
  3204 
  3205     result = sqlite3_step(session->least_trust);
  3206     switch (result) {
  3207         case SQLITE_ROW: {
  3208             int _comm_type = sqlite3_column_int(session->least_trust, 0);
  3209             *comm_type = (PEP_comm_type) _comm_type;
  3210             break;
  3211         }
  3212         default:
  3213             // never reached because of sql min()
  3214             status = PEP_CANNOT_FIND_IDENTITY;
  3215     }
  3216 
  3217     sqlite3_reset(session->least_trust);
  3218     return status;
  3219 }
  3220 
  3221 DYNAMIC_API PEP_STATUS decrypt_and_verify(
  3222     PEP_SESSION session, const char *ctext, size_t csize,
  3223     const char *dsigtext, size_t dsigsize,
  3224     char **ptext, size_t *psize, stringlist_t **keylist
  3225     )
  3226 {
  3227     assert(session);
  3228     assert(ctext);
  3229     assert(csize);
  3230     assert(ptext);
  3231     assert(psize);
  3232     assert(keylist);
  3233 
  3234     if (!(session && ctext && csize && ptext && psize && keylist))
  3235         return PEP_ILLEGAL_VALUE;
  3236 
  3237     return session->cryptotech[PEP_crypt_OpenPGP].decrypt_and_verify(
  3238             session, ctext, csize, dsigtext, dsigsize, ptext, psize, keylist);
  3239 }
  3240 
  3241 DYNAMIC_API PEP_STATUS encrypt_and_sign(
  3242     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  3243     size_t psize, char **ctext, size_t *csize
  3244     )
  3245 {
  3246     assert(session);
  3247     assert(keylist);
  3248     assert(ptext);
  3249     assert(psize);
  3250     assert(ctext);
  3251     assert(csize);
  3252 
  3253     if (!(session && keylist && ptext && psize && ctext && csize))
  3254         return PEP_ILLEGAL_VALUE;
  3255 
  3256     return session->cryptotech[PEP_crypt_OpenPGP].encrypt_and_sign(session,
  3257             keylist, ptext, psize, ctext, csize);
  3258 }
  3259 
  3260 PEP_STATUS encrypt_only(
  3261     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  3262     size_t psize, char **ctext, size_t *csize
  3263     )
  3264 {
  3265     assert(session);
  3266     assert(keylist);
  3267     assert(ptext);
  3268     assert(psize);
  3269     assert(ctext);
  3270     assert(csize);
  3271 
  3272     if (!(session && keylist && ptext && psize && ctext && csize))
  3273         return PEP_ILLEGAL_VALUE;
  3274 
  3275     return session->cryptotech[PEP_crypt_OpenPGP].encrypt_only(session,
  3276             keylist, ptext, psize, ctext, csize);
  3277 }
  3278 
  3279 
  3280 DYNAMIC_API PEP_STATUS verify_text(
  3281     PEP_SESSION session, const char *text, size_t size,
  3282     const char *signature, size_t sig_size, stringlist_t **keylist
  3283     )
  3284 {
  3285     assert(session);
  3286     assert(text);
  3287     assert(size);
  3288     assert(signature);
  3289     assert(sig_size);
  3290     assert(keylist);
  3291 
  3292     if (!(session && text && size && signature && sig_size && keylist))
  3293         return PEP_ILLEGAL_VALUE;
  3294 
  3295     return session->cryptotech[PEP_crypt_OpenPGP].verify_text(session, text,
  3296             size, signature, sig_size, keylist);
  3297 }
  3298 
  3299 DYNAMIC_API PEP_STATUS delete_keypair(PEP_SESSION session, const char *fpr)
  3300 {
  3301     assert(session);
  3302     assert(fpr);
  3303 
  3304     if (!(session && fpr))
  3305         return PEP_ILLEGAL_VALUE;
  3306 
  3307     return session->cryptotech[PEP_crypt_OpenPGP].delete_keypair(session, fpr);
  3308 }
  3309 
  3310 DYNAMIC_API PEP_STATUS export_key(
  3311         PEP_SESSION session, const char *fpr, char **key_data, size_t *size
  3312     )
  3313 {
  3314     assert(session);
  3315     assert(fpr);
  3316     assert(key_data);
  3317     assert(size);
  3318 
  3319     if (!(session && fpr && key_data && size))
  3320         return PEP_ILLEGAL_VALUE;
  3321 
  3322     return session->cryptotech[PEP_crypt_OpenPGP].export_key(session, fpr,
  3323             key_data, size, false);
  3324 }
  3325 
  3326 DYNAMIC_API PEP_STATUS export_secret_key(
  3327         PEP_SESSION session, const char *fpr, char **key_data, size_t *size
  3328     )
  3329 {
  3330     assert(session);
  3331     assert(fpr);
  3332     assert(key_data);
  3333     assert(size);
  3334 
  3335     if (!(session && fpr && key_data && size))
  3336         return PEP_ILLEGAL_VALUE;
  3337 
  3338     // don't accept key IDs but full fingerprints only
  3339     if (strlen(fpr) < 16)
  3340         return PEP_ILLEGAL_VALUE;
  3341 
  3342     return session->cryptotech[PEP_crypt_OpenPGP].export_key(session, fpr,
  3343             key_data, size, true);
  3344 }
  3345 
  3346 // Deprecated
  3347 DYNAMIC_API PEP_STATUS export_secrect_key(
  3348         PEP_SESSION session, const char *fpr, char **key_data, size_t *size
  3349     )
  3350 {
  3351     return export_secret_key(session, fpr, key_data, size);
  3352 }
  3353 
  3354 DYNAMIC_API PEP_STATUS find_keys(
  3355         PEP_SESSION session, const char *pattern, stringlist_t **keylist
  3356     )
  3357 {
  3358     assert(session);
  3359     assert(pattern);
  3360     assert(keylist);
  3361 
  3362     if (!(session && pattern && keylist))
  3363         return PEP_ILLEGAL_VALUE;
  3364 
  3365     return session->cryptotech[PEP_crypt_OpenPGP].find_keys(session, pattern,
  3366             keylist);
  3367 }
  3368 
  3369 
  3370 DYNAMIC_API PEP_STATUS generate_keypair(
  3371         PEP_SESSION session, pEp_identity *identity
  3372     )
  3373 {
  3374     assert(session);
  3375     assert(identity);
  3376     assert(identity->address);
  3377     assert(identity->fpr == NULL || identity->fpr[0] == 0);
  3378     assert(identity->username);
  3379 
  3380     if (!(session && identity && identity->address &&
  3381             (identity->fpr == NULL || identity->fpr[0] == 0) &&
  3382             identity->username))
  3383         return PEP_ILLEGAL_VALUE;
  3384 
  3385     PEP_STATUS status =
  3386         session->cryptotech[PEP_crypt_OpenPGP].generate_keypair(session,
  3387                 identity);
  3388     if (status != PEP_STATUS_OK)
  3389         return status;
  3390 
  3391     if (identity->fpr)
  3392         status = set_pgp_keypair(session, identity->fpr);
  3393 
  3394     // add to known keypair DB, as this might not end up being a default
  3395     return status;
  3396 }
  3397 
  3398 DYNAMIC_API PEP_STATUS get_key_rating(
  3399         PEP_SESSION session,
  3400         const char *fpr,
  3401         PEP_comm_type *comm_type
  3402     )
  3403 {
  3404     assert(session);
  3405     assert(fpr);
  3406     assert(comm_type);
  3407 
  3408     if (!(session && fpr && comm_type))
  3409         return PEP_ILLEGAL_VALUE;
  3410 
  3411     return session->cryptotech[PEP_crypt_OpenPGP].get_key_rating(session, fpr,
  3412             comm_type);
  3413 }
  3414 
  3415 DYNAMIC_API PEP_STATUS import_key(
  3416         PEP_SESSION session,
  3417         const char *key_data,
  3418         size_t size,
  3419         identity_list **private_keys
  3420     )
  3421 {
  3422     assert(session);
  3423     assert(key_data);
  3424 
  3425     if (!(session && key_data))
  3426         return PEP_ILLEGAL_VALUE;
  3427 
  3428     return session->cryptotech[PEP_crypt_OpenPGP].import_key(session, key_data,
  3429             size, private_keys);
  3430 }
  3431 
  3432 DYNAMIC_API PEP_STATUS recv_key(PEP_SESSION session, const char *pattern)
  3433 {
  3434     assert(session);
  3435     assert(pattern);
  3436 
  3437     if (!(session && pattern))
  3438         return PEP_ILLEGAL_VALUE;
  3439 
  3440     return session->cryptotech[PEP_crypt_OpenPGP].recv_key(session, pattern);
  3441 }
  3442 
  3443 DYNAMIC_API PEP_STATUS send_key(PEP_SESSION session, const char *pattern)
  3444 {
  3445     assert(session);
  3446     assert(pattern);
  3447 
  3448     if (!(session && pattern))
  3449         return PEP_ILLEGAL_VALUE;
  3450 
  3451     return session->cryptotech[PEP_crypt_OpenPGP].send_key(session, pattern);
  3452 }
  3453 
  3454 DYNAMIC_API PEP_STATUS renew_key(
  3455         PEP_SESSION session,
  3456         const char *fpr,
  3457         const timestamp *ts
  3458     )
  3459 {
  3460     assert(session);
  3461     assert(fpr);
  3462 
  3463     if (!(session && fpr))
  3464         return PEP_ILLEGAL_VALUE;
  3465 
  3466     return session->cryptotech[PEP_crypt_OpenPGP].renew_key(session, fpr, ts);
  3467 }
  3468 
  3469 DYNAMIC_API PEP_STATUS revoke_key(
  3470         PEP_SESSION session,
  3471         const char *fpr,
  3472         const char *reason
  3473     )
  3474 {
  3475     assert(session);
  3476     assert(fpr);
  3477 
  3478     if (!(session && fpr))
  3479         return PEP_ILLEGAL_VALUE;
  3480 
  3481     return session->cryptotech[PEP_crypt_OpenPGP].revoke_key(session, fpr,
  3482             reason);
  3483 }
  3484 
  3485 DYNAMIC_API PEP_STATUS key_expired(
  3486         PEP_SESSION session,
  3487         const char *fpr,
  3488         const time_t when,
  3489         bool *expired
  3490     )
  3491 {
  3492     assert(session);
  3493     assert(fpr);
  3494     assert(expired);
  3495 
  3496     if (!(session && fpr && expired))
  3497         return PEP_ILLEGAL_VALUE;
  3498 
  3499     return session->cryptotech[PEP_crypt_OpenPGP].key_expired(session, fpr,
  3500             when, expired);
  3501 }
  3502 
  3503 DYNAMIC_API PEP_STATUS key_revoked(
  3504        PEP_SESSION session,
  3505        const char *fpr,
  3506        bool *revoked
  3507    )
  3508 {
  3509     assert(session);
  3510     assert(fpr);
  3511     assert(revoked);
  3512     
  3513     if (!(session && fpr && revoked))
  3514         return PEP_ILLEGAL_VALUE;
  3515     
  3516     return session->cryptotech[PEP_crypt_OpenPGP].key_revoked(session, fpr,
  3517             revoked);
  3518 }
  3519 
  3520 static void _clean_log_value(char *text)
  3521 {
  3522     if (text) {
  3523         for (char *c = text; *c; c++) {
  3524             if (*c < 32 && *c != '\n')
  3525                 *c = 32;
  3526             else if (*c == '"')
  3527                 *c = '\'';
  3528         }
  3529     }
  3530 }
  3531 
  3532 static char *_concat_string(char *str1, const char *str2, char delim)
  3533 {
  3534     str2 = str2 ? str2 : "";
  3535     size_t len1 = str1 ? strlen(str1) : 0;
  3536     size_t len2 = strlen(str2);
  3537     size_t len = len1 + len2 + 3;
  3538     char * result = realloc(str1, len + 1);
  3539 
  3540     if (result) {
  3541         result[len1] = '"';
  3542         strcpy(result + len1 + 1, str2);
  3543         result[len - 2] = '"';
  3544         result[len - 1] = delim;
  3545         result[len] = 0;
  3546     }
  3547     else {
  3548         free(str1);
  3549     }
  3550 
  3551     return result;
  3552 }
  3553 
  3554 DYNAMIC_API PEP_STATUS get_crashdump_log(
  3555         PEP_SESSION session,
  3556         int maxlines,
  3557         char **logdata
  3558     )
  3559 {
  3560     PEP_STATUS status = PEP_STATUS_OK;
  3561     char *_logdata= NULL;
  3562 
  3563     assert(session);
  3564     assert(maxlines >= 0 && maxlines <= CRASHDUMP_MAX_LINES);
  3565     assert(logdata);
  3566 
  3567     if (!(session && logdata && maxlines >= 0 && maxlines <=
  3568             CRASHDUMP_MAX_LINES))
  3569         return PEP_ILLEGAL_VALUE;
  3570 
  3571     *logdata = NULL;
  3572 
  3573     int limit = maxlines ? maxlines : CRASHDUMP_DEFAULT_LINES;
  3574     const char *timestamp = NULL;
  3575     const char *title = NULL;
  3576     const char *entity = NULL;
  3577     const char *desc = NULL;
  3578     const char *comment = NULL;
  3579 
  3580     sqlite3_reset(session->crashdump);
  3581     sqlite3_bind_int(session->crashdump, 1, limit);
  3582 
  3583     int result;
  3584 
  3585     do {
  3586         result = sqlite3_step(session->crashdump);
  3587         switch (result) {
  3588         case SQLITE_ROW:
  3589             timestamp = (const char *) sqlite3_column_text(session->crashdump,
  3590                     0);
  3591             title   = (const char *) sqlite3_column_text(session->crashdump,
  3592                     1);
  3593             entity  = (const char *) sqlite3_column_text(session->crashdump,
  3594                     2);
  3595             desc    = (const char *) sqlite3_column_text(session->crashdump,
  3596                     3);
  3597             comment = (const char *) sqlite3_column_text(session->crashdump,
  3598                     4);
  3599 
  3600             _logdata = _concat_string(_logdata, timestamp, ',');
  3601             if (_logdata == NULL)
  3602                 goto enomem;
  3603 
  3604             _logdata = _concat_string(_logdata, title, ',');
  3605             if (_logdata == NULL)
  3606                 goto enomem;
  3607 
  3608             _logdata = _concat_string(_logdata, entity, ',');
  3609             if (_logdata == NULL)
  3610                 goto enomem;
  3611 
  3612             _logdata = _concat_string(_logdata, desc, ',');
  3613             if (_logdata == NULL)
  3614                 goto enomem;
  3615 
  3616             _logdata = _concat_string(_logdata, comment, '\n');
  3617             if (_logdata == NULL)
  3618                 goto enomem;
  3619 
  3620             _clean_log_value(_logdata);
  3621             break;
  3622 
  3623         case SQLITE_DONE:
  3624             break;
  3625 
  3626         default:
  3627             status = PEP_UNKNOWN_ERROR;
  3628             result = SQLITE_DONE;
  3629         }
  3630     } while (result != SQLITE_DONE);
  3631 
  3632     sqlite3_reset(session->crashdump);
  3633     if (status == PEP_STATUS_OK) {
  3634         if (_logdata) {
  3635             *logdata = _logdata;
  3636         }
  3637         else {
  3638             *logdata = strdup("");
  3639             if (!*logdata)
  3640                 goto enomem;
  3641         }
  3642     }
  3643 
  3644     goto the_end;
  3645 
  3646 enomem:
  3647     status = PEP_OUT_OF_MEMORY;
  3648 
  3649 the_end:
  3650     return status;
  3651 }
  3652 
  3653 DYNAMIC_API PEP_STATUS get_languagelist(
  3654         PEP_SESSION session,
  3655         char **languages
  3656     )
  3657 {
  3658     PEP_STATUS status = PEP_STATUS_OK;
  3659     char *_languages= NULL;
  3660 
  3661     assert(session);
  3662     assert(languages);
  3663 
  3664     if (!(session && languages))
  3665         return PEP_ILLEGAL_VALUE;
  3666 
  3667     *languages = NULL;
  3668 
  3669     const char *lang = NULL;
  3670     const char *name = NULL;
  3671     const char *phrase = NULL;
  3672 
  3673     sqlite3_reset(session->languagelist);
  3674 
  3675     int result;
  3676 
  3677     do {
  3678         result = sqlite3_step(session->languagelist);
  3679         switch (result) {
  3680         case SQLITE_ROW:
  3681             lang = (const char *) sqlite3_column_text(session->languagelist,
  3682                     0);
  3683             name = (const char *) sqlite3_column_text(session->languagelist,
  3684                     1);
  3685             phrase = (const char *) sqlite3_column_text(session->languagelist,
  3686                     2);
  3687 
  3688             _languages = _concat_string(_languages, lang, ',');
  3689             if (_languages == NULL)
  3690                 goto enomem;
  3691 
  3692             _languages = _concat_string(_languages, name, ',');
  3693             if (_languages == NULL)
  3694                 goto enomem;
  3695 
  3696             _languages = _concat_string(_languages, phrase, '\n');
  3697             if (_languages == NULL)
  3698                 goto enomem;
  3699 
  3700             break;
  3701 
  3702         case SQLITE_DONE:
  3703             break;
  3704 
  3705         default:
  3706             status = PEP_UNKNOWN_ERROR;
  3707             result = SQLITE_DONE;
  3708         }
  3709     } while (result != SQLITE_DONE);
  3710 
  3711     sqlite3_reset(session->languagelist);
  3712     if (status == PEP_STATUS_OK)
  3713         *languages = _languages;
  3714 
  3715     goto the_end;
  3716 
  3717 enomem:
  3718     status = PEP_OUT_OF_MEMORY;
  3719 
  3720 the_end:
  3721     return status;
  3722 }
  3723 
  3724 DYNAMIC_API PEP_STATUS get_phrase(
  3725         PEP_SESSION session,
  3726         const char *lang,
  3727         int phrase_id,
  3728         char **phrase
  3729     )
  3730 {
  3731     PEP_STATUS status = PEP_STATUS_OK;
  3732 
  3733     assert(session && lang && lang[0] && lang[1] && lang[2] == 0 && phrase);
  3734     if (!(session && lang && lang[0] && lang[1] && lang[2] == 0 && phrase))
  3735         return PEP_ILLEGAL_VALUE;
  3736 
  3737     *phrase = NULL;
  3738 
  3739     sqlite3_reset(session->i18n_token);
  3740     sqlite3_bind_text(session->i18n_token, 1, lang, -1, SQLITE_STATIC);
  3741     sqlite3_bind_int(session->i18n_token, 2, phrase_id);
  3742 
  3743     const char *_phrase = NULL;
  3744     int result;
  3745 
  3746     result = sqlite3_step(session->i18n_token);
  3747     switch (result) {
  3748     case SQLITE_ROW:
  3749         _phrase = (const char *) sqlite3_column_text(session->i18n_token, 0);
  3750         break;
  3751 
  3752     case SQLITE_DONE:
  3753         status = PEP_PHRASE_NOT_FOUND;
  3754         break;
  3755 
  3756     default:
  3757         status = PEP_UNKNOWN_ERROR;
  3758     }
  3759 
  3760     if (status == PEP_STATUS_OK) {
  3761         *phrase = strdup(_phrase);
  3762         if (*phrase == NULL)
  3763             goto enomem;
  3764     }
  3765 
  3766     sqlite3_reset(session->i18n_token);
  3767     goto the_end;
  3768 
  3769 enomem:
  3770     status = PEP_OUT_OF_MEMORY;
  3771 
  3772 the_end:
  3773     return status;
  3774 }
  3775 
  3776 static PEP_STATUS _get_sequence_value(PEP_SESSION session, const char *name,
  3777         int32_t *value)
  3778 {
  3779     assert(session && name && value);
  3780     if (!(session && name && value))
  3781         return PEP_ILLEGAL_VALUE;
  3782 
  3783     PEP_STATUS status = PEP_STATUS_OK;
  3784 
  3785     sqlite3_reset(session->sequence_value2);
  3786     sqlite3_bind_text(session->sequence_value2, 1, name, -1,
  3787             SQLITE_STATIC);
  3788     int result = sqlite3_step(session->sequence_value2);
  3789     switch (result) {
  3790         case SQLITE_ROW: {
  3791             int32_t _value = (int32_t)
  3792                     sqlite3_column_int(session->sequence_value2, 0);
  3793             int _own = (int)
  3794                     sqlite3_column_int(session->sequence_value2, 1);
  3795             *value = _value;
  3796             if (_own)
  3797                 status = PEP_OWN_SEQUENCE;
  3798             break;
  3799         }
  3800         case SQLITE_DONE:
  3801             status = PEP_RECORD_NOT_FOUND;
  3802             break;
  3803         default:
  3804             status = PEP_UNKNOWN_ERROR;
  3805     }
  3806     sqlite3_reset(session->sequence_value2);
  3807 
  3808     return status;
  3809 }
  3810 
  3811 static PEP_STATUS _increment_sequence_value(PEP_SESSION session,
  3812         const char *name, int own)
  3813 {
  3814     assert(session && name);
  3815     if (!(session && name))
  3816         return PEP_ILLEGAL_VALUE;
  3817 
  3818     sqlite3_reset(session->sequence_value1);
  3819     sqlite3_bind_text(session->sequence_value1, 1, name, -1, SQLITE_STATIC);
  3820     sqlite3_bind_int(session->sequence_value1, 2, own);
  3821     int result = sqlite3_step(session->sequence_value1);
  3822     assert(result == SQLITE_DONE);
  3823     sqlite3_reset(session->sequence_value1);
  3824     if (result == SQLITE_DONE)
  3825         return PEP_STATUS_OK;
  3826     else
  3827         return PEP_CANNOT_INCREASE_SEQUENCE;
  3828 }
  3829 
  3830 static PEP_STATUS _set_sequence_value(PEP_SESSION session,
  3831         const char *name, int32_t value, int own)
  3832 {
  3833     assert(session && name && value > 0);
  3834     if (!(session && name && value > 0))
  3835         return PEP_ILLEGAL_VALUE;
  3836 
  3837     sqlite3_reset(session->sequence_value3);
  3838     sqlite3_bind_text(session->sequence_value3, 1, name, -1, SQLITE_STATIC);
  3839     sqlite3_bind_int(session->sequence_value3, 2, value);
  3840     sqlite3_bind_int(session->sequence_value3, 3, own);
  3841     int result = sqlite3_step(session->sequence_value3);
  3842     assert(result == SQLITE_DONE);
  3843     sqlite3_reset(session->sequence_value3);
  3844     if (result == SQLITE_DONE)
  3845         return PEP_STATUS_OK;
  3846     else
  3847         return PEP_CANNOT_SET_SEQUENCE_VALUE;
  3848 }
  3849 
  3850 DYNAMIC_API PEP_STATUS sequence_value(
  3851         PEP_SESSION session,
  3852         char *name,
  3853         int32_t *value
  3854     )
  3855 {
  3856     PEP_STATUS status = PEP_STATUS_OK;
  3857     int result;
  3858 
  3859     assert(session);
  3860     assert(name && value && *value >= 0);
  3861 
  3862     if (!(session && name && value && *value >= 0))
  3863         return PEP_ILLEGAL_VALUE;
  3864 
  3865     int own = 0;
  3866     if (!name[0]) {
  3867         pEpUUID uuid;
  3868         uuid_generate_random(uuid);
  3869         uuid_unparse_upper(uuid, name);
  3870         own = 1;
  3871     }
  3872     else {
  3873         if (name == session->sync_session->sync_uuid || 
  3874             strcmp(name, session->sync_session->sync_uuid) == 0)
  3875             own = 1;
  3876     }
  3877 
  3878     if (*value) {
  3879         sqlite3_exec(session->db, "BEGIN TRANSACTION ;", NULL, NULL, NULL);
  3880         int32_t old_value = 0;
  3881         status = _get_sequence_value(session, name, &old_value);
  3882         if (status != PEP_STATUS_OK && status != PEP_RECORD_NOT_FOUND)
  3883         {
  3884             sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  3885             return status;
  3886         }
  3887 
  3888         if (old_value >= *value) {
  3889             sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  3890             return PEP_SEQUENCE_VIOLATED;
  3891         }
  3892         else {
  3893             status = _set_sequence_value(session, name, *value, own);
  3894             if (status == PEP_STATUS_OK) {
  3895                 result = sqlite3_exec(session->db, "COMMIT ;", NULL, NULL, NULL);
  3896                 if (result == SQLITE_OK)
  3897                     return PEP_STATUS_OK;
  3898                 else
  3899                     return PEP_COMMIT_FAILED;
  3900             } else {
  3901                 sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  3902                 return status;
  3903             }
  3904         }
  3905     }
  3906 
  3907     assert(*value == 0);
  3908     sqlite3_exec(session->db, "BEGIN TRANSACTION ;", NULL, NULL, NULL);
  3909     status = _increment_sequence_value(session, name, own);
  3910     if (status == PEP_STATUS_OK) {
  3911         status = _get_sequence_value(session, name, value);
  3912     }
  3913     if (status == PEP_STATUS_OK || status == PEP_OWN_SEQUENCE) {
  3914         result = sqlite3_exec(session->db, "COMMIT ;", NULL, NULL, NULL);
  3915         if (result == SQLITE_OK){
  3916             assert(*value < INT32_MAX);
  3917             if (*value == INT32_MAX){
  3918                 return PEP_CANNOT_INCREASE_SEQUENCE;
  3919             }
  3920             return status;
  3921         } else {
  3922             return PEP_COMMIT_FAILED;
  3923         }
  3924     } else {
  3925         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  3926         return status;
  3927     }
  3928     return status;
  3929 }
  3930 
  3931 DYNAMIC_API PEP_STATUS set_revoked(
  3932        PEP_SESSION session,
  3933        const char *revoked_fpr,
  3934        const char *replacement_fpr,
  3935        const uint64_t revocation_date
  3936     )
  3937 {
  3938     PEP_STATUS status = PEP_STATUS_OK;
  3939     
  3940     assert(session &&
  3941            revoked_fpr && revoked_fpr[0] &&
  3942            replacement_fpr && replacement_fpr[0]
  3943           );
  3944     
  3945     if (!(session &&
  3946           revoked_fpr && revoked_fpr[0] &&
  3947           replacement_fpr && replacement_fpr[0]
  3948          ))
  3949         return PEP_ILLEGAL_VALUE;
  3950     
  3951     sqlite3_reset(session->set_revoked);
  3952     sqlite3_bind_text(session->set_revoked, 1, revoked_fpr, -1, SQLITE_STATIC);
  3953     sqlite3_bind_text(session->set_revoked, 2, replacement_fpr, -1,
  3954             SQLITE_STATIC);
  3955     sqlite3_bind_int64(session->set_revoked, 3, revocation_date);
  3956 
  3957     int result;
  3958     
  3959     result = sqlite3_step(session->set_revoked);
  3960     switch (result) {
  3961         case SQLITE_DONE:
  3962             status = PEP_STATUS_OK;
  3963             break;
  3964             
  3965         default:
  3966             status = PEP_UNKNOWN_ERROR;
  3967     }
  3968     
  3969     sqlite3_reset(session->set_revoked);
  3970     return status;
  3971 }
  3972 
  3973 DYNAMIC_API PEP_STATUS get_revoked(
  3974         PEP_SESSION session,
  3975         const char *fpr,
  3976         char **revoked_fpr,
  3977         uint64_t *revocation_date
  3978     )
  3979 {
  3980     PEP_STATUS status = PEP_STATUS_OK;
  3981 
  3982     assert(session &&
  3983            revoked_fpr &&
  3984            fpr && fpr[0]
  3985           );
  3986     
  3987     if (!(session &&
  3988            revoked_fpr &&
  3989            fpr && fpr[0]
  3990           ))
  3991         return PEP_ILLEGAL_VALUE;
  3992 
  3993     *revoked_fpr = NULL;
  3994     *revocation_date = 0;
  3995 
  3996     sqlite3_reset(session->get_revoked);
  3997     sqlite3_bind_text(session->get_revoked, 1, fpr, -1, SQLITE_STATIC);
  3998 
  3999     int result;
  4000     
  4001     result = sqlite3_step(session->get_revoked);
  4002     switch (result) {
  4003         case SQLITE_ROW: {
  4004             *revoked_fpr = strdup((const char *)
  4005                     sqlite3_column_text(session->get_revoked, 0));
  4006             if(*revoked_fpr)
  4007                 *revocation_date = sqlite3_column_int64(session->get_revoked,
  4008                         1);
  4009             else
  4010                 status = PEP_OUT_OF_MEMORY;
  4011 
  4012             break;
  4013         }
  4014         default:
  4015             status = PEP_CANNOT_FIND_IDENTITY;
  4016     }
  4017 
  4018     sqlite3_reset(session->get_revoked);
  4019 
  4020     return status;
  4021 }
  4022 
  4023 DYNAMIC_API PEP_STATUS get_replacement_fpr(
  4024         PEP_SESSION session,
  4025         const char *fpr,
  4026         char **revoked_fpr,
  4027         uint64_t *revocation_date
  4028     )
  4029 {
  4030     PEP_STATUS status = PEP_STATUS_OK;
  4031 
  4032     assert(session &&
  4033            revoked_fpr &&
  4034            fpr && fpr[0]
  4035           );
  4036     
  4037     if (!(session &&
  4038            revoked_fpr &&
  4039            fpr && fpr[0]
  4040           ))
  4041         return PEP_ILLEGAL_VALUE;
  4042 
  4043     *revoked_fpr = NULL;
  4044     *revocation_date = 0;
  4045 
  4046     sqlite3_reset(session->get_replacement_fpr);
  4047     sqlite3_bind_text(session->get_replacement_fpr, 1, fpr, -1, SQLITE_STATIC);
  4048 
  4049     int result;
  4050     
  4051     result = sqlite3_step(session->get_replacement_fpr);
  4052     switch (result) {
  4053         case SQLITE_ROW: {
  4054             *revoked_fpr = strdup((const char *)
  4055                     sqlite3_column_text(session->get_replacement_fpr, 0));
  4056             if(*revoked_fpr)
  4057                 *revocation_date = sqlite3_column_int64(session->get_replacement_fpr,
  4058                         1);
  4059             else
  4060                 status = PEP_OUT_OF_MEMORY;
  4061 
  4062             break;
  4063         }
  4064         default:
  4065             status = PEP_CANNOT_FIND_IDENTITY;
  4066     }
  4067 
  4068     sqlite3_reset(session->get_replacement_fpr);
  4069 
  4070     return status;
  4071 }
  4072 
  4073 
  4074 PEP_STATUS key_created(
  4075         PEP_SESSION session,
  4076         const char *fpr,
  4077         time_t *created
  4078     )
  4079 {
  4080     assert(session && fpr && created);
  4081     if (!(session && fpr && created))
  4082         return PEP_ILLEGAL_VALUE;
  4083 
  4084     return session->cryptotech[PEP_crypt_OpenPGP].key_created(session, fpr,
  4085             created);
  4086 }
  4087 
  4088 PEP_STATUS find_private_keys(PEP_SESSION session, const char* pattern,
  4089                              stringlist_t **keylist) {
  4090     assert(session && keylist);
  4091     if (!(session && keylist))
  4092         return PEP_ILLEGAL_VALUE;
  4093     
  4094     return session->cryptotech[PEP_crypt_OpenPGP].find_private_keys(session, pattern,
  4095                                                                     keylist);
  4096 }
  4097 
  4098 
  4099 DYNAMIC_API const char* get_engine_version() {
  4100     return PEP_ENGINE_VERSION;
  4101 }
  4102 
  4103 
  4104 DYNAMIC_API PEP_STATUS reset_peptest_hack(PEP_SESSION session)
  4105 {
  4106     assert(session);
  4107 
  4108     if (!session)
  4109         return PEP_ILLEGAL_VALUE;
  4110 
  4111     int int_result = sqlite3_exec(
  4112         session->db,
  4113         "delete from identity where address like '%@peptest.ch' ;",
  4114         NULL,
  4115         NULL,
  4116         NULL
  4117     );
  4118     assert(int_result == SQLITE_OK);
  4119 
  4120     if (int_result != SQLITE_OK)
  4121         return PEP_UNKNOWN_ERROR;
  4122 
  4123     return PEP_STATUS_OK;
  4124 }
  4125 
  4126 #ifdef DEBUG_ERRORSTACK
  4127 PEP_STATUS session_add_error(PEP_SESSION session, const char* file, unsigned line, PEP_STATUS status)
  4128 {
  4129     char logline[48];
  4130     if(status>0)
  4131     {
  4132         snprintf(logline,47, "%.24s:%u status=%u (0x%x)", file, line, status, status);
  4133     }else{
  4134         snprintf(logline,47, "%.24s:%u status=%i.", file, line, status);
  4135     }
  4136     stringlist_add(session->errorstack, logline); // logline is copied! :-)
  4137     return status;
  4138 }
  4139 
  4140 DYNAMIC_API const stringlist_t* get_errorstack(PEP_SESSION session)
  4141 {
  4142     return session->errorstack;
  4143 }
  4144 
  4145 DYNAMIC_API void clear_errorstack(PEP_SESSION session)
  4146 {
  4147     const int old_len = stringlist_length(session->errorstack);
  4148     char buf[48];
  4149     free_stringlist(session->errorstack);
  4150     snprintf(buf, 47, "(%i elements cleared)", old_len);
  4151     session->errorstack = new_stringlist(buf);
  4152 }
  4153 
  4154 #else
  4155 
  4156 static stringlist_t* dummy_errorstack = NULL;
  4157 
  4158 DYNAMIC_API const stringlist_t* get_errorstack(PEP_SESSION session)
  4159 {
  4160     if(dummy_errorstack == NULL)
  4161     {
  4162         dummy_errorstack = new_stringlist("( Please recompile pEpEngine with -DDEBUG_ERRORSTACK )");
  4163     }
  4164 
  4165     return dummy_errorstack;
  4166 }
  4167 
  4168 DYNAMIC_API void clear_errorstack(PEP_SESSION session)
  4169 {
  4170     // nothing to do here
  4171 }
  4172 
  4173 #endif