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/Encrypter.h"
27 #include "impl/UnknownElement.h"
28 #include "security/TrustEngine.h"
29 #include "security/OpenSSLCryptoX509CRL.h"
30 #include "security/CredentialResolver.h"
31 #include "security/KeyInfoResolver.h"
32 #include "signature/Signature.h"
33 #include "soap/SOAP.h"
34 #include "soap/SOAPTransport.h"
36 #include "util/ReplayCache.h"
37 #include "util/StorageService.h"
38 #include "util/TemplateEngine.h"
39 #include "util/URLEncoder.h"
40 #include "util/XMLConstants.h"
41 #include "validation/ValidatorSuite.h"
48 #include <curl/curl.h>
49 #include <log4cpp/Category.hh>
50 #include <log4cpp/PropertyConfigurator.hh>
51 #include <log4cpp/OstreamAppender.hh>
52 #include <xercesc/util/PlatformUtils.hpp>
53 #ifndef XMLTOOLING_NO_XMLSEC
54 #include <xsec/framework/XSECProvider.hpp>
55 #include <openssl/err.h>
58 using namespace soap11;
59 using namespace xmlencryption;
60 using namespace xmlsignature;
61 using namespace xmltooling;
62 using namespace log4cpp;
65 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
66 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
67 DECL_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
68 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
69 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
70 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
71 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownExtensionException,xmltooling);
72 DECL_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
73 DECL_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
75 #ifndef XMLTOOLING_NO_XMLSEC
76 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
77 DECL_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
78 DECL_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
81 namespace xmltooling {
82 static XMLToolingInternalConfig g_config;
83 static vector<Mutex*> g_openssl_locks;
85 extern "C" void openssl_locking_callback(int mode,int n,const char *file,int line)
87 if (mode & CRYPTO_LOCK)
88 g_openssl_locks[n]->lock();
90 g_openssl_locks[n]->unlock();
94 extern "C" unsigned long openssl_thread_id(void)
96 return (unsigned long)(pthread_self());
101 XMLToolingConfig& XMLToolingConfig::getConfig()
106 XMLToolingInternalConfig& XMLToolingInternalConfig::getInternalConfig()
111 bool XMLToolingInternalConfig::log_config(const char* config)
114 if (!config || !*config)
115 config=getenv("XMLTOOLING_LOG_CONFIG");
116 if (!config || !*config)
120 Category& root = Category::getRoot();
121 if (!strcmp(config,"DEBUG")) {
122 root.setPriority(Priority::DEBUG);
125 else if (!strcmp(config,"INFO")) {
126 root.setPriority(Priority::INFO);
129 else if (!strcmp(config,"NOTICE")) {
130 root.setPriority(Priority::NOTICE);
133 else if (!strcmp(config,"WARN")) {
134 root.setPriority(Priority::WARN);
137 else if (!strcmp(config,"ERROR")) {
138 root.setPriority(Priority::ERROR);
141 else if (!strcmp(config,"CRIT")) {
142 root.setPriority(Priority::CRIT);
145 else if (!strcmp(config,"ALERT")) {
146 root.setPriority(Priority::ALERT);
149 else if (!strcmp(config,"EMERG")) {
150 root.setPriority(Priority::EMERG);
153 else if (!strcmp(config,"FATAL")) {
154 root.setPriority(Priority::FATAL);
158 root.setAppender(new OstreamAppender("default",&cerr));
160 PropertyConfigurator::configure(config);
162 catch (const ConfigureFailure& e) {
163 Category::getInstance(XMLTOOLING_LOGCAT".Logging").crit("failed to initialize log4cpp: %s", e.what());
170 void XMLToolingConfig::setReplayCache(ReplayCache* replayCache)
172 delete m_replayCache;
173 m_replayCache = replayCache;
176 void XMLToolingConfig::setTemplateEngine(TemplateEngine* templateEngine)
178 delete m_templateEngine;
179 m_templateEngine = templateEngine;
182 void XMLToolingConfig::setURLEncoder(URLEncoder* urlEncoder)
185 m_urlEncoder = urlEncoder;
188 bool XMLToolingInternalConfig::init()
191 xmltooling::NDC ndc("init");
193 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
195 log.debug("library initialization started");
197 if (curl_global_init(CURL_GLOBAL_ALL)) {
198 log.fatal("failed to initialize libcurl, OpenSSL, or Winsock");
201 log.debug("libcurl %s initialization complete", LIBCURL_VERSION);
203 xercesc::XMLPlatformUtils::Initialize();
204 log.debug("Xerces initialization complete");
206 #ifndef XMLTOOLING_NO_XMLSEC
207 XSECPlatformUtils::Initialise();
208 m_xsecProvider=new XSECProvider();
209 log.debug("XMLSec initialization complete");
212 m_parserPool=new ParserPool();
213 m_validatingPool=new ParserPool(true,true);
214 m_lock=xercesc::XMLPlatformUtils::makeMutex();
216 // Load catalogs from path.
217 if (!catalog_path.empty()) {
218 char* catpath=strdup(catalog_path.c_str());
221 while (start && *start) {
222 sep=strchr(start,PATH_SEPARATOR_CHAR);
225 auto_ptr_XMLCh temp(start);
226 m_validatingPool->loadCatalog(temp.get());
227 start = sep ? sep + 1 : NULL;
232 // default registrations
233 XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
235 registerKeyInfoClasses();
236 registerEncryptionClasses();
237 registerSOAPClasses();
239 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
240 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
241 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
242 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
243 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
244 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
245 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
246 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
248 #ifndef XMLTOOLING_NO_XMLSEC
249 XMLObjectBuilder::registerBuilder(QName(xmlconstants::XMLSIG_NS,Signature::LOCAL_NAME),new SignatureBuilder());
250 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
251 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
252 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
253 registerKeyInfoResolvers();
254 registerCredentialResolvers();
255 registerTrustEngines();
257 registerSOAPTransports();
258 initSOAPTransports();
259 registerStorageServices();
261 m_urlEncoder = new URLEncoder();
262 m_keyInfoResolver = KeyInfoResolverManager.newPlugin(INLINE_KEYINFO_RESOLVER,NULL);
264 // Register xml:id as an ID attribute.
265 static const XMLCh xmlid[] = UNICODE_LITERAL_2(i,d);
266 AttributeExtensibleXMLObject::registerIDAttribute(QName(xmlconstants::XML_NS, xmlid));
268 catch (const xercesc::XMLException&) {
269 log.fatal("caught exception while initializing Xerces");
270 curl_global_cleanup();
274 // Set up OpenSSL locking.
275 for (int i=0; i<CRYPTO_num_locks(); i++)
276 g_openssl_locks.push_back(Mutex::create());
277 CRYPTO_set_locking_callback(openssl_locking_callback);
279 CRYPTO_set_id_callback(openssl_thread_id);
282 log.info("library initialization complete");
286 void XMLToolingInternalConfig::term()
288 CRYPTO_set_locking_callback(NULL);
289 for_each(g_openssl_locks.begin(), g_openssl_locks.end(), xmltooling::cleanup<Mutex>());
290 g_openssl_locks.clear();
292 SchemaValidators.destroyValidators();
293 XMLObjectBuilder::destroyBuilders();
294 XMLToolingException::deregisterFactories();
295 AttributeExtensibleXMLObject::deregisterIDAttributes();
297 StorageServiceManager.deregisterFactories();
298 termSOAPTransports();
299 SOAPTransportManager.deregisterFactories();
300 #ifndef XMLTOOLING_NO_XMLSEC
301 TrustEngineManager.deregisterFactories();
302 CredentialResolverManager.deregisterFactories();
303 KeyInfoResolverManager.deregisterFactories();
306 delete m_keyInfoResolver;
307 m_keyInfoResolver = NULL;
309 delete m_replayCache;
310 m_replayCache = NULL;
312 delete m_templateEngine;
313 m_templateEngine = NULL;
318 for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
320 FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
323 FreeLibrary(static_cast<HMODULE>(*i));
324 #elif defined(HAVE_DLFCN_H)
325 void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
330 # error "Don't know about dynamic loading on this platform!"
333 m_libhandles.clear();
337 delete m_validatingPool;
338 m_validatingPool=NULL;
340 #ifndef XMLTOOLING_NO_XMLSEC
341 delete m_xsecProvider;
343 XSECPlatformUtils::Terminate();
346 xercesc::XMLPlatformUtils::closeMutex(m_lock);
348 xercesc::XMLPlatformUtils::Terminate();
350 curl_global_cleanup();
353 xmltooling::NDC ndc("term");
355 Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
358 Lockable* XMLToolingInternalConfig::lock()
360 xercesc::XMLPlatformUtils::lockMutex(m_lock);
364 void XMLToolingInternalConfig::unlock()
366 xercesc::XMLPlatformUtils::unlockMutex(m_lock);
369 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
372 xmltooling::NDC ndc("LoadLibrary");
374 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
375 log.info("loading extension: %s", path);
381 char* fixed=const_cast<char*>(path);
382 if (strchr(fixed,'/')) {
385 while (p=strchr(p,'/'))
389 UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
391 handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
393 handle=LoadLibraryEx(fixed,NULL,0);
395 throw runtime_error(string("unable to load extension library: ") + fixed);
396 FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
398 throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
399 if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
400 throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
405 catch(runtime_error& e) {
415 #elif defined(HAVE_DLFCN_H)
416 void* handle=dlopen(path,RTLD_LAZY);
418 throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
419 int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
423 string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
424 (dlerror() ? dlerror() : "unknown error")
429 throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
431 catch(runtime_error& e) {
438 # error "Don't know about dynamic loading on this platform!"
440 m_libhandles.push_back(handle);
441 log.info("loaded extension: %s", path);
445 #ifndef XMLTOOLING_NO_XMLSEC
446 void xmltooling::log_openssl()
452 unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
454 Category& log=Category::getInstance("OpenSSL");
455 log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
456 if (data && (flags & ERR_TXT_STRING))
457 log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
458 code=ERR_get_error_line_data(&file,&line,&data,&flags);
462 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
464 return new OpenSSLCryptoX509CRL();