2 * Copyright 2001-2007 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * XMLToolingConfig.cpp
20 * Library configuration
24 #include "exceptions.h"
25 #include "XMLToolingConfig.h"
26 #include "encryption/Encryption.h"
27 #include "encryption/Encrypter.h"
28 #include "io/HTTPRequest.h"
29 #include "io/HTTPResponse.h"
30 #include "impl/UnknownElement.h"
31 #include "security/TrustEngine.h"
32 #include "security/OpenSSLCryptoX509CRL.h"
33 #include "security/CredentialResolver.h"
34 #include "security/KeyInfoResolver.h"
35 #include "signature/Signature.h"
36 #include "soap/SOAP.h"
37 #include "soap/SOAPTransport.h"
39 #include "util/ReplayCache.h"
40 #include "util/StorageService.h"
41 #include "util/TemplateEngine.h"
42 #include "util/URLEncoder.h"
43 #include "util/XMLConstants.h"
44 #include "validation/ValidatorSuite.h"
51 #include <log4cpp/Category.hh>
52 #include <log4cpp/PropertyConfigurator.hh>
53 #include <log4cpp/OstreamAppender.hh>
54 #include <xercesc/util/PlatformUtils.hpp>
55 #ifndef XMLTOOLING_NO_XMLSEC
56 # include <curl/curl.h>
57 # include <openssl/err.h>
58 # include <xsec/framework/XSECProvider.hpp>
61 using namespace soap11;
62 using namespace xmlencryption;
63 using namespace xmlsignature;
64 using namespace xmltooling;
65 using namespace log4cpp;
68 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
69 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
70 DECL_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
71 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
72 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
73 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
74 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownExtensionException,xmltooling);
75 DECL_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
76 DECL_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
78 #ifndef XMLTOOLING_NO_XMLSEC
79 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
80 DECL_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
81 DECL_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
84 namespace xmltooling {
85 static XMLToolingInternalConfig g_config;
86 #ifndef XMLTOOLING_NO_XMLSEC
87 static vector<Mutex*> g_openssl_locks;
89 extern "C" void openssl_locking_callback(int mode,int n,const char *file,int line)
91 if (mode & CRYPTO_LOCK)
92 g_openssl_locks[n]->lock();
94 g_openssl_locks[n]->unlock();
98 extern "C" unsigned long openssl_thread_id(void)
100 return (unsigned long)(pthread_self());
106 XMLToolingConfig& XMLToolingConfig::getConfig()
111 XMLToolingInternalConfig& XMLToolingInternalConfig::getInternalConfig()
116 bool XMLToolingInternalConfig::log_config(const char* config)
119 if (!config || !*config)
120 config=getenv("XMLTOOLING_LOG_CONFIG");
121 if (!config || !*config)
125 Category& root = Category::getRoot();
126 if (!strcmp(config,"DEBUG")) {
127 root.setPriority(Priority::DEBUG);
130 else if (!strcmp(config,"INFO")) {
131 root.setPriority(Priority::INFO);
134 else if (!strcmp(config,"NOTICE")) {
135 root.setPriority(Priority::NOTICE);
138 else if (!strcmp(config,"WARN")) {
139 root.setPriority(Priority::WARN);
142 else if (!strcmp(config,"ERROR")) {
143 root.setPriority(Priority::ERROR);
146 else if (!strcmp(config,"CRIT")) {
147 root.setPriority(Priority::CRIT);
150 else if (!strcmp(config,"ALERT")) {
151 root.setPriority(Priority::ALERT);
154 else if (!strcmp(config,"EMERG")) {
155 root.setPriority(Priority::EMERG);
158 else if (!strcmp(config,"FATAL")) {
159 root.setPriority(Priority::FATAL);
163 root.setAppender(new OstreamAppender("default",&cerr));
165 PropertyConfigurator::configure(config);
167 catch (const ConfigureFailure& e) {
168 Category::getInstance(XMLTOOLING_LOGCAT".Logging").crit("failed to initialize log4cpp: %s", e.what());
175 #ifndef XMLTOOLING_LITE
176 void XMLToolingConfig::setReplayCache(ReplayCache* replayCache)
178 delete m_replayCache;
179 m_replayCache = replayCache;
183 void XMLToolingConfig::setTemplateEngine(TemplateEngine* templateEngine)
185 delete m_templateEngine;
186 m_templateEngine = templateEngine;
189 void XMLToolingConfig::setURLEncoder(URLEncoder* urlEncoder)
192 m_urlEncoder = urlEncoder;
195 bool XMLToolingInternalConfig::init()
198 xmltooling::NDC ndc("init");
200 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
202 log.debug("library initialization started");
204 #ifndef XMLTOOLING_NO_XMLSEC
205 if (curl_global_init(CURL_GLOBAL_ALL)) {
206 log.fatal("failed to initialize libcurl, OpenSSL, or Winsock");
209 log.debug("libcurl %s initialization complete", LIBCURL_VERSION);
212 XMLPlatformUtils::Initialize();
213 log.debug("Xerces initialization complete");
215 #ifndef XMLTOOLING_NO_XMLSEC
216 XSECPlatformUtils::Initialise();
217 m_xsecProvider=new XSECProvider();
218 log.debug("XMLSec initialization complete");
221 m_parserPool=new ParserPool();
222 m_validatingPool=new ParserPool(true,true);
223 m_lock=XMLPlatformUtils::makeMutex();
225 // Load catalogs from path.
226 if (!catalog_path.empty()) {
227 char* catpath=strdup(catalog_path.c_str());
230 while (start && *start) {
231 sep=strchr(start,PATH_SEPARATOR_CHAR);
234 auto_ptr_XMLCh temp(start);
235 m_validatingPool->loadCatalog(temp.get());
236 start = sep ? sep + 1 : NULL;
241 // default registrations
242 XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
244 registerKeyInfoClasses();
245 registerEncryptionClasses();
246 registerSOAPClasses();
248 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
249 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
250 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
251 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
252 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
253 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
254 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
255 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
257 #ifndef XMLTOOLING_NO_XMLSEC
258 XMLObjectBuilder::registerBuilder(QName(xmlconstants::XMLSIG_NS,Signature::LOCAL_NAME),new SignatureBuilder());
259 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
260 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
261 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
262 registerKeyInfoResolvers();
263 registerCredentialResolvers();
264 registerTrustEngines();
265 registerXMLAlgorithms();
266 registerSOAPTransports();
267 initSOAPTransports();
268 registerStorageServices();
269 m_keyInfoResolver = KeyInfoResolverManager.newPlugin(INLINE_KEYINFO_RESOLVER,NULL);
272 m_urlEncoder = new URLEncoder();
274 // Register xml:id as an ID attribute.
275 static const XMLCh xmlid[] = UNICODE_LITERAL_2(i,d);
276 AttributeExtensibleXMLObject::registerIDAttribute(QName(xmlconstants::XML_NS, xmlid));
278 catch (const xercesc::XMLException&) {
279 log.fatal("caught exception while initializing Xerces");
280 #ifndef XMLTOOLING_NO_XMLSEC
281 curl_global_cleanup();
286 #ifndef XMLTOOLING_NO_XMLSEC
287 // Set up OpenSSL locking.
288 for (int i=0; i<CRYPTO_num_locks(); i++)
289 g_openssl_locks.push_back(Mutex::create());
290 CRYPTO_set_locking_callback(openssl_locking_callback);
292 CRYPTO_set_id_callback(openssl_thread_id);
296 log.info("library initialization complete");
300 void XMLToolingInternalConfig::term()
302 #ifndef XMLTOOLING_NO_XMLSEC
303 CRYPTO_set_locking_callback(NULL);
304 for_each(g_openssl_locks.begin(), g_openssl_locks.end(), xmltooling::cleanup<Mutex>());
305 g_openssl_locks.clear();
308 SchemaValidators.destroyValidators();
309 XMLObjectBuilder::destroyBuilders();
310 XMLToolingException::deregisterFactories();
311 AttributeExtensibleXMLObject::deregisterIDAttributes();
313 #ifndef XMLTOOLING_NO_XMLSEC
314 StorageServiceManager.deregisterFactories();
315 termSOAPTransports();
316 SOAPTransportManager.deregisterFactories();
317 TrustEngineManager.deregisterFactories();
318 CredentialResolverManager.deregisterFactories();
319 KeyInfoResolverManager.deregisterFactories();
320 m_algorithmMap.clear();
322 delete m_keyInfoResolver;
323 m_keyInfoResolver = NULL;
325 delete m_replayCache;
326 m_replayCache = NULL;
329 delete m_templateEngine;
330 m_templateEngine = NULL;
335 for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
337 FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
340 FreeLibrary(static_cast<HMODULE>(*i));
341 #elif defined(HAVE_DLFCN_H)
342 void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
347 # error "Don't know about dynamic loading on this platform!"
350 m_libhandles.clear();
354 delete m_validatingPool;
355 m_validatingPool=NULL;
357 #ifndef XMLTOOLING_NO_XMLSEC
358 delete m_xsecProvider;
360 XSECPlatformUtils::Terminate();
363 XMLPlatformUtils::closeMutex(m_lock);
365 XMLPlatformUtils::Terminate();
367 #ifndef XMLTOOLING_NO_XMLSEC
368 curl_global_cleanup();
371 xmltooling::NDC ndc("term");
373 Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
376 Lockable* XMLToolingInternalConfig::lock()
378 xercesc::XMLPlatformUtils::lockMutex(m_lock);
382 void XMLToolingInternalConfig::unlock()
384 xercesc::XMLPlatformUtils::unlockMutex(m_lock);
387 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
390 xmltooling::NDC ndc("LoadLibrary");
392 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
393 log.info("loading extension: %s", path);
399 char* fixed=const_cast<char*>(path);
400 if (strchr(fixed,'/')) {
403 while (p=strchr(p,'/'))
407 UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
409 handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
411 handle=LoadLibraryEx(fixed,NULL,0);
413 throw runtime_error(string("unable to load extension library: ") + fixed);
414 FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
416 throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
417 if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
418 throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
423 catch(runtime_error& e) {
433 #elif defined(HAVE_DLFCN_H)
434 void* handle=dlopen(path,RTLD_LAZY);
436 throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
437 int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
441 string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
442 (dlerror() ? dlerror() : "unknown error")
447 throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
449 catch(runtime_error& e) {
456 # error "Don't know about dynamic loading on this platform!"
458 m_libhandles.push_back(handle);
459 log.info("loaded extension: %s", path);
463 #ifndef XMLTOOLING_NO_XMLSEC
464 void xmltooling::log_openssl()
470 unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
472 Category& log=Category::getInstance("OpenSSL");
473 log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
474 if (data && (flags & ERR_TXT_STRING))
475 log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
476 code=ERR_get_error_line_data(&file,&line,&data,&flags);
480 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
482 return new OpenSSLCryptoX509CRL();
485 void XMLToolingInternalConfig::registerXMLAlgorithms()
487 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_MD5, "RSA", 0);
488 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA1, "RSA", 0);
489 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA224, "RSA", 0);
490 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA256, "RSA", 0);
491 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA384, "RSA", 0);
492 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA512, "RSA", 0);
494 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_1_5, "RSA", 0);
495 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_OAEP_MGFP1, "RSA", 0);
497 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIDSA_SHA1, "DSA", 0);
499 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA1, "HMAC", 0);
500 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA224, "HMAC", 0);
501 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA256, "HMAC", 0);
502 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA384, "HMAC", 0);
503 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA512, "HMAC", 0);
505 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURI3DES_CBC, "DESede", 192);
506 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_3DES, "DESede", 192);
508 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES128_CBC, "AES", 128);
509 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES128, "AES", 128);
511 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES192_CBC, "AES", 192);
512 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES192, "AES", 192);
514 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES256_CBC, "AES", 256);
515 registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES256, "AES", 256);