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