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