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