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