Factor out LogoutInitiator class, simpler API to get ACS by binding.
[shibboleth/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 "AccessControl.h"
39 #include "exceptions.h"
40 #include "RequestMapper.h"
41 #include "ServiceProvider.h"
42 #include "SessionCache.h"
43 #include "SPConfig.h"
44 #include "TransactionLog.h"
45 #include "attribute/Attribute.h"
46 #include "handler/LogoutInitiator.h"
47 #include "handler/SessionInitiator.h"
48 #include "remoting/ListenerService.h"
49
50 #ifndef SHIBSP_LITE
51 # include "attribute/AttributeDecoder.h"
52 # include "attribute/filtering/AttributeFilter.h"
53 # include "attribute/filtering/MatchFunctor.h"
54 # include "attribute/resolver/AttributeExtractor.h"
55 # include "attribute/resolver/AttributeResolver.h"
56 # include "binding/ArtifactResolver.h"
57 # include "metadata/MetadataExt.h"
58 # include "security/PKIXTrustEngine.h"
59 # include "security/SecurityPolicyProvider.h"
60 # include <saml/SAMLConfig.h>
61 #endif
62
63 #include <ctime>
64 #include <xercesc/util/XMLUniDefs.hpp>
65 #include <xmltooling/XMLToolingConfig.h>
66 #include <xmltooling/util/NDC.h>
67 #include <xmltooling/util/ParserPool.h>
68 #include <xmltooling/util/PathResolver.h>
69 #include <xmltooling/util/TemplateEngine.h>
70 #include <xmltooling/util/Threads.h>
71 #include <xmltooling/util/XMLHelper.h>
72
73 using namespace shibsp;
74 using namespace opensaml;
75 using namespace xmltooling;
76 using namespace std;
77
78 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
79 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
80 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
81 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
82 DECL_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
83 DECL_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
84
85 #ifdef SHIBSP_LITE
86 DECL_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
87 DECL_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
88 DECL_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
89 DECL_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
90 DECL_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
91 DECL_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
92 #endif
93
94 namespace shibsp {
95    SPConfig g_config;
96 }
97
98 SPConfig& SPConfig::getConfig()
99 {
100     return g_config;
101 }
102
103 SPConfig::SPConfig() : attribute_value_delimeter(';'), m_serviceProvider(nullptr),
104 #ifndef SHIBSP_LITE
105     m_artifactResolver(nullptr),
106 #endif
107     m_features(0), m_configDoc(nullptr)
108 {
109 }
110
111 SPConfig::~SPConfig()
112 {
113 }
114
115 void SPConfig::setFeatures(unsigned long enabled)
116 {
117     m_features = enabled;
118 }
119
120 bool SPConfig::isEnabled(components_t feature)
121 {
122     return (m_features & feature)>0;
123 }
124
125 ServiceProvider* SPConfig::getServiceProvider() const
126 {
127     return m_serviceProvider;
128 }
129
130 void SPConfig::setServiceProvider(ServiceProvider* serviceProvider)
131 {
132     delete m_serviceProvider;
133     m_serviceProvider = serviceProvider;
134 }
135
136 #ifndef SHIBSP_LITE
137 void SPConfig::setArtifactResolver(MessageDecoder::ArtifactResolver* artifactResolver)
138 {
139     delete m_artifactResolver;
140     m_artifactResolver = artifactResolver;
141 }
142
143 const MessageDecoder::ArtifactResolver* SPConfig::getArtifactResolver() const
144 {
145     return m_artifactResolver;
146 }
147 #endif
148
149 bool SPConfig::init(const char* catalog_path, const char* inst_prefix)
150 {
151 #ifdef _DEBUG
152     NDC ndc("init");
153 #endif
154     if (!inst_prefix)
155         inst_prefix = getenv("SHIBSP_PREFIX");
156     if (!inst_prefix)
157         inst_prefix = SHIBSP_PREFIX;
158     std::string inst_prefix2;
159     while (*inst_prefix) {
160         inst_prefix2.push_back((*inst_prefix=='\\') ? ('/') : (*inst_prefix));
161         ++inst_prefix;
162     }
163
164     const char* loglevel=getenv("SHIBSP_LOGGING");
165     if (!loglevel)
166         loglevel = SHIBSP_LOGGING;
167     std::string ll(loglevel);
168     PathResolver localpr;
169     localpr.setDefaultPrefix(inst_prefix2.c_str());
170     inst_prefix = getenv("SHIBSP_CFGDIR");
171     if (!inst_prefix)
172         inst_prefix = SHIBSP_CFGDIR;
173     localpr.setCfgDir(inst_prefix);
174     XMLToolingConfig::getConfig().log_config(localpr.resolve(ll, PathResolver::XMLTOOLING_CFG_FILE, PACKAGE_NAME).c_str());
175
176     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
177     log.debug("%s library initialization started", PACKAGE_STRING);
178
179     if (!catalog_path)
180         catalog_path = getenv("SHIBSP_SCHEMAS");
181     if (!catalog_path)
182         catalog_path = SHIBSP_SCHEMAS;
183     XMLToolingConfig::getConfig().catalog_path = catalog_path;
184
185 #ifndef SHIBSP_LITE
186     if (!SAMLConfig::getConfig().init()) {
187         log.fatal("failed to initialize OpenSAML library");
188         return false;
189     }
190 #else
191     if (!XMLToolingConfig::getConfig().init()) {
192         log.fatal("failed to initialize XMLTooling library");
193         return false;
194     }
195 #endif
196     PathResolver* pr = XMLToolingConfig::getConfig().getPathResolver();
197     pr->setDefaultPackageName(PACKAGE_NAME);
198     pr->setDefaultPrefix(inst_prefix2.c_str());
199     pr->setCfgDir(inst_prefix);
200     inst_prefix = getenv("SHIBSP_LIBDIR");
201     if (!inst_prefix)
202         inst_prefix = SHIBSP_LIBDIR;
203     pr->setLibDir(inst_prefix);
204     inst_prefix = getenv("SHIBSP_LOGDIR");
205     if (!inst_prefix)
206         inst_prefix = SHIBSP_LOGDIR;
207     pr->setLogDir(inst_prefix);
208     inst_prefix = getenv("SHIBSP_RUNDIR");
209     if (!inst_prefix)
210         inst_prefix = SHIBSP_RUNDIR;
211     pr->setRunDir(inst_prefix);
212     inst_prefix = getenv("SHIBSP_XMLDIR");
213     if (!inst_prefix)
214         inst_prefix = SHIBSP_XMLDIR;
215     pr->setXMLDir(inst_prefix);
216
217     XMLToolingConfig::getConfig().setTemplateEngine(new TemplateEngine());
218     XMLToolingConfig::getConfig().getTemplateEngine()->setTagPrefix("shibmlp");
219
220     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
221     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
222     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
223     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
224     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
225     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
226
227 #ifdef SHIBSP_LITE
228     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
229     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
230     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
231     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
232     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
233     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
234 #endif
235
236 #ifndef SHIBSP_LITE
237     if (isEnabled(Metadata))
238         registerMetadataExtClasses();
239     if (isEnabled(Trust))
240         registerPKIXTrustEngine();
241 #endif
242
243     registerAttributeFactories();
244     registerHandlers();
245     registerLogoutInitiators();
246     registerSessionInitiators();
247     registerServiceProviders();
248
249 #ifndef SHIBSP_LITE
250     if (isEnabled(AttributeResolution)) {
251         registerAttributeExtractors();
252         registerAttributeDecoders();
253         registerAttributeResolvers();
254         registerAttributeFilters();
255         registerMatchFunctors();
256     }
257     registerSecurityPolicyProviders();
258 #endif
259
260     if (isEnabled(Listener))
261         registerListenerServices();
262
263     if (isEnabled(RequestMapping)) {
264         registerAccessControls();
265         registerRequestMappers();
266     }
267
268     if (isEnabled(Caching))
269         registerSessionCaches();
270
271 #ifndef SHIBSP_LITE
272     if (isEnabled(OutOfProcess))
273         m_artifactResolver = new ArtifactResolver();
274 #endif
275     srand(static_cast<unsigned int>(std::time(nullptr)));
276
277     log.info("%s library initialization complete", PACKAGE_STRING);
278     return true;
279 }
280
281 void SPConfig::term()
282 {
283 #ifdef _DEBUG
284     NDC ndc("term");
285 #endif
286     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
287     log.info("%s library shutting down", PACKAGE_STRING);
288
289     setServiceProvider(nullptr);
290     if (m_configDoc)
291         m_configDoc->release();
292     m_configDoc = nullptr;
293 #ifndef SHIBSP_LITE
294     setArtifactResolver(nullptr);
295 #endif
296
297     ArtifactResolutionServiceManager.deregisterFactories();
298     AssertionConsumerServiceManager.deregisterFactories();
299     LogoutInitiatorManager.deregisterFactories();
300     ManageNameIDServiceManager.deregisterFactories();
301     SessionInitiatorManager.deregisterFactories();
302     SingleLogoutServiceManager.deregisterFactories();
303     HandlerManager.deregisterFactories();
304     ServiceProviderManager.deregisterFactories();
305     Attribute::deregisterFactories();
306
307 #ifndef SHIBSP_LITE
308     SecurityPolicyProviderManager.deregisterFactories();
309     if (isEnabled(AttributeResolution)) {
310         MatchFunctorManager.deregisterFactories();
311         AttributeFilterManager.deregisterFactories();
312         AttributeDecoderManager.deregisterFactories();
313         AttributeExtractorManager.deregisterFactories();
314         AttributeResolverManager.deregisterFactories();
315     }
316 #endif
317
318     if (isEnabled(Listener))
319         ListenerServiceManager.deregisterFactories();
320
321     if (isEnabled(RequestMapping)) {
322         AccessControlManager.deregisterFactories();
323         RequestMapperManager.deregisterFactories();
324     }
325
326     if (isEnabled(Caching))
327         SessionCacheManager.deregisterFactories();
328
329 #ifndef SHIBSP_LITE
330     SAMLConfig::getConfig().term();
331 #else
332     XMLToolingConfig::getConfig().term();
333 #endif
334     log.info("%s library shutdown complete", PACKAGE_STRING);
335 }
336
337 bool SPConfig::instantiate(const char* config, bool rethrow)
338 {
339 #ifdef _DEBUG
340     NDC ndc("instantiate");
341 #endif
342     if (!config)
343         config = getenv("SHIBSP_CONFIG");
344     if (!config)
345         config = SHIBSP_CONFIG;
346     try {
347         xercesc::DOMDocument* dummydoc;
348         if (*config == '"' || *config == '\'') {
349             throw ConfigurationException("The value of SHIBSP_CONFIG started with a quote.");
350         }
351         else if (*config != '<') {
352
353             // Mock up some XML.
354             string resolved(config);
355             stringstream snippet;
356             snippet
357                 << "<Dummy path='"
358                 << XMLToolingConfig::getConfig().getPathResolver()->resolve(resolved, PathResolver::XMLTOOLING_CFG_FILE)
359                 << "' validate='1'/>";
360             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
361             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
362             setServiceProvider(ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER, dummydoc->getDocumentElement()));
363             if (m_configDoc)
364                 m_configDoc->release();
365             m_configDoc = docjanitor.release();
366         }
367         else {
368             stringstream snippet(config);
369             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
370             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
371             static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
372             auto_ptr_char type(dummydoc->getDocumentElement()->getAttributeNS(nullptr,_type));
373             if (type.get() && *type.get())
374                 setServiceProvider(ServiceProviderManager.newPlugin(type.get(), dummydoc->getDocumentElement()));
375             else
376                 throw ConfigurationException("The supplied XML bootstrapping configuration did not include a type attribute.");
377             if (m_configDoc)
378                 m_configDoc->release();
379             m_configDoc = docjanitor.release();
380         }
381
382         getServiceProvider()->init();
383         return true;
384     }
385     catch (exception& ex) {
386         if (rethrow)
387             throw;
388         Category::getInstance(SHIBSP_LOGCAT".Config").fatal("caught exception while loading configuration: %s", ex.what());
389     }
390     return false;
391 }
392
393 TransactionLog::TransactionLog() : log(logging::Category::getInstance(SHIBSP_TX_LOGCAT)), m_lock(Mutex::create())
394 {
395 }
396
397 TransactionLog::~TransactionLog()
398 {
399     delete m_lock;
400 }
401
402 Lockable* TransactionLog::lock()
403 {
404     m_lock->lock();
405     return this;
406 }
407
408 void TransactionLog::unlock()
409 {
410     m_lock->unlock();
411 }