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