CpEpEngine.cpp
branchCOM-87
changeset 282 3b92433f8da7
parent 281 08164979a405
child 285 9a19b5dbb271
     1.1 --- a/CpEpEngine.cpp	Thu Apr 26 15:20:11 2018 +0200
     1.2 +++ b/CpEpEngine.cpp	Thu Apr 26 15:30:43 2018 +0200
     1.3 @@ -1,1752 +1,1752 @@
     1.4 -// CpEpEngine.cpp : Implementation of CpEpEngine
     1.5 -
     1.6 -#include "stdafx.h"
     1.7 -#include "CpEpEngine.h"
     1.8 -#include <mutex>
     1.9 -
    1.10 -using namespace std;
    1.11 -using namespace pEp::utility;
    1.12 -
    1.13 -// CpEpEngine
    1.14 -
    1.15 -// the init_mutex protects our initialization and destruction
    1.16 -// against a running keysync thread, and it ensures that the
    1.17 -// keysync thread actually has finished before we're destructed.
    1.18 -std::mutex CpEpEngine::init_mutex;
    1.19 -
    1.20 -STDMETHODIMP CpEpEngine::InterfaceSupportsErrorInfo(REFIID riid)
    1.21 -{
    1.22 -    static const IID* const arr[] =
    1.23 -    {
    1.24 -        &IID_IpEpEngine,
    1.25 -    };
    1.26 -
    1.27 -    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
    1.28 -    {
    1.29 -        if (InlineIsEqualGUID(*arr[i], riid))
    1.30 -            return S_OK;
    1.31 -    }
    1.32 -    return S_FALSE;
    1.33 -}
    1.34 -
    1.35 -// The second argument is optional, and currently supports PEP_STATUS.
    1.36 -#define FAIL(msg, ...) error(msg, __VA_ARGS__)
    1.37 -
    1.38 -STDMETHODIMP CpEpEngine::VerboseLogging(VARIANT_BOOL enable)
    1.39 -{
    1.40 -    verbose_mode = enable != VARIANT_FALSE;
    1.41 -    return S_OK;
    1.42 -}
    1.43 -
    1.44 -STDMETHODIMP CpEpEngine::PassiveMode(VARIANT_BOOL enable)
    1.45 -{
    1.46 -    ::config_passive_mode(get_session(), enable != VARIANT_FALSE);
    1.47 -    return S_OK;
    1.48 -}
    1.49 -
    1.50 -STDMETHODIMP CpEpEngine::UnencryptedSubject(VARIANT_BOOL enable)
    1.51 -{
    1.52 -    ::config_unencrypted_subject(get_session(), enable != VARIANT_FALSE);
    1.53 -    return S_OK;
    1.54 -}
    1.55 -
    1.56 -STDMETHODIMP CpEpEngine::ExportKey(BSTR fpr, BSTR * keyData)
    1.57 -{
    1.58 -    assert(fpr);
    1.59 -    assert(keyData);
    1.60 -
    1.61 -    if (!(fpr && keyData))
    1.62 -        return E_INVALIDARG;
    1.63 -
    1.64 -    string _fpr = utf8_string(fpr);
    1.65 -    char *_key_data = NULL;
    1.66 -    size_t _size = 0;
    1.67 -
    1.68 -    ::PEP_STATUS status = ::export_key(get_session(), _fpr.c_str(), &_key_data, &_size);
    1.69 -    assert(status != ::PEP_OUT_OF_MEMORY);
    1.70 -    if (status == ::PEP_OUT_OF_MEMORY)
    1.71 -        return E_OUTOFMEMORY;
    1.72 -
    1.73 -    if (status != ::PEP_STATUS_OK)
    1.74 -        return FAIL(L"export_key", status);
    1.75 -
    1.76 -    _bstr_t b_key_data(utf16_string(_key_data).c_str());
    1.77 -    pEp_free(_key_data);
    1.78 -    *keyData = b_key_data.Detach();
    1.79 -
    1.80 -    return S_OK;
    1.81 -}
    1.82 -
    1.83 -STDMETHODIMP CpEpEngine::Log(BSTR title, BSTR entity, BSTR description, BSTR comment)
    1.84 -{
    1.85 -    string _title;
    1.86 -    string _entity;
    1.87 -    string _description;
    1.88 -    string _comment;
    1.89 -    HRESULT result = S_OK;
    1.90 -
    1.91 -    assert(title);
    1.92 -    if (title)
    1.93 -        _title = utf8_string(title);
    1.94 -    else
    1.95 -        result = E_INVALIDARG;
    1.96 -
    1.97 -    assert(entity);
    1.98 -    if (entity)
    1.99 -        _entity = utf8_string(entity);
   1.100 -    else
   1.101 -        result = E_INVALIDARG;
   1.102 -
   1.103 -    if (description)
   1.104 -        _description = utf8_string(description);
   1.105 -
   1.106 -    if (comment)
   1.107 -        _comment = utf8_string(comment);
   1.108 -
   1.109 -    if (result != S_OK)
   1.110 -        return result;
   1.111 -
   1.112 -    PEP_STATUS _status = ::log_event(get_session(), _title.c_str(), _entity.c_str(), _description.c_str(), _comment.c_str());
   1.113 -    assert(_status == PEP_STATUS_OK);
   1.114 -    if (_status != PEP_STATUS_OK)
   1.115 -        return FAIL(L"log_event", _status);
   1.116 -    else
   1.117 -        return S_OK;
   1.118 -}
   1.119 -
   1.120 -STDMETHODIMP CpEpEngine::Trustwords(BSTR fpr, BSTR lang, LONG max_words, BSTR * words)
   1.121 -{
   1.122 -    assert(fpr);
   1.123 -    assert(max_words >= 0);
   1.124 -    assert(words);
   1.125 -
   1.126 -    HRESULT result = S_OK;
   1.127 -
   1.128 -    string _fpr;
   1.129 -    if (fpr)
   1.130 -        _fpr = utf8_string(fpr);
   1.131 -    else
   1.132 -        result = E_INVALIDARG;
   1.133 -
   1.134 -    string _lang;
   1.135 -    if (lang) {
   1.136 -        _lang = utf8_string(lang);
   1.137 -        if (_lang.length()) {
   1.138 -            if (_lang.length() != 2)
   1.139 -                result = E_INVALIDARG;
   1.140 -        }
   1.141 -        else
   1.142 -            _lang = "en";
   1.143 -    }
   1.144 -    else
   1.145 -        _lang = "en";
   1.146 -
   1.147 -    if (max_words < 0)
   1.148 -        result = E_INVALIDARG;
   1.149 -
   1.150 -    if (words == NULL)
   1.151 -        result = E_INVALIDARG;
   1.152 -
   1.153 -    if (result != S_OK)
   1.154 -        return result;
   1.155 -
   1.156 -    char *_words = NULL;
   1.157 -    size_t _wsize = 0;
   1.158 -
   1.159 -    PEP_STATUS status = ::trustwords(get_session(), _fpr.c_str(), _lang.c_str(), &_words, &_wsize, max_words);
   1.160 -    assert(status != PEP_OUT_OF_MEMORY);
   1.161 -    if (status == PEP_OUT_OF_MEMORY)
   1.162 -        return E_OUTOFMEMORY;
   1.163 -
   1.164 -    if (_words == NULL) {
   1.165 -        *words = NULL;
   1.166 -        return FAIL(L"Trustwords: _words == NULL", status);
   1.167 -    }
   1.168 -    else {
   1.169 -        *words = utf16_bstr(_words);
   1.170 -        pEp_free(_words);
   1.171 -        return S_OK;
   1.172 -    }
   1.173 -}
   1.174 -
   1.175 -STDMETHODIMP CpEpEngine::GetTrustwords(struct pEpIdentity *id1, struct pEpIdentity *id2, BSTR lang, VARIANT_BOOL full, BSTR *words)
   1.176 -{
   1.177 -    assert(id1);
   1.178 -    assert(id2);
   1.179 -    assert(words);
   1.180 -
   1.181 -    if (!(id1 && id2 && words))
   1.182 -    {
   1.183 -        return E_INVALIDARG;
   1.184 -    }
   1.185 -
   1.186 -    HRESULT result = S_OK;
   1.187 -
   1.188 -    pEp_identity* _id1 = NULL;
   1.189 -    pEp_identity* _id2 = NULL;
   1.190 -    string _lang;
   1.191 -    *words = NULL;
   1.192 -
   1.193 -    try {
   1.194 -        _id1 = new_identity(id1);
   1.195 -        _id2 = new_identity(id2);
   1.196 -
   1.197 -        if (lang) {
   1.198 -            _lang = utf8_string(lang);
   1.199 -            if (_lang.length() == 0) {
   1.200 -                _lang = "en";
   1.201 -            }
   1.202 -            else if (_lang.length() != 2) {
   1.203 -                result = E_INVALIDARG;
   1.204 -            }
   1.205 -        }
   1.206 -        else {
   1.207 -            _lang = "en";
   1.208 -        }
   1.209 -    }
   1.210 -    catch (bad_alloc&) {
   1.211 -        result = E_OUTOFMEMORY;
   1.212 -    }
   1.213 -    catch (exception& ex) {
   1.214 -        result = FAIL(ex.what());
   1.215 -    }
   1.216 -
   1.217 -    char* _words;
   1.218 -    size_t _size;
   1.219 -    if (result == S_OK) {
   1.220 -        auto status = ::get_trustwords(get_session(), _id1, _id2, _lang.c_str(), &_words, &_size, full != 0 /* convert variant bool to C bool */);
   1.221 -
   1.222 -        if (status == PEP_OUT_OF_MEMORY) {
   1.223 -            result = E_OUTOFMEMORY;
   1.224 -        }
   1.225 -        else if (status == PEP_TRUSTWORD_NOT_FOUND) {
   1.226 -            result = FAIL(L"GetTrustwords: Trustword not found", status);
   1.227 -        }
   1.228 -        else if (!words) {
   1.229 -            result = FAIL(L"GetTrustwords: _words == NULL", status);
   1.230 -        }
   1.231 -        else {
   1.232 -            *words = utf16_bstr(_words);
   1.233 -            pEp_free(_words);
   1.234 -        }
   1.235 -    }
   1.236 -
   1.237 -    free_identity(_id1);
   1.238 -    free_identity(_id2);
   1.239 -
   1.240 -    return result;
   1.241 -}
   1.242 -
   1.243 -STDMETHODIMP CpEpEngine::GetMessageTrustwords(
   1.244 -    /* [in] */ struct TextMessage *msg,
   1.245 -    /* [in] */ struct pEpIdentity *receivedBy,
   1.246 -    /* [in] */ SAFEARRAY *keylist,
   1.247 -    /* [defaultvalue][in] */ BSTR lang,
   1.248 -    /* [defaultvalue][in] */ VARIANT_BOOL full,
   1.249 -    /* [retval][out] */ BSTR *words) {
   1.250 -    assert(msg);
   1.251 -    assert(receivedBy);
   1.252 -    assert(words);
   1.253 -
   1.254 -    if (!(msg && receivedBy && words))
   1.255 -    {
   1.256 -        return E_INVALIDARG;
   1.257 -    }
   1.258 -
   1.259 -    HRESULT result = S_OK;
   1.260 -
   1.261 -    pEp_identity * _received_by = NULL;
   1.262 -    ::message * _msg = NULL;
   1.263 -    ::stringlist_t *_keylist = NULL;
   1.264 -    string _lang;
   1.265 -    *words = NULL;
   1.266 -
   1.267 -    try {
   1.268 -        _received_by = new_identity(receivedBy);
   1.269 -        _msg = text_message_to_C(msg);
   1.270 -
   1.271 -        if (keylist) {
   1.272 -            _keylist = new_stringlist(keylist);
   1.273 -        }
   1.274 -
   1.275 -        if (lang) {
   1.276 -            _lang = utf8_string(lang);
   1.277 -            if (_lang.length() == 0) {
   1.278 -                _lang = "en";
   1.279 -            }
   1.280 -            else if (_lang.length() != 2) {
   1.281 -                result = E_INVALIDARG;
   1.282 -            }
   1.283 -        }
   1.284 -        else {
   1.285 -            _lang = "en";
   1.286 -        }
   1.287 -    }
   1.288 -    catch (bad_alloc&) {
   1.289 -        result = E_OUTOFMEMORY;
   1.290 -    }
   1.291 -    catch (exception& ex) {
   1.292 -        result = FAIL(ex.what());
   1.293 -    }
   1.294 -
   1.295 -    char* _words = NULL;
   1.296 -    if (result == S_OK) {
   1.297 -        auto status = ::get_message_trustwords(
   1.298 -            get_session(),
   1.299 -            _msg,
   1.300 -            _keylist,
   1.301 -            _received_by,
   1.302 -            _lang.c_str(),
   1.303 -            &_words,
   1.304 -            full != 0 /* convert variant bool to C bool */);
   1.305 -
   1.306 -        if (status == PEP_OUT_OF_MEMORY) {
   1.307 -            result = E_OUTOFMEMORY;
   1.308 -        }
   1.309 -        else if (status == PEP_TRUSTWORD_NOT_FOUND) {
   1.310 -            result = FAIL(L"GetTrustwords: Trustword not found", status);
   1.311 -        }
   1.312 -        else if (!words) {
   1.313 -            result = FAIL(L"GetTrustwords: _words == NULL", status);
   1.314 -        }
   1.315 -        else {
   1.316 -            *words = utf16_bstr(_words);
   1.317 -        }
   1.318 -    }
   1.319 -
   1.320 -    ::pEp_free(_words);
   1.321 -    ::free_message(_msg);
   1.322 -    ::free_stringlist(_keylist);
   1.323 -    ::free_identity(_received_by);
   1.324 -
   1.325 -    return result;
   1.326 -}
   1.327 -
   1.328 -STDMETHODIMP CpEpEngine::GetCrashdumpLog(LONG maxlines, BSTR * log)
   1.329 -{
   1.330 -    // COM-18: Currently, long == int on windows, so the check
   1.331 -    // for INT_MAX is not strictly necessary. However, the code
   1.332 -    // might get copy-pasted to other adapters in the future,
   1.333 -    // so safety first...
   1.334 -    assert(maxlines >= 0 && maxlines <= INT_MAX);
   1.335 -    assert(log);
   1.336 -
   1.337 -    if (!(maxlines >= 0 && maxlines <= INT_MAX && log))
   1.338 -        return E_INVALIDARG;
   1.339 -
   1.340 -    char *_log;
   1.341 -    PEP_STATUS status = ::get_crashdump_log(get_session(), (int)maxlines, &_log);
   1.342 -    assert(status == PEP_STATUS_OK);
   1.343 -    if (status == PEP_OUT_OF_MEMORY)
   1.344 -        return E_OUTOFMEMORY;
   1.345 -    if (status != PEP_STATUS_OK)
   1.346 -        return FAIL(L"GetCrashdumpLog", status);
   1.347 -    if (_log == NULL)
   1.348 -        return FAIL(L"GetCrashdumpLog: _log == NULL");
   1.349 -
   1.350 -    *log = utf16_bstr(_log);
   1.351 -    pEp_free(_log);
   1.352 -    return S_OK;
   1.353 -}
   1.354 -
   1.355 -STDMETHODIMP CpEpEngine::GetEngineVersion(BSTR * engine_version)
   1.356 -{
   1.357 -    assert(engine_version);
   1.358 -
   1.359 -    if (!engine_version)
   1.360 -        return E_INVALIDARG;
   1.361 -
   1.362 -    const char *_engine_version = ::get_engine_version();
   1.363 -
   1.364 -    if (_engine_version == NULL)
   1.365 -        return FAIL(L"GetEngineVersion: _engine_version == NULL");
   1.366 -
   1.367 -    *engine_version = utf16_bstr(_engine_version);
   1.368 -
   1.369 -    return S_OK;
   1.370 -}
   1.371 -
   1.372 -STDMETHODIMP CpEpEngine::GetLanguageList(BSTR * languages)
   1.373 -{
   1.374 -    assert(languages);
   1.375 -
   1.376 -    if (!languages)
   1.377 -        return E_INVALIDARG;
   1.378 -
   1.379 -    char *_languages;
   1.380 -    PEP_STATUS status = ::get_languagelist(get_session(), &_languages);
   1.381 -    assert(status == PEP_STATUS_OK);
   1.382 -    if (status == PEP_OUT_OF_MEMORY)
   1.383 -        return E_OUTOFMEMORY;
   1.384 -    if (status != PEP_STATUS_OK)
   1.385 -        return FAIL(L"GetLanguageList", status);
   1.386 -    if (_languages == NULL)
   1.387 -        return FAIL(L"GetLanguageList: _languages == NULL");
   1.388 -
   1.389 -    *languages = utf16_bstr(_languages);
   1.390 -    pEp_free(_languages);
   1.391 -    return S_OK;
   1.392 -}
   1.393 -
   1.394 -STDMETHODIMP CpEpEngine::SetIdentityFlags(struct pEpIdentity *identity, pEpIdentityFlags flags)
   1.395 -{
   1.396 -    assert(identity);
   1.397 -    if (!identity)
   1.398 -        return E_INVALIDARG;
   1.399 -
   1.400 -    ::pEp_identity *_ident = nullptr;
   1.401 -
   1.402 -    try {
   1.403 -        _ident = new_identity(identity);
   1.404 -        assert(_ident);
   1.405 -        if (_ident == NULL)
   1.406 -            return E_OUTOFMEMORY;
   1.407 -    }
   1.408 -    catch (bad_alloc&) {
   1.409 -        return E_OUTOFMEMORY;
   1.410 -    }
   1.411 -    catch (exception& ex) {
   1.412 -        return FAIL(ex.what());;
   1.413 -    }
   1.414 -
   1.415 -    PEP_STATUS status = ::set_identity_flags(get_session(), _ident, (identity_flags_t)flags);
   1.416 -    ::free_identity(_ident);
   1.417 -    if (status != PEP_STATUS_OK)
   1.418 -        return FAIL(_T("SetIdentityFlags"), status);
   1.419 -
   1.420 -    return S_OK;
   1.421 -}
   1.422 -
   1.423 -STDMETHODIMP CpEpEngine::UnsetIdentityFlags(struct pEpIdentity *identity, pEpIdentityFlags flags)
   1.424 -{
   1.425 -    assert(identity);
   1.426 -    if (!identity)
   1.427 -        return E_INVALIDARG;
   1.428 -
   1.429 -    ::pEp_identity *_ident = nullptr;
   1.430 -
   1.431 -    try {
   1.432 -        _ident = new_identity(identity);
   1.433 -        assert(_ident);
   1.434 -        if (_ident == NULL)
   1.435 -            return E_OUTOFMEMORY;
   1.436 -    }
   1.437 -    catch (bad_alloc&) {
   1.438 -        return E_OUTOFMEMORY;
   1.439 -    }
   1.440 -    catch (exception& ex) {
   1.441 -        return FAIL(ex.what());;
   1.442 -    }
   1.443 -
   1.444 -    PEP_STATUS status = ::unset_identity_flags(get_session(), _ident, (identity_flags_t)flags);
   1.445 -    ::free_identity(_ident);
   1.446 -    if (status != PEP_STATUS_OK)
   1.447 -        return FAIL(_T("UnsetIdentityFlags"), status);
   1.448 -
   1.449 -    return S_OK;
   1.450 -}
   1.451 -
   1.452 -STDMETHODIMP CpEpEngine::StartKeyserverLookup()
   1.453 -{
   1.454 -    if (identity_queue.load())
   1.455 -        return S_OK;
   1.456 -
   1.457 -    identity_queue.store(new identity_queue_t());
   1.458 -    keymanagement_thread = new thread(::do_keymanagement, retrieve_next_identity, (void *)identity_queue.load());
   1.459 -
   1.460 -    return S_OK;
   1.461 -}
   1.462 -
   1.463 -STDMETHODIMP CpEpEngine::StopKeyserverLookup()
   1.464 -{
   1.465 -    if (identity_queue.load() == NULL)
   1.466 -        return S_OK;
   1.467 -
   1.468 -    identity_queue_t *_iq = identity_queue.load();
   1.469 -    identity_queue.store(NULL);
   1.470 -
   1.471 -    pEp_identity_cpp shutdown;
   1.472 -    _iq->push_front(shutdown);
   1.473 -
   1.474 -    keymanagement_thread->join();
   1.475 -    delete keymanagement_thread;
   1.476 -    keymanagement_thread = NULL;
   1.477 -
   1.478 -    delete _iq;
   1.479 -
   1.480 -    return S_OK;
   1.481 -}
   1.482 -
   1.483 -STDMETHODIMP CpEpEngine::Myself(struct pEpIdentity *ident, struct pEpIdentity *result)
   1.484 -{
   1.485 -    assert(ident);
   1.486 -    assert(result);
   1.487 -
   1.488 -    if (!(ident && result))
   1.489 -        return E_INVALIDARG;
   1.490 -
   1.491 -    ::pEp_identity *_ident = 0;
   1.492 -
   1.493 -    try {
   1.494 -        _ident = new_identity(ident);
   1.495 -        assert(_ident);
   1.496 -        if (_ident == NULL)
   1.497 -            return E_OUTOFMEMORY;
   1.498 -    }
   1.499 -    catch (bad_alloc&) {
   1.500 -        return E_OUTOFMEMORY;
   1.501 -    }
   1.502 -    catch (exception& ex) {
   1.503 -        return FAIL(ex.what());;
   1.504 -    }
   1.505 -
   1.506 -
   1.507 -    // DEBUG CODE - REMOVE BEFORE RELEASE!
   1.508 -    // SyncHandshakeResult handshakeResult;
   1.509 -    //
   1.510 -    // HRESULT res = Fire_NotifyHandshake(ident, result, signal, &handshakeResult);
   1.511 -    // 
   1.512 -    // HRESULT res2 = Fire_TestEvent(15, _bstr_t( "hallo"));
   1.513 -
   1.514 -    PEP_STATUS status = ::myself(get_session(), _ident);
   1.515 -
   1.516 -    if (status == PEP_STATUS_OK) {
   1.517 -        assert(_ident->fpr);
   1.518 -        copy_identity(result, _ident);
   1.519 -        ::free_identity(_ident);
   1.520 -        return S_OK;
   1.521 -    }
   1.522 -    else {
   1.523 -        ::free_identity(_ident);
   1.524 -        if (status == PEP_OUT_OF_MEMORY)
   1.525 -            return E_OUTOFMEMORY;
   1.526 -        else
   1.527 -            return FAIL(L"myself", status);
   1.528 -    }
   1.529 -}
   1.530 -
   1.531 -STDMETHODIMP CpEpEngine::UpdateIdentity(struct pEpIdentity *ident, struct pEpIdentity *result)
   1.532 -{
   1.533 -    assert(ident);
   1.534 -    assert(result);
   1.535 -
   1.536 -    if (!(ident && result))
   1.537 -        return E_INVALIDARG;
   1.538 -
   1.539 -    ::pEp_identity *_ident;
   1.540 -    try {
   1.541 -        _ident = new_identity(ident);
   1.542 -    }
   1.543 -    catch (bad_alloc&) {
   1.544 -        return E_OUTOFMEMORY;
   1.545 -    }
   1.546 -    catch (exception& ex) {
   1.547 -        return FAIL(ex.what());
   1.548 -    }
   1.549 -
   1.550 -    assert(_ident);
   1.551 -    if (_ident == NULL)
   1.552 -        return E_OUTOFMEMORY;
   1.553 -
   1.554 -    PEP_STATUS status = ::update_identity(get_session(), _ident);
   1.555 -
   1.556 -    if (status == PEP_STATUS_OK) {
   1.557 -        copy_identity(result, _ident);
   1.558 -        ::free_identity(_ident);
   1.559 -        return S_OK;
   1.560 -    }
   1.561 -    else if (status == PEP_GET_KEY_FAILED || status == PEP_KEY_NOT_FOUND) {
   1.562 -        if (_ident->fpr) {
   1.563 -            pEp_free(_ident->fpr);
   1.564 -            _ident->fpr = NULL;
   1.565 -        }
   1.566 -        copy_identity(result, _ident);
   1.567 -        result->Fpr = NULL;
   1.568 -        ::free_identity(_ident);
   1.569 -        return S_OK;
   1.570 -    }
   1.571 -    else {
   1.572 -        ::free_identity(_ident);
   1.573 -        if (status == PEP_OUT_OF_MEMORY)
   1.574 -            return E_OUTOFMEMORY;
   1.575 -        else
   1.576 -            return FAIL(L"UpdateIdentity", status);
   1.577 -    }
   1.578 -}
   1.579 -
   1.580 -STDMETHODIMP CpEpEngine::KeyMistrusted(struct pEpIdentity *ident)
   1.581 -{
   1.582 -    ::pEp_identity *_ident;
   1.583 -
   1.584 -    assert(ident);
   1.585 -    if (!ident)
   1.586 -        return E_INVALIDARG;
   1.587 -
   1.588 -    try {
   1.589 -        _ident = new_identity(ident);
   1.590 -    }
   1.591 -    catch (bad_alloc&) {
   1.592 -        return E_OUTOFMEMORY;
   1.593 -    }
   1.594 -    catch (exception& ex) {
   1.595 -        return FAIL(ex.what());;
   1.596 -    }
   1.597 -
   1.598 -    PEP_STATUS status = ::key_mistrusted(get_session(), _ident);
   1.599 -    free_identity(_ident);
   1.600 -
   1.601 -    if (status == PEP_OUT_OF_MEMORY)
   1.602 -        return E_OUTOFMEMORY;
   1.603 -
   1.604 -    if (status == PEP_KEY_NOT_FOUND)
   1.605 -        return FAIL(L"key not found");
   1.606 -
   1.607 -    if (status != ::PEP_STATUS_OK)
   1.608 -        return FAIL(L"cannot revoke compromized key", status);
   1.609 -
   1.610 -    return S_OK;
   1.611 -}
   1.612 -
   1.613 -STDMETHODIMP CpEpEngine::UndoLastMistrust()
   1.614 -{
   1.615 -    PEP_STATUS status = ::undo_last_mistrust(get_session());
   1.616 -
   1.617 -    if (status == PEP_CANNOT_FIND_IDENTITY)
   1.618 -        return FAIL(L"Cannot find identity!", status);
   1.619 -
   1.620 -    if (status != ::PEP_STATUS_OK)
   1.621 -        return FAIL(L"cannot revoke compromized key", status);
   1.622 -
   1.623 -    return S_OK;
   1.624 -}
   1.625 -
   1.626 -STDMETHODIMP CpEpEngine::IsPepUser(/* [in] */ struct pEpIdentity *ident, /* [retval][out] */ VARIANT_BOOL *ispEp) 
   1.627 -{
   1.628 -    ::pEp_identity *_ident;
   1.629 -
   1.630 -    assert(ident);
   1.631 -    if (!ident)
   1.632 -        return E_INVALIDARG;
   1.633 -
   1.634 -    try {
   1.635 -        _ident = new_identity(ident);
   1.636 -    }
   1.637 -    catch (bad_alloc&) {
   1.638 -        return E_OUTOFMEMORY;
   1.639 -    }
   1.640 -    catch (exception& ex) {
   1.641 -        return FAIL(ex.what());;
   1.642 -    }
   1.643 -
   1.644 -    bool is_pep = FALSE;
   1.645 -    PEP_STATUS status = ::is_pep_user(get_session(), _ident, &is_pep);
   1.646 -
   1.647 -    *ispEp = is_pep;
   1.648 -
   1.649 -    if (status == PEP_CANNOT_FIND_PERSON)
   1.650 -        return FAIL(L"Cannot find identity!", status);
   1.651 -
   1.652 -    if (status == PEP_ILLEGAL_VALUE)
   1.653 -        return E_INVALIDARG;
   1.654 -
   1.655 -    if (status != ::PEP_STATUS_OK)
   1.656 -        return FAIL(L"Engine is_pep_user returned error", status);
   1.657 -
   1.658 -    return S_OK;
   1.659 -}
   1.660 -
   1.661 -STDMETHODIMP CpEpEngine::KeyResetTrust(struct pEpIdentity *ident)
   1.662 -{
   1.663 -    ::pEp_identity *_ident;
   1.664 -
   1.665 -    assert(ident);
   1.666 -
   1.667 -    if (!ident)
   1.668 -        return E_INVALIDARG;
   1.669 -
   1.670 -    try {
   1.671 -        _ident = new_identity(ident);
   1.672 -    }
   1.673 -    catch (bad_alloc&) {
   1.674 -        return E_OUTOFMEMORY;
   1.675 -    }
   1.676 -    catch (exception& ex) {
   1.677 -        return FAIL(ex.what());;
   1.678 -    }
   1.679 -
   1.680 -    PEP_STATUS status = ::key_reset_trust(get_session(), _ident);
   1.681 -    free_identity(_ident);
   1.682 -
   1.683 -    if (status == PEP_OUT_OF_MEMORY)
   1.684 -        return E_OUTOFMEMORY;
   1.685 -
   1.686 -    if (status == PEP_KEY_NOT_FOUND)
   1.687 -        return FAIL(L"key not found");
   1.688 -
   1.689 -    if (status != ::PEP_STATUS_OK)
   1.690 -        return FAIL(L"cannot reset trust", status);
   1.691 -
   1.692 -    return S_OK;
   1.693 -}
   1.694 -
   1.695 -int CpEpEngine::examine_identity(pEp_identity *ident, void *management)
   1.696 -{
   1.697 -    assert(ident);
   1.698 -    assert(management);
   1.699 -    if (!(ident && management))
   1.700 -        return -1;
   1.701 -
   1.702 -    CpEpEngine *me = (CpEpEngine *)management;
   1.703 -
   1.704 -    if (me->identity_queue.load() == NULL)
   1.705 -        return 0;
   1.706 -
   1.707 -    try {
   1.708 -        me->identity_queue.load()->push_back(ident);
   1.709 -    }
   1.710 -    catch (exception&) {
   1.711 -        return -1;
   1.712 -    }
   1.713 -
   1.714 -    return 0;
   1.715 -}
   1.716 -
   1.717 -::pEp_identity * CpEpEngine::retrieve_next_identity(void *management)
   1.718 -{
   1.719 -    assert(management);
   1.720 -    if (!management)
   1.721 -        return NULL;
   1.722 -
   1.723 -    identity_queue_t *iq = (identity_queue_t *)management;
   1.724 -
   1.725 -    do /* poll queue */ {
   1.726 -        if (iq->size())
   1.727 -            break;
   1.728 -        ::Sleep(100);
   1.729 -    } while (true);
   1.730 -
   1.731 -    ::pEp_identity *_ident;
   1.732 -    pEp_identity_cpp& ident = iq->front();
   1.733 -
   1.734 -    if (ident.address.size() == 0)
   1.735 -        return NULL;
   1.736 -
   1.737 -    _ident = ident.to_pEp_identity();
   1.738 -    iq->pop_front();
   1.739 -
   1.740 -    return _ident;
   1.741 -}
   1.742 -
   1.743 -PEP_STATUS CpEpEngine::messageToSend(void * obj, message *msg)
   1.744 -{
   1.745 -    assert(msg);
   1.746 -    assert(obj);
   1.747 -    if (!(msg && obj))
   1.748 -        return PEP_ILLEGAL_VALUE;
   1.749 -
   1.750 -    TextMessage _msg;
   1.751 -    memset(&_msg, 0, sizeof(TextMessage));
   1.752 -
   1.753 -    text_message_from_C(&_msg, msg);
   1.754 -    CpEpEngine *me = (CpEpEngine *)obj;
   1.755 -    HRESULT r = me->Fire_MessageToSend(&_msg);
   1.756 -    assert(r == S_OK);
   1.757 -    clear_text_message(&_msg);
   1.758 -    if (r == E_OUTOFMEMORY)
   1.759 -        return PEP_OUT_OF_MEMORY;
   1.760 -    if (r != S_OK)
   1.761 -        return PEP_UNKNOWN_ERROR;
   1.762 -
   1.763 -    return PEP_STATUS_OK;
   1.764 -}
   1.765 -
   1.766 -STDMETHODIMP CpEpEngine::BlacklistAdd(BSTR fpr)
   1.767 -{
   1.768 -    assert(fpr);
   1.769 -    if (!fpr)
   1.770 -        return E_INVALIDARG;
   1.771 -
   1.772 -    string _fpr = utf8_string(fpr);
   1.773 -    PEP_STATUS status = ::blacklist_add(get_session(), _fpr.c_str());
   1.774 -    assert(status == PEP_STATUS_OK);
   1.775 -    if (status != PEP_STATUS_OK)
   1.776 -        return FAIL(L"blacklist_add failed in pEp engine", status);
   1.777 -
   1.778 -    return S_OK;
   1.779 -}
   1.780 -
   1.781 -STDMETHODIMP CpEpEngine::BlacklistDelete(BSTR fpr)
   1.782 -{
   1.783 -    assert(fpr);
   1.784 -    if (!fpr)
   1.785 -        return E_INVALIDARG;
   1.786 -
   1.787 -    string _fpr = utf8_string(fpr);
   1.788 -    PEP_STATUS status = ::blacklist_delete(get_session(), _fpr.c_str());
   1.789 -    assert(status == PEP_STATUS_OK);
   1.790 -    if (status != PEP_STATUS_OK)
   1.791 -        return FAIL(L"blacklist_delete failed in pEp engine", status);
   1.792 -
   1.793 -    return S_OK;
   1.794 -}
   1.795 -
   1.796 -STDMETHODIMP CpEpEngine::BlacklistIsListed(BSTR fpr, VARIANT_BOOL *listed)
   1.797 -{
   1.798 -    assert(fpr);
   1.799 -    assert(listed);
   1.800 -
   1.801 -    if (!(fpr && listed))
   1.802 -        return E_INVALIDARG;
   1.803 -
   1.804 -    string _fpr = utf8_string(fpr);
   1.805 -    bool result;
   1.806 -    PEP_STATUS status = ::blacklist_is_listed(get_session(), _fpr.c_str(), &result);
   1.807 -    assert(status == PEP_STATUS_OK);
   1.808 -    if (status != PEP_STATUS_OK)
   1.809 -        return FAIL(L"blacklist_is_listed failed in pEp engine", status);
   1.810 -
   1.811 -    *listed = result ? VARIANT_TRUE : VARIANT_FALSE;
   1.812 -    return S_OK;
   1.813 -}
   1.814 -
   1.815 -STDMETHODIMP CpEpEngine::BlacklistRetrieve(SAFEARRAY **blacklist)
   1.816 -{
   1.817 -    assert(blacklist);
   1.818 -
   1.819 -    if (!blacklist)
   1.820 -        return E_INVALIDARG;
   1.821 -
   1.822 -    ::stringlist_t *_blacklist = NULL;
   1.823 -    PEP_STATUS status = ::blacklist_retrieve(get_session(), &_blacklist);
   1.824 -    assert(status == PEP_STATUS_OK);
   1.825 -    if (status != PEP_STATUS_OK)
   1.826 -        return FAIL(L"blacklist_retrieve failed in pEp engine", status);
   1.827 -    assert(_blacklist);
   1.828 -
   1.829 -    *blacklist = string_array(_blacklist);
   1.830 -    ::free_stringlist(_blacklist);
   1.831 -    return S_OK;
   1.832 -}
   1.833 -
   1.834 -HRESULT CpEpEngine::error(_bstr_t msg)
   1.835 -{
   1.836 -    _bstr_t helpFile = L"";
   1.837 -    _bstr_t source = L"pEp COM Adapter";
   1.838 -
   1.839 -    ICreateErrorInfo *cei;
   1.840 -    if (SUCCEEDED(CreateErrorInfo(&cei))) {
   1.841 -        cei->SetDescription(msg);
   1.842 -        cei->SetGUID(__uuidof(IpEpEngine));
   1.843 -        cei->SetHelpContext(0);
   1.844 -        cei->SetHelpFile(helpFile);
   1.845 -        cei->SetSource(source);
   1.846 -
   1.847 -        IErrorInfo *errinfo;
   1.848 -        if (SUCCEEDED(cei->QueryInterface(IID_IErrorInfo, (LPVOID FAR*) &errinfo))) {
   1.849 -            SetErrorInfo(0, errinfo);
   1.850 -            errinfo->Release();
   1.851 -        }
   1.852 -        cei->Release();
   1.853 -    }
   1.854 -    return E_FAIL;
   1.855 -}
   1.856 -
   1.857 -HRESULT CpEpEngine::error(_bstr_t msg, PEP_STATUS status)
   1.858 -{
   1.859 -    std::stringstream stream;
   1.860 -    stream << msg;
   1.861 -    stream << ": ";
   1.862 -    stream << std::hex << status;
   1.863 -
   1.864 -    error(stream.str().c_str());
   1.865 -
   1.866 -    if (status == ::PEP_OUT_OF_MEMORY)
   1.867 -        return E_OUTOFMEMORY;
   1.868 -
   1.869 -    return MAKE_HRESULT(1, FACILITY_ITF, (0xFFFF & status));
   1.870 -}
   1.871 -
   1.872 -STDMETHODIMP CpEpEngine::EncryptMessage(TextMessage * src, TextMessage * dst, SAFEARRAY * extra, pEpEncryptFlags flags, pEpEncFormat encFormat)
   1.873 -{
   1.874 -    assert(src);
   1.875 -    assert(dst);
   1.876 -
   1.877 -    if (!(src && dst))
   1.878 -        return E_INVALIDARG;
   1.879 -
   1.880 -    ::message *_src = text_message_to_C(src);
   1.881 -
   1.882 -    _PEP_enc_format _encFormat = (_PEP_enc_format)encFormat;
   1.883 -
   1.884 -    // COM-19: Initialize msg_dst to NULL, or we end up calling
   1.885 -    // free_message() below with a pointer to random garbage in
   1.886 -    // case of an error in encrypt_message().
   1.887 -    ::message *msg_dst = NULL;
   1.888 -    ::stringlist_t *_extra = new_stringlist(extra); // can cope with NULL
   1.889 -
   1.890 -    // _PEP_enc_format used to be intentionally hardcoded to PEP_enc_PEP:
   1.891 -    // Since COM-74, this has been changed to an explicit parameter, to allow the engine to attach
   1.892 -    // the keys and headers to outgoing, unencrypted messages.
   1.893 -    PEP_encrypt_flags_t engineFlags = (PEP_encrypt_flags_t)flags;
   1.894 -    PEP_STATUS status = ::encrypt_message(get_session(), _src, _extra, &msg_dst, _encFormat, engineFlags);
   1.895 -    ::free_stringlist(_extra);
   1.896 -
   1.897 -    if (status == PEP_STATUS_OK)
   1.898 -        text_message_from_C(dst, msg_dst);
   1.899 -    else
   1.900 -        text_message_from_C(dst, _src);
   1.901 -
   1.902 -    ::free_message(msg_dst);
   1.903 -    ::free_message(_src);
   1.904 -
   1.905 -    if (status == PEP_OUT_OF_MEMORY)
   1.906 -        return E_OUTOFMEMORY;
   1.907 -
   1.908 -    // COM-41: Enhanced PEP status handling
   1.909 -    if ((status != PEP_STATUS_OK) && (status < PEP_UNENCRYPTED || status >= PEP_TRUSTWORD_NOT_FOUND))
   1.910 -        return FAIL("Failure to encrypt message", status);
   1.911 -
   1.912 -    // Statii like PEP_UNENCRYPTED due to no private key
   1.913 -    // should not be a catastrophic failure here. Using S_FALSE
   1.914 -    // still allows clients to differentiate with S_OK,
   1.915 -    // although this does not work out of the box with
   1.916 -    // the standard .NET mapping of COM.
   1.917 -    if (status != PEP_STATUS_OK)
   1.918 -        return S_FALSE;
   1.919 -
   1.920 -    return S_OK;
   1.921 -}
   1.922 -
   1.923 -STDMETHODIMP CpEpEngine::EncryptMessageForSelf(pEpIdentity * targetId, TextMessage * src,
   1.924 -    /* [in] */ SAFEARRAY *extra, TextMessage * dst, pEpEncryptFlags flags)
   1.925 -{
   1.926 -    assert(targetId);
   1.927 -    assert(src);
   1.928 -    assert(dst);
   1.929 -
   1.930 -    if (!(targetId && src && dst))
   1.931 -        return E_INVALIDARG;
   1.932 -
   1.933 -    PEP_encrypt_flags_t engineFlags = (PEP_encrypt_flags_t)flags;
   1.934 -
   1.935 -    ::pEp_identity *_target_id = new_identity(targetId);
   1.936 -
   1.937 -    ::message *_src = text_message_to_C(src);
   1.938 +// CpEpEngine.cpp : Implementation of CpEpEngine
   1.939  
   1.940 -    ::stringlist_t* _extra = NULL;
   1.941 -    HRESULT result = S_OK;
   1.942 -    ::message *msg_dst = NULL;
   1.943 -    PEP_STATUS status = PEP_STATUS_OK;
   1.944 -
   1.945 -    try {
   1.946 -        if (extra) {
   1.947 -            _extra = new_stringlist(extra);
   1.948 -        }
   1.949 -
   1.950 -        // COM-19: Initialize msg_dst to NULL, or we end up calling
   1.951 -        // free_message() below with a pointer to random garbage in
   1.952 -        // case of an error in encrypt_message_for_self().
   1.953 -        status = ::encrypt_message_for_self(get_session(), _target_id, _src, _extra, &msg_dst, PEP_enc_PEP, engineFlags);
   1.954 -
   1.955 -        if (status == PEP_STATUS_OK)
   1.956 -            text_message_from_C(dst, msg_dst);
   1.957 -        else
   1.958 -            text_message_from_C(dst, _src);
   1.959 -    } catch (bad_alloc&) {
   1.960 -        result = E_OUTOFMEMORY;
   1.961 -    }
   1.962 -    catch (exception& ex) {
   1.963 -        result = FAIL(ex.what());
   1.964 -    }
   1.965 -
   1.966 -    ::free_message(msg_dst);
   1.967 -    ::free_message(_src);
   1.968 -    ::free_identity(_target_id);
   1.969 -    ::free_stringlist(_extra);
   1.970 -
   1.971 -    if (status == PEP_OUT_OF_MEMORY)
   1.972 -        return E_OUTOFMEMORY;
   1.973 -
   1.974 -    // Different to encrypt_message, this should never fail (we ought to always
   1.975 -    // have a private key for ourself).#
   1.976 -    if (status != PEP_STATUS_OK)
   1.977 -        return FAIL("Failure to encrypt message", status);
   1.978 -
   1.979 -    return result;
   1.980 -}
   1.981 -
   1.982 -STDMETHODIMP CpEpEngine::DecryptMessage(TextMessage * src, TextMessage * dst, SAFEARRAY ** keylist, pEpDecryptFlags *flags, pEpRating *rating)
   1.983 -{
   1.984 -    assert(src);
   1.985 -    assert(dst);
   1.986 -    assert(keylist);
   1.987 -    assert(flags);
   1.988 -    assert(rating);
   1.989 -
   1.990 -    if (!(src && dst && keylist && flags && rating))
   1.991 -        return E_INVALIDARG;
   1.992 -
   1.993 -    *keylist = NULL;
   1.994 -    *rating = pEpRatingUndefined;
   1.995 -
   1.996 -    ::message *_src = text_message_to_C(src);
   1.997 -    ::message *msg_dst = NULL;
   1.998 -    ::stringlist_t *_keylist = NULL;
   1.999 -    ::PEP_rating _rating;
  1.1000 -
  1.1001 -    PEP_decrypt_flags_t engineflags = 0;
  1.1002 -    PEP_STATUS status = ::decrypt_message(get_session(), _src, &msg_dst, &_keylist, &_rating, &engineflags);
  1.1003 -
  1.1004 -    *flags = (pEpDecryptFlags)engineflags;
  1.1005 -
  1.1006 -    if (engineflags && PEP_decrypt_flag_src_modified)
  1.1007 -        text_message_from_C(src, _src);
  1.1008 -
  1.1009 -    if (msg_dst)
  1.1010 -        text_message_from_C(dst, msg_dst);
  1.1011 -
  1.1012 -    ::free_message(_src);
  1.1013 -    ::free_message(msg_dst);
  1.1014 -
  1.1015 -    if (_keylist) {
  1.1016 -        *keylist = string_array(_keylist);
  1.1017 -        free_stringlist(_keylist);
  1.1018 -    }
  1.1019 -
  1.1020 -    *rating = (pEpRating)_rating;
  1.1021 -
  1.1022 -    return S_OK;
  1.1023 -}
  1.1024 -
  1.1025 -STDMETHODIMP CpEpEngine::ReEvaluateMessageRating(TextMessage * msg, SAFEARRAY * x_KeyList, pEpRating x_EncStatus, pEpRating *rating)
  1.1026 -{
  1.1027 -    assert(msg);
  1.1028 -    assert(x_EncStatus != PEP_rating_undefined);
  1.1029 -    assert(rating);
  1.1030 -
  1.1031 -    if (!(msg && x_EncStatus != PEP_rating_undefined && rating))
  1.1032 -        return E_INVALIDARG;
  1.1033 -
  1.1034 -    *rating = pEpRatingUndefined;
  1.1035 -
  1.1036 -    ::message *_msg = text_message_to_C(msg);
  1.1037 -    ::stringlist_t *_keylist = new_stringlist(x_KeyList);
  1.1038 -    ::PEP_rating _rating = PEP_rating_undefined;
  1.1039 -
  1.1040 -    PEP_STATUS status = ::re_evaluate_message_rating(get_session(), _msg, _keylist, (PEP_rating)x_EncStatus, &_rating);
  1.1041 -
  1.1042 -    ::free_stringlist(_keylist);
  1.1043 -    ::free_message(_msg);
  1.1044 -
  1.1045 -    *rating = (pEpRating)_rating;
  1.1046 -
  1.1047 -    return S_OK;
  1.1048 -}
  1.1049 -
  1.1050 -STDMETHODIMP CpEpEngine::OutgoingMessageRating(TextMessage *msg, pEpRating * pVal)
  1.1051 -{
  1.1052 -    assert(msg);
  1.1053 -    assert(pVal);
  1.1054 -
  1.1055 -    if (!(msg  && pVal))
  1.1056 -        return E_INVALIDARG;
  1.1057 -
  1.1058 -    ::message *_msg = text_message_to_C(msg);
  1.1059 -
  1.1060 -    PEP_rating _rating;
  1.1061 -    PEP_STATUS status = ::outgoing_message_rating(get_session(), _msg, &_rating);
  1.1062 -    if (status != PEP_STATUS_OK)
  1.1063 -        return FAIL(L"cannot get message rating", status);
  1.1064 -
  1.1065 -    *pVal = (pEpRating)_rating;
  1.1066 -    return S_OK;
  1.1067 -}
  1.1068 -
  1.1069 -STDMETHODIMP CpEpEngine::IdentityRating(struct pEpIdentity *ident, pEpRating * pVal)
  1.1070 -{
  1.1071 -    ::pEp_identity *_ident;
  1.1072 -
  1.1073 -    assert(ident);
  1.1074 -    assert(pVal);
  1.1075 -
  1.1076 -    if (!(ident  && pVal))
  1.1077 -        return E_INVALIDARG;
  1.1078 -
  1.1079 -    try {
  1.1080 -        _ident = new_identity(ident);
  1.1081 -    }
  1.1082 -    catch (bad_alloc&) {
  1.1083 -        return E_OUTOFMEMORY;
  1.1084 -    }
  1.1085 -    catch (exception& ex) {
  1.1086 -        return FAIL(ex.what());;
  1.1087 -    }
  1.1088 -
  1.1089 -    PEP_rating _rating;
  1.1090 -    PEP_STATUS status = ::identity_rating(get_session(), _ident, &_rating);
  1.1091 -    free_identity(_ident);
  1.1092 -
  1.1093 -    if (status != PEP_STATUS_OK)
  1.1094 -        return FAIL(L"cannot get message color", status);
  1.1095 -
  1.1096 -    *pVal = (pEpRating)_rating;
  1.1097 -    return S_OK;
  1.1098 -}
  1.1099 -
  1.1100 -STDMETHODIMP CpEpEngine::ColorFromRating(pEpRating rating, pEpColor * pVal)
  1.1101 -{
  1.1102 -    assert(pVal);
  1.1103 -
  1.1104 -    if (!pVal)
  1.1105 -        return E_INVALIDARG;
  1.1106 -
  1.1107 -    PEP_rating engineRating = (PEP_rating)rating;
  1.1108 -    PEP_color _color = ::color_from_rating(engineRating);
  1.1109 -
  1.1110 -    *pVal = (pEpColor)_color;
  1.1111 -
  1.1112 -    return S_OK;
  1.1113 -}
  1.1114 -
  1.1115 -STDMETHODIMP CpEpEngine::OwnIdentitiesRetrieve(LPSAFEARRAY* ownIdentities)
  1.1116 -{
  1.1117 -    assert(ownIdentities);
  1.1118 -    if (!ownIdentities)
  1.1119 -        return E_INVALIDARG;
  1.1120 -
  1.1121 -    *ownIdentities = nullptr;
  1.1122 -
  1.1123 -    ::identity_list *il = nullptr;
  1.1124 -    PEP_STATUS status = ::own_identities_retrieve(get_session(), &il);
  1.1125 -    if (status == PEP_OUT_OF_MEMORY) {
  1.1126 -        return E_OUTOFMEMORY;
  1.1127 -    }
  1.1128 -    else if (status != PEP_STATUS_OK)
  1.1129 -    {
  1.1130 -        return FAIL(_T("OwnIdentitiesRetrieve"), status);
  1.1131 -    }
  1.1132 -
  1.1133 -    SAFEARRAY * _own_identities = nullptr;
  1.1134 -    try {
  1.1135 -        _own_identities = array_from_C<pEpIdentity, identity_list>(il);
  1.1136 -    }
  1.1137 -    catch (exception& ex)
  1.1138 -    {
  1.1139 -        ::free_identity_list(il);
  1.1140 -        try {
  1.1141 -            dynamic_cast<bad_alloc&>(ex);
  1.1142 -        }
  1.1143 -        catch (bad_cast&)
  1.1144 -        {
  1.1145 -            return FAIL(ex.what());
  1.1146 -        }
  1.1147 -        return E_OUTOFMEMORY;
  1.1148 -    }
  1.1149 -    free_identity_list(il);
  1.1150 -
  1.1151 -    *ownIdentities = _own_identities;
  1.1152 -    return S_OK;
  1.1153 -}
  1.1154 -
  1.1155 -STDMETHODIMP CpEpEngine::TrustPersonalKey(struct pEpIdentity *ident, struct pEpIdentity *result)
  1.1156 -{
  1.1157 -    ::pEp_identity *_ident;
  1.1158 -
  1.1159 -    assert(ident);
  1.1160 -    assert(result);
  1.1161 -
  1.1162 -    if (!ident || !result)
  1.1163 -        return E_INVALIDARG;
  1.1164 -
  1.1165 -    try {
  1.1166 -        _ident = new_identity(ident);
  1.1167 -    }
  1.1168 -    catch (bad_alloc&) {
  1.1169 -        return E_OUTOFMEMORY;
  1.1170 -    }
  1.1171 -    catch (exception& ex) {
  1.1172 -        return FAIL(ex.what());;
  1.1173 -    }
  1.1174 -
  1.1175 -    if (verbose_mode) {
  1.1176 -        stringstream ss;
  1.1177 -        ss << "TrustPersonalKey called with ";
  1.1178 -        ss << utf8_string(ident->Address);
  1.1179 -        ss << L": ";
  1.1180 -        ss << ident->CommType;
  1.1181 -        verbose(ss.str());
  1.1182 -    }
  1.1183 -
  1.1184 -    PEP_STATUS status = ::trust_personal_key(get_session(), _ident);
  1.1185 -
  1.1186 -    if (verbose_mode) {
  1.1187 -        stringstream ss;
  1.1188 -        ss << "result ";
  1.1189 -        ss << status;
  1.1190 -        ss << " for ";
  1.1191 -        ss << _ident->address;
  1.1192 -        ss << L": ";
  1.1193 -        ss << _ident->comm_type;
  1.1194 -        verbose(ss.str());
  1.1195 -    }
  1.1196 -
  1.1197 -    if (status == PEP_STATUS_OK)
  1.1198 -        copy_identity(result, _ident);
  1.1199 -
  1.1200 -    free_identity(_ident);
  1.1201 -    if (status == PEP_OUT_OF_MEMORY)
  1.1202 -        return E_OUTOFMEMORY;
  1.1203 -    else if (status != PEP_STATUS_OK)
  1.1204 -        return FAIL(L"failure while executing TrustPersonalKey()", status);
  1.1205 -
  1.1206 -    return S_OK;
  1.1207 -}
  1.1208 -
  1.1209 -// keysync api
  1.1210 -
  1.1211 -void CpEpEngine::start_keysync()
  1.1212 -{
  1.1213 -    // acquire the lock
  1.1214 -    std::unique_lock<std::recursive_mutex> lock(keysync_mutex);
  1.1215 -
  1.1216 -    // Assert if we're not already running.
  1.1217 -    assert(!this->keysync_thread);
  1.1218 -
  1.1219 -    // Ensure we are not aborting the new thread due to a
  1.1220 -    // left over flag.
  1.1221 -    keysync_abort_requested = false;
  1.1222 -
  1.1223 -    // Init our keysync session
  1.1224 -    { // begin lock scope
  1.1225 -        std::lock_guard<std::mutex> lock(init_mutex);
  1.1226 -        PEP_STATUS status = ::init(&keysync_session);
  1.1227 -        ::register_sync_callbacks(keysync_session, (void*)this, messageToSend, notifyHandshake, inject_sync_msg, retrieve_next_sync_msg);
  1.1228 -        assert(status == PEP_STATUS_OK);
  1.1229 -    } // end lock scope
  1.1230 -
  1.1231 -    attach_sync_session(get_session(), keysync_session);
  1.1232 -
  1.1233 -    // We need to marshal the callbacks to the keysync thread
  1.1234 -    LPSTREAM marshaled_callbacks;
  1.1235 -
  1.1236 -    auto result = CoMarshalInterThreadInterfaceInStream(IID_IpEpEngineCallbacks, client_callbacks, &marshaled_callbacks);
  1.1237 -    assert(result == S_OK);
  1.1238 -
  1.1239 -    // Star the keysync thread
  1.1240 -    keysync_thread = new thread(do_keysync_in_thread, this, marshaled_callbacks);
  1.1241 -}
  1.1242 -
  1.1243 -void CpEpEngine::do_keysync_in_thread(CpEpEngine* self, LPSTREAM marshaled_callbacks)
  1.1244 -{
  1.1245 -    assert(self);
  1.1246 -    assert(marshaled_callbacks);
  1.1247 -
  1.1248 -    // We need to initialize COM here for successfull delivery of the callbacks.
  1.1249 -    // As we don't create any COM instances in our thread, the COMINIT value is
  1.1250 -    // currently irrelevant, so we go with the safest value.
  1.1251 -    auto res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  1.1252 -    assert(res == S_OK);
  1.1253 -
  1.1254 -    LPVOID vp;
  1.1255 -
  1.1256 -    res = CoGetInterfaceAndReleaseStream(marshaled_callbacks, IID_IpEpEngineCallbacks, &vp);
  1.1257 -    assert(SUCCEEDED(res));
  1.1258 -
  1.1259 -    self->client_last_signalled_polling_state = false;
  1.1260 -    self->client_callbacks_on_sync_thread = static_cast<IpEpEngineCallbacks*>(vp);
  1.1261 -
  1.1262 -    ::do_sync_protocol(self->keysync_session, self);
  1.1263 -
  1.1264 -    self->client_callbacks_on_sync_thread->Release();
  1.1265 -
  1.1266 -    self->client_callbacks_on_sync_thread = NULL;
  1.1267 -
  1.1268 -    CoUninitialize();
  1.1269 -}
  1.1270 -
  1.1271 -void CpEpEngine::stop_keysync()
  1.1272 -{
  1.1273 -    // acquire the lock
  1.1274 -    std::unique_lock<std::recursive_mutex> lock(keysync_mutex);
  1.1275 -
  1.1276 -    // Do nothing if keysync is not running.
  1.1277 -    if (!keysync_thread)
  1.1278 -        return;
  1.1279 -
  1.1280 -    assert(!keysync_abort_requested);
  1.1281 -    // signal that we're gonna abort
  1.1282 -    keysync_abort_requested = true;
  1.1283 -
  1.1284 -    // Notify the keysync thread
  1.1285 -    keysync_condition.notify_all();
  1.1286 -
  1.1287 -    // Wait for the other thread to finish and clean up
  1.1288 -    while (keysync_abort_requested)
  1.1289 -        keysync_condition.wait(lock);
  1.1290 -
  1.1291 -    // collect the child thread for the thread to end
  1.1292 -    keysync_thread->join();
  1.1293 -
  1.1294 -    // clean up
  1.1295 -    delete keysync_thread;
  1.1296 -    keysync_thread = NULL;
  1.1297 -
  1.1298 -    ::detach_sync_session(get_session());
  1.1299 -    ::unregister_sync_callbacks(keysync_session);
  1.1300 -
  1.1301 -    std::lock_guard<std::mutex> releaselock(init_mutex);
  1.1302 -    release(keysync_session);
  1.1303 -    keysync_session = NULL;
  1.1304 -}
  1.1305 -
  1.1306 -int CpEpEngine::inject_sync_msg(void * msg, void * management)
  1.1307 -{
  1.1308 -    assert(msg);
  1.1309 -    assert(management);
  1.1310 -    // check argument
  1.1311 -    if (!msg)
  1.1312 -        return E_INVALIDARG;
  1.1313 -    if (!management)
  1.1314 -        return ERROR_INVALID_HANDLE;
  1.1315 -
  1.1316 -    CpEpEngine* me = (CpEpEngine*)management;
  1.1317 -
  1.1318 -    // acquire the lock
  1.1319 -    std::unique_lock<std::recursive_mutex> lock(me->keysync_mutex);
  1.1320 -
  1.1321 -    // check whether we're in a valid state running:
  1.1322 -    if (!me->keysync_thread)
  1.1323 -        return E_ASYNC_OPERATION_NOT_STARTED;
  1.1324 -
  1.1325 -    // queue the message
  1.1326 -    me->keysync_queue.push(msg);
  1.1327 -
  1.1328 -    // notify the receivers
  1.1329 -    me->keysync_condition.notify_all();
  1.1330 -
  1.1331 -    return S_OK;
  1.1332 -}
  1.1333 -
  1.1334 -void * CpEpEngine::retrieve_next_sync_msg(void * management, time_t *timeout)
  1.1335 -{
  1.1336 -    // sanity check
  1.1337 -    assert(management);
  1.1338 -    if (!(management))
  1.1339 -        return NULL;
  1.1340 -
  1.1341 -    CpEpEngine* me = (CpEpEngine*)management;
  1.1342 -
  1.1343 -    if ((timeout && *timeout)
  1.1344 -        && me->client_callbacks_on_sync_thread
  1.1345 -        && me->client_last_signalled_polling_state == false)
  1.1346 -    {
  1.1347 -        me->client_callbacks_on_sync_thread->NeedFastPolling(VARIANT_TRUE);
  1.1348 -        me->client_last_signalled_polling_state = true;
  1.1349 -    }
  1.1350 -    else if (!(timeout && *timeout)
  1.1351 -        && me->client_callbacks_on_sync_thread
  1.1352 -        && me->client_last_signalled_polling_state == true)
  1.1353 -    {
  1.1354 -        me->client_callbacks_on_sync_thread->NeedFastPolling(VARIANT_FALSE);
  1.1355 -        me->client_last_signalled_polling_state = false;
  1.1356 -    }
  1.1357 -
  1.1358 -    // acquire the lock
  1.1359 -    std::unique_lock<std::recursive_mutex> lock(me->keysync_mutex);
  1.1360 -
  1.1361 -    if (me->notify_handshake_finished)
  1.1362 -        me->notify_handshake_deliver_result();
  1.1363 -
  1.1364 -    if (timeout && *timeout) {
  1.1365 -        std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now()
  1.1366 -            + std::chrono::seconds(*timeout);
  1.1367 -
  1.1368 -        while (me->keysync_queue.empty() && !me->keysync_abort_requested)
  1.1369 -        {
  1.1370 -            auto status = me->keysync_condition.wait_until(lock, end_time);
  1.1371 -
  1.1372 -            if (me->notify_handshake_finished)
  1.1373 -                me->notify_handshake_deliver_result();
  1.1374 -
  1.1375 -            if (status == std::cv_status::timeout)
  1.1376 -            {
  1.1377 -                *timeout = 1; // Signal timeout
  1.1378 -                return NULL;
  1.1379 -            }
  1.1380 -            else
  1.1381 -            {
  1.1382 -                std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
  1.1383 -
  1.1384 -                if (now < end_time)
  1.1385 -                {
  1.1386 -                    *timeout = std::chrono::duration_cast<std::chrono::seconds>(end_time - now).count();
  1.1387 -                }
  1.1388 -                else
  1.1389 -                {
  1.1390 -                    *timeout = 0;
  1.1391 -                }
  1.1392 -            }
  1.1393 -        }
  1.1394 -    }
  1.1395 -    else
  1.1396 -    {
  1.1397 -        while (me->keysync_queue.empty() && !me->keysync_abort_requested)
  1.1398 -        {
  1.1399 -            me->keysync_condition.wait(lock);
  1.1400 -
  1.1401 -            if (me->notify_handshake_finished)
  1.1402 -                me->notify_handshake_deliver_result();
  1.1403 -        }
  1.1404 -    }
  1.1405 -
  1.1406 -    if (me->keysync_abort_requested) {
  1.1407 -        // we acknowledge that we're quitting...
  1.1408 -        me->keysync_abort_requested = false;
  1.1409 -
  1.1410 -        // We signal the main thread that we got his signal
  1.1411 -        // so it can gain the mutex again and call join() on us.
  1.1412 -        me->keysync_condition.notify_all();
  1.1413 -
  1.1414 -        // and tell the pep engine we're done.
  1.1415 -        if (timeout)
  1.1416 -            *timeout = 0; // signal for termination.
  1.1417 -        return NULL;
  1.1418 -    }
  1.1419 -
  1.1420 -    assert(!me->keysync_queue.empty());
  1.1421 -
  1.1422 -    // Pop the message and return it.
  1.1423 -    void* msg = me->keysync_queue.front();
  1.1424 -    assert(msg);
  1.1425 -
  1.1426 -    me->keysync_queue.pop();
  1.1427 -
  1.1428 -    return msg;
  1.1429 -}
  1.1430 -
  1.1431 -
  1.1432 -// Event callbacks
  1.1433 -
  1.1434 -STDMETHODIMP CpEpEngine::RegisterCallbacks(IpEpEngineCallbacks* new_callbacks)
  1.1435 -{
  1.1436 -    // check for valid parameter
  1.1437 -    if (!new_callbacks)
  1.1438 -        return E_INVALIDARG;
  1.1439 -
  1.1440 -    // don't allow double registration.
  1.1441 -    if (this->client_callbacks)
  1.1442 -        return E_ILLEGAL_STATE_CHANGE;
  1.1443 -
  1.1444 -    this->client_callbacks = new_callbacks;
  1.1445 -    new_callbacks->AddRef();
  1.1446 -
  1.1447 -    start_keysync();
  1.1448 -
  1.1449 -    return S_OK;
  1.1450 -}
  1.1451 -
  1.1452 -STDMETHODIMP CpEpEngine::UnregisterCallbacks()
  1.1453 -{
  1.1454 -    // don't allow double deregistration.
  1.1455 -    // S_FALSE still is no error (as double deregistration is not fatal).
  1.1456 -    if (!this->client_callbacks)
  1.1457 -        return S_FALSE;
  1.1458 -
  1.1459 -    stop_keysync();
  1.1460 -
  1.1461 -    this->client_callbacks->Release();
  1.1462 -
  1.1463 -    this->client_callbacks = NULL;
  1.1464 -
  1.1465 -    return S_OK;
  1.1466 -}
  1.1467 -
  1.1468 -STDMETHODIMP CpEpEngine::OpenPGPListKeyinfo(BSTR search_pattern, LPSAFEARRAY* keyinfo_list) {
  1.1469 -    assert(keyinfo_list);
  1.1470 -
  1.1471 -    if (keyinfo_list == NULL)
  1.1472 -        return E_INVALIDARG;
  1.1473 -
  1.1474 -    string _pattern = "";
  1.1475 -    if (search_pattern)
  1.1476 -        _pattern = utf8_string(search_pattern);
  1.1477 -    ::stringpair_list_t* _keyinfo_list = NULL;
  1.1478 -
  1.1479 -    PEP_STATUS status = ::OpenPGP_list_keyinfo(get_session(), _pattern.c_str(), &_keyinfo_list);
  1.1480 -    assert(status != PEP_OUT_OF_MEMORY);
  1.1481 -    if (status == PEP_OUT_OF_MEMORY)
  1.1482 -        return E_OUTOFMEMORY;
  1.1483 -
  1.1484 -    if (status != ::PEP_STATUS_OK)
  1.1485 -        return FAIL(L"OpenPGP_list_keyinfo", status);
  1.1486 -
  1.1487 -    if (_keyinfo_list && _keyinfo_list->value) {
  1.1488 -        ::opt_field_array_from_C(_keyinfo_list, keyinfo_list);
  1.1489 -    }
  1.1490 -    else {
  1.1491 -        ::free_stringpair_list(_keyinfo_list);
  1.1492 -        return FAIL(L"OpenPGP_list_keyinfo: no keys found");
  1.1493 -    }
  1.1494 -
  1.1495 -    ::free_stringpair_list(_keyinfo_list);
  1.1496 -    return S_OK;
  1.1497 -
  1.1498 -}
  1.1499 -
  1.1500 -STDMETHODIMP CpEpEngine::SetOwnKey(pEpIdentity * ident, BSTR fpr, struct pEpIdentity *result)
  1.1501 -{
  1.1502 -	assert(ident);
  1.1503 -	assert(result);
  1.1504 -	assert(fpr);
  1.1505 -
  1.1506 -	if (!(ident && result))
  1.1507 -		return E_INVALIDARG;
  1.1508 -
  1.1509 -	::pEp_identity *_ident;
  1.1510 -	try {
  1.1511 -		_ident = new_identity(ident);
  1.1512 -	}
  1.1513 -	catch (bad_alloc&) {
  1.1514 -		return E_OUTOFMEMORY;
  1.1515 -	}
  1.1516 -	catch (exception& ex) {
  1.1517 -		return FAIL(ex.what());
  1.1518 -	}
  1.1519 -
  1.1520 -	assert(_ident);
  1.1521 -	if (_ident == NULL)
  1.1522 -		return E_OUTOFMEMORY;
  1.1523 -
  1.1524 -	string _fpr = utf8_string(fpr);
  1.1525 -	PEP_STATUS status = ::set_own_key(get_session(), _ident, _fpr.c_str());
  1.1526 -
  1.1527 -	if (status == PEP_STATUS_OK) {
  1.1528 -		copy_identity(result, _ident);
  1.1529 -		::free_identity(_ident);
  1.1530 -		return S_OK;
  1.1531 -	}
  1.1532 -	else {
  1.1533 -		::free_identity(_ident);
  1.1534 -		if (status == PEP_OUT_OF_MEMORY)
  1.1535 -			return E_OUTOFMEMORY;
  1.1536 -		else
  1.1537 -			return FAIL(L"SetOwnKey", status);
  1.1538 -	}
  1.1539 -
  1.1540 -	return S_OK;
  1.1541 -}
  1.1542 -
  1.1543 -HRESULT CpEpEngine::Fire_MessageToSend(TextMessage * msg)
  1.1544 -{
  1.1545 -    assert(msg);
  1.1546 -    assert(this->client_callbacks_on_sync_thread);
  1.1547 -
  1.1548 -    if (!msg)
  1.1549 -        return E_INVALIDARG;
  1.1550 -
  1.1551 -    if (!this->client_callbacks_on_sync_thread)
  1.1552 -        return E_ILLEGAL_METHOD_CALL;
  1.1553 -
  1.1554 -    auto result = this->client_callbacks_on_sync_thread->MessageToSend(msg);
  1.1555 -
  1.1556 -    return result;
  1.1557 -}
  1.1558 -
  1.1559 -// This method is called from the keysync thread, and dispatches
  1.1560 -// the handshake asynchroneously to a background thread,
  1.1561 -// so the engine can continue working.
  1.1562 -PEP_STATUS CpEpEngine::notifyHandshake(void * obj, pEp_identity *self, pEp_identity *partner, sync_handshake_signal signal)
  1.1563 -{
  1.1564 -    assert(self && partner);
  1.1565 -    if (!(self && partner))
  1.1566 -        return PEP_ILLEGAL_VALUE;
  1.1567 -
  1.1568 -    CpEpEngine *me = (CpEpEngine *)obj;
  1.1569 -
  1.1570 -    if (me->notify_handshake_active) {
  1.1571 -        // We don't support concurrent handshakes currently, 
  1.1572 -        // with the exception of an abort of the handshake, 
  1.1573 -        // which we deliver synchroneously (as it's non-blocking).
  1.1574 -        if (signal == SYNC_NOTIFY_TIMEOUT) {
  1.1575 -            pEpIdentity timeout_self;
  1.1576 -            pEpIdentity timeout_partner;
  1.1577 -            SyncHandshakeSignal timeout_signal = (SyncHandshakeSignal)signal;
  1.1578 -            copy_identity(&timeout_self, self);
  1.1579 -            copy_identity(&timeout_partner, partner);
  1.1580 -            SyncHandshakeResult result;
  1.1581 -            auto res = me->client_callbacks_on_sync_thread->NotifyHandshake(&timeout_self, &timeout_partner, timeout_signal, &result);
  1.1582 -
  1.1583 -            clear_identity_s(timeout_self);
  1.1584 -            clear_identity_s(timeout_partner);
  1.1585 -
  1.1586 -            if (FAILED(res)) {
  1.1587 -                IErrorInfo* errorInfo = NULL;
  1.1588 -                if (FAILED(GetErrorInfo(0, &errorInfo)))
  1.1589 -                    errorInfo = NULL;
  1.1590 -
  1.1591 -                // The _com_error takes ownership of the errorInfo
  1.1592 -                // and will Release() it. It can also cope with
  1.1593 -                // NULL errorInfos.
  1.1594 -                _com_error error(res, errorInfo);
  1.1595 -
  1.1596 -                string _description = utf8_string(
  1.1597 -                    error.ErrorMessage());
  1.1598 -
  1.1599 -                string _comment = utf8_string(error.Description());
  1.1600 -
  1.1601 -                auto source = error.Source();
  1.1602 -                if (source.length() > 0) {
  1.1603 -                    _comment += "\r\nSource: ";
  1.1604 -                    _comment += utf8_string(source);
  1.1605 -                }
  1.1606 -
  1.1607 -                ::log_event(me->keysync_session,
  1.1608 -                    "Error on NotifyHandshakeTimeout",
  1.1609 -                    "pEp COM Adapter",
  1.1610 -                    _description.c_str(),
  1.1611 -                    _comment.c_str());
  1.1612 -
  1.1613 -                return PEP_UNKNOWN_ERROR;
  1.1614 -            }
  1.1615 -
  1.1616 -            if (res != S_OK)
  1.1617 -
  1.1618 -                return PEP_STATUS_OK;
  1.1619 -        }
  1.1620 -
  1.1621 -        ::log_event(me->keysync_session, "Reentrant notify_handshake call!", "pEp COM Adapter", NULL, NULL);
  1.1622 -        return PEP_UNKNOWN_ERROR;
  1.1623 -    }
  1.1624 -
  1.1625 -    assert(!(me->notify_handshake_active
  1.1626 -        || me->notify_handshake_finished
  1.1627 -        || me->notify_handshake_thread));
  1.1628 -
  1.1629 -    me->notify_handshake_active = true;
  1.1630 -
  1.1631 -    copy_identity(&me->notify_handshake_self, self);
  1.1632 -    copy_identity(&me->notify_handshake_partner, partner);
  1.1633 -    me->notify_handshake_signal = (SyncHandshakeSignal)signal;
  1.1634 -
  1.1635 -    // We need to marshal the callbacks to the keysync thread
  1.1636 -    LPSTREAM marshaled_callbacks;
  1.1637 -
  1.1638 -    auto result = CoMarshalInterThreadInterfaceInStream(IID_IpEpEngineCallbacks, me->client_callbacks_on_sync_thread, &marshaled_callbacks);
  1.1639 -    assert(result == S_OK);
  1.1640 -
  1.1641 -    me->notify_handshake_thread = new thread(notify_handshake_background_thread, me, marshaled_callbacks);
  1.1642 -
  1.1643 -    return PEP_STATUS_OK;
  1.1644 -}
  1.1645 -
  1.1646 -// This method also runs in the keysync thread, called by
  1.1647 -// retrieve_next_sync_msg() to deliver back the results
  1.1648 -// of the sync into the engine.
  1.1649 -void CpEpEngine::notify_handshake_deliver_result()
  1.1650 -{
  1.1651 -    assert(notify_handshake_active
  1.1652 -        && notify_handshake_finished);
  1.1653 -    if (!(notify_handshake_active
  1.1654 -        && notify_handshake_finished))
  1.1655 -        return;
  1.1656 -
  1.1657 -    notify_handshake_thread->join();
  1.1658 -    notify_handshake_thread = NULL;
  1.1659 -
  1.1660 -    Identity partner = new_identity(&notify_handshake_partner);
  1.1661 -
  1.1662 -    if (FAILED(notify_handshake_error))
  1.1663 -    {
  1.1664 -        IErrorInfo *errorInfo = NULL;
  1.1665 -
  1.1666 -        if (notify_handshake_error_info) {
  1.1667 -            LPVOID lp = NULL;
  1.1668 -            auto res = CoGetInterfaceAndReleaseStream(notify_handshake_error_info, IID_IErrorInfo, &lp);
  1.1669 -
  1.1670 -            if (SUCCEEDED(res) && lp)
  1.1671 -                errorInfo = static_cast<IErrorInfo*>(lp);
  1.1672 -        }
  1.1673 -
  1.1674 -        // The _com_error takes ownership of the errorInfo
  1.1675 -        // and will Release() it. It can also cope with
  1.1676 -        // NULL errorInfos.
  1.1677 -        _com_error error(notify_handshake_error, errorInfo);
  1.1678 -
  1.1679 -        string _description = utf8_string(
  1.1680 -            error.ErrorMessage());
  1.1681 -
  1.1682 -        string _comment = utf8_string(error.Description());
  1.1683 -
  1.1684 -        auto source = error.Source();
  1.1685 -        if (source.length() > 0) {
  1.1686 -            _comment += "\r\nSource: ";
  1.1687 -            _comment += utf8_string(source);
  1.1688 -        }
  1.1689 -
  1.1690 -        ::log_event(keysync_session,
  1.1691 -            "Notify Handshake Failed!",
  1.1692 -            "pEp COM Adapter",
  1.1693 -            _description.c_str(),
  1.1694 -            _comment.c_str());
  1.1695 -
  1.1696 -        ::deliverHandshakeResult(keysync_session, partner, SYNC_HANDSHAKE_CANCEL);
  1.1697 -    }
  1.1698 -    else {
  1.1699 -        ::deliverHandshakeResult(
  1.1700 -            keysync_session,
  1.1701 -            partner,
  1.1702 -            (sync_handshake_result)notify_handshake_result);
  1.1703 -    }
  1.1704 -    notify_handshake_error_info = NULL;
  1.1705 -
  1.1706 -    clear_identity_s(notify_handshake_self);
  1.1707 -    clear_identity_s(notify_handshake_partner);
  1.1708 -    notify_handshake_active = false;
  1.1709 -    notify_handshake_finished = false;
  1.1710 -}
  1.1711 -
  1.1712 -// Method on the background thread, calling into Outlook to
  1.1713 -// trigger the Handshake notification, and then scheduling
  1.1714 -// the result back to the main thread.
  1.1715 -void CpEpEngine::notify_handshake_background_thread(CpEpEngine* self, LPSTREAM marshaled_callbacks)
  1.1716 -{
  1.1717 -    assert(self);
  1.1718 -
  1.1719 -    // We need to initialize COM here for successfull delivery of the callbacks.
  1.1720 -    // As we don't create any COM instances in our thread, the COMINIT value is
  1.1721 -    // currently irrelevant, so we go with the safest value.
  1.1722 -    auto res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  1.1723 -    assert(res == S_OK);
  1.1724 -
  1.1725 -    LPVOID vp;
  1.1726 -
  1.1727 -    res = CoGetInterfaceAndReleaseStream(marshaled_callbacks, IID_IpEpEngineCallbacks, &vp);
  1.1728 -    assert(SUCCEEDED(res));
  1.1729 -
  1.1730 -    auto client_callbacks_on_sync_thread = static_cast<IpEpEngineCallbacks*>(vp);
  1.1731 -
  1.1732 -    self->notify_handshake_error = client_callbacks_on_sync_thread->NotifyHandshake(
  1.1733 -        &self->notify_handshake_self,
  1.1734 -        &self->notify_handshake_partner,
  1.1735 -        self->notify_handshake_signal,
  1.1736 -        &self->notify_handshake_result);
  1.1737 -
  1.1738 -    if (FAILED(self->notify_handshake_error)) {
  1.1739 -        IErrorInfo* errorInfo = NULL;
  1.1740 -
  1.1741 -        res = GetErrorInfo(0, &errorInfo);
  1.1742 -
  1.1743 -        if (res = S_OK && errorInfo != NULL) {
  1.1744 -            res = CoMarshalInterThreadInterfaceInStream(
  1.1745 -                IID_IErrorInfo,
  1.1746 -                errorInfo,
  1.1747 -                &self->notify_handshake_error_info);
  1.1748 -
  1.1749 -            errorInfo->Release();
  1.1750 -        }
  1.1751 -    }
  1.1752 -
  1.1753 -    // notify the keysync thread.
  1.1754 -    self->notify_handshake_finished = true;
  1.1755 -    self->keysync_condition.notify_all();
  1.1756 -}
  1.1757 +#include "stdafx.h"
  1.1758 +#include "CpEpEngine.h"
  1.1759 +#include <mutex>
  1.1760 +
  1.1761 +using namespace std;
  1.1762 +using namespace pEp::utility;
  1.1763 +
  1.1764 +// CpEpEngine
  1.1765 +
  1.1766 +// the init_mutex protects our initialization and destruction
  1.1767 +// against a running keysync thread, and it ensures that the
  1.1768 +// keysync thread actually has finished before we're destructed.
  1.1769 +std::mutex CpEpEngine::init_mutex;
  1.1770 +
  1.1771 +STDMETHODIMP CpEpEngine::InterfaceSupportsErrorInfo(REFIID riid)
  1.1772 +{
  1.1773 +    static const IID* const arr[] =
  1.1774 +    {
  1.1775 +        &IID_IpEpEngine,
  1.1776 +    };
  1.1777 +
  1.1778 +    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
  1.1779 +    {
  1.1780 +        if (InlineIsEqualGUID(*arr[i], riid))
  1.1781 +            return S_OK;
  1.1782 +    }
  1.1783 +    return S_FALSE;
  1.1784 +}
  1.1785 +
  1.1786 +// The second argument is optional, and currently supports PEP_STATUS.
  1.1787 +#define FAIL(msg, ...) error(msg, __VA_ARGS__)
  1.1788 +
  1.1789 +STDMETHODIMP CpEpEngine::VerboseLogging(VARIANT_BOOL enable)
  1.1790 +{
  1.1791 +    verbose_mode = enable != VARIANT_FALSE;
  1.1792 +    return S_OK;
  1.1793 +}
  1.1794 +
  1.1795 +STDMETHODIMP CpEpEngine::PassiveMode(VARIANT_BOOL enable)
  1.1796 +{
  1.1797 +    ::config_passive_mode(get_session(), enable != VARIANT_FALSE);
  1.1798 +    return S_OK;
  1.1799 +}
  1.1800 +
  1.1801 +STDMETHODIMP CpEpEngine::UnencryptedSubject(VARIANT_BOOL enable)
  1.1802 +{
  1.1803 +    ::config_unencrypted_subject(get_session(), enable != VARIANT_FALSE);
  1.1804 +    return S_OK;
  1.1805 +}
  1.1806 +
  1.1807 +STDMETHODIMP CpEpEngine::ExportKey(BSTR fpr, BSTR * keyData)
  1.1808 +{
  1.1809 +    assert(fpr);
  1.1810 +    assert(keyData);
  1.1811 +
  1.1812 +    if (!(fpr && keyData))
  1.1813 +        return E_INVALIDARG;
  1.1814 +
  1.1815 +    string _fpr = utf8_string(fpr);
  1.1816 +    char *_key_data = NULL;
  1.1817 +    size_t _size = 0;
  1.1818 +
  1.1819 +    ::PEP_STATUS status = ::export_key(get_session(), _fpr.c_str(), &_key_data, &_size);
  1.1820 +    assert(status != ::PEP_OUT_OF_MEMORY);
  1.1821 +    if (status == ::PEP_OUT_OF_MEMORY)
  1.1822 +        return E_OUTOFMEMORY;
  1.1823 +
  1.1824 +    if (status != ::PEP_STATUS_OK)
  1.1825 +        return FAIL(L"export_key", status);
  1.1826 +
  1.1827 +    _bstr_t b_key_data(utf16_string(_key_data).c_str());
  1.1828 +    pEp_free(_key_data);
  1.1829 +    *keyData = b_key_data.Detach();
  1.1830 +
  1.1831 +    return S_OK;
  1.1832 +}
  1.1833 +
  1.1834 +STDMETHODIMP CpEpEngine::Log(BSTR title, BSTR entity, BSTR description, BSTR comment)
  1.1835 +{
  1.1836 +    string _title;
  1.1837 +    string _entity;
  1.1838 +    string _description;
  1.1839 +    string _comment;
  1.1840 +    HRESULT result = S_OK;
  1.1841 +
  1.1842 +    assert(title);
  1.1843 +    if (title)
  1.1844 +        _title = utf8_string(title);
  1.1845 +    else
  1.1846 +        result = E_INVALIDARG;
  1.1847 +
  1.1848 +    assert(entity);
  1.1849 +    if (entity)
  1.1850 +        _entity = utf8_string(entity);
  1.1851 +    else
  1.1852 +        result = E_INVALIDARG;
  1.1853 +
  1.1854 +    if (description)
  1.1855 +        _description = utf8_string(description);
  1.1856 +
  1.1857 +    if (comment)
  1.1858 +        _comment = utf8_string(comment);
  1.1859 +
  1.1860 +    if (result != S_OK)
  1.1861 +        return result;
  1.1862 +
  1.1863 +    PEP_STATUS _status = ::log_event(get_session(), _title.c_str(), _entity.c_str(), _description.c_str(), _comment.c_str());
  1.1864 +    assert(_status == PEP_STATUS_OK);
  1.1865 +    if (_status != PEP_STATUS_OK)
  1.1866 +        return FAIL(L"log_event", _status);
  1.1867 +    else
  1.1868 +        return S_OK;
  1.1869 +}
  1.1870 +
  1.1871 +STDMETHODIMP CpEpEngine::Trustwords(BSTR fpr, BSTR lang, LONG max_words, BSTR * words)
  1.1872 +{
  1.1873 +    assert(fpr);
  1.1874 +    assert(max_words >= 0);
  1.1875 +    assert(words);
  1.1876 +
  1.1877 +    HRESULT result = S_OK;
  1.1878 +
  1.1879 +    string _fpr;
  1.1880 +    if (fpr)
  1.1881 +        _fpr = utf8_string(fpr);
  1.1882 +    else
  1.1883 +        result = E_INVALIDARG;
  1.1884 +
  1.1885 +    string _lang;
  1.1886 +    if (lang) {
  1.1887 +        _lang = utf8_string(lang);
  1.1888 +        if (_lang.length()) {
  1.1889 +            if (_lang.length() != 2)
  1.1890 +                result = E_INVALIDARG;
  1.1891 +        }
  1.1892 +        else
  1.1893 +            _lang = "en";
  1.1894 +    }
  1.1895 +    else
  1.1896 +        _lang = "en";
  1.1897 +
  1.1898 +    if (max_words < 0)
  1.1899 +        result = E_INVALIDARG;
  1.1900 +
  1.1901 +    if (words == NULL)
  1.1902 +        result = E_INVALIDARG;
  1.1903 +
  1.1904 +    if (result != S_OK)
  1.1905 +        return result;
  1.1906 +
  1.1907 +    char *_words = NULL;
  1.1908 +    size_t _wsize = 0;
  1.1909 +
  1.1910 +    PEP_STATUS status = ::trustwords(get_session(), _fpr.c_str(), _lang.c_str(), &_words, &_wsize, max_words);
  1.1911 +    assert(status != PEP_OUT_OF_MEMORY);
  1.1912 +    if (status == PEP_OUT_OF_MEMORY)
  1.1913 +        return E_OUTOFMEMORY;
  1.1914 +
  1.1915 +    if (_words == NULL) {
  1.1916 +        *words = NULL;
  1.1917 +        return FAIL(L"Trustwords: _words == NULL", status);
  1.1918 +    }
  1.1919 +    else {
  1.1920 +        *words = utf16_bstr(_words);
  1.1921 +        pEp_free(_words);
  1.1922 +        return S_OK;
  1.1923 +    }
  1.1924 +}
  1.1925 +
  1.1926 +STDMETHODIMP CpEpEngine::GetTrustwords(struct pEpIdentity *id1, struct pEpIdentity *id2, BSTR lang, VARIANT_BOOL full, BSTR *words)
  1.1927 +{
  1.1928 +    assert(id1);
  1.1929 +    assert(id2);
  1.1930 +    assert(words);
  1.1931 +
  1.1932 +    if (!(id1 && id2 && words))
  1.1933 +    {
  1.1934 +        return E_INVALIDARG;
  1.1935 +    }
  1.1936 +
  1.1937 +    HRESULT result = S_OK;
  1.1938 +
  1.1939 +    pEp_identity* _id1 = NULL;
  1.1940 +    pEp_identity* _id2 = NULL;
  1.1941 +    string _lang;
  1.1942 +    *words = NULL;
  1.1943 +
  1.1944 +    try {
  1.1945 +        _id1 = new_identity(id1);
  1.1946 +        _id2 = new_identity(id2);
  1.1947 +
  1.1948 +        if (lang) {
  1.1949 +            _lang = utf8_string(lang);
  1.1950 +            if (_lang.length() == 0) {
  1.1951 +                _lang = "en";
  1.1952 +            }
  1.1953 +            else if (_lang.length() != 2) {
  1.1954 +                result = E_INVALIDARG;
  1.1955 +            }
  1.1956 +        }
  1.1957 +        else {
  1.1958 +            _lang = "en";
  1.1959 +        }
  1.1960 +    }
  1.1961 +    catch (bad_alloc&) {
  1.1962 +        result = E_OUTOFMEMORY;
  1.1963 +    }
  1.1964 +    catch (exception& ex) {
  1.1965 +        result = FAIL(ex.what());
  1.1966 +    }
  1.1967 +
  1.1968 +    char* _words;
  1.1969 +    size_t _size;
  1.1970 +    if (result == S_OK) {
  1.1971 +        auto status = ::get_trustwords(get_session(), _id1, _id2, _lang.c_str(), &_words, &_size, full != 0 /* convert variant bool to C bool */);
  1.1972 +
  1.1973 +        if (status == PEP_OUT_OF_MEMORY) {
  1.1974 +            result = E_OUTOFMEMORY;
  1.1975 +        }
  1.1976 +        else if (status == PEP_TRUSTWORD_NOT_FOUND) {
  1.1977 +            result = FAIL(L"GetTrustwords: Trustword not found", status);
  1.1978 +        }
  1.1979 +        else if (!words) {
  1.1980 +            result = FAIL(L"GetTrustwords: _words == NULL", status);
  1.1981 +        }
  1.1982 +        else {
  1.1983 +            *words = utf16_bstr(_words);
  1.1984 +            pEp_free(_words);
  1.1985 +        }
  1.1986 +    }
  1.1987 +
  1.1988 +    free_identity(_id1);
  1.1989 +    free_identity(_id2);
  1.1990 +
  1.1991 +    return result;
  1.1992 +}
  1.1993 +
  1.1994 +STDMETHODIMP CpEpEngine::GetMessageTrustwords(
  1.1995 +    /* [in] */ struct TextMessage *msg,
  1.1996 +    /* [in] */ struct pEpIdentity *receivedBy,
  1.1997 +    /* [in] */ SAFEARRAY *keylist,
  1.1998 +    /* [defaultvalue][in] */ BSTR lang,
  1.1999 +    /* [defaultvalue][in] */ VARIANT_BOOL full,
  1.2000 +    /* [retval][out] */ BSTR *words) {
  1.2001 +    assert(msg);
  1.2002 +    assert(receivedBy);
  1.2003 +    assert(words);
  1.2004 +
  1.2005 +    if (!(msg && receivedBy && words))
  1.2006 +    {
  1.2007 +        return E_INVALIDARG;
  1.2008 +    }
  1.2009 +
  1.2010 +    HRESULT result = S_OK;
  1.2011 +
  1.2012 +    pEp_identity * _received_by = NULL;
  1.2013 +    ::message * _msg = NULL;
  1.2014 +    ::stringlist_t *_keylist = NULL;
  1.2015 +    string _lang;
  1.2016 +    *words = NULL;
  1.2017 +
  1.2018 +    try {
  1.2019 +        _received_by = new_identity(receivedBy);
  1.2020 +        _msg = text_message_to_C(msg);
  1.2021 +
  1.2022 +        if (keylist) {
  1.2023 +            _keylist = new_stringlist(keylist);
  1.2024 +        }
  1.2025 +
  1.2026 +        if (lang) {
  1.2027 +            _lang = utf8_string(lang);
  1.2028 +            if (_lang.length() == 0) {
  1.2029 +                _lang = "en";
  1.2030 +            }
  1.2031 +            else if (_lang.length() != 2) {
  1.2032 +                result = E_INVALIDARG;
  1.2033 +            }
  1.2034 +        }
  1.2035 +        else {
  1.2036 +            _lang = "en";
  1.2037 +        }
  1.2038 +    }
  1.2039 +    catch (bad_alloc&) {
  1.2040 +        result = E_OUTOFMEMORY;
  1.2041 +    }
  1.2042 +    catch (exception& ex) {
  1.2043 +        result = FAIL(ex.what());
  1.2044 +    }
  1.2045 +
  1.2046 +    char* _words = NULL;
  1.2047 +    if (result == S_OK) {
  1.2048 +        auto status = ::get_message_trustwords(
  1.2049 +            get_session(),
  1.2050 +            _msg,
  1.2051 +            _keylist,
  1.2052 +            _received_by,
  1.2053 +            _lang.c_str(),
  1.2054 +            &_words,
  1.2055 +            full != 0 /* convert variant bool to C bool */);
  1.2056 +
  1.2057 +        if (status == PEP_OUT_OF_MEMORY) {
  1.2058 +            result = E_OUTOFMEMORY;
  1.2059 +        }
  1.2060 +        else if (status == PEP_TRUSTWORD_NOT_FOUND) {
  1.2061 +            result = FAIL(L"GetTrustwords: Trustword not found", status);
  1.2062 +        }
  1.2063 +        else if (!words) {
  1.2064 +            result = FAIL(L"GetTrustwords: _words == NULL", status);
  1.2065 +        }
  1.2066 +        else {
  1.2067 +            *words = utf16_bstr(_words);
  1.2068 +        }
  1.2069 +    }
  1.2070 +
  1.2071 +    ::pEp_free(_words);
  1.2072 +    ::free_message(_msg);
  1.2073 +    ::free_stringlist(_keylist);
  1.2074 +    ::free_identity(_received_by);
  1.2075 +
  1.2076 +    return result;
  1.2077 +}
  1.2078 +
  1.2079 +STDMETHODIMP CpEpEngine::GetCrashdumpLog(LONG maxlines, BSTR * log)
  1.2080 +{
  1.2081 +    // COM-18: Currently, long == int on windows, so the check
  1.2082 +    // for INT_MAX is not strictly necessary. However, the code
  1.2083 +    // might get copy-pasted to other adapters in the future,
  1.2084 +    // so safety first...
  1.2085 +    assert(maxlines >= 0 && maxlines <= INT_MAX);
  1.2086 +    assert(log);
  1.2087 +
  1.2088 +    if (!(maxlines >= 0 && maxlines <= INT_MAX && log))
  1.2089 +        return E_INVALIDARG;
  1.2090 +
  1.2091 +    char *_log;
  1.2092 +    PEP_STATUS status = ::get_crashdump_log(get_session(), (int)maxlines, &_log);
  1.2093 +    assert(status == PEP_STATUS_OK);
  1.2094 +    if (status == PEP_OUT_OF_MEMORY)
  1.2095 +        return E_OUTOFMEMORY;
  1.2096 +    if (status != PEP_STATUS_OK)
  1.2097 +        return FAIL(L"GetCrashdumpLog", status);
  1.2098 +    if (_log == NULL)
  1.2099 +        return FAIL(L"GetCrashdumpLog: _log == NULL");
  1.2100 +
  1.2101 +    *log = utf16_bstr(_log);
  1.2102 +    pEp_free(_log);
  1.2103 +    return S_OK;
  1.2104 +}
  1.2105 +
  1.2106 +STDMETHODIMP CpEpEngine::GetEngineVersion(BSTR * engine_version)
  1.2107 +{
  1.2108 +    assert(engine_version);
  1.2109 +
  1.2110 +    if (!engine_version)
  1.2111 +        return E_INVALIDARG;
  1.2112 +
  1.2113 +    const char *_engine_version = ::get_engine_version();
  1.2114 +
  1.2115 +    if (_engine_version == NULL)
  1.2116 +        return FAIL(L"GetEngineVersion: _engine_version == NULL");
  1.2117 +
  1.2118 +    *engine_version = utf16_bstr(_engine_version);
  1.2119 +
  1.2120 +    return S_OK;
  1.2121 +}
  1.2122 +
  1.2123 +STDMETHODIMP CpEpEngine::GetLanguageList(BSTR * languages)
  1.2124 +{
  1.2125 +    assert(languages);
  1.2126 +
  1.2127 +    if (!languages)
  1.2128 +        return E_INVALIDARG;
  1.2129 +
  1.2130 +    char *_languages;
  1.2131 +    PEP_STATUS status = ::get_languagelist(get_session(), &_languages);
  1.2132 +    assert(status == PEP_STATUS_OK);
  1.2133 +    if (status == PEP_OUT_OF_MEMORY)
  1.2134 +        return E_OUTOFMEMORY;
  1.2135 +    if (status != PEP_STATUS_OK)
  1.2136 +        return FAIL(L"GetLanguageList", status);
  1.2137 +    if (_languages == NULL)
  1.2138 +        return FAIL(L"GetLanguageList: _languages == NULL");
  1.2139 +
  1.2140 +    *languages = utf16_bstr(_languages);
  1.2141 +    pEp_free(_languages);
  1.2142 +    return S_OK;
  1.2143 +}
  1.2144 +
  1.2145 +STDMETHODIMP CpEpEngine::SetIdentityFlags(struct pEpIdentity *identity, pEpIdentityFlags flags)
  1.2146 +{
  1.2147 +    assert(identity);
  1.2148 +    if (!identity)
  1.2149 +        return E_INVALIDARG;
  1.2150 +
  1.2151 +    ::pEp_identity *_ident = nullptr;
  1.2152 +
  1.2153 +    try {
  1.2154 +        _ident = new_identity(identity);
  1.2155 +        assert(_ident);
  1.2156 +        if (_ident == NULL)
  1.2157 +            return E_OUTOFMEMORY;
  1.2158 +    }
  1.2159 +    catch (bad_alloc&) {
  1.2160 +        return E_OUTOFMEMORY;
  1.2161 +    }
  1.2162 +    catch (exception& ex) {
  1.2163 +        return FAIL(ex.what());;
  1.2164 +    }
  1.2165 +
  1.2166 +    PEP_STATUS status = ::set_identity_flags(get_session(), _ident, (identity_flags_t)flags);
  1.2167 +    ::free_identity(_ident);
  1.2168 +    if (status != PEP_STATUS_OK)
  1.2169 +        return FAIL(_T("SetIdentityFlags"), status);
  1.2170 +
  1.2171 +    return S_OK;
  1.2172 +}
  1.2173 +
  1.2174 +STDMETHODIMP CpEpEngine::UnsetIdentityFlags(struct pEpIdentity *identity, pEpIdentityFlags flags)
  1.2175 +{
  1.2176 +    assert(identity);
  1.2177 +    if (!identity)
  1.2178 +        return E_INVALIDARG;
  1.2179 +
  1.2180 +    ::pEp_identity *_ident = nullptr;
  1.2181 +
  1.2182 +    try {
  1.2183 +        _ident = new_identity(identity);
  1.2184 +        assert(_ident);
  1.2185 +        if (_ident == NULL)
  1.2186 +            return E_OUTOFMEMORY;
  1.2187 +    }
  1.2188 +    catch (bad_alloc&) {
  1.2189 +        return E_OUTOFMEMORY;
  1.2190 +    }
  1.2191 +    catch (exception& ex) {
  1.2192 +        return FAIL(ex.what());;
  1.2193 +    }
  1.2194 +
  1.2195 +    PEP_STATUS status = ::unset_identity_flags(get_session(), _ident, (identity_flags_t)flags);
  1.2196 +    ::free_identity(_ident);
  1.2197 +    if (status != PEP_STATUS_OK)
  1.2198 +        return FAIL(_T("UnsetIdentityFlags"), status);
  1.2199 +
  1.2200 +    return S_OK;
  1.2201 +}
  1.2202 +
  1.2203 +STDMETHODIMP CpEpEngine::StartKeyserverLookup()
  1.2204 +{
  1.2205 +    if (identity_queue.load())
  1.2206 +        return S_OK;
  1.2207 +
  1.2208 +    identity_queue.store(new identity_queue_t());
  1.2209 +    keymanagement_thread = new thread(::do_keymanagement, retrieve_next_identity, (void *)identity_queue.load());
  1.2210 +
  1.2211 +    return S_OK;
  1.2212 +}
  1.2213 +
  1.2214 +STDMETHODIMP CpEpEngine::StopKeyserverLookup()
  1.2215 +{
  1.2216 +    if (identity_queue.load() == NULL)
  1.2217 +        return S_OK;
  1.2218 +
  1.2219 +    identity_queue_t *_iq = identity_queue.load();
  1.2220 +    identity_queue.store(NULL);
  1.2221 +
  1.2222 +    pEp_identity_cpp shutdown;
  1.2223 +    _iq->push_front(shutdown);
  1.2224 +
  1.2225 +    keymanagement_thread->join();
  1.2226 +    delete keymanagement_thread;
  1.2227 +    keymanagement_thread = NULL;
  1.2228 +
  1.2229 +    delete _iq;
  1.2230 +
  1.2231 +    return S_OK;
  1.2232 +}
  1.2233 +
  1.2234 +STDMETHODIMP CpEpEngine::Myself(struct pEpIdentity *ident, struct pEpIdentity *result)
  1.2235 +{
  1.2236 +    assert(ident);
  1.2237 +    assert(result);
  1.2238 +
  1.2239 +    if (!(ident && result))
  1.2240 +        return E_INVALIDARG;
  1.2241 +
  1.2242 +    ::pEp_identity *_ident = 0;
  1.2243 +
  1.2244 +    try {
  1.2245 +        _ident = new_identity(ident);
  1.2246 +        assert(_ident);
  1.2247 +        if (_ident == NULL)
  1.2248 +            return E_OUTOFMEMORY;
  1.2249 +    }
  1.2250 +    catch (bad_alloc&) {
  1.2251 +        return E_OUTOFMEMORY;
  1.2252 +    }
  1.2253 +    catch (exception& ex) {
  1.2254 +        return FAIL(ex.what());;
  1.2255 +    }
  1.2256 +
  1.2257 +
  1.2258 +    // DEBUG CODE - REMOVE BEFORE RELEASE!
  1.2259 +    // SyncHandshakeResult handshakeResult;
  1.2260 +    //
  1.2261 +    // HRESULT res = Fire_NotifyHandshake(ident, result, signal, &handshakeResult);
  1.2262 +    // 
  1.2263 +    // HRESULT res2 = Fire_TestEvent(15, _bstr_t( "hallo"));
  1.2264 +
  1.2265 +    PEP_STATUS status = ::myself(get_session(), _ident);
  1.2266 +
  1.2267 +    if (status == PEP_STATUS_OK) {
  1.2268 +        assert(_ident->fpr);
  1.2269 +        copy_identity(result, _ident);
  1.2270 +        ::free_identity(_ident);
  1.2271 +        return S_OK;
  1.2272 +    }
  1.2273 +    else {
  1.2274 +        ::free_identity(_ident);
  1.2275 +        if (status == PEP_OUT_OF_MEMORY)
  1.2276 +            return E_OUTOFMEMORY;
  1.2277 +        else
  1.2278 +            return FAIL(L"myself", status);
  1.2279 +    }
  1.2280 +}
  1.2281 +
  1.2282 +STDMETHODIMP CpEpEngine::UpdateIdentity(struct pEpIdentity *ident, struct pEpIdentity *result)
  1.2283 +{
  1.2284 +    assert(ident);
  1.2285 +    assert(result);
  1.2286 +
  1.2287 +    if (!(ident && result))
  1.2288 +        return E_INVALIDARG;
  1.2289 +
  1.2290 +    ::pEp_identity *_ident;
  1.2291 +    try {
  1.2292 +        _ident = new_identity(ident);
  1.2293 +    }
  1.2294 +    catch (bad_alloc&) {
  1.2295 +        return E_OUTOFMEMORY;
  1.2296 +    }
  1.2297 +    catch (exception& ex) {
  1.2298 +        return FAIL(ex.what());
  1.2299 +    }
  1.2300 +
  1.2301 +    assert(_ident);
  1.2302 +    if (_ident == NULL)
  1.2303 +        return E_OUTOFMEMORY;
  1.2304 +
  1.2305 +    PEP_STATUS status = ::update_identity(get_session(), _ident);
  1.2306 +
  1.2307 +    if (status == PEP_STATUS_OK) {
  1.2308 +        copy_identity(result, _ident);
  1.2309 +        ::free_identity(_ident);
  1.2310 +        return S_OK;
  1.2311 +    }
  1.2312 +    else if (status == PEP_GET_KEY_FAILED || status == PEP_KEY_NOT_FOUND) {
  1.2313 +        if (_ident->fpr) {
  1.2314 +            pEp_free(_ident->fpr);
  1.2315 +            _ident->fpr = NULL;
  1.2316 +        }
  1.2317 +        copy_identity(result, _ident);
  1.2318 +        result->Fpr = NULL;
  1.2319 +        ::free_identity(_ident);
  1.2320 +        return S_OK;
  1.2321 +    }
  1.2322 +    else {
  1.2323 +        ::free_identity(_ident);
  1.2324 +        if (status == PEP_OUT_OF_MEMORY)
  1.2325 +            return E_OUTOFMEMORY;
  1.2326 +        else
  1.2327 +            return FAIL(L"UpdateIdentity", status);
  1.2328 +    }
  1.2329 +}
  1.2330 +
  1.2331 +STDMETHODIMP CpEpEngine::KeyMistrusted(struct pEpIdentity *ident)
  1.2332 +{
  1.2333 +    ::pEp_identity *_ident;
  1.2334 +
  1.2335 +    assert(ident);
  1.2336 +    if (!ident)
  1.2337 +        return E_INVALIDARG;
  1.2338 +
  1.2339 +    try {
  1.2340 +        _ident = new_identity(ident);
  1.2341 +    }
  1.2342 +    catch (bad_alloc&) {
  1.2343 +        return E_OUTOFMEMORY;
  1.2344 +    }
  1.2345 +    catch (exception& ex) {
  1.2346 +        return FAIL(ex.what());;
  1.2347 +    }
  1.2348 +
  1.2349 +    PEP_STATUS status = ::key_mistrusted(get_session(), _ident);
  1.2350 +    free_identity(_ident);
  1.2351 +
  1.2352 +    if (status == PEP_OUT_OF_MEMORY)
  1.2353 +        return E_OUTOFMEMORY;
  1.2354 +
  1.2355 +    if (status == PEP_KEY_NOT_FOUND)
  1.2356 +        return FAIL(L"key not found");
  1.2357 +
  1.2358 +    if (status != ::PEP_STATUS_OK)
  1.2359 +        return FAIL(L"cannot revoke compromized key", status);
  1.2360 +
  1.2361 +    return S_OK;
  1.2362 +}
  1.2363 +
  1.2364 +STDMETHODIMP CpEpEngine::UndoLastMistrust()
  1.2365 +{
  1.2366 +    PEP_STATUS status = ::undo_last_mistrust(get_session());
  1.2367 +
  1.2368 +    if (status == PEP_CANNOT_FIND_IDENTITY)
  1.2369 +        return FAIL(L"Cannot find identity!", status);
  1.2370 +
  1.2371 +    if (status != ::PEP_STATUS_OK)
  1.2372 +        return FAIL(L"cannot revoke compromized key", status);
  1.2373 +
  1.2374 +    return S_OK;
  1.2375 +}
  1.2376 +
  1.2377 +STDMETHODIMP CpEpEngine::IsPepUser(/* [in] */ struct pEpIdentity *ident, /* [retval][out] */ VARIANT_BOOL *ispEp) 
  1.2378 +{
  1.2379 +    ::pEp_identity *_ident;
  1.2380 +
  1.2381 +    assert(ident);
  1.2382 +    if (!ident)
  1.2383 +        return E_INVALIDARG;
  1.2384 +
  1.2385 +    try {
  1.2386 +        _ident = new_identity(ident);
  1.2387 +    }
  1.2388 +    catch (bad_alloc&) {
  1.2389 +        return E_OUTOFMEMORY;
  1.2390 +    }
  1.2391 +    catch (exception& ex) {
  1.2392 +        return FAIL(ex.what());;
  1.2393 +    }
  1.2394 +
  1.2395 +    bool is_pep = FALSE;
  1.2396 +    PEP_STATUS status = ::is_pep_user(get_session(), _ident, &is_pep);
  1.2397 +
  1.2398 +    *ispEp = is_pep;
  1.2399 +
  1.2400 +    if (status == PEP_CANNOT_FIND_PERSON)
  1.2401 +        return FAIL(L"Cannot find identity!", status);
  1.2402 +
  1.2403 +    if (status == PEP_ILLEGAL_VALUE)
  1.2404 +        return E_INVALIDARG;
  1.2405 +
  1.2406 +    if (status != ::PEP_STATUS_OK)
  1.2407 +        return FAIL(L"Engine is_pep_user returned error", status);
  1.2408 +
  1.2409 +    return S_OK;
  1.2410 +}
  1.2411 +
  1.2412 +STDMETHODIMP CpEpEngine::KeyResetTrust(struct pEpIdentity *ident)
  1.2413 +{
  1.2414 +    ::pEp_identity *_ident;
  1.2415 +
  1.2416 +    assert(ident);
  1.2417 +
  1.2418 +    if (!ident)
  1.2419 +        return E_INVALIDARG;
  1.2420 +
  1.2421 +    try {
  1.2422 +        _ident = new_identity(ident);
  1.2423 +    }
  1.2424 +    catch (bad_alloc&) {
  1.2425 +        return E_OUTOFMEMORY;
  1.2426 +    }
  1.2427 +    catch (exception& ex) {
  1.2428 +        return FAIL(ex.what());;
  1.2429 +    }
  1.2430 +
  1.2431 +    PEP_STATUS status = ::key_reset_trust(get_session(), _ident);
  1.2432 +    free_identity(_ident);
  1.2433 +
  1.2434 +    if (status == PEP_OUT_OF_MEMORY)
  1.2435 +        return E_OUTOFMEMORY;
  1.2436 +
  1.2437 +    if (status == PEP_KEY_NOT_FOUND)
  1.2438 +        return FAIL(L"key not found");
  1.2439 +
  1.2440 +    if (status != ::PEP_STATUS_OK)
  1.2441 +        return FAIL(L"cannot reset trust", status);
  1.2442 +
  1.2443 +    return S_OK;
  1.2444 +}
  1.2445 +
  1.2446 +int CpEpEngine::examine_identity(pEp_identity *ident, void *management)
  1.2447 +{
  1.2448 +    assert(ident);
  1.2449 +    assert(management);
  1.2450 +    if (!(ident && management))
  1.2451 +        return -1;
  1.2452 +
  1.2453 +    CpEpEngine *me = (CpEpEngine *)management;
  1.2454 +
  1.2455 +    if (me->identity_queue.load() == NULL)
  1.2456 +        return 0;
  1.2457 +
  1.2458 +    try {
  1.2459 +        me->identity_queue.load()->push_back(ident);
  1.2460 +    }
  1.2461 +    catch (exception&) {
  1.2462 +        return -1;
  1.2463 +    }
  1.2464 +
  1.2465 +    return 0;
  1.2466 +}
  1.2467 +
  1.2468 +::pEp_identity * CpEpEngine::retrieve_next_identity(void *management)
  1.2469 +{
  1.2470 +    assert(management);
  1.2471 +    if (!management)
  1.2472 +        return NULL;
  1.2473 +
  1.2474 +    identity_queue_t *iq = (identity_queue_t *)management;
  1.2475 +
  1.2476 +    do /* poll queue */ {
  1.2477 +        if (iq->size())
  1.2478 +            break;
  1.2479 +        ::Sleep(100);
  1.2480 +    } while (true);
  1.2481 +
  1.2482 +    ::pEp_identity *_ident;
  1.2483 +    pEp_identity_cpp& ident = iq->front();
  1.2484 +
  1.2485 +    if (ident.address.size() == 0)
  1.2486 +        return NULL;
  1.2487 +
  1.2488 +    _ident = ident.to_pEp_identity();
  1.2489 +    iq->pop_front();
  1.2490 +
  1.2491 +    return _ident;
  1.2492 +}
  1.2493 +
  1.2494 +PEP_STATUS CpEpEngine::messageToSend(void * obj, message *msg)
  1.2495 +{
  1.2496 +    assert(msg);
  1.2497 +    assert(obj);
  1.2498 +    if (!(msg && obj))
  1.2499 +        return PEP_ILLEGAL_VALUE;
  1.2500 +
  1.2501 +    TextMessage _msg;
  1.2502 +    memset(&_msg, 0, sizeof(TextMessage));
  1.2503 +
  1.2504 +    text_message_from_C(&_msg, msg);
  1.2505 +    CpEpEngine *me = (CpEpEngine *)obj;
  1.2506 +    HRESULT r = me->Fire_MessageToSend(&_msg);
  1.2507 +    assert(r == S_OK);
  1.2508 +    clear_text_message(&_msg);
  1.2509 +    if (r == E_OUTOFMEMORY)
  1.2510 +        return PEP_OUT_OF_MEMORY;
  1.2511 +    if (r != S_OK)
  1.2512 +        return PEP_UNKNOWN_ERROR;
  1.2513 +
  1.2514 +    return PEP_STATUS_OK;
  1.2515 +}
  1.2516 +
  1.2517 +STDMETHODIMP CpEpEngine::BlacklistAdd(BSTR fpr)
  1.2518 +{
  1.2519 +    assert(fpr);
  1.2520 +    if (!fpr)
  1.2521 +        return E_INVALIDARG;
  1.2522 +
  1.2523 +    string _fpr = utf8_string(fpr);
  1.2524 +    PEP_STATUS status = ::blacklist_add(get_session(), _fpr.c_str());
  1.2525 +    assert(status == PEP_STATUS_OK);
  1.2526 +    if (status != PEP_STATUS_OK)
  1.2527 +        return FAIL(L"blacklist_add failed in pEp engine", status);
  1.2528 +
  1.2529 +    return S_OK;
  1.2530 +}
  1.2531 +
  1.2532 +STDMETHODIMP CpEpEngine::BlacklistDelete(BSTR fpr)
  1.2533 +{
  1.2534 +    assert(fpr);
  1.2535 +    if (!fpr)
  1.2536 +        return E_INVALIDARG;
  1.2537 +
  1.2538 +    string _fpr = utf8_string(fpr);
  1.2539 +    PEP_STATUS status = ::blacklist_delete(get_session(), _fpr.c_str());
  1.2540 +    assert(status == PEP_STATUS_OK);
  1.2541 +    if (status != PEP_STATUS_OK)
  1.2542 +        return FAIL(L"blacklist_delete failed in pEp engine", status);
  1.2543 +
  1.2544 +    return S_OK;
  1.2545 +}
  1.2546 +
  1.2547 +STDMETHODIMP CpEpEngine::BlacklistIsListed(BSTR fpr, VARIANT_BOOL *listed)
  1.2548 +{
  1.2549 +    assert(fpr);
  1.2550 +    assert(listed);
  1.2551 +
  1.2552 +    if (!(fpr && listed))
  1.2553 +        return E_INVALIDARG;
  1.2554 +
  1.2555 +    string _fpr = utf8_string(fpr);
  1.2556 +    bool result;
  1.2557 +    PEP_STATUS status = ::blacklist_is_listed(get_session(), _fpr.c_str(), &result);
  1.2558 +    assert(status == PEP_STATUS_OK);
  1.2559 +    if (status != PEP_STATUS_OK)
  1.2560 +        return FAIL(L"blacklist_is_listed failed in pEp engine", status);
  1.2561 +
  1.2562 +    *listed = result ? VARIANT_TRUE : VARIANT_FALSE;
  1.2563 +    return S_OK;
  1.2564 +}
  1.2565 +
  1.2566 +STDMETHODIMP CpEpEngine::BlacklistRetrieve(SAFEARRAY **blacklist)
  1.2567 +{
  1.2568 +    assert(blacklist);
  1.2569 +
  1.2570 +    if (!blacklist)
  1.2571 +        return E_INVALIDARG;
  1.2572 +
  1.2573 +    ::stringlist_t *_blacklist = NULL;
  1.2574 +    PEP_STATUS status = ::blacklist_retrieve(get_session(), &_blacklist);
  1.2575 +    assert(status == PEP_STATUS_OK);
  1.2576 +    if (status != PEP_STATUS_OK)
  1.2577 +        return FAIL(L"blacklist_retrieve failed in pEp engine", status);
  1.2578 +    assert(_blacklist);
  1.2579 +
  1.2580 +    *blacklist = string_array(_blacklist);
  1.2581 +    ::free_stringlist(_blacklist);
  1.2582 +    return S_OK;
  1.2583 +}
  1.2584 +
  1.2585 +HRESULT CpEpEngine::error(_bstr_t msg)
  1.2586 +{
  1.2587 +    _bstr_t helpFile = L"";
  1.2588 +    _bstr_t source = L"pEp COM Adapter";
  1.2589 +
  1.2590 +    ICreateErrorInfo *cei;
  1.2591 +    if (SUCCEEDED(CreateErrorInfo(&cei))) {
  1.2592 +        cei->SetDescription(msg);
  1.2593 +        cei->SetGUID(__uuidof(IpEpEngine));
  1.2594 +        cei->SetHelpContext(0);
  1.2595 +        cei->SetHelpFile(helpFile);
  1.2596 +        cei->SetSource(source);
  1.2597 +
  1.2598 +        IErrorInfo *errinfo;
  1.2599 +        if (SUCCEEDED(cei->QueryInterface(IID_IErrorInfo, (LPVOID FAR*) &errinfo))) {
  1.2600 +            SetErrorInfo(0, errinfo);
  1.2601 +            errinfo->Release();
  1.2602 +        }
  1.2603 +        cei->Release();
  1.2604 +    }
  1.2605 +    return E_FAIL;
  1.2606 +}
  1.2607 +
  1.2608 +HRESULT CpEpEngine::error(_bstr_t msg, PEP_STATUS status)
  1.2609 +{
  1.2610 +    std::stringstream stream;
  1.2611 +    stream << msg;
  1.2612 +    stream << ": ";
  1.2613 +    stream << std::hex << status;
  1.2614 +
  1.2615 +    error(stream.str().c_str());
  1.2616 +
  1.2617 +    if (status == ::PEP_OUT_OF_MEMORY)
  1.2618 +        return E_OUTOFMEMORY;
  1.2619 +
  1.2620 +    return MAKE_HRESULT(1, FACILITY_ITF, (0xFFFF & status));
  1.2621 +}
  1.2622 +
  1.2623 +STDMETHODIMP CpEpEngine::EncryptMessage(TextMessage * src, TextMessage * dst, SAFEARRAY * extra, pEpEncryptFlags flags, pEpEncFormat encFormat)
  1.2624 +{
  1.2625 +    assert(src);
  1.2626 +    assert(dst);
  1.2627 +
  1.2628 +    if (!(src && dst))
  1.2629 +        return E_INVALIDARG;
  1.2630 +
  1.2631 +    ::message *_src = text_message_to_C(src);
  1.2632 +
  1.2633 +    _PEP_enc_format _encFormat = (_PEP_enc_format)encFormat;
  1.2634 +
  1.2635 +    // COM-19: Initialize msg_dst to NULL, or we end up calling
  1.2636 +    // free_message() below with a pointer to random garbage in
  1.2637 +    // case of an error in encrypt_message().
  1.2638 +    ::message *msg_dst = NULL;
  1.2639 +    ::stringlist_t *_extra = new_stringlist(extra); // can cope with NULL
  1.2640 +
  1.2641 +    // _PEP_enc_format used to be intentionally hardcoded to PEP_enc_PEP:
  1.2642 +    // Since COM-74, this has been changed to an explicit parameter, to allow the engine to attach
  1.2643 +    // the keys and headers to outgoing, unencrypted messages.
  1.2644 +    PEP_encrypt_flags_t engineFlags = (PEP_encrypt_flags_t)flags;
  1.2645 +    PEP_STATUS status = ::encrypt_message(get_session(), _src, _extra, &msg_dst, _encFormat, engineFlags);
  1.2646 +    ::free_stringlist(_extra);
  1.2647 +
  1.2648 +    if (status == PEP_STATUS_OK)
  1.2649 +        text_message_from_C(dst, msg_dst);
  1.2650 +    else
  1.2651 +        text_message_from_C(dst, _src);
  1.2652 +
  1.2653 +    ::free_message(msg_dst);
  1.2654 +    ::free_message(_src);
  1.2655 +
  1.2656 +    if (status == PEP_OUT_OF_MEMORY)
  1.2657 +        return E_OUTOFMEMORY;
  1.2658 +
  1.2659 +    // COM-41: Enhanced PEP status handling
  1.2660 +    if ((status != PEP_STATUS_OK) && (status < PEP_UNENCRYPTED || status >= PEP_TRUSTWORD_NOT_FOUND))
  1.2661 +        return FAIL("Failure to encrypt message", status);
  1.2662 +
  1.2663 +    // Statii like PEP_UNENCRYPTED due to no private key
  1.2664 +    // should not be a catastrophic failure here. Using S_FALSE
  1.2665 +    // still allows clients to differentiate with S_OK,
  1.2666 +    // although this does not work out of the box with
  1.2667 +    // the standard .NET mapping of COM.
  1.2668 +    if (status != PEP_STATUS_OK)
  1.2669 +        return S_FALSE;
  1.2670 +
  1.2671 +    return S_OK;
  1.2672 +}
  1.2673 +
  1.2674 +STDMETHODIMP CpEpEngine::EncryptMessageForSelf(pEpIdentity * targetId, TextMessage * src,
  1.2675 +    /* [in] */ SAFEARRAY *extra, TextMessage * dst, pEpEncryptFlags flags)
  1.2676 +{
  1.2677 +    assert(targetId);
  1.2678 +    assert(src);
  1.2679 +    assert(dst);
  1.2680 +
  1.2681 +    if (!(targetId && src && dst))
  1.2682 +        return E_INVALIDARG;
  1.2683 +
  1.2684 +    PEP_encrypt_flags_t engineFlags = (PEP_encrypt_flags_t)flags;
  1.2685 +
  1.2686 +    ::pEp_identity *_target_id = new_identity(targetId);
  1.2687 +
  1.2688 +    ::message *_src = text_message_to_C(src);
  1.2689 +
  1.2690 +    ::stringlist_t* _extra = NULL;
  1.2691 +    HRESULT result = S_OK;
  1.2692 +    ::message *msg_dst = NULL;
  1.2693 +    PEP_STATUS status = PEP_STATUS_OK;
  1.2694 +
  1.2695 +    try {
  1.2696 +        if (extra) {
  1.2697 +            _extra = new_stringlist(extra);
  1.2698 +        }
  1.2699 +
  1.2700 +        // COM-19: Initialize msg_dst to NULL, or we end up calling
  1.2701 +        // free_message() below with a pointer to random garbage in
  1.2702 +        // case of an error in encrypt_message_for_self().
  1.2703 +        status = ::encrypt_message_for_self(get_session(), _target_id, _src, _extra, &msg_dst, PEP_enc_PEP, engineFlags);
  1.2704 +
  1.2705 +        if (status == PEP_STATUS_OK)
  1.2706 +            text_message_from_C(dst, msg_dst);
  1.2707 +        else
  1.2708 +            text_message_from_C(dst, _src);
  1.2709 +    } catch (bad_alloc&) {
  1.2710 +        result = E_OUTOFMEMORY;
  1.2711 +    }
  1.2712 +    catch (exception& ex) {
  1.2713 +        result = FAIL(ex.what());
  1.2714 +    }
  1.2715 +
  1.2716 +    ::free_message(msg_dst);
  1.2717 +    ::free_message(_src);
  1.2718 +    ::free_identity(_target_id);
  1.2719 +    ::free_stringlist(_extra);
  1.2720 +
  1.2721 +    if (status == PEP_OUT_OF_MEMORY)
  1.2722 +        return E_OUTOFMEMORY;
  1.2723 +
  1.2724 +    // Different to encrypt_message, this should never fail (we ought to always
  1.2725 +    // have a private key for ourself).#
  1.2726 +    if (status != PEP_STATUS_OK)
  1.2727 +        return FAIL("Failure to encrypt message", status);
  1.2728 +
  1.2729 +    return result;
  1.2730 +}
  1.2731 +
  1.2732 +STDMETHODIMP CpEpEngine::DecryptMessage(TextMessage * src, TextMessage * dst, SAFEARRAY ** keylist, pEpDecryptFlags *flags, pEpRating *rating)
  1.2733 +{
  1.2734 +    assert(src);
  1.2735 +    assert(dst);
  1.2736 +    assert(keylist);
  1.2737 +    assert(flags);
  1.2738 +    assert(rating);
  1.2739 +
  1.2740 +    if (!(src && dst && keylist && flags && rating))
  1.2741 +        return E_INVALIDARG;
  1.2742 +
  1.2743 +    *keylist = NULL;
  1.2744 +    *rating = pEpRatingUndefined;
  1.2745 +
  1.2746 +    ::message *_src = text_message_to_C(src);
  1.2747 +    ::message *msg_dst = NULL;
  1.2748 +    ::stringlist_t *_keylist = NULL;
  1.2749 +    ::PEP_rating _rating;
  1.2750 +
  1.2751 +    PEP_decrypt_flags_t engineflags = (PEP_decrypt_flags_t) *flags;
  1.2752 +    PEP_STATUS status = ::decrypt_message(get_session(), _src, &msg_dst, &_keylist, &_rating, &engineflags);
  1.2753 +
  1.2754 +    *flags = (pEpDecryptFlags)engineflags;
  1.2755 +
  1.2756 +    if (engineflags && PEP_decrypt_flag_src_modified)
  1.2757 +        text_message_from_C(src, _src);
  1.2758 +
  1.2759 +    if (msg_dst)
  1.2760 +        text_message_from_C(dst, msg_dst);
  1.2761 +
  1.2762 +    ::free_message(_src);
  1.2763 +    ::free_message(msg_dst);
  1.2764 +
  1.2765 +    if (_keylist) {
  1.2766 +        *keylist = string_array(_keylist);
  1.2767 +        free_stringlist(_keylist);
  1.2768 +    }
  1.2769 +
  1.2770 +    *rating = (pEpRating)_rating;
  1.2771 +
  1.2772 +    return S_OK;
  1.2773 +}
  1.2774 +
  1.2775 +STDMETHODIMP CpEpEngine::ReEvaluateMessageRating(TextMessage * msg, SAFEARRAY * x_KeyList, pEpRating x_EncStatus, pEpRating *rating)
  1.2776 +{
  1.2777 +    assert(msg);
  1.2778 +    assert(x_EncStatus != PEP_rating_undefined);
  1.2779 +    assert(rating);
  1.2780 +
  1.2781 +    if (!(msg && x_EncStatus != PEP_rating_undefined && rating))
  1.2782 +        return E_INVALIDARG;
  1.2783 +
  1.2784 +    *rating = pEpRatingUndefined;
  1.2785 +
  1.2786 +    ::message *_msg = text_message_to_C(msg);
  1.2787 +    ::stringlist_t *_keylist = new_stringlist(x_KeyList);
  1.2788 +    ::PEP_rating _rating = PEP_rating_undefined;
  1.2789 +
  1.2790 +    PEP_STATUS status = ::re_evaluate_message_rating(get_session(), _msg, _keylist, (PEP_rating)x_EncStatus, &_rating);
  1.2791 +
  1.2792 +    ::free_stringlist(_keylist);
  1.2793 +    ::free_message(_msg);
  1.2794 +
  1.2795 +    *rating = (pEpRating)_rating;
  1.2796 +
  1.2797 +    return S_OK;
  1.2798 +}
  1.2799 +
  1.2800 +STDMETHODIMP CpEpEngine::OutgoingMessageRating(TextMessage *msg, pEpRating * pVal)
  1.2801 +{
  1.2802 +    assert(msg);
  1.2803 +    assert(pVal);
  1.2804 +
  1.2805 +    if (!(msg  && pVal))
  1.2806 +        return E_INVALIDARG;
  1.2807 +
  1.2808 +    ::message *_msg = text_message_to_C(msg);
  1.2809 +
  1.2810 +    PEP_rating _rating;
  1.2811 +    PEP_STATUS status = ::outgoing_message_rating(get_session(), _msg, &_rating);
  1.2812 +    if (status != PEP_STATUS_OK)
  1.2813 +        return FAIL(L"cannot get message rating", status);
  1.2814 +
  1.2815 +    *pVal = (pEpRating)_rating;
  1.2816 +    return S_OK;
  1.2817 +}
  1.2818 +
  1.2819 +STDMETHODIMP CpEpEngine::IdentityRating(struct pEpIdentity *ident, pEpRating * pVal)
  1.2820 +{
  1.2821 +    ::pEp_identity *_ident;
  1.2822 +
  1.2823 +    assert(ident);
  1.2824 +    assert(pVal);
  1.2825 +
  1.2826 +    if (!(ident  && pVal))
  1.2827 +        return E_INVALIDARG;
  1.2828 +
  1.2829 +    try {
  1.2830 +        _ident = new_identity(ident);
  1.2831 +    }
  1.2832 +    catch (bad_alloc&) {
  1.2833 +        return E_OUTOFMEMORY;
  1.2834 +    }
  1.2835 +    catch (exception& ex) {
  1.2836 +        return FAIL(ex.what());;
  1.2837 +    }
  1.2838 +
  1.2839 +    PEP_rating _rating;
  1.2840 +    PEP_STATUS status = ::identity_rating(get_session(), _ident, &_rating);
  1.2841 +    free_identity(_ident);
  1.2842 +
  1.2843 +    if (status != PEP_STATUS_OK)
  1.2844 +        return FAIL(L"cannot get message color", status);
  1.2845 +
  1.2846 +    *pVal = (pEpRating)_rating;
  1.2847 +    return S_OK;
  1.2848 +}
  1.2849 +
  1.2850 +STDMETHODIMP CpEpEngine::ColorFromRating(pEpRating rating, pEpColor * pVal)
  1.2851 +{
  1.2852 +    assert(pVal);
  1.2853 +
  1.2854 +    if (!pVal)
  1.2855 +        return E_INVALIDARG;
  1.2856 +
  1.2857 +    PEP_rating engineRating = (PEP_rating)rating;
  1.2858 +    PEP_color _color = ::color_from_rating(engineRating);
  1.2859 +
  1.2860 +    *pVal = (pEpColor)_color;
  1.2861 +
  1.2862 +    return S_OK;
  1.2863 +}
  1.2864 +
  1.2865 +STDMETHODIMP CpEpEngine::OwnIdentitiesRetrieve(LPSAFEARRAY* ownIdentities)
  1.2866 +{
  1.2867 +    assert(ownIdentities);
  1.2868 +    if (!ownIdentities)
  1.2869 +        return E_INVALIDARG;
  1.2870 +
  1.2871 +    *ownIdentities = nullptr;
  1.2872 +
  1.2873 +    ::identity_list *il = nullptr;
  1.2874 +    PEP_STATUS status = ::own_identities_retrieve(get_session(), &il);
  1.2875 +    if (status == PEP_OUT_OF_MEMORY) {
  1.2876 +        return E_OUTOFMEMORY;
  1.2877 +    }
  1.2878 +    else if (status != PEP_STATUS_OK)
  1.2879 +    {
  1.2880 +        return FAIL(_T("OwnIdentitiesRetrieve"), status);
  1.2881 +    }
  1.2882 +
  1.2883 +    SAFEARRAY * _own_identities = nullptr;
  1.2884 +    try {
  1.2885 +        _own_identities = array_from_C<pEpIdentity, identity_list>(il);
  1.2886 +    }
  1.2887 +    catch (exception& ex)
  1.2888 +    {
  1.2889 +        ::free_identity_list(il);
  1.2890 +        try {
  1.2891 +            dynamic_cast<bad_alloc&>(ex);
  1.2892 +        }
  1.2893 +        catch (bad_cast&)
  1.2894 +        {
  1.2895 +            return FAIL(ex.what());
  1.2896 +        }
  1.2897 +        return E_OUTOFMEMORY;
  1.2898 +    }
  1.2899 +    free_identity_list(il);
  1.2900 +
  1.2901 +    *ownIdentities = _own_identities;
  1.2902 +    return S_OK;
  1.2903 +}
  1.2904 +
  1.2905 +STDMETHODIMP CpEpEngine::TrustPersonalKey(struct pEpIdentity *ident, struct pEpIdentity *result)
  1.2906 +{
  1.2907 +    ::pEp_identity *_ident;
  1.2908 +
  1.2909 +    assert(ident);
  1.2910 +    assert(result);
  1.2911 +
  1.2912 +    if (!ident || !result)
  1.2913 +        return E_INVALIDARG;
  1.2914 +
  1.2915 +    try {
  1.2916 +        _ident = new_identity(ident);
  1.2917 +    }
  1.2918 +    catch (bad_alloc&) {
  1.2919 +        return E_OUTOFMEMORY;
  1.2920 +    }
  1.2921 +    catch (exception& ex) {
  1.2922 +        return FAIL(ex.what());;
  1.2923 +    }
  1.2924 +
  1.2925 +    if (verbose_mode) {
  1.2926 +        stringstream ss;
  1.2927 +        ss << "TrustPersonalKey called with ";
  1.2928 +        ss << utf8_string(ident->Address);
  1.2929 +        ss << L": ";
  1.2930 +        ss << ident->CommType;
  1.2931 +        verbose(ss.str());
  1.2932 +    }
  1.2933 +
  1.2934 +    PEP_STATUS status = ::trust_personal_key(get_session(), _ident);
  1.2935 +
  1.2936 +    if (verbose_mode) {
  1.2937 +        stringstream ss;
  1.2938 +        ss << "result ";
  1.2939 +        ss << status;
  1.2940 +        ss << " for ";
  1.2941 +        ss << _ident->address;
  1.2942 +        ss << L": ";
  1.2943 +        ss << _ident->comm_type;
  1.2944 +        verbose(ss.str());
  1.2945 +    }
  1.2946 +
  1.2947 +    if (status == PEP_STATUS_OK)
  1.2948 +        copy_identity(result, _ident);
  1.2949 +
  1.2950 +    free_identity(_ident);
  1.2951 +    if (status == PEP_OUT_OF_MEMORY)
  1.2952 +        return E_OUTOFMEMORY;
  1.2953 +    else if (status != PEP_STATUS_OK)
  1.2954 +        return FAIL(L"failure while executing TrustPersonalKey()", status);
  1.2955 +
  1.2956 +    return S_OK;
  1.2957 +}
  1.2958 +
  1.2959 +// keysync api
  1.2960 +
  1.2961 +void CpEpEngine::start_keysync()
  1.2962 +{
  1.2963 +    // acquire the lock
  1.2964 +    std::unique_lock<std::recursive_mutex> lock(keysync_mutex);
  1.2965 +
  1.2966 +    // Assert if we're not already running.
  1.2967 +    assert(!this->keysync_thread);
  1.2968 +
  1.2969 +    // Ensure we are not aborting the new thread due to a
  1.2970 +    // left over flag.
  1.2971 +    keysync_abort_requested = false;
  1.2972 +
  1.2973 +    // Init our keysync session
  1.2974 +    { // begin lock scope
  1.2975 +        std::lock_guard<std::mutex> lock(init_mutex);
  1.2976 +        PEP_STATUS status = ::init(&keysync_session);
  1.2977 +        ::register_sync_callbacks(keysync_session, (void*)this, messageToSend, notifyHandshake, inject_sync_msg, retrieve_next_sync_msg);
  1.2978 +        assert(status == PEP_STATUS_OK);
  1.2979 +    } // end lock scope
  1.2980 +
  1.2981 +    attach_sync_session(get_session(), keysync_session);
  1.2982 +
  1.2983 +    // We need to marshal the callbacks to the keysync thread
  1.2984 +    LPSTREAM marshaled_callbacks;
  1.2985 +
  1.2986 +    auto result = CoMarshalInterThreadInterfaceInStream(IID_IpEpEngineCallbacks, client_callbacks, &marshaled_callbacks);
  1.2987 +    assert(result == S_OK);
  1.2988 +
  1.2989 +    // Star the keysync thread
  1.2990 +    keysync_thread = new thread(do_keysync_in_thread, this, marshaled_callbacks);
  1.2991 +}
  1.2992 +
  1.2993 +void CpEpEngine::do_keysync_in_thread(CpEpEngine* self, LPSTREAM marshaled_callbacks)
  1.2994 +{
  1.2995 +    assert(self);
  1.2996 +    assert(marshaled_callbacks);
  1.2997 +
  1.2998 +    // We need to initialize COM here for successfull delivery of the callbacks.
  1.2999 +    // As we don't create any COM instances in our thread, the COMINIT value is
  1.3000 +    // currently irrelevant, so we go with the safest value.
  1.3001 +    auto res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  1.3002 +    assert(res == S_OK);
  1.3003 +
  1.3004 +    LPVOID vp;
  1.3005 +
  1.3006 +    res = CoGetInterfaceAndReleaseStream(marshaled_callbacks, IID_IpEpEngineCallbacks, &vp);
  1.3007 +    assert(SUCCEEDED(res));
  1.3008 +
  1.3009 +    self->client_last_signalled_polling_state = false;
  1.3010 +    self->client_callbacks_on_sync_thread = static_cast<IpEpEngineCallbacks*>(vp);
  1.3011 +
  1.3012 +    ::do_sync_protocol(self->keysync_session, self);
  1.3013 +
  1.3014 +    self->client_callbacks_on_sync_thread->Release();
  1.3015 +
  1.3016 +    self->client_callbacks_on_sync_thread = NULL;
  1.3017 +
  1.3018 +    CoUninitialize();
  1.3019 +}
  1.3020 +
  1.3021 +void CpEpEngine::stop_keysync()
  1.3022 +{
  1.3023 +    // acquire the lock
  1.3024 +    std::unique_lock<std::recursive_mutex> lock(keysync_mutex);
  1.3025 +
  1.3026 +    // Do nothing if keysync is not running.
  1.3027 +    if (!keysync_thread)
  1.3028 +        return;
  1.3029 +
  1.3030 +    assert(!keysync_abort_requested);
  1.3031 +    // signal that we're gonna abort
  1.3032 +    keysync_abort_requested = true;
  1.3033 +
  1.3034 +    // Notify the keysync thread
  1.3035 +    keysync_condition.notify_all();
  1.3036 +
  1.3037 +    // Wait for the other thread to finish and clean up
  1.3038 +    while (keysync_abort_requested)
  1.3039 +        keysync_condition.wait(lock);
  1.3040 +
  1.3041 +    // collect the child thread for the thread to end
  1.3042 +    keysync_thread->join();
  1.3043 +
  1.3044 +    // clean up
  1.3045 +    delete keysync_thread;
  1.3046 +    keysync_thread = NULL;
  1.3047 +
  1.3048 +    ::detach_sync_session(get_session());
  1.3049 +    ::unregister_sync_callbacks(keysync_session);
  1.3050 +
  1.3051 +    std::lock_guard<std::mutex> releaselock(init_mutex);
  1.3052 +    release(keysync_session);
  1.3053 +    keysync_session = NULL;
  1.3054 +}
  1.3055 +
  1.3056 +int CpEpEngine::inject_sync_msg(void * msg, void * management)
  1.3057 +{
  1.3058 +    assert(msg);
  1.3059 +    assert(management);
  1.3060 +    // check argument
  1.3061 +    if (!msg)
  1.3062 +        return E_INVALIDARG;
  1.3063 +    if (!management)
  1.3064 +        return ERROR_INVALID_HANDLE;
  1.3065 +
  1.3066 +    CpEpEngine* me = (CpEpEngine*)management;
  1.3067 +
  1.3068 +    // acquire the lock
  1.3069 +    std::unique_lock<std::recursive_mutex> lock(me->keysync_mutex);
  1.3070 +
  1.3071 +    // check whether we're in a valid state running:
  1.3072 +    if (!me->keysync_thread)
  1.3073 +        return E_ASYNC_OPERATION_NOT_STARTED;
  1.3074 +
  1.3075 +    // queue the message
  1.3076 +    me->keysync_queue.push(msg);
  1.3077 +
  1.3078 +    // notify the receivers
  1.3079 +    me->keysync_condition.notify_all();
  1.3080 +
  1.3081 +    return S_OK;
  1.3082 +}
  1.3083 +
  1.3084 +void * CpEpEngine::retrieve_next_sync_msg(void * management, time_t *timeout)
  1.3085 +{
  1.3086 +    // sanity check
  1.3087 +    assert(management);
  1.3088 +    if (!(management))
  1.3089 +        return NULL;
  1.3090 +
  1.3091 +    CpEpEngine* me = (CpEpEngine*)management;
  1.3092 +
  1.3093 +    if ((timeout && *timeout)
  1.3094 +        && me->client_callbacks_on_sync_thread
  1.3095 +        && me->client_last_signalled_polling_state == false)
  1.3096 +    {
  1.3097 +        me->client_callbacks_on_sync_thread->NeedFastPolling(VARIANT_TRUE);
  1.3098 +        me->client_last_signalled_polling_state = true;
  1.3099 +    }
  1.3100 +    else if (!(timeout && *timeout)
  1.3101 +        && me->client_callbacks_on_sync_thread
  1.3102 +        && me->client_last_signalled_polling_state == true)
  1.3103 +    {
  1.3104 +        me->client_callbacks_on_sync_thread->NeedFastPolling(VARIANT_FALSE);
  1.3105 +        me->client_last_signalled_polling_state = false;
  1.3106 +    }
  1.3107 +
  1.3108 +    // acquire the lock
  1.3109 +    std::unique_lock<std::recursive_mutex> lock(me->keysync_mutex);
  1.3110 +
  1.3111 +    if (me->notify_handshake_finished)
  1.3112 +        me->notify_handshake_deliver_result();
  1.3113 +
  1.3114 +    if (timeout && *timeout) {
  1.3115 +        std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now()
  1.3116 +            + std::chrono::seconds(*timeout);
  1.3117 +
  1.3118 +        while (me->keysync_queue.empty() && !me->keysync_abort_requested)
  1.3119 +        {
  1.3120 +            auto status = me->keysync_condition.wait_until(lock, end_time);
  1.3121 +
  1.3122 +            if (me->notify_handshake_finished)
  1.3123 +                me->notify_handshake_deliver_result();
  1.3124 +
  1.3125 +            if (status == std::cv_status::timeout)
  1.3126 +            {
  1.3127 +                *timeout = 1; // Signal timeout
  1.3128 +                return NULL;
  1.3129 +            }
  1.3130 +            else
  1.3131 +            {
  1.3132 +                std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
  1.3133 +
  1.3134 +                if (now < end_time)
  1.3135 +                {
  1.3136 +                    *timeout = std::chrono::duration_cast<std::chrono::seconds>(end_time - now).count();
  1.3137 +                }
  1.3138 +                else
  1.3139 +                {
  1.3140 +                    *timeout = 0;
  1.3141 +                }
  1.3142 +            }
  1.3143 +        }
  1.3144 +    }
  1.3145 +    else
  1.3146 +    {
  1.3147 +        while (me->keysync_queue.empty() && !me->keysync_abort_requested)
  1.3148 +        {
  1.3149 +            me->keysync_condition.wait(lock);
  1.3150 +
  1.3151 +            if (me->notify_handshake_finished)
  1.3152 +                me->notify_handshake_deliver_result();
  1.3153 +        }
  1.3154 +    }
  1.3155 +
  1.3156 +    if (me->keysync_abort_requested) {
  1.3157 +        // we acknowledge that we're quitting...
  1.3158 +        me->keysync_abort_requested = false;
  1.3159 +
  1.3160 +        // We signal the main thread that we got his signal
  1.3161 +        // so it can gain the mutex again and call join() on us.
  1.3162 +        me->keysync_condition.notify_all();
  1.3163 +
  1.3164 +        // and tell the pep engine we're done.
  1.3165 +        if (timeout)
  1.3166 +            *timeout = 0; // signal for termination.
  1.3167 +        return NULL;
  1.3168 +    }
  1.3169 +
  1.3170 +    assert(!me->keysync_queue.empty());
  1.3171 +
  1.3172 +    // Pop the message and return it.
  1.3173 +    void* msg = me->keysync_queue.front();
  1.3174 +    assert(msg);
  1.3175 +
  1.3176 +    me->keysync_queue.pop();
  1.3177 +
  1.3178 +    return msg;
  1.3179 +}
  1.3180 +
  1.3181 +
  1.3182 +// Event callbacks
  1.3183 +
  1.3184 +STDMETHODIMP CpEpEngine::RegisterCallbacks(IpEpEngineCallbacks* new_callbacks)
  1.3185 +{
  1.3186 +    // check for valid parameter
  1.3187 +    if (!new_callbacks)
  1.3188 +        return E_INVALIDARG;
  1.3189 +
  1.3190 +    // don't allow double registration.
  1.3191 +    if (this->client_callbacks)
  1.3192 +        return E_ILLEGAL_STATE_CHANGE;
  1.3193 +
  1.3194 +    this->client_callbacks = new_callbacks;
  1.3195 +    new_callbacks->AddRef();
  1.3196 +
  1.3197 +    start_keysync();
  1.3198 +
  1.3199 +    return S_OK;
  1.3200 +}
  1.3201 +
  1.3202 +STDMETHODIMP CpEpEngine::UnregisterCallbacks()
  1.3203 +{
  1.3204 +    // don't allow double deregistration.
  1.3205 +    // S_FALSE still is no error (as double deregistration is not fatal).
  1.3206 +    if (!this->client_callbacks)
  1.3207 +        return S_FALSE;
  1.3208 +
  1.3209 +    stop_keysync();
  1.3210 +
  1.3211 +    this->client_callbacks->Release();
  1.3212 +
  1.3213 +    this->client_callbacks = NULL;
  1.3214 +
  1.3215 +    return S_OK;
  1.3216 +}
  1.3217 +
  1.3218 +STDMETHODIMP CpEpEngine::OpenPGPListKeyinfo(BSTR search_pattern, LPSAFEARRAY* keyinfo_list) {
  1.3219 +    assert(keyinfo_list);
  1.3220 +
  1.3221 +    if (keyinfo_list == NULL)
  1.3222 +        return E_INVALIDARG;
  1.3223 +
  1.3224 +    string _pattern = "";
  1.3225 +    if (search_pattern)
  1.3226 +        _pattern = utf8_string(search_pattern);
  1.3227 +    ::stringpair_list_t* _keyinfo_list = NULL;
  1.3228 +
  1.3229 +    PEP_STATUS status = ::OpenPGP_list_keyinfo(get_session(), _pattern.c_str(), &_keyinfo_list);
  1.3230 +    assert(status != PEP_OUT_OF_MEMORY);
  1.3231 +    if (status == PEP_OUT_OF_MEMORY)
  1.3232 +        return E_OUTOFMEMORY;
  1.3233 +
  1.3234 +    if (status != ::PEP_STATUS_OK)
  1.3235 +        return FAIL(L"OpenPGP_list_keyinfo", status);
  1.3236 +
  1.3237 +    if (_keyinfo_list && _keyinfo_list->value) {
  1.3238 +        ::opt_field_array_from_C(_keyinfo_list, keyinfo_list);
  1.3239 +    }
  1.3240 +    else {
  1.3241 +        ::free_stringpair_list(_keyinfo_list);
  1.3242 +        return FAIL(L"OpenPGP_list_keyinfo: no keys found");
  1.3243 +    }
  1.3244 +
  1.3245 +    ::free_stringpair_list(_keyinfo_list);
  1.3246 +    return S_OK;
  1.3247 +
  1.3248 +}
  1.3249 +
  1.3250 +STDMETHODIMP CpEpEngine::SetOwnKey(pEpIdentity * ident, BSTR fpr, struct pEpIdentity *result)
  1.3251 +{
  1.3252 +	assert(ident);
  1.3253 +	assert(result);
  1.3254 +	assert(fpr);
  1.3255 +
  1.3256 +	if (!(ident && result))
  1.3257 +		return E_INVALIDARG;
  1.3258 +
  1.3259 +	::pEp_identity *_ident;
  1.3260 +	try {
  1.3261 +		_ident = new_identity(ident);
  1.3262 +	}
  1.3263 +	catch (bad_alloc&) {
  1.3264 +		return E_OUTOFMEMORY;
  1.3265 +	}
  1.3266 +	catch (exception& ex) {
  1.3267 +		return FAIL(ex.what());
  1.3268 +	}
  1.3269 +
  1.3270 +	assert(_ident);
  1.3271 +	if (_ident == NULL)
  1.3272 +		return E_OUTOFMEMORY;
  1.3273 +
  1.3274 +	string _fpr = utf8_string(fpr);
  1.3275 +	PEP_STATUS status = ::set_own_key(get_session(), _ident, _fpr.c_str());
  1.3276 +
  1.3277 +	if (status == PEP_STATUS_OK) {
  1.3278 +		copy_identity(result, _ident);
  1.3279 +		::free_identity(_ident);
  1.3280 +		return S_OK;
  1.3281 +	}
  1.3282 +	else {
  1.3283 +		::free_identity(_ident);
  1.3284 +		if (status == PEP_OUT_OF_MEMORY)
  1.3285 +			return E_OUTOFMEMORY;
  1.3286 +		else
  1.3287 +			return FAIL(L"SetOwnKey", status);
  1.3288 +	}
  1.3289 +
  1.3290 +	return S_OK;
  1.3291 +}
  1.3292 +
  1.3293 +HRESULT CpEpEngine::Fire_MessageToSend(TextMessage * msg)
  1.3294 +{
  1.3295 +    assert(msg);
  1.3296 +    assert(this->client_callbacks_on_sync_thread);
  1.3297 +
  1.3298 +    if (!msg)
  1.3299 +        return E_INVALIDARG;
  1.3300 +
  1.3301 +    if (!this->client_callbacks_on_sync_thread)
  1.3302 +        return E_ILLEGAL_METHOD_CALL;
  1.3303 +
  1.3304 +    auto result = this->client_callbacks_on_sync_thread->MessageToSend(msg);
  1.3305 +
  1.3306 +    return result;
  1.3307 +}
  1.3308 +
  1.3309 +// This method is called from the keysync thread, and dispatches
  1.3310 +// the handshake asynchroneously to a background thread,
  1.3311 +// so the engine can continue working.
  1.3312 +PEP_STATUS CpEpEngine::notifyHandshake(void * obj, pEp_identity *self, pEp_identity *partner, sync_handshake_signal signal)
  1.3313 +{
  1.3314 +    assert(self && partner);
  1.3315 +    if (!(self && partner))
  1.3316 +        return PEP_ILLEGAL_VALUE;
  1.3317 +
  1.3318 +    CpEpEngine *me = (CpEpEngine *)obj;
  1.3319 +
  1.3320 +    if (me->notify_handshake_active) {
  1.3321 +        // We don't support concurrent handshakes currently, 
  1.3322 +        // with the exception of an abort of the handshake, 
  1.3323 +        // which we deliver synchroneously (as it's non-blocking).
  1.3324 +        if (signal == SYNC_NOTIFY_TIMEOUT) {
  1.3325 +            pEpIdentity timeout_self;
  1.3326 +            pEpIdentity timeout_partner;
  1.3327 +            SyncHandshakeSignal timeout_signal = (SyncHandshakeSignal)signal;
  1.3328 +            copy_identity(&timeout_self, self);
  1.3329 +            copy_identity(&timeout_partner, partner);
  1.3330 +            SyncHandshakeResult result;
  1.3331 +            auto res = me->client_callbacks_on_sync_thread->NotifyHandshake(&timeout_self, &timeout_partner, timeout_signal, &result);
  1.3332 +
  1.3333 +            clear_identity_s(timeout_self);
  1.3334 +            clear_identity_s(timeout_partner);
  1.3335 +
  1.3336 +            if (FAILED(res)) {
  1.3337 +                IErrorInfo* errorInfo = NULL;
  1.3338 +                if (FAILED(GetErrorInfo(0, &errorInfo)))
  1.3339 +                    errorInfo = NULL;
  1.3340 +
  1.3341 +                // The _com_error takes ownership of the errorInfo
  1.3342 +                // and will Release() it. It can also cope with
  1.3343 +                // NULL errorInfos.
  1.3344 +                _com_error error(res, errorInfo);
  1.3345 +
  1.3346 +                string _description = utf8_string(
  1.3347 +                    error.ErrorMessage());
  1.3348 +
  1.3349 +                string _comment = utf8_string(error.Description());
  1.3350 +
  1.3351 +                auto source = error.Source();
  1.3352 +                if (source.length() > 0) {
  1.3353 +                    _comment += "\r\nSource: ";
  1.3354 +                    _comment += utf8_string(source);
  1.3355 +                }
  1.3356 +
  1.3357 +                ::log_event(me->keysync_session,
  1.3358 +                    "Error on NotifyHandshakeTimeout",
  1.3359 +                    "pEp COM Adapter",
  1.3360 +                    _description.c_str(),
  1.3361 +                    _comment.c_str());
  1.3362 +
  1.3363 +                return PEP_UNKNOWN_ERROR;
  1.3364 +            }
  1.3365 +
  1.3366 +            if (res != S_OK)
  1.3367 +
  1.3368 +                return PEP_STATUS_OK;
  1.3369 +        }
  1.3370 +
  1.3371 +        ::log_event(me->keysync_session, "Reentrant notify_handshake call!", "pEp COM Adapter", NULL, NULL);
  1.3372 +        return PEP_UNKNOWN_ERROR;
  1.3373 +    }
  1.3374 +
  1.3375 +    assert(!(me->notify_handshake_active
  1.3376 +        || me->notify_handshake_finished
  1.3377 +        || me->notify_handshake_thread));
  1.3378 +
  1.3379 +    me->notify_handshake_active = true;
  1.3380 +
  1.3381 +    copy_identity(&me->notify_handshake_self, self);
  1.3382 +    copy_identity(&me->notify_handshake_partner, partner);
  1.3383 +    me->notify_handshake_signal = (SyncHandshakeSignal)signal;
  1.3384 +
  1.3385 +    // We need to marshal the callbacks to the keysync thread
  1.3386 +    LPSTREAM marshaled_callbacks;
  1.3387 +
  1.3388 +    auto result = CoMarshalInterThreadInterfaceInStream(IID_IpEpEngineCallbacks, me->client_callbacks_on_sync_thread, &marshaled_callbacks);
  1.3389 +    assert(result == S_OK);
  1.3390 +
  1.3391 +    me->notify_handshake_thread = new thread(notify_handshake_background_thread, me, marshaled_callbacks);
  1.3392 +
  1.3393 +    return PEP_STATUS_OK;
  1.3394 +}
  1.3395 +
  1.3396 +// This method also runs in the keysync thread, called by
  1.3397 +// retrieve_next_sync_msg() to deliver back the results
  1.3398 +// of the sync into the engine.
  1.3399 +void CpEpEngine::notify_handshake_deliver_result()
  1.3400 +{
  1.3401 +    assert(notify_handshake_active
  1.3402 +        && notify_handshake_finished);
  1.3403 +    if (!(notify_handshake_active
  1.3404 +        && notify_handshake_finished))
  1.3405 +        return;
  1.3406 +
  1.3407 +    notify_handshake_thread->join();
  1.3408 +    notify_handshake_thread = NULL;
  1.3409 +
  1.3410 +    Identity partner = new_identity(&notify_handshake_partner);
  1.3411 +
  1.3412 +    if (FAILED(notify_handshake_error))
  1.3413 +    {
  1.3414 +        IErrorInfo *errorInfo = NULL;
  1.3415 +
  1.3416 +        if (notify_handshake_error_info) {
  1.3417 +            LPVOID lp = NULL;
  1.3418 +            auto res = CoGetInterfaceAndReleaseStream(notify_handshake_error_info, IID_IErrorInfo, &lp);
  1.3419 +
  1.3420 +            if (SUCCEEDED(res) && lp)
  1.3421 +                errorInfo = static_cast<IErrorInfo*>(lp);
  1.3422 +        }
  1.3423 +
  1.3424 +        // The _com_error takes ownership of the errorInfo
  1.3425 +        // and will Release() it. It can also cope with
  1.3426 +        // NULL errorInfos.
  1.3427 +        _com_error error(notify_handshake_error, errorInfo);
  1.3428 +
  1.3429 +        string _description = utf8_string(
  1.3430 +            error.ErrorMessage());
  1.3431 +
  1.3432 +        string _comment = utf8_string(error.Description());
  1.3433 +
  1.3434 +        auto source = error.Source();
  1.3435 +        if (source.length() > 0) {
  1.3436 +            _comment += "\r\nSource: ";
  1.3437 +            _comment += utf8_string(source);
  1.3438 +        }
  1.3439 +
  1.3440 +        ::log_event(keysync_session,
  1.3441 +            "Notify Handshake Failed!",
  1.3442 +            "pEp COM Adapter",
  1.3443 +            _description.c_str(),
  1.3444 +            _comment.c_str());
  1.3445 +
  1.3446 +        ::deliverHandshakeResult(keysync_session, partner, SYNC_HANDSHAKE_CANCEL);
  1.3447 +    }
  1.3448 +    else {
  1.3449 +        ::deliverHandshakeResult(
  1.3450 +            keysync_session,
  1.3451 +            partner,
  1.3452 +            (sync_handshake_result)notify_handshake_result);
  1.3453 +    }
  1.3454 +    notify_handshake_error_info = NULL;
  1.3455 +
  1.3456 +    clear_identity_s(notify_handshake_self);
  1.3457 +    clear_identity_s(notify_handshake_partner);
  1.3458 +    notify_handshake_active = false;
  1.3459 +    notify_handshake_finished = false;
  1.3460 +}
  1.3461 +
  1.3462 +// Method on the background thread, calling into Outlook to
  1.3463 +// trigger the Handshake notification, and then scheduling
  1.3464 +// the result back to the main thread.
  1.3465 +void CpEpEngine::notify_handshake_background_thread(CpEpEngine* self, LPSTREAM marshaled_callbacks)
  1.3466 +{
  1.3467 +    assert(self);
  1.3468 +
  1.3469 +    // We need to initialize COM here for successfull delivery of the callbacks.
  1.3470 +    // As we don't create any COM instances in our thread, the COMINIT value is
  1.3471 +    // currently irrelevant, so we go with the safest value.
  1.3472 +    auto res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  1.3473 +    assert(res == S_OK);
  1.3474 +
  1.3475 +    LPVOID vp;
  1.3476 +
  1.3477 +    res = CoGetInterfaceAndReleaseStream(marshaled_callbacks, IID_IpEpEngineCallbacks, &vp);
  1.3478 +    assert(SUCCEEDED(res));
  1.3479 +
  1.3480 +    auto client_callbacks_on_sync_thread = static_cast<IpEpEngineCallbacks*>(vp);
  1.3481 +
  1.3482 +    self->notify_handshake_error = client_callbacks_on_sync_thread->NotifyHandshake(
  1.3483 +        &self->notify_handshake_self,
  1.3484 +        &self->notify_handshake_partner,
  1.3485 +        self->notify_handshake_signal,
  1.3486 +        &self->notify_handshake_result);
  1.3487 +
  1.3488 +    if (FAILED(self->notify_handshake_error)) {
  1.3489 +        IErrorInfo* errorInfo = NULL;
  1.3490 +
  1.3491 +        res = GetErrorInfo(0, &errorInfo);
  1.3492 +
  1.3493 +        if (res = S_OK && errorInfo != NULL) {
  1.3494 +            res = CoMarshalInterThreadInterfaceInStream(
  1.3495 +                IID_IErrorInfo,
  1.3496 +                errorInfo,
  1.3497 +                &self->notify_handshake_error_info);
  1.3498 +
  1.3499 +            errorInfo->Release();
  1.3500 +        }
  1.3501 +    }
  1.3502 +
  1.3503 +    // notify the keysync thread.
  1.3504 +    self->notify_handshake_finished = true;
  1.3505 +    self->keysync_condition.notify_all();
  1.3506 +}