Implemented EncryptionMethod schema snippet.
[shibboleth/cpp-xmltooling.git] / xmltooling / XMLToolingConfig.cpp
1 /*
2  *  Copyright 2001-2006 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 "impl/UnknownElement.h"
28 #include "signature/KeyInfo.h"
29 #include "signature/Signature.h"
30 #include "util/NDC.h"
31 #include "util/XMLConstants.h"
32 #include "validation/Validator.h"
33
34 #ifdef HAVE_DLFCN_H
35 # include <dlfcn.h>
36 #endif
37
38 #include <log4cpp/Category.hh>
39 #include <log4cpp/PropertyConfigurator.hh>
40 #include <log4cpp/OstreamAppender.hh>
41 #include <xercesc/util/PlatformUtils.hpp>
42 #ifndef XMLTOOLING_NO_XMLSEC
43     #include <xsec/framework/XSECProvider.hpp>
44 #endif
45
46 #include <stdexcept>
47
48 using namespace xmlencryption;
49 using namespace xmlsignature;
50 using namespace xmltooling;
51 using namespace log4cpp;
52 using namespace std;
53
54 DECL_EXCEPTION_FACTORY(XMLParserException,xmltooling);
55 DECL_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
56 DECL_EXCEPTION_FACTORY(MarshallingException,xmltooling);
57 DECL_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
58 DECL_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
59 DECL_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
60 DECL_EXCEPTION_FACTORY(UnknownExtensionException,xmltooling);
61 DECL_EXCEPTION_FACTORY(ValidationException,xmltooling);
62
63 #ifndef XMLTOOLING_NO_XMLSEC
64     DECL_EXCEPTION_FACTORY(SignatureException,xmlsignature);
65 #endif
66
67 namespace xmltooling {
68    XMLToolingInternalConfig g_config;
69 }
70
71 XMLToolingConfig& XMLToolingConfig::getConfig()
72 {
73     return g_config;
74 }
75
76 XMLToolingInternalConfig& XMLToolingInternalConfig::getInternalConfig()
77 {
78     return g_config;
79 }
80
81 bool XMLToolingInternalConfig::log_config(const char* config)
82 {
83     try {
84         if (!config || !*config)
85             config=getenv("XMLTOOLING_LOG_CONFIG");
86         if (!config || !*config)
87             config="WARN";
88         
89         bool level=false;
90         Category& root = Category::getRoot();
91         if (!strcmp(config,"DEBUG")) {
92             root.setPriority(Priority::DEBUG);
93             level=true;
94         }
95         else if (!strcmp(config,"INFO")) {
96             root.setPriority(Priority::INFO);
97             level=true;
98         }
99         else if (!strcmp(config,"NOTICE")) {
100             root.setPriority(Priority::NOTICE);
101             level=true;
102         }
103         else if (!strcmp(config,"WARN")) {
104             root.setPriority(Priority::WARN);
105             level=true;
106         }
107         else if (!strcmp(config,"ERROR")) {
108             root.setPriority(Priority::ERROR);
109             level=true;
110         }
111         else if (!strcmp(config,"CRIT")) {
112             root.setPriority(Priority::CRIT);
113             level=true;
114         }
115         else if (!strcmp(config,"ALERT")) {
116             root.setPriority(Priority::ALERT);
117             level=true;
118         }
119         else if (!strcmp(config,"EMERG")) {
120             root.setPriority(Priority::EMERG);
121             level=true;
122         }
123         else if (!strcmp(config,"FATAL")) {
124             root.setPriority(Priority::FATAL);
125             level=true;
126         }
127         if (level)
128             root.setAppender(new OstreamAppender("default",&cerr));
129         else
130             PropertyConfigurator::configure(config);
131     }
132     catch (const ConfigureFailure& e) {
133         Category::getInstance(XMLTOOLING_LOGCAT".Logging").crit("failed to initialize log4cpp: %s", e.what());
134         return false;
135     }
136     
137     return true;
138 }
139
140 bool XMLToolingInternalConfig::init()
141 {
142 #ifdef _DEBUG
143     xmltooling::NDC ndc("init");
144 #endif
145     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
146     try {
147         log.debug("library initialization started");
148
149         xercesc::XMLPlatformUtils::Initialize();
150         log.debug("Xerces initialization complete");
151
152 #ifndef XMLTOOLING_NO_XMLSEC
153         XSECPlatformUtils::Initialise();
154         m_xsecProvider=new XSECProvider();
155         log.debug("XMLSec initialization complete");
156 #endif
157
158         m_parserPool=new ParserPool();
159         m_validatingPool=new ParserPool(true,true);
160         m_lock=xercesc::XMLPlatformUtils::makeMutex();
161
162         // default registrations
163         XMLObjectBuilder::registerDefaultBuilder(new UnknownElementBuilder());
164
165         registerKeyInfoClasses();
166         registerEncryptionClasses();
167         
168         REGISTER_EXCEPTION_FACTORY(XMLParserException,xmltooling);
169         REGISTER_EXCEPTION_FACTORY(XMLObjectException,xmltooling);
170         REGISTER_EXCEPTION_FACTORY(MarshallingException,xmltooling);
171         REGISTER_EXCEPTION_FACTORY(UnmarshallingException,xmltooling);
172         REGISTER_EXCEPTION_FACTORY(UnknownElementException,xmltooling);
173         REGISTER_EXCEPTION_FACTORY(UnknownAttributeException,xmltooling);
174         REGISTER_EXCEPTION_FACTORY(ValidationException,xmltooling);
175         
176 #ifndef XMLTOOLING_NO_XMLSEC
177         XMLObjectBuilder::registerBuilder(QName(XMLConstants::XMLSIG_NS,Signature::LOCAL_NAME),new SignatureBuilder());
178         REGISTER_EXCEPTION_FACTORY(SignatureException,xmlsignature);
179 #endif
180     }
181     catch (const xercesc::XMLException&) {
182         log.fatal("caught exception while initializing Xerces");
183         return false;
184     }
185
186     log.info("library initialization complete");
187     return true;
188 }
189
190 void XMLToolingInternalConfig::term()
191 {
192     XMLObjectBuilder::destroyBuilders();
193     Validator::destroyValidators();
194     XMLToolingException::deregisterFactories();
195
196     for (vector<void*>::reverse_iterator i=m_libhandles.rbegin(); i!=m_libhandles.rend(); i++) {
197 #if defined(WIN32)
198         FARPROC fn=GetProcAddress(static_cast<HMODULE>(*i),"xmltooling_extension_term");
199         if (fn)
200             fn();
201         FreeLibrary(static_cast<HMODULE>(*i));
202 #elif defined(HAVE_DLFCN_H)
203         void (*fn)()=(void (*)())dlsym(*i,"xmltooling_extension_term");
204         if (fn)
205             fn();
206         dlclose(*i);
207 #else
208 # error "Don't know about dynamic loading on this platform!"
209 #endif
210     }
211     m_libhandles.clear();
212     
213     delete m_parserPool;
214     m_parserPool=NULL;
215     delete m_validatingPool;
216     m_validatingPool=NULL;
217
218 #ifndef XMLTOOLING_NO_XMLSEC
219     delete m_xsecProvider;
220     m_xsecProvider=NULL;
221     XSECPlatformUtils::Terminate();
222 #endif
223
224     xercesc::XMLPlatformUtils::closeMutex(m_lock);
225     m_lock=NULL;
226     xercesc::XMLPlatformUtils::Terminate();
227
228  #ifdef _DEBUG
229     xmltooling::NDC ndc("term");
230 #endif
231    Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig").info("library shutdown complete");
232 }
233
234 Lockable& XMLToolingInternalConfig::lock()
235 {
236     xercesc::XMLPlatformUtils::lockMutex(m_lock);
237     return *this;
238 }
239
240 void XMLToolingInternalConfig::unlock()
241 {
242     xercesc::XMLPlatformUtils::unlockMutex(m_lock);
243 }
244
245 bool XMLToolingInternalConfig::load_library(const char* path, void* context)
246 {
247 #ifdef _DEBUG
248     xmltooling::NDC ndc("LoadLibrary");
249 #endif
250     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".XMLToolingConfig");
251     log.info("loading extension: %s", path);
252
253     Locker locker(this);
254
255 #if defined(WIN32)
256     HMODULE handle=NULL;
257     char* fixed=const_cast<char*>(path);
258     if (strchr(fixed,'/')) {
259         fixed=strdup(path);
260         char* p=fixed;
261         while (p=strchr(p,'/'))
262             *p='\\';
263     }
264
265     UINT em=SetErrorMode(SEM_FAILCRITICALERRORS);
266     try {
267         handle=LoadLibraryEx(fixed,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
268         if (!handle)
269              handle=LoadLibraryEx(fixed,NULL,0);
270         if (!handle)
271             throw runtime_error(string("unable to load extension library: ") + fixed);
272         FARPROC fn=GetProcAddress(handle,"xmltooling_extension_init");
273         if (!fn)
274             throw runtime_error(string("unable to locate xmltooling_extension_init entry point: ") + fixed);
275         if (reinterpret_cast<int(*)(void*)>(fn)(context)!=0)
276             throw runtime_error(string("detected error in xmltooling_extension_init: ") + fixed);
277         if (fixed!=path)
278             free(fixed);
279         SetErrorMode(em);
280     }
281     catch(runtime_error& e) {
282         log.error(e.what());
283         if (handle)
284             FreeLibrary(handle);
285         SetErrorMode(em);
286         if (fixed!=path)
287             free(fixed);
288         return false;
289     }
290
291 #elif defined(HAVE_DLFCN_H)
292     void* handle=dlopen(path,RTLD_LAZY);
293     if (!handle)
294         throw runtime_error(string("unable to load extension library '") + path + "': " + dlerror());
295     int (*fn)(void*)=(int (*)(void*))(dlsym(handle,"xmltooling_extension_init"));
296     if (!fn) {
297         dlclose(handle);
298         throw runtime_error(
299             string("unable to locate xmltooling_extension_init entry point in '") + path + "': " +
300                 (dlerror() ? dlerror() : "unknown error")
301             );
302     }
303     try {
304         if (fn(context)!=0)
305             throw runtime_error(string("detected error in xmltooling_extension_init in ") + path);
306     }
307     catch(runtime_error& e) {
308         log.error(e.what());
309         if (handle)
310             dlclose(handle);
311         return false;
312     }
313 #else
314 # error "Don't know about dynamic loading on this platform!"
315 #endif
316     m_libhandles.push_back(handle);
317     log.info("loaded extension: %s", path);
318     return true;
319 }