https://issues.shibboleth.net/jira/browse/SSPCPP-413
[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 #ifndef SHIBSP_LITE
201     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
202         " OpenSAML/" + gOpenSAMLDotVersionStr +
203         " XMLTooling/" + gXMLToolingDotVersionStr +
204         " XML-Security-C/" + XSEC_FULLVERSIONDOT +
205         " Xerces-C/" + XERCES_FULLVERSIONDOT +
206 #if defined(LOG4SHIB_VERSION)
207         " log4shib/" + LOG4SHIB_VERSION;
208 #elif defined(LOG4CPP_VERSION)
209         " log4cpp/" + LOG4CPP_VERSION;
210 #endif
211     if (!SAMLConfig::getConfig().init()) {
212         log.fatal("failed to initialize OpenSAML library");
213         return false;
214     }
215 #else
216     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
217         " XMLTooling/" + gXMLToolingDotVersionStr +
218         " Xerces-C/" + XERCES_FULLVERSIONDOT +
219 #if defined(LOG4SHIB_VERSION)
220         " log4shib/" + LOG4SHIB_VERSION;
221 #elif defined(LOG4CPP_VERSION)
222         " log4cpp/" + LOG4CPP_VERSION;
223 #endif
224     if (!XMLToolingConfig::getConfig().init()) {
225         log.fatal("failed to initialize XMLTooling library");
226         return false;
227     }
228 #endif
229     if (!catalog_path)
230         catalog_path = getenv("SHIBSP_SCHEMAS");
231     if (!catalog_path)
232         catalog_path = SHIBSP_SCHEMAS;
233     if (!XMLToolingConfig::getConfig().getValidatingParser().loadCatalogs(catalog_path)) {
234         log.warn("failed to load schema catalogs into validating parser");
235     }
236
237     PathResolver* pr = XMLToolingConfig::getConfig().getPathResolver();
238     pr->setDefaultPackageName(PACKAGE_NAME);
239     pr->setDefaultPrefix(inst_prefix2.c_str());
240     pr->setCfgDir(inst_prefix);
241     inst_prefix = getenv("SHIBSP_LIBDIR");
242     if (!inst_prefix)
243         inst_prefix = SHIBSP_LIBDIR;
244     pr->setLibDir(inst_prefix);
245     inst_prefix = getenv("SHIBSP_LOGDIR");
246     if (!inst_prefix)
247         inst_prefix = SHIBSP_LOGDIR;
248     pr->setLogDir(inst_prefix);
249     inst_prefix = getenv("SHIBSP_RUNDIR");
250     if (!inst_prefix)
251         inst_prefix = SHIBSP_RUNDIR;
252     pr->setRunDir(inst_prefix);
253     inst_prefix = getenv("SHIBSP_XMLDIR");
254     if (!inst_prefix)
255         inst_prefix = SHIBSP_XMLDIR;
256     pr->setXMLDir(inst_prefix);
257
258     XMLToolingConfig::getConfig().setTemplateEngine(new TemplateEngine());
259     XMLToolingConfig::getConfig().getTemplateEngine()->setTagPrefix("shibmlp");
260
261     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
262     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
263     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
264     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
265     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
266     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
267
268 #ifdef SHIBSP_LITE
269     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
270     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
271     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
272     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
273     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
274     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
275 #endif
276
277 #ifndef SHIBSP_LITE
278     if (isEnabled(Metadata))
279         registerMetadataExtClasses();
280     if (isEnabled(Trust))
281         registerPKIXTrustEngine();
282 #endif
283
284     registerAttributeFactories();
285
286     if (isEnabled(Handlers)) {
287         registerHandlers();
288         registerLogoutInitiators();
289         registerSessionInitiators();
290         registerProtocolProviders();
291     }
292
293     registerServiceProviders();
294
295 #ifndef SHIBSP_LITE
296     if (isEnabled(AttributeResolution)) {
297         registerAttributeExtractors();
298         registerAttributeDecoders();
299         registerAttributeResolvers();
300         registerAttributeFilters();
301         registerMatchFunctors();
302     }
303     if (isEnabled(Logging)) {
304         registerEvents();
305     }
306     registerSecurityPolicyProviders();
307 #endif
308
309     if (isEnabled(Listener))
310         registerListenerServices();
311
312     if (isEnabled(RequestMapping)) {
313         registerAccessControls();
314         registerRequestMappers();
315     }
316
317     if (isEnabled(Caching))
318         registerSessionCaches();
319
320 #ifndef SHIBSP_LITE
321     if (isEnabled(OutOfProcess))
322         m_artifactResolver = new ArtifactResolver();
323 #endif
324     srand(static_cast<unsigned int>(std::time(nullptr)));
325
326     log.info("%s library initialization complete", PACKAGE_STRING);
327     return true;
328 }
329
330 void SPConfig::term()
331 {
332     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
333     log.info("%s library shutting down", PACKAGE_STRING);
334
335     setServiceProvider(nullptr);
336     if (m_configDoc)
337         m_configDoc->release();
338     m_configDoc = nullptr;
339 #ifndef SHIBSP_LITE
340     setArtifactResolver(nullptr);
341 #endif
342
343     if (isEnabled(Handlers)) {
344         ArtifactResolutionServiceManager.deregisterFactories();
345         AssertionConsumerServiceManager.deregisterFactories();
346         LogoutInitiatorManager.deregisterFactories();
347         ManageNameIDServiceManager.deregisterFactories();
348         SessionInitiatorManager.deregisterFactories();
349         SingleLogoutServiceManager.deregisterFactories();
350         HandlerManager.deregisterFactories();
351         ProtocolProviderManager.deregisterFactories();
352     }
353
354     ServiceProviderManager.deregisterFactories();
355     Attribute::deregisterFactories();
356
357 #ifndef SHIBSP_LITE
358     SecurityPolicyProviderManager.deregisterFactories();
359     if (isEnabled(Logging)) {
360         EventManager.deregisterFactories();
361     }
362     if (isEnabled(AttributeResolution)) {
363         MatchFunctorManager.deregisterFactories();
364         AttributeFilterManager.deregisterFactories();
365         AttributeDecoderManager.deregisterFactories();
366         AttributeExtractorManager.deregisterFactories();
367         AttributeResolverManager.deregisterFactories();
368     }
369 #endif
370
371     if (isEnabled(Listener))
372         ListenerServiceManager.deregisterFactories();
373
374     if (isEnabled(RequestMapping)) {
375         AccessControlManager.deregisterFactories();
376         RequestMapperManager.deregisterFactories();
377     }
378
379     if (isEnabled(Caching))
380         SessionCacheManager.deregisterFactories();
381
382 #ifndef SHIBSP_LITE
383     SAMLConfig::getConfig().term();
384 #else
385     XMLToolingConfig::getConfig().term();
386 #endif
387     log.info("%s library shutdown complete", PACKAGE_STRING);
388 }
389
390 bool SPConfig::instantiate(const char* config, bool rethrow)
391 {
392 #ifdef _DEBUG
393     NDC ndc("instantiate");
394 #endif
395     if (!config)
396         config = getenv("SHIBSP_CONFIG");
397     if (!config)
398         config = SHIBSP_CONFIG;
399     try {
400         xercesc::DOMDocument* dummydoc;
401         if (*config == '"' || *config == '\'') {
402             throw ConfigurationException("The value of SHIBSP_CONFIG started with a quote.");
403         }
404         else if (*config != '<') {
405
406             // Mock up some XML.
407             string resolved(config);
408             stringstream snippet;
409             snippet
410                 << "<Dummy path='"
411                 << XMLToolingConfig::getConfig().getPathResolver()->resolve(resolved, PathResolver::XMLTOOLING_CFG_FILE)
412                 << "' validate='1'/>";
413             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
414             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
415             setServiceProvider(ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER, dummydoc->getDocumentElement()));
416             if (m_configDoc)
417                 m_configDoc->release();
418             m_configDoc = docjanitor.release();
419         }
420         else {
421             stringstream snippet(config);
422             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
423             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
424             static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
425             auto_ptr_char type(dummydoc->getDocumentElement()->getAttributeNS(nullptr,_type));
426             if (type.get() && *type.get())
427                 setServiceProvider(ServiceProviderManager.newPlugin(type.get(), dummydoc->getDocumentElement()));
428             else
429                 throw ConfigurationException("The supplied XML bootstrapping configuration did not include a type attribute.");
430             if (m_configDoc)
431                 m_configDoc->release();
432             m_configDoc = docjanitor.release();
433         }
434
435         getServiceProvider()->init();
436         return true;
437     }
438     catch (exception& ex) {
439         if (rethrow)
440             throw;
441         Category::getInstance(SHIBSP_LOGCAT".Config").fatal("caught exception while loading configuration: %s", ex.what());
442     }
443     return false;
444 }
445
446 SPInternalConfig::SPInternalConfig() : m_initCount(0), m_lock(Mutex::create())
447 {
448 }
449
450 SPInternalConfig::~SPInternalConfig()
451 {
452     delete m_lock;
453 }
454
455 bool SPInternalConfig::init(const char* catalog_path, const char* inst_prefix)
456 {
457 #ifdef _DEBUG
458     xmltooling::NDC ndc("init");
459 #endif
460
461     Lock initLock(m_lock);
462
463     if (m_initCount == INT_MAX) {
464         Category::getInstance(SHIBSP_LOGCAT".Config").crit("library initialized too many times");
465         return false;
466     }
467
468     if (m_initCount >= 1) {
469         ++m_initCount;
470         return true;
471     }
472
473     if (!SPConfig::init(catalog_path, inst_prefix)) {
474         return false;
475     }
476
477     ++m_initCount;
478     return true;
479 }
480
481 void SPInternalConfig::term()
482 {
483 #ifdef _DEBUG
484     xmltooling::NDC ndc("term");
485 #endif
486     
487     Lock initLock(m_lock);
488     if (m_initCount == 0) {
489         Category::getInstance(SHIBSP_LOGCAT".Config").crit("term without corresponding init");
490         return;
491     }
492     else if (--m_initCount > 0) {
493         return;
494     }
495
496     SPConfig::term();
497 }