Added built-in ID attribute support to base 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         // Register xml:id as an ID attribute.        
189         static const XMLCh xmlid[] = UNICODE_LITERAL_2(i,d);
190         AttributeExtensibleXMLObject::registerIDAttribute(QName(XMLConstants::XML_NS, xmlid)); 
191     }
192     catch (const xercesc::XMLException&) {
193         log.fatal("caught exception while initializing Xerces");
194         return false;
195     }
196
197     log.info("library initialization complete");
198     return true;
199 }
200
201 void XMLToolingInternalConfig::term()
202 {
203     XMLObjectBuilder::destroyBuilders();
204     KeyInfoSchemaValidators.destroyValidators();
205     EncryptionSchemaValidators.destroyValidators();
206     XMLToolingException::deregisterFactories();
207     AttributeExtensibleXMLObject::deregisterIDAttributes();
208
209 #ifndef XMLTOOLING_NO_XMLSEC
210     TrustEngineManager.deregisterFactories();
211     CredentialResolverManager.deregisterFactories();
212     KeyResolverManager.deregisterFactories();
213 #endif
214
215     for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
216 #if defined(WIN32)
217         FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
218         if (fn)
219             fn();
220         FreeLibrary(static_cast<HMODULE>(*i));
221 #elif defined(HAVE_DLFCN_H)
222         void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
223         if (fn)
224             fn();
225         dlclose(*i);
226 #else
227 # error "Don't know about dynamic loading on this platform!"
228 #endif
229     }
230     m_libhandles.clear();
231     
232     delete m_parserPool;
233     m_parserPool=NULL;
234     delete m_validatingPool;
235     m_validatingPool=NULL;
236
237 #ifndef XMLTOOLING_NO_XMLSEC
238     delete m_xsecProvider;
239     m_xsecProvider=NULL;
240     XSECPlatformUtils::Terminate();
241 #endif
242
243     xercesc::XMLPlatformUtils::closeMutex(m_lock);
244     m_lock=NULL;
245     xercesc::XMLPlatformUtils::Terminate();
246
247  #ifdef _DEBUG
248     xmltooling::NDC ndc("term");
249 #endif
250    Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
251 }
252
253 Lockable* XMLToolingInternalConfig::lock()
254 {
255     xercesc::XMLPlatformUtils::lockMutex(m_lock);
256     return this;
257 }
258
259 void XMLToolingInternalConfig::unlock()
260 {
261     xercesc::XMLPlatformUtils::unlockMutex(m_lock);
262 }
263
264 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
265 {
266 #ifdef _DEBUG
267     xmltooling::NDC ndc("LoadLibrary");
268 #endif
269     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
270     log.info("loading extension: %s", path);
271
272     Locker locker(this);
273
274 #if defined(WIN32)
275     HMODULE handle=NULL;
276     char* fixed=const_cast<char*>(path);
277     if (strchr(fixed,'/')) {
278         fixed=strdup(path);
279         char* p=fixed;
280         while (p=strchr(p,'/'))
281             *p='\\';
282     }
283
284     UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
285     try {
286         handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
287         if (!handle)
288              handle=LoadLibraryEx(fixed,NULL,0);
289         if (!handle)
290             throw runtime_error(string("unable to load extension library: ") + fixed);
291         FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
292         if (!fn)
293             throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
294         if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
295             throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
296         if (fixed!=path)
297             free(fixed);
298         SetErrorMode(em);
299     }
300     catch(runtime_error& e) {
301         log.error(e.what());
302         if (handle)
303             FreeLibrary(handle);
304         SetErrorMode(em);
305         if (fixed!=path)
306             free(fixed);
307         return false;
308     }
309
310 #elif defined(HAVE_DLFCN_H)
311     void* handle=dlopen(path,RTLD_LAZY);
312     if (!handle)
313         throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
314     int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
315     if (!fn) {
316         dlclose(handle);
317         throw runtime_error(
318             string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
319                 (dlerror() ? dlerror() : "unknown error")
320             );
321     }
322     try {
323         if (fn(context)!=0)
324             throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
325     }
326     catch(runtime_error& e) {
327         log.error(e.what());
328         if (handle)
329             dlclose(handle);
330         return false;
331     }
332 #else
333 # error "Don't know about dynamic loading on this platform!"
334 #endif
335     m_libhandles.push_back(handle);
336     log.info("loaded extension: %s", path);
337     return true;
338 }
339
340 #ifndef XMLTOOLING_NO_XMLSEC
341 void xmltooling::log_openssl()
342 {
343     const char* file;
344     const char* data;
345     int flags,line;
346
347     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
348     while (code) {
349         Category& log=Category::getInstance("OpenSSL");
350         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
351         if (data && (flags & ERR_TXT_STRING))
352             log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
353         code=ERR_get_error_line_data(&file,&line,&data,&flags);
354     }
355 }
356
357 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
358 {
359     return new OpenSSLCryptoX509CRL();
360 }
361 #endif