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