src/keymanagement.c
author Krista Bennett <krista@pep-project.org>
Mon, 05 Mar 2018 18:02:34 +0100
changeset 2552 09d77d1177ce
parent 2549 5fc5d6be0b36
child 2574 f2e0646c4b0d
permissions -rw-r--r--
Fixed call to _myself in trust_personal_key (should now be set_own_key), and also made sure that when an own identity comes in but the key is public only, that it gets verified but never set as the default when being trusted.
     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_compromized &&
    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_compromized:
   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         return PEP_ILLEGAL_VALUE;
   516     }
   517 
   518     // We have, at least, an address.
   519     // Retrieve stored identity information!    
   520     pEp_identity* stored_ident = NULL;
   521 
   522     if (!EMPTYSTR(identity->user_id)) {            
   523         // (we're gonna update the trust/fpr anyway, so we use the no-fpr-from-trust-db variant)
   524         //      * do get_identity() to retrieve stored identity information
   525         status = get_identity_without_trust_check(session, identity->address, identity->user_id, &stored_ident);
   526 
   527         // Before we start - if there was no stored identity, we should check to make sure we don't
   528         // have a stored identity with a temporary user_id that differs from the input user_id. This
   529         // happens in multithreaded environments sometimes.
   530         if (!stored_ident) {
   531             identity_list* id_list = NULL;
   532             status = get_identities_by_address(session, identity->address, &id_list);
   533 
   534             if (id_list) {
   535                 identity_list* id_curr = id_list;
   536                 while (id_curr) {
   537                     pEp_identity* this_id = id_curr->ident;
   538                     if (this_id) {
   539                         char* this_uid = this_id->user_id;
   540                         if (this_uid && (strstr(this_uid, "TOFU_") == this_uid)) {
   541                             // FIXME: should we also be fixing pEp_own_userId in this
   542                             // function here?
   543                             
   544                             // if usernames match, we replace the userid. Or if the temp username
   545                             // is anonymous.
   546                             // FIXME: do we need to create an address match function which
   547                             // matches the whole dot-and-case rigamarole from 
   548                             if (EMPTYSTR(this_id->username) ||
   549                                 strcasecmp(this_id->username, this_id->address) == 0 ||
   550                                 (identity->username && 
   551                                  strcasecmp(identity->username, 
   552                                             this_id->username) == 0)) {
   553                                 
   554                                 // Ok, we have a temp ID. We have to replace this
   555                                 // with the real ID.
   556                                 status = replace_userid(session, 
   557                                                         this_uid, 
   558                                                         identity->user_id);
   559                                 if (status != PEP_STATUS_OK) {
   560                                     free_identity_list(id_list);
   561                                     return status;
   562                                 }
   563                                     
   564                                 free(this_uid);
   565                                 this_uid = NULL;
   566                                 
   567                                 // Reflect the change we just made to the DB
   568                                 this_id->user_id = strdup(identity->user_id);
   569                                 stored_ident = this_id;
   570                                 // FIXME: free list.
   571                                 break;                                
   572                             }                            
   573                         } 
   574                     }
   575                     id_curr = id_curr->next;
   576                 }
   577             }
   578         } 
   579                 
   580         if (status == PEP_STATUS_OK && stored_ident) { 
   581             //  * if identity available
   582             //      * patch it with username
   583             //          (note: this will happen when 
   584             //           setting automatically below...)
   585             //      * elect valid key for identity
   586             //    * if valid key exists
   587             //        * set return value's fpr
   588             status = prepare_updated_identity(session,
   589                                               identity,
   590                                               stored_ident, true);
   591         }
   592         //  * else (identity unavailable)
   593         else {
   594             status = PEP_STATUS_OK;
   595 
   596             // FIXME: We may need to roll this back.
   597             // FIXME: change docs if we don't
   598             //  if we only have user_id and address and identity not available
   599             //      * return error status (identity not found)
   600             if (EMPTYSTR(identity->username)) {
   601                 free(identity->username);
   602                 identity->username = strdup(identity->address);
   603             }
   604             
   605             // Otherwise, if we had user_id, address, and username:
   606             //    * create identity with user_id, address, username
   607             //      (this is the input id without the fpr + comm type!)
   608 
   609             if (status == PEP_STATUS_OK) {
   610                 elect_pubkey(session, identity, false);
   611             }
   612                         
   613             //    * We've already checked and retrieved
   614             //      any applicable temporary identities above. If we're 
   615             //      here, none of them fit.
   616             //    * call set_identity() to store
   617             if (status == PEP_STATUS_OK) {
   618                 // FIXME: Do we set if we had to copy in the address?
   619                 adjust_pep_trust_status(session, identity);
   620                 status = set_identity(session, identity);
   621             }
   622             //  * Return: created identity
   623         }        
   624     }
   625     else if (!EMPTYSTR(identity->username)) {
   626         /*
   627          * Temporary identity information with username supplied
   628             * Input: address, username (no others)
   629          */
   630          
   631         //  * See if there is an own identity that uses this address. If so, we'll
   632         //    prefer that
   633         stored_ident = NULL;
   634         
   635         if (default_own_id) {
   636             status = get_identity(session, 
   637                                   identity->address, 
   638                                   default_own_id, 
   639                                   &stored_ident);
   640         }
   641         // If there isn't an own identity, search for a non-temp stored ident
   642         // with this address.                      
   643         if (status == PEP_CANNOT_FIND_IDENTITY || !stored_ident) { 
   644  
   645             identity_list* id_list = NULL;
   646             status = get_identities_by_address(session, identity->address, &id_list);
   647 
   648             if (id_list) {
   649                 identity_list* id_curr = id_list;
   650                 while (id_curr) {
   651                     pEp_identity* this_id = id_curr->ident;
   652                     if (this_id) {
   653                         char* this_uid = this_id->user_id;
   654                         if (this_uid && (strstr(this_uid, "TOFU_") != this_uid)) {
   655                             // if usernames match, we replace the userid.
   656                             if (identity->username && 
   657                                 strcasecmp(identity->username, 
   658                                            this_id->username) == 0) {
   659                                 
   660                                 // Ok, we have a real ID. Copy it!
   661                                 identity->user_id = strdup(this_uid);
   662                                 
   663                                 if (!identity->user_id)
   664                                     status = PEP_OUT_OF_MEMORY;
   665                                 stored_ident = this_id;
   666                                 
   667                                 break;                                
   668                             }                            
   669                         } 
   670                     }
   671                     id_curr = id_curr->next;
   672                 }
   673             }
   674         }
   675         
   676         if (stored_ident) {
   677             status = prepare_updated_identity(session,
   678                                               identity,
   679                                               stored_ident, true);
   680         }
   681         else {
   682             identity->user_id = calloc(1, strlen(identity->address) + 6);
   683             if (!identity->user_id)
   684                 return PEP_OUT_OF_MEMORY;
   685 
   686             snprintf(identity->user_id, strlen(identity->address) + 6,
   687                      "TOFU_%s", identity->address);        
   688 
   689             status = get_identity(session, 
   690                                   identity->address, 
   691                                   identity->user_id, 
   692                                   &stored_ident);
   693 
   694             if (status == PEP_STATUS_OK && stored_ident) {
   695                 status = prepare_updated_identity(session,
   696                                                   identity,
   697                                                   stored_ident, true);
   698             }
   699             else {
   700                          
   701                 //    * We've already checked and retrieved
   702                 //      any applicable temporary identities above. If we're 
   703                 //      here, none of them fit.
   704                 
   705                 status = elect_pubkey(session, identity, false);
   706                              
   707                 //    * call set_identity() to store
   708                 if (identity->fpr)
   709                     status = get_key_rating(session, identity->fpr, &identity->comm_type);
   710             
   711                 //    * call set_identity() to store
   712                 adjust_pep_trust_status(session, identity);            
   713                 status = set_identity(session, identity);
   714             }
   715         }
   716     }
   717     else {
   718         /*
   719         * Input: address (no others)
   720          * Temporary identity information without username suplied
   721          */
   722          
   723         //  * Again, see if there is an own identity that uses this address. If so, we'll
   724         //    prefer that
   725         stored_ident = NULL;
   726          
   727         if (default_own_id) {
   728             status = get_identity(session, 
   729                                   identity->address, 
   730                                   default_own_id, 
   731                                   &stored_ident);
   732         }
   733         // If there isn't an own identity, search for a non-temp stored ident
   734         // with this address.                      
   735         if (status == PEP_CANNOT_FIND_IDENTITY || !stored_ident) { 
   736  
   737             identity_list* id_list = NULL;
   738             //    * Search for identity with this address
   739             status = get_identities_by_address(session, identity->address, &id_list);
   740 
   741             // Results are ordered by timestamp descending, so this covers
   742             // both the one-result and multi-result cases
   743             if (id_list) {
   744                 if (stored_ident) // unlikely
   745                     free_identity(stored_ident);
   746                 stored_ident = id_list->ident;
   747             }
   748         }
   749         if (stored_ident)
   750             status = prepare_updated_identity(session, identity,
   751                                               stored_ident, false);
   752         else  {            
   753             // too little info. BUT. We see if we can find a key; if so, we create a
   754             // temp identity, look for a key, and store.
   755                          
   756             // create temporary identity, store it, and Return this
   757             // This means TOFU_ user_id
   758             identity->user_id = calloc(1, strlen(identity->address) + 6);
   759             if (!identity->user_id)
   760                 return PEP_OUT_OF_MEMORY;
   761 
   762             snprintf(identity->user_id, strlen(identity->address) + 6,
   763                      "TOFU_%s", identity->address);        
   764         
   765             identity->username = strdup(identity->address);
   766             if (!identity->address)
   767                 return PEP_OUT_OF_MEMORY;            
   768             
   769             free(identity->fpr);
   770             identity->fpr = NULL;
   771             identity->comm_type = PEP_ct_unknown;
   772 
   773             status = elect_pubkey(session, identity, false);
   774                          
   775             if (identity->fpr)
   776                 status = get_key_rating(session, identity->fpr, &identity->comm_type);
   777         
   778             //    * call set_identity() to store
   779             adjust_pep_trust_status(session, identity);            
   780             status = set_identity(session, identity);
   781 
   782         }
   783             
   784     }
   785     
   786     // FIXME: This is legacy. I presume it's a notification for the caller...
   787     // Revisit once I can talk to Volker
   788     if (identity->comm_type != PEP_ct_compromized &&
   789         identity->comm_type < PEP_ct_strong_but_unconfirmed)
   790         if (session->examine_identity)
   791             session->examine_identity(identity, session->examine_management);
   792 
   793     return status;
   794 }
   795 
   796 PEP_STATUS elect_ownkey(
   797         PEP_SESSION session, pEp_identity * identity
   798     )
   799 {
   800     PEP_STATUS status;
   801     stringlist_t *keylist = NULL;
   802 
   803     free(identity->fpr);
   804     identity->fpr = NULL;
   805 
   806     status = find_private_keys(session, identity->address, &keylist);
   807     assert(status != PEP_OUT_OF_MEMORY);
   808     if (status == PEP_OUT_OF_MEMORY)
   809         return PEP_OUT_OF_MEMORY;
   810     
   811     if (keylist != NULL && keylist->value != NULL)
   812     {
   813         char *_fpr = NULL;
   814         identity->comm_type = PEP_ct_unknown;
   815 
   816         stringlist_t *_keylist;
   817         for (_keylist = keylist; _keylist && _keylist->value; _keylist = _keylist->next) {
   818             bool is_own = false;
   819             
   820             status = own_key_is_listed(session, _keylist->value, &is_own);
   821             assert(status == PEP_STATUS_OK);
   822             if (status != PEP_STATUS_OK) {
   823                 free_stringlist(keylist);
   824                 return status;
   825             }
   826             
   827             if (is_own)
   828             {
   829                 PEP_comm_type _comm_type_key;
   830                 
   831                 status = get_key_rating(session, _keylist->value, &_comm_type_key);
   832                 assert(status != PEP_OUT_OF_MEMORY);
   833                 if (status == PEP_OUT_OF_MEMORY) {
   834                     free_stringlist(keylist);
   835                     return PEP_OUT_OF_MEMORY;
   836                 }
   837                 
   838                 if (_comm_type_key != PEP_ct_compromized &&
   839                     _comm_type_key != PEP_ct_unknown)
   840                 {
   841                     if (identity->comm_type == PEP_ct_unknown ||
   842                         _comm_type_key > identity->comm_type)
   843                     {
   844                         identity->comm_type = _comm_type_key;
   845                         _fpr = _keylist->value;
   846                     }
   847                 }
   848             }
   849         }
   850         
   851         if (_fpr)
   852         {
   853             identity->fpr = strdup(_fpr);
   854             assert(identity->fpr);
   855             if (identity->fpr == NULL)
   856             {
   857                 free_stringlist(keylist);
   858                 return PEP_OUT_OF_MEMORY;
   859             }
   860         }
   861         free_stringlist(keylist);
   862     }
   863     return PEP_STATUS_OK;
   864 }
   865 
   866 PEP_STATUS _has_usable_priv_key(PEP_SESSION session, char* fpr,
   867                                 bool* is_usable) {
   868     
   869     bool has_private = false;
   870     PEP_STATUS status = contains_priv_key(session, fpr, &has_private);
   871     
   872     *is_usable = has_private;
   873     
   874     return status;
   875 }
   876 
   877 PEP_STATUS _myself(PEP_SESSION session, pEp_identity * identity, bool do_keygen, bool ignore_flags)
   878 {
   879 
   880     PEP_STATUS status;
   881 
   882     assert(session);
   883     assert(identity);
   884     assert(!EMPTYSTR(identity->address));
   885     assert(!EMPTYSTR(identity->user_id));
   886 
   887     if (!session || !identity || EMPTYSTR(identity->address) ||
   888         EMPTYSTR(identity->user_id))
   889         return PEP_ILLEGAL_VALUE;
   890 
   891     pEp_identity *stored_identity = NULL;
   892     char* revoked_fpr = NULL; 
   893     bool valid_key_found = false;
   894         
   895     char* default_own_id = NULL;
   896     status = get_default_own_userid(session, &default_own_id);
   897 
   898     // Deal with non-default user_ids.
   899     if (default_own_id && strcmp(default_own_id, identity->user_id) != 0) {
   900         
   901         status = set_userid_alias(session, default_own_id, identity->user_id);
   902         // Do we want this to be fatal? For now, we'll do it...
   903         if (status != PEP_STATUS_OK)
   904             goto pep_free;
   905             
   906         free(identity->user_id);
   907         identity->user_id = strdup(default_own_id);
   908         if (identity->user_id == NULL) {
   909             status = PEP_OUT_OF_MEMORY;
   910             goto pep_free;
   911         }
   912     }
   913 
   914     // NOTE: IF WE DON'T YET HAVE AN OWN_ID, WE IGNORE REFERENCES TO THIS ADDRESS IN THE
   915     // DB (WHICH MAY HAVE BEEN SET BEFORE MYSELF WAS CALLED BY RECEIVING AN EMAIL FROM
   916     // THIS ADDRESS), AS IT IS NOT AN OWN_IDENTITY AND HAS NO INFORMATION WE NEED OR WHAT TO
   917     // SET FOR MYSELF
   918     
   919     // Ok, so now, set up the own_identity:
   920     identity->comm_type = PEP_ct_pEp;
   921     identity->me = true;
   922     if(ignore_flags)
   923         identity->flags = 0;
   924     
   925     // Let's see if we have an identity record in the DB for 
   926     // this user_id + address
   927 //    DEBUG_LOG("myself", "debug", identity->address);
   928  
   929     status = get_identity(session,
   930                           identity->address,
   931                           identity->user_id,
   932                           &stored_identity);
   933 
   934     assert(status != PEP_OUT_OF_MEMORY);
   935     if (status == PEP_OUT_OF_MEMORY) {
   936         status = PEP_OUT_OF_MEMORY;
   937         goto pep_free;
   938     }
   939 
   940     // Set usernames - priority is input username > stored name > address
   941     // If there's an input username, we always patch the username with that
   942     // input.
   943     if (EMPTYSTR(identity->username)) {
   944         bool stored_uname = (stored_identity && !EMPTYSTR(stored_identity->username));
   945         char* uname = (stored_uname ? stored_identity->username : identity->address);
   946         free(identity->username);
   947         identity->username = strdup(uname);
   948         if (identity->username == NULL) {
   949             status = PEP_OUT_OF_MEMORY;
   950             goto pep_free;
   951         }
   952     }
   953 
   954     // ignore input fpr
   955 
   956     if (identity->fpr) {
   957         free(identity->fpr);
   958         identity->fpr = NULL;
   959     }
   960 
   961     // check stored identity
   962     if (stored_identity && !EMPTYSTR(stored_identity->fpr)) {
   963         // Fall back / retrieve
   964         status = validate_fpr(session, stored_identity, false);
   965         if (status == PEP_OUT_OF_MEMORY)
   966             goto pep_free;
   967         if (status == PEP_STATUS_OK) {
   968             if (stored_identity->comm_type >= PEP_ct_strong_but_unconfirmed) {
   969                 identity->fpr = strdup(stored_identity->fpr);
   970                 assert(identity->fpr);
   971                 if (!identity->fpr) {
   972                     status = PEP_OUT_OF_MEMORY;
   973                     goto pep_free;
   974                 }
   975                 valid_key_found = true;            
   976             }
   977             else {
   978                 bool revoked = false;
   979                 status = key_revoked(session, stored_identity->fpr, &revoked);
   980                 if (status)
   981                     goto pep_free;
   982                 if (revoked) {
   983                     revoked_fpr = strdup(stored_identity->fpr);
   984                     assert(revoked_fpr);
   985                     if (!revoked_fpr) {
   986                         status = PEP_OUT_OF_MEMORY;
   987                         goto pep_free;
   988                     }
   989                 }
   990             }
   991         }
   992     }
   993     
   994     // Nothing left to do but generate a key
   995     if (!valid_key_found) {
   996         if (!do_keygen)
   997             status = PEP_GET_KEY_FAILED;
   998         else {
   999 // /            DEBUG_LOG("Generating key pair", "debug", identity->address);
  1000 
  1001             free(identity->fpr);
  1002             identity->fpr = NULL;
  1003             status = generate_keypair(session, identity);
  1004             assert(status != PEP_OUT_OF_MEMORY);
  1005 
  1006             if (status != PEP_STATUS_OK) {
  1007                 char buf[11];
  1008                 snprintf(buf, 11, "%d", status); // uh, this is kludgey. FIXME
  1009 //                DEBUG_LOG("Generating key pair failed", "debug", buf);
  1010             }        
  1011             else {
  1012                 valid_key_found = true;
  1013                 if (revoked_fpr) {
  1014                     status = set_revoked(session, revoked_fpr,
  1015                                          stored_identity->fpr, time(NULL));
  1016                 }
  1017             }
  1018         }
  1019     }
  1020 
  1021     if (valid_key_found) {
  1022         identity->comm_type = PEP_ct_pEp;
  1023         status = PEP_STATUS_OK;
  1024     }
  1025     else {
  1026         free(identity->fpr);
  1027         identity->fpr = NULL;
  1028         identity->comm_type = PEP_ct_unknown;
  1029     }
  1030     
  1031     status = set_identity(session, identity);
  1032     if (status == PEP_STATUS_OK)
  1033         status = set_as_pep_user(session, identity);
  1034 
  1035 pep_free:    
  1036     free(default_own_id);
  1037     free(revoked_fpr);                     
  1038     free_identity(stored_identity);
  1039     return status;
  1040 }
  1041 
  1042 // DYNAMIC_API PEP_STATUS initialise_own_identities(PEP_SESSION session,
  1043 //                                                  identity_list* my_idents) {
  1044 //     PEP_STATUS status = PEP_STATUS_OK;
  1045 //     if (!session)
  1046 //         return PEP_ILLEGAL_VALUE;
  1047 //         
  1048 //     if (!my_idents)
  1049 //         return PEP_STATUS_OK;
  1050 //             
  1051 //     identity_list* ident_curr = my_idents;
  1052 //     while (ident_curr) {
  1053 //         pEp_identity* ident = ident_curr->ident;
  1054 //         if (!ident || !ident->address) {
  1055 //             status = PEP_ILLEGAL_VALUE;
  1056 //             goto pep_error;
  1057 //         }
  1058 // 
  1059 //         status = _myself(session, ident, false, false);
  1060 //         
  1061 //         ident_curr = ident_curr->next;
  1062 //     }
  1063 //     
  1064 // pep_error:
  1065 //     return status;
  1066 // }
  1067 
  1068 DYNAMIC_API PEP_STATUS myself(PEP_SESSION session, pEp_identity * identity)
  1069 {
  1070     return _myself(session, identity, true, false);
  1071 }
  1072 
  1073 DYNAMIC_API PEP_STATUS register_examine_function(
  1074         PEP_SESSION session, 
  1075         examine_identity_t examine_identity,
  1076         void *management
  1077     )
  1078 {
  1079     assert(session);
  1080     if (!session)
  1081         return PEP_ILLEGAL_VALUE;
  1082 
  1083     session->examine_management = management;
  1084     session->examine_identity = examine_identity;
  1085 
  1086     return PEP_STATUS_OK;
  1087 }
  1088 
  1089 DYNAMIC_API PEP_STATUS do_keymanagement(
  1090         retrieve_next_identity_t retrieve_next_identity,
  1091         void *management
  1092     )
  1093 {
  1094     PEP_SESSION session;
  1095     pEp_identity *identity;
  1096     PEP_STATUS status;
  1097 
  1098     assert(retrieve_next_identity);
  1099     assert(management);
  1100 
  1101     if (!retrieve_next_identity || !management)
  1102         return PEP_ILLEGAL_VALUE;
  1103 
  1104     status = init(&session);
  1105     assert(status == PEP_STATUS_OK);
  1106     if (status != PEP_STATUS_OK)
  1107         return status;
  1108 
  1109     log_event(session, "keymanagement thread started", "pEp engine", NULL, NULL);
  1110 
  1111     while ((identity = retrieve_next_identity(management))) 
  1112     {
  1113         assert(identity->address);
  1114         if(identity->address)
  1115         {
  1116             DEBUG_LOG("do_keymanagement", "retrieve_next_identity", identity->address);
  1117 
  1118             if (identity->me) {
  1119                 status = myself(session, identity);
  1120             } else {
  1121                 status = recv_key(session, identity->address);
  1122             }
  1123 
  1124             assert(status != PEP_OUT_OF_MEMORY);
  1125             if(status == PEP_OUT_OF_MEMORY)
  1126                 return PEP_OUT_OF_MEMORY;
  1127         }
  1128         free_identity(identity);
  1129     }
  1130 
  1131     log_event(session, "keymanagement thread shutdown", "pEp engine", NULL, NULL);
  1132 
  1133     release(session);
  1134     return PEP_STATUS_OK;
  1135 }
  1136 
  1137 DYNAMIC_API PEP_STATUS key_mistrusted(
  1138         PEP_SESSION session,
  1139         pEp_identity *ident
  1140     )
  1141 {
  1142     PEP_STATUS status = PEP_STATUS_OK;
  1143 
  1144     assert(session);
  1145     assert(ident);
  1146     assert(!EMPTYSTR(ident->fpr));
  1147 
  1148     if (!(session && ident && ident->fpr))
  1149         return PEP_ILLEGAL_VALUE;
  1150 
  1151     if (ident->me)
  1152     {
  1153         revoke_key(session, ident->fpr, NULL);
  1154         myself(session, ident);
  1155     }
  1156     else
  1157     {
  1158         // for undo
  1159         if (session->cached_mistrusted)
  1160             free(session->cached_mistrusted);
  1161         session->cached_mistrusted = identity_dup(ident);
  1162         
  1163         // set mistrust for this user_id/keypair (even if there's not an
  1164         // identity set yet, this is important, as we need to record the mistrust
  1165         // action)
  1166         
  1167         // double-check to be sure key is even in the DB
  1168         if (ident->fpr)
  1169             status = set_pgp_keypair(session, ident->fpr);
  1170 
  1171         // We set this temporarily but will grab it back from the cache afterwards
  1172         ident->comm_type = PEP_ct_mistrusted;
  1173         status = set_trust(session, ident);
  1174         ident->comm_type = session->cached_mistrusted->comm_type;
  1175         
  1176         if (status == PEP_STATUS_OK)
  1177             // cascade that mistrust for anyone using this key
  1178             status = mark_as_compromized(session, ident->fpr);
  1179         if (status == PEP_STATUS_OK)
  1180             status = remove_fpr_as_default(session, ident->fpr);
  1181         if (status == PEP_STATUS_OK)
  1182             status = add_mistrusted_key(session, ident->fpr);
  1183     }
  1184 
  1185     return status;
  1186 }
  1187 
  1188 DYNAMIC_API PEP_STATUS undo_last_mistrust(PEP_SESSION session) {
  1189     assert(session);
  1190     
  1191     if (!session)
  1192         return PEP_ILLEGAL_VALUE;
  1193     
  1194     PEP_STATUS status = PEP_STATUS_OK;
  1195         
  1196     pEp_identity* cached_ident = session->cached_mistrusted;
  1197     
  1198     if (!cached_ident)
  1199         status = PEP_CANNOT_FIND_IDENTITY;
  1200     else {
  1201         status = delete_mistrusted_key(session, cached_ident->fpr);
  1202         if (status == PEP_STATUS_OK) {
  1203             status = set_identity(session, cached_ident);
  1204             // THIS SHOULDN'T BE NECESSARY - PREVIOUS VALUE WAS IN THE DB
  1205             // if (status == PEP_STATUS_OK) {
  1206             //     if ((cached_ident->comm_type | PEP_ct_confirmed) == PEP_ct_pEp)
  1207             //         status = set_as_pep_user(session, cached_ident);
  1208             // }            
  1209             free_identity(session->cached_mistrusted);
  1210         }
  1211     }
  1212     
  1213     session->cached_mistrusted = NULL;
  1214     
  1215     return status;
  1216 }
  1217 
  1218 DYNAMIC_API PEP_STATUS key_reset_trust(
  1219         PEP_SESSION session,
  1220         pEp_identity *ident
  1221     )
  1222 {
  1223     PEP_STATUS status = PEP_STATUS_OK;
  1224 
  1225     assert(session);
  1226     assert(ident);
  1227     assert(!EMPTYSTR(ident->fpr));
  1228     assert(!EMPTYSTR(ident->address));
  1229     assert(!EMPTYSTR(ident->user_id));
  1230 
  1231     if (!(session && ident && ident->fpr && ident->fpr[0] != '\0' && ident->address &&
  1232             ident->user_id))
  1233         return PEP_ILLEGAL_VALUE;
  1234 
  1235     // we do not change the input struct at ALL.
  1236     pEp_identity* input_copy = identity_dup(ident);
  1237     
  1238     pEp_identity* tmp_ident = NULL;
  1239     
  1240     status = get_trust(session, input_copy);
  1241     
  1242     if (status != PEP_STATUS_OK)
  1243         goto pep_free;
  1244         
  1245     PEP_comm_type new_trust = PEP_ct_unknown;
  1246 
  1247     if (input_copy->comm_type != PEP_ct_mistrusted)
  1248         new_trust = input_copy->comm_type & ~PEP_ct_confirmed;
  1249 
  1250     // We'll return the status from the input_copy cache afterward
  1251     input_copy->comm_type = new_trust;
  1252     status = set_trust(session, input_copy);
  1253     
  1254     if (status != PEP_STATUS_OK)
  1255         goto pep_free;
  1256 
  1257     bool mistrusted_key = false;
  1258         
  1259     status = is_mistrusted_key(session, ident->fpr, &mistrusted_key);
  1260 
  1261     if (status != PEP_STATUS_OK)
  1262         goto pep_free;
  1263     
  1264     if (mistrusted_key)
  1265         status = delete_mistrusted_key(session, ident->fpr);
  1266 
  1267     if (status != PEP_STATUS_OK)
  1268         goto pep_free;
  1269         
  1270     tmp_ident = new_identity(ident->address, NULL, ident->user_id, NULL);
  1271 
  1272     if (!tmp_ident)
  1273         return PEP_OUT_OF_MEMORY;
  1274     
  1275     status = update_identity(session, tmp_ident);
  1276     
  1277     if (status != PEP_STATUS_OK)
  1278         goto pep_free;
  1279     
  1280     // remove as default if necessary
  1281     if (!EMPTYSTR(tmp_ident->fpr) && strcmp(tmp_ident->fpr, ident->fpr) == 0) {
  1282         free(tmp_ident->fpr);
  1283         tmp_ident->fpr = NULL;
  1284         tmp_ident->comm_type = PEP_ct_unknown;
  1285         status = set_identity(session, tmp_ident);
  1286         if (status != PEP_STATUS_OK)
  1287             goto pep_free;
  1288     }
  1289     
  1290     char* user_default = NULL;
  1291     status = get_main_user_fpr(session, tmp_ident->user_id, &user_default);
  1292     
  1293     if (!EMPTYSTR(user_default)) {
  1294         if (strcmp(user_default, ident->fpr) == 0)
  1295             status = refresh_userid_default_key(session, ident->user_id);
  1296         if (status != PEP_STATUS_OK)
  1297             goto pep_free;    
  1298     }
  1299             
  1300 pep_free:
  1301     free_identity(tmp_ident);
  1302     free_identity(input_copy);
  1303     return status;
  1304 }
  1305 
  1306 DYNAMIC_API PEP_STATUS trust_personal_key(
  1307         PEP_SESSION session,
  1308         pEp_identity *ident
  1309     )
  1310 {
  1311     PEP_STATUS status = PEP_STATUS_OK;
  1312 
  1313     assert(session);
  1314     assert(ident);
  1315     assert(!EMPTYSTR(ident->address));
  1316     assert(!EMPTYSTR(ident->user_id));
  1317     assert(!EMPTYSTR(ident->fpr));
  1318 
  1319     if (!ident || EMPTYSTR(ident->address) || EMPTYSTR(ident->user_id) ||
  1320             EMPTYSTR(ident->fpr))
  1321         return PEP_ILLEGAL_VALUE;
  1322 
  1323     //bool ident_has_trusted_default = false;
  1324     char* ident_default_fpr = NULL;
  1325 
  1326     // Before we do anything, be sure the input fpr is even eligible to be trusted
  1327     PEP_comm_type input_default_ct = PEP_ct_unknown;
  1328     status = get_key_rating(session, ident->fpr, &input_default_ct);
  1329     if (input_default_ct < PEP_ct_strong_but_unconfirmed)
  1330         return PEP_KEY_UNSUITABLE;
  1331 
  1332     status = set_pgp_keypair(session, ident->fpr);
  1333     if (status != PEP_STATUS_OK)
  1334         return status;
  1335 
  1336     bool me = is_me(session, ident);
  1337 
  1338     pEp_identity* ident_copy = identity_dup(ident);
  1339     char* cached_fpr = NULL;
  1340 
  1341     // for setting up a temp trusted identity for the input fpr
  1342     pEp_identity* tmp_id = NULL;
  1343 
  1344     // For later, in case we need to check the user default key
  1345     pEp_identity* tmp_user_ident = NULL;
  1346 
  1347     if (me) {
  1348         bool has_private = false;
  1349         // first of all, does this key even have a private component.
  1350         status = contains_priv_key(session, ident->fpr, &has_private);
  1351         if (status != PEP_STATUS_OK && status != PEP_KEY_NOT_FOUND)
  1352             goto pep_free;
  1353             
  1354         if (has_private) {
  1355             status = set_own_key(session, ident_copy, ident->fpr); 
  1356             goto pep_free;
  1357         }
  1358     }
  1359     
  1360     // Either it's not me, or it's me but the key has no private key. 
  1361     // We're only talking about pub keys here. Moving on.
  1362     
  1363     // Save the input fpr, which we already tested as non-NULL
  1364     cached_fpr = strdup(ident->fpr);
  1365 
  1366     // Set up a temp trusted identity for the input fpr without a comm type;
  1367     tmp_id = new_identity(ident->address, ident->fpr, ident->user_id, NULL);
  1368     
  1369     // ->me isn't set, even if this is an own identity, so this will work.
  1370     status = validate_fpr(session, tmp_id, false);
  1371         
  1372     if (status == PEP_STATUS_OK) {
  1373         // Validate fpr gets trust DB or, when that fails, key comm type. we checked
  1374         // above that the key was ok. (not revoked or expired), but we want the max.
  1375         tmp_id->comm_type = _MAX(tmp_id->comm_type, input_default_ct) | PEP_ct_confirmed;
  1376 
  1377         // Get the default identity without setting the fpr                                       
  1378         if (me)
  1379             status = _myself(session, ident_copy, false, true);
  1380         else    
  1381             status = update_identity(session, ident_copy);
  1382             
  1383         ident_default_fpr = (EMPTYSTR(ident_copy->fpr) ? NULL : strdup(ident_copy->fpr));
  1384 
  1385         if (status == PEP_STATUS_OK) {
  1386             bool trusted_default = false;
  1387 
  1388             // If there's no default, or the default is different from the input...
  1389             if (me || EMPTYSTR(ident_default_fpr) || strcmp(cached_fpr, ident_default_fpr) != 0) {
  1390                 
  1391                 // If the default fpr (if there is one) is trusted and key is strong enough,
  1392                 // don't replace, we just set the trusted bit on this key for this user_id...
  1393                 // (If there's no default fpr, this won't be true anyway.)
  1394                 if (me || (ident_copy->comm_type >= PEP_ct_strong_but_unconfirmed && 
  1395                           (ident_copy->comm_type & PEP_ct_confirmed))) {                        
  1396 
  1397                     trusted_default = true;
  1398                                     
  1399                     status = set_trust(session, tmp_id);
  1400                     input_default_ct = tmp_id->comm_type;                    
  1401                 }
  1402                 else {
  1403                     free(ident_copy->fpr);
  1404                     ident_copy->fpr = strdup(cached_fpr);
  1405                     ident_copy->comm_type = tmp_id->comm_type;
  1406                     status = set_identity(session, ident_copy); // replace identity default
  1407                     if (status == PEP_STATUS_OK) {
  1408                         if ((ident_copy->comm_type | PEP_ct_confirmed) == PEP_ct_pEp)
  1409                             status = set_as_pep_user(session, ident_copy);
  1410                     }            
  1411                 }
  1412             }
  1413             else { // we're setting this on the default fpr
  1414                 ident->comm_type = tmp_id->comm_type;
  1415                 status = set_identity(session, ident);
  1416                 trusted_default = true;
  1417             }
  1418             if (status == PEP_STATUS_OK && !trusted_default) {
  1419                 // Ok, there wasn't a trusted default, so we replaced. Thus, we also
  1420                 // make sure there's a trusted default on the user_id. If there
  1421                 // is not, we make this the default.
  1422                 char* user_default = NULL;
  1423                 status = get_main_user_fpr(session, ident->user_id, &user_default);
  1424             
  1425                 if (status == PEP_STATUS_OK && user_default) {
  1426                     tmp_user_ident = new_identity(ident->address, 
  1427                                                   user_default, 
  1428                                                   ident->user_id, 
  1429                                                   NULL);
  1430                     if (!tmp_user_ident)
  1431                         status = PEP_OUT_OF_MEMORY;
  1432                     else {
  1433                         status = validate_fpr(session, tmp_user_ident, false);
  1434                         
  1435                         if (status != PEP_STATUS_OK ||
  1436                             tmp_user_ident->comm_type < PEP_ct_strong_but_unconfirmed ||
  1437                             !(tmp_user_ident->comm_type & PEP_ct_confirmed)) 
  1438                         {
  1439                             char* trusted_fpr = (trusted_default ? ident_default_fpr : cached_fpr);
  1440                             status = replace_main_user_fpr(session, ident->user_id, trusted_fpr);
  1441                         } 
  1442                     }
  1443                 }
  1444             }
  1445         }
  1446     }    
  1447 
  1448 pep_free:
  1449     free(ident_default_fpr);
  1450     free(cached_fpr);
  1451     free_identity(tmp_id);
  1452     free_identity(ident_copy);
  1453     free_identity(tmp_user_ident);
  1454     return status;
  1455 }
  1456 
  1457 DYNAMIC_API PEP_STATUS own_key_is_listed(
  1458         PEP_SESSION session,
  1459         const char *fpr,
  1460         bool *listed
  1461     )
  1462 {
  1463     PEP_STATUS status = PEP_STATUS_OK;
  1464     int count;
  1465     
  1466     assert(session && fpr && fpr[0] && listed);
  1467     
  1468     if (!(session && fpr && fpr[0] && listed))
  1469         return PEP_ILLEGAL_VALUE;
  1470     
  1471     *listed = false;
  1472     
  1473     sqlite3_reset(session->own_key_is_listed);
  1474     sqlite3_bind_text(session->own_key_is_listed, 1, fpr, -1, SQLITE_STATIC);
  1475     
  1476     int result;
  1477     
  1478     result = sqlite3_step(session->own_key_is_listed);
  1479     switch (result) {
  1480         case SQLITE_ROW:
  1481             count = sqlite3_column_int(session->own_key_is_listed, 0);
  1482             *listed = count > 0;
  1483             status = PEP_STATUS_OK;
  1484             break;
  1485             
  1486         default:
  1487             status = PEP_UNKNOWN_ERROR;
  1488     }
  1489     
  1490     sqlite3_reset(session->own_key_is_listed);
  1491     return status;
  1492 }
  1493 
  1494 PEP_STATUS _own_identities_retrieve(
  1495         PEP_SESSION session,
  1496         identity_list **own_identities,
  1497         identity_flags_t excluded_flags
  1498       )
  1499 {
  1500     PEP_STATUS status = PEP_STATUS_OK;
  1501     
  1502     assert(session && own_identities);
  1503     if (!(session && own_identities))
  1504         return PEP_ILLEGAL_VALUE;
  1505     
  1506     *own_identities = NULL;
  1507     identity_list *_own_identities = new_identity_list(NULL);
  1508     if (_own_identities == NULL)
  1509         goto enomem;
  1510     
  1511     sqlite3_reset(session->own_identities_retrieve);
  1512     
  1513     int result;
  1514     // address, fpr, username, user_id, comm_type, lang, flags
  1515     const char *address = NULL;
  1516     const char *fpr = NULL;
  1517     const char *username = NULL;
  1518     const char *user_id = NULL;
  1519     PEP_comm_type comm_type = PEP_ct_unknown;
  1520     const char *lang = NULL;
  1521     unsigned int flags = 0;
  1522     
  1523     identity_list *_bl = _own_identities;
  1524     do {
  1525         sqlite3_bind_int(session->own_identities_retrieve, 1, excluded_flags);
  1526         result = sqlite3_step(session->own_identities_retrieve);
  1527         switch (result) {
  1528             case SQLITE_ROW:
  1529                 address = (const char *)
  1530                     sqlite3_column_text(session->own_identities_retrieve, 0);
  1531                 fpr = (const char *)
  1532                     sqlite3_column_text(session->own_identities_retrieve, 1);
  1533                 user_id = (const char *)
  1534                     sqlite3_column_text(session->own_identities_retrieve, 2);
  1535                 username = (const char *)
  1536                     sqlite3_column_text(session->own_identities_retrieve, 3);
  1537                 comm_type = PEP_ct_pEp;
  1538                 lang = (const char *)
  1539                     sqlite3_column_text(session->own_identities_retrieve, 4);
  1540                 flags = (unsigned int)
  1541                     sqlite3_column_int(session->own_identities_retrieve, 5);
  1542 
  1543                 pEp_identity *ident = new_identity(address, fpr, user_id, username);
  1544                 if (!ident)
  1545                     goto enomem;
  1546                 ident->comm_type = comm_type;
  1547                 if (lang && lang[0]) {
  1548                     ident->lang[0] = lang[0];
  1549                     ident->lang[1] = lang[1];
  1550                     ident->lang[2] = 0;
  1551                 }
  1552                 ident->me = true;
  1553                 ident->flags = flags;
  1554 
  1555                 _bl = identity_list_add(_bl, ident);
  1556                 if (_bl == NULL) {
  1557                     free_identity(ident);
  1558                     goto enomem;
  1559                 }
  1560                 
  1561                 break;
  1562                 
  1563             case SQLITE_DONE:
  1564                 break;
  1565                 
  1566             default:
  1567                 status = PEP_UNKNOWN_ERROR;
  1568                 result = SQLITE_DONE;
  1569         }
  1570     } while (result != SQLITE_DONE);
  1571     
  1572     sqlite3_reset(session->own_identities_retrieve);
  1573     if (status == PEP_STATUS_OK)
  1574         *own_identities = _own_identities;
  1575     else
  1576         free_identity_list(_own_identities);
  1577     
  1578     goto the_end;
  1579     
  1580 enomem:
  1581     free_identity_list(_own_identities);
  1582     status = PEP_OUT_OF_MEMORY;
  1583     
  1584 the_end:
  1585     return status;
  1586 }
  1587 
  1588 DYNAMIC_API PEP_STATUS own_identities_retrieve(
  1589         PEP_SESSION session,
  1590         identity_list **own_identities
  1591       )
  1592 {
  1593     return _own_identities_retrieve(session, own_identities, 0);
  1594 }
  1595 
  1596 PEP_STATUS _own_keys_retrieve(
  1597         PEP_SESSION session,
  1598         stringlist_t **keylist,
  1599         identity_flags_t excluded_flags
  1600       )
  1601 {
  1602     PEP_STATUS status = PEP_STATUS_OK;
  1603     
  1604     assert(session && keylist);
  1605     if (!(session && keylist))
  1606         return PEP_ILLEGAL_VALUE;
  1607     
  1608     *keylist = NULL;
  1609     stringlist_t *_keylist = NULL;
  1610     
  1611     sqlite3_reset(session->own_keys_retrieve);
  1612     
  1613     int result;
  1614     char *fpr = NULL;
  1615     
  1616     stringlist_t *_bl = _keylist;
  1617     do {
  1618         sqlite3_bind_int(session->own_keys_retrieve, 1, excluded_flags);
  1619         result = sqlite3_step(session->own_keys_retrieve);
  1620         switch (result) {
  1621             case SQLITE_ROW:
  1622                 fpr = strdup((const char *) sqlite3_column_text(session->own_keys_retrieve, 0));
  1623                 if(fpr == NULL)
  1624                     goto enomem;
  1625 
  1626                 _bl = stringlist_add(_bl, fpr);
  1627                 if (_bl == NULL) {
  1628                     free(fpr);
  1629                     goto enomem;
  1630                 }
  1631                 if (_keylist == NULL)
  1632                     _keylist = _bl;
  1633                 
  1634                 break;
  1635                 
  1636             case SQLITE_DONE:
  1637                 break;
  1638                 
  1639             default:
  1640                 status = PEP_UNKNOWN_ERROR;
  1641                 result = SQLITE_DONE;
  1642         }
  1643     } while (result != SQLITE_DONE);
  1644     
  1645     sqlite3_reset(session->own_keys_retrieve);
  1646     if (status == PEP_STATUS_OK)
  1647         *keylist = _keylist;
  1648     else
  1649         free_stringlist(_keylist);
  1650     
  1651     goto the_end;
  1652     
  1653 enomem:
  1654     free_stringlist(_keylist);
  1655     status = PEP_OUT_OF_MEMORY;
  1656     
  1657 the_end:
  1658     return status;
  1659 }
  1660 
  1661 DYNAMIC_API PEP_STATUS own_keys_retrieve(PEP_SESSION session, stringlist_t **keylist)
  1662 {
  1663     return _own_keys_retrieve(session, keylist, 0);
  1664 }
  1665 
  1666 DYNAMIC_API PEP_STATUS set_own_key(
  1667        PEP_SESSION session,
  1668        pEp_identity *me,
  1669        const char *fpr
  1670     )
  1671 {
  1672     PEP_STATUS status = PEP_STATUS_OK;
  1673     
  1674     assert(session && me);
  1675     assert(!EMPTYSTR(fpr));
  1676     assert(!EMPTYSTR(me->address));
  1677     assert(!EMPTYSTR(me->user_id));
  1678     assert(!EMPTYSTR(me->username));
  1679 
  1680     if (!session || !me || EMPTYSTR(fpr) || EMPTYSTR(me->address) ||
  1681             EMPTYSTR(me->user_id) || EMPTYSTR(me->username))
  1682         return PEP_ILLEGAL_VALUE;
  1683 
  1684     status = _myself(session, me, false, true);
  1685     // we do not need a valid key but dislike other errors
  1686     if (status != PEP_STATUS_OK && status != PEP_GET_KEY_FAILED && status != PEP_KEY_UNSUITABLE)
  1687         return status;
  1688     status = PEP_STATUS_OK;
  1689  
  1690     if (me->fpr)
  1691         free(me->fpr);
  1692     me->fpr = strdup(fpr);
  1693     assert(me->fpr);
  1694     if (!me->fpr)
  1695         return PEP_OUT_OF_MEMORY;
  1696 
  1697     status = validate_fpr(session, me, false);
  1698     if (status)
  1699         return status;
  1700 
  1701     me->comm_type = PEP_ct_pEp;
  1702     status = set_identity(session, me);
  1703     return status;
  1704 }
  1705 
  1706 PEP_STATUS contains_priv_key(PEP_SESSION session, const char *fpr,
  1707                              bool *has_private) {
  1708 
  1709     assert(session);
  1710     assert(fpr);
  1711     assert(has_private);
  1712     
  1713     if (!(session && fpr && has_private))
  1714         return PEP_ILLEGAL_VALUE;
  1715 
  1716     return session->cryptotech[PEP_crypt_OpenPGP].contains_priv_key(session, fpr, has_private);
  1717 }
  1718 
  1719 PEP_STATUS add_mistrusted_key(PEP_SESSION session, const char* fpr)
  1720 {
  1721     int result;
  1722 
  1723     assert(!EMPTYSTR(fpr));
  1724     
  1725     if (!(session) || EMPTYSTR(fpr))
  1726         return PEP_ILLEGAL_VALUE;
  1727 
  1728     sqlite3_reset(session->add_mistrusted_key);
  1729     sqlite3_bind_text(session->add_mistrusted_key, 1, fpr, -1,
  1730             SQLITE_STATIC);
  1731 
  1732     result = sqlite3_step(session->add_mistrusted_key);
  1733     sqlite3_reset(session->add_mistrusted_key);
  1734 
  1735     if (result != SQLITE_DONE)
  1736         return PEP_CANNOT_SET_PGP_KEYPAIR; // FIXME: Better status?
  1737 
  1738     return PEP_STATUS_OK;
  1739 }
  1740 
  1741 PEP_STATUS delete_mistrusted_key(PEP_SESSION session, const char* fpr)
  1742 {
  1743     int result;
  1744 
  1745     assert(!EMPTYSTR(fpr));
  1746     
  1747     if (!(session) || EMPTYSTR(fpr))
  1748         return PEP_ILLEGAL_VALUE;
  1749 
  1750     sqlite3_reset(session->delete_mistrusted_key);
  1751     sqlite3_bind_text(session->delete_mistrusted_key, 1, fpr, -1,
  1752             SQLITE_STATIC);
  1753 
  1754     result = sqlite3_step(session->delete_mistrusted_key);
  1755     sqlite3_reset(session->delete_mistrusted_key);
  1756 
  1757     if (result != SQLITE_DONE)
  1758         return PEP_UNKNOWN_ERROR; // FIXME: Better status?
  1759 
  1760     return PEP_STATUS_OK;
  1761 }
  1762 
  1763 PEP_STATUS is_mistrusted_key(PEP_SESSION session, const char* fpr,
  1764                              bool* mistrusted)
  1765 {
  1766     PEP_STATUS status = PEP_STATUS_OK;
  1767 
  1768     assert(session);
  1769     assert(!EMPTYSTR(fpr));
  1770 
  1771     if (!(session && fpr))
  1772         return PEP_ILLEGAL_VALUE;
  1773 
  1774     *mistrusted = false;
  1775 
  1776     sqlite3_reset(session->is_mistrusted_key);
  1777     sqlite3_bind_text(session->is_mistrusted_key, 1, fpr, -1, SQLITE_STATIC);
  1778 
  1779     int result;
  1780 
  1781     result = sqlite3_step(session->is_mistrusted_key);
  1782     switch (result) {
  1783     case SQLITE_ROW:
  1784         *mistrusted = sqlite3_column_int(session->is_mistrusted_key, 0);
  1785         status = PEP_STATUS_OK;
  1786         break;
  1787 
  1788     default:
  1789         status = PEP_UNKNOWN_ERROR;
  1790     }
  1791 
  1792     sqlite3_reset(session->is_mistrusted_key);
  1793     return status;
  1794 }
  1795 
  1796 #ifdef USE_GPG
  1797 PEP_STATUS pgp_find_trusted_private_keys(
  1798         PEP_SESSION session, stringlist_t **keylist
  1799     );
  1800 
  1801 enum _pgp_thing {
  1802     _pgp_none = 0,
  1803     _pgp_fpr,
  1804     _pgp_email,
  1805     _pgp_name
  1806 };
  1807 
  1808 static enum _pgp_thing _pgp_thing_next(enum _pgp_thing thing)
  1809 {
  1810     switch (thing) {
  1811         case _pgp_fpr:
  1812             return _pgp_email;
  1813         case _pgp_email:
  1814             return _pgp_name;
  1815         case _pgp_name:
  1816             return _pgp_fpr;
  1817         default:
  1818             return _pgp_fpr;
  1819     }
  1820 }
  1821 
  1822 PEP_STATUS pgp_import_ultimately_trusted_keypairs(PEP_SESSION session) {
  1823     assert(session);
  1824     if (!session)
  1825         return PEP_ILLEGAL_VALUE;
  1826 
  1827     stringlist_t* priv_keylist = NULL;
  1828     PEP_STATUS status = PEP_STATUS_OK;
  1829 
  1830     // 1. get keys
  1831     status = pgp_find_trusted_private_keys(session, &priv_keylist);
  1832     if (status)
  1833         return status;
  1834 
  1835     pEp_identity *identity = NULL;
  1836     stringlist_t *_sl;
  1837 	
  1838     char *fpr = NULL;
  1839     enum _pgp_thing thing = _pgp_none;
  1840     for (_sl = priv_keylist; _sl && _sl->value; _sl = _sl->next) {
  1841         thing = _pgp_thing_next(thing);
  1842         switch (thing) {
  1843             case _pgp_fpr:
  1844                 identity = new_identity(NULL, NULL, PEP_OWN_USERID, NULL);
  1845                 if (!identity)
  1846                     status = PEP_OUT_OF_MEMORY;
  1847                 identity->me = true;
  1848                 fpr = strdup(_sl->value);
  1849                 assert(fpr);
  1850                 if (!fpr) {
  1851                     status = PEP_OUT_OF_MEMORY;
  1852                     free_identity(identity);
  1853                 }
  1854                 break;
  1855             case _pgp_email:
  1856                 assert(identity);
  1857                 identity->address = strdup(_sl->value);
  1858                 assert(identity->address);
  1859                 if (!identity->address) {
  1860                     status = PEP_OUT_OF_MEMORY;
  1861                     free_identity(identity);
  1862                 }
  1863                 break;
  1864             case _pgp_name:
  1865                 assert(identity);
  1866                 identity->username = strdup(_sl->value);
  1867                 assert(identity->username);
  1868                 if (!identity->username)
  1869                     status = PEP_OUT_OF_MEMORY;
  1870                 else
  1871                     status = set_own_key(session, identity, fpr);
  1872                 free_identity(identity);
  1873                 identity = NULL;
  1874                 break;
  1875             default:
  1876                 assert(0);
  1877                 free_identity(identity);
  1878                 status = PEP_UNKNOWN_ERROR;
  1879         }
  1880         if (status)
  1881             break;
  1882     }
  1883     
  1884     free_stringlist(priv_keylist);
  1885     return status;
  1886 }
  1887 #endif // USE_GPG