src/pEpEngine.c
author Volker Birk <vb@pep.foundation>
Mon, 01 Aug 2016 09:14:47 +0200
branchkeysync
changeset 955 060272dfaaeb
parent 951 dec407deb10e
child 958 cef602982909
permissions -rw-r--r--
...
     1 #include "pEp_internal.h"
     2 #include "dynamic_api.h"
     3 #include "cryptotech.h"
     4 #include "transport.h"
     5 #include "blacklist.h"
     6 #include "sync_fsm.h"
     7 
     8 static int init_count = -1;
     9 
    10 static int user_version(void *_version, int count, char **text, char **name)
    11 {
    12     assert(_version);
    13     assert(count == 1);
    14     assert(text && text[0]);
    15     if (!(_version && count == 1 && text && text[0]))
    16         return -1;
    17 
    18     int *version = (int *) _version;
    19     *version = atoi(text[0]);
    20     return 0;
    21 }
    22 
    23 DYNAMIC_API PEP_STATUS init(PEP_SESSION *session)
    24 {
    25     PEP_STATUS status = PEP_STATUS_OK;
    26     int int_result;
    27     static const char *sql_log;
    28     static const char *sql_trustword;
    29     static const char *sql_get_identity;
    30     static const char *sql_set_person;
    31     static const char *sql_set_pgp_keypair;
    32     static const char *sql_set_identity;
    33     static const char *sql_set_identity_flags;
    34     static const char *sql_set_trust;
    35     static const char *sql_get_trust;
    36     static const char *sql_least_trust;
    37     static const char *sql_mark_as_compromized;
    38     static const char *sql_crashdump;
    39     static const char *sql_languagelist;
    40     static const char *sql_i18n_token;
    41 
    42     // blacklist
    43     static const char *sql_blacklist_add;
    44     static const char *sql_blacklist_delete;
    45     static const char *sql_blacklist_is_listed;
    46     static const char *sql_blacklist_retrieve;
    47 
    48     // Own keys
    49     static const char *sql_own_key_is_listed;
    50     static const char *sql_own_identities_retrieve;
    51 
    52     // Sequence
    53     static const char *sql_sequence_value1;
    54     static const char *sql_sequence_value2;
    55 
    56     // Revocation tracking
    57     static const char *sql_set_revoked;
    58     static const char *sql_get_revoked;
    59     
    60     bool in_first = false;
    61 
    62     assert(sqlite3_threadsafe());
    63     if (!sqlite3_threadsafe())
    64         return PEP_INIT_SQLITE3_WITHOUT_MUTEX;
    65 
    66     // a little race condition - but still a race condition
    67     // mitigated by calling caveat (see documentation)
    68 
    69     ++init_count;
    70     if (init_count == 0)
    71         in_first = true;
    72 
    73     assert(session);
    74     if (session == NULL)
    75         return PEP_ILLEGAL_VALUE;
    76 
    77     *session = NULL;
    78 
    79     pEpSession *_session = calloc(1, sizeof(pEpSession));
    80     assert(_session);
    81     if (_session == NULL)
    82         goto enomem;
    83 
    84     _session->version = PEP_ENGINE_VERSION;
    85 
    86     assert(LOCAL_DB);
    87     if (LOCAL_DB == NULL) {
    88         status = PEP_INIT_CANNOT_OPEN_DB;
    89         goto pep_error;
    90     }
    91 
    92     int_result = sqlite3_open_v2(
    93             LOCAL_DB,
    94             &_session->db,
    95             SQLITE_OPEN_READWRITE
    96                 | SQLITE_OPEN_CREATE
    97                 | SQLITE_OPEN_FULLMUTEX
    98                 | SQLITE_OPEN_PRIVATECACHE,
    99             NULL 
   100         );
   101 
   102     if (int_result != SQLITE_OK) {
   103         status = PEP_INIT_CANNOT_OPEN_DB;
   104         goto pep_error;
   105     }
   106 
   107     sqlite3_busy_timeout(_session->db, BUSY_WAIT_TIME);
   108 
   109     assert(SYSTEM_DB);
   110     if (SYSTEM_DB == NULL) {
   111         status = PEP_INIT_CANNOT_OPEN_SYSTEM_DB;
   112         goto pep_error;
   113     }
   114 
   115     int_result = sqlite3_open_v2(
   116             SYSTEM_DB, &_session->system_db,
   117             SQLITE_OPEN_READONLY
   118                 | SQLITE_OPEN_FULLMUTEX
   119                 | SQLITE_OPEN_SHAREDCACHE,
   120             NULL
   121         );
   122 
   123     if (int_result != SQLITE_OK) {
   124         status = PEP_INIT_CANNOT_OPEN_SYSTEM_DB;
   125         goto pep_error;
   126     }
   127 
   128     sqlite3_busy_timeout(_session->system_db, 1000);
   129 
   130 // increment this when patching DDL
   131 #define _DDL_USER_VERSION "2"
   132 
   133     if (in_first) {
   134         int_result = sqlite3_exec(
   135             _session->db,
   136                 "create table version_info (\n"
   137                 "   id integer primary key,\n"
   138                 "   timestamp integer default (datetime('now')) ,\n"
   139                 "   version text,\n"
   140                 "   comment text\n"
   141                 ");\n",
   142                 NULL,
   143                 NULL,
   144                 NULL
   145         );
   146         if (int_result == SQLITE_OK) {
   147             int_result = sqlite3_exec(
   148                 _session->db,
   149                 "pragma user_version = "_DDL_USER_VERSION";\n"
   150                 "insert or replace into version_info (id, version)"
   151                     "values (1, '" PEP_ENGINE_VERSION "');",
   152                 NULL,
   153                 NULL,
   154                 NULL
   155             );
   156             assert(int_result == SQLITE_OK);
   157         }
   158 
   159         int_result = sqlite3_exec(
   160             _session->db,
   161                 "PRAGMA application_id = 0x23423423;\n"
   162                 "create table if not exists log (\n"
   163                 "   timestamp integer default (datetime('now')) ,\n"
   164                 "   title text not null,\n"
   165                 "   entity text not null,\n"
   166                 "   description text,\n"
   167                 "   comment text\n"
   168                 ");\n"
   169                 "create index if not exists log_timestamp on log (\n"
   170                 "   timestamp\n"
   171                 ");\n"
   172                 "create table if not exists pgp_keypair (\n"
   173                 "   fpr text primary key,\n"
   174                 "   public_id text unique,\n"
   175                 "   private_id text,\n"
   176                 "   created integer,\n"
   177                 "   expires integer,\n"
   178                 "   comment text,\n"
   179                 "   flags integer default (0)\n"
   180                 ");\n"
   181                 "create index if not exists pgp_keypair_expires on pgp_keypair (\n"
   182                 "   expires\n"
   183                 ");\n"
   184                 "create table if not exists person (\n"
   185                 "   id text primary key,\n"
   186                 "   username text not null,\n"
   187                 "   main_key_id text\n"
   188                 "       references pgp_keypair (fpr)\n"
   189                 "       on delete set null,\n"
   190                 "   lang text,\n"
   191                 "   comment text,\n"
   192                 "   device_group text\n"
   193                 ");\n"
   194                 "create table if not exists identity (\n"
   195                 "   address text,\n"
   196                 "   user_id text\n"
   197                 "       references person (id)\n"
   198                 "       on delete cascade,\n"
   199                 "   main_key_id text\n"
   200                 "       references pgp_keypair (fpr)\n"
   201                 "       on delete set null,\n"
   202                 "   comment text,\n"
   203                 "   flags integer default (0),"
   204                 "   primary key (address, user_id)\n"
   205                 ");\n"
   206                 "create table if not exists trust (\n"
   207                 "   user_id text not null\n"
   208                 "       references person (id)\n"
   209                 "       on delete cascade,\n"
   210                 "   pgp_keypair_fpr text not null\n"
   211                 "       references pgp_keypair (fpr)\n"
   212                 "       on delete cascade,\n"
   213                 "   comm_type integer not null,\n"
   214                 "   comment text,\n"
   215                 "   primary key (user_id, pgp_keypair_fpr)\n"
   216                 ");\n"
   217                 // blacklist
   218                 "create table if not exists blacklist_keys (\n"
   219                 "   fpr text primary key\n"
   220                 ");\n"
   221                 // sequences
   222                 "create table if not exists sequences(\n"
   223                 "   name text primary key,\n"
   224                 "   value integer default 0\n"
   225                 ");\n"
   226                 "create table if not exists revoked_keys (\n"
   227                 "   revoked_fpr text primary key,\n"
   228                 "   replacement_fpr text not null\n"
   229                 "       references pgp_keypair (fpr)\n"
   230                 "       on delete cascade,\n"
   231                 "   revocation_date integer\n"
   232                 ");\n"
   233                 ,
   234             NULL,
   235             NULL,
   236             NULL
   237         );
   238         assert(int_result == SQLITE_OK);
   239 
   240         int version;
   241         int_result = sqlite3_exec(
   242             _session->db,
   243             "pragma user_version;",
   244             user_version,
   245             &version,
   246             NULL
   247         );
   248         assert(int_result == SQLITE_OK);
   249 
   250         if (version < 1) {
   251             int_result = sqlite3_exec(
   252                 _session->db,
   253                 "alter table identity\n"
   254                 "   add column flags integer default (0);\n",
   255                 NULL,
   256                 NULL,
   257                 NULL
   258             );
   259             assert(int_result == SQLITE_OK);
   260         }
   261 
   262         if (version < 2) {
   263             int_result = sqlite3_exec(
   264                 _session->db,
   265                 "alter table pgp_keypair\n"
   266                 "   add column flags integer default (0);\n"
   267                 "alter table person\n"
   268                 "   add column device_group text;\n",
   269                 NULL,
   270                 NULL,
   271                 NULL
   272             );
   273             assert(int_result == SQLITE_OK);
   274         }
   275 
   276         if (version < atoi(_DDL_USER_VERSION)) {
   277             int_result = sqlite3_exec(
   278                 _session->db,
   279                 "pragma user_version = "_DDL_USER_VERSION";\n"
   280                 "insert or replace into version_info (id, version)"
   281                     "values (1, '" PEP_ENGINE_VERSION "');",
   282                 NULL,
   283                 NULL,
   284                 NULL
   285             );
   286             assert(int_result == SQLITE_OK);
   287         }
   288 
   289         sql_log = "insert into log (title, entity, description, comment)"
   290                   "values (?1, ?2, ?3, ?4);";
   291 
   292         sql_get_identity =  "select fpr, username, comm_type, lang,"
   293                             "   identity.flags | pgp_keypair.flags"
   294                             "   from identity"
   295                             "   join person on id = identity.user_id"
   296                             "   join pgp_keypair on fpr = identity.main_key_id"
   297                             "   join trust on id = trust.user_id"
   298                             "       and pgp_keypair_fpr = identity.main_key_id"
   299                             "   where address = ?1 and identity.user_id = ?2;";
   300 
   301         sql_trustword = "select id, word from wordlist where lang = lower(?1) "
   302                        "and id = ?2 ;";
   303 
   304         // Set person, but if already exist, only update.
   305         // if main_key_id already set, don't touch.
   306         sql_set_person = "insert or replace into person (id, username, lang, main_key_id)"
   307                          "  values (?1, ?2, ?3,"
   308                          "    (select coalesce((select main_key_id from person "
   309                          "      where id = ?1), upper(replace(?4,' ',''))))) ;";
   310 
   311         sql_set_pgp_keypair = "insert or replace into pgp_keypair (fpr) "
   312                               "values (upper(replace(?1,' ',''))) ;";
   313 
   314         sql_set_identity = "insert or replace into identity (address, main_key_id, "
   315                            "user_id, flags) values (?1, upper(replace(?2,' ','')),"
   316                            "?3, ?4 & 255) ;";
   317 
   318         sql_set_identity_flags = "update identity set flags = ?1 & 255 "
   319                                  "where address = ?2 and user_id = ?3 ;";
   320 
   321         sql_set_trust = "insert or replace into trust (user_id, pgp_keypair_fpr, comm_type) "
   322                         "values (?1, upper(replace(?2,' ','')), ?3) ;";
   323 
   324         sql_get_trust = "select comm_type from trust where user_id = ?1 "
   325                         "and pgp_keypair_fpr = upper(replace(?2,' ','')) ;";
   326 
   327         sql_least_trust = "select min(comm_type) from trust where pgp_keypair_fpr = upper(replace(?1,' ','')) ;";
   328 
   329         sql_mark_as_compromized = "update trust not indexed set comm_type = 15"
   330                                   " where pgp_keypair_fpr = upper(replace(?1,' ','')) ;";
   331 
   332         sql_crashdump = "select timestamp, title, entity, description, comment"
   333                         " from log order by timestamp desc limit ?1 ;";
   334 
   335         sql_languagelist = "select i18n_language.lang, name, phrase from i18n_language join i18n_token using (lang) where i18n_token.id = 1000;" ;
   336 
   337         sql_i18n_token = "select phrase from i18n_token where lang = lower(?1) and id = ?2 ;";
   338 
   339         // blacklist
   340 
   341         sql_blacklist_add = "insert or replace into blacklist_keys (fpr) values (upper(replace(?1,' ',''))) ;"
   342                             "delete from identity where main_key_id = upper(replace(?1,' ','')) ;"
   343                             "delete from pgp_keypair where fpr = upper(replace(?1,' ','')) ;";
   344 
   345         sql_blacklist_delete = "delete from blacklist_keys where fpr = upper(replace(?1,' ','')) ;";
   346 
   347         sql_blacklist_is_listed = "select count(*) from blacklist_keys where fpr = upper(replace(?1,' ','')) ;";
   348 
   349         sql_blacklist_retrieve = "select * from blacklist_keys ;";
   350         
   351         // Own keys
   352         
   353         sql_own_key_is_listed =
   354                                 "select count(*) from ("
   355                                 " select main_key_id from person "
   356                                 "   where main_key_id = upper(replace(?1,' ',''))"
   357                                 "    and id = '" PEP_OWN_USERID "' "
   358                                 " union "
   359                                 "  select main_key_id from identity "
   360                                 "   where main_key_id = upper(replace(?1,' ',''))"
   361                                 "    and user_id = '" PEP_OWN_USERID "' );";
   362 
   363         sql_own_identities_retrieve =  "select address, fpr, username, '" PEP_OWN_USERID "',"
   364                             "   comm_type, lang, identity.flags | pgp_keypair.flags"
   365                             "   from identity"
   366                             "   join person on id = identity.user_id"
   367                             "   join pgp_keypair on fpr = identity.main_key_id"
   368                             "   join trust on id = trust.user_id"
   369                             "       and pgp_keypair_fpr = identity.main_key_id"
   370                             "   where identity.user_id = '" PEP_OWN_USERID "';";
   371         
   372         sql_sequence_value1 = "insert or replace into sequences (name, value) "
   373                               "values (?1, "
   374                               "(select coalesce((select value + 1 from sequences "
   375                               "where name = ?1), 1 ))) ; ";
   376         sql_sequence_value2 = "select value from sequences where name = ?1 ;";
   377         
   378         sql_set_revoked =     "insert or replace into revoked_keys ("
   379                               "    revoked_fpr, replacement_fpr, revocation_date) "
   380                               "values (upper(replace(?1,' ','')),"
   381                               "        upper(replace(?2,' ','')),"
   382                               "        ?3) ;";
   383         
   384         sql_get_revoked =     "select revoked_fpr, revocation_date from revoked_keys"
   385                               "    where replacement_fpr = upper(replace(?1,' ','')) ;";
   386     }
   387 
   388     int_result = sqlite3_prepare_v2(_session->db, sql_log,
   389             (int)strlen(sql_log), &_session->log, NULL);
   390     assert(int_result == SQLITE_OK);
   391 
   392     int_result = sqlite3_prepare_v2(_session->system_db, sql_trustword,
   393             (int)strlen(sql_trustword), &_session->trustword, NULL);
   394     assert(int_result == SQLITE_OK);
   395 
   396     int_result = sqlite3_prepare_v2(_session->db, sql_get_identity,
   397             (int)strlen(sql_get_identity), &_session->get_identity, NULL);
   398     assert(int_result == SQLITE_OK);
   399 
   400     int_result = sqlite3_prepare_v2(_session->db, sql_set_person,
   401             (int)strlen(sql_set_person), &_session->set_person, NULL);
   402     assert(int_result == SQLITE_OK);
   403 
   404     int_result = sqlite3_prepare_v2(_session->db, sql_set_pgp_keypair,
   405             (int)strlen(sql_set_pgp_keypair), &_session->set_pgp_keypair,
   406             NULL);
   407     assert(int_result == SQLITE_OK);
   408 
   409     int_result = sqlite3_prepare_v2(_session->db, sql_set_identity,
   410             (int)strlen(sql_set_identity), &_session->set_identity, NULL);
   411     assert(int_result == SQLITE_OK);
   412 
   413     int_result = sqlite3_prepare_v2(_session->db, sql_set_identity_flags,
   414             (int)strlen(sql_set_identity_flags), &_session->set_identity_flags,
   415             NULL);
   416     assert(int_result == SQLITE_OK);
   417 
   418     int_result = sqlite3_prepare_v2(_session->db, sql_set_trust,
   419             (int)strlen(sql_set_trust), &_session->set_trust, NULL);
   420     assert(int_result == SQLITE_OK);
   421 
   422     int_result = sqlite3_prepare_v2(_session->db, sql_get_trust,
   423             (int)strlen(sql_get_trust), &_session->get_trust, NULL);
   424     assert(int_result == SQLITE_OK);
   425 
   426     int_result = sqlite3_prepare_v2(_session->db, sql_least_trust,
   427             (int)strlen(sql_least_trust), &_session->least_trust, NULL);
   428     assert(int_result == SQLITE_OK);
   429 
   430     int_result = sqlite3_prepare_v2(_session->db, sql_mark_as_compromized,
   431             (int)strlen(sql_mark_as_compromized), &_session->mark_compromized,
   432             NULL);
   433     assert(int_result == SQLITE_OK);
   434 
   435     int_result = sqlite3_prepare_v2(_session->db, sql_crashdump,
   436             (int)strlen(sql_crashdump), &_session->crashdump, NULL);
   437     assert(int_result == SQLITE_OK);
   438 
   439     int_result = sqlite3_prepare_v2(_session->system_db, sql_languagelist,
   440             (int)strlen(sql_languagelist), &_session->languagelist, NULL);
   441     assert(int_result == SQLITE_OK);
   442 
   443     int_result = sqlite3_prepare_v2(_session->system_db, sql_i18n_token,
   444             (int)strlen(sql_i18n_token), &_session->i18n_token, NULL);
   445     assert(int_result == SQLITE_OK);
   446 
   447     // blacklist
   448 
   449     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_add,
   450             (int)strlen(sql_blacklist_add), &_session->blacklist_add, NULL);
   451     assert(int_result == SQLITE_OK);
   452 
   453     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_delete,
   454             (int)strlen(sql_blacklist_delete), &_session->blacklist_delete,
   455             NULL);
   456     assert(int_result == SQLITE_OK);
   457 
   458     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_is_listed,
   459             (int)strlen(sql_blacklist_is_listed),
   460             &_session->blacklist_is_listed, NULL);
   461     assert(int_result == SQLITE_OK);
   462 
   463     int_result = sqlite3_prepare_v2(_session->db, sql_blacklist_retrieve,
   464             (int)strlen(sql_blacklist_retrieve), &_session->blacklist_retrieve,
   465             NULL);
   466     assert(int_result == SQLITE_OK);
   467 
   468     // Own keys
   469     
   470     int_result = sqlite3_prepare_v2(_session->db, sql_own_key_is_listed,
   471             (int)strlen(sql_own_key_is_listed), &_session->own_key_is_listed,
   472             NULL);
   473     assert(int_result == SQLITE_OK);
   474     
   475     int_result = sqlite3_prepare_v2(_session->db, sql_own_identities_retrieve,
   476             (int)strlen(sql_own_identities_retrieve),
   477             &_session->own_identities_retrieve, NULL);
   478     assert(int_result == SQLITE_OK);
   479  
   480     // Sequence
   481 
   482     int_result = sqlite3_prepare_v2(_session->db, sql_sequence_value1,
   483             (int)strlen(sql_sequence_value1), &_session->sequence_value1,
   484             NULL);
   485     assert(int_result == SQLITE_OK);
   486 
   487     int_result = sqlite3_prepare_v2(_session->db, sql_sequence_value2,
   488             (int)strlen(sql_sequence_value2), &_session->sequence_value2,
   489             NULL);
   490     assert(int_result == SQLITE_OK);
   491 
   492     // Revocation tracking
   493     
   494     int_result = sqlite3_prepare_v2(_session->db, sql_set_revoked,
   495             (int)strlen(sql_set_revoked), &_session->set_revoked, NULL);
   496     assert(int_result == SQLITE_OK);
   497     
   498     int_result = sqlite3_prepare_v2(_session->db, sql_get_revoked,
   499             (int)strlen(sql_get_revoked), &_session->get_revoked, NULL);
   500     assert(int_result == SQLITE_OK);
   501     
   502     status = init_cryptotech(_session, in_first);
   503     if (status != PEP_STATUS_OK)
   504         goto pep_error;
   505 
   506     status = init_transport_system(_session, in_first);
   507     if (status != PEP_STATUS_OK)
   508         goto pep_error;
   509 
   510     status = log_event(_session, "init", "pEp " PEP_ENGINE_VERSION, NULL, NULL);
   511     if (status != PEP_STATUS_OK)
   512         goto pep_error;
   513 
   514     // runtime config
   515 
   516     _session->passive_mode = false;
   517     _session->unencrypted_subject = false;
   518 #ifdef ANDROID
   519     _session->use_only_own_private_keys = true;
   520 #elif TARGET_OS_IPHONE
   521     _session->use_only_own_private_keys = true;
   522 #else
   523     _session->use_only_own_private_keys = false;
   524 #endif
   525 
   526     *session = _session;
   527     return PEP_STATUS_OK;
   528 
   529 enomem:
   530     status = PEP_OUT_OF_MEMORY;
   531 
   532 pep_error:
   533     release(_session);
   534     return status;
   535 }
   536 
   537 DYNAMIC_API void release(PEP_SESSION session)
   538 {
   539     bool out_last = false;
   540 
   541     assert(init_count >= 0);
   542     assert(session);
   543 
   544     if (!((init_count >= 0) && session))
   545         return;
   546 
   547     // a small race condition but still a race condition
   548     // mitigated by calling caveat (see documentation)
   549 
   550     if (init_count == 0)
   551         out_last = true;
   552     --init_count;
   553 
   554     if (session) {
   555         if (session->db) {
   556             if (session->log)
   557                 sqlite3_finalize(session->log);
   558             if (session->trustword)
   559                 sqlite3_finalize(session->trustword);
   560             if (session->get_identity)
   561                 sqlite3_finalize(session->get_identity);
   562             if (session->set_person)
   563                 sqlite3_finalize(session->set_person);
   564             if (session->set_pgp_keypair)
   565                 sqlite3_finalize(session->set_pgp_keypair);
   566             if (session->set_identity)
   567                 sqlite3_finalize(session->set_identity);
   568             if (session->set_identity_flags)
   569                 sqlite3_finalize(session->set_identity_flags);
   570             if (session->set_trust)
   571                 sqlite3_finalize(session->set_trust);
   572             if (session->get_trust)
   573                 sqlite3_finalize(session->get_trust);
   574             if (session->least_trust)
   575                 sqlite3_finalize(session->least_trust);
   576             if (session->mark_compromized)
   577                 sqlite3_finalize(session->mark_compromized);
   578             if (session->crashdump)
   579                 sqlite3_finalize(session->crashdump);
   580             if (session->languagelist)
   581                 sqlite3_finalize(session->languagelist);
   582             if (session->i18n_token)
   583                 sqlite3_finalize(session->i18n_token);
   584             if (session->blacklist_add)
   585                 sqlite3_finalize(session->blacklist_add);
   586             if (session->blacklist_delete)
   587                 sqlite3_finalize(session->blacklist_delete);
   588             if (session->blacklist_is_listed)
   589                 sqlite3_finalize(session->blacklist_is_listed);
   590             if (session->blacklist_retrieve)
   591                 sqlite3_finalize(session->blacklist_retrieve);
   592 
   593             if (session->db)
   594                 sqlite3_close_v2(session->db);
   595             if (session->system_db)
   596                 sqlite3_close_v2(session->system_db);
   597         }
   598 
   599         release_transport_system(session, out_last);
   600         release_cryptotech(session, out_last);
   601 
   602         free(session);
   603     }
   604 }
   605 
   606 DYNAMIC_API void config_passive_mode(PEP_SESSION session, bool enable)
   607 {
   608     assert(session);
   609     session->passive_mode = enable;
   610 }
   611 
   612 DYNAMIC_API void config_unencrypted_subject(PEP_SESSION session, bool enable)
   613 {
   614     assert(session);
   615     session->unencrypted_subject = enable;
   616 }
   617 
   618 DYNAMIC_API void config_use_only_own_private_keys(PEP_SESSION session,
   619         bool enable)
   620 {
   621     assert(session);
   622     session->use_only_own_private_keys = enable;
   623 }
   624 
   625 DYNAMIC_API PEP_STATUS log_event(
   626         PEP_SESSION session,
   627         const char *title,
   628         const char *entity,
   629         const char *description,
   630         const char *comment
   631     )
   632 {
   633     PEP_STATUS status = PEP_STATUS_OK;
   634     int result;
   635 
   636     assert(session);
   637     assert(title);
   638     assert(entity);
   639 
   640     if (!(session && title && entity))
   641         return PEP_ILLEGAL_VALUE;
   642 
   643     sqlite3_reset(session->log);
   644     sqlite3_bind_text(session->log, 1, title, -1, SQLITE_STATIC);
   645     sqlite3_bind_text(session->log, 2, entity, -1, SQLITE_STATIC);
   646     if (description)
   647         sqlite3_bind_text(session->log, 3, description, -1, SQLITE_STATIC);
   648     else
   649         sqlite3_bind_null(session->log, 3);
   650     if (comment)
   651         sqlite3_bind_text(session->log, 4, comment, -1, SQLITE_STATIC);
   652     else
   653         sqlite3_bind_null(session->log, 4);
   654     do {
   655         result = sqlite3_step(session->log);
   656         assert(result == SQLITE_DONE || result == SQLITE_BUSY);
   657         if (result != SQLITE_DONE && result != SQLITE_BUSY)
   658             status = PEP_UNKNOWN_ERROR;
   659     } while (result == SQLITE_BUSY);
   660     sqlite3_reset(session->log);
   661 
   662     return status;
   663 }
   664 
   665 DYNAMIC_API PEP_STATUS trustword(
   666             PEP_SESSION session, uint16_t value, const char *lang,
   667             char **word, size_t *wsize
   668         )
   669 {
   670     PEP_STATUS status = PEP_STATUS_OK;
   671 
   672     assert(session);
   673     assert(word);
   674     assert(wsize);
   675 
   676     if (!(session && word && wsize))
   677         return PEP_ILLEGAL_VALUE;
   678 
   679     *word = NULL;
   680     *wsize = 0;
   681 
   682     if (lang == NULL)
   683         lang = "en";
   684 
   685     assert((lang[0] >= 'A' && lang[0] <= 'Z')
   686             || (lang[0] >= 'a' && lang[0] <= 'z'));
   687     assert((lang[1] >= 'A' && lang[1] <= 'Z')
   688             || (lang[1] >= 'a' && lang[1] <= 'z'));
   689     assert(lang[2] == 0);
   690 
   691     sqlite3_reset(session->trustword);
   692     sqlite3_bind_text(session->trustword, 1, lang, -1, SQLITE_STATIC);
   693     sqlite3_bind_int(session->trustword, 2, value);
   694 
   695     const int result = sqlite3_step(session->trustword);
   696     if (result == SQLITE_ROW) {
   697         *word = strdup((const char *) sqlite3_column_text(session->trustword,
   698                     1));
   699         if (*word)
   700             *wsize = sqlite3_column_bytes(session->trustword, 1);
   701         else
   702             status = PEP_OUT_OF_MEMORY;
   703     } else
   704         status = PEP_TRUSTWORD_NOT_FOUND;
   705 
   706     sqlite3_reset(session->trustword);
   707     return status;
   708 }
   709 
   710 DYNAMIC_API PEP_STATUS trustwords(
   711         PEP_SESSION session, const char *fingerprint, const char *lang,
   712         char **words, size_t *wsize, int max_words
   713     )
   714 {
   715     const char *source = fingerprint;
   716     char *buffer;
   717     char *dest;
   718     size_t fsize;
   719 
   720     assert(session);
   721     assert(fingerprint);
   722     assert(words);
   723     assert(wsize);
   724     assert(max_words >= 0);
   725 
   726     if (!(session && fingerprint && words && wsize && max_words >= 0))
   727         return PEP_ILLEGAL_VALUE;
   728 
   729     *words = NULL;
   730     *wsize = 0;
   731 
   732     buffer = calloc(1, MAX_TRUSTWORDS_SPACE);
   733     assert(buffer);
   734     if (buffer == NULL)
   735         return PEP_OUT_OF_MEMORY;
   736     dest = buffer;
   737 
   738     fsize = strlen(fingerprint);
   739 
   740     if (!lang || !lang[0])
   741         lang = "en";
   742 
   743     assert((lang[0] >= 'A' && lang[0] <= 'Z')
   744             || (lang[0] >= 'a' && lang[0] <= 'z'));
   745     assert((lang[1] >= 'A' && lang[1] <= 'Z')
   746             || (lang[1] >= 'a' && lang[1] <= 'z'));
   747     assert(lang[2] == 0);
   748 
   749     int n_words = 0;
   750     while (source < fingerprint + fsize) {
   751         PEP_STATUS _status;
   752         uint16_t value;
   753         char *word;
   754         size_t _wsize;
   755         int j;
   756 
   757         for (value=0, j=0; j < 4 && source < fingerprint + fsize; ) {
   758             if (*source >= 'a' && *source <= 'f')
   759                 value += (*source - 'a' + 10) << (3 - j++) * 4;
   760             else if (*source >= 'A' && *source <= 'F')
   761                 value += (*source - 'A' + 10) << (3 - j++) * 4;
   762             else if (*source >= '0' && *source <= '9')
   763                 value += (*source - '0') << (3 - j++) * 4;
   764             
   765             source++;
   766         }
   767 
   768         _status = trustword(session, value, lang, &word, &_wsize);
   769         if (_status == PEP_OUT_OF_MEMORY) {
   770             free(buffer);
   771             return PEP_OUT_OF_MEMORY;
   772         }
   773         if (word == NULL) {
   774             free(buffer);
   775             return PEP_TRUSTWORD_NOT_FOUND;
   776         }
   777 
   778         if (dest + _wsize < buffer + MAX_TRUSTWORDS_SPACE - 1) {
   779             strncpy(dest, word, _wsize);
   780             free(word);
   781             dest += _wsize;
   782         }
   783         else {
   784             free(word);
   785             break; // buffer full
   786         }
   787 
   788         if (source < fingerprint + fsize
   789                 && dest + _wsize < buffer + MAX_TRUSTWORDS_SPACE - 1)
   790             *dest++ = ' ';
   791 
   792         ++n_words;
   793         if (max_words && n_words >= max_words)
   794             break;
   795     }
   796 
   797     *words = buffer;
   798     *wsize = dest - buffer;
   799     return PEP_STATUS_OK;
   800 }
   801 
   802 pEp_identity *new_identity(
   803         const char *address, const char *fpr, const char *user_id,
   804         const char *username
   805     )
   806 {
   807     pEp_identity *result = calloc(1, sizeof(pEp_identity));
   808     assert(result);
   809     if (result) {
   810         if (address) {
   811             result->address = strdup(address);
   812             assert(result->address);
   813             if (result->address == NULL) {
   814                 free(result);
   815                 return NULL;
   816             }
   817         }
   818         if (fpr) {
   819             result->fpr = strdup(fpr);
   820             assert(result->fpr);
   821             if (result->fpr == NULL) {
   822                 free_identity(result);
   823                 return NULL;
   824             }
   825         }
   826         if (user_id) {
   827             result->user_id = strdup(user_id);
   828             assert(result->user_id);
   829             if (result->user_id == NULL) {
   830                 free_identity(result);
   831                 return NULL;
   832             }
   833         }
   834         if (username) {
   835             result->username = strdup(username);
   836             assert(result->username);
   837             if (result->username == NULL) {
   838                 free_identity(result);
   839                 return NULL;
   840             }
   841         }
   842     }
   843     return result;
   844 }
   845 
   846 pEp_identity *identity_dup(const pEp_identity *src)
   847 {
   848     assert(src);
   849 
   850     pEp_identity *dup = new_identity(src->address, src->fpr, src->user_id,
   851             src->username);
   852     assert(dup);
   853     if (dup == NULL)
   854         return NULL;
   855     
   856     dup->comm_type = src->comm_type;
   857     dup->lang[0] = src->lang[0];
   858     dup->lang[1] = src->lang[1];
   859     dup->lang[2] = 0;
   860     dup->me = src->me;
   861     dup->flags = src->flags;
   862 
   863     return dup;
   864 }
   865 
   866 void free_identity(pEp_identity *identity)
   867 {
   868     if (identity) {
   869         free(identity->address);
   870         free(identity->fpr);
   871         free(identity->user_id);
   872         free(identity->username);
   873         free(identity);
   874     }
   875 }
   876 
   877 DYNAMIC_API PEP_STATUS get_identity(
   878         PEP_SESSION session,
   879         const char *address,
   880         const char *user_id,
   881         pEp_identity **identity
   882     )
   883 {
   884     PEP_STATUS status = PEP_STATUS_OK;
   885     static pEp_identity *_identity;
   886 
   887     assert(session);
   888     assert(address);
   889     assert(address[0]);
   890     assert(identity);
   891 
   892     if (!(session && address && address[0] && identity))
   893         return PEP_ILLEGAL_VALUE;
   894 
   895     *identity = NULL;
   896 
   897     sqlite3_reset(session->get_identity);
   898     sqlite3_bind_text(session->get_identity, 1, address, -1, SQLITE_STATIC);
   899     sqlite3_bind_text(session->get_identity, 2, user_id, -1, SQLITE_STATIC);
   900 
   901     const int result = sqlite3_step(session->get_identity);
   902     switch (result) {
   903     case SQLITE_ROW:
   904         _identity = new_identity(
   905                 address,
   906                 (const char *) sqlite3_column_text(session->get_identity, 0),
   907                 user_id,
   908                 (const char *) sqlite3_column_text(session->get_identity, 1)
   909                 );
   910         assert(_identity);
   911         if (_identity == NULL)
   912             return PEP_OUT_OF_MEMORY;
   913 
   914         _identity->comm_type = (PEP_comm_type)
   915             sqlite3_column_int(session->get_identity, 2);
   916         const char* const _lang = (const char *)
   917             sqlite3_column_text(session->get_identity, 3);
   918         if (_lang && _lang[0]) {
   919             assert(_lang[0] >= 'a' && _lang[0] <= 'z');
   920             assert(_lang[1] >= 'a' && _lang[1] <= 'z');
   921             assert(_lang[2] == 0);
   922             _identity->lang[0] = _lang[0];
   923             _identity->lang[1] = _lang[1];
   924             _identity->lang[2] = 0;
   925         }
   926         _identity->flags = (unsigned int)
   927             sqlite3_column_int(session->get_identity, 4);
   928         *identity = _identity;
   929         break;
   930     default:
   931         status = PEP_CANNOT_FIND_IDENTITY;
   932         *identity = NULL;
   933     }
   934 
   935     sqlite3_reset(session->get_identity);
   936     return status;
   937 }
   938 
   939 DYNAMIC_API PEP_STATUS set_identity(
   940         PEP_SESSION session, const pEp_identity *identity
   941     )
   942 {
   943     int result;
   944 
   945     assert(session);
   946     assert(identity);
   947     assert(identity->address);
   948     assert(identity->fpr);
   949     assert(identity->user_id);
   950     assert(identity->username);
   951 
   952     if (!(session && identity && identity->address && identity->fpr &&
   953                 identity->user_id && identity->username))
   954         return PEP_ILLEGAL_VALUE;
   955 
   956     bool listed;
   957     PEP_STATUS status = blacklist_is_listed(session, identity->fpr, &listed);
   958     assert(status == PEP_STATUS_OK);
   959     if (status != PEP_STATUS_OK)
   960         return status;
   961 
   962     if (listed)
   963         return PEP_KEY_BLACKLISTED;
   964 
   965     sqlite3_exec(session->db, "BEGIN ;", NULL, NULL, NULL);
   966 
   967     sqlite3_reset(session->set_person);
   968     sqlite3_bind_text(session->set_person, 1, identity->user_id, -1,
   969             SQLITE_STATIC);
   970     sqlite3_bind_text(session->set_person, 2, identity->username, -1,
   971             SQLITE_STATIC);
   972     if (identity->lang[0])
   973         sqlite3_bind_text(session->set_person, 3, identity->lang, 1,
   974                 SQLITE_STATIC);
   975     else
   976         sqlite3_bind_null(session->set_person, 3);
   977     sqlite3_bind_text(session->set_person, 4, identity->fpr, -1,
   978                       SQLITE_STATIC);
   979     result = sqlite3_step(session->set_person);
   980     sqlite3_reset(session->set_person);
   981     if (result != SQLITE_DONE) {
   982         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
   983         return PEP_CANNOT_SET_PERSON;
   984     }
   985 
   986     sqlite3_reset(session->set_pgp_keypair);
   987     sqlite3_bind_text(session->set_pgp_keypair, 1, identity->fpr, -1,
   988             SQLITE_STATIC);
   989     result = sqlite3_step(session->set_pgp_keypair);
   990     sqlite3_reset(session->set_pgp_keypair);
   991     if (result != SQLITE_DONE) {
   992         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
   993         return PEP_CANNOT_SET_PGP_KEYPAIR;
   994     }
   995 
   996     sqlite3_reset(session->set_identity);
   997     sqlite3_bind_text(session->set_identity, 1, identity->address, -1,
   998             SQLITE_STATIC);
   999     sqlite3_bind_text(session->set_identity, 2, identity->fpr, -1,
  1000             SQLITE_STATIC);
  1001     sqlite3_bind_text(session->set_identity, 3, identity->user_id, -1,
  1002             SQLITE_STATIC);
  1003     sqlite3_bind_int(session->set_identity, 4, identity->flags);
  1004     result = sqlite3_step(session->set_identity);
  1005     sqlite3_reset(session->set_identity);
  1006     if (result != SQLITE_DONE) {
  1007         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1008         return PEP_CANNOT_SET_IDENTITY;
  1009     }
  1010 
  1011     sqlite3_reset(session->set_trust);
  1012     sqlite3_bind_text(session->set_trust, 1, identity->user_id, -1,
  1013             SQLITE_STATIC);
  1014     sqlite3_bind_text(session->set_trust, 2, identity->fpr, -1,
  1015             SQLITE_STATIC);
  1016     sqlite3_bind_int(session->set_trust, 3, identity->comm_type);
  1017     result = sqlite3_step(session->set_trust);
  1018     sqlite3_reset(session->set_trust);
  1019     if (result != SQLITE_DONE) {
  1020         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1021         return PEP_CANNOT_SET_TRUST;
  1022     }
  1023 
  1024     result = sqlite3_exec(session->db, "COMMIT ;", NULL, NULL, NULL);
  1025     if (result == SQLITE_OK)
  1026         return PEP_STATUS_OK;
  1027     else
  1028         return PEP_COMMIT_FAILED;
  1029 }
  1030 
  1031 DYNAMIC_API PEP_STATUS set_identity_flags(
  1032         PEP_SESSION session,
  1033         pEp_identity *identity,
  1034         unsigned int flags
  1035     )
  1036 {
  1037     int result;
  1038 
  1039     assert(session);
  1040     assert(identity);
  1041     assert(identity->address);
  1042     assert(identity->user_id);
  1043 
  1044     if (!(session && identity && identity->address && identity->user_id))
  1045         return PEP_ILLEGAL_VALUE;
  1046 
  1047     sqlite3_reset(session->set_identity_flags);
  1048     sqlite3_bind_int(session->set_identity_flags, 1, flags);
  1049     sqlite3_bind_text(session->set_identity_flags, 2, identity->address, -1,
  1050             SQLITE_STATIC);
  1051     sqlite3_bind_text(session->set_identity_flags, 3, identity->user_id, -1,
  1052             SQLITE_STATIC);
  1053     result = sqlite3_step(session->set_identity_flags);
  1054     sqlite3_reset(session->set_identity_flags);
  1055     if (result != SQLITE_DONE)
  1056         return PEP_CANNOT_SET_IDENTITY;
  1057 
  1058     identity->flags = flags;
  1059     return PEP_STATUS_OK;
  1060 }
  1061 
  1062 DYNAMIC_API PEP_STATUS mark_as_compromized(
  1063         PEP_SESSION session,
  1064         const char *fpr
  1065     )
  1066 {
  1067     int result;
  1068 
  1069     assert(session);
  1070     assert(fpr && fpr[0]);
  1071 
  1072     if (!(session && fpr && fpr[0]))
  1073         return PEP_ILLEGAL_VALUE;
  1074 
  1075     sqlite3_reset(session->mark_compromized);
  1076     sqlite3_bind_text(session->mark_compromized, 1, fpr, -1,
  1077             SQLITE_STATIC);
  1078     result = sqlite3_step(session->mark_compromized);
  1079     sqlite3_reset(session->mark_compromized);
  1080 
  1081     if (result != SQLITE_DONE)
  1082         return PEP_CANNOT_SET_TRUST;
  1083 
  1084     return PEP_STATUS_OK;
  1085 }
  1086 
  1087 void pEp_free(void *p)
  1088 {
  1089     free(p);
  1090 }
  1091 
  1092 DYNAMIC_API PEP_STATUS get_trust(PEP_SESSION session, pEp_identity *identity)
  1093 {
  1094     PEP_STATUS status = PEP_STATUS_OK;
  1095     int result;
  1096 
  1097     assert(session);
  1098     assert(identity);
  1099     assert(identity->user_id);
  1100     assert(identity->user_id[0]);
  1101     assert(identity->fpr);
  1102     assert(identity->fpr[0]);
  1103 
  1104     if (!(session && identity && identity->user_id && identity->user_id[0] &&
  1105                 identity->fpr && identity->fpr[0]))
  1106         return PEP_ILLEGAL_VALUE;
  1107 
  1108     identity->comm_type = PEP_ct_unknown;
  1109 
  1110     sqlite3_reset(session->get_trust);
  1111     sqlite3_bind_text(session->get_trust, 1, identity->user_id, -1,
  1112             SQLITE_STATIC);
  1113     sqlite3_bind_text(session->get_trust, 2, identity->fpr, -1, SQLITE_STATIC);
  1114 
  1115     result = sqlite3_step(session->get_trust);
  1116     switch (result) {
  1117     case SQLITE_ROW: {
  1118         int comm_type = (PEP_comm_type) sqlite3_column_int(session->get_trust,
  1119                 0);
  1120         identity->comm_type = comm_type;
  1121         break;
  1122     }
  1123  
  1124     default:
  1125         status = PEP_CANNOT_FIND_IDENTITY;
  1126     }
  1127 
  1128     sqlite3_reset(session->get_trust);
  1129     return status;
  1130 }
  1131 
  1132 DYNAMIC_API PEP_STATUS least_trust(
  1133         PEP_SESSION session,
  1134         const char *fpr,
  1135         PEP_comm_type *comm_type
  1136     )
  1137 {
  1138     PEP_STATUS status = PEP_STATUS_OK;
  1139     int result;
  1140 
  1141     assert(session);
  1142     assert(fpr);
  1143     assert(comm_type);
  1144 
  1145     if (!(session && fpr && comm_type))
  1146         return PEP_ILLEGAL_VALUE;
  1147 
  1148     *comm_type = PEP_ct_unknown;
  1149 
  1150     sqlite3_reset(session->least_trust);
  1151     sqlite3_bind_text(session->least_trust, 1, fpr, -1, SQLITE_STATIC);
  1152 
  1153     result = sqlite3_step(session->least_trust);
  1154     switch (result) {
  1155         case SQLITE_ROW: {
  1156             int _comm_type = sqlite3_column_int(session->least_trust, 0);
  1157             *comm_type = (PEP_comm_type) _comm_type;
  1158             break;
  1159         }
  1160         default:
  1161             status = PEP_CANNOT_FIND_IDENTITY;
  1162     }
  1163 
  1164     sqlite3_reset(session->least_trust);
  1165     return status;
  1166 }
  1167 
  1168 DYNAMIC_API PEP_STATUS decrypt_and_verify(
  1169     PEP_SESSION session, const char *ctext, size_t csize,
  1170     char **ptext, size_t *psize, stringlist_t **keylist
  1171     )
  1172 {
  1173     assert(session);
  1174     assert(ctext);
  1175     assert(csize);
  1176     assert(ptext);
  1177     assert(psize);
  1178     assert(keylist);
  1179 
  1180     if (!(session && ctext && csize && ptext && psize && keylist))
  1181         return PEP_ILLEGAL_VALUE;
  1182 
  1183     return session->cryptotech[PEP_crypt_OpenPGP].decrypt_and_verify(
  1184             session, ctext, csize, ptext, psize, keylist);
  1185 }
  1186 
  1187 DYNAMIC_API PEP_STATUS encrypt_and_sign(
  1188     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1189     size_t psize, char **ctext, size_t *csize
  1190     )
  1191 {
  1192     assert(session);
  1193     assert(keylist);
  1194     assert(ptext);
  1195     assert(psize);
  1196     assert(ctext);
  1197     assert(csize);
  1198 
  1199     if (!(session && keylist && ptext && psize && ctext && csize))
  1200         return PEP_ILLEGAL_VALUE;
  1201 
  1202     return session->cryptotech[PEP_crypt_OpenPGP].encrypt_and_sign(session,
  1203             keylist, ptext, psize, ctext, csize);
  1204 }
  1205 
  1206 DYNAMIC_API PEP_STATUS verify_text(
  1207     PEP_SESSION session, const char *text, size_t size,
  1208     const char *signature, size_t sig_size, stringlist_t **keylist
  1209     )
  1210 {
  1211     assert(session);
  1212     assert(text);
  1213     assert(size);
  1214     assert(signature);
  1215     assert(sig_size);
  1216     assert(keylist);
  1217 
  1218     if (!(session && text && size && signature && sig_size && keylist))
  1219         return PEP_ILLEGAL_VALUE;
  1220 
  1221     return session->cryptotech[PEP_crypt_OpenPGP].verify_text(session, text,
  1222             size, signature, sig_size, keylist);
  1223 }
  1224 
  1225 DYNAMIC_API PEP_STATUS delete_keypair(PEP_SESSION session, const char *fpr)
  1226 {
  1227     assert(session);
  1228     assert(fpr);
  1229 
  1230     if (!(session && fpr))
  1231         return PEP_ILLEGAL_VALUE;
  1232 
  1233     return session->cryptotech[PEP_crypt_OpenPGP].delete_keypair(session, fpr);
  1234 }
  1235 
  1236 DYNAMIC_API PEP_STATUS export_key(
  1237         PEP_SESSION session, const char *fpr, char **key_data, size_t *size
  1238     )
  1239 {
  1240     assert(session);
  1241     assert(fpr);
  1242     assert(key_data);
  1243     assert(size);
  1244 
  1245     if (!(session && fpr && key_data && size))
  1246         return PEP_ILLEGAL_VALUE;
  1247 
  1248     return session->cryptotech[PEP_crypt_OpenPGP].export_key(session, fpr,
  1249             key_data, size);
  1250 }
  1251 
  1252 DYNAMIC_API PEP_STATUS find_keys(
  1253         PEP_SESSION session, const char *pattern, stringlist_t **keylist
  1254     )
  1255 {
  1256     assert(session);
  1257     assert(pattern);
  1258     assert(keylist);
  1259 
  1260     if (!(session && pattern && keylist))
  1261         return PEP_ILLEGAL_VALUE;
  1262 
  1263     return session->cryptotech[PEP_crypt_OpenPGP].find_keys(session, pattern,
  1264             keylist);
  1265 }
  1266 
  1267 DYNAMIC_API PEP_STATUS generate_keypair(
  1268         PEP_SESSION session, pEp_identity *identity
  1269     )
  1270 {
  1271     assert(session);
  1272     assert(identity);
  1273     assert(identity->address);
  1274     assert(identity->fpr == NULL || identity->fpr[0] == 0);
  1275     assert(identity->username);
  1276 
  1277     if (!(session && identity && identity->address &&
  1278             (identity->fpr == NULL || identity->fpr[0] == 0) &&
  1279             identity->username))
  1280         return PEP_ILLEGAL_VALUE;
  1281 
  1282     PEP_STATUS status =
  1283         session->cryptotech[PEP_crypt_OpenPGP].generate_keypair(session,
  1284                 identity);
  1285     if (status != PEP_STATUS_OK)
  1286         return status;
  1287 
  1288     // if a state machine for keysync is in place, inject notify
  1289     if (session->sync_state != DeviceState_state_NONE)
  1290         status = fsm_DeviceState_inject(session, KeyGen, NULL, NULL);
  1291 
  1292     return status;
  1293 }
  1294 
  1295 DYNAMIC_API PEP_STATUS get_key_rating(
  1296         PEP_SESSION session,
  1297         const char *fpr,
  1298         PEP_comm_type *comm_type
  1299     )
  1300 {
  1301     assert(session);
  1302     assert(fpr);
  1303     assert(comm_type);
  1304 
  1305     if (!(session && fpr && comm_type))
  1306         return PEP_ILLEGAL_VALUE;
  1307 
  1308     return session->cryptotech[PEP_crypt_OpenPGP].get_key_rating(session, fpr,
  1309             comm_type);
  1310 }
  1311 
  1312 DYNAMIC_API PEP_STATUS import_key(
  1313         PEP_SESSION session,
  1314         const char *key_data,
  1315         size_t size,
  1316         identity_list **private_keys
  1317     )
  1318 {
  1319     assert(session);
  1320     assert(key_data);
  1321 
  1322     if (!(session && key_data))
  1323         return PEP_ILLEGAL_VALUE;
  1324 
  1325     return session->cryptotech[PEP_crypt_OpenPGP].import_key(session, key_data,
  1326             size, private_keys);
  1327 }
  1328 
  1329 DYNAMIC_API PEP_STATUS recv_key(PEP_SESSION session, const char *pattern)
  1330 {
  1331     assert(session);
  1332     assert(pattern);
  1333 
  1334     if (!(session && pattern))
  1335         return PEP_ILLEGAL_VALUE;
  1336 
  1337     return session->cryptotech[PEP_crypt_OpenPGP].recv_key(session, pattern);
  1338 }
  1339 
  1340 DYNAMIC_API PEP_STATUS send_key(PEP_SESSION session, const char *pattern)
  1341 {
  1342     assert(session);
  1343     assert(pattern);
  1344 
  1345     if (!(session && pattern))
  1346         return PEP_ILLEGAL_VALUE;
  1347 
  1348     return session->cryptotech[PEP_crypt_OpenPGP].send_key(session, pattern);
  1349 }
  1350 
  1351 DYNAMIC_API PEP_STATUS renew_key(
  1352         PEP_SESSION session,
  1353         const char *fpr,
  1354         const timestamp *ts
  1355     )
  1356 {
  1357     assert(session);
  1358     assert(fpr);
  1359 
  1360     if (!(session && fpr))
  1361         return PEP_ILLEGAL_VALUE;
  1362 
  1363     return session->cryptotech[PEP_crypt_OpenPGP].renew_key(session, fpr, ts);
  1364 }
  1365 
  1366 DYNAMIC_API PEP_STATUS revoke_key(
  1367         PEP_SESSION session,
  1368         const char *fpr,
  1369         const char *reason
  1370     )
  1371 {
  1372     assert(session);
  1373     assert(fpr);
  1374 
  1375     if (!(session && fpr))
  1376         return PEP_ILLEGAL_VALUE;
  1377 
  1378     return session->cryptotech[PEP_crypt_OpenPGP].revoke_key(session, fpr,
  1379             reason);
  1380 }
  1381 
  1382 DYNAMIC_API PEP_STATUS key_expired(
  1383         PEP_SESSION session,
  1384         const char *fpr,
  1385         const time_t when,
  1386         bool *expired
  1387     )
  1388 {
  1389     assert(session);
  1390     assert(fpr);
  1391     assert(expired);
  1392 
  1393     if (!(session && fpr && expired))
  1394         return PEP_ILLEGAL_VALUE;
  1395 
  1396     return session->cryptotech[PEP_crypt_OpenPGP].key_expired(session, fpr,
  1397             when, expired);
  1398 }
  1399 
  1400 DYNAMIC_API PEP_STATUS key_revoked(
  1401        PEP_SESSION session,
  1402        const char *fpr,
  1403        bool *revoked
  1404    )
  1405 {
  1406     assert(session);
  1407     assert(fpr);
  1408     assert(revoked);
  1409     
  1410     if (!(session && fpr && revoked))
  1411         return PEP_ILLEGAL_VALUE;
  1412     
  1413     return session->cryptotech[PEP_crypt_OpenPGP].key_revoked(session, fpr,
  1414             revoked);
  1415 }
  1416 
  1417 static void _clean_log_value(char *text)
  1418 {
  1419     if (text) {
  1420         for (char *c = text; *c; c++) {
  1421             if (*c < 32 && *c != '\n')
  1422                 *c = 32;
  1423             else if (*c == '"')
  1424                 *c = '\'';
  1425         }
  1426     }
  1427 }
  1428 
  1429 static char *_concat_string(char *str1, const char *str2, char delim)
  1430 {
  1431     str2 = str2 ? str2 : "";
  1432     size_t len1 = str1 ? strlen(str1) : 0;
  1433     size_t len2 = strlen(str2);
  1434     size_t len = len1 + len2 + 3;
  1435     char * result = realloc(str1, len + 1);
  1436 
  1437     if (result) {
  1438         result[len1] = '"';
  1439         strcpy(result + len1 + 1, str2);
  1440         result[len - 2] = '"';
  1441         result[len - 1] = delim;
  1442         result[len] = 0;
  1443     }
  1444     else {
  1445         free(str1);
  1446     }
  1447 
  1448     return result;
  1449 }
  1450 
  1451 DYNAMIC_API PEP_STATUS get_crashdump_log(
  1452         PEP_SESSION session,
  1453         int maxlines,
  1454         char **logdata
  1455     )
  1456 {
  1457     PEP_STATUS status = PEP_STATUS_OK;
  1458     char *_logdata= NULL;
  1459 
  1460     assert(session);
  1461     assert(maxlines >= 0 && maxlines <= CRASHDUMP_MAX_LINES);
  1462     assert(logdata);
  1463 
  1464     if (!(session && logdata && maxlines >= 0 && maxlines <=
  1465             CRASHDUMP_MAX_LINES))
  1466         return PEP_ILLEGAL_VALUE;
  1467 
  1468     *logdata = NULL;
  1469 
  1470     int limit = maxlines ? maxlines : CRASHDUMP_DEFAULT_LINES;
  1471     const char *timestamp = NULL;
  1472     const char *title = NULL;
  1473     const char *entity = NULL;
  1474     const char *desc = NULL;
  1475     const char *comment = NULL;
  1476 
  1477     sqlite3_reset(session->crashdump);
  1478     sqlite3_bind_int(session->crashdump, 1, limit);
  1479 
  1480     int result;
  1481 
  1482     do {
  1483         result = sqlite3_step(session->crashdump);
  1484         switch (result) {
  1485         case SQLITE_ROW:
  1486             timestamp = (const char *) sqlite3_column_text(session->crashdump,
  1487                     0);
  1488             title   = (const char *) sqlite3_column_text(session->crashdump,
  1489                     1);
  1490             entity  = (const char *) sqlite3_column_text(session->crashdump,
  1491                     2);
  1492             desc    = (const char *) sqlite3_column_text(session->crashdump,
  1493                     3);
  1494             comment = (const char *) sqlite3_column_text(session->crashdump,
  1495                     4);
  1496 
  1497             _logdata = _concat_string(_logdata, timestamp, ',');
  1498             if (_logdata == NULL)
  1499                 goto enomem;
  1500 
  1501             _logdata = _concat_string(_logdata, title, ',');
  1502             if (_logdata == NULL)
  1503                 goto enomem;
  1504 
  1505             _logdata = _concat_string(_logdata, entity, ',');
  1506             if (_logdata == NULL)
  1507                 goto enomem;
  1508 
  1509             _logdata = _concat_string(_logdata, desc, ',');
  1510             if (_logdata == NULL)
  1511                 goto enomem;
  1512 
  1513             _logdata = _concat_string(_logdata, comment, '\n');
  1514             if (_logdata == NULL)
  1515                 goto enomem;
  1516 
  1517             _clean_log_value(_logdata);
  1518             break;
  1519 
  1520         case SQLITE_DONE:
  1521             break;
  1522 
  1523         default:
  1524             status = PEP_UNKNOWN_ERROR;
  1525             result = SQLITE_DONE;
  1526         }
  1527     } while (result != SQLITE_DONE);
  1528 
  1529     sqlite3_reset(session->crashdump);
  1530     if (status == PEP_STATUS_OK)
  1531         *logdata = _logdata;
  1532 
  1533     goto the_end;
  1534 
  1535 enomem:
  1536     status = PEP_OUT_OF_MEMORY;
  1537 
  1538 the_end:
  1539     return status;
  1540 }
  1541 
  1542 DYNAMIC_API PEP_STATUS get_languagelist(
  1543         PEP_SESSION session,
  1544         char **languages
  1545     )
  1546 {
  1547     PEP_STATUS status = PEP_STATUS_OK;
  1548     char *_languages= NULL;
  1549 
  1550     assert(session);
  1551     assert(languages);
  1552 
  1553     if (!(session && languages))
  1554         return PEP_ILLEGAL_VALUE;
  1555 
  1556     *languages = NULL;
  1557 
  1558     const char *lang = NULL;
  1559     const char *name = NULL;
  1560     const char *phrase = NULL;
  1561 
  1562     sqlite3_reset(session->languagelist);
  1563 
  1564     int result;
  1565 
  1566     do {
  1567         result = sqlite3_step(session->languagelist);
  1568         switch (result) {
  1569         case SQLITE_ROW:
  1570             lang = (const char *) sqlite3_column_text(session->languagelist,
  1571                     0);
  1572             name = (const char *) sqlite3_column_text(session->languagelist,
  1573                     1);
  1574             phrase = (const char *) sqlite3_column_text(session->languagelist,
  1575                     2);
  1576 
  1577             _languages = _concat_string(_languages, lang, ',');
  1578             if (_languages == NULL)
  1579                 goto enomem;
  1580 
  1581             _languages = _concat_string(_languages, name, ',');
  1582             if (_languages == NULL)
  1583                 goto enomem;
  1584 
  1585             _languages = _concat_string(_languages, phrase, '\n');
  1586             if (_languages == NULL)
  1587                 goto enomem;
  1588 
  1589             break;
  1590 
  1591         case SQLITE_DONE:
  1592             break;
  1593 
  1594         default:
  1595             status = PEP_UNKNOWN_ERROR;
  1596             result = SQLITE_DONE;
  1597         }
  1598     } while (result != SQLITE_DONE);
  1599 
  1600     sqlite3_reset(session->languagelist);
  1601     if (status == PEP_STATUS_OK)
  1602         *languages = _languages;
  1603 
  1604     goto the_end;
  1605 
  1606 enomem:
  1607     status = PEP_OUT_OF_MEMORY;
  1608 
  1609 the_end:
  1610     return status;
  1611 }
  1612 
  1613 DYNAMIC_API PEP_STATUS get_phrase(
  1614         PEP_SESSION session,
  1615         const char *lang,
  1616         int phrase_id,
  1617         char **phrase
  1618     )
  1619 {
  1620     PEP_STATUS status = PEP_STATUS_OK;
  1621 
  1622     assert(session && lang && lang[0] && lang[1] && lang[2] == 0 && phrase);
  1623     if (!(session && lang && lang[0] && lang[1] && lang[2] == 0 && phrase))
  1624         return PEP_ILLEGAL_VALUE;
  1625 
  1626     *phrase = NULL;
  1627 
  1628     sqlite3_reset(session->i18n_token);
  1629     sqlite3_bind_text(session->i18n_token, 1, lang, -1, SQLITE_STATIC);
  1630     sqlite3_bind_int(session->i18n_token, 2, phrase_id);
  1631 
  1632     const char *_phrase = NULL;
  1633     int result;
  1634 
  1635     result = sqlite3_step(session->i18n_token);
  1636     switch (result) {
  1637     case SQLITE_ROW:
  1638         _phrase = (const char *) sqlite3_column_text(session->i18n_token, 0);
  1639         break;
  1640 
  1641     case SQLITE_DONE:
  1642         status = PEP_PHRASE_NOT_FOUND;
  1643         break;
  1644 
  1645     default:
  1646         status = PEP_UNKNOWN_ERROR;
  1647     }
  1648 
  1649     if (status == PEP_STATUS_OK) {
  1650         *phrase = strdup(_phrase);
  1651         if (*phrase == NULL)
  1652             goto enomem;
  1653     }
  1654 
  1655     sqlite3_reset(session->i18n_token);
  1656     goto the_end;
  1657 
  1658 enomem:
  1659     status = PEP_OUT_OF_MEMORY;
  1660 
  1661 the_end:
  1662     return status;
  1663 }
  1664 
  1665 DYNAMIC_API PEP_STATUS sequence_value(
  1666         PEP_SESSION session,
  1667         const char *name,
  1668         int32_t *value
  1669     )
  1670 {
  1671     PEP_STATUS status = PEP_STATUS_OK;
  1672     int result;
  1673 
  1674     assert(session);
  1675     assert(name);
  1676     assert(value);
  1677 
  1678     if (!(session && name && value))
  1679         return PEP_ILLEGAL_VALUE;
  1680 
  1681     *value = 0;
  1682 
  1683     sqlite3_reset(session->sequence_value1);
  1684     sqlite3_bind_text(session->sequence_value1, 1, name, -1, SQLITE_STATIC);
  1685     result = sqlite3_step(session->sequence_value1);
  1686     assert(result == SQLITE_DONE);
  1687     sqlite3_reset(session->sequence_value1);
  1688     if (result != SQLITE_DONE) {
  1689         status = PEP_UNKNOWN_ERROR;
  1690     }
  1691     else {
  1692         sqlite3_reset(session->sequence_value2);
  1693         sqlite3_bind_text(session->sequence_value2, 1, name, -1,
  1694                 SQLITE_STATIC);
  1695         result = sqlite3_step(session->sequence_value2);
  1696         switch (result) {
  1697             case SQLITE_ROW: {
  1698                 int32_t _value = (int32_t)
  1699                         sqlite3_column_int64(session->sequence_value2, 0);
  1700                 *value = _value;
  1701                 break;
  1702             }
  1703             default:
  1704                 status = PEP_UNKNOWN_ERROR;
  1705         }
  1706         sqlite3_reset(session->sequence_value2);
  1707     }
  1708     return status;
  1709 }
  1710 
  1711 DYNAMIC_API PEP_STATUS set_revoked(
  1712        PEP_SESSION session,
  1713        const char *revoked_fpr,
  1714        const char *replacement_fpr,
  1715        const uint64_t revocation_date
  1716     )
  1717 {
  1718     PEP_STATUS status = PEP_STATUS_OK;
  1719     
  1720     assert(session &&
  1721            revoked_fpr && revoked_fpr[0] &&
  1722            replacement_fpr && replacement_fpr[0]
  1723           );
  1724     
  1725     if (!(session &&
  1726           revoked_fpr && revoked_fpr[0] &&
  1727           replacement_fpr && replacement_fpr[0]
  1728          ))
  1729         return PEP_ILLEGAL_VALUE;
  1730     
  1731     sqlite3_reset(session->set_revoked);
  1732     sqlite3_bind_text(session->set_revoked, 1, revoked_fpr, -1, SQLITE_STATIC);
  1733     sqlite3_bind_text(session->set_revoked, 2, replacement_fpr, -1,
  1734             SQLITE_STATIC);
  1735     sqlite3_bind_int64(session->set_revoked, 3, revocation_date);
  1736 
  1737     int result;
  1738     
  1739     result = sqlite3_step(session->set_revoked);
  1740     switch (result) {
  1741         case SQLITE_DONE:
  1742             status = PEP_STATUS_OK;
  1743             break;
  1744             
  1745         default:
  1746             status = PEP_UNKNOWN_ERROR;
  1747     }
  1748     
  1749     sqlite3_reset(session->set_revoked);
  1750     return status;
  1751 }
  1752 
  1753 DYNAMIC_API PEP_STATUS get_revoked(
  1754         PEP_SESSION session,
  1755         const char *fpr,
  1756         char **revoked_fpr,
  1757         uint64_t *revocation_date
  1758     )
  1759 {
  1760     PEP_STATUS status = PEP_STATUS_OK;
  1761 
  1762     assert(session &&
  1763            revoked_fpr &&
  1764            fpr && fpr[0]
  1765           );
  1766     
  1767     if (!(session &&
  1768            revoked_fpr &&
  1769            fpr && fpr[0]
  1770           ))
  1771         return PEP_ILLEGAL_VALUE;
  1772 
  1773     *revoked_fpr = NULL;
  1774     *revocation_date = 0;
  1775 
  1776     sqlite3_reset(session->get_revoked);
  1777     sqlite3_bind_text(session->get_revoked, 1, fpr, -1, SQLITE_STATIC);
  1778 
  1779     int result;
  1780     
  1781     result = sqlite3_step(session->get_revoked);
  1782     switch (result) {
  1783         case SQLITE_ROW: {
  1784             *revoked_fpr = strdup((const char *)
  1785                     sqlite3_column_text(session->get_revoked, 0));
  1786             if(*revoked_fpr)
  1787                 *revocation_date = sqlite3_column_int64(session->get_revoked,
  1788                         1);
  1789             else
  1790                 status = PEP_OUT_OF_MEMORY;
  1791 
  1792             break;
  1793         }
  1794         default:
  1795             status = PEP_CANNOT_FIND_IDENTITY;
  1796     }
  1797 
  1798     sqlite3_reset(session->get_revoked);
  1799 
  1800     return status;
  1801 }
  1802 
  1803 DYNAMIC_API PEP_STATUS reset_peptest_hack(PEP_SESSION session)
  1804 {
  1805     assert(session);
  1806 
  1807     if (!session)
  1808         return PEP_ILLEGAL_VALUE;
  1809 
  1810     int int_result = sqlite3_exec(
  1811         session->db,
  1812         "delete from identity where address like '%@peptest.ch' ;",
  1813         NULL,
  1814         NULL,
  1815         NULL
  1816     );
  1817     assert(int_result == SQLITE_OK);
  1818 
  1819     return PEP_STATUS_OK;
  1820 }
  1821