ce584320c4cb9e32a0d038ed72fccd66da41f635
[shibboleth/cpp-xmltooling.git] / xmltooling / XMLToolingConfig.cpp
1 /*
2  *  Copyright 2001-2006 Internet2
3  * 
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * XMLToolingConfig.cpp
19  * 
20  * Library configuration 
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "XMLToolingConfig.h"
26 #include "encryption/Encryption.h"
27 #include "impl/UnknownElement.h"
28 #include "security/TrustEngine.h"
29 #include "security/OpenSSLCryptoX509CRL.h"
30 #include "signature/CredentialResolver.h"
31 #include "util/NDC.h"
32 #include "util/XMLConstants.h"
33 #include "validation/Validator.h"
34
35 #ifdef HAVE_DLFCN_H
36 # include <dlfcn.h>
37 #endif
38
39 #include <stdexcept>
40 #include <log4cpp/Category.hh>
41 #include <log4cpp/PropertyConfigurator.hh>
42 #include <log4cpp/OstreamAppender.hh>
43 #include <xercesc/util/PlatformUtils.hpp>
44 #ifndef XMLTOOLING_NO_XMLSEC
45     #include <xsec/framework/XSECProvider.hpp>
46     #include <openssl/err.h>
47 #endif
48
49 using namespace xmlencryption;
50 using namespace xmlsignature;
51 using namespace xmltooling;
52 using namespace log4cpp;
53 using namespace std;
54
55 DECL_EXCEPTION_FACTORY(XMLParserException,xmltooling);
56 DECL_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
57 DECL_EXCEPTION_FACTORY(MarshallingException,xmltooling);
58 DECL_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
59 DECL_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
60 DECL_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
61 DECL_EXCEPTION_FACTORY(UnknownExtensionException,xmltooling);
62 DECL_EXCEPTION_FACTORY(ValidationException,xmltooling);
63
64 #ifndef XMLTOOLING_NO_XMLSEC
65     DECL_EXCEPTION_FACTORY(SignatureException,xmlsignature);
66 #endif
67
68 namespace xmltooling {
69    XMLToolingInternalConfig g_config;
70 }
71
72 XMLToolingConfig& XMLToolingConfig::getConfig()
73 {
74     return g_config;
75 }
76
77 XMLToolingInternalConfig& XMLToolingInternalConfig::getInternalConfig()
78 {
79     return g_config;
80 }
81
82 bool XMLToolingInternalConfig::log_config(const char* config)
83 {
84     try {
85         if (!config || !*config)
86             config=getenv("XMLTOOLING_LOG_CONFIG");
87         if (!config || !*config)
88             config="WARN";
89         
90         bool level=false;
91         Category& root = Category::getRoot();
92         if (!strcmp(config,"DEBUG")) {
93             root.setPriority(Priority::DEBUG);
94             level=true;
95         }
96         else if (!strcmp(config,"INFO")) {
97             root.setPriority(Priority::INFO);
98             level=true;
99         }
100         else if (!strcmp(config,"NOTICE")) {
101             root.setPriority(Priority::NOTICE);
102             level=true;
103         }
104         else if (!strcmp(config,"WARN")) {
105             root.setPriority(Priority::WARN);
106             level=true;
107         }
108         else if (!strcmp(config,"ERROR")) {
109             root.setPriority(Priority::ERROR);
110             level=true;
111         }
112         else if (!strcmp(config,"CRIT")) {
113             root.setPriority(Priority::CRIT);
114             level=true;
115         }
116         else if (!strcmp(config,"ALERT")) {
117             root.setPriority(Priority::ALERT);
118             level=true;
119         }
120         else if (!strcmp(config,"EMERG")) {
121             root.setPriority(Priority::EMERG);
122             level=true;
123         }
124         else if (!strcmp(config,"FATAL")) {
125             root.setPriority(Priority::FATAL);
126             level=true;
127         }
128         if (level)
129             root.setAppender(new OstreamAppender("default",&cerr));
130         else
131             PropertyConfigurator::configure(config);
132     }
133     catch (const ConfigureFailure& e) {
134         Category::getInstance(XMLTOOLING_LOGCAT".Logging").crit("failed to initialize log4cpp: %s", e.what());
135         return false;
136     }
137     
138     return true;
139 }
140
141 bool XMLToolingInternalConfig::init()
142 {
143 #ifdef _DEBUG
144     xmltooling::NDC ndc("init");
145 #endif
146     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
147     try {
148         log.debug("library initialization started");
149
150         xercesc::XMLPlatformUtils::Initialize();
151         log.debug("Xerces initialization complete");
152
153 #ifndef XMLTOOLING_NO_XMLSEC
154         XSECPlatformUtils::Initialise();
155         m_xsecProvider=new XSECProvider();
156         log.debug("XMLSec initialization complete");
157 #endif
158
159         m_parserPool=new ParserPool();
160         m_validatingPool=new ParserPool(true,true);
161         m_lock=xercesc::XMLPlatformUtils::makeMutex();
162
163         // default registrations
164         XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
165
166         registerKeyInfoClasses();
167         registerEncryptionClasses();
168         
169         REGISTER_EXCEPTION_FACTORY(XMLParserException,xmltooling);
170         REGISTER_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
171         REGISTER_EXCEPTION_FACTORY(MarshallingException,xmltooling);
172         REGISTER_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
173         REGISTER_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
174         REGISTER_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
175         REGISTER_EXCEPTION_FACTORY(ValidationException,xmltooling);
176         
177 #ifndef XMLTOOLING_NO_XMLSEC
178         XMLObjectBuilder::registerBuilder(QName(XMLConstants::XMLSIG_NS,Signature::LOCAL_NAME),new SignatureBuilder());
179         REGISTER_EXCEPTION_FACTORY(SignatureException,xmlsignature);
180         registerKeyResolvers();
181         registerCredentialResolvers();
182         registerTrustEngines();
183 #endif
184     }
185     catch (const xercesc::XMLException&) {
186         log.fatal("caught exception while initializing Xerces");
187         return false;
188     }
189
190     log.info("library initialization complete");
191     return true;
192 }
193
194 void XMLToolingInternalConfig::term()
195 {
196     XMLObjectBuilder::destroyBuilders();
197     KeyInfoSchemaValidators.destroyValidators();
198     EncryptionSchemaValidators.destroyValidators();
199     XMLToolingException::deregisterFactories();
200
201 #ifndef XMLTOOLING_NO_XMLSEC
202     TrustEngineManager.deregisterFactories();
203     CredentialResolverManager.deregisterFactories();
204     KeyResolverManager.deregisterFactories();
205 #endif
206
207     for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
208 #if defined(WIN32)
209         FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
210         if (fn)
211             fn();
212         FreeLibrary(static_cast<HMODULE>(*i));
213 #elif defined(HAVE_DLFCN_H)
214         void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
215         if (fn)
216             fn();
217         dlclose(*i);
218 #else
219 # error "Don't know about dynamic loading on this platform!"
220 #endif
221     }
222     m_libhandles.clear();
223     
224     delete m_parserPool;
225     m_parserPool=NULL;
226     delete m_validatingPool;
227     m_validatingPool=NULL;
228
229 #ifndef XMLTOOLING_NO_XMLSEC
230     delete m_xsecProvider;
231     m_xsecProvider=NULL;
232     XSECPlatformUtils::Terminate();
233 #endif
234
235     xercesc::XMLPlatformUtils::closeMutex(m_lock);
236     m_lock=NULL;
237     xercesc::XMLPlatformUtils::Terminate();
238
239  #ifdef _DEBUG
240     xmltooling::NDC ndc("term");
241 #endif
242    Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
243 }
244
245 Lockable* XMLToolingInternalConfig::lock()
246 {
247     xercesc::XMLPlatformUtils::lockMutex(m_lock);
248     return this;
249 }
250
251 void XMLToolingInternalConfig::unlock()
252 {
253     xercesc::XMLPlatformUtils::unlockMutex(m_lock);
254 }
255
256 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
257 {
258 #ifdef _DEBUG
259     xmltooling::NDC ndc("LoadLibrary");
260 #endif
261     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
262     log.info("loading extension: %s", path);
263
264     Locker locker(this);
265
266 #if defined(WIN32)
267     HMODULE handle=NULL;
268     char* fixed=const_cast<char*>(path);
269     if (strchr(fixed,'/')) {
270         fixed=strdup(path);
271         char* p=fixed;
272         while (p=strchr(p,'/'))
273             *p='\\';
274     }
275
276     UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
277     try {
278         handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
279         if (!handle)
280              handle=LoadLibraryEx(fixed,NULL,0);
281         if (!handle)
282             throw runtime_error(string("unable to load extension library: ") + fixed);
283         FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
284         if (!fn)
285             throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
286         if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
287             throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
288         if (fixed!=path)
289             free(fixed);
290         SetErrorMode(em);
291     }
292     catch(runtime_error& e) {
293         log.error(e.what());
294         if (handle)
295             FreeLibrary(handle);
296         SetErrorMode(em);
297         if (fixed!=path)
298             free(fixed);
299         return false;
300     }
301
302 #elif defined(HAVE_DLFCN_H)
303     void* handle=dlopen(path,RTLD_LAZY);
304     if (!handle)
305         throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
306     int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
307     if (!fn) {
308         dlclose(handle);
309         throw runtime_error(
310             string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
311                 (dlerror() ? dlerror() : "unknown error")
312             );
313     }
314     try {
315         if (fn(context)!=0)
316             throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
317     }
318     catch(runtime_error& e) {
319         log.error(e.what());
320         if (handle)
321             dlclose(handle);
322         return false;
323     }
324 #else
325 # error "Don't know about dynamic loading on this platform!"
326 #endif
327     m_libhandles.push_back(handle);
328     log.info("loaded extension: %s", path);
329     return true;
330 }
331
332 #ifndef XMLTOOLING_NO_XMLSEC
333 void xmltooling::log_openssl()
334 {
335     const char* file;
336     const char* data;
337     int flags,line;
338
339     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
340     while (code) {
341         Category& log=Category::getInstance("OpenSSL");
342         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
343         if (data && (flags & ERR_TXT_STRING))
344             log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
345         code=ERR_get_error_line_data(&file,&line,&data,&flags);
346     }
347 }
348
349 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
350 {
351     return new OpenSSLCryptoX509CRL();
352 }
353 #endif