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