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