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