CpEpEngine.cpp
author Markus Schaber <markus@pep-security.net>
Thu, 01 Feb 2018 23:30:55 +0100
changeset 268 4d41410af9a0
parent 264 aa6bd84bd6c3
child 269 26c8597fe860
permissions -rw-r--r--
COM-49: When system.db is missing, adapter keeps restaring in a loop with no error message.

- Move most initialization work from constructor to FinalConstruct(), where
we can (at least) return an error code.

- Fix null dereference crashes in destructor when FinalConstruct() failed.

- Generally preserve the PEP_STATUS via FACILITY_ITF HRESULTs (except OOM,
which results in an OutOfMemoryException via E_OUTOFMEMORY).

- Add pEpStatus enum to IDL file, so the client can (potentially) use it to make
more sense out of the HRESULTs.
     1 // CpEpEngine.cpp : Implementation of CpEpEngine
     2 
     3 #include "stdafx.h"
     4 #include "CpEpEngine.h"
     5 #include <mutex>
     6 
     7 using namespace std;
     8 using namespace pEp::utility;
     9 
    10 // CpEpEngine
    11 
    12 // the init_mutex protects our initialization and destruction
    13 // against a running keysync thread, and it ensures that the
    14 // keysync thread actually has finished before we're destructed.
    15 std::mutex CpEpEngine::init_mutex;
    16 
    17 STDMETHODIMP CpEpEngine::InterfaceSupportsErrorInfo(REFIID riid)
    18 {
    19     static const IID* const arr[] =
    20     {
    21         &IID_IpEpEngine,
    22         &IID_IpEpEngine2,
    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         assert(_ident->fpr); // Guaranteed not NULL, but possibly empty string.
   556         copy_identity(result, _ident);
   557         ::free_identity(_ident);
   558         return S_OK;
   559     }
   560     else if (status == PEP_GET_KEY_FAILED) {
   561         if (_ident->fpr) {
   562             pEp_free(_ident->fpr);
   563             _ident->fpr = NULL;
   564         }
   565         copy_identity(result, _ident);
   566         result->Fpr = NULL;
   567         ::free_identity(_ident);
   568         return S_OK;
   569     }
   570     else {
   571         ::free_identity(_ident);
   572         if (status == PEP_OUT_OF_MEMORY)
   573             return E_OUTOFMEMORY;
   574         else
   575             return FAIL(L"UpdateIdentity", status);
   576     }
   577 }
   578 
   579 STDMETHODIMP CpEpEngine::KeyMistrusted(struct pEpIdentity *ident)
   580 {
   581     ::pEp_identity *_ident;
   582 
   583     assert(ident);
   584     if (!ident)
   585         return E_INVALIDARG;
   586 
   587     try {
   588         _ident = new_identity(ident);
   589     }
   590     catch (bad_alloc&) {
   591         return E_OUTOFMEMORY;
   592     }
   593     catch (exception& ex) {
   594         return FAIL(ex.what());;
   595     }
   596 
   597     PEP_STATUS status = ::key_mistrusted(get_session(), _ident);
   598     free_identity(_ident);
   599 
   600     if (status == PEP_OUT_OF_MEMORY)
   601         return E_OUTOFMEMORY;
   602 
   603     if (status == PEP_KEY_NOT_FOUND)
   604         return FAIL(L"key not found");
   605 
   606     if (status != ::PEP_STATUS_OK)
   607         return FAIL(L"cannot revoke compromized key", status);
   608 
   609     return S_OK;
   610 }
   611 
   612 STDMETHODIMP CpEpEngine::UndoLastMistrust()
   613 {
   614 	PEP_STATUS status = ::undo_last_mistrust(get_session());
   615 
   616 	if (status == PEP_CANNOT_FIND_IDENTITY)
   617 		return FAIL(L"Cannot find identity!", status);
   618 
   619 	if (status != ::PEP_STATUS_OK)
   620 		return FAIL(L"cannot revoke compromized key", status);
   621 
   622 	return S_OK;
   623 }
   624 
   625 STDMETHODIMP CpEpEngine::KeyResetTrust(struct pEpIdentity *ident)
   626 {
   627     ::pEp_identity *_ident;
   628 
   629     assert(ident);
   630 
   631     if (!ident)
   632         return E_INVALIDARG;
   633 
   634     try {
   635         _ident = new_identity(ident);
   636     }
   637     catch (bad_alloc&) {
   638         return E_OUTOFMEMORY;
   639     }
   640     catch (exception& ex) {
   641         return FAIL(ex.what());;
   642     }
   643 
   644     PEP_STATUS status = ::key_reset_trust(get_session(), _ident);
   645     free_identity(_ident);
   646 
   647     if (status == PEP_OUT_OF_MEMORY)
   648         return E_OUTOFMEMORY;
   649 
   650     if (status == PEP_KEY_NOT_FOUND)
   651         return FAIL(L"key not found");
   652 
   653     if (status != ::PEP_STATUS_OK)
   654         return FAIL(L"cannot reset trust", status);
   655 
   656     return S_OK;
   657 }
   658 
   659 int CpEpEngine::examine_identity(pEp_identity *ident, void *management)
   660 {
   661     assert(ident);
   662     assert(management);
   663     if (!(ident && management))
   664         return -1;
   665 
   666     CpEpEngine *me = (CpEpEngine *)management;
   667 
   668     if (me->identity_queue.load() == NULL)
   669         return 0;
   670 
   671     try {
   672         me->identity_queue.load()->push_back(ident);
   673     }
   674     catch (exception&) {
   675         return -1;
   676     }
   677 
   678     return 0;
   679 }
   680 
   681 ::pEp_identity * CpEpEngine::retrieve_next_identity(void *management)
   682 {
   683     assert(management);
   684     if (!management)
   685         return NULL;
   686 
   687     identity_queue_t *iq = (identity_queue_t *)management;
   688 
   689     do /* poll queue */ {
   690         if (iq->size())
   691             break;
   692         ::Sleep(100);
   693     } while (true);
   694 
   695     ::pEp_identity *_ident;
   696     pEp_identity_cpp& ident = iq->front();
   697 
   698     if (ident.address.size() == 0)
   699         return NULL;
   700 
   701     _ident = ident.to_pEp_identity();
   702     iq->pop_front();
   703 
   704     return _ident;
   705 }
   706 
   707 PEP_STATUS CpEpEngine::messageToSend(void * obj, message *msg)
   708 {
   709     assert(msg);
   710     assert(obj);
   711     if (!(msg && obj))
   712         return PEP_ILLEGAL_VALUE;
   713 
   714     TextMessage _msg;
   715     memset(&_msg, 0, sizeof(TextMessage));
   716 
   717     text_message_from_C(&_msg, msg);
   718     CpEpEngine *me = (CpEpEngine *)obj;
   719     HRESULT r = me->Fire_MessageToSend(&_msg);
   720     assert(r == S_OK);
   721     clear_text_message(&_msg);
   722     if (r == E_OUTOFMEMORY)
   723         return PEP_OUT_OF_MEMORY;
   724     if (r != S_OK)
   725         return PEP_UNKNOWN_ERROR;
   726 
   727     return PEP_STATUS_OK;
   728 }
   729 
   730 STDMETHODIMP CpEpEngine::BlacklistAdd(BSTR fpr)
   731 {
   732     assert(fpr);
   733     if (!fpr)
   734         return E_INVALIDARG;
   735 
   736     string _fpr = utf8_string(fpr);
   737     PEP_STATUS status = ::blacklist_add(get_session(), _fpr.c_str());
   738     assert(status == PEP_STATUS_OK);
   739     if (status != PEP_STATUS_OK)
   740         return FAIL(L"blacklist_add failed in pEp engine", status);
   741 
   742     return S_OK;
   743 }
   744 
   745 STDMETHODIMP CpEpEngine::BlacklistDelete(BSTR fpr)
   746 {
   747     assert(fpr);
   748     if (!fpr)
   749         return E_INVALIDARG;
   750 
   751     string _fpr = utf8_string(fpr);
   752     PEP_STATUS status = ::blacklist_delete(get_session(), _fpr.c_str());
   753     assert(status == PEP_STATUS_OK);
   754     if (status != PEP_STATUS_OK)
   755         return FAIL(L"blacklist_delete failed in pEp engine", status);
   756 
   757     return S_OK;
   758 }
   759 
   760 STDMETHODIMP CpEpEngine::BlacklistIsListed(BSTR fpr, VARIANT_BOOL *listed)
   761 {
   762     assert(fpr);
   763     assert(listed);
   764 
   765     if (!(fpr && listed))
   766         return E_INVALIDARG;
   767 
   768     string _fpr = utf8_string(fpr);
   769     bool result;
   770     PEP_STATUS status = ::blacklist_is_listed(get_session(), _fpr.c_str(), &result);
   771     assert(status == PEP_STATUS_OK);
   772     if (status != PEP_STATUS_OK)
   773         return FAIL(L"blacklist_is_listed failed in pEp engine", status);
   774 
   775     *listed = result ? VARIANT_TRUE : VARIANT_FALSE;
   776     return S_OK;
   777 }
   778 
   779 STDMETHODIMP CpEpEngine::BlacklistRetrieve(SAFEARRAY **blacklist)
   780 {
   781     assert(blacklist);
   782 
   783     if (!blacklist)
   784         return E_INVALIDARG;
   785 
   786     ::stringlist_t *_blacklist = NULL;
   787     PEP_STATUS status = ::blacklist_retrieve(get_session(), &_blacklist);
   788     assert(status == PEP_STATUS_OK);
   789     if (status != PEP_STATUS_OK)
   790         return FAIL(L"blacklist_retrieve failed in pEp engine", status);
   791     assert(_blacklist);
   792 
   793     *blacklist = string_array(_blacklist);
   794     ::free_stringlist(_blacklist);
   795     return S_OK;
   796 }
   797 
   798 HRESULT CpEpEngine::error(_bstr_t msg)
   799 {
   800     _bstr_t helpFile = L"";
   801     _bstr_t source = L"pEp COM Adapter";
   802 
   803     ICreateErrorInfo *cei;
   804     if (SUCCEEDED(CreateErrorInfo(&cei))) {
   805         cei->SetDescription(msg);
   806         cei->SetGUID(__uuidof(IpEpEngine));
   807         cei->SetHelpContext(0);
   808         cei->SetHelpFile(helpFile);
   809         cei->SetSource(source);
   810 
   811         IErrorInfo *errinfo;
   812         if (SUCCEEDED(cei->QueryInterface(IID_IErrorInfo, (LPVOID FAR*) &errinfo))) {
   813             SetErrorInfo(0, errinfo);
   814             errinfo->Release();
   815         }
   816         cei->Release();
   817     }
   818     return E_FAIL;
   819 }
   820 
   821 HRESULT CpEpEngine::error(_bstr_t msg, PEP_STATUS status)
   822 {
   823     std::stringstream stream;
   824     stream << msg;
   825     stream << ": ";
   826     stream << std::hex << status;
   827 
   828     error(stream.str().c_str());
   829 
   830     if (status == ::PEP_OUT_OF_MEMORY)
   831         return E_OUTOFMEMORY;
   832 
   833     return MAKE_HRESULT(1, FACILITY_ITF, (0xFFFF & status));
   834 }
   835 
   836 STDMETHODIMP CpEpEngine::EncryptMessage(TextMessage * src, TextMessage * dst, SAFEARRAY * extra, pEpEncryptFlags flags)
   837 {
   838     assert(src);
   839     assert(dst);
   840 
   841     if (!(src && dst))
   842         return E_INVALIDARG;
   843 
   844     ::message *_src = text_message_to_C(src);
   845 
   846     // COM-19: Initialize msg_dst to NULL, or we end up calling
   847     // free_message() below with a pointer to random garbage in
   848     // case of an error in encrypt_message().
   849     ::message *msg_dst = NULL;
   850     ::stringlist_t *_extra = new_stringlist(extra); // can cope with NULL
   851 
   852     // _PEP_enc_format is intentionally hardcoded to PEP_enc_PEP:
   853     // 2016-10-02 14:10 < fdik> schabi: actually, all adapters now must use PEP_enc_PEP
   854     PEP_encrypt_flags_t engineFlags = (PEP_encrypt_flags_t)flags;
   855     PEP_STATUS status = ::encrypt_message(get_session(), _src, _extra, &msg_dst, PEP_enc_PEP, engineFlags);
   856     ::free_stringlist(_extra);
   857 
   858     if (status == PEP_STATUS_OK)
   859         text_message_from_C(dst, msg_dst);
   860     else
   861         text_message_from_C(dst, _src);
   862 
   863     ::free_message(msg_dst);
   864     ::free_message(_src);
   865 
   866     if (status == PEP_OUT_OF_MEMORY)
   867         return E_OUTOFMEMORY;
   868 
   869     // COM-41: Enhanced PEP status handling
   870     if ((status != PEP_STATUS_OK) && (status < PEP_UNENCRYPTED || status >= PEP_TRUSTWORD_NOT_FOUND))
   871         return FAIL("Failure to encrypt message", status);
   872 
   873     // Statii like PEP_UNENCRYPTED due to no private key
   874     // should not be a catastrophic failure here. Using S_FALSE
   875     // still allows clients to differentiate with S_OK,
   876     // although this does not work out of the box with
   877     // the standard .NET mapping of COM.
   878     if (status != PEP_STATUS_OK)
   879         return S_FALSE;
   880 
   881     return S_OK;
   882 }
   883 
   884 
   885 STDMETHODIMP CpEpEngine::EncryptMessageForSelf(pEpIdentity * targetId, TextMessage * src, TextMessage * dst, pEpEncryptFlags flags)
   886 {
   887     assert(targetId);
   888     assert(src);
   889     assert(dst);
   890 
   891     if (!(targetId && src && dst))
   892         return E_INVALIDARG;
   893 
   894     PEP_encrypt_flags_t engineFlags = (PEP_encrypt_flags_t)flags;
   895 
   896     ::pEp_identity *_target_id = new_identity(targetId);
   897 
   898     ::message *_src = text_message_to_C(src);
   899 
   900     // COM-19: Initialize msg_dst to NULL, or we end up calling
   901     // free_message() below with a pointer to random garbage in
   902     // case of an error in encrypt_message_for_self().
   903     ::message *msg_dst = NULL;
   904     PEP_STATUS status = ::encrypt_message_for_self(get_session(), _target_id, _src, &msg_dst, PEP_enc_PEP, engineFlags);
   905 
   906     if (status == PEP_STATUS_OK)
   907         text_message_from_C(dst, msg_dst);
   908     else
   909         text_message_from_C(dst, _src);
   910 
   911     ::free_message(msg_dst);
   912     ::free_message(_src);
   913     ::free_identity(_target_id);
   914 
   915     if (status == PEP_OUT_OF_MEMORY)
   916         return E_OUTOFMEMORY;
   917 
   918     // Different to encrypt_message, this should never fail (we ought to always
   919     // have a private key for ourself).#
   920     if (status != PEP_STATUS_OK)
   921         return FAIL("Failure to encrypt message", status);
   922 
   923     return S_OK;
   924 }
   925 
   926 STDMETHODIMP CpEpEngine::DecryptMessage(TextMessage * src, TextMessage * dst, SAFEARRAY ** keylist, pEpDecryptFlags *flags, pEpRating *rating)
   927 {
   928     assert(src);
   929     assert(dst);
   930     assert(keylist);
   931     assert(flags);
   932     assert(rating);
   933 
   934     if (!(src && dst && keylist && flags && rating))
   935         return E_INVALIDARG;
   936 
   937     *keylist = NULL;
   938     *rating = pEpRatingUndefined;
   939 
   940     ::message *_src = text_message_to_C(src);
   941     ::message *msg_dst = NULL;
   942     ::stringlist_t *_keylist = NULL;
   943     ::PEP_rating _rating;
   944 
   945     PEP_decrypt_flags_t engineflags = 0;
   946     PEP_STATUS status = ::decrypt_message(get_session(), _src, &msg_dst, &_keylist, &_rating, &engineflags);
   947 
   948     *flags = (pEpDecryptFlags)engineflags;
   949 
   950     if (msg_dst)
   951         text_message_from_C(dst, msg_dst);
   952 
   953     ::free_message(_src);
   954     ::free_message(msg_dst);
   955 
   956     if (_keylist) {
   957         *keylist = string_array(_keylist);
   958         free_stringlist(_keylist);
   959     }
   960 
   961     *rating = (pEpRating)_rating;
   962 
   963     return S_OK;
   964 }
   965 
   966 STDMETHODIMP CpEpEngine::ReEvaluateMessageRating(TextMessage * msg, SAFEARRAY * x_KeyList, pEpRating x_EncStatus, pEpRating *rating)
   967 {
   968     assert(msg);
   969     assert(x_EncStatus != PEP_rating_undefined);
   970     assert(rating);
   971 
   972     if (!(msg && x_EncStatus != PEP_rating_undefined && rating))
   973         return E_INVALIDARG;
   974 
   975     *rating = pEpRatingUndefined;
   976 
   977     ::message *_msg = text_message_to_C(msg);
   978     ::stringlist_t *_keylist = new_stringlist(x_KeyList);
   979     ::PEP_rating _rating = PEP_rating_undefined;
   980 
   981     PEP_STATUS status = ::re_evaluate_message_rating(get_session(), _msg, _keylist, (PEP_rating)x_EncStatus, &_rating);
   982 
   983     ::free_stringlist(_keylist);
   984     ::free_message(_msg);
   985 
   986     *rating = (pEpRating)_rating;
   987 
   988     return S_OK;
   989 }
   990 
   991 STDMETHODIMP CpEpEngine::OutgoingMessageRating(TextMessage *msg, pEpRating * pVal)
   992 {
   993     assert(msg);
   994     assert(pVal);
   995 
   996     if (!(msg  && pVal))
   997         return E_INVALIDARG;
   998 
   999     ::message *_msg = text_message_to_C(msg);
  1000 
  1001     PEP_rating _rating;
  1002     PEP_STATUS status = ::outgoing_message_rating(get_session(), _msg, &_rating);
  1003     if (status != PEP_STATUS_OK)
  1004         return FAIL(L"cannot get message rating", status);
  1005 
  1006     *pVal = (pEpRating)_rating;
  1007     return S_OK;
  1008 }
  1009 
  1010 STDMETHODIMP CpEpEngine::IdentityRating(struct pEpIdentity *ident, pEpRating * pVal)
  1011 {
  1012     ::pEp_identity *_ident;
  1013 
  1014     assert(ident);
  1015     assert(pVal);
  1016 
  1017     if (!(ident  && pVal))
  1018         return E_INVALIDARG;
  1019 
  1020     try {
  1021         _ident = new_identity(ident);
  1022     }
  1023     catch (bad_alloc&) {
  1024         return E_OUTOFMEMORY;
  1025     }
  1026     catch (exception& ex) {
  1027         return FAIL(ex.what());;
  1028     }
  1029 
  1030     PEP_rating _rating;
  1031     PEP_STATUS status = ::identity_rating(get_session(), _ident, &_rating);
  1032     free_identity(_ident);
  1033 
  1034     if (status != PEP_STATUS_OK)
  1035         return FAIL(L"cannot get message color", status);
  1036 
  1037     *pVal = (pEpRating)_rating;
  1038     return S_OK;
  1039 }
  1040 
  1041 STDMETHODIMP CpEpEngine::ColorFromRating(pEpRating rating, pEpColor * pVal)
  1042 {
  1043     assert(pVal);
  1044 
  1045     if (!pVal)
  1046         return E_INVALIDARG;
  1047 
  1048     PEP_rating engineRating = (PEP_rating)rating;
  1049     PEP_color _color = ::color_from_rating(engineRating);
  1050 
  1051     *pVal = (pEpColor)_color;
  1052 
  1053     return S_OK;
  1054 }
  1055 
  1056 STDMETHODIMP CpEpEngine::OwnIdentitiesRetrieve(LPSAFEARRAY* ownIdentities)
  1057 {
  1058     assert(ownIdentities);
  1059     if (!ownIdentities)
  1060         return E_INVALIDARG;
  1061 
  1062     *ownIdentities = nullptr;
  1063 
  1064     ::identity_list *il = nullptr;
  1065     PEP_STATUS status = ::own_identities_retrieve(get_session(), &il);
  1066     if (status == PEP_OUT_OF_MEMORY) {
  1067         return E_OUTOFMEMORY;
  1068     }
  1069     else if (status != PEP_STATUS_OK)
  1070     {
  1071         return FAIL(_T("OwnIdentitiesRetrieve"), status);
  1072     }
  1073 
  1074     SAFEARRAY * _own_identities = nullptr;
  1075     try {
  1076         _own_identities = array_from_C<pEpIdentity, identity_list>(il);
  1077     }
  1078     catch (exception& ex)
  1079     {
  1080         ::free_identity_list(il);
  1081         try {
  1082             dynamic_cast<bad_alloc&>(ex);
  1083         }
  1084         catch (bad_cast&)
  1085         {
  1086             return FAIL(ex.what());
  1087         }
  1088         return E_OUTOFMEMORY;
  1089     }
  1090     free_identity_list(il);
  1091 
  1092     *ownIdentities = _own_identities;
  1093     return S_OK;
  1094 }
  1095 
  1096 STDMETHODIMP CpEpEngine::TrustPersonalKey(struct pEpIdentity *ident, struct pEpIdentity *result)
  1097 {
  1098     ::pEp_identity *_ident;
  1099 
  1100     assert(ident);
  1101     assert(result);
  1102 
  1103     if (!ident || !result)
  1104         return E_INVALIDARG;
  1105 
  1106     try {
  1107         _ident = new_identity(ident);
  1108     }
  1109     catch (bad_alloc&) {
  1110         return E_OUTOFMEMORY;
  1111     }
  1112     catch (exception& ex) {
  1113         return FAIL(ex.what());;
  1114     }
  1115 
  1116     if (verbose_mode) {
  1117         stringstream ss;
  1118         ss << "TrustPersonalKey called with ";
  1119         ss << utf8_string(ident->Address);
  1120         ss << L": ";
  1121         ss << ident->CommType;
  1122         verbose(ss.str());
  1123     }
  1124 
  1125     PEP_STATUS status = ::trust_personal_key(get_session(), _ident);
  1126 
  1127     if (verbose_mode) {
  1128         stringstream ss;
  1129         ss << "result ";
  1130         ss << status;
  1131         ss << " for ";
  1132         ss << _ident->address;
  1133         ss << L": ";
  1134         ss << _ident->comm_type;
  1135         verbose(ss.str());
  1136     }
  1137 
  1138     if (status == PEP_STATUS_OK)
  1139         copy_identity(result, _ident);
  1140 
  1141     free_identity(_ident);
  1142     if (status == PEP_OUT_OF_MEMORY)
  1143         return E_OUTOFMEMORY;
  1144     else if (status != PEP_STATUS_OK)
  1145         return FAIL(L"failure while executing TrustPersonalKey()", status);
  1146 
  1147     return S_OK;
  1148 }
  1149 
  1150 // keysync api
  1151 
  1152 void CpEpEngine::start_keysync()
  1153 {
  1154     // acquire the lock
  1155     std::unique_lock<std::recursive_mutex> lock(keysync_mutex);
  1156 
  1157     // Assert if we're not already running.
  1158     assert(!this->keysync_thread);
  1159 
  1160     // Ensure we are not aborting the new thread due to a
  1161     // left over flag.
  1162     keysync_abort_requested = false;
  1163 
  1164     // Init our keysync session
  1165 	{ // begin lock scope
  1166 		std::lock_guard<std::mutex> lock(init_mutex);
  1167 		PEP_STATUS status = ::init(&keysync_session);
  1168 		::register_sync_callbacks(keysync_session, (void*)this, messageToSend, notifyHandshake, inject_sync_msg, retrieve_next_sync_msg);
  1169 		assert(status == PEP_STATUS_OK);
  1170 	} // end lock scope
  1171 
  1172     attach_sync_session(get_session(), keysync_session);
  1173 
  1174     // We need to marshal the callbacks to the keysync thread
  1175     LPSTREAM marshaled_callbacks;
  1176 
  1177     auto result = CoMarshalInterThreadInterfaceInStream(IID_IpEpEngineCallbacks, client_callbacks, &marshaled_callbacks);
  1178     assert(result == S_OK);
  1179 
  1180     // Star the keysync thread
  1181     keysync_thread = new thread(do_keysync_in_thread, this, marshaled_callbacks);
  1182 }
  1183 
  1184 void CpEpEngine::do_keysync_in_thread(CpEpEngine* self, LPSTREAM marshaled_callbacks)
  1185 {
  1186     assert(self);
  1187     assert(marshaled_callbacks);
  1188 
  1189     // We need to initialize COM here for successfull delivery of the callbacks.
  1190     // As we don't create any COM instances in our thread, the COMINIT value is
  1191     // currently irrelevant, so we go with the safest value.
  1192     auto res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  1193     assert(res == S_OK);
  1194 
  1195     LPVOID vp;
  1196 
  1197     res = CoGetInterfaceAndReleaseStream(marshaled_callbacks, IID_IpEpEngineCallbacks, &vp);
  1198     assert(SUCCEEDED(res));
  1199 
  1200     self->client_last_signalled_polling_state = false;
  1201     self->client_callbacks_on_sync_thread = static_cast<IpEpEngineCallbacks*>(vp);
  1202 
  1203     res = self->client_callbacks_on_sync_thread->QueryInterface(
  1204         &self->client_callbacks2_on_sync_thread);
  1205     if (res != S_OK)
  1206         self->client_callbacks2_on_sync_thread = NULL;
  1207 
  1208     ::do_sync_protocol(self->keysync_session, self);
  1209 
  1210     self->client_callbacks_on_sync_thread->Release();
  1211 
  1212     self->client_callbacks_on_sync_thread = NULL;
  1213 
  1214     if (self->client_callbacks2_on_sync_thread)
  1215         self->client_callbacks2_on_sync_thread->Release();
  1216     self->client_callbacks2_on_sync_thread = NULL;
  1217 
  1218     CoUninitialize();
  1219 }
  1220 
  1221 void CpEpEngine::stop_keysync()
  1222 {
  1223     // acquire the lock
  1224     std::unique_lock<std::recursive_mutex> lock(keysync_mutex);
  1225 
  1226     // Do nothing if keysync is not running.
  1227     if (!keysync_thread)
  1228         return;
  1229 
  1230     assert(!keysync_abort_requested);
  1231     // signal that we're gonna abort
  1232     keysync_abort_requested = true;
  1233 
  1234     // Notify the keysync thread
  1235     keysync_condition.notify_all();
  1236 
  1237     // Wait for the other thread to finish and clean up
  1238     while (keysync_abort_requested)
  1239         keysync_condition.wait(lock);
  1240 
  1241     // collect the child thread for the thread to end
  1242     keysync_thread->join();
  1243 
  1244     // clean up
  1245     delete keysync_thread;
  1246     keysync_thread = NULL;
  1247 
  1248     ::detach_sync_session(get_session());
  1249     ::unregister_sync_callbacks(keysync_session);
  1250 
  1251 	std::lock_guard<std::mutex> releaselock(init_mutex);
  1252     release(keysync_session);
  1253     keysync_session = NULL;
  1254 }
  1255 
  1256 int CpEpEngine::inject_sync_msg(void * msg, void * management)
  1257 {
  1258     assert(msg);
  1259     assert(management);
  1260     // check argument
  1261     if (!msg)
  1262         return E_INVALIDARG;
  1263     if (!management)
  1264         return ERROR_INVALID_HANDLE;
  1265 
  1266     CpEpEngine* me = (CpEpEngine*)management;
  1267 
  1268     // acquire the lock
  1269     std::unique_lock<std::recursive_mutex> lock(me->keysync_mutex);
  1270 
  1271     // check whether we're in a valid state running:
  1272     if (!me->keysync_thread)
  1273         return E_ASYNC_OPERATION_NOT_STARTED;
  1274 
  1275     // queue the message
  1276     me->keysync_queue.push(msg);
  1277 
  1278     // notify the receivers
  1279     me->keysync_condition.notify_all();
  1280 
  1281     return S_OK;
  1282 }
  1283 
  1284 void * CpEpEngine::retrieve_next_sync_msg(void * management, time_t *timeout)
  1285 {
  1286     // sanity check
  1287     assert(management);
  1288     if (!(management))
  1289         return NULL;
  1290 
  1291     CpEpEngine* me = (CpEpEngine*)management;
  1292 
  1293     if ((timeout && *timeout)
  1294         && me->client_callbacks2_on_sync_thread
  1295         && me->client_last_signalled_polling_state == false)
  1296     {
  1297         me->client_callbacks2_on_sync_thread->NeedFastPolling(VARIANT_TRUE);
  1298         me->client_last_signalled_polling_state = true;
  1299     }
  1300     else if (!(timeout && *timeout)
  1301         && me->client_callbacks2_on_sync_thread
  1302         && me->client_last_signalled_polling_state == true)
  1303     {
  1304         me->client_callbacks2_on_sync_thread->NeedFastPolling(VARIANT_FALSE);
  1305         me->client_last_signalled_polling_state = false;
  1306     }
  1307 
  1308     // acquire the lock
  1309     std::unique_lock<std::recursive_mutex> lock(me->keysync_mutex);
  1310 
  1311     if (me->notify_handshake_finished)
  1312         me->notify_handshake_deliver_result();
  1313 
  1314     if (timeout && *timeout) {
  1315         std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now()
  1316             + std::chrono::seconds(*timeout);
  1317 
  1318         while (me->keysync_queue.empty() && !me->keysync_abort_requested)
  1319         {
  1320             auto status = me->keysync_condition.wait_until(lock, end_time);
  1321 
  1322             if (me->notify_handshake_finished)
  1323                 me->notify_handshake_deliver_result();
  1324 
  1325             if (status == std::cv_status::timeout)
  1326             {
  1327                 *timeout = 1; // Signal timeout
  1328                 return NULL;
  1329             } 
  1330             else 
  1331             {
  1332                 std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
  1333 
  1334                 if (now < end_time) 
  1335                 {
  1336                     *timeout = std::chrono::duration_cast<std::chrono::seconds>(end_time - now).count();
  1337                 } 
  1338                 else 
  1339                 {
  1340                     *timeout = 0;
  1341                 }
  1342             }
  1343         }
  1344     }
  1345     else
  1346     {
  1347         while (me->keysync_queue.empty() && !me->keysync_abort_requested)
  1348         {
  1349             me->keysync_condition.wait(lock);
  1350 
  1351             if (me->notify_handshake_finished)
  1352                 me->notify_handshake_deliver_result();
  1353         }
  1354     }
  1355 
  1356     if (me->keysync_abort_requested) {
  1357         // we acknowledge that we're quitting...
  1358         me->keysync_abort_requested = false;
  1359 
  1360         // We signal the main thread that we got his signal
  1361         // so it can gain the mutex again and call join() on us.
  1362         me->keysync_condition.notify_all();
  1363 
  1364         // and tell the pep engine we're done.
  1365         if (timeout)
  1366             *timeout = 0; // signal for termination.
  1367         return NULL;
  1368     }
  1369 
  1370     assert(!me->keysync_queue.empty());
  1371 
  1372     // Pop the message and return it.
  1373     void* msg = me->keysync_queue.front();
  1374     assert(msg);
  1375 
  1376     me->keysync_queue.pop();
  1377 
  1378     return msg;
  1379 }
  1380 
  1381 
  1382 // Event callbacks
  1383 
  1384 STDMETHODIMP CpEpEngine::RegisterCallbacks(IpEpEngineCallbacks* new_callbacks)
  1385 {
  1386     // check for valid parameter
  1387     if (!new_callbacks)
  1388         return E_INVALIDARG;
  1389 
  1390     // don't allow double registration.
  1391     if (this->client_callbacks)
  1392         return E_ILLEGAL_STATE_CHANGE;
  1393 
  1394     this->client_callbacks = new_callbacks;
  1395     new_callbacks->AddRef();
  1396 
  1397     start_keysync();
  1398 
  1399     return S_OK;
  1400 }
  1401 
  1402 STDMETHODIMP CpEpEngine::UnregisterCallbacks()
  1403 {
  1404     // don't allow double deregistration.
  1405     // S_FALSE still is no error (as double deregistration is not fatal).
  1406     if (!this->client_callbacks)
  1407         return S_FALSE;
  1408 
  1409     stop_keysync();
  1410 
  1411     this->client_callbacks->Release();
  1412 
  1413     this->client_callbacks = NULL;
  1414 
  1415     return S_OK;
  1416 }
  1417 
  1418 STDMETHODIMP CpEpEngine::OpenPGPListKeyinfo(BSTR search_pattern, LPSAFEARRAY* keyinfo_list) {
  1419     assert(keyinfo_list);
  1420 
  1421     if (keyinfo_list == NULL)
  1422         return E_INVALIDARG;
  1423 
  1424     string _pattern = "";
  1425     if (search_pattern)
  1426         _pattern = utf8_string(search_pattern);
  1427     ::stringpair_list_t* _keyinfo_list = NULL;
  1428 
  1429     PEP_STATUS status = ::OpenPGP_list_keyinfo(get_session(), _pattern.c_str(), &_keyinfo_list);
  1430     assert(status != PEP_OUT_OF_MEMORY);
  1431     if (status == PEP_OUT_OF_MEMORY)
  1432         return E_OUTOFMEMORY;
  1433 
  1434     if (status != ::PEP_STATUS_OK)
  1435         return FAIL(L"OpenPGP_list_keyinfo", status);
  1436 
  1437     if (_keyinfo_list && _keyinfo_list->value) {
  1438         ::opt_field_array_from_C(_keyinfo_list, keyinfo_list);
  1439     }
  1440     else {
  1441         ::free_stringpair_list(_keyinfo_list);
  1442         return FAIL(L"OpenPGP_list_keyinfo: no keys found");
  1443     }
  1444 
  1445     ::free_stringpair_list(_keyinfo_list);
  1446     return S_OK;
  1447 
  1448 }
  1449 
  1450 HRESULT CpEpEngine::Fire_MessageToSend(TextMessage * msg)
  1451 {
  1452     assert(msg);
  1453     assert(this->client_callbacks_on_sync_thread);
  1454 
  1455     if (!msg)
  1456         return E_INVALIDARG;
  1457 
  1458     if (!this->client_callbacks_on_sync_thread)
  1459         return E_ILLEGAL_METHOD_CALL;
  1460 
  1461     auto result = this->client_callbacks_on_sync_thread->MessageToSend(msg);
  1462 
  1463     return result;
  1464 }
  1465 
  1466 // This method is called from the keysync thread, and dispatches
  1467 // the handshake asynchroneously to a background thread,
  1468 // so the engine can continue working.
  1469 PEP_STATUS CpEpEngine::notifyHandshake(void * obj, pEp_identity *self, pEp_identity *partner, sync_handshake_signal signal)
  1470 {
  1471     assert(self && partner);
  1472     if (!(self && partner))
  1473         return PEP_ILLEGAL_VALUE;
  1474 
  1475     CpEpEngine *me = (CpEpEngine *)obj;
  1476 
  1477     if (me->notify_handshake_active) {
  1478         // We don't support concurrent handshakes currently, 
  1479         // with the exception of an abort of the handshake, 
  1480         // which we deliver synchroneously (as it's non-blocking).
  1481         if (signal == SYNC_NOTIFY_TIMEOUT) {
  1482             pEpIdentity timeout_self;
  1483             pEpIdentity timeout_partner;
  1484             SyncHandshakeSignal timeout_signal = (SyncHandshakeSignal)signal;
  1485             copy_identity(&timeout_self, self);
  1486             copy_identity(&timeout_partner, partner);
  1487             SyncHandshakeResult result;
  1488             auto res = me->client_callbacks_on_sync_thread->NotifyHandshake(&timeout_self, &timeout_partner, timeout_signal, &result);
  1489 
  1490             clear_identity_s(timeout_self);
  1491             clear_identity_s(timeout_partner);
  1492 
  1493             if (FAILED(res)) {
  1494                 IErrorInfo* errorInfo = NULL;
  1495                 if (FAILED(GetErrorInfo(0, &errorInfo)))
  1496                     errorInfo = NULL;
  1497 
  1498                 // The _com_error takes ownership of the errorInfo
  1499                 // and will Release() it. It can also cope with
  1500                 // NULL errorInfos.
  1501                 _com_error error(res, errorInfo);
  1502 
  1503                 string _description = utf8_string(
  1504                     error.ErrorMessage());
  1505 
  1506                 string _comment = utf8_string(error.Description());
  1507 
  1508                 auto source = error.Source();
  1509                 if (source.length() > 0) {
  1510                     _comment += "\r\nSource: ";
  1511                     _comment += utf8_string(source);
  1512                 }
  1513 
  1514                 ::log_event(me->keysync_session,
  1515                     "Error on NotifyHandshakeTimeout",
  1516                     "pEp COM Adapter",
  1517                     _description.c_str(),
  1518                     _comment.c_str());
  1519 
  1520                 return PEP_UNKNOWN_ERROR;
  1521             }
  1522 
  1523             if (res != S_OK)
  1524 
  1525             return PEP_STATUS_OK;
  1526         }
  1527 
  1528         ::log_event(me->keysync_session, "Reentrant notify_handshake call!", "pEp COM Adapter", NULL, NULL);
  1529         return PEP_UNKNOWN_ERROR;
  1530     }
  1531 
  1532     assert(!(me->notify_handshake_active
  1533         || me->notify_handshake_finished
  1534         || me->notify_handshake_thread));
  1535 
  1536     me->notify_handshake_active = true;
  1537 
  1538     copy_identity(&me->notify_handshake_self, self);
  1539     copy_identity(&me->notify_handshake_partner, partner);
  1540     me->notify_handshake_signal = (SyncHandshakeSignal)signal;
  1541 
  1542     // We need to marshal the callbacks to the keysync thread
  1543     LPSTREAM marshaled_callbacks;
  1544 
  1545     auto result = CoMarshalInterThreadInterfaceInStream(IID_IpEpEngineCallbacks, me->client_callbacks_on_sync_thread, &marshaled_callbacks);
  1546     assert(result == S_OK);
  1547 
  1548     me->notify_handshake_thread = new thread(notify_handshake_background_thread, me, marshaled_callbacks);
  1549 
  1550     return PEP_STATUS_OK;
  1551 }
  1552 
  1553 // This method also runs in the keysync thread, called by
  1554 // retrieve_next_sync_msg() to deliver back the results
  1555 // of the sync into the engine.
  1556 void CpEpEngine::notify_handshake_deliver_result()
  1557 {
  1558     assert(notify_handshake_active
  1559         && notify_handshake_finished);
  1560     if (!(notify_handshake_active
  1561         && notify_handshake_finished))
  1562         return;
  1563 
  1564     notify_handshake_thread->join();
  1565     notify_handshake_thread = NULL;
  1566 
  1567     Identity partner = new_identity(&notify_handshake_partner);
  1568 
  1569     if (FAILED(notify_handshake_error))
  1570     {
  1571         IErrorInfo *errorInfo = NULL;
  1572 
  1573         if (notify_handshake_error_info) {
  1574             LPVOID lp = NULL;
  1575             auto res = CoGetInterfaceAndReleaseStream(notify_handshake_error_info, IID_IErrorInfo, &lp);
  1576 
  1577             if (SUCCEEDED(res) && lp)
  1578                 errorInfo = static_cast<IErrorInfo*>(lp);
  1579         }
  1580 
  1581         // The _com_error takes ownership of the errorInfo
  1582         // and will Release() it. It can also cope with
  1583         // NULL errorInfos.
  1584         _com_error error(notify_handshake_error, errorInfo);
  1585 
  1586         string _description = utf8_string(
  1587             error.ErrorMessage());
  1588 
  1589         string _comment = utf8_string(error.Description());
  1590 
  1591         auto source = error.Source();
  1592         if (source.length() > 0) {
  1593             _comment += "\r\nSource: ";
  1594             _comment += utf8_string(source);
  1595         }
  1596 
  1597         ::log_event(keysync_session,
  1598             "Notify Handshake Failed!",
  1599             "pEp COM Adapter",
  1600             _description.c_str(),
  1601             _comment.c_str());
  1602 
  1603         ::deliverHandshakeResult(keysync_session, partner, SYNC_HANDSHAKE_CANCEL);
  1604     }
  1605     else {
  1606         ::deliverHandshakeResult(
  1607             keysync_session,
  1608             partner,
  1609             (sync_handshake_result)notify_handshake_result);
  1610     }
  1611     notify_handshake_error_info = NULL;
  1612 
  1613     clear_identity_s(notify_handshake_self);
  1614     clear_identity_s(notify_handshake_partner);
  1615     notify_handshake_active = false;
  1616     notify_handshake_finished = false;
  1617 }
  1618 
  1619 // Method on the background thread, calling into Outlook to
  1620 // trigger the Handshake notification, and then scheduling
  1621 // the result back to the main thread.
  1622 void CpEpEngine::notify_handshake_background_thread(CpEpEngine* self, LPSTREAM marshaled_callbacks)
  1623 {
  1624     assert(self);
  1625 
  1626     // We need to initialize COM here for successfull delivery of the callbacks.
  1627     // As we don't create any COM instances in our thread, the COMINIT value is
  1628     // currently irrelevant, so we go with the safest value.
  1629     auto res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  1630     assert(res == S_OK);
  1631 
  1632     LPVOID vp;
  1633 
  1634     res = CoGetInterfaceAndReleaseStream(marshaled_callbacks, IID_IpEpEngineCallbacks, &vp);
  1635     assert(SUCCEEDED(res));
  1636 
  1637     auto client_callbacks_on_sync_thread = static_cast<IpEpEngineCallbacks*>(vp);
  1638 
  1639     self->notify_handshake_error = client_callbacks_on_sync_thread->NotifyHandshake(
  1640         &self->notify_handshake_self,
  1641         &self->notify_handshake_partner,
  1642         self->notify_handshake_signal,
  1643         &self->notify_handshake_result);
  1644 
  1645     if (FAILED(self->notify_handshake_error)) {
  1646         IErrorInfo* errorInfo = NULL;
  1647 
  1648         res = GetErrorInfo(0, &errorInfo);
  1649 
  1650         if (res = S_OK && errorInfo != NULL) {
  1651             res = CoMarshalInterThreadInterfaceInStream(
  1652                 IID_IErrorInfo,
  1653                 errorInfo,
  1654                 &self->notify_handshake_error_info);
  1655 
  1656             errorInfo->Release();
  1657         }
  1658     }
  1659 
  1660     // notify the keysync thread.
  1661     self->notify_handshake_finished = true;
  1662     self->keysync_condition.notify_all();
  1663 }