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