Add schema for new config settings
[shibboleth/cpp-sp.git] / shibsp / SPConfig.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SPConfig.cpp
23  *
24  * Library configuration.
25  */
26
27 #include "internal.h"
28
29 #if defined(XMLTOOLING_LOG4SHIB)
30 # ifndef SHIBSP_LOG4SHIB
31 #  error "Logging library mismatch (XMLTooling is using log4shib)."
32 # endif
33 #elif defined(XMLTOOLING_LOG4CPP)
34 # ifndef SHIBSP_LOG4CPP
35 #  error "Logging library mismatch (XMLTooling is using log4cpp)."
36 # endif
37 #else
38 # error "No supported logging library."
39 #endif
40
41 #include "exceptions.h"
42 #include "version.h"
43 #include "AccessControl.h"
44 #include "RequestMapper.h"
45 #include "ServiceProvider.h"
46 #include "SessionCache.h"
47 #include "SPConfig.h"
48 #include "attribute/Attribute.h"
49 #include "binding/ProtocolProvider.h"
50 #include "handler/LogoutInitiator.h"
51 #include "handler/SessionInitiator.h"
52 #include "remoting/ListenerService.h"
53
54 #ifndef SHIBSP_LITE
55 # include "attribute/AttributeDecoder.h"
56 # include "attribute/filtering/AttributeFilter.h"
57 # include "attribute/filtering/MatchFunctor.h"
58 # include "attribute/resolver/AttributeExtractor.h"
59 # include "attribute/resolver/AttributeResolver.h"
60 # include "binding/ArtifactResolver.h"
61 # include "metadata/MetadataExt.h"
62 # include "security/PKIXTrustEngine.h"
63 # include "security/SecurityPolicyProvider.h"
64 # include <saml/version.h>
65 # include <saml/SAMLConfig.h>
66 #endif
67
68 #include <ctime>
69 #include <boost/scoped_ptr.hpp>
70 #include <xercesc/util/XMLUniDefs.hpp>
71 #include <xmltooling/version.h>
72 #include <xmltooling/XMLToolingConfig.h>
73 #include <xmltooling/util/NDC.h>
74 #include <xmltooling/util/ParserPool.h>
75 #include <xmltooling/util/PathResolver.h>
76 #include <xmltooling/util/TemplateEngine.h>
77 #include <xmltooling/util/Threads.h>
78 #include <xmltooling/util/XMLHelper.h>
79
80 using namespace shibsp;
81 using namespace opensaml;
82 using namespace xmltooling;
83 using namespace boost;
84 using namespace std;
85
86 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
87 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
88 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
89 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
90 DECL_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
91 DECL_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
92
93 #ifdef SHIBSP_LITE
94 DECL_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
95 DECL_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
96 DECL_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
97 DECL_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
98 DECL_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
99 DECL_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
100 #endif
101
102 namespace shibsp {
103     class SHIBSP_DLLLOCAL SPInternalConfig : public SPConfig
104     {
105     public:
106         SPInternalConfig() : m_initCount(0), m_lock(Mutex::create()) {}
107         ~SPInternalConfig() {}
108
109         bool init(const char* catalog_path=nullptr, const char* inst_prefix=nullptr);
110         void term();
111
112     private:
113         int m_initCount;
114         scoped_ptr<Mutex> m_lock;
115     };
116     
117     SPInternalConfig g_config;
118 }
119
120 SPConfig& SPConfig::getConfig()
121 {
122     return g_config;
123 }
124
125 SPConfig::SPConfig() : attribute_value_delimeter(';'), m_serviceProvider(nullptr),
126 #ifndef SHIBSP_LITE
127     m_artifactResolver(nullptr),
128 #endif
129     m_features(0), m_configDoc(nullptr)
130 {
131 }
132
133 SPConfig::~SPConfig()
134 {
135 }
136
137 void SPConfig::setFeatures(unsigned long enabled)
138 {
139     m_features = enabled;
140 }
141
142 unsigned long SPConfig::getFeatures() const {
143     return m_features;
144 }
145
146 bool SPConfig::isEnabled(components_t feature) const
147 {
148     return (m_features & feature)>0;
149 }
150
151 ServiceProvider* SPConfig::getServiceProvider() const
152 {
153     return m_serviceProvider;
154 }
155
156 void SPConfig::setServiceProvider(ServiceProvider* serviceProvider)
157 {
158     delete m_serviceProvider;
159     m_serviceProvider = serviceProvider;
160 }
161
162 #ifndef SHIBSP_LITE
163 void SPConfig::setArtifactResolver(MessageDecoder::ArtifactResolver* artifactResolver)
164 {
165     delete m_artifactResolver;
166     m_artifactResolver = artifactResolver;
167 }
168
169 const MessageDecoder::ArtifactResolver* SPConfig::getArtifactResolver() const
170 {
171     return m_artifactResolver;
172 }
173 #endif
174
175 bool SPConfig::init(const char* catalog_path, const char* inst_prefix)
176 {
177     if (!inst_prefix)
178         inst_prefix = getenv("SHIBSP_PREFIX");
179     if (!inst_prefix)
180         inst_prefix = SHIBSP_PREFIX;
181     std::string inst_prefix2;
182     while (*inst_prefix) {
183         inst_prefix2.push_back((*inst_prefix=='\\') ? ('/') : (*inst_prefix));
184         ++inst_prefix;
185     }
186
187     const char* loglevel=getenv("SHIBSP_LOGGING");
188     if (!loglevel)
189         loglevel = SHIBSP_LOGGING;
190     std::string ll(loglevel);
191     PathResolver localpr;
192     localpr.setDefaultPrefix(inst_prefix2.c_str());
193     inst_prefix = getenv("SHIBSP_CFGDIR");
194     if (!inst_prefix)
195         inst_prefix = SHIBSP_CFGDIR;
196     localpr.setCfgDir(inst_prefix);
197     XMLToolingConfig::getConfig().log_config(localpr.resolve(ll, PathResolver::XMLTOOLING_CFG_FILE, PACKAGE_NAME).c_str());
198
199     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
200     log.debug("%s library initialization started", PACKAGE_STRING);
201
202 #ifndef SHIBSP_LITE
203     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
204         " OpenSAML/" + gOpenSAMLDotVersionStr +
205         " XMLTooling/" + gXMLToolingDotVersionStr +
206         " XML-Security-C/" + XSEC_FULLVERSIONDOT +
207         " Xerces-C/" + XERCES_FULLVERSIONDOT +
208 #if defined(LOG4SHIB_VERSION)
209         " log4shib/" + LOG4SHIB_VERSION;
210 #elif defined(LOG4CPP_VERSION)
211         " log4cpp/" + LOG4CPP_VERSION;
212 #endif
213     if (!SAMLConfig::getConfig().init()) {
214         log.fatal("failed to initialize OpenSAML library");
215         return false;
216     }
217 #else
218     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
219         " XMLTooling/" + gXMLToolingDotVersionStr +
220         " Xerces-C/" + XERCES_FULLVERSIONDOT +
221 #if defined(LOG4SHIB_VERSION)
222         " log4shib/" + LOG4SHIB_VERSION;
223 #elif defined(LOG4CPP_VERSION)
224         " log4cpp/" + LOG4CPP_VERSION;
225 #endif
226     if (!XMLToolingConfig::getConfig().init()) {
227         log.fatal("failed to initialize XMLTooling library");
228         return false;
229     }
230 #endif
231     if (!catalog_path)
232         catalog_path = getenv("SHIBSP_SCHEMAS");
233     if (!catalog_path)
234         catalog_path = SHIBSP_SCHEMAS;
235     if (!XMLToolingConfig::getConfig().getValidatingParser().loadCatalogs(catalog_path)) {
236         log.warn("failed to load schema catalogs into validating parser");
237     }
238
239     PathResolver* pr = XMLToolingConfig::getConfig().getPathResolver();
240     pr->setDefaultPackageName(PACKAGE_NAME);
241     pr->setDefaultPrefix(inst_prefix2.c_str());
242     pr->setCfgDir(inst_prefix);
243     inst_prefix = getenv("SHIBSP_LIBDIR");
244     if (!inst_prefix)
245         inst_prefix = SHIBSP_LIBDIR;
246     pr->setLibDir(inst_prefix);
247     inst_prefix = getenv("SHIBSP_LOGDIR");
248     if (!inst_prefix)
249         inst_prefix = SHIBSP_LOGDIR;
250     pr->setLogDir(inst_prefix);
251     inst_prefix = getenv("SHIBSP_RUNDIR");
252     if (!inst_prefix)
253         inst_prefix = SHIBSP_RUNDIR;
254     pr->setRunDir(inst_prefix);
255     inst_prefix = getenv("SHIBSP_XMLDIR");
256     if (!inst_prefix)
257         inst_prefix = SHIBSP_XMLDIR;
258     pr->setXMLDir(inst_prefix);
259
260     XMLToolingConfig::getConfig().setTemplateEngine(new TemplateEngine());
261     XMLToolingConfig::getConfig().getTemplateEngine()->setTagPrefix("shibmlp");
262
263     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
264     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
265     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
266     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
267     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
268     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
269
270 #ifdef SHIBSP_LITE
271     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
272     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
273     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
274     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
275     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
276     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
277 #endif
278
279 #ifndef SHIBSP_LITE
280     if (isEnabled(Metadata))
281         registerMetadataExtClasses();
282     if (isEnabled(Trust))
283         registerPKIXTrustEngine();
284 #endif
285
286     registerAttributeFactories();
287
288     if (isEnabled(Handlers)) {
289         registerHandlers();
290         registerLogoutInitiators();
291         registerSessionInitiators();
292         registerProtocolProviders();
293     }
294
295     registerServiceProviders();
296
297 #ifndef SHIBSP_LITE
298     if (isEnabled(AttributeResolution)) {
299         registerAttributeExtractors();
300         registerAttributeDecoders();
301         registerAttributeResolvers();
302         registerAttributeFilters();
303         registerMatchFunctors();
304     }
305     if (isEnabled(Logging)) {
306         registerEvents();
307     }
308     registerSecurityPolicyProviders();
309 #endif
310
311     if (isEnabled(Listener))
312         registerListenerServices();
313
314     if (isEnabled(RequestMapping)) {
315         registerAccessControls();
316         registerRequestMappers();
317     }
318
319     if (isEnabled(Caching))
320         registerSessionCaches();
321
322 #ifndef SHIBSP_LITE
323     if (isEnabled(OutOfProcess))
324         m_artifactResolver = new ArtifactResolver();
325 #endif
326     srand(static_cast<unsigned int>(std::time(nullptr)));
327
328     log.info("%s library initialization complete", PACKAGE_STRING);
329     return true;
330 }
331
332 void SPConfig::term()
333 {
334     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
335     log.info("%s library shutting down", PACKAGE_STRING);
336
337     setServiceProvider(nullptr);
338     if (m_configDoc)
339         m_configDoc->release();
340     m_configDoc = nullptr;
341 #ifndef SHIBSP_LITE
342     setArtifactResolver(nullptr);
343 #endif
344
345     if (isEnabled(Handlers)) {
346         ArtifactResolutionServiceManager.deregisterFactories();
347         AssertionConsumerServiceManager.deregisterFactories();
348         LogoutInitiatorManager.deregisterFactories();
349         ManageNameIDServiceManager.deregisterFactories();
350         SessionInitiatorManager.deregisterFactories();
351         SingleLogoutServiceManager.deregisterFactories();
352         HandlerManager.deregisterFactories();
353         ProtocolProviderManager.deregisterFactories();
354     }
355
356     ServiceProviderManager.deregisterFactories();
357     Attribute::deregisterFactories();
358
359 #ifndef SHIBSP_LITE
360     SecurityPolicyProviderManager.deregisterFactories();
361     if (isEnabled(Logging)) {
362         EventManager.deregisterFactories();
363     }
364     if (isEnabled(AttributeResolution)) {
365         MatchFunctorManager.deregisterFactories();
366         AttributeFilterManager.deregisterFactories();
367         AttributeDecoderManager.deregisterFactories();
368         AttributeExtractorManager.deregisterFactories();
369         AttributeResolverManager.deregisterFactories();
370     }
371 #endif
372
373     if (isEnabled(Listener))
374         ListenerServiceManager.deregisterFactories();
375
376     if (isEnabled(RequestMapping)) {
377         AccessControlManager.deregisterFactories();
378         RequestMapperManager.deregisterFactories();
379     }
380
381     if (isEnabled(Caching))
382         SessionCacheManager.deregisterFactories();
383
384 #ifndef SHIBSP_LITE
385     SAMLConfig::getConfig().term();
386 #else
387     XMLToolingConfig::getConfig().term();
388 #endif
389     log.info("%s library shutdown complete", PACKAGE_STRING);
390 }
391
392 bool SPConfig::instantiate(const char* config, bool rethrow)
393 {
394 #ifdef _DEBUG
395     NDC ndc("instantiate");
396 #endif
397     if (!config)
398         config = getenv("SHIBSP_CONFIG");
399     if (!config)
400         config = SHIBSP_CONFIG;
401     try {
402         xercesc::DOMDocument* dummydoc;
403         if (*config == '"' || *config == '\'') {
404             throw ConfigurationException("The value of SHIBSP_CONFIG started with a quote.");
405         }
406         else if (*config != '<') {
407
408             // Mock up some XML.
409             string resolved(config);
410             stringstream snippet;
411             snippet
412                 << "<Dummy path='"
413                 << XMLToolingConfig::getConfig().getPathResolver()->resolve(resolved, PathResolver::XMLTOOLING_CFG_FILE)
414                 << "' validate='1'/>";
415             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
416             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
417             setServiceProvider(ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER, dummydoc->getDocumentElement()));
418             if (m_configDoc)
419                 m_configDoc->release();
420             m_configDoc = docjanitor.release();
421         }
422         else {
423             stringstream snippet(config);
424             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
425             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
426             static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
427             auto_ptr_char type(dummydoc->getDocumentElement()->getAttributeNS(nullptr,_type));
428             if (type.get() && *type.get())
429                 setServiceProvider(ServiceProviderManager.newPlugin(type.get(), dummydoc->getDocumentElement()));
430             else
431                 throw ConfigurationException("The supplied XML bootstrapping configuration did not include a type attribute.");
432             if (m_configDoc)
433                 m_configDoc->release();
434             m_configDoc = docjanitor.release();
435         }
436
437         getServiceProvider()->init();
438         return true;
439     }
440     catch (exception& ex) {
441         if (rethrow)
442             throw;
443         Category::getInstance(SHIBSP_LOGCAT".Config").fatal("caught exception while loading configuration: %s", ex.what());
444     }
445     return false;
446 }
447
448 bool SPInternalConfig::init(const char* catalog_path, const char* inst_prefix)
449 {
450 #ifdef _DEBUG
451     xmltooling::NDC ndc("init");
452 #endif
453
454     Lock initLock(m_lock);
455
456     if (m_initCount == INT_MAX) {
457         Category::getInstance(SHIBSP_LOGCAT".Config").crit("library initialized too many times");
458         return false;
459     }
460
461     if (m_initCount >= 1) {
462         ++m_initCount;
463         return true;
464     }
465
466     if (!SPConfig::init(catalog_path, inst_prefix)) {
467         return false;
468     }
469
470     ++m_initCount;
471     return true;
472 }
473
474 void SPInternalConfig::term()
475 {
476 #ifdef _DEBUG
477     xmltooling::NDC ndc("term");
478 #endif
479     
480     Lock initLock(m_lock);
481     if (m_initCount == 0) {
482         Category::getInstance(SHIBSP_LOGCAT".Config").crit("term without corresponding init");
483         return;
484     }
485     else if (--m_initCount > 0) {
486         return;
487     }
488
489     SPConfig::term();
490 }