src/keymanagement.c
author Krista Bennett <krista@pep-project.org>
Mon, 10 Sep 2018 15:09:45 +0200
branchENGINE-398
changeset 2936 d5e80c521be1
parent 2917 51f4afe41dcb
child 2955 3b2500a15709
permissions -rw-r--r--
ENGINE-398: removed key_reset functionality from key_mistrust; need to adjust a test or two.
     1 // This file is under GNU General Public License 3.0
     2 // see LICENSE.txt
     3 
     4 #include "platform.h"
     5 
     6 #include <string.h>
     7 #include <stdio.h>
     8 #include <stdlib.h>
     9 #include <assert.h>
    10 #include <ctype.h>
    11 
    12 #include "pEp_internal.h"
    13 #include "keymanagement.h"
    14 
    15 #include "sync_fsm.h"
    16 #include "blacklist.h"
    17 
    18 static bool key_matches_address(PEP_SESSION session, const char* address,
    19                                 const char* fpr) {
    20     if (!session || !address || !fpr)
    21         return false;
    22     
    23     bool retval = false;
    24     stringlist_t *keylist = NULL;
    25     PEP_STATUS status = find_keys(session, address, &keylist);
    26     if (status == PEP_STATUS_OK && keylist) {
    27         stringlist_t* curr = keylist;
    28         while (curr) {
    29             if (curr->value) {
    30                 if (strcasecmp(curr->value, fpr)) {
    31                     retval = true;
    32                     break;
    33                 }
    34             }
    35             curr = curr->next;
    36         }
    37     }
    38     
    39     free_stringlist(keylist);
    40     return retval;                             
    41 }
    42 
    43 PEP_STATUS elect_pubkey(
    44         PEP_SESSION session, pEp_identity * identity, bool check_blacklist
    45     )
    46 {
    47     PEP_STATUS status;
    48     stringlist_t *keylist = NULL;
    49     char *_fpr = "";
    50     identity->comm_type = PEP_ct_unknown;
    51 
    52     status = find_keys(session, identity->address, &keylist);
    53     assert(status != PEP_OUT_OF_MEMORY);
    54     if (status == PEP_OUT_OF_MEMORY)
    55         return PEP_OUT_OF_MEMORY;
    56     
    57     if (!keylist || !keylist->value)
    58         identity->comm_type = PEP_ct_key_not_found;    
    59     else {
    60         stringlist_t *_keylist;
    61         for (_keylist = keylist; _keylist && _keylist->value; _keylist = _keylist->next) {
    62             PEP_comm_type _comm_type_key;
    63 
    64             status = get_key_rating(session, _keylist->value, &_comm_type_key);
    65             assert(status != PEP_OUT_OF_MEMORY);
    66             if (status == PEP_OUT_OF_MEMORY) {
    67                 free_stringlist(keylist);
    68                 return PEP_OUT_OF_MEMORY;
    69             }
    70 
    71             if (_comm_type_key != PEP_ct_compromised &&
    72                 _comm_type_key != PEP_ct_unknown)
    73             {
    74                 if (identity->comm_type == PEP_ct_unknown ||
    75                     _comm_type_key > identity->comm_type)
    76                 {
    77                     bool blacklisted = false;
    78                     bool mistrusted = false;
    79                     status = is_mistrusted_key(session, _keylist->value, &mistrusted);
    80                     if (status == PEP_STATUS_OK && check_blacklist)
    81                         status = blacklist_is_listed(session, _keylist->value, &blacklisted);
    82                     if (status == PEP_STATUS_OK && !mistrusted && !blacklisted) {
    83                         identity->comm_type = _comm_type_key;
    84                         _fpr = _keylist->value;
    85                     }
    86                 }
    87             }
    88         }
    89     }
    90     free(identity->fpr);
    91 
    92     if (!_fpr || _fpr[0] == '\0')
    93         identity->fpr = NULL;
    94     else {    
    95         identity->fpr = strdup(_fpr);
    96         if (identity->fpr == NULL) {
    97             free_stringlist(keylist);
    98             return PEP_OUT_OF_MEMORY;
    99         }
   100     }
   101     
   102     free_stringlist(keylist);
   103     return PEP_STATUS_OK;
   104 }
   105 
   106 static PEP_STATUS validate_fpr(PEP_SESSION session, 
   107                                pEp_identity* ident,
   108                                bool check_blacklist) {
   109     
   110     PEP_STATUS status = PEP_STATUS_OK;
   111     
   112     if (!session || !ident || !ident->fpr || !ident->fpr[0])
   113         return PEP_ILLEGAL_VALUE;    
   114         
   115     char* fpr = ident->fpr;
   116     
   117     bool has_private = false;
   118     
   119     if (ident->me) {
   120         status = contains_priv_key(session, fpr, &has_private);
   121         if (status != PEP_STATUS_OK || !has_private)
   122             return PEP_KEY_UNSUITABLE;
   123     }
   124     
   125     status = get_trust(session, ident);
   126     if (status != PEP_STATUS_OK)
   127         ident->comm_type = PEP_ct_unknown;
   128             
   129     PEP_comm_type ct = ident->comm_type;
   130 
   131     if (ct == PEP_ct_unknown) {
   132         // If status is bad, it's ok, we get the rating
   133         // we should use then (PEP_ct_unknown)
   134         get_key_rating(session, fpr, &ct);
   135         ident->comm_type = ct;
   136     }
   137     
   138     bool pep_user = false;
   139     
   140     is_pep_user(session, ident, &pep_user);
   141 
   142     if (pep_user) {
   143         switch (ct) {
   144             case PEP_ct_OpenPGP:
   145             case PEP_ct_OpenPGP_unconfirmed:
   146                 ct += 0x47; // difference between PEP and OpenPGP values;
   147                 ident->comm_type = ct;
   148                 break;
   149             default:
   150                 break;
   151         }
   152     }
   153     
   154     bool revoked, expired;
   155     bool blacklisted = false;
   156     
   157     status = key_revoked(session, fpr, &revoked);    
   158         
   159     if (status != PEP_STATUS_OK) {
   160         return status;
   161     }
   162     
   163     if (!revoked) {
   164         time_t exp_time = (ident->me ? 
   165                            time(NULL) + (7*24*3600) : time(NULL));
   166                            
   167         status = key_expired(session, fpr, 
   168                              exp_time,
   169                              &expired);
   170                              
   171         assert(status == PEP_STATUS_OK);
   172         if (status != PEP_STATUS_OK)
   173             return status;
   174 
   175         if (check_blacklist && IS_PGP_CT(ct) &&
   176             !ident->me) {
   177             status = blacklist_is_listed(session, 
   178                                          fpr, 
   179                                          &blacklisted);
   180                                          
   181             if (status != PEP_STATUS_OK)
   182                 return status;
   183         }
   184     }
   185             
   186     if (ident->me && (ct >= PEP_ct_strong_but_unconfirmed) && !revoked && expired) {
   187         // extend key
   188         timestamp *ts = new_timestamp(time(NULL) + KEY_EXPIRE_DELTA);
   189         status = renew_key(session, fpr, ts);
   190         free_timestamp(ts);
   191 
   192         if (status == PEP_STATUS_OK) {
   193             // if key is valid (second check because pEp key might be extended above)
   194             //      Return fpr        
   195             status = key_expired(session, fpr, time(NULL), &expired);            
   196             if (status != PEP_STATUS_OK) {
   197                  ident->comm_type = PEP_ct_key_expired;
   198                  return status;
   199              }
   200             // communicate key(?)
   201         }        
   202     }
   203      
   204     if (revoked) 
   205         ct = PEP_ct_key_revoked;
   206     else if (expired)
   207         ct = PEP_ct_key_expired;        
   208     else if (blacklisted) { // never true for .me
   209         ident->comm_type = ct = PEP_ct_key_not_found;
   210         free(ident->fpr);
   211             ident->fpr = strdup("");
   212         status = PEP_KEY_BLACKLISTED;
   213     }
   214     
   215     switch (ct) {
   216         case PEP_ct_key_expired:
   217         case PEP_ct_key_revoked:
   218         case PEP_ct_key_b0rken:
   219             // delete key from being default key for all users/identities
   220             status = remove_fpr_as_default(session, fpr);
   221             status = update_trust_for_fpr(session, 
   222                                           fpr, 
   223                                           ct);
   224         case PEP_ct_mistrusted:                                  
   225             free(ident->fpr);
   226             ident->fpr = NULL;
   227             ident->comm_type = ct;            
   228             status = PEP_KEY_UNSUITABLE;
   229         default:
   230             break;
   231     }            
   232 
   233     return status;
   234 }
   235 
   236 PEP_STATUS get_all_keys_for_user(PEP_SESSION session, 
   237                                  const char* user_id,
   238                                  stringlist_t** keys) {
   239 
   240     if (!session || EMPTYSTR(user_id) || !keys)
   241         return PEP_ILLEGAL_VALUE;
   242         
   243     PEP_STATUS status = PEP_STATUS_OK;
   244         
   245     *keys = NULL;
   246     stringlist_t* _kl = NULL;
   247     
   248     sqlite3_reset(session->get_all_keys_for_user);
   249     sqlite3_bind_text(session->get_all_keys_for_user, 1, user_id, -1, SQLITE_STATIC);
   250 
   251     int result = -1;
   252     
   253     while ((result = sqlite3_step(session->get_all_keys_for_user)) == SQLITE_ROW) {
   254         const char* keyres = (const char *) sqlite3_column_text(session->get_all_keys_for_user, 0);
   255         if (keyres) {
   256             if (_kl)
   257                 stringlist_add(_kl, keyres);
   258             else
   259                 _kl = new_stringlist(keyres);
   260         }
   261     }
   262     
   263     if (!_kl)
   264         return PEP_KEY_NOT_FOUND;
   265         
   266     *keys = _kl;
   267     
   268     sqlite3_reset(session->get_all_keys_for_user);
   269 
   270     return status;
   271 }
   272 
   273 PEP_STATUS get_user_default_key(PEP_SESSION session, const char* user_id,
   274                                 char** default_key) {
   275     assert(session);
   276     assert(user_id);
   277     
   278     if (!session || !user_id)
   279         return PEP_ILLEGAL_VALUE;
   280 
   281     PEP_STATUS status = PEP_STATUS_OK;
   282             
   283     // try to get default key for user_data
   284     sqlite3_reset(session->get_user_default_key);
   285     sqlite3_bind_text(session->get_user_default_key, 1, user_id, 
   286                       -1, SQLITE_STATIC);
   287     
   288     const int result = sqlite3_step(session->get_user_default_key);
   289     char* user_fpr = NULL;
   290     if (result == SQLITE_ROW) {
   291         const char* u_fpr =
   292             (char *) sqlite3_column_text(session->get_user_default_key, 0);
   293         if (u_fpr)
   294             user_fpr = strdup(u_fpr);
   295     }
   296     else
   297         status = PEP_GET_KEY_FAILED;
   298         
   299     sqlite3_reset(session->get_user_default_key);
   300     
   301     *default_key = user_fpr;
   302     return status;     
   303 }
   304 
   305 // Only call on retrieval of previously stored identity!
   306 // Also, we presume that if the stored_identity was sent in
   307 // without an fpr, there wasn't one in the trust DB for this
   308 // identity.
   309 PEP_STATUS get_valid_pubkey(PEP_SESSION session,
   310                          pEp_identity* stored_identity,
   311                          bool* is_identity_default,
   312                          bool* is_user_default,
   313                          bool* is_address_default,
   314                          bool check_blacklist) {
   315     
   316     PEP_STATUS status = PEP_STATUS_OK;
   317 
   318     if (!stored_identity || EMPTYSTR(stored_identity->user_id)
   319         || !is_identity_default || !is_user_default || !is_address_default)
   320         return PEP_ILLEGAL_VALUE;
   321         
   322     *is_identity_default = *is_user_default = *is_address_default = false;
   323 
   324     PEP_comm_type first_reject_comm_type = PEP_ct_key_not_found;
   325     PEP_STATUS first_reject_status = PEP_KEY_NOT_FOUND;
   326     
   327     char* stored_fpr = stored_identity->fpr;
   328     // Input: stored identity retrieved from database
   329     // if stored identity contains a default key
   330     if (!EMPTYSTR(stored_fpr)) {
   331         status = validate_fpr(session, stored_identity, check_blacklist);    
   332         if (status == PEP_STATUS_OK && !EMPTYSTR(stored_identity->fpr)) {
   333             *is_identity_default = *is_address_default = true;
   334             return status;
   335         }
   336         else if (status != PEP_KEY_NOT_FOUND) {
   337             first_reject_status = status;
   338             first_reject_comm_type = stored_identity->comm_type;
   339         }
   340     }
   341     // if no valid default stored identity key found
   342     free(stored_identity->fpr);
   343     stored_identity->fpr = NULL;
   344     
   345     char* user_fpr = NULL;
   346     status = get_user_default_key(session, stored_identity->user_id, &user_fpr);
   347     
   348     if (!EMPTYSTR(user_fpr)) {             
   349         // There exists a default key for user, so validate
   350         stored_identity->fpr = user_fpr;
   351         status = validate_fpr(session, stored_identity, check_blacklist);
   352         if (status == PEP_STATUS_OK && stored_identity->fpr) {
   353             *is_user_default = true;
   354             *is_address_default = key_matches_address(session, 
   355                                                       stored_identity->address,
   356                                                       stored_identity->fpr);
   357             return status;
   358         }        
   359         else if (status != PEP_KEY_NOT_FOUND && first_reject_status != PEP_KEY_NOT_FOUND) {
   360             first_reject_status = status;
   361             first_reject_comm_type = stored_identity->comm_type;
   362         }
   363     }
   364     
   365     status = elect_pubkey(session, stored_identity, check_blacklist);
   366     if (status == PEP_STATUS_OK) {
   367         if (!EMPTYSTR(stored_identity->fpr))
   368             validate_fpr(session, stored_identity, false); // blacklist already filtered of needed
   369     }    
   370     else if (status != PEP_KEY_NOT_FOUND && first_reject_status != PEP_KEY_NOT_FOUND) {
   371         first_reject_status = status;
   372         first_reject_comm_type = stored_identity->comm_type;
   373     }
   374     
   375     switch (stored_identity->comm_type) {
   376         case PEP_ct_key_revoked:
   377         case PEP_ct_key_b0rken:
   378         case PEP_ct_key_expired:
   379         case PEP_ct_compromised:
   380         case PEP_ct_mistrusted:
   381             // this only happens when it's all there is
   382             status = first_reject_status;
   383             free(stored_identity->fpr);
   384             stored_identity->fpr = NULL;
   385             stored_identity->comm_type = first_reject_comm_type;
   386             break;    
   387         default:
   388             if (check_blacklist && status == PEP_KEY_BLACKLISTED) {
   389                 free(stored_identity->fpr);
   390                 stored_identity->fpr = NULL;
   391                 stored_identity->comm_type = PEP_ct_key_not_found;
   392             }
   393             break;
   394     }
   395     return status;
   396 }
   397 
   398 static void transfer_ident_lang_and_flags(pEp_identity* new_ident,
   399                                           pEp_identity* stored_ident) {
   400     if (new_ident->lang[0] == 0) {
   401       new_ident->lang[0] = stored_ident->lang[0];
   402       new_ident->lang[1] = stored_ident->lang[1];
   403       new_ident->lang[2] = 0;
   404     }
   405 
   406     new_ident->flags = stored_ident->flags;
   407     new_ident->me = new_ident->me || stored_ident->me;
   408 }
   409 
   410 static void adjust_pep_trust_status(PEP_SESSION session, pEp_identity* identity) {
   411     assert(session);
   412     assert(identity);
   413     
   414     if (identity->comm_type < PEP_ct_strong_but_unconfirmed ||
   415         (identity->comm_type | PEP_ct_confirmed) == PEP_ct_pEp)
   416         return;
   417     
   418     bool pep_user;
   419     
   420     is_pep_user(session, identity, &pep_user);
   421     
   422     if (pep_user) {
   423         PEP_comm_type confirmation_status = identity->comm_type & PEP_ct_confirmed;
   424         identity->comm_type = PEP_ct_pEp_unconfirmed | confirmation_status;    
   425     }
   426 }
   427 
   428 
   429 static PEP_STATUS prepare_updated_identity(PEP_SESSION session,
   430                                                  pEp_identity* return_id,
   431                                                  pEp_identity* stored_ident,
   432                                                  bool store) {
   433     
   434     if (!session || !return_id || !stored_ident)
   435         return PEP_ILLEGAL_VALUE;
   436     
   437     PEP_STATUS status;
   438     
   439     bool is_identity_default, is_user_default, is_address_default;
   440     status = get_valid_pubkey(session, stored_ident,
   441                                 &is_identity_default,
   442                                 &is_user_default,
   443                                 &is_address_default,
   444                               false);
   445                                 
   446     if (status == PEP_STATUS_OK && stored_ident->fpr && *(stored_ident->fpr) != '\0') {
   447     // set identity comm_type from trust db (user_id, FPR)
   448         status = get_trust(session, stored_ident);
   449         if (status == PEP_CANNOT_FIND_IDENTITY || stored_ident->comm_type == PEP_ct_unknown) {
   450             // This is OK - there is no trust DB entry, but we
   451             // found a key. We won't store this, but we'll
   452             // use it.
   453             PEP_comm_type ct = PEP_ct_unknown;
   454             status = get_key_rating(session, stored_ident->fpr, &ct);
   455             stored_ident->comm_type = ct;
   456         }
   457     }
   458     else {
   459         if (stored_ident->comm_type == PEP_ct_unknown)
   460             stored_ident->comm_type = PEP_ct_key_not_found;
   461     }
   462     free(return_id->fpr);
   463     return_id->fpr = NULL;
   464     if (status == PEP_STATUS_OK && !EMPTYSTR(stored_ident->fpr))
   465         return_id->fpr = strdup(stored_ident->fpr);
   466         
   467     return_id->comm_type = stored_ident->comm_type;
   468                     
   469     // We patch the DB with the input username, but if we didn't have
   470     // one, we pull it out of storage if available.
   471     // (also, if the input username is "anonymous" and there exists
   472     //  a DB username, we replace)
   473     if (!EMPTYSTR(stored_ident->username)) {
   474         if (!EMPTYSTR(return_id->username) && 
   475             (strcasecmp(return_id->username, return_id->address) == 0)) {
   476             free(return_id->username);
   477             return_id->username = NULL;
   478         }
   479         if (EMPTYSTR(return_id->username)) {
   480             free(return_id->username);
   481             return_id->username = strdup(stored_ident->username);
   482         }
   483     }
   484     else {
   485         if (EMPTYSTR(return_id->username))
   486             return_id->username = strdup(return_id->address);
   487     }
   488     
   489     return_id->me = stored_ident->me;
   490     
   491     // FIXME: Do we ALWAYS do this? We probably should...
   492     if (EMPTYSTR(return_id->user_id)) {
   493         free(return_id->user_id);
   494         return_id->user_id = strdup(stored_ident->user_id);
   495     } 
   496     
   497     adjust_pep_trust_status(session, return_id);
   498    
   499     // Call set_identity() to store
   500     if ((is_identity_default || is_user_default) &&
   501          is_address_default) {                 
   502          // if we got an fpr which is default for either user
   503          // or identity AND is valid for this address, set in DB
   504          // as default
   505          status = set_identity(session, return_id);
   506     }
   507     else {
   508         // Store without default fpr/ct, but return the fpr and ct 
   509         // for current use
   510         char* save_fpr = return_id->fpr;
   511         PEP_comm_type save_ct = return_id->comm_type;
   512         return_id->fpr = NULL;
   513         return_id->comm_type = PEP_ct_unknown;
   514         PEP_STATUS save_status = status;
   515         status = set_identity(session, return_id);
   516         if (save_status != PEP_STATUS_OK)
   517             status = save_status;
   518         return_id->fpr = save_fpr;
   519         return_id->comm_type = save_ct;
   520     }
   521     
   522     transfer_ident_lang_and_flags(return_id, stored_ident);
   523     
   524     if (return_id->comm_type == PEP_ct_unknown)
   525         return_id->comm_type = PEP_ct_key_not_found;
   526     
   527     return status;
   528 }
   529 
   530 DYNAMIC_API PEP_STATUS update_identity(
   531         PEP_SESSION session, pEp_identity * identity
   532     )
   533 {
   534     PEP_STATUS status;
   535 
   536     assert(session);
   537     assert(identity);
   538     assert(!EMPTYSTR(identity->address));
   539 
   540     if (!(session && identity && !EMPTYSTR(identity->address)))
   541         return PEP_ILLEGAL_VALUE;
   542 
   543     char* default_own_id = NULL;
   544     status = get_default_own_userid(session, &default_own_id);    
   545 
   546     // Is this me, temporary or not? If so, BAIL.
   547     if (identity->me || 
   548        (default_own_id && identity->user_id && (strcmp(default_own_id, identity->user_id) == 0))) 
   549     {
   550         free(default_own_id);
   551         return PEP_ILLEGAL_VALUE;
   552     }
   553 
   554     // We have, at least, an address.
   555     // Retrieve stored identity information!    
   556     pEp_identity* stored_ident = NULL;
   557 
   558     if (!EMPTYSTR(identity->user_id)) {            
   559         // (we're gonna update the trust/fpr anyway, so we use the no-fpr-from-trust-db variant)
   560         //      * do get_identity() to retrieve stored identity information
   561         status = get_identity_without_trust_check(session, identity->address, identity->user_id, &stored_ident);
   562 
   563         // Before we start - if there was no stored identity, we should check to make sure we don't
   564         // have a stored identity with a temporary user_id that differs from the input user_id. This
   565         // happens in multithreaded environments sometimes.
   566         if (!stored_ident) {
   567             identity_list* id_list = NULL;
   568             status = get_identities_by_address(session, identity->address, &id_list);
   569 
   570             if (id_list) {
   571                 identity_list* id_curr = id_list;
   572                 while (id_curr) {
   573                     pEp_identity* this_id = id_curr->ident;
   574                     if (this_id) {
   575                         char* this_uid = this_id->user_id;
   576                         if (this_uid && (strstr(this_uid, "TOFU_") == this_uid)) {
   577                             // FIXME: should we also be fixing pEp_own_userId in this
   578                             // function here?
   579                             
   580                             // if usernames match, we replace the userid. Or if the temp username
   581                             // is anonymous.
   582                             // FIXME: do we need to create an address match function which
   583                             // matches the whole dot-and-case rigamarole from 
   584                             if (EMPTYSTR(this_id->username) ||
   585                                 strcasecmp(this_id->username, this_id->address) == 0 ||
   586                                 (identity->username && 
   587                                  strcasecmp(identity->username, 
   588                                             this_id->username) == 0)) {
   589                                 
   590                                 // Ok, we have a temp ID. We have to replace this
   591                                 // with the real ID.
   592                                 status = replace_userid(session, 
   593                                                         this_uid, 
   594                                                         identity->user_id);
   595                                 if (status != PEP_STATUS_OK) {
   596                                     free_identity_list(id_list);
   597                                     free(default_own_id);
   598                                     return status;
   599                                 }
   600                                     
   601                                 free(this_uid);
   602                                 this_uid = NULL;
   603                                 
   604                                 // Reflect the change we just made to the DB
   605                                 this_id->user_id = strdup(identity->user_id);
   606                                 stored_ident = this_id;
   607                                 // FIXME: free list.
   608                                 break;                                
   609                             }                            
   610                         } 
   611                     }
   612                     id_curr = id_curr->next;
   613                 }
   614             }
   615         } 
   616                 
   617         if (status == PEP_STATUS_OK && stored_ident) { 
   618             //  * if identity available
   619             //      * patch it with username
   620             //          (note: this will happen when 
   621             //           setting automatically below...)
   622             //      * elect valid key for identity
   623             //    * if valid key exists
   624             //        * set return value's fpr
   625             status = prepare_updated_identity(session,
   626                                               identity,
   627                                               stored_ident, true);
   628         }
   629         //  * else (identity unavailable)
   630         else {
   631             status = PEP_STATUS_OK;
   632 
   633             // FIXME: We may need to roll this back.
   634             // FIXME: change docs if we don't
   635             //  if we only have user_id and address and identity not available
   636             //      * return error status (identity not found)
   637             if (EMPTYSTR(identity->username)) {
   638                 free(identity->username);
   639                 identity->username = strdup(identity->address);
   640             }
   641             
   642             // Otherwise, if we had user_id, address, and username:
   643             //    * create identity with user_id, address, username
   644             //      (this is the input id without the fpr + comm type!)
   645 
   646             if (status == PEP_STATUS_OK) {
   647                 elect_pubkey(session, identity, false);
   648             }
   649                         
   650             //    * We've already checked and retrieved
   651             //      any applicable temporary identities above. If we're 
   652             //      here, none of them fit.
   653             //    * call set_identity() to store
   654             if (status == PEP_STATUS_OK) {
   655                 // FIXME: Do we set if we had to copy in the address?
   656                 adjust_pep_trust_status(session, identity);
   657                 status = set_identity(session, identity);
   658             }
   659             //  * Return: created identity
   660         }        
   661     }
   662     else if (!EMPTYSTR(identity->username)) {
   663         /*
   664          * Temporary identity information with username supplied
   665             * Input: address, username (no others)
   666          */
   667          
   668         //  * See if there is an own identity that uses this address. If so, we'll
   669         //    prefer that
   670         stored_ident = NULL;
   671         
   672         if (default_own_id) {
   673             status = get_identity(session, 
   674                                   identity->address, 
   675                                   default_own_id, 
   676                                   &stored_ident);
   677         }
   678         // If there isn't an own identity, search for a non-temp stored ident
   679         // with this address.                      
   680         if (status == PEP_CANNOT_FIND_IDENTITY || !stored_ident) { 
   681  
   682             identity_list* id_list = NULL;
   683             status = get_identities_by_address(session, identity->address, &id_list);
   684 
   685             if (id_list) {
   686                 identity_list* id_curr = id_list;
   687                 while (id_curr) {
   688                     pEp_identity* this_id = id_curr->ident;
   689                     if (this_id) {
   690                         char* this_uid = this_id->user_id;
   691                         if (this_uid && (strstr(this_uid, "TOFU_") != this_uid)) {
   692                             // if usernames match, we replace the userid.
   693                             if (identity->username && 
   694                                 strcasecmp(identity->username, 
   695                                            this_id->username) == 0) {
   696                                 
   697                                 // Ok, we have a real ID. Copy it!
   698                                 identity->user_id = strdup(this_uid);
   699                                 assert(identity->user_id);
   700                                 if (!identity->user_id)
   701                                     goto enomem;
   702 
   703                                 stored_ident = this_id;
   704                                 
   705                                 break;                                
   706                             }                            
   707                         } 
   708                     }
   709                     id_curr = id_curr->next;
   710                 }
   711             }
   712         }
   713         
   714         if (stored_ident) {
   715             status = prepare_updated_identity(session,
   716                                               identity,
   717                                               stored_ident, true);
   718         }
   719         else {
   720             identity->user_id = calloc(1, strlen(identity->address) + 6);
   721             if (!identity->user_id)
   722                 goto enomem;
   723 
   724             snprintf(identity->user_id, strlen(identity->address) + 6,
   725                      "TOFU_%s", identity->address);        
   726 
   727             status = get_identity(session, 
   728                                   identity->address, 
   729                                   identity->user_id, 
   730                                   &stored_ident);
   731 
   732             if (status == PEP_STATUS_OK && stored_ident) {
   733                 status = prepare_updated_identity(session,
   734                                                   identity,
   735                                                   stored_ident, true);
   736             }
   737             else {
   738                          
   739                 //    * We've already checked and retrieved
   740                 //      any applicable temporary identities above. If we're 
   741                 //      here, none of them fit.
   742                 
   743                 status = elect_pubkey(session, identity, false);
   744                              
   745                 //    * call set_identity() to store
   746                 if (identity->fpr)
   747                     status = get_key_rating(session, identity->fpr, &identity->comm_type);
   748             
   749                 //    * call set_identity() to store
   750                 adjust_pep_trust_status(session, identity);            
   751                 status = set_identity(session, identity);
   752             }
   753         }
   754     }
   755     else {
   756         /*
   757         * Input: address (no others)
   758          * Temporary identity information without username suplied
   759          */
   760          
   761         //  * Again, see if there is an own identity that uses this address. If so, we'll
   762         //    prefer that
   763         stored_ident = NULL;
   764          
   765         if (default_own_id) {
   766             status = get_identity(session, 
   767                                   identity->address, 
   768                                   default_own_id, 
   769                                   &stored_ident);
   770         }
   771         // If there isn't an own identity, search for a non-temp stored ident
   772         // with this address.                      
   773         if (status == PEP_CANNOT_FIND_IDENTITY || !stored_ident) { 
   774  
   775             identity_list* id_list = NULL;
   776             //    * Search for identity with this address
   777             status = get_identities_by_address(session, identity->address, &id_list);
   778 
   779             // Results are ordered by timestamp descending, so this covers
   780             // both the one-result and multi-result cases
   781             if (id_list) {
   782                 if (stored_ident) // unlikely
   783                     free_identity(stored_ident);
   784                 stored_ident = id_list->ident;
   785             }
   786         }
   787         if (stored_ident)
   788             status = prepare_updated_identity(session, identity,
   789                                               stored_ident, false);
   790         else  {            
   791             // too little info. BUT. We see if we can find a key; if so, we create a
   792             // temp identity, look for a key, and store.
   793                          
   794             // create temporary identity, store it, and Return this
   795             // This means TOFU_ user_id
   796             identity->user_id = calloc(1, strlen(identity->address) + 6);
   797             if (!identity->user_id)
   798                 goto enomem;
   799 
   800             snprintf(identity->user_id, strlen(identity->address) + 6,
   801                      "TOFU_%s", identity->address);        
   802         
   803             identity->username = strdup(identity->address);
   804             if (!identity->address)
   805                 goto enomem;
   806             
   807             free(identity->fpr);
   808             identity->fpr = NULL;
   809             identity->comm_type = PEP_ct_unknown;
   810 
   811             status = elect_pubkey(session, identity, false);
   812                          
   813             if (identity->fpr)
   814                 status = get_key_rating(session, identity->fpr, &identity->comm_type);
   815         
   816             //    * call set_identity() to store
   817             adjust_pep_trust_status(session, identity);            
   818             status = set_identity(session, identity);
   819 
   820         }
   821     }
   822     
   823     // FIXME: This is legacy. I presume it's a notification for the caller...
   824     // Revisit once I can talk to Volker
   825     if (identity->comm_type != PEP_ct_compromised &&
   826         identity->comm_type < PEP_ct_strong_but_unconfirmed)
   827         if (session->examine_identity)
   828             session->examine_identity(identity, session->examine_management);
   829 
   830     goto pep_free;
   831 
   832 enomem:
   833     status = PEP_OUT_OF_MEMORY;
   834 
   835 pep_free:
   836     free(default_own_id);
   837     free_identity(stored_ident);
   838     return status;
   839 }
   840 
   841 PEP_STATUS elect_ownkey(
   842         PEP_SESSION session, pEp_identity * identity
   843     )
   844 {
   845     PEP_STATUS status;
   846     stringlist_t *keylist = NULL;
   847 
   848     free(identity->fpr);
   849     identity->fpr = NULL;
   850 
   851     status = find_private_keys(session, identity->address, &keylist);
   852     assert(status != PEP_OUT_OF_MEMORY);
   853     if (status == PEP_OUT_OF_MEMORY)
   854         return PEP_OUT_OF_MEMORY;
   855     
   856     if (keylist != NULL && keylist->value != NULL)
   857     {
   858         char *_fpr = NULL;
   859         identity->comm_type = PEP_ct_unknown;
   860 
   861         stringlist_t *_keylist;
   862         for (_keylist = keylist; _keylist && _keylist->value; _keylist = _keylist->next) {
   863             bool is_own = false;
   864             
   865             status = own_key_is_listed(session, _keylist->value, &is_own);
   866             assert(status == PEP_STATUS_OK);
   867             if (status != PEP_STATUS_OK) {
   868                 free_stringlist(keylist);
   869                 return status;
   870             }
   871             
   872             if (is_own)
   873             {
   874                 PEP_comm_type _comm_type_key;
   875                 
   876                 status = get_key_rating(session, _keylist->value, &_comm_type_key);
   877                 assert(status != PEP_OUT_OF_MEMORY);
   878                 if (status == PEP_OUT_OF_MEMORY) {
   879                     free_stringlist(keylist);
   880                     return PEP_OUT_OF_MEMORY;
   881                 }
   882                 
   883                 if (_comm_type_key != PEP_ct_compromised &&
   884                     _comm_type_key != PEP_ct_unknown)
   885                 {
   886                     if (identity->comm_type == PEP_ct_unknown ||
   887                         _comm_type_key > identity->comm_type)
   888                     {
   889                         identity->comm_type = _comm_type_key;
   890                         _fpr = _keylist->value;
   891                     }
   892                 }
   893             }
   894         }
   895         
   896         if (_fpr)
   897         {
   898             identity->fpr = strdup(_fpr);
   899             assert(identity->fpr);
   900             if (identity->fpr == NULL)
   901             {
   902                 free_stringlist(keylist);
   903                 return PEP_OUT_OF_MEMORY;
   904             }
   905         }
   906         free_stringlist(keylist);
   907     }
   908     return PEP_STATUS_OK;
   909 }
   910 
   911 PEP_STATUS _has_usable_priv_key(PEP_SESSION session, char* fpr,
   912                                 bool* is_usable) {
   913     
   914     bool has_private = false;
   915     PEP_STATUS status = contains_priv_key(session, fpr, &has_private);
   916     
   917     *is_usable = has_private;
   918     
   919     return status;
   920 }
   921 
   922 PEP_STATUS _myself(PEP_SESSION session, pEp_identity * identity, bool do_keygen, bool ignore_flags)
   923 {
   924 
   925     PEP_STATUS status;
   926 
   927     assert(session);
   928     assert(identity);
   929     assert(!EMPTYSTR(identity->address));
   930     assert(!EMPTYSTR(identity->user_id));
   931 
   932     if (!session || !identity || EMPTYSTR(identity->address) ||
   933         EMPTYSTR(identity->user_id))
   934         return PEP_ILLEGAL_VALUE;
   935 
   936     pEp_identity *stored_identity = NULL;
   937     char* revoked_fpr = NULL; 
   938     bool valid_key_found = false;
   939         
   940     char* default_own_id = NULL;
   941     status = get_default_own_userid(session, &default_own_id);
   942 
   943     // Deal with non-default user_ids.
   944     if (default_own_id && strcmp(default_own_id, identity->user_id) != 0) {
   945         
   946         status = set_userid_alias(session, default_own_id, identity->user_id);
   947         // Do we want this to be fatal? For now, we'll do it...
   948         if (status != PEP_STATUS_OK)
   949             goto pep_free;
   950             
   951         free(identity->user_id);
   952         identity->user_id = strdup(default_own_id);
   953         if (identity->user_id == NULL) {
   954             status = PEP_OUT_OF_MEMORY;
   955             goto pep_free;
   956         }
   957     }
   958 
   959     // NOTE: IF WE DON'T YET HAVE AN OWN_ID, WE IGNORE REFERENCES TO THIS ADDRESS IN THE
   960     // DB (WHICH MAY HAVE BEEN SET BEFORE MYSELF WAS CALLED BY RECEIVING AN EMAIL FROM
   961     // THIS ADDRESS), AS IT IS NOT AN OWN_IDENTITY AND HAS NO INFORMATION WE NEED OR WHAT TO
   962     // SET FOR MYSELF
   963     
   964     // Ok, so now, set up the own_identity:
   965     identity->comm_type = PEP_ct_pEp;
   966     identity->me = true;
   967     if(ignore_flags)
   968         identity->flags = 0;
   969     
   970     // Let's see if we have an identity record in the DB for 
   971     // this user_id + address
   972 //    DEBUG_LOG("myself", "debug", identity->address);
   973  
   974     status = get_identity(session,
   975                           identity->address,
   976                           identity->user_id,
   977                           &stored_identity);
   978 
   979     assert(status != PEP_OUT_OF_MEMORY);
   980     if (status == PEP_OUT_OF_MEMORY) {
   981         status = PEP_OUT_OF_MEMORY;
   982         goto pep_free;
   983     }
   984 
   985     // Set usernames - priority is input username > stored name > address
   986     // If there's an input username, we always patch the username with that
   987     // input.
   988     if (EMPTYSTR(identity->username)) {
   989         bool stored_uname = (stored_identity && !EMPTYSTR(stored_identity->username));
   990         char* uname = (stored_uname ? stored_identity->username : identity->address);
   991         free(identity->username);
   992         identity->username = strdup(uname);
   993         if (identity->username == NULL) {
   994             status = PEP_OUT_OF_MEMORY;
   995             goto pep_free;
   996         }
   997     }
   998 
   999     // ignore input fpr
  1000 
  1001     if (identity->fpr) {
  1002         free(identity->fpr);
  1003         identity->fpr = NULL;
  1004     }
  1005 
  1006     // check stored identity
  1007     if (stored_identity && !EMPTYSTR(stored_identity->fpr)) {
  1008         // Fall back / retrieve
  1009         status = validate_fpr(session, stored_identity, false);
  1010         if (status == PEP_OUT_OF_MEMORY)
  1011             goto pep_free;
  1012         if (status == PEP_STATUS_OK) {
  1013             if (stored_identity->comm_type >= PEP_ct_strong_but_unconfirmed) {
  1014                 identity->fpr = strdup(stored_identity->fpr);
  1015                 assert(identity->fpr);
  1016                 if (!identity->fpr) {
  1017                     status = PEP_OUT_OF_MEMORY;
  1018                     goto pep_free;
  1019                 }
  1020                 valid_key_found = true;            
  1021             }
  1022             else {
  1023                 bool revoked = false;
  1024                 status = key_revoked(session, stored_identity->fpr, &revoked);
  1025                 if (status)
  1026                     goto pep_free;
  1027                 if (revoked) {
  1028                     revoked_fpr = strdup(stored_identity->fpr);
  1029                     assert(revoked_fpr);
  1030                     if (!revoked_fpr) {
  1031                         status = PEP_OUT_OF_MEMORY;
  1032                         goto pep_free;
  1033                     }
  1034                 }
  1035             }
  1036         }
  1037     }
  1038     
  1039     // Nothing left to do but generate a key
  1040     if (!valid_key_found) {
  1041         if (!do_keygen)
  1042             status = PEP_GET_KEY_FAILED;
  1043         else {
  1044 // /            DEBUG_LOG("Generating key pair", "debug", identity->address);
  1045 
  1046             free(identity->fpr);
  1047             identity->fpr = NULL;
  1048             status = generate_keypair(session, identity);
  1049             assert(status != PEP_OUT_OF_MEMORY);
  1050 
  1051             if (status != PEP_STATUS_OK) {
  1052                 char buf[11];
  1053                 snprintf(buf, 11, "%d", status); // uh, this is kludgey. FIXME
  1054 //                DEBUG_LOG("Generating key pair failed", "debug", buf);
  1055             }        
  1056             else {
  1057                 valid_key_found = true;
  1058                 if (revoked_fpr) {
  1059                     status = set_revoked(session, revoked_fpr,
  1060                                          stored_identity->fpr, time(NULL));
  1061                 }
  1062             }
  1063         }
  1064     }
  1065 
  1066     if (valid_key_found) {
  1067         identity->comm_type = PEP_ct_pEp;
  1068         status = PEP_STATUS_OK;
  1069     }
  1070     else {
  1071         free(identity->fpr);
  1072         identity->fpr = NULL;
  1073         identity->comm_type = PEP_ct_unknown;
  1074     }
  1075     
  1076     status = set_identity(session, identity);
  1077     if (status == PEP_STATUS_OK)
  1078         status = set_as_pep_user(session, identity);
  1079 
  1080 pep_free:    
  1081     free(default_own_id);
  1082     free(revoked_fpr);                     
  1083     free_identity(stored_identity);
  1084     return status;
  1085 }
  1086 
  1087 // DYNAMIC_API PEP_STATUS initialise_own_identities(PEP_SESSION session,
  1088 //                                                  identity_list* my_idents) {
  1089 //     PEP_STATUS status = PEP_STATUS_OK;
  1090 //     if (!session)
  1091 //         return PEP_ILLEGAL_VALUE;
  1092 //         
  1093 //     if (!my_idents)
  1094 //         return PEP_STATUS_OK;
  1095 //             
  1096 //     identity_list* ident_curr = my_idents;
  1097 //     while (ident_curr) {
  1098 //         pEp_identity* ident = ident_curr->ident;
  1099 //         if (!ident || !ident->address) {
  1100 //             status = PEP_ILLEGAL_VALUE;
  1101 //             goto pep_error;
  1102 //         }
  1103 // 
  1104 //         status = _myself(session, ident, false, false);
  1105 //         
  1106 //         ident_curr = ident_curr->next;
  1107 //     }
  1108 //     
  1109 // pep_error:
  1110 //     return status;
  1111 // }
  1112 
  1113 DYNAMIC_API PEP_STATUS myself(PEP_SESSION session, pEp_identity * identity)
  1114 {
  1115     return _myself(session, identity, true, false);
  1116 }
  1117 
  1118 DYNAMIC_API PEP_STATUS register_examine_function(
  1119         PEP_SESSION session, 
  1120         examine_identity_t examine_identity,
  1121         void *management
  1122     )
  1123 {
  1124     assert(session);
  1125     if (!session)
  1126         return PEP_ILLEGAL_VALUE;
  1127 
  1128     session->examine_management = management;
  1129     session->examine_identity = examine_identity;
  1130 
  1131     return PEP_STATUS_OK;
  1132 }
  1133 
  1134 DYNAMIC_API PEP_STATUS do_keymanagement(
  1135         retrieve_next_identity_t retrieve_next_identity,
  1136         void *management
  1137     )
  1138 {
  1139     PEP_SESSION session;
  1140     pEp_identity *identity;
  1141     PEP_STATUS status;
  1142 
  1143     assert(retrieve_next_identity);
  1144     assert(management);
  1145 
  1146     if (!retrieve_next_identity || !management)
  1147         return PEP_ILLEGAL_VALUE;
  1148 
  1149     status = init(&session);
  1150     assert(status == PEP_STATUS_OK);
  1151     if (status != PEP_STATUS_OK)
  1152         return status;
  1153 
  1154     log_event(session, "keymanagement thread started", "pEp engine", NULL, NULL);
  1155 
  1156     while ((identity = retrieve_next_identity(management))) 
  1157     {
  1158         assert(identity->address);
  1159         if(identity->address)
  1160         {
  1161             DEBUG_LOG("do_keymanagement", "retrieve_next_identity", identity->address);
  1162 
  1163             if (identity->me) {
  1164                 status = myself(session, identity);
  1165             } else {
  1166                 status = recv_key(session, identity->address);
  1167             }
  1168 
  1169             assert(status != PEP_OUT_OF_MEMORY);
  1170             if(status == PEP_OUT_OF_MEMORY)
  1171                 return PEP_OUT_OF_MEMORY;
  1172         }
  1173         free_identity(identity);
  1174     }
  1175 
  1176     log_event(session, "keymanagement thread shutdown", "pEp engine", NULL, NULL);
  1177 
  1178     release(session);
  1179     return PEP_STATUS_OK;
  1180 }
  1181 
  1182 DYNAMIC_API PEP_STATUS key_mistrusted(
  1183         PEP_SESSION session,
  1184         pEp_identity *ident
  1185     )
  1186 {
  1187     PEP_STATUS status = PEP_STATUS_OK;
  1188 
  1189     assert(session);
  1190     assert(ident);
  1191     assert(!EMPTYSTR(ident->fpr));
  1192 
  1193     if (!(session && ident && ident->fpr))
  1194         return PEP_ILLEGAL_VALUE;
  1195             
  1196     // double-check to be sure key is even in the DB
  1197     if (ident->fpr)
  1198         status = set_pgp_keypair(session, ident->fpr);
  1199 
  1200     // We set this temporarily but will grab it back from the cache afterwards
  1201     ident->comm_type = PEP_ct_mistrusted;
  1202     status = set_trust(session, ident);
  1203     
  1204     if (status == PEP_STATUS_OK)
  1205         // cascade that mistrust for anyone using this key
  1206         status = mark_as_compromised(session, ident->fpr);
  1207     if (status == PEP_STATUS_OK)
  1208         status = add_mistrusted_key(session, ident->fpr);
  1209             
  1210     return status;
  1211 }
  1212 
  1213 DYNAMIC_API PEP_STATUS key_reset_trust(
  1214         PEP_SESSION session,
  1215         pEp_identity *ident
  1216     )
  1217 {
  1218     PEP_STATUS status = PEP_STATUS_OK;
  1219 
  1220     assert(session);
  1221     assert(ident);
  1222     assert(!EMPTYSTR(ident->fpr));
  1223     assert(!EMPTYSTR(ident->address));
  1224     assert(!EMPTYSTR(ident->user_id));
  1225 
  1226     if (!(session && ident && ident->fpr && ident->fpr[0] != '\0' && ident->address &&
  1227             ident->user_id))
  1228         return PEP_ILLEGAL_VALUE;
  1229 
  1230     // we do not change the input struct at ALL.
  1231     pEp_identity* input_copy = identity_dup(ident);
  1232     
  1233     pEp_identity* tmp_ident = NULL;
  1234     
  1235     status = get_trust(session, input_copy);
  1236     
  1237     if (status != PEP_STATUS_OK)
  1238         goto pep_free;
  1239         
  1240     PEP_comm_type new_trust = PEP_ct_unknown;
  1241     status = get_key_rating(session, ident->fpr, &new_trust);
  1242     if (status != PEP_STATUS_OK)
  1243         goto pep_free;
  1244 
  1245     bool pep_user = false;
  1246     
  1247     status = is_pep_user(session, ident, &pep_user);
  1248     
  1249     if (pep_user && new_trust >= PEP_ct_unconfirmed_encryption)
  1250         input_copy->comm_type = PEP_ct_pEp_unconfirmed;
  1251     else
  1252         input_copy->comm_type = new_trust;
  1253         
  1254     status = set_trust(session, input_copy);
  1255     
  1256     if (status != PEP_STATUS_OK)
  1257         goto pep_free;
  1258 
  1259     bool mistrusted_key = false;
  1260         
  1261     status = is_mistrusted_key(session, ident->fpr, &mistrusted_key);
  1262 
  1263     if (status != PEP_STATUS_OK)
  1264         goto pep_free;
  1265     
  1266     if (mistrusted_key)
  1267         status = delete_mistrusted_key(session, ident->fpr);
  1268 
  1269     if (status != PEP_STATUS_OK)
  1270         goto pep_free;
  1271         
  1272     tmp_ident = new_identity(ident->address, NULL, ident->user_id, NULL);
  1273 
  1274     if (!tmp_ident)
  1275         return PEP_OUT_OF_MEMORY;
  1276     
  1277     if (is_me(session, tmp_ident))
  1278         status = myself(session, tmp_ident);
  1279     else
  1280         status = update_identity(session, tmp_ident);
  1281     
  1282     if (status != PEP_STATUS_OK)
  1283         goto pep_free;
  1284     
  1285     // remove as default if necessary
  1286     if (!EMPTYSTR(tmp_ident->fpr) && strcmp(tmp_ident->fpr, ident->fpr) == 0) {
  1287         free(tmp_ident->fpr);
  1288         tmp_ident->fpr = NULL;
  1289         tmp_ident->comm_type = PEP_ct_unknown;
  1290         status = set_identity(session, tmp_ident);
  1291         if (status != PEP_STATUS_OK)
  1292             goto pep_free;
  1293     }
  1294     
  1295     char* user_default = NULL;
  1296     get_main_user_fpr(session, tmp_ident->user_id, &user_default);
  1297     
  1298     if (!EMPTYSTR(user_default)) {
  1299         if (strcmp(user_default, ident->fpr) == 0)
  1300             status = refresh_userid_default_key(session, ident->user_id);
  1301         if (status != PEP_STATUS_OK)
  1302             goto pep_free;    
  1303     }
  1304             
  1305 pep_free:
  1306     free_identity(tmp_ident);
  1307     free_identity(input_copy);
  1308     return status;
  1309 }
  1310 
  1311 DYNAMIC_API PEP_STATUS trust_personal_key(
  1312         PEP_SESSION session,
  1313         pEp_identity *ident
  1314     )
  1315 {
  1316     PEP_STATUS status = PEP_STATUS_OK;
  1317 
  1318     assert(session);
  1319     assert(ident);
  1320     assert(!EMPTYSTR(ident->address));
  1321     assert(!EMPTYSTR(ident->user_id));
  1322     assert(!EMPTYSTR(ident->fpr));
  1323 
  1324     if (!ident || EMPTYSTR(ident->address) || EMPTYSTR(ident->user_id) ||
  1325             EMPTYSTR(ident->fpr))
  1326         return PEP_ILLEGAL_VALUE;
  1327 
  1328     //bool ident_has_trusted_default = false;
  1329     char* ident_default_fpr = NULL;
  1330 
  1331     // Before we do anything, be sure the input fpr is even eligible to be trusted
  1332     PEP_comm_type input_default_ct = PEP_ct_unknown;
  1333     status = get_key_rating(session, ident->fpr, &input_default_ct);
  1334     if (input_default_ct < PEP_ct_strong_but_unconfirmed)
  1335         return PEP_KEY_UNSUITABLE;
  1336 
  1337     status = set_pgp_keypair(session, ident->fpr);
  1338     if (status != PEP_STATUS_OK)
  1339         return status;
  1340 
  1341     bool me = is_me(session, ident);
  1342 
  1343     pEp_identity* ident_copy = identity_dup(ident);
  1344     char* cached_fpr = NULL;
  1345 
  1346     // for setting up a temp trusted identity for the input fpr
  1347     pEp_identity* tmp_id = NULL;
  1348 
  1349     // For later, in case we need to check the user default key
  1350     pEp_identity* tmp_user_ident = NULL;
  1351 
  1352     if (me) {
  1353         bool has_private = false;
  1354         // first of all, does this key even have a private component.
  1355         status = contains_priv_key(session, ident->fpr, &has_private);
  1356         if (status != PEP_STATUS_OK && status != PEP_KEY_NOT_FOUND)
  1357             goto pep_free;
  1358             
  1359         if (has_private) {
  1360             status = set_own_key(session, ident_copy, ident->fpr); 
  1361             goto pep_free;
  1362         }
  1363     }
  1364     
  1365     // Either it's not me, or it's me but the key has no private key. 
  1366     // We're only talking about pub keys here. Moving on.
  1367     
  1368     // Save the input fpr, which we already tested as non-NULL
  1369     cached_fpr = strdup(ident->fpr);
  1370 
  1371     // Set up a temp trusted identity for the input fpr without a comm type;
  1372     tmp_id = new_identity(ident->address, ident->fpr, ident->user_id, NULL);
  1373     
  1374     // ->me isn't set, even if this is an own identity, so this will work.
  1375     status = validate_fpr(session, tmp_id, false);
  1376         
  1377     if (status == PEP_STATUS_OK) {
  1378         // Validate fpr gets trust DB or, when that fails, key comm type. we checked
  1379         // above that the key was ok. (not revoked or expired), but we want the max.
  1380         tmp_id->comm_type = _MAX(tmp_id->comm_type, input_default_ct) | PEP_ct_confirmed;
  1381 
  1382         // Get the default identity without setting the fpr                                       
  1383         if (me)
  1384             status = _myself(session, ident_copy, false, true);
  1385         else    
  1386             status = update_identity(session, ident_copy);
  1387             
  1388         ident_default_fpr = (EMPTYSTR(ident_copy->fpr) ? NULL : strdup(ident_copy->fpr));
  1389 
  1390         if (status == PEP_STATUS_OK) {
  1391             bool trusted_default = false;
  1392 
  1393             // If there's no default, or the default is different from the input...
  1394             if (me || EMPTYSTR(ident_default_fpr) || strcmp(cached_fpr, ident_default_fpr) != 0) {
  1395                 
  1396                 // If the default fpr (if there is one) is trusted and key is strong enough,
  1397                 // don't replace, we just set the trusted bit on this key for this user_id...
  1398                 // (If there's no default fpr, this won't be true anyway.)
  1399                 if (me || (ident_copy->comm_type >= PEP_ct_strong_but_unconfirmed && 
  1400                           (ident_copy->comm_type & PEP_ct_confirmed))) {                        
  1401 
  1402                     trusted_default = true;
  1403                                     
  1404                     status = set_trust(session, tmp_id);
  1405                     input_default_ct = tmp_id->comm_type;                    
  1406                 }
  1407                 else {
  1408                     free(ident_copy->fpr);
  1409                     ident_copy->fpr = strdup(cached_fpr);
  1410                     ident_copy->comm_type = tmp_id->comm_type;
  1411                     status = set_identity(session, ident_copy); // replace identity default
  1412                     if (status == PEP_STATUS_OK) {
  1413                         if ((ident_copy->comm_type | PEP_ct_confirmed) == PEP_ct_pEp)
  1414                             status = set_as_pep_user(session, ident_copy);
  1415                     }            
  1416                 }
  1417             }
  1418             else { // we're setting this on the default fpr
  1419                 ident->comm_type = tmp_id->comm_type;
  1420                 status = set_identity(session, ident);
  1421                 trusted_default = true;
  1422             }
  1423             if (status == PEP_STATUS_OK && !trusted_default) {
  1424                 // Ok, there wasn't a trusted default, so we replaced. Thus, we also
  1425                 // make sure there's a trusted default on the user_id. If there
  1426                 // is not, we make this the default.
  1427                 char* user_default = NULL;
  1428                 status = get_main_user_fpr(session, ident->user_id, &user_default);
  1429             
  1430                 if (status == PEP_STATUS_OK && user_default) {
  1431                     tmp_user_ident = new_identity(ident->address, 
  1432                                                   user_default, 
  1433                                                   ident->user_id, 
  1434                                                   NULL);
  1435                     if (!tmp_user_ident)
  1436                         status = PEP_OUT_OF_MEMORY;
  1437                     else {
  1438                         status = validate_fpr(session, tmp_user_ident, false);
  1439                         
  1440                         if (status != PEP_STATUS_OK ||
  1441                             tmp_user_ident->comm_type < PEP_ct_strong_but_unconfirmed ||
  1442                             !(tmp_user_ident->comm_type & PEP_ct_confirmed)) 
  1443                         {
  1444                             char* trusted_fpr = (trusted_default ? ident_default_fpr : cached_fpr);
  1445                             status = replace_main_user_fpr(session, ident->user_id, trusted_fpr);
  1446                         } 
  1447                     }
  1448                 }
  1449             }
  1450         }
  1451     }    
  1452 
  1453 pep_free:
  1454     free(ident_default_fpr);
  1455     free(cached_fpr);
  1456     free_identity(tmp_id);
  1457     free_identity(ident_copy);
  1458     free_identity(tmp_user_ident);
  1459     return status;
  1460 }
  1461 
  1462 DYNAMIC_API PEP_STATUS own_key_is_listed(
  1463         PEP_SESSION session,
  1464         const char *fpr,
  1465         bool *listed
  1466     )
  1467 {
  1468     PEP_STATUS status = PEP_STATUS_OK;
  1469     int count;
  1470     
  1471     assert(session && fpr && fpr[0] && listed);
  1472     
  1473     if (!(session && fpr && fpr[0] && listed))
  1474         return PEP_ILLEGAL_VALUE;
  1475     
  1476     *listed = false;
  1477     
  1478     sqlite3_reset(session->own_key_is_listed);
  1479     sqlite3_bind_text(session->own_key_is_listed, 1, fpr, -1, SQLITE_STATIC);
  1480     
  1481     int result;
  1482     
  1483     result = sqlite3_step(session->own_key_is_listed);
  1484     switch (result) {
  1485         case SQLITE_ROW:
  1486             count = sqlite3_column_int(session->own_key_is_listed, 0);
  1487             *listed = count > 0;
  1488             status = PEP_STATUS_OK;
  1489             break;
  1490             
  1491         default:
  1492             status = PEP_UNKNOWN_ERROR;
  1493     }
  1494     
  1495     sqlite3_reset(session->own_key_is_listed);
  1496     return status;
  1497 }
  1498 
  1499 PEP_STATUS _own_identities_retrieve(
  1500         PEP_SESSION session,
  1501         identity_list **own_identities,
  1502         identity_flags_t excluded_flags
  1503       )
  1504 {
  1505     PEP_STATUS status = PEP_STATUS_OK;
  1506     
  1507     assert(session && own_identities);
  1508     if (!(session && own_identities))
  1509         return PEP_ILLEGAL_VALUE;
  1510     
  1511     *own_identities = NULL;
  1512     identity_list *_own_identities = new_identity_list(NULL);
  1513     if (_own_identities == NULL)
  1514         goto enomem;
  1515     
  1516     sqlite3_reset(session->own_identities_retrieve);
  1517     
  1518     int result;
  1519     // address, fpr, username, user_id, comm_type, lang, flags
  1520     const char *address = NULL;
  1521     const char *fpr = NULL;
  1522     const char *username = NULL;
  1523     const char *user_id = NULL;
  1524     PEP_comm_type comm_type = PEP_ct_unknown;
  1525     const char *lang = NULL;
  1526     unsigned int flags = 0;
  1527     
  1528     identity_list *_bl = _own_identities;
  1529     do {
  1530         sqlite3_bind_int(session->own_identities_retrieve, 1, excluded_flags);
  1531         result = sqlite3_step(session->own_identities_retrieve);
  1532         switch (result) {
  1533             case SQLITE_ROW:
  1534                 address = (const char *)
  1535                     sqlite3_column_text(session->own_identities_retrieve, 0);
  1536                 fpr = (const char *)
  1537                     sqlite3_column_text(session->own_identities_retrieve, 1);
  1538                 user_id = (const char *)
  1539                     sqlite3_column_text(session->own_identities_retrieve, 2);
  1540                 username = (const char *)
  1541                     sqlite3_column_text(session->own_identities_retrieve, 3);
  1542                 comm_type = PEP_ct_pEp;
  1543                 lang = (const char *)
  1544                     sqlite3_column_text(session->own_identities_retrieve, 4);
  1545                 flags = (unsigned int)
  1546                     sqlite3_column_int(session->own_identities_retrieve, 5);
  1547 
  1548                 pEp_identity *ident = new_identity(address, fpr, user_id, username);
  1549                 if (!ident)
  1550                     goto enomem;
  1551                 ident->comm_type = comm_type;
  1552                 if (lang && lang[0]) {
  1553                     ident->lang[0] = lang[0];
  1554                     ident->lang[1] = lang[1];
  1555                     ident->lang[2] = 0;
  1556                 }
  1557                 ident->me = true;
  1558                 ident->flags = flags;
  1559 
  1560                 _bl = identity_list_add(_bl, ident);
  1561                 if (_bl == NULL) {
  1562                     free_identity(ident);
  1563                     goto enomem;
  1564                 }
  1565                 
  1566                 break;
  1567                 
  1568             case SQLITE_DONE:
  1569                 break;
  1570                 
  1571             default:
  1572                 status = PEP_UNKNOWN_ERROR;
  1573                 result = SQLITE_DONE;
  1574         }
  1575     } while (result != SQLITE_DONE);
  1576     
  1577     sqlite3_reset(session->own_identities_retrieve);
  1578     if (status == PEP_STATUS_OK)
  1579         *own_identities = _own_identities;
  1580     else
  1581         free_identity_list(_own_identities);
  1582     
  1583     goto the_end;
  1584     
  1585 enomem:
  1586     free_identity_list(_own_identities);
  1587     status = PEP_OUT_OF_MEMORY;
  1588     
  1589 the_end:
  1590     return status;
  1591 }
  1592 
  1593 DYNAMIC_API PEP_STATUS own_identities_retrieve(
  1594         PEP_SESSION session,
  1595         identity_list **own_identities
  1596       )
  1597 {
  1598     return _own_identities_retrieve(session, own_identities, 0);
  1599 }
  1600 
  1601 PEP_STATUS _own_keys_retrieve(
  1602         PEP_SESSION session,
  1603         stringlist_t **keylist,
  1604         identity_flags_t excluded_flags
  1605       )
  1606 {
  1607     PEP_STATUS status = PEP_STATUS_OK;
  1608     
  1609     assert(session && keylist);
  1610     if (!(session && keylist))
  1611         return PEP_ILLEGAL_VALUE;
  1612     
  1613     *keylist = NULL;
  1614     stringlist_t *_keylist = NULL;
  1615     
  1616     sqlite3_reset(session->own_keys_retrieve);
  1617     
  1618     int result;
  1619     char *fpr = NULL;
  1620     
  1621     stringlist_t *_bl = _keylist;
  1622     do {
  1623         sqlite3_bind_int(session->own_keys_retrieve, 1, excluded_flags);
  1624         result = sqlite3_step(session->own_keys_retrieve);
  1625         switch (result) {
  1626             case SQLITE_ROW:
  1627                 fpr = strdup((const char *) sqlite3_column_text(session->own_keys_retrieve, 0));
  1628                 if(fpr == NULL)
  1629                     goto enomem;
  1630 
  1631                 _bl = stringlist_add(_bl, fpr);
  1632                 if (_bl == NULL) {
  1633                     free(fpr);
  1634                     goto enomem;
  1635                 }
  1636                 if (_keylist == NULL)
  1637                     _keylist = _bl;
  1638                 
  1639                 break;
  1640                 
  1641             case SQLITE_DONE:
  1642                 break;
  1643                 
  1644             default:
  1645                 status = PEP_UNKNOWN_ERROR;
  1646                 result = SQLITE_DONE;
  1647         }
  1648     } while (result != SQLITE_DONE);
  1649     
  1650     sqlite3_reset(session->own_keys_retrieve);
  1651     if (status == PEP_STATUS_OK)
  1652         *keylist = _keylist;
  1653     else
  1654         free_stringlist(_keylist);
  1655     
  1656     goto the_end;
  1657     
  1658 enomem:
  1659     free_stringlist(_keylist);
  1660     status = PEP_OUT_OF_MEMORY;
  1661     
  1662 the_end:
  1663     return status;
  1664 }
  1665 
  1666 DYNAMIC_API PEP_STATUS own_keys_retrieve(PEP_SESSION session, stringlist_t **keylist)
  1667 {
  1668     return _own_keys_retrieve(session, keylist, 0);
  1669 }
  1670 
  1671 DYNAMIC_API PEP_STATUS set_own_key(
  1672        PEP_SESSION session,
  1673        pEp_identity *me,
  1674        const char *fpr
  1675     )
  1676 {
  1677     PEP_STATUS status = PEP_STATUS_OK;
  1678     
  1679     assert(session && me);
  1680     assert(!EMPTYSTR(fpr));
  1681     assert(!EMPTYSTR(me->address));
  1682     assert(!EMPTYSTR(me->user_id));
  1683     assert(!EMPTYSTR(me->username));
  1684 
  1685     if (!session || !me || EMPTYSTR(fpr) || EMPTYSTR(me->address) ||
  1686             EMPTYSTR(me->user_id) || EMPTYSTR(me->username))
  1687         return PEP_ILLEGAL_VALUE;
  1688 
  1689     status = _myself(session, me, false, true);
  1690     // we do not need a valid key but dislike other errors
  1691     if (status != PEP_STATUS_OK && status != PEP_GET_KEY_FAILED && status != PEP_KEY_UNSUITABLE)
  1692         return status;
  1693     status = PEP_STATUS_OK;
  1694 
  1695     bool private = false;
  1696     status = contains_priv_key(session, fpr, &private);
  1697     
  1698     if (status != PEP_STATUS_OK)
  1699         return status;
  1700         
  1701     if (!private)
  1702         return PEP_KEY_UNSUITABLE;
  1703  
  1704     if (me->fpr)
  1705         free(me->fpr);
  1706     me->fpr = strdup(fpr);
  1707     assert(me->fpr);
  1708     if (!me->fpr)
  1709         return PEP_OUT_OF_MEMORY;
  1710 
  1711     status = validate_fpr(session, me, false);
  1712     if (status)
  1713         return status;
  1714 
  1715     me->comm_type = PEP_ct_pEp;
  1716     status = set_identity(session, me);
  1717     return status;
  1718 }
  1719 
  1720 PEP_STATUS contains_priv_key(PEP_SESSION session, const char *fpr,
  1721                              bool *has_private) {
  1722 
  1723     assert(session);
  1724     assert(fpr);
  1725     assert(has_private);
  1726     
  1727     if (!(session && fpr && has_private))
  1728         return PEP_ILLEGAL_VALUE;
  1729 
  1730     return session->cryptotech[PEP_crypt_OpenPGP].contains_priv_key(session, fpr, has_private);
  1731 }
  1732 
  1733 PEP_STATUS add_mistrusted_key(PEP_SESSION session, const char* fpr)
  1734 {
  1735     int result;
  1736 
  1737     assert(!EMPTYSTR(fpr));
  1738     
  1739     if (!(session) || EMPTYSTR(fpr))
  1740         return PEP_ILLEGAL_VALUE;
  1741 
  1742     sqlite3_reset(session->add_mistrusted_key);
  1743     sqlite3_bind_text(session->add_mistrusted_key, 1, fpr, -1,
  1744             SQLITE_STATIC);
  1745 
  1746     result = sqlite3_step(session->add_mistrusted_key);
  1747     sqlite3_reset(session->add_mistrusted_key);
  1748 
  1749     if (result != SQLITE_DONE)
  1750         return PEP_CANNOT_SET_PGP_KEYPAIR; // FIXME: Better status?
  1751 
  1752     return PEP_STATUS_OK;
  1753 }
  1754 
  1755 PEP_STATUS delete_mistrusted_key(PEP_SESSION session, const char* fpr)
  1756 {
  1757     int result;
  1758 
  1759     assert(!EMPTYSTR(fpr));
  1760     
  1761     if (!(session) || EMPTYSTR(fpr))
  1762         return PEP_ILLEGAL_VALUE;
  1763 
  1764     sqlite3_reset(session->delete_mistrusted_key);
  1765     sqlite3_bind_text(session->delete_mistrusted_key, 1, fpr, -1,
  1766             SQLITE_STATIC);
  1767 
  1768     result = sqlite3_step(session->delete_mistrusted_key);
  1769     sqlite3_reset(session->delete_mistrusted_key);
  1770 
  1771     if (result != SQLITE_DONE)
  1772         return PEP_UNKNOWN_ERROR; // FIXME: Better status?
  1773 
  1774     return PEP_STATUS_OK;
  1775 }
  1776 
  1777 PEP_STATUS is_mistrusted_key(PEP_SESSION session, const char* fpr,
  1778                              bool* mistrusted)
  1779 {
  1780     PEP_STATUS status = PEP_STATUS_OK;
  1781 
  1782     assert(session);
  1783     assert(!EMPTYSTR(fpr));
  1784 
  1785     if (!(session && fpr))
  1786         return PEP_ILLEGAL_VALUE;
  1787 
  1788     *mistrusted = false;
  1789 
  1790     sqlite3_reset(session->is_mistrusted_key);
  1791     sqlite3_bind_text(session->is_mistrusted_key, 1, fpr, -1, SQLITE_STATIC);
  1792 
  1793     int result;
  1794 
  1795     result = sqlite3_step(session->is_mistrusted_key);
  1796     switch (result) {
  1797     case SQLITE_ROW:
  1798         *mistrusted = sqlite3_column_int(session->is_mistrusted_key, 0);
  1799         status = PEP_STATUS_OK;
  1800         break;
  1801 
  1802     default:
  1803         status = PEP_UNKNOWN_ERROR;
  1804     }
  1805 
  1806     sqlite3_reset(session->is_mistrusted_key);
  1807     return status;
  1808 }
  1809 
  1810 #ifdef USE_GPG
  1811 PEP_STATUS pgp_find_trusted_private_keys(
  1812         PEP_SESSION session, stringlist_t **keylist
  1813     );
  1814 
  1815 enum _pgp_thing {
  1816     _pgp_none = 0,
  1817     _pgp_fpr,
  1818     _pgp_email,
  1819     _pgp_name
  1820 };
  1821 
  1822 static enum _pgp_thing _pgp_thing_next(enum _pgp_thing thing)
  1823 {
  1824     switch (thing) {
  1825         case _pgp_fpr:
  1826             return _pgp_email;
  1827         case _pgp_email:
  1828             return _pgp_name;
  1829         case _pgp_name:
  1830             return _pgp_fpr;
  1831         default:
  1832             return _pgp_fpr;
  1833     }
  1834 }
  1835 
  1836 PEP_STATUS pgp_import_ultimately_trusted_keypairs(PEP_SESSION session) {
  1837     assert(session);
  1838     if (!session)
  1839         return PEP_ILLEGAL_VALUE;
  1840 
  1841     stringlist_t* priv_keylist = NULL;
  1842     PEP_STATUS status = PEP_STATUS_OK;
  1843 
  1844     // 1. get keys
  1845     status = pgp_find_trusted_private_keys(session, &priv_keylist);
  1846     if (status)
  1847         return status;
  1848 
  1849     pEp_identity *identity = NULL;
  1850     stringlist_t *_sl;
  1851 	
  1852     char *fpr = NULL;
  1853     enum _pgp_thing thing = _pgp_none;
  1854     for (_sl = priv_keylist; _sl && _sl->value; _sl = _sl->next) {
  1855         thing = _pgp_thing_next(thing);
  1856         switch (thing) {
  1857             case _pgp_fpr:
  1858                 identity = new_identity(NULL, NULL, PEP_OWN_USERID, NULL);
  1859                 if (!identity)
  1860                     status = PEP_OUT_OF_MEMORY;
  1861                 identity->me = true;
  1862                 fpr = strdup(_sl->value);
  1863                 assert(fpr);
  1864                 if (!fpr) {
  1865                     status = PEP_OUT_OF_MEMORY;
  1866                     free_identity(identity);
  1867                 }
  1868                 break;
  1869             case _pgp_email:
  1870                 assert(identity);
  1871                 identity->address = strdup(_sl->value);
  1872                 assert(identity->address);
  1873                 if (!identity->address) {
  1874                     status = PEP_OUT_OF_MEMORY;
  1875                     free_identity(identity);
  1876                 }
  1877                 break;
  1878             case _pgp_name:
  1879                 assert(identity);
  1880                 identity->username = strdup(_sl->value);
  1881                 assert(identity->username);
  1882                 if (!identity->username)
  1883                     status = PEP_OUT_OF_MEMORY;
  1884                 else
  1885                     status = set_own_key(session, identity, fpr);
  1886                 free_identity(identity);
  1887                 identity = NULL;
  1888                 break;
  1889             default:
  1890                 assert(0);
  1891                 free_identity(identity);
  1892                 status = PEP_UNKNOWN_ERROR;
  1893         }
  1894         if (status)
  1895             break;
  1896     }
  1897     
  1898     free_stringlist(priv_keylist);
  1899     return status;
  1900 }
  1901 #endif // USE_GPG