CpEpEngine.cpp
author Markus Schaber <markus@pep-security.net>
Wed, 07 Feb 2018 18:53:25 +0100
branchCOM-74
changeset 270 c713a265866f
parent 267 ae02fcd56811
child 271 92866cd8b0c4
permissions -rw-r--r--
COM-74: Expose _PEP_enc_format to app for EncryptMessage

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