src/keymanagement.c
author Volker Birk <vb@pep.foundation>
Mon, 15 Oct 2018 21:35:52 +0200
branchsync
changeset 3057 fff5fb5e01fe
parent 3056 924a5dfb5367
parent 3054 446b47c16304
child 3076 feab4daed302
permissions -rw-r--r--
merging
     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         retrieve_next_identity_t retrieve_next_identity,
  1122         void *management
  1123     )
  1124 {
  1125     PEP_SESSION session;
  1126     pEp_identity *identity;
  1127     PEP_STATUS status = init(&session, NULL, NULL);
  1128     assert(!status);
  1129     if (status)
  1130         return status;
  1131 
  1132     assert(session && retrieve_next_identity);
  1133     if (!(session && retrieve_next_identity))
  1134         return PEP_ILLEGAL_VALUE;
  1135 
  1136     log_event(session, "keymanagement thread started", "pEp engine", NULL, NULL);
  1137 
  1138     while ((identity = retrieve_next_identity(management))) 
  1139     {
  1140         assert(identity->address);
  1141         if(identity->address)
  1142         {
  1143             DEBUG_LOG("do_keymanagement", "retrieve_next_identity", identity->address);
  1144 
  1145             if (identity->me) {
  1146                 status = myself(session, identity);
  1147             } else {
  1148                 status = recv_key(session, identity->address);
  1149             }
  1150 
  1151             assert(status != PEP_OUT_OF_MEMORY);
  1152             if(status == PEP_OUT_OF_MEMORY)
  1153                 return PEP_OUT_OF_MEMORY;
  1154         }
  1155         free_identity(identity);
  1156     }
  1157 
  1158     log_event(session, "keymanagement thread shutdown", "pEp engine", NULL, NULL);
  1159     release(session);
  1160     return PEP_STATUS_OK;
  1161 }
  1162 
  1163 DYNAMIC_API PEP_STATUS key_mistrusted(
  1164         PEP_SESSION session,
  1165         pEp_identity *ident
  1166     )
  1167 {
  1168     PEP_STATUS status = PEP_STATUS_OK;
  1169 
  1170     assert(session);
  1171     assert(ident);
  1172     assert(!EMPTYSTR(ident->fpr));
  1173 
  1174     if (!(session && ident && ident->fpr))
  1175         return PEP_ILLEGAL_VALUE;
  1176             
  1177         // See if key is revoked already
  1178         bool revoked = false;
  1179         status = key_revoked(session, ident->fpr, &revoked);
  1180         if (!revoked)
  1181             revoke_key(session, ident->fpr, NULL);
  1182             
  1183     // double-check to be sure key is even in the DB
  1184     if (ident->fpr)
  1185         status = set_pgp_keypair(session, ident->fpr);
  1186 
  1187     // We set this temporarily but will grab it back from the cache afterwards
  1188     ident->comm_type = PEP_ct_mistrusted;
  1189     status = set_trust(session, ident);
  1190     
  1191     if (status == PEP_STATUS_OK)
  1192         // cascade that mistrust for anyone using this key
  1193         status = mark_as_compromised(session, ident->fpr);
  1194     if (status == PEP_STATUS_OK)
  1195         status = add_mistrusted_key(session, ident->fpr);
  1196             
  1197     return status;
  1198 }
  1199 
  1200 DYNAMIC_API PEP_STATUS key_reset_trust(
  1201         PEP_SESSION session,
  1202         pEp_identity *ident
  1203     )
  1204 {
  1205     PEP_STATUS status = PEP_STATUS_OK;
  1206 
  1207     assert(session);
  1208     assert(ident);
  1209     assert(!EMPTYSTR(ident->fpr));
  1210     assert(!EMPTYSTR(ident->address));
  1211     assert(!EMPTYSTR(ident->user_id));
  1212 
  1213     if (!(session && ident && ident->fpr && ident->fpr[0] != '\0' && ident->address &&
  1214             ident->user_id))
  1215         return PEP_ILLEGAL_VALUE;
  1216 
  1217     // we do not change the input struct at ALL.
  1218     pEp_identity* input_copy = identity_dup(ident);
  1219     
  1220     pEp_identity* tmp_ident = NULL;
  1221     
  1222     status = get_trust(session, input_copy);
  1223     
  1224     if (status != PEP_STATUS_OK)
  1225         goto pEp_free;
  1226         
  1227     PEP_comm_type new_trust = PEP_ct_unknown;
  1228     status = get_key_rating(session, ident->fpr, &new_trust);
  1229     if (status != PEP_STATUS_OK)
  1230         goto pEp_free;
  1231 
  1232     bool pEp_user = false;
  1233     
  1234     status = is_pEp_user(session, ident, &pEp_user);
  1235     
  1236     if (pEp_user && new_trust >= PEP_ct_unconfirmed_encryption)
  1237         input_copy->comm_type = PEP_ct_pEp_unconfirmed;
  1238     else
  1239         input_copy->comm_type = new_trust;
  1240         
  1241     status = set_trust(session, input_copy);
  1242     
  1243     if (status != PEP_STATUS_OK)
  1244         goto pEp_free;
  1245 
  1246     bool mistrusted_key = false;
  1247         
  1248     status = is_mistrusted_key(session, ident->fpr, &mistrusted_key);
  1249 
  1250     if (status != PEP_STATUS_OK)
  1251         goto pEp_free;
  1252     
  1253     if (mistrusted_key)
  1254         status = delete_mistrusted_key(session, ident->fpr);
  1255 
  1256     if (status != PEP_STATUS_OK)
  1257         goto pEp_free;
  1258         
  1259     tmp_ident = new_identity(ident->address, NULL, ident->user_id, NULL);
  1260 
  1261     if (!tmp_ident)
  1262         return PEP_OUT_OF_MEMORY;
  1263     
  1264     if (is_me(session, tmp_ident))
  1265         status = myself(session, tmp_ident);
  1266     else
  1267         status = update_identity(session, tmp_ident);
  1268     
  1269     if (status != PEP_STATUS_OK)
  1270         goto pEp_free;
  1271     
  1272     // remove as default if necessary
  1273     if (!EMPTYSTR(tmp_ident->fpr) && strcmp(tmp_ident->fpr, ident->fpr) == 0) {
  1274         free(tmp_ident->fpr);
  1275         tmp_ident->fpr = NULL;
  1276         tmp_ident->comm_type = PEP_ct_unknown;
  1277         status = set_identity(session, tmp_ident);
  1278         if (status != PEP_STATUS_OK)
  1279             goto pEp_free;
  1280     }
  1281     
  1282     char* user_default = NULL;
  1283     get_main_user_fpr(session, tmp_ident->user_id, &user_default);
  1284     
  1285     if (!EMPTYSTR(user_default)) {
  1286         if (strcmp(user_default, ident->fpr) == 0)
  1287             status = refresh_userid_default_key(session, ident->user_id);
  1288         if (status != PEP_STATUS_OK)
  1289             goto pEp_free;    
  1290     }
  1291             
  1292 pEp_free:
  1293     free_identity(tmp_ident);
  1294     free_identity(input_copy);
  1295     return status;
  1296 }
  1297 
  1298 DYNAMIC_API PEP_STATUS trust_personal_key(
  1299         PEP_SESSION session,
  1300         pEp_identity *ident
  1301     )
  1302 {
  1303     PEP_STATUS status = PEP_STATUS_OK;
  1304 
  1305     assert(session);
  1306     assert(ident);
  1307     assert(!EMPTYSTR(ident->address));
  1308     assert(!EMPTYSTR(ident->user_id));
  1309     assert(!EMPTYSTR(ident->fpr));
  1310 
  1311     if (!ident || EMPTYSTR(ident->address) || EMPTYSTR(ident->user_id) ||
  1312             EMPTYSTR(ident->fpr))
  1313         return PEP_ILLEGAL_VALUE;
  1314 
  1315     //bool ident_has_trusted_default = false;
  1316     char* ident_default_fpr = NULL;
  1317 
  1318     // Before we do anything, be sure the input fpr is even eligible to be trusted
  1319     PEP_comm_type input_default_ct = PEP_ct_unknown;
  1320     status = get_key_rating(session, ident->fpr, &input_default_ct);
  1321     if (input_default_ct < PEP_ct_strong_but_unconfirmed)
  1322         return PEP_KEY_UNSUITABLE;
  1323 
  1324     status = set_pgp_keypair(session, ident->fpr);
  1325     if (status != PEP_STATUS_OK)
  1326         return status;
  1327 
  1328     bool me = is_me(session, ident);
  1329 
  1330     pEp_identity* ident_copy = identity_dup(ident);
  1331     char* cached_fpr = NULL;
  1332 
  1333     // for setting up a temp trusted identity for the input fpr
  1334     pEp_identity* tmp_id = NULL;
  1335 
  1336     // For later, in case we need to check the user default key
  1337     pEp_identity* tmp_user_ident = NULL;
  1338 
  1339     if (me) {
  1340         bool has_private = false;
  1341         // first of all, does this key even have a private component.
  1342         status = contains_priv_key(session, ident->fpr, &has_private);
  1343         if (status != PEP_STATUS_OK && status != PEP_KEY_NOT_FOUND)
  1344             goto pEp_free;
  1345             
  1346         if (has_private) {
  1347             status = set_own_key(session, ident_copy, ident->fpr); 
  1348             goto pEp_free;
  1349         }
  1350     }
  1351     
  1352     // Either it's not me, or it's me but the key has no private key. 
  1353     // We're only talking about pub keys here. Moving on.
  1354     
  1355     // Save the input fpr, which we already tested as non-NULL
  1356     cached_fpr = strdup(ident->fpr);
  1357 
  1358     // Set up a temp trusted identity for the input fpr without a comm type;
  1359     tmp_id = new_identity(ident->address, ident->fpr, ident->user_id, NULL);
  1360     
  1361     // ->me isn't set, even if this is an own identity, so this will work.
  1362     status = validate_fpr(session, tmp_id, false);
  1363         
  1364     if (status == PEP_STATUS_OK) {
  1365         // Validate fpr gets trust DB or, when that fails, key comm type. we checked
  1366         // above that the key was ok. (not revoked or expired), but we want the max.
  1367         tmp_id->comm_type = _MAX(tmp_id->comm_type, input_default_ct) | PEP_ct_confirmed;
  1368 
  1369         // Get the default identity without setting the fpr                                       
  1370         if (me)
  1371             status = _myself(session, ident_copy, false, true);
  1372         else    
  1373             status = update_identity(session, ident_copy);
  1374             
  1375         ident_default_fpr = (EMPTYSTR(ident_copy->fpr) ? NULL : strdup(ident_copy->fpr));
  1376 
  1377         if (status == PEP_STATUS_OK) {
  1378             bool trusted_default = false;
  1379 
  1380             // If there's no default, or the default is different from the input...
  1381             if (me || EMPTYSTR(ident_default_fpr) || strcmp(cached_fpr, ident_default_fpr) != 0) {
  1382                 
  1383                 // If the default fpr (if there is one) is trusted and key is strong enough,
  1384                 // don't replace, we just set the trusted bit on this key for this user_id...
  1385                 // (If there's no default fpr, this won't be true anyway.)
  1386                 if (me || (ident_copy->comm_type >= PEP_ct_strong_but_unconfirmed && 
  1387                           (ident_copy->comm_type & PEP_ct_confirmed))) {                        
  1388 
  1389                     trusted_default = true;
  1390                                     
  1391                     status = set_trust(session, tmp_id);
  1392                     input_default_ct = tmp_id->comm_type;                    
  1393                 }
  1394                 else {
  1395                     free(ident_copy->fpr);
  1396                     ident_copy->fpr = strdup(cached_fpr);
  1397                     ident_copy->comm_type = tmp_id->comm_type;
  1398                     status = set_identity(session, ident_copy); // replace identity default
  1399                     if (status == PEP_STATUS_OK) {
  1400                         if ((ident_copy->comm_type | PEP_ct_confirmed) == PEP_ct_pEp)
  1401                             status = set_as_pEp_user(session, ident_copy);
  1402                     }            
  1403                 }
  1404             }
  1405             else { // we're setting this on the default fpr
  1406                 ident->comm_type = tmp_id->comm_type;
  1407                 status = set_identity(session, ident);
  1408                 trusted_default = true;
  1409             }
  1410             if (status == PEP_STATUS_OK && !trusted_default) {
  1411                 // Ok, there wasn't a trusted default, so we replaced. Thus, we also
  1412                 // make sure there's a trusted default on the user_id. If there
  1413                 // is not, we make this the default.
  1414                 char* user_default = NULL;
  1415                 status = get_main_user_fpr(session, ident->user_id, &user_default);
  1416             
  1417                 if (status == PEP_STATUS_OK && user_default) {
  1418                     tmp_user_ident = new_identity(ident->address, 
  1419                                                   user_default, 
  1420                                                   ident->user_id, 
  1421                                                   NULL);
  1422                     if (!tmp_user_ident)
  1423                         status = PEP_OUT_OF_MEMORY;
  1424                     else {
  1425                         status = validate_fpr(session, tmp_user_ident, false);
  1426                         
  1427                         if (status != PEP_STATUS_OK ||
  1428                             tmp_user_ident->comm_type < PEP_ct_strong_but_unconfirmed ||
  1429                             !(tmp_user_ident->comm_type & PEP_ct_confirmed)) 
  1430                         {
  1431                             char* trusted_fpr = (trusted_default ? ident_default_fpr : cached_fpr);
  1432                             status = replace_main_user_fpr(session, ident->user_id, trusted_fpr);
  1433                         } 
  1434                     }
  1435                 }
  1436             }
  1437         }
  1438     }    
  1439 
  1440 pEp_free:
  1441     free(ident_default_fpr);
  1442     free(cached_fpr);
  1443     free_identity(tmp_id);
  1444     free_identity(ident_copy);
  1445     free_identity(tmp_user_ident);
  1446     return status;
  1447 }
  1448 
  1449 DYNAMIC_API PEP_STATUS own_key_is_listed(
  1450         PEP_SESSION session,
  1451         const char *fpr,
  1452         bool *listed
  1453     )
  1454 {
  1455     PEP_STATUS status = PEP_STATUS_OK;
  1456     int count;
  1457     
  1458     assert(session && fpr && fpr[0] && listed);
  1459     
  1460     if (!(session && fpr && fpr[0] && listed))
  1461         return PEP_ILLEGAL_VALUE;
  1462     
  1463     *listed = false;
  1464     
  1465     sqlite3_reset(session->own_key_is_listed);
  1466     sqlite3_bind_text(session->own_key_is_listed, 1, fpr, -1, SQLITE_STATIC);
  1467     
  1468     int result;
  1469     
  1470     result = sqlite3_step(session->own_key_is_listed);
  1471     switch (result) {
  1472         case SQLITE_ROW:
  1473             count = sqlite3_column_int(session->own_key_is_listed, 0);
  1474             *listed = count > 0;
  1475             status = PEP_STATUS_OK;
  1476             break;
  1477             
  1478         default:
  1479             status = PEP_UNKNOWN_ERROR;
  1480     }
  1481     
  1482     sqlite3_reset(session->own_key_is_listed);
  1483     return status;
  1484 }
  1485 
  1486 PEP_STATUS _own_identities_retrieve(
  1487         PEP_SESSION session,
  1488         identity_list **own_identities,
  1489         identity_flags_t excluded_flags
  1490       )
  1491 {
  1492     PEP_STATUS status = PEP_STATUS_OK;
  1493     
  1494     assert(session && own_identities);
  1495     if (!(session && own_identities))
  1496         return PEP_ILLEGAL_VALUE;
  1497     
  1498     *own_identities = NULL;
  1499     identity_list *_own_identities = new_identity_list(NULL);
  1500     if (_own_identities == NULL)
  1501         goto enomem;
  1502     
  1503     sqlite3_reset(session->own_identities_retrieve);
  1504     
  1505     int result;
  1506     // address, fpr, username, user_id, comm_type, lang, flags
  1507     const char *address = NULL;
  1508     const char *fpr = NULL;
  1509     const char *username = NULL;
  1510     const char *user_id = NULL;
  1511     PEP_comm_type comm_type = PEP_ct_unknown;
  1512     const char *lang = NULL;
  1513     unsigned int flags = 0;
  1514     
  1515     identity_list *_bl = _own_identities;
  1516     do {
  1517         sqlite3_bind_int(session->own_identities_retrieve, 1, excluded_flags);
  1518         result = sqlite3_step(session->own_identities_retrieve);
  1519         switch (result) {
  1520             case SQLITE_ROW:
  1521                 address = (const char *)
  1522                     sqlite3_column_text(session->own_identities_retrieve, 0);
  1523                 fpr = (const char *)
  1524                     sqlite3_column_text(session->own_identities_retrieve, 1);
  1525                 user_id = (const char *)
  1526                     sqlite3_column_text(session->own_identities_retrieve, 2);
  1527                 username = (const char *)
  1528                     sqlite3_column_text(session->own_identities_retrieve, 3);
  1529                 comm_type = PEP_ct_pEp;
  1530                 lang = (const char *)
  1531                     sqlite3_column_text(session->own_identities_retrieve, 4);
  1532                 flags = (unsigned int)
  1533                     sqlite3_column_int(session->own_identities_retrieve, 5);
  1534 
  1535                 pEp_identity *ident = new_identity(address, fpr, user_id, username);
  1536                 if (!ident)
  1537                     goto enomem;
  1538                 ident->comm_type = comm_type;
  1539                 if (lang && lang[0]) {
  1540                     ident->lang[0] = lang[0];
  1541                     ident->lang[1] = lang[1];
  1542                     ident->lang[2] = 0;
  1543                 }
  1544                 ident->me = true;
  1545                 ident->flags = flags;
  1546 
  1547                 _bl = identity_list_add(_bl, ident);
  1548                 if (_bl == NULL) {
  1549                     free_identity(ident);
  1550                     goto enomem;
  1551                 }
  1552                 
  1553                 break;
  1554                 
  1555             case SQLITE_DONE:
  1556                 break;
  1557                 
  1558             default:
  1559                 status = PEP_UNKNOWN_ERROR;
  1560                 result = SQLITE_DONE;
  1561         }
  1562     } while (result != SQLITE_DONE);
  1563     
  1564     sqlite3_reset(session->own_identities_retrieve);
  1565     if (status == PEP_STATUS_OK)
  1566         *own_identities = _own_identities;
  1567     else
  1568         free_identity_list(_own_identities);
  1569     
  1570     goto the_end;
  1571     
  1572 enomem:
  1573     free_identity_list(_own_identities);
  1574     status = PEP_OUT_OF_MEMORY;
  1575     
  1576 the_end:
  1577     return status;
  1578 }
  1579 
  1580 DYNAMIC_API PEP_STATUS own_identities_retrieve(
  1581         PEP_SESSION session,
  1582         identity_list **own_identities
  1583       )
  1584 {
  1585     return _own_identities_retrieve(session, own_identities, 0);
  1586 }
  1587 
  1588 PEP_STATUS _own_keys_retrieve(
  1589         PEP_SESSION session,
  1590         stringlist_t **keylist,
  1591         identity_flags_t excluded_flags
  1592       )
  1593 {
  1594     PEP_STATUS status = PEP_STATUS_OK;
  1595     
  1596     assert(session && keylist);
  1597     if (!(session && keylist))
  1598         return PEP_ILLEGAL_VALUE;
  1599     
  1600     *keylist = NULL;
  1601     stringlist_t *_keylist = NULL;
  1602     
  1603     sqlite3_reset(session->own_keys_retrieve);
  1604     
  1605     int result;
  1606     char *fpr = NULL;
  1607     
  1608     stringlist_t *_bl = _keylist;
  1609     do {
  1610         sqlite3_bind_int(session->own_keys_retrieve, 1, excluded_flags);
  1611         result = sqlite3_step(session->own_keys_retrieve);
  1612         switch (result) {
  1613             case SQLITE_ROW:
  1614                 fpr = strdup((const char *) sqlite3_column_text(session->own_keys_retrieve, 0));
  1615                 if(fpr == NULL)
  1616                     goto enomem;
  1617 
  1618                 _bl = stringlist_add(_bl, fpr);
  1619                 if (_bl == NULL) {
  1620                     free(fpr);
  1621                     goto enomem;
  1622                 }
  1623                 if (_keylist == NULL)
  1624                     _keylist = _bl;
  1625                 
  1626                 break;
  1627                 
  1628             case SQLITE_DONE:
  1629                 break;
  1630                 
  1631             default:
  1632                 status = PEP_UNKNOWN_ERROR;
  1633                 result = SQLITE_DONE;
  1634         }
  1635     } while (result != SQLITE_DONE);
  1636     
  1637     sqlite3_reset(session->own_keys_retrieve);
  1638     if (status == PEP_STATUS_OK)
  1639         *keylist = _keylist;
  1640     else
  1641         free_stringlist(_keylist);
  1642     
  1643     goto the_end;
  1644     
  1645 enomem:
  1646     free_stringlist(_keylist);
  1647     status = PEP_OUT_OF_MEMORY;
  1648     
  1649 the_end:
  1650     return status;
  1651 }
  1652 
  1653 DYNAMIC_API PEP_STATUS own_keys_retrieve(PEP_SESSION session, stringlist_t **keylist)
  1654 {
  1655     return _own_keys_retrieve(session, keylist, 0);
  1656 }
  1657 
  1658 DYNAMIC_API PEP_STATUS set_own_key(
  1659        PEP_SESSION session,
  1660        pEp_identity *me,
  1661        const char *fpr
  1662     )
  1663 {
  1664     PEP_STATUS status = PEP_STATUS_OK;
  1665     
  1666     assert(session && me);
  1667     assert(!EMPTYSTR(fpr));
  1668     assert(!EMPTYSTR(me->address));
  1669     assert(!EMPTYSTR(me->user_id));
  1670     assert(!EMPTYSTR(me->username));
  1671 
  1672     if (!session || !me || EMPTYSTR(fpr) || EMPTYSTR(me->address) ||
  1673             EMPTYSTR(me->user_id) || EMPTYSTR(me->username))
  1674         return PEP_ILLEGAL_VALUE;
  1675 
  1676     status = _myself(session, me, false, true);
  1677     // we do not need a valid key but dislike other errors
  1678     if (status != PEP_STATUS_OK && status != PEP_GET_KEY_FAILED && status != PEP_KEY_UNSUITABLE)
  1679         return status;
  1680     status = PEP_STATUS_OK;
  1681 
  1682     bool private = false;
  1683     status = contains_priv_key(session, fpr, &private);
  1684     
  1685     if (status != PEP_STATUS_OK)
  1686         return status;
  1687         
  1688     if (!private)
  1689         return PEP_KEY_UNSUITABLE;
  1690  
  1691     if (me->fpr)
  1692         free(me->fpr);
  1693     me->fpr = strdup(fpr);
  1694     assert(me->fpr);
  1695     if (!me->fpr)
  1696         return PEP_OUT_OF_MEMORY;
  1697 
  1698     status = validate_fpr(session, me, false);
  1699     if (status)
  1700         return status;
  1701 
  1702     me->comm_type = PEP_ct_pEp;
  1703     status = set_identity(session, me);
  1704     return status;
  1705 }
  1706 
  1707 PEP_STATUS contains_priv_key(PEP_SESSION session, const char *fpr,
  1708                              bool *has_private) {
  1709 
  1710     assert(session);
  1711     assert(fpr);
  1712     assert(has_private);
  1713     
  1714     if (!(session && fpr && has_private))
  1715         return PEP_ILLEGAL_VALUE;
  1716 
  1717     return session->cryptotech[PEP_crypt_OpenPGP].contains_priv_key(session, fpr, has_private);
  1718 }
  1719 
  1720 PEP_STATUS add_mistrusted_key(PEP_SESSION session, const char* fpr)
  1721 {
  1722     int result;
  1723 
  1724     assert(!EMPTYSTR(fpr));
  1725     
  1726     if (!(session) || EMPTYSTR(fpr))
  1727         return PEP_ILLEGAL_VALUE;
  1728 
  1729     sqlite3_reset(session->add_mistrusted_key);
  1730     sqlite3_bind_text(session->add_mistrusted_key, 1, fpr, -1,
  1731             SQLITE_STATIC);
  1732 
  1733     result = sqlite3_step(session->add_mistrusted_key);
  1734     sqlite3_reset(session->add_mistrusted_key);
  1735 
  1736     if (result != SQLITE_DONE)
  1737         return PEP_CANNOT_SET_PGP_KEYPAIR; // FIXME: Better status?
  1738 
  1739     return PEP_STATUS_OK;
  1740 }
  1741 
  1742 PEP_STATUS delete_mistrusted_key(PEP_SESSION session, const char* fpr)
  1743 {
  1744     int result;
  1745 
  1746     assert(!EMPTYSTR(fpr));
  1747     
  1748     if (!(session) || EMPTYSTR(fpr))
  1749         return PEP_ILLEGAL_VALUE;
  1750 
  1751     sqlite3_reset(session->delete_mistrusted_key);
  1752     sqlite3_bind_text(session->delete_mistrusted_key, 1, fpr, -1,
  1753             SQLITE_STATIC);
  1754 
  1755     result = sqlite3_step(session->delete_mistrusted_key);
  1756     sqlite3_reset(session->delete_mistrusted_key);
  1757 
  1758     if (result != SQLITE_DONE)
  1759         return PEP_UNKNOWN_ERROR; // FIXME: Better status?
  1760 
  1761     return PEP_STATUS_OK;
  1762 }
  1763 
  1764 PEP_STATUS is_mistrusted_key(PEP_SESSION session, const char* fpr,
  1765                              bool* mistrusted)
  1766 {
  1767     PEP_STATUS status = PEP_STATUS_OK;
  1768 
  1769     assert(session);
  1770     assert(!EMPTYSTR(fpr));
  1771 
  1772     if (!(session && fpr))
  1773         return PEP_ILLEGAL_VALUE;
  1774 
  1775     *mistrusted = false;
  1776 
  1777     sqlite3_reset(session->is_mistrusted_key);
  1778     sqlite3_bind_text(session->is_mistrusted_key, 1, fpr, -1, SQLITE_STATIC);
  1779 
  1780     int result;
  1781 
  1782     result = sqlite3_step(session->is_mistrusted_key);
  1783     switch (result) {
  1784     case SQLITE_ROW:
  1785         *mistrusted = sqlite3_column_int(session->is_mistrusted_key, 0);
  1786         status = PEP_STATUS_OK;
  1787         break;
  1788 
  1789     default:
  1790         status = PEP_UNKNOWN_ERROR;
  1791     }
  1792 
  1793     sqlite3_reset(session->is_mistrusted_key);
  1794     return status;
  1795 }
  1796 
  1797 #ifdef USE_GPG
  1798 PEP_STATUS pgp_find_trusted_private_keys(
  1799         PEP_SESSION session, stringlist_t **keylist
  1800     );
  1801 
  1802 enum _pgp_thing {
  1803     _pgp_none = 0,
  1804     _pgp_fpr,
  1805     _pgp_email,
  1806     _pgp_name
  1807 };
  1808 
  1809 static enum _pgp_thing _pgp_thing_next(enum _pgp_thing thing)
  1810 {
  1811     switch (thing) {
  1812         case _pgp_fpr:
  1813             return _pgp_email;
  1814         case _pgp_email:
  1815             return _pgp_name;
  1816         case _pgp_name:
  1817             return _pgp_fpr;
  1818         default:
  1819             return _pgp_fpr;
  1820     }
  1821 }
  1822 
  1823 PEP_STATUS pgp_import_ultimately_trusted_keypairs(PEP_SESSION session) {
  1824     assert(session);
  1825     if (!session)
  1826         return PEP_ILLEGAL_VALUE;
  1827 
  1828     stringlist_t* priv_keylist = NULL;
  1829     PEP_STATUS status = PEP_STATUS_OK;
  1830 
  1831     // 1. get keys
  1832     status = pgp_find_trusted_private_keys(session, &priv_keylist);
  1833     if (status)
  1834         return status;
  1835 
  1836     pEp_identity *identity = NULL;
  1837     stringlist_t *_sl;
  1838 	
  1839     char *fpr = NULL;
  1840     enum _pgp_thing thing = _pgp_none;
  1841     for (_sl = priv_keylist; _sl && _sl->value; _sl = _sl->next) {
  1842         thing = _pgp_thing_next(thing);
  1843         switch (thing) {
  1844             case _pgp_fpr:
  1845                 identity = new_identity(NULL, NULL, PEP_OWN_USERID, NULL);
  1846                 if (!identity)
  1847                     status = PEP_OUT_OF_MEMORY;
  1848                 identity->me = true;
  1849                 fpr = strdup(_sl->value);
  1850                 assert(fpr);
  1851                 if (!fpr) {
  1852                     status = PEP_OUT_OF_MEMORY;
  1853                     free_identity(identity);
  1854                 }
  1855                 break;
  1856             case _pgp_email:
  1857                 assert(identity);
  1858                 identity->address = strdup(_sl->value);
  1859                 assert(identity->address);
  1860                 if (!identity->address) {
  1861                     status = PEP_OUT_OF_MEMORY;
  1862                     free_identity(identity);
  1863                 }
  1864                 break;
  1865             case _pgp_name:
  1866                 assert(identity);
  1867                 identity->username = strdup(_sl->value);
  1868                 assert(identity->username);
  1869                 if (!identity->username)
  1870                     status = PEP_OUT_OF_MEMORY;
  1871                 else
  1872                     status = set_own_key(session, identity, fpr);
  1873                 free_identity(identity);
  1874                 identity = NULL;
  1875                 break;
  1876             default:
  1877                 assert(0);
  1878                 free_identity(identity);
  1879                 status = PEP_UNKNOWN_ERROR;
  1880         }
  1881         if (status)
  1882             break;
  1883     }
  1884     
  1885     free_stringlist(priv_keylist);
  1886     return status;
  1887 }
  1888 #endif // USE_GPG
  1889