Unified trust engines w/ KeyInfoSource interface, first cut at SOAP transport layer.
[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 "security/OpenSSLCryptoX509CRL.h"
30 #include "signature/CredentialResolver.h"
31 #include "soap/SOAP.h"
32 #include "soap/SOAPTransport.h"
33 #include "util/NDC.h"
34 #include "util/ReplayCache.h"
35 #include "util/StorageService.h"
36 #include "util/TemplateEngine.h"
37 #include "util/XMLConstants.h"
38 #include "validation/ValidatorSuite.h"
39
40 #ifdef HAVE_DLFCN_H
41 # include <dlfcn.h>
42 #endif
43
44 #include <stdexcept>
45 #include <log4cpp/Category.hh>
46 #include <log4cpp/PropertyConfigurator.hh>
47 #include <log4cpp/OstreamAppender.hh>
48 #include <xercesc/util/PlatformUtils.hpp>
49 #ifndef XMLTOOLING_NO_XMLSEC
50     #include <xsec/framework/XSECProvider.hpp>
51     #include <openssl/err.h>
52 #endif
53
54 using namespace soap11;
55 using namespace xmlencryption;
56 using namespace xmlsignature;
57 using namespace xmltooling;
58 using namespace log4cpp;
59 using namespace std;
60
61 DECL_EXCEPTION_FACTORY(XMLParserException,xmltooling);
62 DECL_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
63 DECL_EXCEPTION_FACTORY(MarshallingException,xmltooling);
64 DECL_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
65 DECL_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
66 DECL_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
67 DECL_EXCEPTION_FACTORY(UnknownExtensionException,xmltooling);
68 DECL_EXCEPTION_FACTORY(ValidationException,xmltooling);
69 DECL_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
70 DECL_EXCEPTION_FACTORY(IOException,xmltooling);
71
72 #ifndef XMLTOOLING_NO_XMLSEC
73     DECL_EXCEPTION_FACTORY(SignatureException,xmlsignature);
74 #endif
75
76 namespace xmltooling {
77    XMLToolingInternalConfig g_config;
78 }
79
80 XMLToolingConfig& XMLToolingConfig::getConfig()
81 {
82     return g_config;
83 }
84
85 XMLToolingInternalConfig& XMLToolingInternalConfig::getInternalConfig()
86 {
87     return g_config;
88 }
89
90 bool XMLToolingInternalConfig::log_config(const char* config)
91 {
92     try {
93         if (!config || !*config)
94             config=getenv("XMLTOOLING_LOG_CONFIG");
95         if (!config || !*config)
96             config="WARN";
97         
98         bool level=false;
99         Category& root = Category::getRoot();
100         if (!strcmp(config,"DEBUG")) {
101             root.setPriority(Priority::DEBUG);
102             level=true;
103         }
104         else if (!strcmp(config,"INFO")) {
105             root.setPriority(Priority::INFO);
106             level=true;
107         }
108         else if (!strcmp(config,"NOTICE")) {
109             root.setPriority(Priority::NOTICE);
110             level=true;
111         }
112         else if (!strcmp(config,"WARN")) {
113             root.setPriority(Priority::WARN);
114             level=true;
115         }
116         else if (!strcmp(config,"ERROR")) {
117             root.setPriority(Priority::ERROR);
118             level=true;
119         }
120         else if (!strcmp(config,"CRIT")) {
121             root.setPriority(Priority::CRIT);
122             level=true;
123         }
124         else if (!strcmp(config,"ALERT")) {
125             root.setPriority(Priority::ALERT);
126             level=true;
127         }
128         else if (!strcmp(config,"EMERG")) {
129             root.setPriority(Priority::EMERG);
130             level=true;
131         }
132         else if (!strcmp(config,"FATAL")) {
133             root.setPriority(Priority::FATAL);
134             level=true;
135         }
136         if (level)
137             root.setAppender(new OstreamAppender("default",&cerr));
138         else
139             PropertyConfigurator::configure(config);
140     }
141     catch (const ConfigureFailure& e) {
142         Category::getInstance(XMLTOOLING_LOGCAT".Logging").crit("failed to initialize log4cpp: %s", e.what());
143         return false;
144     }
145     
146     return true;
147 }
148
149 void XMLToolingConfig::setReplayCache(ReplayCache* replayCache)
150 {
151     delete m_replayCache;
152     m_replayCache = replayCache;
153 }
154
155 void XMLToolingConfig::setTemplateEngine(TemplateEngine* templateEngine)
156 {
157     delete m_templateEngine;
158     m_templateEngine = templateEngine;
159 }
160
161 bool XMLToolingInternalConfig::init()
162 {
163 #ifdef _DEBUG
164     xmltooling::NDC ndc("init");
165 #endif
166     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
167     try {
168         log.debug("library initialization started");
169
170         xercesc::XMLPlatformUtils::Initialize();
171         log.debug("Xerces initialization complete");
172
173 #ifndef XMLTOOLING_NO_XMLSEC
174         XSECPlatformUtils::Initialise();
175         m_xsecProvider=new XSECProvider();
176         log.debug("XMLSec initialization complete");
177 #endif
178
179         m_parserPool=new ParserPool();
180         m_validatingPool=new ParserPool(true,true);
181         m_lock=xercesc::XMLPlatformUtils::makeMutex();
182         
183         // Load catalogs from path.
184         if (!catalog_path.empty()) {
185             char* catpath=strdup(catalog_path.c_str());
186             char* sep=NULL;
187             char* start=catpath;
188             while (start && *start) {
189                 sep=strchr(start,PATH_SEPARATOR_CHAR);
190                 if (sep)
191                     *sep=0;
192                 auto_ptr_XMLCh temp(start);
193                 m_validatingPool->loadCatalog(temp.get());
194                 start = sep ? sep + 1 : NULL;
195             }
196             free(catpath);
197         }
198
199         // default registrations
200         XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
201
202         registerKeyInfoClasses();
203         registerEncryptionClasses();
204         registerSOAPClasses();
205         
206         REGISTER_EXCEPTION_FACTORY(XMLParserException,xmltooling);
207         REGISTER_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
208         REGISTER_EXCEPTION_FACTORY(MarshallingException,xmltooling);
209         REGISTER_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
210         REGISTER_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
211         REGISTER_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
212         REGISTER_EXCEPTION_FACTORY(ValidationException,xmltooling);
213         REGISTER_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
214         REGISTER_EXCEPTION_FACTORY(IOException,xmltooling);
215         
216 #ifndef XMLTOOLING_NO_XMLSEC
217         XMLObjectBuilder::registerBuilder(QName(xmlconstants::XMLSIG_NS,Signature::LOCAL_NAME),new SignatureBuilder());
218         REGISTER_EXCEPTION_FACTORY(SignatureException,xmlsignature);
219         registerKeyResolvers();
220         registerCredentialResolvers();
221         registerTrustEngines();
222 #endif
223         registerSOAPTransports();
224         initSOAPTransports();
225         registerStorageServices();
226
227         // Register xml:id as an ID attribute.        
228         static const XMLCh xmlid[] = UNICODE_LITERAL_2(i,d);
229         AttributeExtensibleXMLObject::registerIDAttribute(QName(xmlconstants::XML_NS, xmlid)); 
230     }
231     catch (const xercesc::XMLException&) {
232         log.fatal("caught exception while initializing Xerces");
233         return false;
234     }
235
236     log.info("library initialization complete");
237     return true;
238 }
239
240 void XMLToolingInternalConfig::term()
241 {
242     SchemaValidators.destroyValidators();
243     XMLObjectBuilder::destroyBuilders();
244     XMLToolingException::deregisterFactories();
245     AttributeExtensibleXMLObject::deregisterIDAttributes();
246
247     StorageServiceManager.deregisterFactories();
248     termSOAPTransports();
249     SOAPTransportManager.deregisterFactories();
250 #ifndef XMLTOOLING_NO_XMLSEC
251     TrustEngineManager.deregisterFactories();
252     CredentialResolverManager.deregisterFactories();
253     KeyResolverManager.deregisterFactories();
254 #endif
255
256     delete m_replayCache;
257     m_replayCache = NULL;
258     
259     delete m_templateEngine;
260     m_templateEngine = NULL;
261
262     for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
263 #if defined(WIN32)
264         FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
265         if (fn)
266             fn();
267         FreeLibrary(static_cast<HMODULE>(*i));
268 #elif defined(HAVE_DLFCN_H)
269         void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
270         if (fn)
271             fn();
272         dlclose(*i);
273 #else
274 # error "Don't know about dynamic loading on this platform!"
275 #endif
276     }
277     m_libhandles.clear();
278     
279     delete m_parserPool;
280     m_parserPool=NULL;
281     delete m_validatingPool;
282     m_validatingPool=NULL;
283
284 #ifndef XMLTOOLING_NO_XMLSEC
285     delete m_xsecProvider;
286     m_xsecProvider=NULL;
287     XSECPlatformUtils::Terminate();
288 #endif
289
290     xercesc::XMLPlatformUtils::closeMutex(m_lock);
291     m_lock=NULL;
292     xercesc::XMLPlatformUtils::Terminate();
293
294  #ifdef _DEBUG
295     xmltooling::NDC ndc("term");
296 #endif
297    Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
298 }
299
300 Lockable* XMLToolingInternalConfig::lock()
301 {
302     xercesc::XMLPlatformUtils::lockMutex(m_lock);
303     return this;
304 }
305
306 void XMLToolingInternalConfig::unlock()
307 {
308     xercesc::XMLPlatformUtils::unlockMutex(m_lock);
309 }
310
311 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
312 {
313 #ifdef _DEBUG
314     xmltooling::NDC ndc("LoadLibrary");
315 #endif
316     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
317     log.info("loading extension: %s", path);
318
319     Locker locker(this);
320
321 #if defined(WIN32)
322     HMODULE handle=NULL;
323     char* fixed=const_cast<char*>(path);
324     if (strchr(fixed,'/')) {
325         fixed=strdup(path);
326         char* p=fixed;
327         while (p=strchr(p,'/'))
328             *p='\\';
329     }
330
331     UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
332     try {
333         handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
334         if (!handle)
335              handle=LoadLibraryEx(fixed,NULL,0);
336         if (!handle)
337             throw runtime_error(string("unable to load extension library: ") + fixed);
338         FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
339         if (!fn)
340             throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
341         if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
342             throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
343         if (fixed!=path)
344             free(fixed);
345         SetErrorMode(em);
346     }
347     catch(runtime_error& e) {
348         log.error(e.what());
349         if (handle)
350             FreeLibrary(handle);
351         SetErrorMode(em);
352         if (fixed!=path)
353             free(fixed);
354         return false;
355     }
356
357 #elif defined(HAVE_DLFCN_H)
358     void* handle=dlopen(path,RTLD_LAZY);
359     if (!handle)
360         throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
361     int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
362     if (!fn) {
363         dlclose(handle);
364         throw runtime_error(
365             string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
366                 (dlerror() ? dlerror() : "unknown error")
367             );
368     }
369     try {
370         if (fn(context)!=0)
371             throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
372     }
373     catch(runtime_error& e) {
374         log.error(e.what());
375         if (handle)
376             dlclose(handle);
377         return false;
378     }
379 #else
380 # error "Don't know about dynamic loading on this platform!"
381 #endif
382     m_libhandles.push_back(handle);
383     log.info("loaded extension: %s", path);
384     return true;
385 }
386
387 #ifndef XMLTOOLING_NO_XMLSEC
388 void xmltooling::log_openssl()
389 {
390     const char* file;
391     const char* data;
392     int flags,line;
393
394     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
395     while (code) {
396         Category& log=Category::getInstance("OpenSSL");
397         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
398         if (data && (flags & ERR_TXT_STRING))
399             log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
400         code=ERR_get_error_line_data(&file,&line,&data,&flags);
401     }
402 }
403
404 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
405 {
406     return new OpenSSLCryptoX509CRL();
407 }
408 #endif