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