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