Move curl dependent code to full build only.
[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 <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 <curl/curl.h>
55 # include <openssl/err.h>
56 # include <xsec/framework/XSECProvider.hpp>
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 #ifndef XMLTOOLING_NO_XMLSEC
201         if (curl_global_init(CURL_GLOBAL_ALL)) {
202             log.fatal("failed to initialize libcurl, OpenSSL, or Winsock");
203             return false;
204         }
205         log.debug("libcurl %s initialization complete", LIBCURL_VERSION);
206 #endif
207
208         XMLPlatformUtils::Initialize();
209         log.debug("Xerces initialization complete");
210
211 #ifndef XMLTOOLING_NO_XMLSEC
212         XSECPlatformUtils::Initialise();
213         m_xsecProvider=new XSECProvider();
214         log.debug("XMLSec initialization complete");
215 #endif
216
217         m_parserPool=new ParserPool();
218         m_validatingPool=new ParserPool(true,true);
219         m_lock=XMLPlatformUtils::makeMutex();
220         
221         // Load catalogs from path.
222         if (!catalog_path.empty()) {
223             char* catpath=strdup(catalog_path.c_str());
224             char* sep=NULL;
225             char* start=catpath;
226             while (start && *start) {
227                 sep=strchr(start,PATH_SEPARATOR_CHAR);
228                 if (sep)
229                     *sep=0;
230                 auto_ptr_XMLCh temp(start);
231                 m_validatingPool->loadCatalog(temp.get());
232                 start = sep ? sep + 1 : NULL;
233             }
234             free(catpath);
235         }
236
237         // default registrations
238         XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
239
240         registerKeyInfoClasses();
241         registerEncryptionClasses();
242         registerSOAPClasses();
243
244         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLParserException,xmltooling);
245         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
246         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MarshallingException,xmltooling);
247         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
248         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
249         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
250         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ValidationException,xmltooling);
251         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(IOException,xmltooling);
252         
253 #ifndef XMLTOOLING_NO_XMLSEC
254         XMLObjectBuilder::registerBuilder(QName(xmlconstants::XMLSIG_NS,Signature::LOCAL_NAME),new SignatureBuilder());
255         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(XMLSecurityException,xmltooling);
256         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SignatureException,xmlsignature);
257         REGISTER_XMLTOOLING_EXCEPTION_FACTORY(EncryptionException,xmlencryption);
258         registerKeyInfoResolvers();
259         registerCredentialResolvers();
260         registerTrustEngines();
261         registerXMLAlgorithms();
262         registerSOAPTransports();
263         initSOAPTransports();
264 #endif
265         registerStorageServices();
266
267         m_urlEncoder = new URLEncoder();
268 #ifndef XMLTOOLING_NO_XMLSEC
269         m_keyInfoResolver = KeyInfoResolverManager.newPlugin(INLINE_KEYINFO_RESOLVER,NULL);
270 #endif
271         
272         // Register xml:id as an ID attribute.        
273         static const XMLCh xmlid[] = UNICODE_LITERAL_2(i,d);
274         AttributeExtensibleXMLObject::registerIDAttribute(QName(xmlconstants::XML_NS, xmlid)); 
275     }
276     catch (const xercesc::XMLException&) {
277         log.fatal("caught exception while initializing Xerces");
278 #ifndef XMLTOOLING_NO_XMLSEC
279         curl_global_cleanup();
280 #endif
281         return false;
282     }
283
284 #ifndef XMLTOOLING_NO_XMLSEC
285     // Set up OpenSSL locking.
286     for (int i=0; i<CRYPTO_num_locks(); i++)
287         g_openssl_locks.push_back(Mutex::create());
288     CRYPTO_set_locking_callback(openssl_locking_callback);
289 # ifndef WIN32
290     CRYPTO_set_id_callback(openssl_thread_id);
291 # endif
292 #endif
293
294     log.info("library initialization complete");
295     return true;
296 }
297
298 void XMLToolingInternalConfig::term()
299 {
300 #ifndef XMLTOOLING_NO_XMLSEC
301     CRYPTO_set_locking_callback(NULL);
302     for_each(g_openssl_locks.begin(), g_openssl_locks.end(), xmltooling::cleanup<Mutex>());
303     g_openssl_locks.clear();
304 #endif
305
306     SchemaValidators.destroyValidators();
307     XMLObjectBuilder::destroyBuilders();
308     XMLToolingException::deregisterFactories();
309     AttributeExtensibleXMLObject::deregisterIDAttributes();
310
311     StorageServiceManager.deregisterFactories();
312
313 #ifndef XMLTOOLING_NO_XMLSEC
314     termSOAPTransports();
315     SOAPTransportManager.deregisterFactories();
316     TrustEngineManager.deregisterFactories();
317     CredentialResolverManager.deregisterFactories();
318     KeyInfoResolverManager.deregisterFactories();
319     m_algorithmMap.clear();
320
321     delete m_keyInfoResolver;
322     m_keyInfoResolver = NULL;
323 #endif
324
325     delete m_replayCache;
326     m_replayCache = NULL;
327     
328     delete m_templateEngine;
329     m_templateEngine = NULL;
330
331     delete m_urlEncoder;
332     m_urlEncoder = NULL;
333
334     for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
335 #if defined(WIN32)
336         FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
337         if (fn)
338             fn();
339         FreeLibrary(static_cast<HMODULE>(*i));
340 #elif defined(HAVE_DLFCN_H)
341         void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
342         if (fn)
343             fn();
344         dlclose(*i);
345 #else
346 # error "Don't know about dynamic loading on this platform!"
347 #endif
348     }
349     m_libhandles.clear();
350     
351     delete m_parserPool;
352     m_parserPool=NULL;
353     delete m_validatingPool;
354     m_validatingPool=NULL;
355
356 #ifndef XMLTOOLING_NO_XMLSEC
357     delete m_xsecProvider;
358     m_xsecProvider=NULL;
359     XSECPlatformUtils::Terminate();
360 #endif
361
362     XMLPlatformUtils::closeMutex(m_lock);
363     m_lock=NULL;
364     XMLPlatformUtils::Terminate();
365
366 #ifndef XMLTOOLING_NO_XMLSEC
367     curl_global_cleanup();
368 #endif   
369 #ifdef _DEBUG
370     xmltooling::NDC ndc("term");
371 #endif
372    Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
373 }
374
375 Lockable* XMLToolingInternalConfig::lock()
376 {
377     xercesc::XMLPlatformUtils::lockMutex(m_lock);
378     return this;
379 }
380
381 void XMLToolingInternalConfig::unlock()
382 {
383     xercesc::XMLPlatformUtils::unlockMutex(m_lock);
384 }
385
386 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
387 {
388 #ifdef _DEBUG
389     xmltooling::NDC ndc("LoadLibrary");
390 #endif
391     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
392     log.info("loading extension: %s", path);
393
394     Locker locker(this);
395
396 #if defined(WIN32)
397     HMODULE handle=NULL;
398     char* fixed=const_cast<char*>(path);
399     if (strchr(fixed,'/')) {
400         fixed=strdup(path);
401         char* p=fixed;
402         while (p=strchr(p,'/'))
403             *p='\\';
404     }
405
406     UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
407     try {
408         handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
409         if (!handle)
410              handle=LoadLibraryEx(fixed,NULL,0);
411         if (!handle)
412             throw runtime_error(string("unable to load extension library: ") + fixed);
413         FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
414         if (!fn)
415             throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
416         if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
417             throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
418         if (fixed!=path)
419             free(fixed);
420         SetErrorMode(em);
421     }
422     catch(runtime_error& e) {
423         log.error(e.what());
424         if (handle)
425             FreeLibrary(handle);
426         SetErrorMode(em);
427         if (fixed!=path)
428             free(fixed);
429         return false;
430     }
431
432 #elif defined(HAVE_DLFCN_H)
433     void* handle=dlopen(path,RTLD_LAZY);
434     if (!handle)
435         throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
436     int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
437     if (!fn) {
438         dlclose(handle);
439         throw runtime_error(
440             string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
441                 (dlerror() ? dlerror() : "unknown error")
442             );
443     }
444     try {
445         if (fn(context)!=0)
446             throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
447     }
448     catch(runtime_error& e) {
449         log.error(e.what());
450         if (handle)
451             dlclose(handle);
452         return false;
453     }
454 #else
455 # error "Don't know about dynamic loading on this platform!"
456 #endif
457     m_libhandles.push_back(handle);
458     log.info("loaded extension: %s", path);
459     return true;
460 }
461
462 #ifndef XMLTOOLING_NO_XMLSEC
463 void xmltooling::log_openssl()
464 {
465     const char* file;
466     const char* data;
467     int flags,line;
468
469     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
470     while (code) {
471         Category& log=Category::getInstance("OpenSSL");
472         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
473         if (data && (flags & ERR_TXT_STRING))
474             log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
475         code=ERR_get_error_line_data(&file,&line,&data,&flags);
476     }
477 }
478
479 XSECCryptoX509CRL* XMLToolingInternalConfig::X509CRL() const
480 {
481     return new OpenSSLCryptoX509CRL();
482 }
483
484 void XMLToolingInternalConfig::registerXMLAlgorithms()
485 {
486     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_MD5, "RSA", 0);
487     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA1, "RSA", 0);
488     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA224, "RSA", 0);
489     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA256, "RSA", 0);
490     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA384, "RSA", 0);
491     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_SHA512, "RSA", 0);
492
493     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_1_5, "RSA", 0);
494     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIRSA_OAEP_MGFP1, "RSA", 0);
495
496     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIDSA_SHA1, "DSA", 0);
497
498     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA1, "HMAC", 0);
499     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA224, "HMAC", 0);
500     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA256, "HMAC", 0);
501     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA384, "HMAC", 0);
502     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIHMAC_SHA512, "HMAC", 0);
503
504     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURI3DES_CBC, "DESede", 192);
505     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_3DES, "DESede", 192);
506
507     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES128_CBC, "AES", 128);
508     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES128, "AES", 128);
509
510     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES192_CBC, "AES", 192);
511     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES192, "AES", 192);
512
513     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIAES256_CBC, "AES", 256);
514     registerXMLAlgorithm(DSIGConstants::s_unicodeStrURIKW_AES256, "AES", 256);
515 }
516 #endif