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