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 "soap/SOAP.h"
32 #include "soap/SOAPTransport.h"
34 #include "util/ReplayCache.h"
35 #include "util/StorageService.h"
36 #include "util/TemplateEngine.h"
37 #include "util/URLEncoder.h"
38 #include "util/XMLConstants.h"
39 #include "validation/ValidatorSuite.h"
46 #include <curl/curl.h>
47 #include <log4cpp/Category.hh>
48 #include <log4cpp/PropertyConfigurator.hh>
49 #include <log4cpp/OstreamAppender.hh>
50 #include <xercesc/util/PlatformUtils.hpp>
51 #ifndef XMLTOOLING_NO_XMLSEC
52 #include <xsec/framework/XSECProvider.hpp>
53 #include <openssl/err.h>
56 using namespace soap11;
57 using namespace xmlencryption;
58 using namespace xmlsignature;
59 using namespace xmltooling;
60 using namespace log4cpp;
63 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
64 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
65 DECL_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
66 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
67 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
68 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
69 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownExtensionException,xmltooling);
70 DECL_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
71 DECL_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
73 #ifndef XMLTOOLING_NO_XMLSEC
74 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
75 DECL_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
76 DECL_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
79 namespace xmltooling {
80 static XMLToolingInternalConfig g_config;
81 static vector<Mutex*> g_openssl_locks;
83 extern "C" void openssl_locking_callback(int mode,int n,const char *file,int line)
85 if (mode & CRYPTO_LOCK)
86 g_openssl_locks[n]->lock();
88 g_openssl_locks[n]->unlock();
92 extern "C" unsigned long openssl_thread_id(void)
94 return (unsigned long)(pthread_self());
99 XMLToolingConfig& XMLToolingConfig::getConfig()
104 XMLToolingInternalConfig& XMLToolingInternalConfig::getInternalConfig()
109 bool XMLToolingInternalConfig::log_config(const char* config)
112 if (!config || !*config)
113 config=getenv("XMLTOOLING_LOG_CONFIG");
114 if (!config || !*config)
118 Category& root = Category::getRoot();
119 if (!strcmp(config,"DEBUG")) {
120 root.setPriority(Priority::DEBUG);
123 else if (!strcmp(config,"INFO")) {
124 root.setPriority(Priority::INFO);
127 else if (!strcmp(config,"NOTICE")) {
128 root.setPriority(Priority::NOTICE);
131 else if (!strcmp(config,"WARN")) {
132 root.setPriority(Priority::WARN);
135 else if (!strcmp(config,"ERROR")) {
136 root.setPriority(Priority::ERROR);
139 else if (!strcmp(config,"CRIT")) {
140 root.setPriority(Priority::CRIT);
143 else if (!strcmp(config,"ALERT")) {
144 root.setPriority(Priority::ALERT);
147 else if (!strcmp(config,"EMERG")) {
148 root.setPriority(Priority::EMERG);
151 else if (!strcmp(config,"FATAL")) {
152 root.setPriority(Priority::FATAL);
156 root.setAppender(new OstreamAppender("default",&cerr));
158 PropertyConfigurator::configure(config);
160 catch (const ConfigureFailure& e) {
161 Category::getInstance(XMLTOOLING_LOGCAT".Logging").crit("failed to initialize log4cpp: %s", e.what());
168 void XMLToolingConfig::setReplayCache(ReplayCache* replayCache)
170 delete m_replayCache;
171 m_replayCache = replayCache;
174 void XMLToolingConfig::setTemplateEngine(TemplateEngine* templateEngine)
176 delete m_templateEngine;
177 m_templateEngine = templateEngine;
180 void XMLToolingConfig::setURLEncoder(URLEncoder* urlEncoder)
183 m_urlEncoder = urlEncoder;
186 bool XMLToolingInternalConfig::init()
189 xmltooling::NDC ndc("init");
191 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
193 log.debug("library initialization started");
195 if (curl_global_init(CURL_GLOBAL_ALL)) {
196 log.fatal("failed to initialize libcurl, OpenSSL, or Winsock");
199 log.debug("libcurl %s initialization complete", LIBCURL_VERSION);
201 xercesc::XMLPlatformUtils::Initialize();
202 log.debug("Xerces initialization complete");
204 #ifndef XMLTOOLING_NO_XMLSEC
205 XSECPlatformUtils::Initialise();
206 m_xsecProvider=new XSECProvider();
207 log.debug("XMLSec initialization complete");
210 m_parserPool=new ParserPool();
211 m_validatingPool=new ParserPool(true,true);
212 m_lock=xercesc::XMLPlatformUtils::makeMutex();
214 // Load catalogs from path.
215 if (!catalog_path.empty()) {
216 char* catpath=strdup(catalog_path.c_str());
219 while (start && *start) {
220 sep=strchr(start,PATH_SEPARATOR_CHAR);
223 auto_ptr_XMLCh temp(start);
224 m_validatingPool->loadCatalog(temp.get());
225 start = sep ? sep + 1 : NULL;
230 // default registrations
231 XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
233 registerKeyInfoClasses();
234 registerEncryptionClasses();
235 registerSOAPClasses();
237 m_urlEncoder = new URLEncoder();
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 registerKeyResolvers();
254 registerCredentialResolvers();
255 registerTrustEngines();
257 registerSOAPTransports();
258 initSOAPTransports();
259 registerStorageServices();
261 // Register xml:id as an ID attribute.
262 static const XMLCh xmlid[] = UNICODE_LITERAL_2(i,d);
263 AttributeExtensibleXMLObject::registerIDAttribute(QName(xmlconstants::XML_NS, xmlid));
265 catch (const xercesc::XMLException&) {
266 log.fatal("caught exception while initializing Xerces");
267 curl_global_cleanup();
271 // Set up OpenSSL locking.
272 for (int i=0; i<CRYPTO_num_locks(); i++)
273 g_openssl_locks.push_back(Mutex::create());
274 CRYPTO_set_locking_callback(openssl_locking_callback);
276 CRYPTO_set_id_callback(openssl_thread_id);
279 log.info("library initialization complete");
283 void XMLToolingInternalConfig::term()
285 CRYPTO_set_locking_callback(NULL);
286 for_each(g_openssl_locks.begin(), g_openssl_locks.end(), xmltooling::cleanup<Mutex>());
287 g_openssl_locks.clear();
289 SchemaValidators.destroyValidators();
290 XMLObjectBuilder::destroyBuilders();
291 XMLToolingException::deregisterFactories();
292 AttributeExtensibleXMLObject::deregisterIDAttributes();
294 StorageServiceManager.deregisterFactories();
295 termSOAPTransports();
296 SOAPTransportManager.deregisterFactories();
297 #ifndef XMLTOOLING_NO_XMLSEC
298 TrustEngineManager.deregisterFactories();
299 CredentialResolverManager.deregisterFactories();
300 KeyResolverManager.deregisterFactories();
303 delete m_replayCache;
304 m_replayCache = NULL;
306 delete m_templateEngine;
307 m_templateEngine = NULL;
312 for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
314 FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
317 FreeLibrary(static_cast<HMODULE>(*i));
318 #elif defined(HAVE_DLFCN_H)
319 void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
324 # error "Don't know about dynamic loading on this platform!"
327 m_libhandles.clear();
331 delete m_validatingPool;
332 m_validatingPool=NULL;
334 #ifndef XMLTOOLING_NO_XMLSEC
335 delete m_xsecProvider;
337 XSECPlatformUtils::Terminate();
340 xercesc::XMLPlatformUtils::closeMutex(m_lock);
342 xercesc::XMLPlatformUtils::Terminate();
344 curl_global_cleanup();
347 xmltooling::NDC ndc("term");
349 Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
352 Lockable* XMLToolingInternalConfig::lock()
354 xercesc::XMLPlatformUtils::lockMutex(m_lock);
358 void XMLToolingInternalConfig::unlock()
360 xercesc::XMLPlatformUtils::unlockMutex(m_lock);
363 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
366 xmltooling::NDC ndc("LoadLibrary");
368 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
369 log.info("loading extension: %s", path);
375 char* fixed=const_cast<char*>(path);
376 if (strchr(fixed,'/')) {
379 while (p=strchr(p,'/'))
383 UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
385 handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
387 handle=LoadLibraryEx(fixed,NULL,0);
389 throw runtime_error(string("unable to load extension library: ") + fixed);
390 FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
392 throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
393 if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
394 throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
399 catch(runtime_error& e) {
409 #elif defined(HAVE_DLFCN_H)
410 void* handle=dlopen(path,RTLD_LAZY);
412 throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
413 int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
417 string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
418 (dlerror() ? dlerror() : "unknown error")
423 throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
425 catch(runtime_error& e) {
432 # error "Don't know about dynamic loading on this platform!"
434 m_libhandles.push_back(handle);
435 log.info("loaded extension: %s", path);
439 #ifndef XMLTOOLING_NO_XMLSEC
440 void xmltooling::log_openssl()
446 unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
448 Category& log=Category::getInstance("OpenSSL");
449 log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
450 if (data && (flags & ERR_TXT_STRING))
451 log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
452 code=ERR_get_error_line_data(&file,&line,&data,&flags);
456 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
458 return new OpenSSLCryptoX509CRL();