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