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