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