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