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