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