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