src/pEpEngine.c
author Volker Birk <vb@pep.foundation>
Tue, 09 Aug 2016 00:08:08 +0200
branchkeysync
changeset 986 8f85f70bdd75
parent 958 cef602982909
child 1001 42e0841b71f0
permissions -rw-r--r--
auto stop keysync on release() of session
     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->sync_state != DeviceState_state_NONE)
   556             unregister_sync_callbacks(session);
   557 
   558         if (session->db) {
   559             if (session->log)
   560                 sqlite3_finalize(session->log);
   561             if (session->trustword)
   562                 sqlite3_finalize(session->trustword);
   563             if (session->get_identity)
   564                 sqlite3_finalize(session->get_identity);
   565             if (session->set_person)
   566                 sqlite3_finalize(session->set_person);
   567             if (session->set_pgp_keypair)
   568                 sqlite3_finalize(session->set_pgp_keypair);
   569             if (session->set_identity)
   570                 sqlite3_finalize(session->set_identity);
   571             if (session->set_identity_flags)
   572                 sqlite3_finalize(session->set_identity_flags);
   573             if (session->set_trust)
   574                 sqlite3_finalize(session->set_trust);
   575             if (session->get_trust)
   576                 sqlite3_finalize(session->get_trust);
   577             if (session->least_trust)
   578                 sqlite3_finalize(session->least_trust);
   579             if (session->mark_compromized)
   580                 sqlite3_finalize(session->mark_compromized);
   581             if (session->crashdump)
   582                 sqlite3_finalize(session->crashdump);
   583             if (session->languagelist)
   584                 sqlite3_finalize(session->languagelist);
   585             if (session->i18n_token)
   586                 sqlite3_finalize(session->i18n_token);
   587             if (session->blacklist_add)
   588                 sqlite3_finalize(session->blacklist_add);
   589             if (session->blacklist_delete)
   590                 sqlite3_finalize(session->blacklist_delete);
   591             if (session->blacklist_is_listed)
   592                 sqlite3_finalize(session->blacklist_is_listed);
   593             if (session->blacklist_retrieve)
   594                 sqlite3_finalize(session->blacklist_retrieve);
   595 
   596             if (session->db)
   597                 sqlite3_close_v2(session->db);
   598             if (session->system_db)
   599                 sqlite3_close_v2(session->system_db);
   600         }
   601 
   602         release_transport_system(session, out_last);
   603         release_cryptotech(session, out_last);
   604 
   605         free(session);
   606     }
   607 }
   608 
   609 DYNAMIC_API void config_passive_mode(PEP_SESSION session, bool enable)
   610 {
   611     assert(session);
   612     session->passive_mode = enable;
   613 }
   614 
   615 DYNAMIC_API void config_unencrypted_subject(PEP_SESSION session, bool enable)
   616 {
   617     assert(session);
   618     session->unencrypted_subject = enable;
   619 }
   620 
   621 DYNAMIC_API void config_use_only_own_private_keys(PEP_SESSION session,
   622         bool enable)
   623 {
   624     assert(session);
   625     session->use_only_own_private_keys = enable;
   626 }
   627 
   628 DYNAMIC_API PEP_STATUS log_event(
   629         PEP_SESSION session,
   630         const char *title,
   631         const char *entity,
   632         const char *description,
   633         const char *comment
   634     )
   635 {
   636     PEP_STATUS status = PEP_STATUS_OK;
   637     int result;
   638 
   639     assert(session);
   640     assert(title);
   641     assert(entity);
   642 
   643     if (!(session && title && entity))
   644         return PEP_ILLEGAL_VALUE;
   645 
   646     sqlite3_reset(session->log);
   647     sqlite3_bind_text(session->log, 1, title, -1, SQLITE_STATIC);
   648     sqlite3_bind_text(session->log, 2, entity, -1, SQLITE_STATIC);
   649     if (description)
   650         sqlite3_bind_text(session->log, 3, description, -1, SQLITE_STATIC);
   651     else
   652         sqlite3_bind_null(session->log, 3);
   653     if (comment)
   654         sqlite3_bind_text(session->log, 4, comment, -1, SQLITE_STATIC);
   655     else
   656         sqlite3_bind_null(session->log, 4);
   657     do {
   658         result = sqlite3_step(session->log);
   659         assert(result == SQLITE_DONE || result == SQLITE_BUSY);
   660         if (result != SQLITE_DONE && result != SQLITE_BUSY)
   661             status = PEP_UNKNOWN_ERROR;
   662     } while (result == SQLITE_BUSY);
   663     sqlite3_reset(session->log);
   664 
   665     return status;
   666 }
   667 
   668 DYNAMIC_API PEP_STATUS trustword(
   669             PEP_SESSION session, uint16_t value, const char *lang,
   670             char **word, size_t *wsize
   671         )
   672 {
   673     PEP_STATUS status = PEP_STATUS_OK;
   674 
   675     assert(session);
   676     assert(word);
   677     assert(wsize);
   678 
   679     if (!(session && word && wsize))
   680         return PEP_ILLEGAL_VALUE;
   681 
   682     *word = NULL;
   683     *wsize = 0;
   684 
   685     if (lang == NULL)
   686         lang = "en";
   687 
   688     assert((lang[0] >= 'A' && lang[0] <= 'Z')
   689             || (lang[0] >= 'a' && lang[0] <= 'z'));
   690     assert((lang[1] >= 'A' && lang[1] <= 'Z')
   691             || (lang[1] >= 'a' && lang[1] <= 'z'));
   692     assert(lang[2] == 0);
   693 
   694     sqlite3_reset(session->trustword);
   695     sqlite3_bind_text(session->trustword, 1, lang, -1, SQLITE_STATIC);
   696     sqlite3_bind_int(session->trustword, 2, value);
   697 
   698     const int result = sqlite3_step(session->trustword);
   699     if (result == SQLITE_ROW) {
   700         *word = strdup((const char *) sqlite3_column_text(session->trustword,
   701                     1));
   702         if (*word)
   703             *wsize = sqlite3_column_bytes(session->trustword, 1);
   704         else
   705             status = PEP_OUT_OF_MEMORY;
   706     } else
   707         status = PEP_TRUSTWORD_NOT_FOUND;
   708 
   709     sqlite3_reset(session->trustword);
   710     return status;
   711 }
   712 
   713 DYNAMIC_API PEP_STATUS trustwords(
   714         PEP_SESSION session, const char *fingerprint, const char *lang,
   715         char **words, size_t *wsize, int max_words
   716     )
   717 {
   718     const char *source = fingerprint;
   719     char *buffer;
   720     char *dest;
   721     size_t fsize;
   722 
   723     assert(session);
   724     assert(fingerprint);
   725     assert(words);
   726     assert(wsize);
   727     assert(max_words >= 0);
   728 
   729     if (!(session && fingerprint && words && wsize && max_words >= 0))
   730         return PEP_ILLEGAL_VALUE;
   731 
   732     *words = NULL;
   733     *wsize = 0;
   734 
   735     buffer = calloc(1, MAX_TRUSTWORDS_SPACE);
   736     assert(buffer);
   737     if (buffer == NULL)
   738         return PEP_OUT_OF_MEMORY;
   739     dest = buffer;
   740 
   741     fsize = strlen(fingerprint);
   742 
   743     if (!lang || !lang[0])
   744         lang = "en";
   745 
   746     assert((lang[0] >= 'A' && lang[0] <= 'Z')
   747             || (lang[0] >= 'a' && lang[0] <= 'z'));
   748     assert((lang[1] >= 'A' && lang[1] <= 'Z')
   749             || (lang[1] >= 'a' && lang[1] <= 'z'));
   750     assert(lang[2] == 0);
   751 
   752     int n_words = 0;
   753     while (source < fingerprint + fsize) {
   754         PEP_STATUS _status;
   755         uint16_t value;
   756         char *word;
   757         size_t _wsize;
   758         int j;
   759 
   760         for (value=0, j=0; j < 4 && source < fingerprint + fsize; ) {
   761             if (*source >= 'a' && *source <= 'f')
   762                 value += (*source - 'a' + 10) << (3 - j++) * 4;
   763             else if (*source >= 'A' && *source <= 'F')
   764                 value += (*source - 'A' + 10) << (3 - j++) * 4;
   765             else if (*source >= '0' && *source <= '9')
   766                 value += (*source - '0') << (3 - j++) * 4;
   767             
   768             source++;
   769         }
   770 
   771         _status = trustword(session, value, lang, &word, &_wsize);
   772         if (_status == PEP_OUT_OF_MEMORY) {
   773             free(buffer);
   774             return PEP_OUT_OF_MEMORY;
   775         }
   776         if (word == NULL) {
   777             free(buffer);
   778             return PEP_TRUSTWORD_NOT_FOUND;
   779         }
   780 
   781         if (dest + _wsize < buffer + MAX_TRUSTWORDS_SPACE - 1) {
   782             strncpy(dest, word, _wsize);
   783             free(word);
   784             dest += _wsize;
   785         }
   786         else {
   787             free(word);
   788             break; // buffer full
   789         }
   790 
   791         if (source < fingerprint + fsize
   792                 && dest + _wsize < buffer + MAX_TRUSTWORDS_SPACE - 1)
   793             *dest++ = ' ';
   794 
   795         ++n_words;
   796         if (max_words && n_words >= max_words)
   797             break;
   798     }
   799 
   800     *words = buffer;
   801     *wsize = dest - buffer;
   802     return PEP_STATUS_OK;
   803 }
   804 
   805 pEp_identity *new_identity(
   806         const char *address, const char *fpr, const char *user_id,
   807         const char *username
   808     )
   809 {
   810     pEp_identity *result = calloc(1, sizeof(pEp_identity));
   811     assert(result);
   812     if (result) {
   813         if (address) {
   814             result->address = strdup(address);
   815             assert(result->address);
   816             if (result->address == NULL) {
   817                 free(result);
   818                 return NULL;
   819             }
   820         }
   821         if (fpr) {
   822             result->fpr = strdup(fpr);
   823             assert(result->fpr);
   824             if (result->fpr == NULL) {
   825                 free_identity(result);
   826                 return NULL;
   827             }
   828         }
   829         if (user_id) {
   830             result->user_id = strdup(user_id);
   831             assert(result->user_id);
   832             if (result->user_id == NULL) {
   833                 free_identity(result);
   834                 return NULL;
   835             }
   836         }
   837         if (username) {
   838             result->username = strdup(username);
   839             assert(result->username);
   840             if (result->username == NULL) {
   841                 free_identity(result);
   842                 return NULL;
   843             }
   844         }
   845     }
   846     return result;
   847 }
   848 
   849 pEp_identity *identity_dup(const pEp_identity *src)
   850 {
   851     assert(src);
   852 
   853     pEp_identity *dup = new_identity(src->address, src->fpr, src->user_id,
   854             src->username);
   855     assert(dup);
   856     if (dup == NULL)
   857         return NULL;
   858     
   859     dup->comm_type = src->comm_type;
   860     dup->lang[0] = src->lang[0];
   861     dup->lang[1] = src->lang[1];
   862     dup->lang[2] = 0;
   863     dup->me = src->me;
   864     dup->flags = src->flags;
   865 
   866     return dup;
   867 }
   868 
   869 void free_identity(pEp_identity *identity)
   870 {
   871     if (identity) {
   872         free(identity->address);
   873         free(identity->fpr);
   874         free(identity->user_id);
   875         free(identity->username);
   876         free(identity);
   877     }
   878 }
   879 
   880 DYNAMIC_API PEP_STATUS get_identity(
   881         PEP_SESSION session,
   882         const char *address,
   883         const char *user_id,
   884         pEp_identity **identity
   885     )
   886 {
   887     PEP_STATUS status = PEP_STATUS_OK;
   888     static pEp_identity *_identity;
   889 
   890     assert(session);
   891     assert(address);
   892     assert(address[0]);
   893     assert(identity);
   894 
   895     if (!(session && address && address[0] && identity))
   896         return PEP_ILLEGAL_VALUE;
   897 
   898     *identity = NULL;
   899 
   900     sqlite3_reset(session->get_identity);
   901     sqlite3_bind_text(session->get_identity, 1, address, -1, SQLITE_STATIC);
   902     sqlite3_bind_text(session->get_identity, 2, user_id, -1, SQLITE_STATIC);
   903 
   904     const int result = sqlite3_step(session->get_identity);
   905     switch (result) {
   906     case SQLITE_ROW:
   907         _identity = new_identity(
   908                 address,
   909                 (const char *) sqlite3_column_text(session->get_identity, 0),
   910                 user_id,
   911                 (const char *) sqlite3_column_text(session->get_identity, 1)
   912                 );
   913         assert(_identity);
   914         if (_identity == NULL)
   915             return PEP_OUT_OF_MEMORY;
   916 
   917         _identity->comm_type = (PEP_comm_type)
   918             sqlite3_column_int(session->get_identity, 2);
   919         const char* const _lang = (const char *)
   920             sqlite3_column_text(session->get_identity, 3);
   921         if (_lang && _lang[0]) {
   922             assert(_lang[0] >= 'a' && _lang[0] <= 'z');
   923             assert(_lang[1] >= 'a' && _lang[1] <= 'z');
   924             assert(_lang[2] == 0);
   925             _identity->lang[0] = _lang[0];
   926             _identity->lang[1] = _lang[1];
   927             _identity->lang[2] = 0;
   928         }
   929         _identity->flags = (unsigned int)
   930             sqlite3_column_int(session->get_identity, 4);
   931         *identity = _identity;
   932         break;
   933     default:
   934         status = PEP_CANNOT_FIND_IDENTITY;
   935         *identity = NULL;
   936     }
   937 
   938     sqlite3_reset(session->get_identity);
   939     return status;
   940 }
   941 
   942 DYNAMIC_API PEP_STATUS set_identity(
   943         PEP_SESSION session, const pEp_identity *identity
   944     )
   945 {
   946     int result;
   947 
   948     assert(session);
   949     assert(identity);
   950     assert(identity->address);
   951     assert(identity->fpr);
   952     assert(identity->user_id);
   953     assert(identity->username);
   954 
   955     if (!(session && identity && identity->address && identity->fpr &&
   956                 identity->user_id && identity->username))
   957         return PEP_ILLEGAL_VALUE;
   958 
   959     bool listed;
   960     PEP_STATUS status = blacklist_is_listed(session, identity->fpr, &listed);
   961     assert(status == PEP_STATUS_OK);
   962     if (status != PEP_STATUS_OK)
   963         return status;
   964 
   965     if (listed)
   966         return PEP_KEY_BLACKLISTED;
   967 
   968     sqlite3_exec(session->db, "BEGIN ;", NULL, NULL, NULL);
   969 
   970     sqlite3_reset(session->set_person);
   971     sqlite3_bind_text(session->set_person, 1, identity->user_id, -1,
   972             SQLITE_STATIC);
   973     sqlite3_bind_text(session->set_person, 2, identity->username, -1,
   974             SQLITE_STATIC);
   975     if (identity->lang[0])
   976         sqlite3_bind_text(session->set_person, 3, identity->lang, 1,
   977                 SQLITE_STATIC);
   978     else
   979         sqlite3_bind_null(session->set_person, 3);
   980     sqlite3_bind_text(session->set_person, 4, identity->fpr, -1,
   981                       SQLITE_STATIC);
   982     result = sqlite3_step(session->set_person);
   983     sqlite3_reset(session->set_person);
   984     if (result != SQLITE_DONE) {
   985         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
   986         return PEP_CANNOT_SET_PERSON;
   987     }
   988 
   989     sqlite3_reset(session->set_pgp_keypair);
   990     sqlite3_bind_text(session->set_pgp_keypair, 1, identity->fpr, -1,
   991             SQLITE_STATIC);
   992     result = sqlite3_step(session->set_pgp_keypair);
   993     sqlite3_reset(session->set_pgp_keypair);
   994     if (result != SQLITE_DONE) {
   995         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
   996         return PEP_CANNOT_SET_PGP_KEYPAIR;
   997     }
   998 
   999     sqlite3_reset(session->set_identity);
  1000     sqlite3_bind_text(session->set_identity, 1, identity->address, -1,
  1001             SQLITE_STATIC);
  1002     sqlite3_bind_text(session->set_identity, 2, identity->fpr, -1,
  1003             SQLITE_STATIC);
  1004     sqlite3_bind_text(session->set_identity, 3, identity->user_id, -1,
  1005             SQLITE_STATIC);
  1006     sqlite3_bind_int(session->set_identity, 4, identity->flags);
  1007     result = sqlite3_step(session->set_identity);
  1008     sqlite3_reset(session->set_identity);
  1009     if (result != SQLITE_DONE) {
  1010         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1011         return PEP_CANNOT_SET_IDENTITY;
  1012     }
  1013 
  1014     sqlite3_reset(session->set_trust);
  1015     sqlite3_bind_text(session->set_trust, 1, identity->user_id, -1,
  1016             SQLITE_STATIC);
  1017     sqlite3_bind_text(session->set_trust, 2, identity->fpr, -1,
  1018             SQLITE_STATIC);
  1019     sqlite3_bind_int(session->set_trust, 3, identity->comm_type);
  1020     result = sqlite3_step(session->set_trust);
  1021     sqlite3_reset(session->set_trust);
  1022     if (result != SQLITE_DONE) {
  1023         sqlite3_exec(session->db, "ROLLBACK ;", NULL, NULL, NULL);
  1024         return PEP_CANNOT_SET_TRUST;
  1025     }
  1026 
  1027     result = sqlite3_exec(session->db, "COMMIT ;", NULL, NULL, NULL);
  1028     if (result == SQLITE_OK)
  1029         return PEP_STATUS_OK;
  1030     else
  1031         return PEP_COMMIT_FAILED;
  1032 }
  1033 
  1034 DYNAMIC_API PEP_STATUS set_identity_flags(
  1035         PEP_SESSION session,
  1036         pEp_identity *identity,
  1037         unsigned int flags
  1038     )
  1039 {
  1040     int result;
  1041 
  1042     assert(session);
  1043     assert(identity);
  1044     assert(identity->address);
  1045     assert(identity->user_id);
  1046 
  1047     if (!(session && identity && identity->address && identity->user_id))
  1048         return PEP_ILLEGAL_VALUE;
  1049 
  1050     sqlite3_reset(session->set_identity_flags);
  1051     sqlite3_bind_int(session->set_identity_flags, 1, flags);
  1052     sqlite3_bind_text(session->set_identity_flags, 2, identity->address, -1,
  1053             SQLITE_STATIC);
  1054     sqlite3_bind_text(session->set_identity_flags, 3, identity->user_id, -1,
  1055             SQLITE_STATIC);
  1056     result = sqlite3_step(session->set_identity_flags);
  1057     sqlite3_reset(session->set_identity_flags);
  1058     if (result != SQLITE_DONE)
  1059         return PEP_CANNOT_SET_IDENTITY;
  1060 
  1061     identity->flags = flags;
  1062     return PEP_STATUS_OK;
  1063 }
  1064 
  1065 DYNAMIC_API PEP_STATUS mark_as_compromized(
  1066         PEP_SESSION session,
  1067         const char *fpr
  1068     )
  1069 {
  1070     int result;
  1071 
  1072     assert(session);
  1073     assert(fpr && fpr[0]);
  1074 
  1075     if (!(session && fpr && fpr[0]))
  1076         return PEP_ILLEGAL_VALUE;
  1077 
  1078     sqlite3_reset(session->mark_compromized);
  1079     sqlite3_bind_text(session->mark_compromized, 1, fpr, -1,
  1080             SQLITE_STATIC);
  1081     result = sqlite3_step(session->mark_compromized);
  1082     sqlite3_reset(session->mark_compromized);
  1083 
  1084     if (result != SQLITE_DONE)
  1085         return PEP_CANNOT_SET_TRUST;
  1086 
  1087     return PEP_STATUS_OK;
  1088 }
  1089 
  1090 void pEp_free(void *p)
  1091 {
  1092     free(p);
  1093 }
  1094 
  1095 DYNAMIC_API PEP_STATUS get_trust(PEP_SESSION session, pEp_identity *identity)
  1096 {
  1097     PEP_STATUS status = PEP_STATUS_OK;
  1098     int result;
  1099 
  1100     assert(session);
  1101     assert(identity);
  1102     assert(identity->user_id);
  1103     assert(identity->user_id[0]);
  1104     assert(identity->fpr);
  1105     assert(identity->fpr[0]);
  1106 
  1107     if (!(session && identity && identity->user_id && identity->user_id[0] &&
  1108                 identity->fpr && identity->fpr[0]))
  1109         return PEP_ILLEGAL_VALUE;
  1110 
  1111     identity->comm_type = PEP_ct_unknown;
  1112 
  1113     sqlite3_reset(session->get_trust);
  1114     sqlite3_bind_text(session->get_trust, 1, identity->user_id, -1,
  1115             SQLITE_STATIC);
  1116     sqlite3_bind_text(session->get_trust, 2, identity->fpr, -1, SQLITE_STATIC);
  1117 
  1118     result = sqlite3_step(session->get_trust);
  1119     switch (result) {
  1120     case SQLITE_ROW: {
  1121         int comm_type = (PEP_comm_type) sqlite3_column_int(session->get_trust,
  1122                 0);
  1123         identity->comm_type = comm_type;
  1124         break;
  1125     }
  1126  
  1127     default:
  1128         status = PEP_CANNOT_FIND_IDENTITY;
  1129     }
  1130 
  1131     sqlite3_reset(session->get_trust);
  1132     return status;
  1133 }
  1134 
  1135 DYNAMIC_API PEP_STATUS least_trust(
  1136         PEP_SESSION session,
  1137         const char *fpr,
  1138         PEP_comm_type *comm_type
  1139     )
  1140 {
  1141     PEP_STATUS status = PEP_STATUS_OK;
  1142     int result;
  1143 
  1144     assert(session);
  1145     assert(fpr);
  1146     assert(comm_type);
  1147 
  1148     if (!(session && fpr && comm_type))
  1149         return PEP_ILLEGAL_VALUE;
  1150 
  1151     *comm_type = PEP_ct_unknown;
  1152 
  1153     sqlite3_reset(session->least_trust);
  1154     sqlite3_bind_text(session->least_trust, 1, fpr, -1, SQLITE_STATIC);
  1155 
  1156     result = sqlite3_step(session->least_trust);
  1157     switch (result) {
  1158         case SQLITE_ROW: {
  1159             int _comm_type = sqlite3_column_int(session->least_trust, 0);
  1160             *comm_type = (PEP_comm_type) _comm_type;
  1161             break;
  1162         }
  1163         default:
  1164             status = PEP_CANNOT_FIND_IDENTITY;
  1165     }
  1166 
  1167     sqlite3_reset(session->least_trust);
  1168     return status;
  1169 }
  1170 
  1171 DYNAMIC_API PEP_STATUS decrypt_and_verify(
  1172     PEP_SESSION session, const char *ctext, size_t csize,
  1173     char **ptext, size_t *psize, stringlist_t **keylist
  1174     )
  1175 {
  1176     assert(session);
  1177     assert(ctext);
  1178     assert(csize);
  1179     assert(ptext);
  1180     assert(psize);
  1181     assert(keylist);
  1182 
  1183     if (!(session && ctext && csize && ptext && psize && keylist))
  1184         return PEP_ILLEGAL_VALUE;
  1185 
  1186     return session->cryptotech[PEP_crypt_OpenPGP].decrypt_and_verify(
  1187             session, ctext, csize, ptext, psize, keylist);
  1188 }
  1189 
  1190 DYNAMIC_API PEP_STATUS encrypt_and_sign(
  1191     PEP_SESSION session, const stringlist_t *keylist, const char *ptext,
  1192     size_t psize, char **ctext, size_t *csize
  1193     )
  1194 {
  1195     assert(session);
  1196     assert(keylist);
  1197     assert(ptext);
  1198     assert(psize);
  1199     assert(ctext);
  1200     assert(csize);
  1201 
  1202     if (!(session && keylist && ptext && psize && ctext && csize))
  1203         return PEP_ILLEGAL_VALUE;
  1204 
  1205     return session->cryptotech[PEP_crypt_OpenPGP].encrypt_and_sign(session,
  1206             keylist, ptext, psize, ctext, csize);
  1207 }
  1208 
  1209 DYNAMIC_API PEP_STATUS verify_text(
  1210     PEP_SESSION session, const char *text, size_t size,
  1211     const char *signature, size_t sig_size, stringlist_t **keylist
  1212     )
  1213 {
  1214     assert(session);
  1215     assert(text);
  1216     assert(size);
  1217     assert(signature);
  1218     assert(sig_size);
  1219     assert(keylist);
  1220 
  1221     if (!(session && text && size && signature && sig_size && keylist))
  1222         return PEP_ILLEGAL_VALUE;
  1223 
  1224     return session->cryptotech[PEP_crypt_OpenPGP].verify_text(session, text,
  1225             size, signature, sig_size, keylist);
  1226 }
  1227 
  1228 DYNAMIC_API PEP_STATUS delete_keypair(PEP_SESSION session, const char *fpr)
  1229 {
  1230     assert(session);
  1231     assert(fpr);
  1232 
  1233     if (!(session && fpr))
  1234         return PEP_ILLEGAL_VALUE;
  1235 
  1236     return session->cryptotech[PEP_crypt_OpenPGP].delete_keypair(session, fpr);
  1237 }
  1238 
  1239 DYNAMIC_API PEP_STATUS export_key(
  1240         PEP_SESSION session, const char *fpr, char **key_data, size_t *size
  1241     )
  1242 {
  1243     assert(session);
  1244     assert(fpr);
  1245     assert(key_data);
  1246     assert(size);
  1247 
  1248     if (!(session && fpr && key_data && size))
  1249         return PEP_ILLEGAL_VALUE;
  1250 
  1251     return session->cryptotech[PEP_crypt_OpenPGP].export_key(session, fpr,
  1252             key_data, size);
  1253 }
  1254 
  1255 DYNAMIC_API PEP_STATUS find_keys(
  1256         PEP_SESSION session, const char *pattern, stringlist_t **keylist
  1257     )
  1258 {
  1259     assert(session);
  1260     assert(pattern);
  1261     assert(keylist);
  1262 
  1263     if (!(session && pattern && keylist))
  1264         return PEP_ILLEGAL_VALUE;
  1265 
  1266     return session->cryptotech[PEP_crypt_OpenPGP].find_keys(session, pattern,
  1267             keylist);
  1268 }
  1269 
  1270 DYNAMIC_API PEP_STATUS generate_keypair(
  1271         PEP_SESSION session, pEp_identity *identity
  1272     )
  1273 {
  1274     assert(session);
  1275     assert(identity);
  1276     assert(identity->address);
  1277     assert(identity->fpr == NULL || identity->fpr[0] == 0);
  1278     assert(identity->username);
  1279 
  1280     if (!(session && identity && identity->address &&
  1281             (identity->fpr == NULL || identity->fpr[0] == 0) &&
  1282             identity->username))
  1283         return PEP_ILLEGAL_VALUE;
  1284 
  1285     PEP_STATUS status =
  1286         session->cryptotech[PEP_crypt_OpenPGP].generate_keypair(session,
  1287                 identity);
  1288     if (status != PEP_STATUS_OK)
  1289         return status;
  1290 
  1291     // if a state machine for keysync is in place, inject notify
  1292     if (session->sync_state != DeviceState_state_NONE)
  1293         status = fsm_DeviceState_inject(session, KeyGen, NULL, NULL);
  1294 
  1295     return status;
  1296 }
  1297 
  1298 DYNAMIC_API PEP_STATUS get_key_rating(
  1299         PEP_SESSION session,
  1300         const char *fpr,
  1301         PEP_comm_type *comm_type
  1302     )
  1303 {
  1304     assert(session);
  1305     assert(fpr);
  1306     assert(comm_type);
  1307 
  1308     if (!(session && fpr && comm_type))
  1309         return PEP_ILLEGAL_VALUE;
  1310 
  1311     return session->cryptotech[PEP_crypt_OpenPGP].get_key_rating(session, fpr,
  1312             comm_type);
  1313 }
  1314 
  1315 DYNAMIC_API PEP_STATUS import_key(
  1316         PEP_SESSION session,
  1317         const char *key_data,
  1318         size_t size,
  1319         identity_list **private_keys
  1320     )
  1321 {
  1322     assert(session);
  1323     assert(key_data);
  1324 
  1325     if (!(session && key_data))
  1326         return PEP_ILLEGAL_VALUE;
  1327 
  1328     return session->cryptotech[PEP_crypt_OpenPGP].import_key(session, key_data,
  1329             size, private_keys);
  1330 }
  1331 
  1332 DYNAMIC_API PEP_STATUS recv_key(PEP_SESSION session, const char *pattern)
  1333 {
  1334     assert(session);
  1335     assert(pattern);
  1336 
  1337     if (!(session && pattern))
  1338         return PEP_ILLEGAL_VALUE;
  1339 
  1340     return session->cryptotech[PEP_crypt_OpenPGP].recv_key(session, pattern);
  1341 }
  1342 
  1343 DYNAMIC_API PEP_STATUS send_key(PEP_SESSION session, const char *pattern)
  1344 {
  1345     assert(session);
  1346     assert(pattern);
  1347 
  1348     if (!(session && pattern))
  1349         return PEP_ILLEGAL_VALUE;
  1350 
  1351     return session->cryptotech[PEP_crypt_OpenPGP].send_key(session, pattern);
  1352 }
  1353 
  1354 DYNAMIC_API PEP_STATUS renew_key(
  1355         PEP_SESSION session,
  1356         const char *fpr,
  1357         const timestamp *ts
  1358     )
  1359 {
  1360     assert(session);
  1361     assert(fpr);
  1362 
  1363     if (!(session && fpr))
  1364         return PEP_ILLEGAL_VALUE;
  1365 
  1366     return session->cryptotech[PEP_crypt_OpenPGP].renew_key(session, fpr, ts);
  1367 }
  1368 
  1369 DYNAMIC_API PEP_STATUS revoke_key(
  1370         PEP_SESSION session,
  1371         const char *fpr,
  1372         const char *reason
  1373     )
  1374 {
  1375     assert(session);
  1376     assert(fpr);
  1377 
  1378     if (!(session && fpr))
  1379         return PEP_ILLEGAL_VALUE;
  1380 
  1381     return session->cryptotech[PEP_crypt_OpenPGP].revoke_key(session, fpr,
  1382             reason);
  1383 }
  1384 
  1385 DYNAMIC_API PEP_STATUS key_expired(
  1386         PEP_SESSION session,
  1387         const char *fpr,
  1388         const time_t when,
  1389         bool *expired
  1390     )
  1391 {
  1392     assert(session);
  1393     assert(fpr);
  1394     assert(expired);
  1395 
  1396     if (!(session && fpr && expired))
  1397         return PEP_ILLEGAL_VALUE;
  1398 
  1399     return session->cryptotech[PEP_crypt_OpenPGP].key_expired(session, fpr,
  1400             when, expired);
  1401 }
  1402 
  1403 DYNAMIC_API PEP_STATUS key_revoked(
  1404        PEP_SESSION session,
  1405        const char *fpr,
  1406        bool *revoked
  1407    )
  1408 {
  1409     assert(session);
  1410     assert(fpr);
  1411     assert(revoked);
  1412     
  1413     if (!(session && fpr && revoked))
  1414         return PEP_ILLEGAL_VALUE;
  1415     
  1416     return session->cryptotech[PEP_crypt_OpenPGP].key_revoked(session, fpr,
  1417             revoked);
  1418 }
  1419 
  1420 static void _clean_log_value(char *text)
  1421 {
  1422     if (text) {
  1423         for (char *c = text; *c; c++) {
  1424             if (*c < 32 && *c != '\n')
  1425                 *c = 32;
  1426             else if (*c == '"')
  1427                 *c = '\'';
  1428         }
  1429     }
  1430 }
  1431 
  1432 static char *_concat_string(char *str1, const char *str2, char delim)
  1433 {
  1434     str2 = str2 ? str2 : "";
  1435     size_t len1 = str1 ? strlen(str1) : 0;
  1436     size_t len2 = strlen(str2);
  1437     size_t len = len1 + len2 + 3;
  1438     char * result = realloc(str1, len + 1);
  1439 
  1440     if (result) {
  1441         result[len1] = '"';
  1442         strcpy(result + len1 + 1, str2);
  1443         result[len - 2] = '"';
  1444         result[len - 1] = delim;
  1445         result[len] = 0;
  1446     }
  1447     else {
  1448         free(str1);
  1449     }
  1450 
  1451     return result;
  1452 }
  1453 
  1454 DYNAMIC_API PEP_STATUS get_crashdump_log(
  1455         PEP_SESSION session,
  1456         int maxlines,
  1457         char **logdata
  1458     )
  1459 {
  1460     PEP_STATUS status = PEP_STATUS_OK;
  1461     char *_logdata= NULL;
  1462 
  1463     assert(session);
  1464     assert(maxlines >= 0 && maxlines <= CRASHDUMP_MAX_LINES);
  1465     assert(logdata);
  1466 
  1467     if (!(session && logdata && maxlines >= 0 && maxlines <=
  1468             CRASHDUMP_MAX_LINES))
  1469         return PEP_ILLEGAL_VALUE;
  1470 
  1471     *logdata = NULL;
  1472 
  1473     int limit = maxlines ? maxlines : CRASHDUMP_DEFAULT_LINES;
  1474     const char *timestamp = NULL;
  1475     const char *title = NULL;
  1476     const char *entity = NULL;
  1477     const char *desc = NULL;
  1478     const char *comment = NULL;
  1479 
  1480     sqlite3_reset(session->crashdump);
  1481     sqlite3_bind_int(session->crashdump, 1, limit);
  1482 
  1483     int result;
  1484 
  1485     do {
  1486         result = sqlite3_step(session->crashdump);
  1487         switch (result) {
  1488         case SQLITE_ROW:
  1489             timestamp = (const char *) sqlite3_column_text(session->crashdump,
  1490                     0);
  1491             title   = (const char *) sqlite3_column_text(session->crashdump,
  1492                     1);
  1493             entity  = (const char *) sqlite3_column_text(session->crashdump,
  1494                     2);
  1495             desc    = (const char *) sqlite3_column_text(session->crashdump,
  1496                     3);
  1497             comment = (const char *) sqlite3_column_text(session->crashdump,
  1498                     4);
  1499 
  1500             _logdata = _concat_string(_logdata, timestamp, ',');
  1501             if (_logdata == NULL)
  1502                 goto enomem;
  1503 
  1504             _logdata = _concat_string(_logdata, title, ',');
  1505             if (_logdata == NULL)
  1506                 goto enomem;
  1507 
  1508             _logdata = _concat_string(_logdata, entity, ',');
  1509             if (_logdata == NULL)
  1510                 goto enomem;
  1511 
  1512             _logdata = _concat_string(_logdata, desc, ',');
  1513             if (_logdata == NULL)
  1514                 goto enomem;
  1515 
  1516             _logdata = _concat_string(_logdata, comment, '\n');
  1517             if (_logdata == NULL)
  1518                 goto enomem;
  1519 
  1520             _clean_log_value(_logdata);
  1521             break;
  1522 
  1523         case SQLITE_DONE:
  1524             break;
  1525 
  1526         default:
  1527             status = PEP_UNKNOWN_ERROR;
  1528             result = SQLITE_DONE;
  1529         }
  1530     } while (result != SQLITE_DONE);
  1531 
  1532     sqlite3_reset(session->crashdump);
  1533     if (status == PEP_STATUS_OK)
  1534         *logdata = _logdata;
  1535 
  1536     goto the_end;
  1537 
  1538 enomem:
  1539     status = PEP_OUT_OF_MEMORY;
  1540 
  1541 the_end:
  1542     return status;
  1543 }
  1544 
  1545 DYNAMIC_API PEP_STATUS get_languagelist(
  1546         PEP_SESSION session,
  1547         char **languages
  1548     )
  1549 {
  1550     PEP_STATUS status = PEP_STATUS_OK;
  1551     char *_languages= NULL;
  1552 
  1553     assert(session);
  1554     assert(languages);
  1555 
  1556     if (!(session && languages))
  1557         return PEP_ILLEGAL_VALUE;
  1558 
  1559     *languages = NULL;
  1560 
  1561     const char *lang = NULL;
  1562     const char *name = NULL;
  1563     const char *phrase = NULL;
  1564 
  1565     sqlite3_reset(session->languagelist);
  1566 
  1567     int result;
  1568 
  1569     do {
  1570         result = sqlite3_step(session->languagelist);
  1571         switch (result) {
  1572         case SQLITE_ROW:
  1573             lang = (const char *) sqlite3_column_text(session->languagelist,
  1574                     0);
  1575             name = (const char *) sqlite3_column_text(session->languagelist,
  1576                     1);
  1577             phrase = (const char *) sqlite3_column_text(session->languagelist,
  1578                     2);
  1579 
  1580             _languages = _concat_string(_languages, lang, ',');
  1581             if (_languages == NULL)
  1582                 goto enomem;
  1583 
  1584             _languages = _concat_string(_languages, name, ',');
  1585             if (_languages == NULL)
  1586                 goto enomem;
  1587 
  1588             _languages = _concat_string(_languages, phrase, '\n');
  1589             if (_languages == NULL)
  1590                 goto enomem;
  1591 
  1592             break;
  1593 
  1594         case SQLITE_DONE:
  1595             break;
  1596 
  1597         default:
  1598             status = PEP_UNKNOWN_ERROR;
  1599             result = SQLITE_DONE;
  1600         }
  1601     } while (result != SQLITE_DONE);
  1602 
  1603     sqlite3_reset(session->languagelist);
  1604     if (status == PEP_STATUS_OK)
  1605         *languages = _languages;
  1606 
  1607     goto the_end;
  1608 
  1609 enomem:
  1610     status = PEP_OUT_OF_MEMORY;
  1611 
  1612 the_end:
  1613     return status;
  1614 }
  1615 
  1616 DYNAMIC_API PEP_STATUS get_phrase(
  1617         PEP_SESSION session,
  1618         const char *lang,
  1619         int phrase_id,
  1620         char **phrase
  1621     )
  1622 {
  1623     PEP_STATUS status = PEP_STATUS_OK;
  1624 
  1625     assert(session && lang && lang[0] && lang[1] && lang[2] == 0 && phrase);
  1626     if (!(session && lang && lang[0] && lang[1] && lang[2] == 0 && phrase))
  1627         return PEP_ILLEGAL_VALUE;
  1628 
  1629     *phrase = NULL;
  1630 
  1631     sqlite3_reset(session->i18n_token);
  1632     sqlite3_bind_text(session->i18n_token, 1, lang, -1, SQLITE_STATIC);
  1633     sqlite3_bind_int(session->i18n_token, 2, phrase_id);
  1634 
  1635     const char *_phrase = NULL;
  1636     int result;
  1637 
  1638     result = sqlite3_step(session->i18n_token);
  1639     switch (result) {
  1640     case SQLITE_ROW:
  1641         _phrase = (const char *) sqlite3_column_text(session->i18n_token, 0);
  1642         break;
  1643 
  1644     case SQLITE_DONE:
  1645         status = PEP_PHRASE_NOT_FOUND;
  1646         break;
  1647 
  1648     default:
  1649         status = PEP_UNKNOWN_ERROR;
  1650     }
  1651 
  1652     if (status == PEP_STATUS_OK) {
  1653         *phrase = strdup(_phrase);
  1654         if (*phrase == NULL)
  1655             goto enomem;
  1656     }
  1657 
  1658     sqlite3_reset(session->i18n_token);
  1659     goto the_end;
  1660 
  1661 enomem:
  1662     status = PEP_OUT_OF_MEMORY;
  1663 
  1664 the_end:
  1665     return status;
  1666 }
  1667 
  1668 DYNAMIC_API PEP_STATUS sequence_value(
  1669         PEP_SESSION session,
  1670         const char *name,
  1671         int32_t *value
  1672     )
  1673 {
  1674     PEP_STATUS status = PEP_STATUS_OK;
  1675     int result;
  1676 
  1677     assert(session);
  1678     assert(name);
  1679     assert(value);
  1680 
  1681     if (!(session && name && value))
  1682         return PEP_ILLEGAL_VALUE;
  1683 
  1684     *value = 0;
  1685 
  1686     sqlite3_reset(session->sequence_value1);
  1687     sqlite3_bind_text(session->sequence_value1, 1, name, -1, SQLITE_STATIC);
  1688     result = sqlite3_step(session->sequence_value1);
  1689     assert(result == SQLITE_DONE);
  1690     sqlite3_reset(session->sequence_value1);
  1691     if (result != SQLITE_DONE) {
  1692         status = PEP_UNKNOWN_ERROR;
  1693     }
  1694     else {
  1695         sqlite3_reset(session->sequence_value2);
  1696         sqlite3_bind_text(session->sequence_value2, 1, name, -1,
  1697                 SQLITE_STATIC);
  1698         result = sqlite3_step(session->sequence_value2);
  1699         switch (result) {
  1700             case SQLITE_ROW: {
  1701                 int32_t _value = (int32_t)
  1702                         sqlite3_column_int64(session->sequence_value2, 0);
  1703                 *value = _value;
  1704                 break;
  1705             }
  1706             default:
  1707                 status = PEP_UNKNOWN_ERROR;
  1708         }
  1709         sqlite3_reset(session->sequence_value2);
  1710     }
  1711     return status;
  1712 }
  1713 
  1714 DYNAMIC_API PEP_STATUS set_revoked(
  1715        PEP_SESSION session,
  1716        const char *revoked_fpr,
  1717        const char *replacement_fpr,
  1718        const uint64_t revocation_date
  1719     )
  1720 {
  1721     PEP_STATUS status = PEP_STATUS_OK;
  1722     
  1723     assert(session &&
  1724            revoked_fpr && revoked_fpr[0] &&
  1725            replacement_fpr && replacement_fpr[0]
  1726           );
  1727     
  1728     if (!(session &&
  1729           revoked_fpr && revoked_fpr[0] &&
  1730           replacement_fpr && replacement_fpr[0]
  1731          ))
  1732         return PEP_ILLEGAL_VALUE;
  1733     
  1734     sqlite3_reset(session->set_revoked);
  1735     sqlite3_bind_text(session->set_revoked, 1, revoked_fpr, -1, SQLITE_STATIC);
  1736     sqlite3_bind_text(session->set_revoked, 2, replacement_fpr, -1,
  1737             SQLITE_STATIC);
  1738     sqlite3_bind_int64(session->set_revoked, 3, revocation_date);
  1739 
  1740     int result;
  1741     
  1742     result = sqlite3_step(session->set_revoked);
  1743     switch (result) {
  1744         case SQLITE_DONE:
  1745             status = PEP_STATUS_OK;
  1746             break;
  1747             
  1748         default:
  1749             status = PEP_UNKNOWN_ERROR;
  1750     }
  1751     
  1752     sqlite3_reset(session->set_revoked);
  1753     return status;
  1754 }
  1755 
  1756 DYNAMIC_API PEP_STATUS get_revoked(
  1757         PEP_SESSION session,
  1758         const char *fpr,
  1759         char **revoked_fpr,
  1760         uint64_t *revocation_date
  1761     )
  1762 {
  1763     PEP_STATUS status = PEP_STATUS_OK;
  1764 
  1765     assert(session &&
  1766            revoked_fpr &&
  1767            fpr && fpr[0]
  1768           );
  1769     
  1770     if (!(session &&
  1771            revoked_fpr &&
  1772            fpr && fpr[0]
  1773           ))
  1774         return PEP_ILLEGAL_VALUE;
  1775 
  1776     *revoked_fpr = NULL;
  1777     *revocation_date = 0;
  1778 
  1779     sqlite3_reset(session->get_revoked);
  1780     sqlite3_bind_text(session->get_revoked, 1, fpr, -1, SQLITE_STATIC);
  1781 
  1782     int result;
  1783     
  1784     result = sqlite3_step(session->get_revoked);
  1785     switch (result) {
  1786         case SQLITE_ROW: {
  1787             *revoked_fpr = strdup((const char *)
  1788                     sqlite3_column_text(session->get_revoked, 0));
  1789             if(*revoked_fpr)
  1790                 *revocation_date = sqlite3_column_int64(session->get_revoked,
  1791                         1);
  1792             else
  1793                 status = PEP_OUT_OF_MEMORY;
  1794 
  1795             break;
  1796         }
  1797         default:
  1798             status = PEP_CANNOT_FIND_IDENTITY;
  1799     }
  1800 
  1801     sqlite3_reset(session->get_revoked);
  1802 
  1803     return status;
  1804 }
  1805 
  1806 PEP_STATUS key_created(
  1807         PEP_SESSION session,
  1808         const char *fpr,
  1809         time_t *created
  1810     )
  1811 {
  1812     assert(session && fpr && created);
  1813     if (!(session && fpr && created))
  1814         return PEP_ILLEGAL_VALUE;
  1815 
  1816     return session->cryptotech[PEP_crypt_OpenPGP].key_created(session, fpr,
  1817             created);
  1818 }
  1819 
  1820 DYNAMIC_API PEP_STATUS reset_peptest_hack(PEP_SESSION session)
  1821 {
  1822     assert(session);
  1823 
  1824     if (!session)
  1825         return PEP_ILLEGAL_VALUE;
  1826 
  1827     int int_result = sqlite3_exec(
  1828         session->db,
  1829         "delete from identity where address like '%@peptest.ch' ;",
  1830         NULL,
  1831         NULL,
  1832         NULL
  1833     );
  1834     assert(int_result == SQLITE_OK);
  1835 
  1836     return PEP_STATUS_OK;
  1837 }
  1838