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