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