CpEpEngine.h
author Thomas
Wed, 20 Nov 2019 17:14:38 +0100
branchsync
changeset 374 ccc4c88f280e
parent 368 407097584d25
child 375 fe31c63ea77d
permissions -rw-r--r--
Wrap is_sync_running()
     1 // CpEpEngine.h : Declaration of the CpEpEngine
     2 
     3 #pragma once
     4 #include "resource.h"       // main symbols
     5 
     6 #include "pEpComServerAdapter_i.h"
     7 #include "..\libpEpAdapter\locked_queue.hh"
     8 #include "utf8_helper.h"
     9 #include "pEp_utility.h"
    10 #include "..\libpEpAdapter\Adapter.hh"
    11 #include <queue>
    12 #include <mutex>
    13 #include <vector>
    14 #include "..\libpEpAdapter\pc_container.hh"
    15 #include "..\pEp\sync_codec.h"
    16 
    17 #if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA)
    18 #error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms."
    19 #endif
    20 
    21 using namespace ATL;
    22 using namespace utility;
    23 using namespace pEp::utility;
    24 using namespace pEp::Adapter;
    25 
    26 // CpEpEngine
    27 
    28 class ATL_NO_VTABLE CpEpEngine :
    29     public CComObjectRootEx<CComObjectThreadModel>,
    30     public CComCoClass<CpEpEngine, &CLSID_pEpEngine>,
    31     public ISupportErrorInfo,
    32     public IpEpEngine
    33 {
    34 
    35 protected:
    36     static int examine_identity(pEp_identity *ident, void *management);
    37 
    38 public:
    39     CpEpEngine() : keymanagement_thread(NULL), identity_queue(NULL), verbose_mode(false)
    40     {
    41         // See FinalConstruct() below for most initialization work, and an
    42         // explanation why it had to be moved there...
    43         ++count;
    44     }
    45 
    46     ~CpEpEngine()
    47     {
    48         --count;
    49         if (!count) {
    50             StopKeyserverLookup();
    51             ::log_event(session(), "Shutdown", "pEp COM Adapter", NULL, NULL);
    52             session(pEp::Adapter::release);
    53             shutdown();
    54 
    55             sync_callbacks.clear([](CpEpEngine::MarshaledCallbacks *p) {
    56                 if (p) {
    57                     if (p->marshaled)
    58                         p->marshaled->Release();
    59                     if (p->unmarshaled)
    60                         p->unmarshaled->Release();
    61                     delete p;
    62                 }
    63             });
    64         }
    65     }
    66 
    67     DECLARE_REGISTRY_RESOURCEID(IDR_PEPENGINE)
    68 
    69     DECLARE_NOT_AGGREGATABLE(CpEpEngine)
    70 
    71     BEGIN_COM_MAP(CpEpEngine)
    72         COM_INTERFACE_ENTRY(IpEpEngine)
    73         COM_INTERFACE_ENTRY(ISupportErrorInfo)
    74     END_COM_MAP()
    75 
    76     // ISupportsErrorInfo
    77     STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
    78 
    79     DECLARE_PROTECT_FINAL_CONSTRUCT()
    80 
    81     // Unfortunately, neither FAIL nor error() work in the constructor, as 
    82     // CreateErrorInfo/SetErrorInfo cannot work when the instance is not constructed.
    83     // AtlThrow works, but the exception is caught in CComCreator.CreateInstance, and
    84     // unconditionally turned into E_OUTOFMEMORY. Thus, we need to do most constructor
    85     // work in FinalConstruct. CreateErrorInfo/SetErrorInfo still won't work, but at least,
    86     // we can return a meaningful HRESULT. Thus, we pack our PEP_STATUS into a custom HRESULT.	
    87     HRESULT FinalConstruct()
    88     {
    89         std::lock_guard<std::mutex> lock(init_mutex);
    90         try {
    91             if (!_messageToSend) {
    92                 _messageToSend = messageToSend;
    93             }
    94             session();
    95         }
    96         catch (pEp::RuntimeError& e) {
    97             HRESULT res = MAKE_HRESULT(1, FACILITY_ITF, (0xFFFF & e.status));
    98             return res;
    99         }       
   100 
   101         ::register_examine_function(session(), CpEpEngine::examine_identity, (void *)this);
   102         ::log_event(session(), "FinalConstruct", "pEp COM Adapter", NULL, NULL);
   103 
   104         return S_OK;
   105     }
   106 
   107     void FinalRelease()
   108     {
   109     }
   110 
   111     struct MarshaledCallbacks {
   112         IpEpEngineCallbacks *unmarshaled;
   113         LPSTREAM marshaled;
   114     };
   115 
   116     typedef pEp::pc_container< MarshaledCallbacks, IpEpEngineCallbacks > callback_container;
   117 
   118 protected:
   119     typedef locked_queue<pEp_identity_cpp> identity_queue_t;
   120     static ::pEp_identity * retrieve_next_identity(void *management);
   121 
   122     static PEP_STATUS messageToSend(message *msg);
   123     static PEP_STATUS notifyHandshake(pEp_identity *self, pEp_identity *partner, sync_handshake_signal signal);
   124 
   125     HRESULT error(_bstr_t msg);
   126     HRESULT error(_bstr_t msg, PEP_STATUS errorcode);
   127 
   128     void verbose(string text)
   129     {
   130         if (verbose_mode) {
   131             stringstream ss;
   132             ss << __FILE__ << ":" << __LINE__ << " " << text;
   133             ::log_event(session(), "verbose", "pEp COM Server Adapter", ss.str().c_str(), NULL);
   134         }
   135     }
   136 
   137 private:
   138     // callbacks for sync
   139 
   140     static callback_container sync_callbacks;
   141 
   142     void Startup_sync()
   143     {
   144         HRESULT r = CoInitializeEx(NULL, COINIT_MULTITHREADED);
   145         if (!SUCCEEDED(r))
   146             throw runtime_error("CoInitializeEx() failed on sync thread");
   147     }
   148 
   149     void Shutdown_sync()
   150     {
   151         for (auto p = sync_callbacks.begin(); p != sync_callbacks.end(); ++p) {
   152             if (p->cdata) {
   153                 // p->cdata->Release(); FIXME: This occasionally raises an access violation. To be investigated, why => COM-99
   154                 p->cdata = nullptr;
   155             }
   156         }
   157 
   158         CoUninitialize();
   159     }
   160 
   161     atomic< identity_queue_t * > identity_queue;
   162     thread *keymanagement_thread;
   163     bool verbose_mode;
   164 
   165     IpEpEngineCallbacks* client_callbacks = NULL;
   166     bool client_last_signalled_polling_state = true;
   167 
   168     static std::mutex init_mutex;
   169     static atomic< int > count;
   170 
   171 public:
   172     // runtime config of the adapter
   173 
   174     STDMETHOD(VerboseLogging)(VARIANT_BOOL enable);
   175 
   176     // runtime config of the engine
   177 
   178     STDMETHOD(PassiveMode)(VARIANT_BOOL enable);
   179     STDMETHOD(UnencryptedSubject)(VARIANT_BOOL enable);
   180 
   181     // basic API
   182 
   183     STDMETHOD(ExportKey)(BSTR fpr, BSTR * keyData);
   184     STDMETHOD(Log)(BSTR title, BSTR entity, BSTR description, BSTR comment);
   185     STDMETHOD(Trustwords)(BSTR fpr, BSTR lang, LONG max_words, BSTR * words);
   186     STDMETHOD(GetTrustwords)(struct pEpIdentity *id1, struct pEpIdentity *id2, BSTR lang, VARIANT_BOOL full, BSTR *words);
   187     STDMETHOD(GetTrustwordsForFprs)(BSTR fpr1, BSTR fpr2, BSTR lang, VARIANT_BOOL full, BSTR *words);
   188     STDMETHOD(GetMessageTrustwords)(
   189         /* [in] */ struct TextMessage *msg,
   190         /* [in] */ struct pEpIdentity *receivedBy,
   191         /* [in] */ SAFEARRAY *keylist,
   192         /* [defaultvalue][in] */ BSTR lang,
   193         /* [defaultvalue][in] */ VARIANT_BOOL full,
   194         /* [retval][out] */ BSTR *words);
   195     STDMETHOD(GetCrashdumpLog)(LONG maxlines, BSTR * log);
   196     STDMETHOD(GetEngineVersion)(BSTR * engineVersion);
   197     STDMETHOD(GetLanguageList)(BSTR * languages);
   198     STDMETHOD(SetIdentityFlags)(struct pEpIdentity *identity, pEpIdentityFlags flags);
   199     STDMETHOD(UnsetIdentityFlags)(struct pEpIdentity *identity, pEpIdentityFlags flags);
   200     STDMETHOD(ImportKey)(BSTR keyData, LPSAFEARRAY *privateKeys);
   201 
   202     // keymanagement API
   203 
   204     STDMETHOD(StartKeyserverLookup)();
   205     STDMETHOD(StopKeyserverLookup)();
   206 
   207     STDMETHOD(Myself)(struct pEpIdentity *ident, struct pEpIdentity *result);
   208     STDMETHOD(UpdateIdentity)(struct pEpIdentity *ident, struct pEpIdentity *result);
   209     STDMETHOD(KeyMistrusted)(struct pEpIdentity *ident);
   210     STDMETHOD(KeyResetIdentity)(pEpIdentity ident, BSTR fpr);
   211     STDMETHOD(KeyResetUser)(BSTR userId, BSTR fpr);
   212     STDMETHOD(KeyResetAllOwnKeys)();
   213     STDMETHOD(KeyResetTrust)(struct pEpIdentity *ident);
   214     STDMETHOD(TrustPersonalKey)(struct pEpIdentity *ident, struct pEpIdentity *result);
   215     STDMETHOD(OwnIdentitiesRetrieve)(LPSAFEARRAY* ownIdentities);
   216     STDMETHOD(ConfigCipherSuite)(pEpCipherSuite cipherSuite);
   217 
   218     // STDMETHOD(UndoLastMistrust)(); 
   219     
   220     STDMETHOD(IspEpUser)(
   221         /* [in] */ struct pEpIdentity *ident,
   222         /* [retval][out] */ VARIANT_BOOL *ispEp);
   223 
   224 
   225     // Blacklist API
   226 
   227     STDMETHOD(BlacklistAdd)(BSTR fpr);
   228     STDMETHOD(BlacklistDelete)(BSTR fpr);
   229     STDMETHOD(BlacklistIsListed)(BSTR fpr, VARIANT_BOOL *listed);
   230     STDMETHOD(BlacklistRetrieve)(SAFEARRAY **blacklist);
   231 
   232     // Message API
   233 
   234     STDMETHOD(EncryptMessage)(
   235         /* [in] */ struct TextMessage *src,
   236         /* [out] */ struct TextMessage *dst,
   237         /* [in] */ SAFEARRAY * extra,
   238         /* [defaultvalue][in] */ pEpEncryptFlags flags = pEpEncryptFlagDefault,
   239         /* [defaultvalue][in] */ pEpEncFormat encFormat = pEpEncPep);
   240 
   241     STDMETHOD(EncryptMessageAndAddPrivKey)(
   242         /* [in] */ struct TextMessage *src,
   243         /* [out] */ struct TextMessage *dst,
   244         /* [in] */ BSTR to_fpr,
   245         /* [defaultvalue][in] */ pEpEncryptFlags flags = pEpEncryptFlagDefault,
   246         /* [defaultvalue][in] */ pEpEncFormat encFormat = pEpEncPep);
   247 
   248     STDMETHOD(DecryptMessage)(TextMessage * src, TextMessage * dst, SAFEARRAY ** keylist, pEpDecryptFlags* flags, pEpRating *rating);
   249     STDMETHOD(ReEvaluateMessageRating)(TextMessage * msg, SAFEARRAY * x_KeyList, pEpRating x_EncStatus, pEpRating *rating);
   250     STDMETHOD(OutgoingMessageRating)(TextMessage *msg, pEpRating * pVal);
   251     STDMETHOD(OutgoingMessageRatingPreview)(TextMessage *msg, pEpRating * pVal);
   252     STDMETHOD(IdentityRating)(pEpIdentity * ident, pEpRating * pVal);
   253     STDMETHOD(ColorFromRating)(pEpRating rating, pEpColor * pVal);
   254     STDMETHOD(RatingFromCommType)(pEpComType commType, pEpRating * rating);
   255 
   256     STDMETHOD(EncryptMessageForSelf)(
   257         pEpIdentity * targetId,
   258         TextMessage* src,
   259         /* [in] */ SAFEARRAY *extra,
   260         TextMessage *dst,
   261         pEpEncryptFlags flags
   262         );
   263 
   264     // Event callbacks
   265 
   266     STDMETHOD(RegisterCallbacks)(IpEpEngineCallbacks *new_callback);
   267     STDMETHOD(UnregisterCallbacks)();
   268 
   269     // PGP compatibility functions
   270     STDMETHOD(OpenPGPListKeyinfo)(BSTR search_pattern, LPSAFEARRAY* keyinfo_list);
   271     STDMETHOD(SetOwnKey)(pEpIdentity * ident, BSTR fpr, struct pEpIdentity *result);
   272     STDMETHOD(TrustOwnKey)(pEpIdentity * ident);
   273 
   274     // Trigger an immediate update
   275     STDMETHOD(UpdateNow)(BSTR productCode, VARIANT_BOOL *didUpdate);
   276 
   277     STDMETHOD(Startup)();
   278 
   279     STDMETHOD(GetKeyRatingForUser)(BSTR userId, BSTR fpr, pEpRating *rating);
   280     STDMETHOD(GetKeyRating)(BSTR fpr, pEpComType *commType);
   281 
   282     // sync API
   283     STDMETHOD(DeliverHandshakeResult)(enum SyncHandshakeResult result, SAFEARRAY *identities_sharing);
   284     STDMETHOD(LeaveDeviceGroup)();
   285     STDMETHOD(DisableIdentityForSync)(struct pEpIdentity * ident);
   286     STDMETHOD(EnableIdentityForSync)(struct pEpIdentity * ident);
   287     STDMETHOD(GetIsSyncRunning)(VARIANT_BOOL *running);
   288 
   289     STDMETHOD(PERToXERSyncMessage)(TextMessage *msg, BSTR * xer);
   290 
   291     STDMETHOD(PerMachineDirectory)(BSTR * directory);
   292     STDMETHOD(PerUserDirectory)(BSTR * directory);
   293 };
   294 
   295 OBJECT_ENTRY_AUTO(__uuidof(pEpEngine), CpEpEngine)