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