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