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