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