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