Base TrustEngine APIs and explicit key engine impl.
[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 "security/TrustEngine.h"
29 #include "signature/CredentialResolver.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 <stdexcept>
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     #include <openssl/err.h>
46 #endif
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         registerKeyResolvers();
180         registerCredentialResolvers();
181         registerTrustEngines();
182 #endif
183     }
184     catch (const xercesc::XMLException&) {
185         log.fatal("caught exception while initializing Xerces");
186         return false;
187     }
188
189     log.info("library initialization complete");
190     return true;
191 }
192
193 void XMLToolingInternalConfig::term()
194 {
195     XMLObjectBuilder::destroyBuilders();
196     KeyInfoSchemaValidators.destroyValidators();
197     EncryptionSchemaValidators.destroyValidators();
198     XMLToolingException::deregisterFactories();
199
200 #ifndef XMLTOOLING_NO_XMLSEC
201     TrustEngineManager.deregisterFactories();
202     CredentialResolverManager.deregisterFactories();
203     KeyResolverManager.deregisterFactories();
204 #endif
205
206     for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
207 #if defined(WIN32)
208         FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
209         if (fn)
210             fn();
211         FreeLibrary(static_cast<HMODULE>(*i));
212 #elif defined(HAVE_DLFCN_H)
213         void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
214         if (fn)
215             fn();
216         dlclose(*i);
217 #else
218 # error "Don't know about dynamic loading on this platform!"
219 #endif
220     }
221     m_libhandles.clear();
222     
223     delete m_parserPool;
224     m_parserPool=NULL;
225     delete m_validatingPool;
226     m_validatingPool=NULL;
227
228 #ifndef XMLTOOLING_NO_XMLSEC
229     delete m_xsecProvider;
230     m_xsecProvider=NULL;
231     XSECPlatformUtils::Terminate();
232 #endif
233
234     xercesc::XMLPlatformUtils::closeMutex(m_lock);
235     m_lock=NULL;
236     xercesc::XMLPlatformUtils::Terminate();
237
238  #ifdef _DEBUG
239     xmltooling::NDC ndc("term");
240 #endif
241    Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
242 }
243
244 Lockable* XMLToolingInternalConfig::lock()
245 {
246     xercesc::XMLPlatformUtils::lockMutex(m_lock);
247     return this;
248 }
249
250 void XMLToolingInternalConfig::unlock()
251 {
252     xercesc::XMLPlatformUtils::unlockMutex(m_lock);
253 }
254
255 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
256 {
257 #ifdef _DEBUG
258     xmltooling::NDC ndc("LoadLibrary");
259 #endif
260     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
261     log.info("loading extension: %s", path);
262
263     Locker locker(this);
264
265 #if defined(WIN32)
266     HMODULE handle=NULL;
267     char* fixed=const_cast<char*>(path);
268     if (strchr(fixed,'/')) {
269         fixed=strdup(path);
270         char* p=fixed;
271         while (p=strchr(p,'/'))
272             *p='\\';
273     }
274
275     UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
276     try {
277         handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
278         if (!handle)
279              handle=LoadLibraryEx(fixed,NULL,0);
280         if (!handle)
281             throw runtime_error(string("unable to load extension library: ") + fixed);
282         FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
283         if (!fn)
284             throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
285         if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
286             throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
287         if (fixed!=path)
288             free(fixed);
289         SetErrorMode(em);
290     }
291     catch(runtime_error& e) {
292         log.error(e.what());
293         if (handle)
294             FreeLibrary(handle);
295         SetErrorMode(em);
296         if (fixed!=path)
297             free(fixed);
298         return false;
299     }
300
301 #elif defined(HAVE_DLFCN_H)
302     void* handle=dlopen(path,RTLD_LAZY);
303     if (!handle)
304         throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
305     int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
306     if (!fn) {
307         dlclose(handle);
308         throw runtime_error(
309             string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
310                 (dlerror() ? dlerror() : "unknown error")
311             );
312     }
313     try {
314         if (fn(context)!=0)
315             throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
316     }
317     catch(runtime_error& e) {
318         log.error(e.what());
319         if (handle)
320             dlclose(handle);
321         return false;
322     }
323 #else
324 # error "Don't know about dynamic loading on this platform!"
325 #endif
326     m_libhandles.push_back(handle);
327     log.info("loaded extension: %s", path);
328     return true;
329 }
330
331 #ifndef XMLTOOLING_NO_XMLSEC
332 void xmltooling::log_openssl()
333 {
334     const char* file;
335     const char* data;
336     int flags,line;
337
338     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
339     while (code) {
340         Category& log=Category::getInstance("OpenSSL");
341         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
342         if (data && (flags & ERR_TXT_STRING))
343             log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
344         code=ERR_get_error_line_data(&file,&line,&data,&flags);
345     }
346 }
347 #endif