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