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