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