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