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