fd6ce97cffb6ac5b48d26ac8860426fb8de965cd
[shibboleth/cpp-xmltooling.git] / xmltooling / XMLToolingConfig.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * XMLToolingConfig.cpp
23  *
24  * Library configuration.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "logging.h"
30 #include "XMLToolingConfig.h"
31 #include "encryption/Encryption.h"
32 #include "encryption/Encrypter.h"
33 #include "impl/UnknownElement.h"
34 #include "io/HTTPResponse.h"
35 #include "security/TrustEngine.h"
36 #include "security/OpenSSLCryptoX509CRL.h"
37 #include "security/CredentialResolver.h"
38 #include "security/KeyInfoResolver.h"
39 #include "security/PathValidator.h"
40 #include "signature/KeyInfo.h"
41 #include "signature/Signature.h"
42 #include "soap/SOAP.h"
43 #include "soap/SOAPTransport.h"
44 #include "util/NDC.h"
45 #include "util/PathResolver.h"
46 #include "util/ReplayCache.h"
47 #include "util/StorageService.h"
48 #include "util/TemplateEngine.h"
49 #include "util/Threads.h"
50 #include "util/URLEncoder.h"
51 #include "validation/ValidatorSuite.h"
52
53 #ifdef HAVE_DLFCN_H
54 # include <dlfcn.h>
55 #endif
56
57 #include <stdexcept>
58 #include <boost/algorithm/string.hpp>
59 #include <boost/lambda/bind.hpp>
60 #include <boost/lambda/lambda.hpp>
61
62 #if defined(XMLTOOLING_LOG4SHIB)
63 # include <log4shib/PropertyConfigurator.hh>
64 # include <log4shib/OstreamAppender.hh>
65 #elif defined(XMLTOOLING_LOG4CPP)
66 # include <log4cpp/PropertyConfigurator.hh>
67 # include <log4cpp/OstreamAppender.hh>
68 #endif
69 #include <xercesc/util/PlatformUtils.hpp>
70 #include <xercesc/util/XMLUniDefs.hpp>
71 #ifndef XMLTOOLING_NO_XMLSEC
72 # include <curl/curl.h>
73 # include <openssl/err.h>
74 # include <openssl/evp.h>
75 # include <xsec/framework/XSECAlgorithmMapper.hpp>
76 # include <xsec/framework/XSECException.hpp>
77 # include <xsec/framework/XSECProvider.hpp>
78 # include <xsec/transformers/TXFMBase.hpp>
79 #endif
80
81 using namespace soap11;
82 using namespace xmltooling::logging;
83 using namespace xmltooling;
84 using namespace xercesc;
85 using namespace boost::lambda;
86 using namespace boost;
87 using namespace std;
88
89 #ifdef WIN32
90 # if (OPENSSL_VERSION_NUMBER >= 0x00908000)
91 #  define XMLTOOLING_OPENSSL_HAVE_SHA2 1
92 # endif
93 #endif
94
95
96 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
97 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
98 DECL_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
99 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
100 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
101 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
102 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownExtensionException,xmltooling);
103 DECL_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
104 DECL_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
105
106 #ifndef XMLTOOLING_NO_XMLSEC
107 using namespace xmlencryption;
108 using namespace xmlsignature;
109     DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
110     DECL_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
111     DECL_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
112 #endif
113
114 namespace {
115     static XMLToolingInternalConfig g_config;
116 #ifndef XMLTOOLING_NO_XMLSEC
117     static vector<Mutex*> g_openssl_locks;
118
119     extern "C" void openssl_locking_callback(int mode,int n,const char *file,int line)
120     {
121         if (mode & CRYPTO_LOCK)
122             g_openssl_locks[n]->lock();
123         else
124             g_openssl_locks[n]->unlock();
125     }
126
127 # ifndef WIN32
128     extern "C" unsigned long openssl_thread_id(void)
129     {
130         return (unsigned long)(pthread_self());
131     }
132 # endif
133
134 # ifdef XMLTOOLING_XMLSEC_DEBUGLOGGING
135     class TXFMOutputLog : public TXFMBase {
136             TXFMOutputLog();
137     public:
138         TXFMOutputLog(DOMDocument* doc) : TXFMBase(doc), m_log(Category::getInstance(XMLTOOLING_LOGCAT".Signature.Debugger")) {
139             input = nullptr;
140         }
141         ~TXFMOutputLog() {
142             m_log.debug("\n----- END SIGNATURE DEBUG -----\n");
143         }
144
145             void setInput(TXFMBase *newInput) {
146                 input = newInput;
147                 if (newInput->getOutputType() != TXFMBase::BYTE_STREAM)
148                         throw XSECException(XSECException::TransformInputOutputFail, "OutputLog transform requires BYTE_STREAM input");
149                 keepComments = input->getCommentsStatus();
150             m_log.debug("\n----- BEGIN SIGNATURE DEBUG -----\n");
151         }
152
153             TXFMBase::ioType getInputType() {
154             return TXFMBase::BYTE_STREAM;
155         }
156             TXFMBase::ioType getOutputType() {
157             return TXFMBase::BYTE_STREAM;
158         }
159             TXFMBase::nodeType getNodeType() {
160             return TXFMBase::DOM_NODE_NONE;
161         }
162
163             unsigned int readBytes(XMLByte * const toFill, const unsigned int maxToFill) {
164                 unsigned int sz = input->readBytes(toFill, maxToFill);
165             m_log.debug(string(reinterpret_cast<char* const>(toFill), sz));
166                 return sz;
167         }
168
169             DOMDocument* getDocument() {
170             return nullptr;
171         }
172             DOMNode* getFragmentNode() {
173             return nullptr;
174         }
175             const XMLCh* getFragmentId() {
176             return nullptr;
177         }
178         
179     private:
180         Category& m_log;
181     };
182
183     TXFMBase* TXFMOutputLogFactory(DOMDocument* doc) {
184         if (Category::getInstance(XMLTOOLING_LOGCAT".Signature.Debugger").isDebugEnabled())
185             return new TXFMOutputLog(doc);
186         return nullptr;
187     }
188 # endif
189
190 #endif
191
192 #ifdef WIN32
193     BOOL LogEvent(
194         LPCSTR  lpUNCServerName,
195         WORD  wType,
196         DWORD  dwEventID,
197         PSID  lpUserSid,
198         LPCSTR  message)
199     {
200         LPCSTR  messages[] = {message, nullptr};
201
202         HANDLE hElog = RegisterEventSource(lpUNCServerName, "OpenSAML XMLTooling Library");
203         BOOL res = ReportEvent(hElog, wType, 0, dwEventID, lpUserSid, 1, 0, messages, nullptr);
204         return (DeregisterEventSource(hElog) && res);
205     }
206 #endif
207 }
208
209 XMLToolingConfig& XMLToolingConfig::getConfig()
210 {
211     return g_config;
212 }
213
214 XMLToolingInternalConfig& XMLToolingInternalConfig::getInternalConfig()
215 {
216     return g_config;
217 }
218
219 #ifndef XMLTOOLING_NO_XMLSEC
220 XMLToolingConfig::XMLToolingConfig()
221     : m_keyInfoResolver(nullptr), m_replayCache(nullptr), m_pathResolver(nullptr), m_templateEngine(nullptr), m_urlEncoder(nullptr), clock_skew_secs(180)
222 #else
223 XMLToolingConfig::XMLToolingConfig()
224     : m_pathResolver(nullptr), m_templateEngine(nullptr), m_urlEncoder(nullptr), clock_skew_secs(180)
225 #endif
226 {
227 }
228
229 XMLToolingConfig::~XMLToolingConfig()
230 {
231 }
232
233 #ifndef XMLTOOLING_LITE
234 const KeyInfoResolver* XMLToolingConfig::getKeyInfoResolver() const
235 {
236     return m_keyInfoResolver;
237 }
238
239 ReplayCache* XMLToolingConfig::getReplayCache() const
240 {
241     return m_replayCache;
242 }
243
244 void XMLToolingConfig::setKeyInfoResolver(xmltooling::KeyInfoResolver *keyInfoResolver)
245 {
246     delete m_keyInfoResolver;
247     m_keyInfoResolver = keyInfoResolver;
248 }
249
250 void XMLToolingConfig::setReplayCache(ReplayCache* replayCache)
251 {
252     delete m_replayCache;
253     m_replayCache = replayCache;
254 }
255 #endif
256
257 PathResolver* XMLToolingConfig::getPathResolver() const
258 {
259     return m_pathResolver;
260 }
261
262 TemplateEngine* XMLToolingConfig::getTemplateEngine() const
263 {
264     return m_templateEngine;
265 }
266
267 const URLEncoder* XMLToolingConfig::getURLEncoder() const
268 {
269     return m_urlEncoder;
270 }
271
272 void XMLToolingConfig::setPathResolver(PathResolver* pathResolver)
273 {
274     delete m_pathResolver;
275     m_pathResolver = pathResolver;
276 }
277
278 void XMLToolingConfig::setTemplateEngine(TemplateEngine* templateEngine)
279 {
280     delete m_templateEngine;
281     m_templateEngine = templateEngine;
282 }
283
284 void XMLToolingConfig::setURLEncoder(URLEncoder* urlEncoder)
285 {
286     delete m_urlEncoder;
287     m_urlEncoder = urlEncoder;
288 }
289
290 XMLToolingInternalConfig::XMLToolingInternalConfig() :
291 #ifndef XMLTOOLING_NO_XMLSEC
292     m_xsecProvider(nullptr),
293 #endif
294     m_initCount(0), m_lock(Mutex::create()), m_parserPool(nullptr), m_validatingPool(nullptr)
295 {
296 }
297
298 XMLToolingInternalConfig::~XMLToolingInternalConfig()
299 {
300     delete m_lock;
301 }
302
303 bool XMLToolingInternalConfig::log_config(const char* config)
304 {
305     try {
306         if (!config || !*config)
307             config=getenv("XMLTOOLING_LOG_CONFIG");
308         if (!config || !*config)
309             config="WARN";
310
311         bool level=false;
312         Category& root = Category::getRoot();
313         if (!strcmp(config,"DEBUG")) {
314             root.setPriority(Priority::DEBUG);
315             level=true;
316         }
317         else if (!strcmp(config,"INFO")) {
318             root.setPriority(Priority::INFO);
319             level=true;
320         }
321         else if (!strcmp(config,"NOTICE")) {
322             root.setPriority(Priority::NOTICE);
323             level=true;
324         }
325         else if (!strcmp(config,"WARN")) {
326             root.setPriority(Priority::WARN);
327             level=true;
328         }
329         else if (!strcmp(config,"ERROR")) {
330             root.setPriority(Priority::ERROR);
331             level=true;
332         }
333         else if (!strcmp(config,"CRIT")) {
334             root.setPriority(Priority::CRIT);
335             level=true;
336         }
337         else if (!strcmp(config,"ALERT")) {
338             root.setPriority(Priority::ALERT);
339             level=true;
340         }
341         else if (!strcmp(config,"EMERG")) {
342             root.setPriority(Priority::EMERG);
343             level=true;
344         }
345         else if (!strcmp(config,"FATAL")) {
346             root.setPriority(Priority::FATAL);
347             level=true;
348         }
349         if (level) {
350             root.setAppender(new OstreamAppender("default",&cerr));
351         }
352         else {
353             string path(config);
354             PropertyConfigurator::configure(m_pathResolver ? m_pathResolver->resolve(path, PathResolver::XMLTOOLING_CFG_FILE) : path);
355         }
356
357 #ifndef XMLTOOLING_NO_XMLSEC
358         Category::getInstance(XMLTOOLING_LOGCAT".Signature.Debugger").setAdditivity(false);
359 #endif
360         }
361     catch (const ConfigureFailure& e) {
362         string msg = string("failed to configure logging: ") + e.what();
363         Category::getInstance(XMLTOOLING_LOGCAT".Logging").crit(msg);
364 #ifdef WIN32
365         LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, msg.c_str());
366 #endif
367         return false;
368     }
369
370     return true;
371 }
372
373 bool XMLToolingInternalConfig::init()
374 {
375 #ifdef _DEBUG
376     xmltooling::NDC ndc("init");
377 #endif
378     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".Config");
379
380     Lock initLock(m_lock);
381
382     if (m_initCount == INT_MAX) {
383         log.crit("library initialized too many times");
384         return false;
385     }
386
387     if (m_initCount >= 1) {
388         ++m_initCount;
389         return true;
390     }
391
392     try {
393         log.debug("library initialization started");
394
395 #ifndef XMLTOOLING_NO_XMLSEC
396         if (curl_global_init(CURL_GLOBAL_ALL)) {
397             log.fatal("failed to initialize libcurl, OpenSSL, or Winsock");
398             return false;
399         }
400         curl_version_info_data* curlver = curl_version_info(CURLVERSION_NOW);
401         if (curlver) {
402             log.debug("libcurl %s initialization complete", curlver->version);
403             if (!(curlver->features & CURL_VERSION_SSL)) {
404                 log.warn("libcurl lacks TLS/SSL support, this will greatly limit functionality");
405             }
406         }
407         else {
408             log.debug("libcurl %s initialization complete", LIBCURL_VERSION);
409         }
410 #endif
411
412         XMLPlatformUtils::Initialize();
413         log.debug("Xerces %s initialization complete", XERCES_FULLVERSIONDOT);
414
415 #ifndef XMLTOOLING_NO_XMLSEC
416         XSECPlatformUtils::Initialise();
417 # ifdef XMLTOOLING_XMLSEC_DEBUGLOGGING
418         XSECPlatformUtils::SetReferenceLoggingSink(TXFMOutputLogFactory);
419 # endif
420         m_xsecProvider=new XSECProvider();
421         log.debug("XML-Security %s initialization complete", XSEC_FULLVERSIONDOT);
422 #endif
423
424         m_parserPool=new ParserPool();
425         m_validatingPool=new ParserPool(true,true);
426
427         // Load catalogs from path.
428         if (!catalog_path.empty()) {
429             vector<string> catpaths;
430             split(catpaths, catalog_path, is_any_of(PATH_SEPARATOR_STR), algorithm::token_compress_on);
431             for_each(
432                 catpaths.begin(), catpaths.end(),
433                 // Call loadCatalog with an inner call to s->c_str() on each entry.
434                 lambda::bind(static_cast<bool (ParserPool::*)(const char*)>(&ParserPool::loadCatalog), m_validatingPool, lambda::bind(&string::c_str,_1))
435                 );
436         }
437
438         // default registrations
439         XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
440
441         registerSOAPClasses();
442
443         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
444         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
445         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
446         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
447         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
448         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
449         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
450         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
451
452 #ifndef XMLTOOLING_NO_XMLSEC
453         XMLObjectBuilder::registerBuilder(QName(xmlconstants::XMLSIG_NS,Signature::LOCAL_NAME),new SignatureBuilder());
454         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
455         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
456         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
457         registerKeyInfoClasses();
458         registerEncryptionClasses();
459         registerCredentialResolvers();
460         registerKeyInfoResolvers();
461         registerPathValidators();
462         registerTrustEngines();
463         registerXMLAlgorithms();
464         m_keyInfoResolver = KeyInfoResolverManager.newPlugin(INLINE_KEYINFO_RESOLVER,nullptr);
465 #endif
466
467 #ifndef XMLTOOLING_LITE
468         registerStorageServices();
469 #endif
470         registerSOAPTransports();
471         initSOAPTransports();
472
473         m_pathResolver = new PathResolver();
474         m_urlEncoder = new URLEncoder();
475
476         HTTPResponse::getAllowedSchemes().push_back("https");
477         HTTPResponse::getAllowedSchemes().push_back("http");
478
479         // Register xml:id as an ID attribute.
480         static const XMLCh xmlid[] = UNICODE_LITERAL_2(i,d);
481         AttributeExtensibleXMLObject::registerIDAttribute(QName(xmlconstants::XML_NS, xmlid));
482     }
483     catch (const xercesc::XMLException&) {
484         log.fatal("caught exception while initializing Xerces");
485 #ifndef XMLTOOLING_NO_XMLSEC
486         curl_global_cleanup();
487 #endif
488         return false;
489     }
490
491 #ifndef XMLTOOLING_NO_XMLSEC
492     // Set up OpenSSL locking.
493     for (int i=0; i<CRYPTO_num_locks(); i++)
494         g_openssl_locks.push_back(Mutex::create());
495     CRYPTO_set_locking_callback(openssl_locking_callback);
496 # ifndef WIN32
497     CRYPTO_set_id_callback(openssl_thread_id);
498 # endif
499 #endif
500
501     log.info("%s library initialization complete", PACKAGE_STRING);
502     ++m_initCount;
503     return true;
504 }
505
506 void XMLToolingInternalConfig::term()
507 {
508 #ifdef _DEBUG
509     xmltooling::NDC ndc("term");
510 #endif
511
512     Lock initLock(m_lock);
513     if (m_initCount == 0) {
514         Category::getInstance(XMLTOOLING_LOGCAT".Config").crit("term without corresponding init");
515         return;
516     }
517     else if (--m_initCount > 0) {
518         return;
519     }
520
521 #ifndef XMLTOOLING_NO_XMLSEC
522     CRYPTO_set_locking_callback(nullptr);
523     for_each(g_openssl_locks.begin(), g_openssl_locks.end(), xmltooling::cleanup<Mutex>());
524     g_openssl_locks.clear();
525 #endif
526
527     SchemaValidators.destroyValidators();
528     XMLObjectBuilder::destroyBuilders();
529     XMLToolingException::deregisterFactories();
530     AttributeExtensibleXMLObject::deregisterIDAttributes();
531
532     termSOAPTransports();
533     SOAPTransportManager.deregisterFactories();
534
535 #ifndef XMLTOOLING_LITE
536     StorageServiceManager.deregisterFactories();
537 #endif
538
539 #ifndef XMLTOOLING_NO_XMLSEC
540     TrustEngineManager.deregisterFactories();
541     CredentialResolverManager.deregisterFactories();
542     KeyInfoResolverManager.deregisterFactories();
543     m_algorithmMap.clear();
544
545     delete m_keyInfoResolver;
546     m_keyInfoResolver = nullptr;
547
548     delete m_replayCache;
549     m_replayCache = nullptr;
550 #endif
551
552     delete m_pathResolver;
553     m_pathResolver = nullptr;
554
555     delete m_templateEngine;
556     m_templateEngine = nullptr;
557
558     delete m_urlEncoder;
559     m_urlEncoder = nullptr;
560
561     for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
562 #if defined(WIN32)
563         FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
564         if (fn)
565             fn();
566         FreeLibrary(static_cast<HMODULE>(*i));
567 #elif defined(HAVE_DLFCN_H)
568         void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
569         if (fn)
570             fn();
571         dlclose(*i);
572 #else
573 # error "Don't know about dynamic loading on this platform!"
574 #endif
575     }
576     m_libhandles.clear();
577
578     delete m_parserPool;
579     m_parserPool=nullptr;
580     delete m_validatingPool;
581     m_validatingPool=nullptr;
582
583     for_each(m_namedLocks.begin(), m_namedLocks.end(), cleanup_pair<string,Mutex>());
584     m_namedLocks.clear();
585
586 #ifndef XMLTOOLING_NO_XMLSEC
587     delete m_xsecProvider;
588     m_xsecProvider=nullptr;
589     XSECPlatformUtils::Terminate();
590 #endif
591
592     XMLPlatformUtils::Terminate();
593
594 #ifndef XMLTOOLING_NO_XMLSEC
595     curl_global_cleanup();
596 #endif
597    Category::getInstance(XMLTOOLING_LOGCAT".Config").info("%s library shutdown complete", PACKAGE_STRING);
598 }
599
600 Lockable* XMLToolingInternalConfig::lock()
601 {
602     m_lock->lock();
603     return this;
604 }
605
606 void XMLToolingInternalConfig::unlock()
607 {
608     m_lock->unlock();
609 }
610
611 Mutex& XMLToolingInternalConfig::getNamedMutex(const char* name)
612 {
613     Locker glock(this);
614     map<string,Mutex*>::const_iterator m = m_namedLocks.find(name);
615     if (m != m_namedLocks.end())
616         return *(m->second);
617     Mutex* newlock = Mutex::create();
618     m_namedLocks[name] = newlock;
619     return *newlock;
620 }
621
622 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
623 {
624 #ifdef _DEBUG
625     xmltooling::NDC ndc("LoadLibrary");
626 #endif
627     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".Config");
628     log.info("loading extension: %s", path);
629
630     Locker locker(this);
631
632     string resolved(path);
633     m_pathResolver->resolve(resolved, PathResolver::XMLTOOLING_LIB_FILE);
634
635 #if defined(WIN32)
636     HMODULE handle=nullptr;
637     for (string::iterator i = resolved.begin(); i != resolved.end(); ++i)
638         if (*i == '/')
639             *i = '\\';
640
641     UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
642     try {
643         handle=LoadLibraryEx(resolved.c_str(),nullptr,LOAD_WITH_ALTERED_SEARCH_PATH);
644         if (!handle)
645              handle=LoadLibraryEx(resolved.c_str(),nullptr,0);
646         if (!handle)
647             throw runtime_error(string("unable to load extension library: ") + resolved);
648         FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
649         if (!fn)
650             throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + resolved);
651         if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
652             throw runtime_error(string("detected error in xmltooling_extension_init: ") + resolved);
653         SetErrorMode(em);
654     }
655     catch(std::exception&) {
656         if (handle)
657             FreeLibrary(handle);
658         SetErrorMode(em);
659         throw;
660     }
661
662 #elif defined(HAVE_DLFCN_H)
663     void* handle=dlopen(resolved.c_str(),RTLD_LAZY);
664     if (!handle)
665         throw runtime_error(string("unable to load extension library '") + resolved + "': " + dlerror());
666     int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
667     if (!fn) {
668         dlclose(handle);
669         throw runtime_error(
670             string("unable to locate xmltooling_extension_init entry point in '") + resolved + "': " +
671                 (dlerror() ? dlerror() : "unknown error")
672             );
673     }
674     try {
675         if (fn(context)!=0)
676             throw runtime_error(string("detected error in xmltooling_extension_init in ") + resolved);
677     }
678     catch(std::exception&) {
679         if (handle)
680             dlclose(handle);
681         throw;
682     }
683 #else
684 # error "Don't know about dynamic loading on this platform!"
685 #endif
686     m_libhandles.push_back(handle);
687     log.info("loaded extension: %s", resolved.c_str());
688     return true;
689 }
690
691 #ifndef XMLTOOLING_NO_XMLSEC
692
693 void xmltooling::log_openssl()
694 {
695     const char* file;
696     const char* data;
697     int flags,line;
698
699     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
700     while (code) {
701         Category& log=Category::getInstance("OpenSSL");
702         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << logging::eol;
703         if (data && (flags & ERR_TXT_STRING))
704             log.errorStream() << "error data: " << data << logging::eol;
705         code=ERR_get_error_line_data(&file,&line,&data,&flags);
706     }
707 }
708
709 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
710 {
711     return new OpenSSLCryptoX509CRL();
712 }
713
714 pair<const char*,unsigned int> XMLToolingInternalConfig::mapXMLAlgorithmToKeyAlgorithm(const XMLCh* xmlAlgorithm) const
715 {
716     for (algmap_t::const_iterator i = m_algorithmMap.begin(); i != m_algorithmMap.end(); ++i) {
717         algmap_t::value_type::second_type::const_iterator j = i->second.find(xmlAlgorithm);
718         if (j != i->second.end())
719             return pair<const char*,unsigned int>(j->second.first.c_str(), j->second.second);
720     }
721     return pair<const char*,unsigned int>(nullptr, 0);
722 }
723
724 void XMLToolingInternalConfig::registerXMLAlgorithm(
725     const XMLCh* xmlAlgorithm, const char* keyAlgorithm, unsigned int size, XMLSecurityAlgorithmType type
726     )
727 {
728     m_algorithmMap[type][xmlAlgorithm] = pair<string,unsigned int>((keyAlgorithm ? keyAlgorithm : ""), size);
729 }
730
731 bool XMLToolingInternalConfig::isXMLAlgorithmSupported(const XMLCh* xmlAlgorithm, XMLSecurityAlgorithmType type)
732 {
733     try {
734         // First check for basic support from the xmlsec layer.
735         if (XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(xmlAlgorithm)) {
736             // Make sure the algorithm is registered.
737             algmap_t::const_iterator i = m_algorithmMap.find(type);
738             if (i != m_algorithmMap.end()) {
739                 algmap_t::value_type::second_type::const_iterator j = i->second.find(xmlAlgorithm);
740                 if (j != i->second.end())
741                     return true;
742             }
743         }
744     }
745     catch (XSECException&) {
746     }
747     return false;
748 }
749
750 void XMLToolingInternalConfig::registerXMLAlgorithms()
751 {
752     // The deal with all the macros is to try and figure out with no false positives whether
753     // the OpenSSL version *and* the XML-Security version support the algorithms.
754
755     // With ECDSA, XML-Security exports a public macro for OpenSSL's support, and any
756     // versions of XML-Security that didn't provide the macro don't handle ECDSA anyway.
757
758     // With AES, all supported XML-Security versions export a macro for OpenSSL's support.
759
760     // With SHA2, only the very latest XML-Security exports a macro, but all the versions
761     // will handle SHA2 *if* OpenSSL does. So we use our own macro to check OpenSSL's
762     // support, and then add checks to see if specific versions are compiled out.
763
764     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIMD5, nullptr, 0, ALGTYPE_DIGEST);
765     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURISHA1, nullptr, 0, ALGTYPE_DIGEST);
766 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA256)
767     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURISHA224, nullptr, 0, ALGTYPE_DIGEST);
768     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURISHA256, nullptr, 0, ALGTYPE_DIGEST);
769 #endif
770 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA512)
771     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURISHA384, nullptr, 0, ALGTYPE_DIGEST);
772     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURISHA512, nullptr, 0, ALGTYPE_DIGEST);
773 #endif
774
775     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIDSA_SHA1, "DSA", 0, ALGTYPE_SIGN);
776     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_MD5, "RSA", 0, ALGTYPE_SIGN);
777     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA1, "RSA", 0, ALGTYPE_SIGN);
778 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA256)
779     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA224, "RSA", 0, ALGTYPE_SIGN);
780     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA256, "RSA", 0, ALGTYPE_SIGN);
781 #endif
782 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA512)
783     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA384, "RSA", 0, ALGTYPE_SIGN);
784     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA512, "RSA", 0, ALGTYPE_SIGN);
785 #endif
786
787 #ifdef XSEC_OPENSSL_HAVE_EC
788     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIECDSA_SHA1, "EC", 0, ALGTYPE_SIGN);
789 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA256)
790     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIECDSA_SHA256, "EC", 0, ALGTYPE_SIGN);
791 # endif
792 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA512)
793     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIECDSA_SHA384, "EC", 0, ALGTYPE_SIGN);
794     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIECDSA_SHA512, "EC", 0, ALGTYPE_SIGN);
795 # endif
796 #endif
797
798     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA1, "HMAC", 0, ALGTYPE_SIGN);
799 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA256)
800     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA224, "HMAC", 0, ALGTYPE_SIGN);
801     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA256, "HMAC", 0, ALGTYPE_SIGN);
802 #endif
803 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA512)
804     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA384, "HMAC", 0, ALGTYPE_SIGN);
805     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA512, "HMAC", 0, ALGTYPE_SIGN);
806 #endif
807
808     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_1_5, "RSA", 0, ALGTYPE_KEYENCRYPT);
809     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_OAEP_MGFP1, "RSA", 0, ALGTYPE_KEYENCRYPT);
810
811     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURI3DES_CBC, "DESede", 192, ALGTYPE_ENCRYPT);
812     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_3DES, "DESede", 192, ALGTYPE_KEYENCRYPT);
813
814 #ifdef XSEC_OPENSSL_HAVE_AES
815     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES128_CBC, "AES", 128, ALGTYPE_ENCRYPT);
816     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES128, "AES", 128, ALGTYPE_KEYENCRYPT);
817
818     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES192_CBC, "AES", 192, ALGTYPE_ENCRYPT);
819     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES192, "AES", 192, ALGTYPE_KEYENCRYPT);
820
821     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES256_CBC, "AES", 256, ALGTYPE_ENCRYPT);
822     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES256, "AES", 256, ALGTYPE_KEYENCRYPT);
823 #endif
824 }
825
826 #endif
827
828 #ifdef WIN32
829
830 extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)
831 {
832     if (fdwReason == DLL_THREAD_DETACH || fdwReason == DLL_PROCESS_DETACH)
833         ThreadKey::onDetach();
834     return TRUE;
835 }
836
837 #endif