Remove extra header
[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 <xercesc/util/XMLUniDefs.hpp>
70 #include <xmltooling/version.h>
71 #include <xmltooling/XMLToolingConfig.h>
72 #include <xmltooling/util/NDC.h>
73 #include <xmltooling/util/ParserPool.h>
74 #include <xmltooling/util/PathResolver.h>
75 #include <xmltooling/util/TemplateEngine.h>
76 #include <xmltooling/util/Threads.h>
77 #include <xmltooling/util/XMLHelper.h>
78
79 using namespace shibsp;
80 using namespace opensaml;
81 using namespace xmltooling;
82 using namespace boost;
83 using namespace std;
84
85 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
86 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
87 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
88 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
89 DECL_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
90 DECL_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
91
92 #ifdef SHIBSP_LITE
93 DECL_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
94 DECL_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
95 DECL_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
96 DECL_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
97 DECL_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
98 DECL_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
99 #endif
100
101 namespace shibsp {
102     class SHIBSP_DLLLOCAL SPInternalConfig : public SPConfig
103     {
104     public:
105         SPInternalConfig() : m_initCount(0), m_lock(Mutex::create()) {}
106         ~SPInternalConfig() {}
107
108         bool init(const char* catalog_path=nullptr, const char* inst_prefix=nullptr);
109         void term();
110
111     private:
112         int m_initCount;
113         scoped_ptr<Mutex> m_lock;
114     };
115     
116     SPInternalConfig g_config;
117 }
118
119 SPConfig& SPConfig::getConfig()
120 {
121     return g_config;
122 }
123
124 SPConfig::SPConfig() : attribute_value_delimeter(';'), m_serviceProvider(nullptr),
125 #ifndef SHIBSP_LITE
126     m_artifactResolver(nullptr),
127 #endif
128     m_features(0), m_configDoc(nullptr)
129 {
130 }
131
132 SPConfig::~SPConfig()
133 {
134 }
135
136 void SPConfig::setFeatures(unsigned long enabled)
137 {
138     m_features = enabled;
139 }
140
141 unsigned long SPConfig::getFeatures() const {
142     return m_features;
143 }
144
145 bool SPConfig::isEnabled(components_t feature) const
146 {
147     return (m_features & feature)>0;
148 }
149
150 ServiceProvider* SPConfig::getServiceProvider() const
151 {
152     return m_serviceProvider;
153 }
154
155 void SPConfig::setServiceProvider(ServiceProvider* serviceProvider)
156 {
157     delete m_serviceProvider;
158     m_serviceProvider = serviceProvider;
159 }
160
161 #ifndef SHIBSP_LITE
162 void SPConfig::setArtifactResolver(MessageDecoder::ArtifactResolver* artifactResolver)
163 {
164     delete m_artifactResolver;
165     m_artifactResolver = artifactResolver;
166 }
167
168 const MessageDecoder::ArtifactResolver* SPConfig::getArtifactResolver() const
169 {
170     return m_artifactResolver;
171 }
172 #endif
173
174 bool SPConfig::init(const char* catalog_path, const char* inst_prefix)
175 {
176     if (!inst_prefix)
177         inst_prefix = getenv("SHIBSP_PREFIX");
178     if (!inst_prefix)
179         inst_prefix = SHIBSP_PREFIX;
180     std::string inst_prefix2;
181     while (*inst_prefix) {
182         inst_prefix2.push_back((*inst_prefix=='\\') ? ('/') : (*inst_prefix));
183         ++inst_prefix;
184     }
185
186     const char* loglevel=getenv("SHIBSP_LOGGING");
187     if (!loglevel)
188         loglevel = SHIBSP_LOGGING;
189     std::string ll(loglevel);
190     PathResolver localpr;
191     localpr.setDefaultPrefix(inst_prefix2.c_str());
192     inst_prefix = getenv("SHIBSP_CFGDIR");
193     if (!inst_prefix)
194         inst_prefix = SHIBSP_CFGDIR;
195     localpr.setCfgDir(inst_prefix);
196     XMLToolingConfig::getConfig().log_config(localpr.resolve(ll, PathResolver::XMLTOOLING_CFG_FILE, PACKAGE_NAME).c_str());
197
198     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
199     log.debug("%s library initialization started", PACKAGE_STRING);
200
201 #ifndef SHIBSP_LITE
202     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
203         " OpenSAML/" + gOpenSAMLDotVersionStr +
204         " XMLTooling/" + gXMLToolingDotVersionStr +
205         " XML-Security-C/" + XSEC_FULLVERSIONDOT +
206         " Xerces-C/" + XERCES_FULLVERSIONDOT +
207 #if defined(LOG4SHIB_VERSION)
208         " log4shib/" + LOG4SHIB_VERSION;
209 #elif defined(LOG4CPP_VERSION)
210         " log4cpp/" + LOG4CPP_VERSION;
211 #endif
212     if (!SAMLConfig::getConfig().init()) {
213         log.fatal("failed to initialize OpenSAML library");
214         return false;
215     }
216 #else
217     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
218         " XMLTooling/" + gXMLToolingDotVersionStr +
219         " Xerces-C/" + XERCES_FULLVERSIONDOT +
220 #if defined(LOG4SHIB_VERSION)
221         " log4shib/" + LOG4SHIB_VERSION;
222 #elif defined(LOG4CPP_VERSION)
223         " log4cpp/" + LOG4CPP_VERSION;
224 #endif
225     if (!XMLToolingConfig::getConfig().init()) {
226         log.fatal("failed to initialize XMLTooling library");
227         return false;
228     }
229 #endif
230     if (!catalog_path)
231         catalog_path = getenv("SHIBSP_SCHEMAS");
232     if (!catalog_path)
233         catalog_path = SHIBSP_SCHEMAS;
234     if (!XMLToolingConfig::getConfig().getValidatingParser().loadCatalogs(catalog_path)) {
235         log.warn("failed to load schema catalogs into validating parser");
236     }
237
238     PathResolver* pr = XMLToolingConfig::getConfig().getPathResolver();
239     pr->setDefaultPackageName(PACKAGE_NAME);
240     pr->setDefaultPrefix(inst_prefix2.c_str());
241     pr->setCfgDir(inst_prefix);
242     inst_prefix = getenv("SHIBSP_LIBDIR");
243     if (!inst_prefix)
244         inst_prefix = SHIBSP_LIBDIR;
245     pr->setLibDir(inst_prefix);
246     inst_prefix = getenv("SHIBSP_LOGDIR");
247     if (!inst_prefix)
248         inst_prefix = SHIBSP_LOGDIR;
249     pr->setLogDir(inst_prefix);
250     inst_prefix = getenv("SHIBSP_RUNDIR");
251     if (!inst_prefix)
252         inst_prefix = SHIBSP_RUNDIR;
253     pr->setRunDir(inst_prefix);
254     inst_prefix = getenv("SHIBSP_XMLDIR");
255     if (!inst_prefix)
256         inst_prefix = SHIBSP_XMLDIR;
257     pr->setXMLDir(inst_prefix);
258
259     XMLToolingConfig::getConfig().setTemplateEngine(new TemplateEngine());
260     XMLToolingConfig::getConfig().getTemplateEngine()->setTagPrefix("shibmlp");
261
262     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
263     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
264     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
265     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
266     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
267     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
268
269 #ifdef SHIBSP_LITE
270     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
271     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
272     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
273     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
274     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
275     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
276 #endif
277
278 #ifndef SHIBSP_LITE
279     if (isEnabled(Metadata))
280         registerMetadataExtClasses();
281     if (isEnabled(Trust))
282         registerPKIXTrustEngine();
283 #endif
284
285     registerAttributeFactories();
286
287     if (isEnabled(Handlers)) {
288         registerHandlers();
289         registerLogoutInitiators();
290         registerSessionInitiators();
291         registerProtocolProviders();
292     }
293
294     registerServiceProviders();
295
296 #ifndef SHIBSP_LITE
297     if (isEnabled(AttributeResolution)) {
298         registerAttributeExtractors();
299         registerAttributeDecoders();
300         registerAttributeResolvers();
301         registerAttributeFilters();
302         registerMatchFunctors();
303     }
304     if (isEnabled(Logging)) {
305         registerEvents();
306     }
307     registerSecurityPolicyProviders();
308 #endif
309
310     if (isEnabled(Listener))
311         registerListenerServices();
312
313     if (isEnabled(RequestMapping)) {
314         registerAccessControls();
315         registerRequestMappers();
316     }
317
318     if (isEnabled(Caching))
319         registerSessionCaches();
320
321 #ifndef SHIBSP_LITE
322     if (isEnabled(OutOfProcess))
323         m_artifactResolver = new ArtifactResolver();
324 #endif
325     srand(static_cast<unsigned int>(std::time(nullptr)));
326
327     log.info("%s library initialization complete", PACKAGE_STRING);
328     return true;
329 }
330
331 void SPConfig::term()
332 {
333     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
334     log.info("%s library shutting down", PACKAGE_STRING);
335
336     setServiceProvider(nullptr);
337     if (m_configDoc)
338         m_configDoc->release();
339     m_configDoc = nullptr;
340 #ifndef SHIBSP_LITE
341     setArtifactResolver(nullptr);
342 #endif
343
344     if (isEnabled(Handlers)) {
345         ArtifactResolutionServiceManager.deregisterFactories();
346         AssertionConsumerServiceManager.deregisterFactories();
347         LogoutInitiatorManager.deregisterFactories();
348         ManageNameIDServiceManager.deregisterFactories();
349         SessionInitiatorManager.deregisterFactories();
350         SingleLogoutServiceManager.deregisterFactories();
351         HandlerManager.deregisterFactories();
352         ProtocolProviderManager.deregisterFactories();
353     }
354
355     ServiceProviderManager.deregisterFactories();
356     Attribute::deregisterFactories();
357
358 #ifndef SHIBSP_LITE
359     SecurityPolicyProviderManager.deregisterFactories();
360     if (isEnabled(Logging)) {
361         EventManager.deregisterFactories();
362     }
363     if (isEnabled(AttributeResolution)) {
364         MatchFunctorManager.deregisterFactories();
365         AttributeFilterManager.deregisterFactories();
366         AttributeDecoderManager.deregisterFactories();
367         AttributeExtractorManager.deregisterFactories();
368         AttributeResolverManager.deregisterFactories();
369     }
370 #endif
371
372     if (isEnabled(Listener))
373         ListenerServiceManager.deregisterFactories();
374
375     if (isEnabled(RequestMapping)) {
376         AccessControlManager.deregisterFactories();
377         RequestMapperManager.deregisterFactories();
378     }
379
380     if (isEnabled(Caching))
381         SessionCacheManager.deregisterFactories();
382
383 #ifndef SHIBSP_LITE
384     SAMLConfig::getConfig().term();
385 #else
386     XMLToolingConfig::getConfig().term();
387 #endif
388     log.info("%s library shutdown complete", PACKAGE_STRING);
389 }
390
391 bool SPConfig::instantiate(const char* config, bool rethrow)
392 {
393 #ifdef _DEBUG
394     NDC ndc("instantiate");
395 #endif
396     if (!config)
397         config = getenv("SHIBSP_CONFIG");
398     if (!config)
399         config = SHIBSP_CONFIG;
400     try {
401         xercesc::DOMDocument* dummydoc;
402         if (*config == '"' || *config == '\'') {
403             throw ConfigurationException("The value of SHIBSP_CONFIG started with a quote.");
404         }
405         else if (*config != '<') {
406
407             // Mock up some XML.
408             string resolved(config);
409             stringstream snippet;
410             snippet
411                 << "<Dummy path='"
412                 << XMLToolingConfig::getConfig().getPathResolver()->resolve(resolved, PathResolver::XMLTOOLING_CFG_FILE)
413                 << "' validate='1'/>";
414             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
415             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
416             setServiceProvider(ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER, dummydoc->getDocumentElement()));
417             if (m_configDoc)
418                 m_configDoc->release();
419             m_configDoc = docjanitor.release();
420         }
421         else {
422             stringstream snippet(config);
423             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
424             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
425             static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
426             auto_ptr_char type(dummydoc->getDocumentElement()->getAttributeNS(nullptr,_type));
427             if (type.get() && *type.get())
428                 setServiceProvider(ServiceProviderManager.newPlugin(type.get(), dummydoc->getDocumentElement()));
429             else
430                 throw ConfigurationException("The supplied XML bootstrapping configuration did not include a type attribute.");
431             if (m_configDoc)
432                 m_configDoc->release();
433             m_configDoc = docjanitor.release();
434         }
435
436         getServiceProvider()->init();
437         return true;
438     }
439     catch (exception& ex) {
440         if (rethrow)
441             throw;
442         Category::getInstance(SHIBSP_LOGCAT".Config").fatal("caught exception while loading configuration: %s", ex.what());
443     }
444     return false;
445 }
446
447 bool SPInternalConfig::init(const char* catalog_path, const char* inst_prefix)
448 {
449 #ifdef _DEBUG
450     xmltooling::NDC ndc("init");
451 #endif
452
453     Lock initLock(m_lock);
454
455     if (m_initCount == INT_MAX) {
456         Category::getInstance(SHIBSP_LOGCAT".Config").crit("library initialized too many times");
457         return false;
458     }
459
460     if (m_initCount >= 1) {
461         ++m_initCount;
462         return true;
463     }
464
465     if (!SPConfig::init(catalog_path, inst_prefix)) {
466         return false;
467     }
468
469     ++m_initCount;
470     return true;
471 }
472
473 void SPInternalConfig::term()
474 {
475 #ifdef _DEBUG
476     xmltooling::NDC ndc("term");
477 #endif
478     
479     Lock initLock(m_lock);
480     if (m_initCount == 0) {
481         Category::getInstance(SHIBSP_LOGCAT".Config").crit("term without corresponding init");
482         return;
483     }
484     else if (--m_initCount > 0) {
485         return;
486     }
487
488     SPConfig::term();
489 }