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/XMLConstants.h"
38 #include "validation/ValidatorSuite.h"
45 #include <curl/curl.h>
46 #include <log4cpp/Category.hh>
47 #include <log4cpp/PropertyConfigurator.hh>
48 #include <log4cpp/OstreamAppender.hh>
49 #include <xercesc/util/PlatformUtils.hpp>
50 #ifndef XMLTOOLING_NO_XMLSEC
51 #include <xsec/framework/XSECProvider.hpp>
52 #include <openssl/err.h>
55 using namespace soap11;
56 using namespace xmlencryption;
57 using namespace xmlsignature;
58 using namespace xmltooling;
59 using namespace log4cpp;
62 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
63 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
64 DECL_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
65 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
66 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
67 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
68 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownExtensionException,xmltooling);
69 DECL_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
70 DECL_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
72 #ifndef XMLTOOLING_NO_XMLSEC
73 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
74 DECL_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
75 DECL_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
78 namespace xmltooling {
79 static XMLToolingInternalConfig g_config;
80 static vector<Mutex*> g_openssl_locks;
82 extern "C" void openssl_locking_callback(int mode,int n,const char *file,int line)
84 if (mode & CRYPTO_LOCK)
85 g_openssl_locks[n]->lock();
87 g_openssl_locks[n]->unlock();
91 extern "C" unsigned long openssl_thread_id(void)
93 return (unsigned long)(pthread_self());
98 XMLToolingConfig& XMLToolingConfig::getConfig()
103 XMLToolingInternalConfig& XMLToolingInternalConfig::getInternalConfig()
108 bool XMLToolingInternalConfig::log_config(const char* config)
111 if (!config || !*config)
112 config=getenv("XMLTOOLING_LOG_CONFIG");
113 if (!config || !*config)
117 Category& root = Category::getRoot();
118 if (!strcmp(config,"DEBUG")) {
119 root.setPriority(Priority::DEBUG);
122 else if (!strcmp(config,"INFO")) {
123 root.setPriority(Priority::INFO);
126 else if (!strcmp(config,"NOTICE")) {
127 root.setPriority(Priority::NOTICE);
130 else if (!strcmp(config,"WARN")) {
131 root.setPriority(Priority::WARN);
134 else if (!strcmp(config,"ERROR")) {
135 root.setPriority(Priority::ERROR);
138 else if (!strcmp(config,"CRIT")) {
139 root.setPriority(Priority::CRIT);
142 else if (!strcmp(config,"ALERT")) {
143 root.setPriority(Priority::ALERT);
146 else if (!strcmp(config,"EMERG")) {
147 root.setPriority(Priority::EMERG);
150 else if (!strcmp(config,"FATAL")) {
151 root.setPriority(Priority::FATAL);
155 root.setAppender(new OstreamAppender("default",&cerr));
157 PropertyConfigurator::configure(config);
159 catch (const ConfigureFailure& e) {
160 Category::getInstance(XMLTOOLING_LOGCAT".Logging").crit("failed to initialize log4cpp: %s", e.what());
167 void XMLToolingConfig::setReplayCache(ReplayCache* replayCache)
169 delete m_replayCache;
170 m_replayCache = replayCache;
173 void XMLToolingConfig::setTemplateEngine(TemplateEngine* templateEngine)
175 delete m_templateEngine;
176 m_templateEngine = templateEngine;
179 bool XMLToolingInternalConfig::init()
182 xmltooling::NDC ndc("init");
184 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
186 log.debug("library initialization started");
188 if (curl_global_init(CURL_GLOBAL_ALL)) {
189 log.fatal("failed to initialize libcurl, OpenSSL, or Winsock");
192 log.debug("libcurl %s initialization complete", LIBCURL_VERSION);
194 xercesc::XMLPlatformUtils::Initialize();
195 log.debug("Xerces initialization complete");
197 #ifndef XMLTOOLING_NO_XMLSEC
198 XSECPlatformUtils::Initialise();
199 m_xsecProvider=new XSECProvider();
200 log.debug("XMLSec initialization complete");
203 m_parserPool=new ParserPool();
204 m_validatingPool=new ParserPool(true,true);
205 m_lock=xercesc::XMLPlatformUtils::makeMutex();
207 // Load catalogs from path.
208 if (!catalog_path.empty()) {
209 char* catpath=strdup(catalog_path.c_str());
212 while (start && *start) {
213 sep=strchr(start,PATH_SEPARATOR_CHAR);
216 auto_ptr_XMLCh temp(start);
217 m_validatingPool->loadCatalog(temp.get());
218 start = sep ? sep + 1 : NULL;
223 // default registrations
224 XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
226 registerKeyInfoClasses();
227 registerEncryptionClasses();
228 registerSOAPClasses();
230 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
231 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
232 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
233 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
234 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
235 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
236 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
237 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
239 #ifndef XMLTOOLING_NO_XMLSEC
240 XMLObjectBuilder::registerBuilder(QName(xmlconstants::XMLSIG_NS,Signature::LOCAL_NAME),new SignatureBuilder());
241 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
242 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
243 REGISTER_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
244 registerKeyResolvers();
245 registerCredentialResolvers();
246 registerTrustEngines();
248 registerSOAPTransports();
249 initSOAPTransports();
250 registerStorageServices();
252 // Register xml:id as an ID attribute.
253 static const XMLCh xmlid[] = UNICODE_LITERAL_2(i,d);
254 AttributeExtensibleXMLObject::registerIDAttribute(QName(xmlconstants::XML_NS, xmlid));
256 catch (const xercesc::XMLException&) {
257 log.fatal("caught exception while initializing Xerces");
258 curl_global_cleanup();
262 // Set up OpenSSL locking.
263 for (int i=0; i<CRYPTO_num_locks(); i++)
264 g_openssl_locks.push_back(Mutex::create());
265 CRYPTO_set_locking_callback(openssl_locking_callback);
267 CRYPTO_set_id_callback(openssl_thread_id);
270 log.info("library initialization complete");
274 void XMLToolingInternalConfig::term()
276 CRYPTO_set_locking_callback(NULL);
277 for_each(g_openssl_locks.begin(), g_openssl_locks.end(), xmltooling::cleanup<Mutex>());
278 g_openssl_locks.clear();
280 SchemaValidators.destroyValidators();
281 XMLObjectBuilder::destroyBuilders();
282 XMLToolingException::deregisterFactories();
283 AttributeExtensibleXMLObject::deregisterIDAttributes();
285 StorageServiceManager.deregisterFactories();
286 termSOAPTransports();
287 SOAPTransportManager.deregisterFactories();
288 #ifndef XMLTOOLING_NO_XMLSEC
289 TrustEngineManager.deregisterFactories();
290 CredentialResolverManager.deregisterFactories();
291 KeyResolverManager.deregisterFactories();
294 delete m_replayCache;
295 m_replayCache = NULL;
297 delete m_templateEngine;
298 m_templateEngine = NULL;
300 for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
302 FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
305 FreeLibrary(static_cast<HMODULE>(*i));
306 #elif defined(HAVE_DLFCN_H)
307 void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
312 # error "Don't know about dynamic loading on this platform!"
315 m_libhandles.clear();
319 delete m_validatingPool;
320 m_validatingPool=NULL;
322 #ifndef XMLTOOLING_NO_XMLSEC
323 delete m_xsecProvider;
325 XSECPlatformUtils::Terminate();
328 xercesc::XMLPlatformUtils::closeMutex(m_lock);
330 xercesc::XMLPlatformUtils::Terminate();
332 curl_global_cleanup();
335 xmltooling::NDC ndc("term");
337 Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
340 Lockable* XMLToolingInternalConfig::lock()
342 xercesc::XMLPlatformUtils::lockMutex(m_lock);
346 void XMLToolingInternalConfig::unlock()
348 xercesc::XMLPlatformUtils::unlockMutex(m_lock);
351 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
354 xmltooling::NDC ndc("LoadLibrary");
356 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
357 log.info("loading extension: %s", path);
363 char* fixed=const_cast<char*>(path);
364 if (strchr(fixed,'/')) {
367 while (p=strchr(p,'/'))
371 UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
373 handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
375 handle=LoadLibraryEx(fixed,NULL,0);
377 throw runtime_error(string("unable to load extension library: ") + fixed);
378 FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
380 throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
381 if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
382 throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
387 catch(runtime_error& e) {
397 #elif defined(HAVE_DLFCN_H)
398 void* handle=dlopen(path,RTLD_LAZY);
400 throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
401 int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
405 string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
406 (dlerror() ? dlerror() : "unknown error")
411 throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
413 catch(runtime_error& e) {
420 # error "Don't know about dynamic loading on this platform!"
422 m_libhandles.push_back(handle);
423 log.info("loaded extension: %s", path);
427 #ifndef XMLTOOLING_NO_XMLSEC
428 void xmltooling::log_openssl()
434 unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
436 Category& log=Category::getInstance("OpenSSL");
437 log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
438 if (data && (flags & ERR_TXT_STRING))
439 log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
440 code=ERR_get_error_line_data(&file,&line,&data,&flags);
444 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
446 return new OpenSSLCryptoX509CRL();