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