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