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