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