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