src/keymanagement.c
author Krista Bennett <krista@pep-project.org>
Wed, 28 Feb 2018 12:24:48 +0100
branchENGINE-294
changeset 2548 3bfda8f2136e
parent 2543 32487b3323ea
child 2549 5fc5d6be0b36
permissions -rw-r--r--
ENGINE-294: basic code is in to remove blacklisting from anything but encrypt_message and outgoing_message_rating, but tests need to be extended, and have to switch to ENGINE-397 and fix that to keep the keyring clean.
     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 && (ct | PEP_ct_confirmed) == PEP_ct_OpenPGP &&
   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 dont_use_fpr = true;
   870     
   871     PEP_STATUS status = blacklist_is_listed(session, fpr, &dont_use_fpr);
   872     if (status == PEP_STATUS_OK && !dont_use_fpr) {
   873         // Make sure there is a *private* key associated with this fpr
   874         bool has_private = false;
   875         status = contains_priv_key(session, fpr, &has_private);
   876 
   877         if (status == PEP_STATUS_OK)
   878             dont_use_fpr = !has_private;
   879     }
   880     
   881     *is_usable = !dont_use_fpr;
   882     
   883     return status;
   884 }
   885 
   886 PEP_STATUS _myself(PEP_SESSION session, pEp_identity * identity, bool do_keygen, bool ignore_flags)
   887 {
   888 
   889     PEP_STATUS status;
   890 
   891     assert(session);
   892     assert(identity);
   893     assert(!EMPTYSTR(identity->address));
   894     assert(!EMPTYSTR(identity->user_id));
   895 
   896     if (!session || !identity || EMPTYSTR(identity->address) ||
   897         EMPTYSTR(identity->user_id))
   898         return PEP_ILLEGAL_VALUE;
   899 
   900     pEp_identity *stored_identity = NULL;
   901     char* revoked_fpr = NULL; 
   902     bool valid_key_found = false;
   903         
   904     char* default_own_id = NULL;
   905     status = get_default_own_userid(session, &default_own_id);
   906 
   907     // Deal with non-default user_ids.
   908     if (default_own_id && strcmp(default_own_id, identity->user_id) != 0) {
   909         
   910         status = set_userid_alias(session, default_own_id, identity->user_id);
   911         // Do we want this to be fatal? For now, we'll do it...
   912         if (status != PEP_STATUS_OK)
   913             goto pep_free;
   914             
   915         free(identity->user_id);
   916         identity->user_id = strdup(default_own_id);
   917         if (identity->user_id == NULL) {
   918             status = PEP_OUT_OF_MEMORY;
   919             goto pep_free;
   920         }
   921     }
   922 
   923     // NOTE: IF WE DON'T YET HAVE AN OWN_ID, WE IGNORE REFERENCES TO THIS ADDRESS IN THE
   924     // DB (WHICH MAY HAVE BEEN SET BEFORE MYSELF WAS CALLED BY RECEIVING AN EMAIL FROM
   925     // THIS ADDRESS), AS IT IS NOT AN OWN_IDENTITY AND HAS NO INFORMATION WE NEED OR WHAT TO
   926     // SET FOR MYSELF
   927     
   928     // Ok, so now, set up the own_identity:
   929     identity->comm_type = PEP_ct_pEp;
   930     identity->me = true;
   931     if(ignore_flags)
   932         identity->flags = 0;
   933     
   934     // Let's see if we have an identity record in the DB for 
   935     // this user_id + address
   936 //    DEBUG_LOG("myself", "debug", identity->address);
   937  
   938     status = get_identity(session,
   939                           identity->address,
   940                           identity->user_id,
   941                           &stored_identity);
   942 
   943     assert(status != PEP_OUT_OF_MEMORY);
   944     if (status == PEP_OUT_OF_MEMORY) {
   945         status = PEP_OUT_OF_MEMORY;
   946         goto pep_free;
   947     }
   948 
   949     // Set usernames - priority is input username > stored name > address
   950     // If there's an input username, we always patch the username with that
   951     // input.
   952     if (EMPTYSTR(identity->username)) {
   953         bool stored_uname = (stored_identity && !EMPTYSTR(stored_identity->username));
   954         char* uname = (stored_uname ? stored_identity->username : identity->address);
   955         free(identity->username);
   956         identity->username = strdup(uname);
   957         if (identity->username == NULL) {
   958             status = PEP_OUT_OF_MEMORY;
   959             goto pep_free;
   960         }
   961     }
   962 
   963     // ignore input fpr
   964 
   965     if (identity->fpr) {
   966         free(identity->fpr);
   967         identity->fpr = NULL;
   968     }
   969 
   970     // check stored identity
   971     if (stored_identity && !EMPTYSTR(stored_identity->fpr)) {
   972         // Fall back / retrieve
   973         status = validate_fpr(session, stored_identity, false);
   974         if (status == PEP_OUT_OF_MEMORY)
   975             goto pep_free;
   976         if (status == PEP_STATUS_OK) {
   977             if (stored_identity->comm_type >= PEP_ct_strong_but_unconfirmed) {
   978                 identity->fpr = strdup(stored_identity->fpr);
   979                 assert(identity->fpr);
   980                 if (!identity->fpr) {
   981                     status = PEP_OUT_OF_MEMORY;
   982                     goto pep_free;
   983                 }
   984                 valid_key_found = true;            
   985             }
   986             else {
   987                 bool revoked = false;
   988                 status = key_revoked(session, stored_identity->fpr, &revoked);
   989                 if (status)
   990                     goto pep_free;
   991                 if (revoked) {
   992                     revoked_fpr = strdup(stored_identity->fpr);
   993                     assert(revoked_fpr);
   994                     if (!revoked_fpr) {
   995                         status = PEP_OUT_OF_MEMORY;
   996                         goto pep_free;
   997                     }
   998                 }
   999             }
  1000         }
  1001     }
  1002     
  1003     // Nothing left to do but generate a key
  1004     if (!valid_key_found) {
  1005         if (!do_keygen)
  1006             status = PEP_GET_KEY_FAILED;
  1007         else {
  1008 // /            DEBUG_LOG("Generating key pair", "debug", identity->address);
  1009 
  1010             free(identity->fpr);
  1011             identity->fpr = NULL;
  1012             status = generate_keypair(session, identity);
  1013             assert(status != PEP_OUT_OF_MEMORY);
  1014 
  1015             if (status != PEP_STATUS_OK) {
  1016                 char buf[11];
  1017                 snprintf(buf, 11, "%d", status); // uh, this is kludgey. FIXME
  1018 //                DEBUG_LOG("Generating key pair failed", "debug", buf);
  1019             }        
  1020             else {
  1021                 valid_key_found = true;
  1022                 if (revoked_fpr) {
  1023                     status = set_revoked(session, revoked_fpr,
  1024                                          stored_identity->fpr, time(NULL));
  1025                 }
  1026             }
  1027         }
  1028     }
  1029 
  1030     if (valid_key_found) {
  1031         identity->comm_type = PEP_ct_pEp;
  1032         status = PEP_STATUS_OK;
  1033     }
  1034     else {
  1035         free(identity->fpr);
  1036         identity->fpr = NULL;
  1037         identity->comm_type = PEP_ct_unknown;
  1038     }
  1039     
  1040     status = set_identity(session, identity);
  1041     if (status == PEP_STATUS_OK)
  1042         status = set_as_pep_user(session, identity);
  1043 
  1044 pep_free:    
  1045     free(default_own_id);
  1046     free(revoked_fpr);                     
  1047     free_identity(stored_identity);
  1048     return status;
  1049 }
  1050 
  1051 // DYNAMIC_API PEP_STATUS initialise_own_identities(PEP_SESSION session,
  1052 //                                                  identity_list* my_idents) {
  1053 //     PEP_STATUS status = PEP_STATUS_OK;
  1054 //     if (!session)
  1055 //         return PEP_ILLEGAL_VALUE;
  1056 //         
  1057 //     if (!my_idents)
  1058 //         return PEP_STATUS_OK;
  1059 //             
  1060 //     identity_list* ident_curr = my_idents;
  1061 //     while (ident_curr) {
  1062 //         pEp_identity* ident = ident_curr->ident;
  1063 //         if (!ident || !ident->address) {
  1064 //             status = PEP_ILLEGAL_VALUE;
  1065 //             goto pep_error;
  1066 //         }
  1067 // 
  1068 //         status = _myself(session, ident, false, false);
  1069 //         
  1070 //         ident_curr = ident_curr->next;
  1071 //     }
  1072 //     
  1073 // pep_error:
  1074 //     return status;
  1075 // }
  1076 
  1077 DYNAMIC_API PEP_STATUS myself(PEP_SESSION session, pEp_identity * identity)
  1078 {
  1079     return _myself(session, identity, true, false);
  1080 }
  1081 
  1082 DYNAMIC_API PEP_STATUS register_examine_function(
  1083         PEP_SESSION session, 
  1084         examine_identity_t examine_identity,
  1085         void *management
  1086     )
  1087 {
  1088     assert(session);
  1089     if (!session)
  1090         return PEP_ILLEGAL_VALUE;
  1091 
  1092     session->examine_management = management;
  1093     session->examine_identity = examine_identity;
  1094 
  1095     return PEP_STATUS_OK;
  1096 }
  1097 
  1098 DYNAMIC_API PEP_STATUS do_keymanagement(
  1099         retrieve_next_identity_t retrieve_next_identity,
  1100         void *management
  1101     )
  1102 {
  1103     PEP_SESSION session;
  1104     pEp_identity *identity;
  1105     PEP_STATUS status;
  1106 
  1107     assert(retrieve_next_identity);
  1108     assert(management);
  1109 
  1110     if (!retrieve_next_identity || !management)
  1111         return PEP_ILLEGAL_VALUE;
  1112 
  1113     status = init(&session);
  1114     assert(status == PEP_STATUS_OK);
  1115     if (status != PEP_STATUS_OK)
  1116         return status;
  1117 
  1118     log_event(session, "keymanagement thread started", "pEp engine", NULL, NULL);
  1119 
  1120     while ((identity = retrieve_next_identity(management))) 
  1121     {
  1122         assert(identity->address);
  1123         if(identity->address)
  1124         {
  1125             DEBUG_LOG("do_keymanagement", "retrieve_next_identity", identity->address);
  1126 
  1127             if (identity->me) {
  1128                 status = myself(session, identity);
  1129             } else {
  1130                 status = recv_key(session, identity->address);
  1131             }
  1132 
  1133             assert(status != PEP_OUT_OF_MEMORY);
  1134             if(status == PEP_OUT_OF_MEMORY)
  1135                 return PEP_OUT_OF_MEMORY;
  1136         }
  1137         free_identity(identity);
  1138     }
  1139 
  1140     log_event(session, "keymanagement thread shutdown", "pEp engine", NULL, NULL);
  1141 
  1142     release(session);
  1143     return PEP_STATUS_OK;
  1144 }
  1145 
  1146 DYNAMIC_API PEP_STATUS key_mistrusted(
  1147         PEP_SESSION session,
  1148         pEp_identity *ident
  1149     )
  1150 {
  1151     PEP_STATUS status = PEP_STATUS_OK;
  1152 
  1153     assert(session);
  1154     assert(ident);
  1155     assert(!EMPTYSTR(ident->fpr));
  1156 
  1157     if (!(session && ident && ident->fpr))
  1158         return PEP_ILLEGAL_VALUE;
  1159 
  1160     if (ident->me)
  1161     {
  1162         revoke_key(session, ident->fpr, NULL);
  1163         myself(session, ident);
  1164     }
  1165     else
  1166     {
  1167         // for undo
  1168         if (session->cached_mistrusted)
  1169             free(session->cached_mistrusted);
  1170         session->cached_mistrusted = identity_dup(ident);
  1171         
  1172         // set mistrust for this user_id/keypair (even if there's not an
  1173         // identity set yet, this is important, as we need to record the mistrust
  1174         // action)
  1175         
  1176         // double-check to be sure key is even in the DB
  1177         if (ident->fpr)
  1178             status = set_pgp_keypair(session, ident->fpr);
  1179 
  1180         // We set this temporarily but will grab it back from the cache afterwards
  1181         ident->comm_type = PEP_ct_mistrusted;
  1182         status = set_trust(session, ident);
  1183         ident->comm_type = session->cached_mistrusted->comm_type;
  1184         
  1185         if (status == PEP_STATUS_OK)
  1186             // cascade that mistrust for anyone using this key
  1187             status = mark_as_compromized(session, ident->fpr);
  1188         if (status == PEP_STATUS_OK)
  1189             status = remove_fpr_as_default(session, ident->fpr);
  1190         if (status == PEP_STATUS_OK)
  1191             status = add_mistrusted_key(session, ident->fpr);
  1192     }
  1193 
  1194     return status;
  1195 }
  1196 
  1197 DYNAMIC_API PEP_STATUS undo_last_mistrust(PEP_SESSION session) {
  1198     assert(session);
  1199     
  1200     if (!session)
  1201         return PEP_ILLEGAL_VALUE;
  1202     
  1203     PEP_STATUS status = PEP_STATUS_OK;
  1204         
  1205     pEp_identity* cached_ident = session->cached_mistrusted;
  1206     
  1207     if (!cached_ident)
  1208         status = PEP_CANNOT_FIND_IDENTITY;
  1209     else {
  1210         status = delete_mistrusted_key(session, cached_ident->fpr);
  1211         if (status == PEP_STATUS_OK) {
  1212             status = set_identity(session, cached_ident);
  1213             // THIS SHOULDN'T BE NECESSARY - PREVIOUS VALUE WAS IN THE DB
  1214             // if (status == PEP_STATUS_OK) {
  1215             //     if ((cached_ident->comm_type | PEP_ct_confirmed) == PEP_ct_pEp)
  1216             //         status = set_as_pep_user(session, cached_ident);
  1217             // }            
  1218             free_identity(session->cached_mistrusted);
  1219         }
  1220     }
  1221     
  1222     session->cached_mistrusted = NULL;
  1223     
  1224     return status;
  1225 }
  1226 
  1227 DYNAMIC_API PEP_STATUS key_reset_trust(
  1228         PEP_SESSION session,
  1229         pEp_identity *ident
  1230     )
  1231 {
  1232     PEP_STATUS status = PEP_STATUS_OK;
  1233 
  1234     assert(session);
  1235     assert(ident);
  1236     assert(!EMPTYSTR(ident->fpr));
  1237     assert(!EMPTYSTR(ident->address));
  1238     assert(!EMPTYSTR(ident->user_id));
  1239 
  1240     if (!(session && ident && ident->fpr && ident->fpr[0] != '\0' && ident->address &&
  1241             ident->user_id))
  1242         return PEP_ILLEGAL_VALUE;
  1243 
  1244     // we do not change the input struct at ALL.
  1245     pEp_identity* input_copy = identity_dup(ident);
  1246     
  1247     pEp_identity* tmp_ident = NULL;
  1248     
  1249     status = get_trust(session, input_copy);
  1250     
  1251     if (status != PEP_STATUS_OK)
  1252         goto pep_free;
  1253         
  1254     PEP_comm_type new_trust = PEP_ct_unknown;
  1255 
  1256     if (input_copy->comm_type != PEP_ct_mistrusted)
  1257         new_trust = input_copy->comm_type & ~PEP_ct_confirmed;
  1258 
  1259     // We'll return the status from the input_copy cache afterward
  1260     input_copy->comm_type = new_trust;
  1261     status = set_trust(session, input_copy);
  1262     
  1263     if (status != PEP_STATUS_OK)
  1264         goto pep_free;
  1265 
  1266     bool mistrusted_key = false;
  1267         
  1268     status = is_mistrusted_key(session, ident->fpr, &mistrusted_key);
  1269 
  1270     if (status != PEP_STATUS_OK)
  1271         goto pep_free;
  1272     
  1273     if (mistrusted_key)
  1274         status = delete_mistrusted_key(session, ident->fpr);
  1275 
  1276     if (status != PEP_STATUS_OK)
  1277         goto pep_free;
  1278         
  1279     tmp_ident = new_identity(ident->address, NULL, ident->user_id, NULL);
  1280 
  1281     if (!tmp_ident)
  1282         return PEP_OUT_OF_MEMORY;
  1283     
  1284     status = update_identity(session, tmp_ident);
  1285     
  1286     if (status != PEP_STATUS_OK)
  1287         goto pep_free;
  1288     
  1289     // remove as default if necessary
  1290     if (!EMPTYSTR(tmp_ident->fpr) && strcmp(tmp_ident->fpr, ident->fpr) == 0) {
  1291         free(tmp_ident->fpr);
  1292         tmp_ident->fpr = NULL;
  1293         tmp_ident->comm_type = PEP_ct_unknown;
  1294         status = set_identity(session, tmp_ident);
  1295         if (status != PEP_STATUS_OK)
  1296             goto pep_free;
  1297     }
  1298     
  1299     char* user_default = NULL;
  1300     status = get_main_user_fpr(session, tmp_ident->user_id, &user_default);
  1301     
  1302     if (!EMPTYSTR(user_default)) {
  1303         if (strcmp(user_default, ident->fpr) == 0)
  1304             status = refresh_userid_default_key(session, ident->user_id);
  1305         if (status != PEP_STATUS_OK)
  1306             goto pep_free;    
  1307     }
  1308             
  1309 pep_free:
  1310     free_identity(tmp_ident);
  1311     free_identity(input_copy);
  1312     return status;
  1313 }
  1314 
  1315 DYNAMIC_API PEP_STATUS trust_personal_key(
  1316         PEP_SESSION session,
  1317         pEp_identity *ident
  1318     )
  1319 {
  1320     PEP_STATUS status = PEP_STATUS_OK;
  1321 
  1322     assert(session);
  1323     assert(ident);
  1324     assert(!EMPTYSTR(ident->address));
  1325     assert(!EMPTYSTR(ident->user_id));
  1326     assert(!EMPTYSTR(ident->fpr));
  1327 
  1328     if (!ident || EMPTYSTR(ident->address) || EMPTYSTR(ident->user_id) ||
  1329             EMPTYSTR(ident->fpr))
  1330         return PEP_ILLEGAL_VALUE;
  1331 
  1332     //bool ident_has_trusted_default = false;
  1333     char* ident_default_fpr = NULL;
  1334 
  1335     // Before we do anything, be sure the input fpr is even eligible to be trusted
  1336     PEP_comm_type input_default_ct = PEP_ct_unknown;
  1337     status = get_key_rating(session, ident->fpr, &input_default_ct);
  1338     if (input_default_ct < PEP_ct_strong_but_unconfirmed)
  1339         return PEP_KEY_UNSUITABLE;
  1340 
  1341     status = set_pgp_keypair(session, ident->fpr);
  1342     if (status != PEP_STATUS_OK)
  1343         return status;
  1344 
  1345     bool me = is_me(session, ident);
  1346 
  1347     pEp_identity* ident_copy = identity_dup(ident);
  1348     char* cached_fpr = NULL;
  1349 
  1350     // for setting up a temp trusted identity for the input fpr
  1351     pEp_identity* tmp_id = NULL;
  1352 
  1353     // For later, in case we need to check the user default key
  1354     pEp_identity* tmp_user_ident = NULL;
  1355 
  1356     if (me) {
  1357         status = myself(session, ident_copy); 
  1358         goto pep_free;
  1359     }
  1360     
  1361     // Save the input fpr, which we already tested as non-NULL
  1362     cached_fpr = strdup(ident->fpr);
  1363 
  1364     // First, set up a temp trusted identity for the input fpr without a comm type;
  1365     tmp_id = new_identity(ident->address, ident->fpr, ident->user_id, NULL);
  1366     status = validate_fpr(session, tmp_id, false);
  1367         
  1368     if (status == PEP_STATUS_OK) {
  1369         // Validate fpr gets trust DB or, when that fails, key comm type. we checked
  1370         // above that the key was ok. (not revoked or expired), but we want the max.
  1371         tmp_id->comm_type = _MAX(tmp_id->comm_type, input_default_ct) | PEP_ct_confirmed;
  1372                                        
  1373         // Get the default identity without setting the fpr
  1374         status = update_identity(session, ident_copy);
  1375         ident_default_fpr = (EMPTYSTR(ident_copy->fpr) ? NULL : strdup(ident_copy->fpr));
  1376 
  1377         if (status == PEP_STATUS_OK) {
  1378             bool trusted_default = false;
  1379 
  1380             // If there's no default, or the default is different from the input...
  1381             if (EMPTYSTR(ident_default_fpr) || strcmp(cached_fpr, ident_default_fpr) != 0) {
  1382                 
  1383                 // If the default fpr (if there is one) is trusted and key is strong enough,
  1384                 // don't replace, we just set the trusted bit on this key for this user_id...
  1385                 // (If there's no default fpr, this won't be true anyway.)
  1386                 if (ident->comm_type >= PEP_ct_strong_but_unconfirmed && 
  1387                     (ident->comm_type & PEP_ct_confirmed)) {                        
  1388 
  1389                     trusted_default = true;
  1390                                     
  1391                     status = set_trust(session, tmp_id);
  1392                     input_default_ct = tmp_id->comm_type;                    
  1393                 }
  1394                 else {
  1395                     free(ident_copy->fpr);
  1396                     ident_copy->fpr = strdup(cached_fpr);
  1397                     ident_copy->comm_type = tmp_id->comm_type;
  1398                     status = set_identity(session, ident_copy); // replace identity default
  1399                     if (status == PEP_STATUS_OK) {
  1400                         if ((ident_copy->comm_type | PEP_ct_confirmed) == PEP_ct_pEp)
  1401                             status = set_as_pep_user(session, ident_copy);
  1402                     }            
  1403                 }
  1404             }
  1405             else { // we're setting this on the default fpr
  1406                 ident->comm_type = tmp_id->comm_type;
  1407                 status = set_identity(session, ident);
  1408                 trusted_default = true;
  1409             }
  1410             if (status == PEP_STATUS_OK && !trusted_default) {
  1411                 // Ok, there wasn't a trusted default, so we replaced. Thus, we also
  1412                 // make sure there's a trusted default on the user_id. If there
  1413                 // is not, we make this the default.
  1414                 char* user_default = NULL;
  1415                 status = get_main_user_fpr(session, ident->user_id, &user_default);
  1416             
  1417                 if (status == PEP_STATUS_OK && user_default) {
  1418                     tmp_user_ident = new_identity(ident->address, 
  1419                                                   user_default, 
  1420                                                   ident->user_id, 
  1421                                                   NULL);
  1422                     if (!tmp_user_ident)
  1423                         status = PEP_OUT_OF_MEMORY;
  1424                     else {
  1425                         status = validate_fpr(session, tmp_user_ident, false);
  1426                         
  1427                         if (status != PEP_STATUS_OK ||
  1428                             tmp_user_ident->comm_type < PEP_ct_strong_but_unconfirmed ||
  1429                             !(tmp_user_ident->comm_type & PEP_ct_confirmed)) 
  1430                         {
  1431                             char* trusted_fpr = (trusted_default ? ident_default_fpr : cached_fpr);
  1432                             status = replace_main_user_fpr(session, ident->user_id, trusted_fpr);
  1433                         } 
  1434                     }
  1435                 }
  1436             }
  1437         }
  1438     }    
  1439 
  1440 pep_free:
  1441     free(ident_default_fpr);
  1442     free(cached_fpr);
  1443     free_identity(tmp_id);
  1444     free_identity(ident_copy);
  1445     free_identity(tmp_user_ident);
  1446     return status;
  1447 }
  1448 
  1449 DYNAMIC_API PEP_STATUS own_key_is_listed(
  1450         PEP_SESSION session,
  1451         const char *fpr,
  1452         bool *listed
  1453     )
  1454 {
  1455     PEP_STATUS status = PEP_STATUS_OK;
  1456     int count;
  1457     
  1458     assert(session && fpr && fpr[0] && listed);
  1459     
  1460     if (!(session && fpr && fpr[0] && listed))
  1461         return PEP_ILLEGAL_VALUE;
  1462     
  1463     *listed = false;
  1464     
  1465     sqlite3_reset(session->own_key_is_listed);
  1466     sqlite3_bind_text(session->own_key_is_listed, 1, fpr, -1, SQLITE_STATIC);
  1467     
  1468     int result;
  1469     
  1470     result = sqlite3_step(session->own_key_is_listed);
  1471     switch (result) {
  1472         case SQLITE_ROW:
  1473             count = sqlite3_column_int(session->own_key_is_listed, 0);
  1474             *listed = count > 0;
  1475             status = PEP_STATUS_OK;
  1476             break;
  1477             
  1478         default:
  1479             status = PEP_UNKNOWN_ERROR;
  1480     }
  1481     
  1482     sqlite3_reset(session->own_key_is_listed);
  1483     return status;
  1484 }
  1485 
  1486 PEP_STATUS _own_identities_retrieve(
  1487         PEP_SESSION session,
  1488         identity_list **own_identities,
  1489         identity_flags_t excluded_flags
  1490       )
  1491 {
  1492     PEP_STATUS status = PEP_STATUS_OK;
  1493     
  1494     assert(session && own_identities);
  1495     if (!(session && own_identities))
  1496         return PEP_ILLEGAL_VALUE;
  1497     
  1498     *own_identities = NULL;
  1499     identity_list *_own_identities = new_identity_list(NULL);
  1500     if (_own_identities == NULL)
  1501         goto enomem;
  1502     
  1503     sqlite3_reset(session->own_identities_retrieve);
  1504     
  1505     int result;
  1506     // address, fpr, username, user_id, comm_type, lang, flags
  1507     const char *address = NULL;
  1508     const char *fpr = NULL;
  1509     const char *username = NULL;
  1510     const char *user_id = NULL;
  1511     PEP_comm_type comm_type = PEP_ct_unknown;
  1512     const char *lang = NULL;
  1513     unsigned int flags = 0;
  1514     
  1515     identity_list *_bl = _own_identities;
  1516     do {
  1517         sqlite3_bind_int(session->own_identities_retrieve, 1, excluded_flags);
  1518         result = sqlite3_step(session->own_identities_retrieve);
  1519         switch (result) {
  1520             case SQLITE_ROW:
  1521                 address = (const char *)
  1522                     sqlite3_column_text(session->own_identities_retrieve, 0);
  1523                 fpr = (const char *)
  1524                     sqlite3_column_text(session->own_identities_retrieve, 1);
  1525                 user_id = (const char *)
  1526                     sqlite3_column_text(session->own_identities_retrieve, 2);
  1527                 username = (const char *)
  1528                     sqlite3_column_text(session->own_identities_retrieve, 3);
  1529                 comm_type = PEP_ct_pEp;
  1530                 lang = (const char *)
  1531                     sqlite3_column_text(session->own_identities_retrieve, 4);
  1532                 flags = (unsigned int)
  1533                     sqlite3_column_int(session->own_identities_retrieve, 5);
  1534 
  1535                 pEp_identity *ident = new_identity(address, fpr, user_id, username);
  1536                 if (!ident)
  1537                     goto enomem;
  1538                 ident->comm_type = comm_type;
  1539                 if (lang && lang[0]) {
  1540                     ident->lang[0] = lang[0];
  1541                     ident->lang[1] = lang[1];
  1542                     ident->lang[2] = 0;
  1543                 }
  1544                 ident->me = true;
  1545                 ident->flags = flags;
  1546 
  1547                 _bl = identity_list_add(_bl, ident);
  1548                 if (_bl == NULL) {
  1549                     free_identity(ident);
  1550                     goto enomem;
  1551                 }
  1552                 
  1553                 break;
  1554                 
  1555             case SQLITE_DONE:
  1556                 break;
  1557                 
  1558             default:
  1559                 status = PEP_UNKNOWN_ERROR;
  1560                 result = SQLITE_DONE;
  1561         }
  1562     } while (result != SQLITE_DONE);
  1563     
  1564     sqlite3_reset(session->own_identities_retrieve);
  1565     if (status == PEP_STATUS_OK)
  1566         *own_identities = _own_identities;
  1567     else
  1568         free_identity_list(_own_identities);
  1569     
  1570     goto the_end;
  1571     
  1572 enomem:
  1573     free_identity_list(_own_identities);
  1574     status = PEP_OUT_OF_MEMORY;
  1575     
  1576 the_end:
  1577     return status;
  1578 }
  1579 
  1580 DYNAMIC_API PEP_STATUS own_identities_retrieve(
  1581         PEP_SESSION session,
  1582         identity_list **own_identities
  1583       )
  1584 {
  1585     return _own_identities_retrieve(session, own_identities, 0);
  1586 }
  1587 
  1588 PEP_STATUS _own_keys_retrieve(
  1589         PEP_SESSION session,
  1590         stringlist_t **keylist,
  1591         identity_flags_t excluded_flags
  1592       )
  1593 {
  1594     PEP_STATUS status = PEP_STATUS_OK;
  1595     
  1596     assert(session && keylist);
  1597     if (!(session && keylist))
  1598         return PEP_ILLEGAL_VALUE;
  1599     
  1600     *keylist = NULL;
  1601     stringlist_t *_keylist = NULL;
  1602     
  1603     sqlite3_reset(session->own_keys_retrieve);
  1604     
  1605     int result;
  1606     char *fpr = NULL;
  1607     
  1608     stringlist_t *_bl = _keylist;
  1609     do {
  1610         sqlite3_bind_int(session->own_keys_retrieve, 1, excluded_flags);
  1611         result = sqlite3_step(session->own_keys_retrieve);
  1612         switch (result) {
  1613             case SQLITE_ROW:
  1614                 fpr = strdup((const char *) sqlite3_column_text(session->own_keys_retrieve, 0));
  1615                 if(fpr == NULL)
  1616                     goto enomem;
  1617 
  1618                 _bl = stringlist_add(_bl, fpr);
  1619                 if (_bl == NULL) {
  1620                     free(fpr);
  1621                     goto enomem;
  1622                 }
  1623                 if (_keylist == NULL)
  1624                     _keylist = _bl;
  1625                 
  1626                 break;
  1627                 
  1628             case SQLITE_DONE:
  1629                 break;
  1630                 
  1631             default:
  1632                 status = PEP_UNKNOWN_ERROR;
  1633                 result = SQLITE_DONE;
  1634         }
  1635     } while (result != SQLITE_DONE);
  1636     
  1637     sqlite3_reset(session->own_keys_retrieve);
  1638     if (status == PEP_STATUS_OK)
  1639         *keylist = _keylist;
  1640     else
  1641         free_stringlist(_keylist);
  1642     
  1643     goto the_end;
  1644     
  1645 enomem:
  1646     free_stringlist(_keylist);
  1647     status = PEP_OUT_OF_MEMORY;
  1648     
  1649 the_end:
  1650     return status;
  1651 }
  1652 
  1653 DYNAMIC_API PEP_STATUS own_keys_retrieve(PEP_SESSION session, stringlist_t **keylist)
  1654 {
  1655     return _own_keys_retrieve(session, keylist, 0);
  1656 }
  1657 
  1658 DYNAMIC_API PEP_STATUS set_own_key(
  1659        PEP_SESSION session,
  1660        pEp_identity *me,
  1661        const char *fpr
  1662     )
  1663 {
  1664     PEP_STATUS status = PEP_STATUS_OK;
  1665     
  1666     assert(session && me);
  1667     assert(!EMPTYSTR(fpr));
  1668     assert(!EMPTYSTR(me->address));
  1669     assert(!EMPTYSTR(me->user_id));
  1670     assert(!EMPTYSTR(me->username));
  1671 
  1672     if (!session || !me || EMPTYSTR(fpr) || EMPTYSTR(me->address) ||
  1673             EMPTYSTR(me->user_id) || EMPTYSTR(me->username))
  1674         return PEP_ILLEGAL_VALUE;
  1675 
  1676     status = _myself(session, me, false, true);
  1677     // we do not need a valid key but dislike other errors
  1678     if (status != PEP_STATUS_OK && status != PEP_GET_KEY_FAILED && status != PEP_KEY_UNSUITABLE)
  1679         return status;
  1680     status = PEP_STATUS_OK;
  1681  
  1682     if (me->fpr)
  1683         free(me->fpr);
  1684     me->fpr = strdup(fpr);
  1685     assert(me->fpr);
  1686     if (!me->fpr)
  1687         return PEP_OUT_OF_MEMORY;
  1688 
  1689     status = validate_fpr(session, me, false);
  1690     if (status)
  1691         return status;
  1692 
  1693     me->comm_type = PEP_ct_pEp;
  1694     status = set_identity(session, me);
  1695     return status;
  1696 }
  1697 
  1698 PEP_STATUS contains_priv_key(PEP_SESSION session, const char *fpr,
  1699                              bool *has_private) {
  1700 
  1701     assert(session);
  1702     assert(fpr);
  1703     assert(has_private);
  1704     
  1705     if (!(session && fpr && has_private))
  1706         return PEP_ILLEGAL_VALUE;
  1707 
  1708     return session->cryptotech[PEP_crypt_OpenPGP].contains_priv_key(session, fpr, has_private);
  1709 }
  1710 
  1711 PEP_STATUS add_mistrusted_key(PEP_SESSION session, const char* fpr)
  1712 {
  1713     int result;
  1714 
  1715     assert(!EMPTYSTR(fpr));
  1716     
  1717     if (!(session) || EMPTYSTR(fpr))
  1718         return PEP_ILLEGAL_VALUE;
  1719 
  1720     sqlite3_reset(session->add_mistrusted_key);
  1721     sqlite3_bind_text(session->add_mistrusted_key, 1, fpr, -1,
  1722             SQLITE_STATIC);
  1723 
  1724     result = sqlite3_step(session->add_mistrusted_key);
  1725     sqlite3_reset(session->add_mistrusted_key);
  1726 
  1727     if (result != SQLITE_DONE)
  1728         return PEP_CANNOT_SET_PGP_KEYPAIR; // FIXME: Better status?
  1729 
  1730     return PEP_STATUS_OK;
  1731 }
  1732 
  1733 PEP_STATUS delete_mistrusted_key(PEP_SESSION session, const char* fpr)
  1734 {
  1735     int result;
  1736 
  1737     assert(!EMPTYSTR(fpr));
  1738     
  1739     if (!(session) || EMPTYSTR(fpr))
  1740         return PEP_ILLEGAL_VALUE;
  1741 
  1742     sqlite3_reset(session->delete_mistrusted_key);
  1743     sqlite3_bind_text(session->delete_mistrusted_key, 1, fpr, -1,
  1744             SQLITE_STATIC);
  1745 
  1746     result = sqlite3_step(session->delete_mistrusted_key);
  1747     sqlite3_reset(session->delete_mistrusted_key);
  1748 
  1749     if (result != SQLITE_DONE)
  1750         return PEP_UNKNOWN_ERROR; // FIXME: Better status?
  1751 
  1752     return PEP_STATUS_OK;
  1753 }
  1754 
  1755 PEP_STATUS is_mistrusted_key(PEP_SESSION session, const char* fpr,
  1756                              bool* mistrusted)
  1757 {
  1758     PEP_STATUS status = PEP_STATUS_OK;
  1759 
  1760     assert(session);
  1761     assert(!EMPTYSTR(fpr));
  1762 
  1763     if (!(session && fpr))
  1764         return PEP_ILLEGAL_VALUE;
  1765 
  1766     *mistrusted = false;
  1767 
  1768     sqlite3_reset(session->is_mistrusted_key);
  1769     sqlite3_bind_text(session->is_mistrusted_key, 1, fpr, -1, SQLITE_STATIC);
  1770 
  1771     int result;
  1772 
  1773     result = sqlite3_step(session->is_mistrusted_key);
  1774     switch (result) {
  1775     case SQLITE_ROW:
  1776         *mistrusted = sqlite3_column_int(session->is_mistrusted_key, 0);
  1777         status = PEP_STATUS_OK;
  1778         break;
  1779 
  1780     default:
  1781         status = PEP_UNKNOWN_ERROR;
  1782     }
  1783 
  1784     sqlite3_reset(session->is_mistrusted_key);
  1785     return status;
  1786 }
  1787 
  1788 #ifdef USE_GPG
  1789 PEP_STATUS pgp_find_trusted_private_keys(
  1790         PEP_SESSION session, stringlist_t **keylist
  1791     );
  1792 
  1793 enum _pgp_thing {
  1794     _pgp_none = 0,
  1795     _pgp_fpr,
  1796     _pgp_email,
  1797     _pgp_name
  1798 };
  1799 
  1800 static enum _pgp_thing _pgp_thing_next(enum _pgp_thing thing)
  1801 {
  1802     switch (thing) {
  1803         case _pgp_fpr:
  1804             return _pgp_email;
  1805         case _pgp_email:
  1806             return _pgp_name;
  1807         case _pgp_name:
  1808             return _pgp_fpr;
  1809         default:
  1810             return _pgp_fpr;
  1811     }
  1812 }
  1813 
  1814 PEP_STATUS pgp_import_ultimately_trusted_keypairs(PEP_SESSION session) {
  1815     assert(session);
  1816     if (!session)
  1817         return PEP_ILLEGAL_VALUE;
  1818 
  1819     stringlist_t* priv_keylist = NULL;
  1820     PEP_STATUS status = PEP_STATUS_OK;
  1821 
  1822     // 1. get keys
  1823     status = pgp_find_trusted_private_keys(session, &priv_keylist);
  1824     if (status)
  1825         return status;
  1826 
  1827     pEp_identity *identity = NULL;
  1828     stringlist_t *_sl;
  1829 	
  1830     char *fpr = NULL;
  1831     enum _pgp_thing thing = _pgp_none;
  1832     for (_sl = priv_keylist; _sl && _sl->value; _sl = _sl->next) {
  1833         thing = _pgp_thing_next(thing);
  1834         switch (thing) {
  1835             case _pgp_fpr:
  1836                 identity = new_identity(NULL, NULL, PEP_OWN_USERID, NULL);
  1837                 if (!identity)
  1838                     status = PEP_OUT_OF_MEMORY;
  1839                 identity->me = true;
  1840                 fpr = strdup(_sl->value);
  1841                 assert(fpr);
  1842                 if (!fpr) {
  1843                     status = PEP_OUT_OF_MEMORY;
  1844                     free_identity(identity);
  1845                 }
  1846                 break;
  1847             case _pgp_email:
  1848                 assert(identity);
  1849                 identity->address = strdup(_sl->value);
  1850                 assert(identity->address);
  1851                 if (!identity->address) {
  1852                     status = PEP_OUT_OF_MEMORY;
  1853                     free_identity(identity);
  1854                 }
  1855                 break;
  1856             case _pgp_name:
  1857                 assert(identity);
  1858                 identity->username = strdup(_sl->value);
  1859                 assert(identity->username);
  1860                 if (!identity->username)
  1861                     status = PEP_OUT_OF_MEMORY;
  1862                 else
  1863                     status = set_own_key(session, identity, fpr);
  1864                 free_identity(identity);
  1865                 identity = NULL;
  1866                 break;
  1867             default:
  1868                 assert(0);
  1869                 free_identity(identity);
  1870                 status = PEP_UNKNOWN_ERROR;
  1871         }
  1872         if (status)
  1873             break;
  1874     }
  1875     
  1876     free_stringlist(priv_keylist);
  1877     return status;
  1878 }
  1879 #endif // USE_GPG