CpEpEngine.cpp
author Volker Birk <vb@pep.foundation>
Sat, 24 Feb 2018 20:46:07 +0100
changeset 275 08f4040eca91
parent 264 aa6bd84bd6c3
child 276 35af9f35a9af
permissions -rw-r--r--
adding SetOwnKey
     1 // CpEpEngine.cpp : Implementation of CpEpEngine
     2 
     3 #include "stdafx.h"
     4 #include "CpEpEngine.h"
     5 #include <mutex>
     6 
     7 using namespace std;
     8 using namespace pEp::utility;
     9 
    10 // CpEpEngine
    11 std::mutex CpEpEngine::init_mutex;
    12 
    13 STDMETHODIMP CpEpEngine::InterfaceSupportsErrorInfo(REFIID riid)
    14 {
    15     static const IID* const arr[] =
    16     {
    17         &IID_IpEpEngine,
    18         &IID_IpEpEngine2,
    19     };
    20 
    21     for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
    22     {
    23         if (InlineIsEqualGUID(*arr[i], riid))
    24             return S_OK;
    25     }
    26     return S_FALSE;
    27 }
    28 
    29 // The second argument is optional, and currently supports PEP_STATUS.
    30 #define FAIL(msg, ...) error(msg, __VA_ARGS__)
    31 
    32 STDMETHODIMP CpEpEngine::VerboseLogging(VARIANT_BOOL enable)
    33 {
    34     verbose_mode = enable != VARIANT_FALSE;
    35     return S_OK;
    36 }
    37 
    38 STDMETHODIMP CpEpEngine::PassiveMode(VARIANT_BOOL enable)
    39 {
    40     ::config_passive_mode(get_session(), enable != VARIANT_FALSE);
    41     return S_OK;
    42 }
    43 
    44 STDMETHODIMP CpEpEngine::UnencryptedSubject(VARIANT_BOOL enable)
    45 {
    46     ::config_unencrypted_subject(get_session(), enable != VARIANT_FALSE);
    47     return S_OK;
    48 }
    49 
    50 STDMETHODIMP CpEpEngine::ExportKey(BSTR fpr, BSTR * keyData)
    51 {
    52     assert(fpr);
    53     assert(keyData);
    54 
    55     if (!(fpr && keyData))
    56         return E_INVALIDARG;
    57 
    58     string _fpr = utf8_string(fpr);
    59     char *_key_data = NULL;
    60     size_t _size = 0;
    61 
    62     ::PEP_STATUS status = ::export_key(get_session(), _fpr.c_str(), &_key_data, &_size);
    63     assert(status != ::PEP_OUT_OF_MEMORY);
    64     if (status == ::PEP_OUT_OF_MEMORY)
    65         return E_OUTOFMEMORY;
    66 
    67     if (status != ::PEP_STATUS_OK)
    68         return FAIL(L"export_key", status);
    69 
    70     _bstr_t b_key_data(utf16_string(_key_data).c_str());
    71     pEp_free(_key_data);
    72     *keyData = b_key_data.Detach();
    73 
    74     return S_OK;
    75 }
    76 
    77 STDMETHODIMP CpEpEngine::Log(BSTR title, BSTR entity, BSTR description, BSTR comment)
    78 {
    79     string _title;
    80     string _entity;
    81     string _description;
    82     string _comment;
    83     HRESULT result = S_OK;
    84 
    85     assert(title);
    86     if (title)
    87         _title = utf8_string(title);
    88     else
    89         result = E_INVALIDARG;
    90 
    91     assert(entity);
    92     if (entity)
    93         _entity = utf8_string(entity);
    94     else
    95         result = E_INVALIDARG;
    96 
    97     if (description)
    98         _description = utf8_string(description);
    99 
   100     if (comment)
   101         _comment = utf8_string(comment);
   102 
   103     if (result != S_OK)
   104         return result;
   105 
   106     PEP_STATUS _status = ::log_event(get_session(), _title.c_str(), _entity.c_str(), _description.c_str(), _comment.c_str());
   107     assert(_status == PEP_STATUS_OK);
   108     if (_status != PEP_STATUS_OK)
   109         return FAIL(L"log_event", _status);
   110     else
   111         return S_OK;
   112 }
   113 
   114 STDMETHODIMP CpEpEngine::Trustwords(BSTR fpr, BSTR lang, LONG max_words, BSTR * words)
   115 {
   116     assert(fpr);
   117     assert(max_words >= 0);
   118     assert(words);
   119 
   120     HRESULT result = S_OK;
   121 
   122     string _fpr;
   123     if (fpr)
   124         _fpr = utf8_string(fpr);
   125     else
   126         result = E_INVALIDARG;
   127 
   128     string _lang;
   129     if (lang) {
   130         _lang = utf8_string(lang);
   131         if (_lang.length()) {
   132             if (_lang.length() != 2)
   133                 result = E_INVALIDARG;
   134         }
   135         else
   136             _lang = "en";
   137     }
   138     else
   139         _lang = "en";
   140 
   141     if (max_words < 0)
   142         result = E_INVALIDARG;
   143 
   144     if (words == NULL)
   145         result = E_INVALIDARG;
   146 
   147     if (result != S_OK)
   148         return result;
   149 
   150     char *_words = NULL;
   151     size_t _wsize = 0;
   152 
   153     PEP_STATUS status = ::trustwords(get_session(), _fpr.c_str(), _lang.c_str(), &_words, &_wsize, max_words);
   154     assert(status != PEP_OUT_OF_MEMORY);
   155     if (status == PEP_OUT_OF_MEMORY)
   156         return E_OUTOFMEMORY;
   157 
   158     if (_words == NULL) {
   159         *words = NULL;
   160         return FAIL(L"Trustwords: _words == NULL", status);
   161     }
   162     else {
   163         *words = utf16_bstr(_words);
   164         pEp_free(_words);
   165         return S_OK;
   166     }
   167 }
   168 
   169 STDMETHODIMP CpEpEngine::GetTrustwords(struct pEpIdentity *id1, struct pEpIdentity *id2, BSTR lang, VARIANT_BOOL full, BSTR *words)
   170 {
   171     assert(id1);
   172     assert(id2);
   173     assert(words);
   174 
   175     if (!(id1 && id2 && words))
   176     {
   177         return E_INVALIDARG;
   178     }
   179 
   180     HRESULT result = S_OK;
   181 
   182     pEp_identity* _id1 = NULL;
   183     pEp_identity* _id2 = NULL;
   184     string _lang;
   185     *words = NULL;
   186 
   187     try {
   188         _id1 = new_identity(id1);
   189         _id2 = new_identity(id2);
   190 
   191         if (lang) {
   192             _lang = utf8_string(lang);
   193             if (_lang.length() == 0) {
   194                 _lang = "en";
   195             }
   196             else if (_lang.length() != 2) {
   197                 result = E_INVALIDARG;
   198             }
   199         }
   200         else {
   201             _lang = "en";
   202         }
   203     }
   204     catch (bad_alloc&) {
   205         result = E_OUTOFMEMORY;
   206     }
   207     catch (exception& ex) {
   208         result = FAIL(ex.what());
   209     }
   210 
   211     char* _words;
   212     size_t _size;
   213     if (result == S_OK) {
   214         auto status = ::get_trustwords(get_session(), _id1, _id2, _lang.c_str(), &_words, &_size, full != 0 /* convert variant bool to C bool */);
   215 
   216         if (status == PEP_OUT_OF_MEMORY) {
   217             result = E_OUTOFMEMORY;
   218         }
   219         else if (status == PEP_TRUSTWORD_NOT_FOUND) {
   220             result = FAIL(L"GetTrustwords: Trustword not found", status);
   221         }
   222         else if (!words) {
   223             result = FAIL(L"GetTrustwords: _words == NULL", status);
   224         }
   225         else {
   226             *words = utf16_bstr(_words);
   227             pEp_free(_words);
   228         }
   229     }
   230 
   231     free_identity(_id1);
   232     free_identity(_id2);
   233 
   234     return result;
   235 }
   236 
   237 STDMETHODIMP CpEpEngine::GetMessageTrustwords(
   238     /* [in] */ struct TextMessage *msg,
   239     /* [in] */ struct pEpIdentity *receivedBy,
   240     /* [in] */ SAFEARRAY *keylist,
   241     /* [defaultvalue][in] */ BSTR lang,
   242     /* [defaultvalue][in] */ VARIANT_BOOL full,
   243     /* [retval][out] */ BSTR *words) {
   244     assert(msg);
   245     assert(receivedBy);
   246     assert(words);
   247 
   248     if (!(msg && receivedBy && words))
   249     {
   250         return E_INVALIDARG;
   251     }
   252 
   253     HRESULT result = S_OK;
   254 
   255     pEp_identity * _received_by = NULL;
   256     ::message * _msg = NULL;
   257     ::stringlist_t *_keylist = NULL;
   258     string _lang;
   259     *words = NULL;
   260 
   261     try {
   262         _received_by = new_identity(receivedBy);
   263         _msg = text_message_to_C(msg);
   264 
   265         if (keylist) {
   266             _keylist = new_stringlist(keylist);
   267         }
   268 
   269         if (lang) {
   270             _lang = utf8_string(lang);
   271             if (_lang.length() == 0) {
   272                 _lang = "en";
   273             }
   274             else if (_lang.length() != 2) {
   275                 result = E_INVALIDARG;
   276             }
   277         }
   278         else {
   279             _lang = "en";
   280         }
   281     }
   282     catch (bad_alloc&) {
   283         result = E_OUTOFMEMORY;
   284     }
   285     catch (exception& ex) {
   286         result = FAIL(ex.what());
   287     }
   288 
   289     char* _words = NULL;
   290     if (result == S_OK) {
   291         auto status = ::get_message_trustwords(
   292             get_session(),
   293             _msg,
   294             _keylist,
   295             _received_by,
   296             _lang.c_str(),
   297             &_words,
   298             full != 0 /* convert variant bool to C bool */);
   299 
   300         if (status == PEP_OUT_OF_MEMORY) {
   301             result = E_OUTOFMEMORY;
   302         }
   303         else if (status == PEP_TRUSTWORD_NOT_FOUND) {
   304             result = FAIL(L"GetTrustwords: Trustword not found", status);
   305         }
   306         else if (!words) {
   307             result = FAIL(L"GetTrustwords: _words == NULL", status);
   308         }
   309         else {
   310             *words = utf16_bstr(_words);
   311         }
   312     }
   313 
   314     ::pEp_free(_words);
   315     ::free_message(_msg);
   316     ::free_stringlist(_keylist);
   317     ::free_identity(_received_by);
   318 
   319     return result;
   320 }
   321 
   322 STDMETHODIMP CpEpEngine::GetCrashdumpLog(LONG maxlines, BSTR * log)
   323 {
   324     // COM-18: Currently, long == int on windows, so the check
   325     // for INT_MAX is not strictly necessary. However, the code
   326     // might get copy-pasted to other adapters in the future,
   327     // so safety first...
   328     assert(maxlines >= 0 && maxlines <= INT_MAX);
   329     assert(log);
   330 
   331     if (!(maxlines >= 0 && maxlines <= INT_MAX && log))
   332         return E_INVALIDARG;
   333 
   334     char *_log;
   335     PEP_STATUS status = ::get_crashdump_log(get_session(), (int)maxlines, &_log);
   336     assert(status == PEP_STATUS_OK);
   337     if (status == PEP_OUT_OF_MEMORY)
   338         return E_OUTOFMEMORY;
   339     if (status != PEP_STATUS_OK)
   340         return FAIL(L"GetCrashdumpLog", status);
   341     if (_log == NULL)
   342         return FAIL(L"GetCrashdumpLog: _log == NULL");
   343 
   344     *log = utf16_bstr(_log);
   345     pEp_free(_log);
   346     return S_OK;
   347 }
   348 
   349 STDMETHODIMP CpEpEngine::GetEngineVersion(BSTR * engine_version)
   350 {
   351     assert(engine_version);
   352 
   353     if (!engine_version)
   354         return E_INVALIDARG;
   355 
   356     const char *_engine_version = ::get_engine_version();
   357 
   358     if (_engine_version == NULL)
   359         return FAIL(L"GetEngineVersion: _engine_version == NULL");
   360 
   361     *engine_version = utf16_bstr(_engine_version);
   362 
   363     return S_OK;
   364 }
   365 
   366 STDMETHODIMP CpEpEngine::GetLanguageList(BSTR * languages)
   367 {
   368     assert(languages);
   369 
   370     if (!languages)
   371         return E_INVALIDARG;
   372 
   373     char *_languages;
   374     PEP_STATUS status = ::get_languagelist(get_session(), &_languages);
   375     assert(status == PEP_STATUS_OK);
   376     if (status == PEP_OUT_OF_MEMORY)
   377         return E_OUTOFMEMORY;
   378     if (status != PEP_STATUS_OK)
   379         return FAIL(L"GetLanguageList", status);
   380     if (_languages == NULL)
   381         return FAIL(L"GetLanguageList: _languages == NULL");
   382 
   383     *languages = utf16_bstr(_languages);
   384     pEp_free(_languages);
   385     return S_OK;
   386 }
   387 
   388 STDMETHODIMP CpEpEngine::SetIdentityFlags(struct pEpIdentity *identity, pEpIdentityFlags flags)
   389 {
   390     assert(identity);
   391     if (!identity)
   392         return E_INVALIDARG;
   393 
   394     ::pEp_identity *_ident = nullptr;
   395 
   396     try {
   397         _ident = new_identity(identity);
   398         assert(_ident);
   399         if (_ident == NULL)
   400             return E_OUTOFMEMORY;
   401     }
   402     catch (bad_alloc&) {
   403         return E_OUTOFMEMORY;
   404     }
   405     catch (exception& ex) {
   406         return FAIL(ex.what());;
   407     }
   408 
   409     PEP_STATUS status = ::set_identity_flags(get_session(), _ident, (identity_flags_t)flags);
   410     ::free_identity(_ident);
   411     if (status != PEP_STATUS_OK)
   412         return FAIL(_T("SetIdentityFlags"), status);
   413 
   414     return S_OK;
   415 }
   416 
   417 STDMETHODIMP CpEpEngine::UnsetIdentityFlags(struct pEpIdentity *identity, pEpIdentityFlags flags)
   418 {
   419     assert(identity);
   420     if (!identity)
   421         return E_INVALIDARG;
   422 
   423     ::pEp_identity *_ident = nullptr;
   424 
   425     try {
   426         _ident = new_identity(identity);
   427         assert(_ident);
   428         if (_ident == NULL)
   429             return E_OUTOFMEMORY;
   430     }
   431     catch (bad_alloc&) {
   432         return E_OUTOFMEMORY;
   433     }
   434     catch (exception& ex) {
   435         return FAIL(ex.what());;
   436     }
   437 
   438     PEP_STATUS status = ::unset_identity_flags(get_session(), _ident, (identity_flags_t)flags);
   439     ::free_identity(_ident);
   440     if (status != PEP_STATUS_OK)
   441         return FAIL(_T("UnsetIdentityFlags"), status);
   442 
   443     return S_OK;
   444 }
   445 
   446 STDMETHODIMP CpEpEngine::StartKeyserverLookup()
   447 {
   448     if (identity_queue.load())
   449         return S_OK;
   450 
   451     identity_queue.store(new identity_queue_t());
   452     keymanagement_thread = new thread(::do_keymanagement, retrieve_next_identity, (void *)identity_queue.load());
   453 
   454     return S_OK;
   455 }
   456 
   457 STDMETHODIMP CpEpEngine::StopKeyserverLookup()
   458 {
   459     if (identity_queue.load() == NULL)
   460         return S_OK;
   461 
   462     identity_queue_t *_iq = identity_queue.load();
   463     identity_queue.store(NULL);
   464 
   465     pEp_identity_cpp shutdown;
   466     _iq->push_front(shutdown);
   467 
   468     keymanagement_thread->join();
   469     delete keymanagement_thread;
   470     keymanagement_thread = NULL;
   471 
   472     delete _iq;
   473 
   474     return S_OK;
   475 }
   476 
   477 STDMETHODIMP CpEpEngine::Myself(struct pEpIdentity *ident, struct pEpIdentity *result)
   478 {
   479     assert(ident);
   480     assert(result);
   481 
   482     if (!(ident && result))
   483         return E_INVALIDARG;
   484 
   485     ::pEp_identity *_ident = 0;
   486 
   487     try {
   488         _ident = new_identity(ident);
   489         assert(_ident);
   490         if (_ident == NULL)
   491             return E_OUTOFMEMORY;
   492     }
   493     catch (bad_alloc&) {
   494         return E_OUTOFMEMORY;
   495     }
   496     catch (exception& ex) {
   497         return FAIL(ex.what());;
   498     }
   499 
   500 
   501     // DEBUG CODE - REMOVE BEFORE RELEASE!
   502     // SyncHandshakeResult handshakeResult;
   503     //
   504     // HRESULT res = Fire_NotifyHandshake(ident, result, signal, &handshakeResult);
   505     // 
   506     // HRESULT res2 = Fire_TestEvent(15, _bstr_t( "hallo"));
   507 
   508     PEP_STATUS status = ::myself(get_session(), _ident);
   509 
   510     if (status == PEP_STATUS_OK) {
   511         assert(_ident->fpr);
   512         copy_identity(result, _ident);
   513         ::free_identity(_ident);
   514         return S_OK;
   515     }
   516     else {
   517         ::free_identity(_ident);
   518         if (status == PEP_OUT_OF_MEMORY)
   519             return E_OUTOFMEMORY;
   520         else
   521             return FAIL(L"myself", status);
   522     }
   523 }
   524 
   525 STDMETHODIMP CpEpEngine::UpdateIdentity(struct pEpIdentity *ident, struct pEpIdentity *result)
   526 {
   527     assert(ident);
   528     assert(result);
   529 
   530     if (!(ident && result))
   531         return E_INVALIDARG;
   532 
   533     ::pEp_identity *_ident;
   534     try {
   535         _ident = new_identity(ident);
   536     }
   537     catch (bad_alloc&) {
   538         return E_OUTOFMEMORY;
   539     }
   540     catch (exception& ex) {
   541         return FAIL(ex.what());
   542     }
   543 
   544     assert(_ident);
   545     if (_ident == NULL)
   546         return E_OUTOFMEMORY;
   547 
   548     PEP_STATUS status = ::update_identity(get_session(), _ident);
   549 
   550     if (status == PEP_STATUS_OK) {
   551         assert(_ident->fpr); // Guaranteed not NULL, but possibly empty string.
   552         copy_identity(result, _ident);
   553         ::free_identity(_ident);
   554         return S_OK;
   555     }
   556     else if (status == PEP_GET_KEY_FAILED) {
   557         if (_ident->fpr) {
   558             pEp_free(_ident->fpr);
   559             _ident->fpr = NULL;
   560         }
   561         copy_identity(result, _ident);
   562         result->Fpr = NULL;
   563         ::free_identity(_ident);
   564         return S_OK;
   565     }
   566     else {
   567         ::free_identity(_ident);
   568         if (status == PEP_OUT_OF_MEMORY)
   569             return E_OUTOFMEMORY;
   570         else
   571             return FAIL(L"UpdateIdentity", status);
   572     }
   573 }
   574 
   575 STDMETHODIMP CpEpEngine::KeyMistrusted(struct pEpIdentity *ident)
   576 {
   577     ::pEp_identity *_ident;
   578 
   579     assert(ident);
   580     if (!ident)
   581         return E_INVALIDARG;
   582 
   583     try {
   584         _ident = new_identity(ident);
   585     }
   586     catch (bad_alloc&) {
   587         return E_OUTOFMEMORY;
   588     }
   589     catch (exception& ex) {
   590         return FAIL(ex.what());;
   591     }
   592 
   593     PEP_STATUS status = ::key_mistrusted(get_session(), _ident);
   594     free_identity(_ident);
   595 
   596     if (status == PEP_OUT_OF_MEMORY)
   597         return E_OUTOFMEMORY;
   598 
   599     if (status == PEP_KEY_NOT_FOUND)
   600         return FAIL(L"key not found");
   601 
   602     if (status != ::PEP_STATUS_OK)
   603         return FAIL(L"cannot revoke compromized key", status);
   604 
   605     return S_OK;
   606 }
   607 
   608 STDMETHODIMP CpEpEngine::UndoLastMistrust()
   609 {
   610 	PEP_STATUS status = ::undo_last_mistrust(get_session());
   611 
   612 	if (status == PEP_CANNOT_FIND_IDENTITY)
   613 		return FAIL(L"Cannot find identity!", status);
   614 
   615 	if (status != ::PEP_STATUS_OK)
   616 		return FAIL(L"cannot revoke compromized key", status);
   617 
   618 	return S_OK;
   619 }
   620 
   621 STDMETHODIMP CpEpEngine::SetOwnKey(pEpIdentity * identity, BSTR fpr, struct pEpIdentity *result)
   622 {
   623 
   624 	return S_OK;
   625 }
   626 
   627 STDMETHODIMP CpEpEngine::KeyResetTrust(struct pEpIdentity *ident)
   628 {
   629     ::pEp_identity *_ident;
   630 
   631     assert(ident);
   632 
   633     if (!ident)
   634         return E_INVALIDARG;
   635 
   636     try {
   637         _ident = new_identity(ident);
   638     }
   639     catch (bad_alloc&) {
   640         return E_OUTOFMEMORY;
   641     }
   642     catch (exception& ex) {
   643         return FAIL(ex.what());;
   644     }
   645 
   646     PEP_STATUS status = ::key_reset_trust(get_session(), _ident);
   647     free_identity(_ident);
   648 
   649     if (status == PEP_OUT_OF_MEMORY)
   650         return E_OUTOFMEMORY;
   651 
   652     if (status == PEP_KEY_NOT_FOUND)
   653         return FAIL(L"key not found");
   654 
   655     if (status != ::PEP_STATUS_OK)
   656         return FAIL(L"cannot reset trust", status);
   657 
   658     return S_OK;
   659 }
   660 
   661 int CpEpEngine::examine_identity(pEp_identity *ident, void *management)
   662 {
   663     assert(ident);
   664     assert(management);
   665     if (!(ident && management))
   666         return -1;
   667 
   668     CpEpEngine *me = (CpEpEngine *)management;
   669 
   670     if (me->identity_queue.load() == NULL)
   671         return 0;
   672 
   673     try {
   674         me->identity_queue.load()->push_back(ident);
   675     }
   676     catch (exception&) {
   677         return -1;
   678     }
   679 
   680     return 0;
   681 }
   682 
   683 ::pEp_identity * CpEpEngine::retrieve_next_identity(void *management)
   684 {
   685     assert(management);
   686     if (!management)
   687         return NULL;
   688 
   689     identity_queue_t *iq = (identity_queue_t *)management;
   690 
   691     do /* poll queue */ {
   692         if (iq->size())
   693             break;
   694         ::Sleep(100);
   695     } while (true);
   696 
   697     ::pEp_identity *_ident;
   698     pEp_identity_cpp& ident = iq->front();
   699 
   700     if (ident.address.size() == 0)
   701         return NULL;
   702 
   703     _ident = ident.to_pEp_identity();
   704     iq->pop_front();
   705 
   706     return _ident;
   707 }
   708 
   709 PEP_STATUS CpEpEngine::messageToSend(void * obj, message *msg)
   710 {
   711     assert(msg);
   712     assert(obj);
   713     if (!(msg && obj))
   714         return PEP_ILLEGAL_VALUE;
   715 
   716     TextMessage _msg;
   717     memset(&_msg, 0, sizeof(TextMessage));
   718 
   719     text_message_from_C(&_msg, msg);
   720     CpEpEngine *me = (CpEpEngine *)obj;
   721     HRESULT r = me->Fire_MessageToSend(&_msg);
   722     assert(r == S_OK);
   723     clear_text_message(&_msg);
   724     if (r == E_OUTOFMEMORY)
   725         return PEP_OUT_OF_MEMORY;
   726     if (r != S_OK)
   727         return PEP_UNKNOWN_ERROR;
   728 
   729     return PEP_STATUS_OK;
   730 }
   731 
   732 STDMETHODIMP CpEpEngine::BlacklistAdd(BSTR fpr)
   733 {
   734     assert(fpr);
   735     if (!fpr)
   736         return E_INVALIDARG;
   737 
   738     string _fpr = utf8_string(fpr);
   739     PEP_STATUS status = ::blacklist_add(get_session(), _fpr.c_str());
   740     assert(status == PEP_STATUS_OK);
   741     if (status != PEP_STATUS_OK)
   742         return FAIL(L"blacklist_add failed in pEp engine", status);
   743 
   744     return S_OK;
   745 }
   746 
   747 STDMETHODIMP CpEpEngine::BlacklistDelete(BSTR fpr)
   748 {
   749     assert(fpr);
   750     if (!fpr)
   751         return E_INVALIDARG;
   752 
   753     string _fpr = utf8_string(fpr);
   754     PEP_STATUS status = ::blacklist_delete(get_session(), _fpr.c_str());
   755     assert(status == PEP_STATUS_OK);
   756     if (status != PEP_STATUS_OK)
   757         return FAIL(L"blacklist_delete failed in pEp engine", status);
   758 
   759     return S_OK;
   760 }
   761 
   762 STDMETHODIMP CpEpEngine::BlacklistIsListed(BSTR fpr, VARIANT_BOOL *listed)
   763 {
   764     assert(fpr);
   765     assert(listed);
   766 
   767     if (!(fpr && listed))
   768         return E_INVALIDARG;
   769 
   770     string _fpr = utf8_string(fpr);
   771     bool result;
   772     PEP_STATUS status = ::blacklist_is_listed(get_session(), _fpr.c_str(), &result);
   773     assert(status == PEP_STATUS_OK);
   774     if (status != PEP_STATUS_OK)
   775         return FAIL(L"blacklist_is_listed failed in pEp engine", status);
   776 
   777     *listed = result ? VARIANT_TRUE : VARIANT_FALSE;
   778     return S_OK;
   779 }
   780 
   781 STDMETHODIMP CpEpEngine::BlacklistRetrieve(SAFEARRAY **blacklist)
   782 {
   783     assert(blacklist);
   784 
   785     if (!blacklist)
   786         return E_INVALIDARG;
   787 
   788     ::stringlist_t *_blacklist = NULL;
   789     PEP_STATUS status = ::blacklist_retrieve(get_session(), &_blacklist);
   790     assert(status == PEP_STATUS_OK);
   791     if (status != PEP_STATUS_OK)
   792         return FAIL(L"blacklist_retrieve failed in pEp engine", status);
   793     assert(_blacklist);
   794 
   795     *blacklist = string_array(_blacklist);
   796     ::free_stringlist(_blacklist);
   797     return S_OK;
   798 }
   799 
   800 HRESULT CpEpEngine::error(_bstr_t msg)
   801 {
   802     _bstr_t helpFile = L"";
   803     _bstr_t source = L"pEp COM Adapter";
   804 
   805     ICreateErrorInfo *cei;
   806     if (SUCCEEDED(CreateErrorInfo(&cei))) {
   807         cei->SetDescription(msg);
   808         cei->SetGUID(__uuidof(IpEpEngine));
   809         cei->SetHelpContext(0);
   810         cei->SetHelpFile(helpFile);
   811         cei->SetSource(source);
   812 
   813         IErrorInfo *errinfo;
   814         if (SUCCEEDED(cei->QueryInterface(IID_IErrorInfo, (LPVOID FAR*) &errinfo))) {
   815             SetErrorInfo(0, errinfo);
   816             errinfo->Release();
   817         }
   818         cei->Release();
   819     }
   820     return E_FAIL;
   821 }
   822 
   823 HRESULT CpEpEngine::error(_bstr_t msg, PEP_STATUS status)
   824 {
   825     std::stringstream stream;
   826     stream << msg;
   827     stream << ": ";
   828     stream << std::hex << status;
   829 
   830     error(stream.str().c_str());
   831 
   832     if (status == ::PEP_OUT_OF_MEMORY)
   833         return E_OUTOFMEMORY;
   834 
   835     return E_FAIL;
   836 }
   837 
   838 STDMETHODIMP CpEpEngine::EncryptMessage(TextMessage * src, TextMessage * dst, SAFEARRAY * extra, pEpEncryptFlags flags)
   839 {
   840     assert(src);
   841     assert(dst);
   842 
   843     if (!(src && dst))
   844         return E_INVALIDARG;
   845 
   846     ::message *_src = text_message_to_C(src);
   847 
   848     // COM-19: Initialize msg_dst to NULL, or we end up calling
   849     // free_message() below with a pointer to random garbage in
   850     // case of an error in encrypt_message().
   851     ::message *msg_dst = NULL;
   852     ::stringlist_t *_extra = new_stringlist(extra); // can cope with NULL
   853 
   854     // _PEP_enc_format is intentionally hardcoded to PEP_enc_PEP:
   855     // 2016-10-02 14:10 < fdik> schabi: actually, all adapters now must use PEP_enc_PEP
   856     PEP_encrypt_flags_t engineFlags = (PEP_encrypt_flags_t)flags;
   857     PEP_STATUS status = ::encrypt_message(get_session(), _src, _extra, &msg_dst, PEP_enc_PEP, engineFlags);
   858     ::free_stringlist(_extra);
   859 
   860     if (status == PEP_STATUS_OK)
   861         text_message_from_C(dst, msg_dst);
   862     else
   863         text_message_from_C(dst, _src);
   864 
   865     ::free_message(msg_dst);
   866     ::free_message(_src);
   867 
   868     if (status == PEP_OUT_OF_MEMORY)
   869         return E_OUTOFMEMORY;
   870 
   871     // COM-41: Enhanced PEP status handling
   872     if ((status != PEP_STATUS_OK) && (status < PEP_UNENCRYPTED || status >= PEP_TRUSTWORD_NOT_FOUND))
   873         return FAIL("Failure to encrypt message", status);
   874 
   875     // Statii like PEP_UNENCRYPTED due to no private key
   876     // should not be a catastrophic failure here. Using S_FALSE
   877     // still allows clients to differentiate with S_OK,
   878     // although this does not work out of the box with
   879     // the standard .NET mapping of COM.
   880     if (status != PEP_STATUS_OK)
   881         return S_FALSE;
   882 
   883     return S_OK;
   884 }
   885 
   886 
   887 STDMETHODIMP CpEpEngine::EncryptMessageForSelf(pEpIdentity * targetId, TextMessage * src, TextMessage * dst, pEpEncryptFlags flags)
   888 {
   889     assert(targetId);
   890     assert(src);
   891     assert(dst);
   892 
   893     if (!(targetId && src && dst))
   894         return E_INVALIDARG;
   895 
   896     PEP_encrypt_flags_t engineFlags = (PEP_encrypt_flags_t)flags;
   897 
   898     ::pEp_identity *_target_id = new_identity(targetId);
   899 
   900     ::message *_src = text_message_to_C(src);
   901 
   902     // COM-19: Initialize msg_dst to NULL, or we end up calling
   903     // free_message() below with a pointer to random garbage in
   904     // case of an error in encrypt_message_for_self().
   905     ::message *msg_dst = NULL;
   906     PEP_STATUS status = ::encrypt_message_for_self(get_session(), _target_id, _src, &msg_dst, PEP_enc_PEP, engineFlags);
   907 
   908     if (status == PEP_STATUS_OK)
   909         text_message_from_C(dst, msg_dst);
   910     else
   911         text_message_from_C(dst, _src);
   912 
   913     ::free_message(msg_dst);
   914     ::free_message(_src);
   915     ::free_identity(_target_id);
   916 
   917     if (status == PEP_OUT_OF_MEMORY)
   918         return E_OUTOFMEMORY;
   919 
   920     // Different to encrypt_message, this should never fail (we ought to always
   921     // have a private key for ourself).#
   922     if (status != PEP_STATUS_OK)
   923         return FAIL("Failure to encrypt message", status);
   924 
   925     return S_OK;
   926 }
   927 
   928 STDMETHODIMP CpEpEngine::DecryptMessage(TextMessage * src, TextMessage * dst, SAFEARRAY ** keylist, pEpDecryptFlags *flags, pEpRating *rating)
   929 {
   930     assert(src);
   931     assert(dst);
   932     assert(keylist);
   933     assert(flags);
   934     assert(rating);
   935 
   936     if (!(src && dst && keylist && flags && rating))
   937         return E_INVALIDARG;
   938 
   939     *keylist = NULL;
   940     *rating = pEpRatingUndefined;
   941 
   942     ::message *_src = text_message_to_C(src);
   943     ::message *msg_dst = NULL;
   944     ::stringlist_t *_keylist = NULL;
   945     ::PEP_rating _rating;
   946 
   947     PEP_decrypt_flags_t engineflags = 0;
   948     PEP_STATUS status = ::decrypt_message(get_session(), _src, &msg_dst, &_keylist, &_rating, &engineflags);
   949 
   950     *flags = (pEpDecryptFlags)engineflags;
   951 
   952     if (msg_dst)
   953         text_message_from_C(dst, msg_dst);
   954 
   955     ::free_message(_src);
   956     ::free_message(msg_dst);
   957 
   958     if (_keylist) {
   959         *keylist = string_array(_keylist);
   960         free_stringlist(_keylist);
   961     }
   962 
   963     *rating = (pEpRating)_rating;
   964 
   965     return S_OK;
   966 }
   967 
   968 STDMETHODIMP CpEpEngine::ReEvaluateMessageRating(TextMessage * msg, SAFEARRAY * x_KeyList, pEpRating x_EncStatus, pEpRating *rating)
   969 {
   970     assert(msg);
   971     assert(x_EncStatus != PEP_rating_undefined);
   972     assert(rating);
   973 
   974     if (!(msg && x_EncStatus != PEP_rating_undefined && rating))
   975         return E_INVALIDARG;
   976 
   977     *rating = pEpRatingUndefined;
   978 
   979     ::message *_msg = text_message_to_C(msg);
   980     ::stringlist_t *_keylist = new_stringlist(x_KeyList);
   981     ::PEP_rating _rating = PEP_rating_undefined;
   982 
   983     PEP_STATUS status = ::re_evaluate_message_rating(get_session(), _msg, _keylist, (PEP_rating)x_EncStatus, &_rating);
   984 
   985     ::free_stringlist(_keylist);
   986     ::free_message(_msg);
   987 
   988     *rating = (pEpRating)_rating;
   989 
   990     return S_OK;
   991 }
   992 
   993 STDMETHODIMP CpEpEngine::OutgoingMessageRating(TextMessage *msg, pEpRating * pVal)
   994 {
   995     assert(msg);
   996     assert(pVal);
   997 
   998     if (!(msg  && pVal))
   999         return E_INVALIDARG;
  1000 
  1001     ::message *_msg = text_message_to_C(msg);
  1002 
  1003     PEP_rating _rating;
  1004     PEP_STATUS status = ::outgoing_message_rating(get_session(), _msg, &_rating);
  1005     if (status != PEP_STATUS_OK)
  1006         return FAIL(L"cannot get message rating", status);
  1007 
  1008     *pVal = (pEpRating)_rating;
  1009     return S_OK;
  1010 }
  1011 
  1012 STDMETHODIMP CpEpEngine::IdentityRating(struct pEpIdentity *ident, pEpRating * pVal)
  1013 {
  1014     ::pEp_identity *_ident;
  1015 
  1016     assert(ident);
  1017     assert(pVal);
  1018 
  1019     if (!(ident  && pVal))
  1020         return E_INVALIDARG;
  1021 
  1022     try {
  1023         _ident = new_identity(ident);
  1024     }
  1025     catch (bad_alloc&) {
  1026         return E_OUTOFMEMORY;
  1027     }
  1028     catch (exception& ex) {
  1029         return FAIL(ex.what());;
  1030     }
  1031 
  1032     PEP_rating _rating;
  1033     PEP_STATUS status = ::identity_rating(get_session(), _ident, &_rating);
  1034     free_identity(_ident);
  1035 
  1036     if (status != PEP_STATUS_OK)
  1037         return FAIL(L"cannot get message color", status);
  1038 
  1039     *pVal = (pEpRating)_rating;
  1040     return S_OK;
  1041 }
  1042 
  1043 STDMETHODIMP CpEpEngine::ColorFromRating(pEpRating rating, pEpColor * pVal)
  1044 {
  1045     assert(pVal);
  1046 
  1047     if (!pVal)
  1048         return E_INVALIDARG;
  1049 
  1050     PEP_rating engineRating = (PEP_rating)rating;
  1051     PEP_color _color = ::color_from_rating(engineRating);
  1052 
  1053     *pVal = (pEpColor)_color;
  1054 
  1055     return S_OK;
  1056 }
  1057 
  1058 STDMETHODIMP CpEpEngine::OwnIdentitiesRetrieve(LPSAFEARRAY* ownIdentities)
  1059 {
  1060     assert(ownIdentities);
  1061     if (!ownIdentities)
  1062         return E_INVALIDARG;
  1063 
  1064     *ownIdentities = nullptr;
  1065 
  1066     ::identity_list *il = nullptr;
  1067     PEP_STATUS status = ::own_identities_retrieve(get_session(), &il);
  1068     if (status == PEP_OUT_OF_MEMORY) {
  1069         return E_OUTOFMEMORY;
  1070     }
  1071     else if (status != PEP_STATUS_OK)
  1072     {
  1073         return FAIL(_T("OwnIdentitiesRetrieve"), status);
  1074     }
  1075 
  1076     SAFEARRAY * _own_identities = nullptr;
  1077     try {
  1078         _own_identities = array_from_C<pEpIdentity, identity_list>(il);
  1079     }
  1080     catch (exception& ex)
  1081     {
  1082         ::free_identity_list(il);
  1083         try {
  1084             dynamic_cast<bad_alloc&>(ex);
  1085         }
  1086         catch (bad_cast&)
  1087         {
  1088             return FAIL(ex.what());
  1089         }
  1090         return E_OUTOFMEMORY;
  1091     }
  1092     free_identity_list(il);
  1093 
  1094     *ownIdentities = _own_identities;
  1095     return S_OK;
  1096 }
  1097 
  1098 STDMETHODIMP CpEpEngine::TrustPersonalKey(struct pEpIdentity *ident, struct pEpIdentity *result)
  1099 {
  1100     ::pEp_identity *_ident;
  1101 
  1102     assert(ident);
  1103     assert(result);
  1104 
  1105     if (!ident || !result)
  1106         return E_INVALIDARG;
  1107 
  1108     try {
  1109         _ident = new_identity(ident);
  1110     }
  1111     catch (bad_alloc&) {
  1112         return E_OUTOFMEMORY;
  1113     }
  1114     catch (exception& ex) {
  1115         return FAIL(ex.what());;
  1116     }
  1117 
  1118     if (verbose_mode) {
  1119         stringstream ss;
  1120         ss << "TrustPersonalKey called with ";
  1121         ss << utf8_string(ident->Address);
  1122         ss << L": ";
  1123         ss << ident->CommType;
  1124         verbose(ss.str());
  1125     }
  1126 
  1127     PEP_STATUS status = ::trust_personal_key(get_session(), _ident);
  1128 
  1129     if (verbose_mode) {
  1130         stringstream ss;
  1131         ss << "result ";
  1132         ss << status;
  1133         ss << " for ";
  1134         ss << _ident->address;
  1135         ss << L": ";
  1136         ss << _ident->comm_type;
  1137         verbose(ss.str());
  1138     }
  1139 
  1140     if (status == PEP_STATUS_OK)
  1141         copy_identity(result, _ident);
  1142 
  1143     free_identity(_ident);
  1144     if (status == PEP_OUT_OF_MEMORY)
  1145         return E_OUTOFMEMORY;
  1146     else if (status != PEP_STATUS_OK)
  1147         return FAIL(L"failure while executing TrustPersonalKey()", status);
  1148 
  1149     return S_OK;
  1150 }
  1151 
  1152 // keysync api
  1153 
  1154 void CpEpEngine::start_keysync()
  1155 {
  1156     // acquire the lock
  1157     std::unique_lock<std::recursive_mutex> lock(keysync_mutex);
  1158 
  1159     // Assert if we're not already running.
  1160     assert(!this->keysync_thread);
  1161 
  1162     // Ensure we are not aborting the new thread due to a
  1163     // left over flag.
  1164     keysync_abort_requested = false;
  1165 
  1166     // Init our keysync session
  1167 	{ // begin lock scope
  1168 		std::lock_guard<std::mutex> lock(init_mutex);
  1169 		PEP_STATUS status = ::init(&keysync_session);
  1170 		::register_sync_callbacks(keysync_session, (void*)this, messageToSend, notifyHandshake, inject_sync_msg, retrieve_next_sync_msg);
  1171 		assert(status == PEP_STATUS_OK);
  1172 	} // end lock scope
  1173 
  1174     attach_sync_session(get_session(), keysync_session);
  1175 
  1176     // We need to marshal the callbacks to the keysync thread
  1177     LPSTREAM marshaled_callbacks;
  1178 
  1179     auto result = CoMarshalInterThreadInterfaceInStream(IID_IpEpEngineCallbacks, client_callbacks, &marshaled_callbacks);
  1180     assert(result == S_OK);
  1181 
  1182     // Star the keysync thread
  1183     keysync_thread = new thread(do_keysync_in_thread, this, marshaled_callbacks);
  1184 }
  1185 
  1186 void CpEpEngine::do_keysync_in_thread(CpEpEngine* self, LPSTREAM marshaled_callbacks)
  1187 {
  1188     assert(self);
  1189     assert(marshaled_callbacks);
  1190 
  1191     // We need to initialize COM here for successfull delivery of the callbacks.
  1192     // As we don't create any COM instances in our thread, the COMINIT value is
  1193     // currently irrelevant, so we go with the safest value.
  1194     auto res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  1195     assert(res == S_OK);
  1196 
  1197     LPVOID vp;
  1198 
  1199     res = CoGetInterfaceAndReleaseStream(marshaled_callbacks, IID_IpEpEngineCallbacks, &vp);
  1200     assert(SUCCEEDED(res));
  1201 
  1202     self->client_last_signalled_polling_state = false;
  1203     self->client_callbacks_on_sync_thread = static_cast<IpEpEngineCallbacks*>(vp);
  1204 
  1205     res = self->client_callbacks_on_sync_thread->QueryInterface(
  1206         &self->client_callbacks2_on_sync_thread);
  1207     if (res != S_OK)
  1208         self->client_callbacks2_on_sync_thread = NULL;
  1209 
  1210     ::do_sync_protocol(self->keysync_session, self);
  1211 
  1212     self->client_callbacks_on_sync_thread->Release();
  1213 
  1214     self->client_callbacks_on_sync_thread = NULL;
  1215 
  1216     if (self->client_callbacks2_on_sync_thread)
  1217         self->client_callbacks2_on_sync_thread->Release();
  1218     self->client_callbacks2_on_sync_thread = NULL;
  1219 
  1220     CoUninitialize();
  1221 }
  1222 
  1223 void CpEpEngine::stop_keysync()
  1224 {
  1225     // acquire the lock
  1226     std::unique_lock<std::recursive_mutex> lock(keysync_mutex);
  1227 
  1228     // Do nothing if keysync is not running.
  1229     if (!keysync_thread)
  1230         return;
  1231 
  1232     assert(!keysync_abort_requested);
  1233     // signal that we're gonna abort
  1234     keysync_abort_requested = true;
  1235 
  1236     // Notify the keysync thread
  1237     keysync_condition.notify_all();
  1238 
  1239     // Wait for the other thread to finish and clean up
  1240     while (keysync_abort_requested)
  1241         keysync_condition.wait(lock);
  1242 
  1243     // collect the child thread for the thread to end
  1244     keysync_thread->join();
  1245 
  1246     // clean up
  1247     delete keysync_thread;
  1248     keysync_thread = NULL;
  1249 
  1250     ::detach_sync_session(get_session());
  1251     ::unregister_sync_callbacks(keysync_session);
  1252 
  1253 	std::lock_guard<std::mutex> releaselock(init_mutex);
  1254     release(keysync_session);
  1255     keysync_session = NULL;
  1256 }
  1257 
  1258 int CpEpEngine::inject_sync_msg(void * msg, void * management)
  1259 {
  1260     assert(msg);
  1261     assert(management);
  1262     // check argument
  1263     if (!msg)
  1264         return E_INVALIDARG;
  1265     if (!management)
  1266         return ERROR_INVALID_HANDLE;
  1267 
  1268     CpEpEngine* me = (CpEpEngine*)management;
  1269 
  1270     // acquire the lock
  1271     std::unique_lock<std::recursive_mutex> lock(me->keysync_mutex);
  1272 
  1273     // check whether we're in a valid state running:
  1274     if (!me->keysync_thread)
  1275         return E_ASYNC_OPERATION_NOT_STARTED;
  1276 
  1277     // queue the message
  1278     me->keysync_queue.push(msg);
  1279 
  1280     // notify the receivers
  1281     me->keysync_condition.notify_all();
  1282 
  1283     return S_OK;
  1284 }
  1285 
  1286 void * CpEpEngine::retrieve_next_sync_msg(void * management, time_t *timeout)
  1287 {
  1288     // sanity check
  1289     assert(management);
  1290     if (!(management))
  1291         return NULL;
  1292 
  1293     CpEpEngine* me = (CpEpEngine*)management;
  1294 
  1295     if ((timeout && *timeout)
  1296         && me->client_callbacks2_on_sync_thread
  1297         && me->client_last_signalled_polling_state == false)
  1298     {
  1299         me->client_callbacks2_on_sync_thread->NeedFastPolling(VARIANT_TRUE);
  1300         me->client_last_signalled_polling_state = true;
  1301     }
  1302     else if (!(timeout && *timeout)
  1303         && me->client_callbacks2_on_sync_thread
  1304         && me->client_last_signalled_polling_state == true)
  1305     {
  1306         me->client_callbacks2_on_sync_thread->NeedFastPolling(VARIANT_FALSE);
  1307         me->client_last_signalled_polling_state = false;
  1308     }
  1309 
  1310     // acquire the lock
  1311     std::unique_lock<std::recursive_mutex> lock(me->keysync_mutex);
  1312 
  1313     if (me->notify_handshake_finished)
  1314         me->notify_handshake_deliver_result();
  1315 
  1316     if (timeout && *timeout) {
  1317         std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now()
  1318             + std::chrono::seconds(*timeout);
  1319 
  1320         while (me->keysync_queue.empty() && !me->keysync_abort_requested)
  1321         {
  1322             auto status = me->keysync_condition.wait_until(lock, end_time);
  1323 
  1324             if (me->notify_handshake_finished)
  1325                 me->notify_handshake_deliver_result();
  1326 
  1327             if (status == std::cv_status::timeout)
  1328             {
  1329                 *timeout = 1; // Signal timeout
  1330                 return NULL;
  1331             } 
  1332             else 
  1333             {
  1334                 std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
  1335 
  1336                 if (now < end_time) 
  1337                 {
  1338                     *timeout = std::chrono::duration_cast<std::chrono::seconds>(end_time - now).count();
  1339                 } 
  1340                 else 
  1341                 {
  1342                     *timeout = 0;
  1343                 }
  1344             }
  1345         }
  1346     }
  1347     else
  1348     {
  1349         while (me->keysync_queue.empty() && !me->keysync_abort_requested)
  1350         {
  1351             me->keysync_condition.wait(lock);
  1352 
  1353             if (me->notify_handshake_finished)
  1354                 me->notify_handshake_deliver_result();
  1355         }
  1356     }
  1357 
  1358     if (me->keysync_abort_requested) {
  1359         // we acknowledge that we're quitting...
  1360         me->keysync_abort_requested = false;
  1361 
  1362         // We signal the main thread that we got his signal
  1363         // so it can gain the mutex again and call join() on us.
  1364         me->keysync_condition.notify_all();
  1365 
  1366         // and tell the pep engine we're done.
  1367         if (timeout)
  1368             *timeout = 0; // signal for termination.
  1369         return NULL;
  1370     }
  1371 
  1372     assert(!me->keysync_queue.empty());
  1373 
  1374     // Pop the message and return it.
  1375     void* msg = me->keysync_queue.front();
  1376     assert(msg);
  1377 
  1378     me->keysync_queue.pop();
  1379 
  1380     return msg;
  1381 }
  1382 
  1383 
  1384 // Event callbacks
  1385 
  1386 STDMETHODIMP CpEpEngine::RegisterCallbacks(IpEpEngineCallbacks* new_callbacks)
  1387 {
  1388     // check for valid parameter
  1389     if (!new_callbacks)
  1390         return E_INVALIDARG;
  1391 
  1392     // don't allow double registration.
  1393     if (this->client_callbacks)
  1394         return E_ILLEGAL_STATE_CHANGE;
  1395 
  1396     this->client_callbacks = new_callbacks;
  1397     new_callbacks->AddRef();
  1398 
  1399     start_keysync();
  1400 
  1401     return S_OK;
  1402 }
  1403 
  1404 STDMETHODIMP CpEpEngine::UnregisterCallbacks()
  1405 {
  1406     // don't allow double deregistration.
  1407     // S_FALSE still is no error (as double deregistration is not fatal).
  1408     if (!this->client_callbacks)
  1409         return S_FALSE;
  1410 
  1411     stop_keysync();
  1412 
  1413     this->client_callbacks->Release();
  1414 
  1415     this->client_callbacks = NULL;
  1416 
  1417     return S_OK;
  1418 }
  1419 
  1420 STDMETHODIMP CpEpEngine::OpenPGPListKeyinfo(BSTR search_pattern, LPSAFEARRAY* keyinfo_list) {
  1421     assert(keyinfo_list);
  1422 
  1423     if (keyinfo_list == NULL)
  1424         return E_INVALIDARG;
  1425 
  1426     string _pattern = "";
  1427     if (search_pattern)
  1428         _pattern = utf8_string(search_pattern);
  1429     ::stringpair_list_t* _keyinfo_list = NULL;
  1430 
  1431     PEP_STATUS status = ::OpenPGP_list_keyinfo(get_session(), _pattern.c_str(), &_keyinfo_list);
  1432     assert(status != PEP_OUT_OF_MEMORY);
  1433     if (status == PEP_OUT_OF_MEMORY)
  1434         return E_OUTOFMEMORY;
  1435 
  1436     if (status != ::PEP_STATUS_OK)
  1437         return FAIL(L"OpenPGP_list_keyinfo", status);
  1438 
  1439     if (_keyinfo_list && _keyinfo_list->value) {
  1440         ::opt_field_array_from_C(_keyinfo_list, keyinfo_list);
  1441     }
  1442     else {
  1443         ::free_stringpair_list(_keyinfo_list);
  1444         return FAIL(L"OpenPGP_list_keyinfo: no keys found");
  1445     }
  1446 
  1447     ::free_stringpair_list(_keyinfo_list);
  1448     return S_OK;
  1449 
  1450 }
  1451 
  1452 HRESULT CpEpEngine::Fire_MessageToSend(TextMessage * msg)
  1453 {
  1454     assert(msg);
  1455     assert(this->client_callbacks_on_sync_thread);
  1456 
  1457     if (!msg)
  1458         return E_INVALIDARG;
  1459 
  1460     if (!this->client_callbacks_on_sync_thread)
  1461         return E_ILLEGAL_METHOD_CALL;
  1462 
  1463     auto result = this->client_callbacks_on_sync_thread->MessageToSend(msg);
  1464 
  1465     return result;
  1466 }
  1467 
  1468 // This method is called from the keysync thread, and dispatches
  1469 // the handshake asynchroneously to a background thread,
  1470 // so the engine can continue working.
  1471 PEP_STATUS CpEpEngine::notifyHandshake(void * obj, pEp_identity *self, pEp_identity *partner, sync_handshake_signal signal)
  1472 {
  1473     assert(self && partner);
  1474     if (!(self && partner))
  1475         return PEP_ILLEGAL_VALUE;
  1476 
  1477     CpEpEngine *me = (CpEpEngine *)obj;
  1478 
  1479     if (me->notify_handshake_active) {
  1480         // We don't support concurrent handshakes currently, 
  1481         // with the exception of an abort of the handshake, 
  1482         // which we deliver synchroneously (as it's non-blocking).
  1483         if (signal == SYNC_NOTIFY_TIMEOUT) {
  1484             pEpIdentity timeout_self;
  1485             pEpIdentity timeout_partner;
  1486             SyncHandshakeSignal timeout_signal = (SyncHandshakeSignal)signal;
  1487             copy_identity(&timeout_self, self);
  1488             copy_identity(&timeout_partner, partner);
  1489             SyncHandshakeResult result;
  1490             auto res = me->client_callbacks_on_sync_thread->NotifyHandshake(&timeout_self, &timeout_partner, timeout_signal, &result);
  1491 
  1492             clear_identity_s(timeout_self);
  1493             clear_identity_s(timeout_partner);
  1494 
  1495             if (FAILED(res)) {
  1496                 IErrorInfo* errorInfo = NULL;
  1497                 if (FAILED(GetErrorInfo(0, &errorInfo)))
  1498                     errorInfo = NULL;
  1499 
  1500                 // The _com_error takes ownership of the errorInfo
  1501                 // and will Release() it. It can also cope with
  1502                 // NULL errorInfos.
  1503                 _com_error error(res, errorInfo);
  1504 
  1505                 string _description = utf8_string(
  1506                     error.ErrorMessage());
  1507 
  1508                 string _comment = utf8_string(error.Description());
  1509 
  1510                 auto source = error.Source();
  1511                 if (source.length() > 0) {
  1512                     _comment += "\r\nSource: ";
  1513                     _comment += utf8_string(source);
  1514                 }
  1515 
  1516                 ::log_event(me->keysync_session,
  1517                     "Error on NotifyHandshakeTimeout",
  1518                     "pEp COM Adapter",
  1519                     _description.c_str(),
  1520                     _comment.c_str());
  1521 
  1522                 return PEP_UNKNOWN_ERROR;
  1523             }
  1524 
  1525             if (res != S_OK)
  1526 
  1527             return PEP_STATUS_OK;
  1528         }
  1529 
  1530         ::log_event(me->keysync_session, "Reentrant notify_handshake call!", "pEp COM Adapter", NULL, NULL);
  1531         return PEP_UNKNOWN_ERROR;
  1532     }
  1533 
  1534     assert(!(me->notify_handshake_active
  1535         || me->notify_handshake_finished
  1536         || me->notify_handshake_thread));
  1537 
  1538     me->notify_handshake_active = true;
  1539 
  1540     copy_identity(&me->notify_handshake_self, self);
  1541     copy_identity(&me->notify_handshake_partner, partner);
  1542     me->notify_handshake_signal = (SyncHandshakeSignal)signal;
  1543 
  1544     // We need to marshal the callbacks to the keysync thread
  1545     LPSTREAM marshaled_callbacks;
  1546 
  1547     auto result = CoMarshalInterThreadInterfaceInStream(IID_IpEpEngineCallbacks, me->client_callbacks_on_sync_thread, &marshaled_callbacks);
  1548     assert(result == S_OK);
  1549 
  1550     me->notify_handshake_thread = new thread(notify_handshake_background_thread, me, marshaled_callbacks);
  1551 
  1552     return PEP_STATUS_OK;
  1553 }
  1554 
  1555 // This method also runs in the keysync thread, called by
  1556 // retrieve_next_sync_msg() to deliver back the results
  1557 // of the sync into the engine.
  1558 void CpEpEngine::notify_handshake_deliver_result()
  1559 {
  1560     assert(notify_handshake_active
  1561         && notify_handshake_finished);
  1562     if (!(notify_handshake_active
  1563         && notify_handshake_finished))
  1564         return;
  1565 
  1566     notify_handshake_thread->join();
  1567     notify_handshake_thread = NULL;
  1568 
  1569     Identity partner = new_identity(&notify_handshake_partner);
  1570 
  1571     if (FAILED(notify_handshake_error))
  1572     {
  1573         IErrorInfo *errorInfo = NULL;
  1574 
  1575         if (notify_handshake_error_info) {
  1576             LPVOID lp = NULL;
  1577             auto res = CoGetInterfaceAndReleaseStream(notify_handshake_error_info, IID_IErrorInfo, &lp);
  1578 
  1579             if (SUCCEEDED(res) && lp)
  1580                 errorInfo = static_cast<IErrorInfo*>(lp);
  1581         }
  1582 
  1583         // The _com_error takes ownership of the errorInfo
  1584         // and will Release() it. It can also cope with
  1585         // NULL errorInfos.
  1586         _com_error error(notify_handshake_error, errorInfo);
  1587 
  1588         string _description = utf8_string(
  1589             error.ErrorMessage());
  1590 
  1591         string _comment = utf8_string(error.Description());
  1592 
  1593         auto source = error.Source();
  1594         if (source.length() > 0) {
  1595             _comment += "\r\nSource: ";
  1596             _comment += utf8_string(source);
  1597         }
  1598 
  1599         ::log_event(keysync_session,
  1600             "Notify Handshake Failed!",
  1601             "pEp COM Adapter",
  1602             _description.c_str(),
  1603             _comment.c_str());
  1604 
  1605         ::deliverHandshakeResult(keysync_session, partner, SYNC_HANDSHAKE_CANCEL);
  1606     }
  1607     else {
  1608         ::deliverHandshakeResult(
  1609             keysync_session,
  1610             partner,
  1611             (sync_handshake_result)notify_handshake_result);
  1612     }
  1613     notify_handshake_error_info = NULL;
  1614 
  1615     clear_identity_s(notify_handshake_self);
  1616     clear_identity_s(notify_handshake_partner);
  1617     notify_handshake_active = false;
  1618     notify_handshake_finished = false;
  1619 }
  1620 
  1621 // Method on the background thread, calling into Outlook to
  1622 // trigger the Handshake notification, and then scheduling
  1623 // the result back to the main thread.
  1624 void CpEpEngine::notify_handshake_background_thread(CpEpEngine* self, LPSTREAM marshaled_callbacks)
  1625 {
  1626     assert(self);
  1627 
  1628     // We need to initialize COM here for successfull delivery of the callbacks.
  1629     // As we don't create any COM instances in our thread, the COMINIT value is
  1630     // currently irrelevant, so we go with the safest value.
  1631     auto res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  1632     assert(res == S_OK);
  1633 
  1634     LPVOID vp;
  1635 
  1636     res = CoGetInterfaceAndReleaseStream(marshaled_callbacks, IID_IpEpEngineCallbacks, &vp);
  1637     assert(SUCCEEDED(res));
  1638 
  1639     auto client_callbacks_on_sync_thread = static_cast<IpEpEngineCallbacks*>(vp);
  1640 
  1641     self->notify_handshake_error = client_callbacks_on_sync_thread->NotifyHandshake(
  1642         &self->notify_handshake_self,
  1643         &self->notify_handshake_partner,
  1644         self->notify_handshake_signal,
  1645         &self->notify_handshake_result);
  1646 
  1647     if (FAILED(self->notify_handshake_error)) {
  1648         IErrorInfo* errorInfo = NULL;
  1649 
  1650         res = GetErrorInfo(0, &errorInfo);
  1651 
  1652         if (res = S_OK && errorInfo != NULL) {
  1653             res = CoMarshalInterThreadInterfaceInStream(
  1654                 IID_IErrorInfo,
  1655                 errorInfo,
  1656                 &self->notify_handshake_error_info);
  1657 
  1658             errorInfo->Release();
  1659         }
  1660     }
  1661 
  1662     // notify the keysync thread.
  1663     self->notify_handshake_finished = true;
  1664     self->keysync_condition.notify_all();
  1665 }