Bump version, adjust VC build for parallel make, fixes for CPPXT-76.
[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 bool XMLToolingInternalConfig::log_config(const char* config)
223 {
224     try {
225         if (!config || !*config)
226             config=getenv("XMLTOOLING_LOG_CONFIG");
227         if (!config || !*config)
228             config="WARN";
229
230         bool level=false;
231         Category& root = Category::getRoot();
232         if (!strcmp(config,"DEBUG")) {
233             root.setPriority(Priority::DEBUG);
234             level=true;
235         }
236         else if (!strcmp(config,"INFO")) {
237             root.setPriority(Priority::INFO);
238             level=true;
239         }
240         else if (!strcmp(config,"NOTICE")) {
241             root.setPriority(Priority::NOTICE);
242             level=true;
243         }
244         else if (!strcmp(config,"WARN")) {
245             root.setPriority(Priority::WARN);
246             level=true;
247         }
248         else if (!strcmp(config,"ERROR")) {
249             root.setPriority(Priority::ERROR);
250             level=true;
251         }
252         else if (!strcmp(config,"CRIT")) {
253             root.setPriority(Priority::CRIT);
254             level=true;
255         }
256         else if (!strcmp(config,"ALERT")) {
257             root.setPriority(Priority::ALERT);
258             level=true;
259         }
260         else if (!strcmp(config,"EMERG")) {
261             root.setPriority(Priority::EMERG);
262             level=true;
263         }
264         else if (!strcmp(config,"FATAL")) {
265             root.setPriority(Priority::FATAL);
266             level=true;
267         }
268         if (level) {
269             root.setAppender(new OstreamAppender("default",&cerr));
270         }
271         else {
272             string path(config);
273             PropertyConfigurator::configure(m_pathResolver ? m_pathResolver->resolve(path, PathResolver::XMLTOOLING_CFG_FILE) : path);
274         }
275
276 #ifndef XMLTOOLING_NO_XMLSEC
277         Category::getInstance(XMLTOOLING_LOGCAT".Signature.Debugger").setAdditivity(false);
278 #endif
279         }
280     catch (const ConfigureFailure& e) {
281         string msg = string("failed to configure logging: ") + e.what();
282         Category::getInstance(XMLTOOLING_LOGCAT".Logging").crit(msg);
283 #ifdef WIN32
284         LogEvent(nullptr, EVENTLOG_ERROR_TYPE, 2100, nullptr, msg.c_str());
285 #endif
286         return false;
287     }
288
289     return true;
290 }
291
292 #ifndef XMLTOOLING_LITE
293 const KeyInfoResolver* XMLToolingConfig::getKeyInfoResolver() const
294 {
295     return m_keyInfoResolver;
296 }
297
298 ReplayCache* XMLToolingConfig::getReplayCache() const
299 {
300     return m_replayCache;
301 }
302
303 void XMLToolingConfig::setKeyInfoResolver(xmltooling::KeyInfoResolver *keyInfoResolver)
304 {
305     delete m_keyInfoResolver;
306     m_keyInfoResolver = keyInfoResolver;
307 }
308
309 void XMLToolingConfig::setReplayCache(ReplayCache* replayCache)
310 {
311     delete m_replayCache;
312     m_replayCache = replayCache;
313 }
314 #endif
315
316 PathResolver* XMLToolingConfig::getPathResolver() const
317 {
318     return m_pathResolver;
319 }
320
321 TemplateEngine* XMLToolingConfig::getTemplateEngine() const
322 {
323     return m_templateEngine;
324 }
325
326 const URLEncoder* XMLToolingConfig::getURLEncoder() const
327 {
328     return m_urlEncoder;
329 }
330
331 void XMLToolingConfig::setPathResolver(PathResolver* pathResolver)
332 {
333     delete m_pathResolver;
334     m_pathResolver = pathResolver;
335 }
336
337 void XMLToolingConfig::setTemplateEngine(TemplateEngine* templateEngine)
338 {
339     delete m_templateEngine;
340     m_templateEngine = templateEngine;
341 }
342
343 void XMLToolingConfig::setURLEncoder(URLEncoder* urlEncoder)
344 {
345     delete m_urlEncoder;
346     m_urlEncoder = urlEncoder;
347 }
348
349 bool XMLToolingInternalConfig::init()
350 {
351 #ifdef _DEBUG
352     xmltooling::NDC ndc("init");
353 #endif
354     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
355     try {
356         log.debug("library initialization started");
357
358 #ifndef XMLTOOLING_NO_XMLSEC
359         if (curl_global_init(CURL_GLOBAL_ALL)) {
360             log.fatal("failed to initialize libcurl, OpenSSL, or Winsock");
361             return false;
362         }
363         curl_version_info_data* curlver = curl_version_info(CURLVERSION_NOW);
364         if (curlver) {
365             log.debug("libcurl %s initialization complete", curlver->version);
366             if (!(curlver->features & CURL_VERSION_SSL)) {
367                 log.warn("libcurl lacks TLS/SSL support, this will greatly limit functionality");
368             }
369         }
370         else {
371             log.debug("libcurl %s initialization complete", LIBCURL_VERSION);
372         }
373 #endif
374
375         XMLPlatformUtils::Initialize();
376         log.debug("Xerces %s initialization complete", XERCES_FULLVERSIONDOT);
377
378 #ifndef XMLTOOLING_NO_XMLSEC
379         XSECPlatformUtils::Initialise();
380 # ifdef XMLTOOLING_XMLSEC_DEBUGLOGGING
381         XSECPlatformUtils::SetReferenceLoggingSink(TXFMOutputLogFactory);
382 # endif
383         m_xsecProvider=new XSECProvider();
384         log.debug("XML-Security %s initialization complete", XSEC_FULLVERSIONDOT);
385 #endif
386
387         m_parserPool=new ParserPool();
388         m_validatingPool=new ParserPool(true,true);
389         m_lock=XMLPlatformUtils::makeMutex();
390
391         // Load catalogs from path.
392         if (!catalog_path.empty()) {
393             char* catpath=strdup(catalog_path.c_str());
394             char* sep=nullptr;
395             char* start=catpath;
396             while (start && *start) {
397                 sep=strchr(start,PATH_SEPARATOR_CHAR);
398                 if (sep)
399                     *sep=0;
400                 auto_ptr_XMLCh temp(start);
401                 m_validatingPool->loadCatalog(temp.get());
402                 start = sep ? sep + 1 : nullptr;
403             }
404             free(catpath);
405         }
406
407         // default registrations
408         XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
409
410         registerSOAPClasses();
411
412         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
413         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
414         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
415         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
416         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
417         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
418         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
419         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
420
421 #ifndef XMLTOOLING_NO_XMLSEC
422         XMLObjectBuilder::registerBuilder(QName(xmlconstants::XMLSIG_NS,Signature::LOCAL_NAME),new SignatureBuilder());
423         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
424         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
425         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
426         registerKeyInfoClasses();
427         registerEncryptionClasses();
428         registerKeyInfoResolvers();
429         registerCredentialResolvers();
430         registerTrustEngines();
431         registerXMLAlgorithms();
432         registerSOAPTransports();
433         initSOAPTransports();
434         registerStorageServices();
435         m_keyInfoResolver = KeyInfoResolverManager.newPlugin(INLINE_KEYINFO_RESOLVER,nullptr);
436 #endif
437
438         m_pathResolver = new PathResolver();
439         m_urlEncoder = new URLEncoder();
440
441         HTTPResponse::getAllowedSchemes().push_back("https");
442         HTTPResponse::getAllowedSchemes().push_back("http");
443
444         // Register xml:id as an ID attribute.
445         static const XMLCh xmlid[] = UNICODE_LITERAL_2(i,d);
446         AttributeExtensibleXMLObject::registerIDAttribute(QName(xmlconstants::XML_NS, xmlid));
447     }
448     catch (const xercesc::XMLException&) {
449         log.fatal("caught exception while initializing Xerces");
450 #ifndef XMLTOOLING_NO_XMLSEC
451         curl_global_cleanup();
452 #endif
453         return false;
454     }
455
456 #ifndef XMLTOOLING_NO_XMLSEC
457     // Set up OpenSSL locking.
458     for (int i=0; i<CRYPTO_num_locks(); i++)
459         g_openssl_locks.push_back(Mutex::create());
460     CRYPTO_set_locking_callback(openssl_locking_callback);
461 # ifndef WIN32
462     CRYPTO_set_id_callback(openssl_thread_id);
463 # endif
464 #endif
465
466     log.info("%s library initialization complete", PACKAGE_STRING);
467     return true;
468 }
469
470 void XMLToolingInternalConfig::term()
471 {
472 #ifndef XMLTOOLING_NO_XMLSEC
473     CRYPTO_set_locking_callback(nullptr);
474     for_each(g_openssl_locks.begin(), g_openssl_locks.end(), xmltooling::cleanup<Mutex>());
475     g_openssl_locks.clear();
476 #endif
477
478     SchemaValidators.destroyValidators();
479     XMLObjectBuilder::destroyBuilders();
480     XMLToolingException::deregisterFactories();
481     AttributeExtensibleXMLObject::deregisterIDAttributes();
482
483 #ifndef XMLTOOLING_NO_XMLSEC
484     StorageServiceManager.deregisterFactories();
485     termSOAPTransports();
486     SOAPTransportManager.deregisterFactories();
487     TrustEngineManager.deregisterFactories();
488     CredentialResolverManager.deregisterFactories();
489     KeyInfoResolverManager.deregisterFactories();
490     m_algorithmMap.clear();
491
492     delete m_keyInfoResolver;
493     m_keyInfoResolver = nullptr;
494
495     delete m_replayCache;
496     m_replayCache = nullptr;
497 #endif
498
499     delete m_pathResolver;
500     m_pathResolver = nullptr;
501
502     delete m_templateEngine;
503     m_templateEngine = nullptr;
504
505     delete m_urlEncoder;
506     m_urlEncoder = nullptr;
507
508     for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
509 #if defined(WIN32)
510         FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
511         if (fn)
512             fn();
513         FreeLibrary(static_cast<HMODULE>(*i));
514 #elif defined(HAVE_DLFCN_H)
515         void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
516         if (fn)
517             fn();
518         dlclose(*i);
519 #else
520 # error "Don't know about dynamic loading on this platform!"
521 #endif
522     }
523     m_libhandles.clear();
524
525     delete m_parserPool;
526     m_parserPool=nullptr;
527     delete m_validatingPool;
528     m_validatingPool=nullptr;
529
530 #ifndef XMLTOOLING_NO_XMLSEC
531     delete m_xsecProvider;
532     m_xsecProvider=nullptr;
533     XSECPlatformUtils::Terminate();
534 #endif
535
536     XMLPlatformUtils::closeMutex(m_lock);
537     m_lock=nullptr;
538     XMLPlatformUtils::Terminate();
539
540 #ifndef XMLTOOLING_NO_XMLSEC
541     curl_global_cleanup();
542 #endif
543 #ifdef _DEBUG
544     xmltooling::NDC ndc("term");
545 #endif
546    Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("%s library shutdown complete", PACKAGE_STRING);
547 }
548
549 Lockable* XMLToolingInternalConfig::lock()
550 {
551     xercesc::XMLPlatformUtils::lockMutex(m_lock);
552     return this;
553 }
554
555 void XMLToolingInternalConfig::unlock()
556 {
557     xercesc::XMLPlatformUtils::unlockMutex(m_lock);
558 }
559
560 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
561 {
562 #ifdef _DEBUG
563     xmltooling::NDC ndc("LoadLibrary");
564 #endif
565     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
566     log.info("loading extension: %s", path);
567
568     Locker locker(this);
569
570     string resolved(path);
571     m_pathResolver->resolve(resolved, PathResolver::XMLTOOLING_LIB_FILE);
572
573 #if defined(WIN32)
574     HMODULE handle=nullptr;
575     for (string::iterator i = resolved.begin(); i != resolved.end(); ++i)
576         if (*i == '/')
577             *i = '\\';
578
579     UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
580     try {
581         handle=LoadLibraryEx(resolved.c_str(),nullptr,LOAD_WITH_ALTERED_SEARCH_PATH);
582         if (!handle)
583              handle=LoadLibraryEx(resolved.c_str(),nullptr,0);
584         if (!handle)
585             throw runtime_error(string("unable to load extension library: ") + resolved);
586         FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
587         if (!fn)
588             throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + resolved);
589         if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
590             throw runtime_error(string("detected error in xmltooling_extension_init: ") + resolved);
591         SetErrorMode(em);
592     }
593     catch(exception&) {
594         if (handle)
595             FreeLibrary(handle);
596         SetErrorMode(em);
597         throw;
598     }
599
600 #elif defined(HAVE_DLFCN_H)
601     void* handle=dlopen(resolved.c_str(),RTLD_LAZY);
602     if (!handle)
603         throw runtime_error(string("unable to load extension library '") + resolved + "': " + dlerror());
604     int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
605     if (!fn) {
606         dlclose(handle);
607         throw runtime_error(
608             string("unable to locate xmltooling_extension_init entry point in '") + resolved + "': " +
609                 (dlerror() ? dlerror() : "unknown error")
610             );
611     }
612     try {
613         if (fn(context)!=0)
614             throw runtime_error(string("detected error in xmltooling_extension_init in ") + resolved);
615     }
616     catch(exception&) {
617         if (handle)
618             dlclose(handle);
619         throw;
620     }
621 #else
622 # error "Don't know about dynamic loading on this platform!"
623 #endif
624     m_libhandles.push_back(handle);
625     log.info("loaded extension: %s", resolved.c_str());
626     return true;
627 }
628
629 #ifndef XMLTOOLING_NO_XMLSEC
630
631 void xmltooling::log_openssl()
632 {
633     const char* file;
634     const char* data;
635     int flags,line;
636
637     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
638     while (code) {
639         Category& log=Category::getInstance("OpenSSL");
640         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << logging::eol;
641         if (data && (flags & ERR_TXT_STRING))
642             log.errorStream() << "error data: " << data << logging::eol;
643         code=ERR_get_error_line_data(&file,&line,&data,&flags);
644     }
645 }
646
647 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
648 {
649     return new OpenSSLCryptoX509CRL();
650 }
651
652 pair<const char*,unsigned int> XMLToolingInternalConfig::mapXMLAlgorithmToKeyAlgorithm(const XMLCh* xmlAlgorithm) const
653 {
654     for (algmap_t::const_iterator i = m_algorithmMap.begin(); i != m_algorithmMap.end(); ++i) {
655         algmap_t::value_type::second_type::const_iterator j = i->second.find(xmlAlgorithm);
656         if (j != i->second.end())
657             return pair<const char*,unsigned int>(j->second.first.c_str(), j->second.second);
658     }
659     return pair<const char*,unsigned int>(nullptr, 0);
660 }
661
662 void XMLToolingInternalConfig::registerXMLAlgorithm(
663     const XMLCh* xmlAlgorithm, const char* keyAlgorithm, unsigned int size, XMLSecurityAlgorithmType type
664     )
665 {
666     m_algorithmMap[type][xmlAlgorithm] = pair<string,unsigned int>((keyAlgorithm ? keyAlgorithm : ""), size);
667 }
668
669 bool XMLToolingInternalConfig::isXMLAlgorithmSupported(const XMLCh* xmlAlgorithm, XMLSecurityAlgorithmType type)
670 {
671     try {
672         // First check for basic support from the xmlsec layer.
673         if (XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(xmlAlgorithm)) {
674             // Make sure the algorithm is registered.
675             algmap_t::const_iterator i = m_algorithmMap.find(type);
676             if (i != m_algorithmMap.end()) {
677                 algmap_t::value_type::second_type::const_iterator j = i->second.find(xmlAlgorithm);
678                 if (j != i->second.end())
679                     return true;
680             }
681         }
682     }
683     catch (XSECException&) {
684     }
685     return false;
686 }
687
688 void XMLToolingInternalConfig::registerXMLAlgorithms()
689 {
690     // The deal with all the macros is to try and figure out with no false positives whether
691     // the OpenSSL version *and* the XML-Security version support the algorithms.
692
693     // With ECDSA, XML-Security exports a public macro for OpenSSL's support, and any
694     // versions of XML-Security that didn't provide the macro don't handle ECDSA anyway.
695
696     // With AES, all supported XML-Security versions export a macro for OpenSSL's support.
697
698     // With SHA2, only the very latest XML-Security exports a macro, but all the versions
699     // will handle SHA2 *if* OpenSSL does. So we use our own macro to check OpenSSL's
700     // support, and then add checks to see if specific versions are compiled out.
701
702     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIMD5, nullptr, 0, ALGTYPE_DIGEST);
703     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURISHA1, nullptr, 0, ALGTYPE_DIGEST);
704 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA256)
705     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURISHA224, nullptr, 0, ALGTYPE_DIGEST);
706     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURISHA256, nullptr, 0, ALGTYPE_DIGEST);
707 #endif
708 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA512)
709     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURISHA384, nullptr, 0, ALGTYPE_DIGEST);
710     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURISHA512, nullptr, 0, ALGTYPE_DIGEST);
711 #endif
712
713     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIDSA_SHA1, "DSA", 0, ALGTYPE_SIGN);
714     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_MD5, "RSA", 0, ALGTYPE_SIGN);
715     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA1, "RSA", 0, ALGTYPE_SIGN);
716 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA256)
717     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA224, "RSA", 0, ALGTYPE_SIGN);
718     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA256, "RSA", 0, ALGTYPE_SIGN);
719 #endif
720 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA512)
721     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA384, "RSA", 0, ALGTYPE_SIGN);
722     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA512, "RSA", 0, ALGTYPE_SIGN);
723 #endif
724
725 #ifdef XSEC_OPENSSL_HAVE_EC
726     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIECDSA_SHA1, "EC", 0, ALGTYPE_SIGN);
727 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA256)
728     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIECDSA_SHA256, "EC", 0, ALGTYPE_SIGN);
729 # endif
730 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA512)
731     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIECDSA_SHA384, "EC", 0, ALGTYPE_SIGN);
732     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIECDSA_SHA512, "EC", 0, ALGTYPE_SIGN);
733 # endif
734 #endif
735
736     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA1, "HMAC", 0, ALGTYPE_SIGN);
737 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA256)
738     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA224, "HMAC", 0, ALGTYPE_SIGN);
739     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA256, "HMAC", 0, ALGTYPE_SIGN);
740 #endif
741 #if defined(XMLTOOLING_OPENSSL_HAVE_SHA2) && !defined(OPENSSL_NO_SHA512)
742     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA384, "HMAC", 0, ALGTYPE_SIGN);
743     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA512, "HMAC", 0, ALGTYPE_SIGN);
744 #endif
745
746     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_1_5, "RSA", 0, ALGTYPE_KEYENCRYPT);
747     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_OAEP_MGFP1, "RSA", 0, ALGTYPE_KEYENCRYPT);
748
749     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURI3DES_CBC, "DESede", 192, ALGTYPE_ENCRYPT);
750     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_3DES, "DESede", 192, ALGTYPE_KEYENCRYPT);
751
752 #ifdef XSEC_OPENSSL_HAVE_AES
753     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES128_CBC, "AES", 128, ALGTYPE_ENCRYPT);
754     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES128, "AES", 128, ALGTYPE_KEYENCRYPT);
755
756     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES192_CBC, "AES", 192, ALGTYPE_ENCRYPT);
757     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES192, "AES", 192, ALGTYPE_KEYENCRYPT);
758
759     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES256_CBC, "AES", 256, ALGTYPE_ENCRYPT);
760     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES256, "AES", 256, ALGTYPE_KEYENCRYPT);
761 #endif
762 }
763
764 #endif
765
766 #ifdef WIN32
767
768 extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)
769 {
770     if (fdwReason == DLL_THREAD_DETACH || fdwReason == DLL_PROCESS_DETACH)
771         ThreadKey::onDetach();
772     return TRUE;
773 }
774
775 #endif