Multi-line svn commit, see body.
[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 "security/CredentialResolver.h"
31 #include "security/KeyInfoResolver.h"
32 #include "signature/Signature.h"
33 #include "soap/SOAP.h"
34 #include "soap/SOAPTransport.h"
35 #include "util/NDC.h"
36 #include "util/ReplayCache.h"
37 #include "util/StorageService.h"
38 #include "util/TemplateEngine.h"
39 #include "util/URLEncoder.h"
40 #include "util/XMLConstants.h"
41 #include "validation/ValidatorSuite.h"
42
43 #ifdef HAVE_DLFCN_H
44 # include <dlfcn.h>
45 #endif
46
47 #include <stdexcept>
48 #include <curl/curl.h>
49 #include <log4cpp/Category.hh>
50 #include <log4cpp/PropertyConfigurator.hh>
51 #include <log4cpp/OstreamAppender.hh>
52 #include <xercesc/util/PlatformUtils.hpp>
53 #ifndef XMLTOOLING_NO_XMLSEC
54     #include <xsec/framework/XSECProvider.hpp>
55     #include <openssl/err.h>
56 #endif
57
58 using namespace soap11;
59 using namespace xmlencryption;
60 using namespace xmlsignature;
61 using namespace xmltooling;
62 using namespace log4cpp;
63 using namespace std;
64
65 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
66 DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
67 DECL_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
68 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
69 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
70 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
71 DECL_XMLTOOLING_EXCEPTION_FACTORY(UnknownExtensionException,xmltooling);
72 DECL_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
73 DECL_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
74
75 #ifndef XMLTOOLING_NO_XMLSEC
76     DECL_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
77     DECL_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
78     DECL_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
79 #endif
80
81 namespace xmltooling {
82     static XMLToolingInternalConfig g_config;
83     static vector<Mutex*> g_openssl_locks;
84
85     extern "C" void openssl_locking_callback(int mode,int n,const char *file,int line)
86     {
87         if (mode & CRYPTO_LOCK)
88             g_openssl_locks[n]->lock();
89         else
90             g_openssl_locks[n]->unlock();
91     }
92     
93     #ifndef WIN32
94     extern "C" unsigned long openssl_thread_id(void)
95     {
96         return (unsigned long)(pthread_self());
97     }
98     #endif
99 }
100
101 XMLToolingConfig& XMLToolingConfig::getConfig()
102 {
103     return g_config;
104 }
105
106 XMLToolingInternalConfig& XMLToolingInternalConfig::getInternalConfig()
107 {
108     return g_config;
109 }
110
111 bool XMLToolingInternalConfig::log_config(const char* config)
112 {
113     try {
114         if (!config || !*config)
115             config=getenv("XMLTOOLING_LOG_CONFIG");
116         if (!config || !*config)
117             config="WARN";
118         
119         bool level=false;
120         Category& root = Category::getRoot();
121         if (!strcmp(config,"DEBUG")) {
122             root.setPriority(Priority::DEBUG);
123             level=true;
124         }
125         else if (!strcmp(config,"INFO")) {
126             root.setPriority(Priority::INFO);
127             level=true;
128         }
129         else if (!strcmp(config,"NOTICE")) {
130             root.setPriority(Priority::NOTICE);
131             level=true;
132         }
133         else if (!strcmp(config,"WARN")) {
134             root.setPriority(Priority::WARN);
135             level=true;
136         }
137         else if (!strcmp(config,"ERROR")) {
138             root.setPriority(Priority::ERROR);
139             level=true;
140         }
141         else if (!strcmp(config,"CRIT")) {
142             root.setPriority(Priority::CRIT);
143             level=true;
144         }
145         else if (!strcmp(config,"ALERT")) {
146             root.setPriority(Priority::ALERT);
147             level=true;
148         }
149         else if (!strcmp(config,"EMERG")) {
150             root.setPriority(Priority::EMERG);
151             level=true;
152         }
153         else if (!strcmp(config,"FATAL")) {
154             root.setPriority(Priority::FATAL);
155             level=true;
156         }
157         if (level)
158             root.setAppender(new OstreamAppender("default",&cerr));
159         else
160             PropertyConfigurator::configure(config);
161     }
162     catch (const ConfigureFailure& e) {
163         Category::getInstance(XMLTOOLING_LOGCAT".Logging").crit("failed to initialize log4cpp: %s", e.what());
164         return false;
165     }
166     
167     return true;
168 }
169
170 void XMLToolingConfig::setReplayCache(ReplayCache* replayCache)
171 {
172     delete m_replayCache;
173     m_replayCache = replayCache;
174 }
175
176 void XMLToolingConfig::setTemplateEngine(TemplateEngine* templateEngine)
177 {
178     delete m_templateEngine;
179     m_templateEngine = templateEngine;
180 }
181
182 void XMLToolingConfig::setURLEncoder(URLEncoder* urlEncoder)
183 {
184     delete m_urlEncoder;
185     m_urlEncoder = urlEncoder;
186 }
187
188 bool XMLToolingInternalConfig::init()
189 {
190 #ifdef _DEBUG
191     xmltooling::NDC ndc("init");
192 #endif
193     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
194     try {
195         log.debug("library initialization started");
196
197         if (curl_global_init(CURL_GLOBAL_ALL)) {
198             log.fatal("failed to initialize libcurl, OpenSSL, or Winsock");
199             return false;
200         }
201         log.debug("libcurl %s initialization complete", LIBCURL_VERSION);
202
203         XMLPlatformUtils::Initialize();
204         log.debug("Xerces initialization complete");
205
206 #ifndef XMLTOOLING_NO_XMLSEC
207         XSECPlatformUtils::Initialise();
208         m_xsecProvider=new XSECProvider();
209         log.debug("XMLSec initialization complete");
210 #endif
211
212         m_parserPool=new ParserPool();
213         m_validatingPool=new ParserPool(true,true);
214         m_lock=XMLPlatformUtils::makeMutex();
215         
216         // Load catalogs from path.
217         if (!catalog_path.empty()) {
218             char* catpath=strdup(catalog_path.c_str());
219             char* sep=NULL;
220             char* start=catpath;
221             while (start && *start) {
222                 sep=strchr(start,PATH_SEPARATOR_CHAR);
223                 if (sep)
224                     *sep=0;
225                 auto_ptr_XMLCh temp(start);
226                 m_validatingPool->loadCatalog(temp.get());
227                 start = sep ? sep + 1 : NULL;
228             }
229             free(catpath);
230         }
231
232         // default registrations
233         XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
234
235         registerKeyInfoClasses();
236         registerEncryptionClasses();
237         registerSOAPClasses();
238
239         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
240         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
241         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
242         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
243         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
244         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
245         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
246         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
247         
248 #ifndef XMLTOOLING_NO_XMLSEC
249         XMLObjectBuilder::registerBuilder(QName(xmlconstants::XMLSIG_NS,Signature::LOCAL_NAME),new SignatureBuilder());
250         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
251         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
252         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
253         registerKeyInfoResolvers();
254         registerCredentialResolvers();
255         registerTrustEngines();
256         registerXMLAlgorithms();
257 #endif
258         registerSOAPTransports();
259         initSOAPTransports();
260         registerStorageServices();
261
262         m_urlEncoder = new URLEncoder();
263         m_keyInfoResolver = KeyInfoResolverManager.newPlugin(INLINE_KEYINFO_RESOLVER,NULL);
264         
265         // Register xml:id as an ID attribute.        
266         static const XMLCh xmlid[] = UNICODE_LITERAL_2(i,d);
267         AttributeExtensibleXMLObject::registerIDAttribute(QName(xmlconstants::XML_NS, xmlid)); 
268     }
269     catch (const xercesc::XMLException&) {
270         log.fatal("caught exception while initializing Xerces");
271         curl_global_cleanup();
272         return false;
273     }
274
275     // Set up OpenSSL locking.
276     for (int i=0; i<CRYPTO_num_locks(); i++)
277         g_openssl_locks.push_back(Mutex::create());
278     CRYPTO_set_locking_callback(openssl_locking_callback);
279 #ifndef WIN32
280     CRYPTO_set_id_callback(openssl_thread_id);
281 #endif
282
283     log.info("library initialization complete");
284     return true;
285 }
286
287 void XMLToolingInternalConfig::term()
288 {
289     CRYPTO_set_locking_callback(NULL);
290     for_each(g_openssl_locks.begin(), g_openssl_locks.end(), xmltooling::cleanup<Mutex>());
291     g_openssl_locks.clear();
292
293     SchemaValidators.destroyValidators();
294     XMLObjectBuilder::destroyBuilders();
295     XMLToolingException::deregisterFactories();
296     AttributeExtensibleXMLObject::deregisterIDAttributes();
297
298     StorageServiceManager.deregisterFactories();
299     termSOAPTransports();
300     SOAPTransportManager.deregisterFactories();
301 #ifndef XMLTOOLING_NO_XMLSEC
302     TrustEngineManager.deregisterFactories();
303     CredentialResolverManager.deregisterFactories();
304     KeyInfoResolverManager.deregisterFactories();
305     m_algorithmMap.clear();
306 #endif
307
308     delete m_keyInfoResolver;
309     m_keyInfoResolver = NULL;
310
311     delete m_replayCache;
312     m_replayCache = NULL;
313     
314     delete m_templateEngine;
315     m_templateEngine = NULL;
316
317     delete m_urlEncoder;
318     m_urlEncoder = NULL;
319
320     for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
321 #if defined(WIN32)
322         FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
323         if (fn)
324             fn();
325         FreeLibrary(static_cast<HMODULE>(*i));
326 #elif defined(HAVE_DLFCN_H)
327         void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
328         if (fn)
329             fn();
330         dlclose(*i);
331 #else
332 # error "Don't know about dynamic loading on this platform!"
333 #endif
334     }
335     m_libhandles.clear();
336     
337     delete m_parserPool;
338     m_parserPool=NULL;
339     delete m_validatingPool;
340     m_validatingPool=NULL;
341
342 #ifndef XMLTOOLING_NO_XMLSEC
343     delete m_xsecProvider;
344     m_xsecProvider=NULL;
345     XSECPlatformUtils::Terminate();
346 #endif
347
348     XMLPlatformUtils::closeMutex(m_lock);
349     m_lock=NULL;
350     XMLPlatformUtils::Terminate();
351
352     curl_global_cleanup();
353     
354  #ifdef _DEBUG
355     xmltooling::NDC ndc("term");
356 #endif
357    Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
358 }
359
360 Lockable* XMLToolingInternalConfig::lock()
361 {
362     xercesc::XMLPlatformUtils::lockMutex(m_lock);
363     return this;
364 }
365
366 void XMLToolingInternalConfig::unlock()
367 {
368     xercesc::XMLPlatformUtils::unlockMutex(m_lock);
369 }
370
371 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
372 {
373 #ifdef _DEBUG
374     xmltooling::NDC ndc("LoadLibrary");
375 #endif
376     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
377     log.info("loading extension: %s", path);
378
379     Locker locker(this);
380
381 #if defined(WIN32)
382     HMODULE handle=NULL;
383     char* fixed=const_cast<char*>(path);
384     if (strchr(fixed,'/')) {
385         fixed=strdup(path);
386         char* p=fixed;
387         while (p=strchr(p,'/'))
388             *p='\\';
389     }
390
391     UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
392     try {
393         handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
394         if (!handle)
395              handle=LoadLibraryEx(fixed,NULL,0);
396         if (!handle)
397             throw runtime_error(string("unable to load extension library: ") + fixed);
398         FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
399         if (!fn)
400             throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
401         if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
402             throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
403         if (fixed!=path)
404             free(fixed);
405         SetErrorMode(em);
406     }
407     catch(runtime_error& e) {
408         log.error(e.what());
409         if (handle)
410             FreeLibrary(handle);
411         SetErrorMode(em);
412         if (fixed!=path)
413             free(fixed);
414         return false;
415     }
416
417 #elif defined(HAVE_DLFCN_H)
418     void* handle=dlopen(path,RTLD_LAZY);
419     if (!handle)
420         throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
421     int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
422     if (!fn) {
423         dlclose(handle);
424         throw runtime_error(
425             string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
426                 (dlerror() ? dlerror() : "unknown error")
427             );
428     }
429     try {
430         if (fn(context)!=0)
431             throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
432     }
433     catch(runtime_error& e) {
434         log.error(e.what());
435         if (handle)
436             dlclose(handle);
437         return false;
438     }
439 #else
440 # error "Don't know about dynamic loading on this platform!"
441 #endif
442     m_libhandles.push_back(handle);
443     log.info("loaded extension: %s", path);
444     return true;
445 }
446
447 #ifndef XMLTOOLING_NO_XMLSEC
448 void xmltooling::log_openssl()
449 {
450     const char* file;
451     const char* data;
452     int flags,line;
453
454     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
455     while (code) {
456         Category& log=Category::getInstance("OpenSSL");
457         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
458         if (data && (flags & ERR_TXT_STRING))
459             log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
460         code=ERR_get_error_line_data(&file,&line,&data,&flags);
461     }
462 }
463
464 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
465 {
466     return new OpenSSLCryptoX509CRL();
467 }
468
469 void XMLToolingInternalConfig::registerXMLAlgorithms()
470 {
471     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_MD5, "RSA", 0);
472     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA1, "RSA", 0);
473     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA224, "RSA", 0);
474     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA256, "RSA", 0);
475     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA384, "RSA", 0);
476     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA512, "RSA", 0);
477
478     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_1_5, "RSA", 0);
479     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_OAEP_MGFP1, "RSA", 0);
480
481     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIDSA_SHA1, "DSA", 0);
482
483     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA1, "HMAC", 0);
484     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA224, "HMAC", 0);
485     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA256, "HMAC", 0);
486     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA384, "HMAC", 0);
487     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA512, "HMAC", 0);
488
489     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURI3DES_CBC, "DESede", 192);
490     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_3DES, "DESede", 192);
491
492     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES128_CBC, "AES", 128);
493     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES128, "AES", 128);
494
495     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES192_CBC, "AES", 192);
496     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES192, "AES", 192);
497
498     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES256_CBC, "AES", 256);
499     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES256, "AES", 256);
500 }
501 #endif