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