https://issues.shibboleth.net/jira/browse/SSPCPP-297
[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 bool SPConfig::isEnabled(components_t feature)
125 {
126     return (m_features & feature)>0;
127 }
128
129 ServiceProvider* SPConfig::getServiceProvider() const
130 {
131     return m_serviceProvider;
132 }
133
134 void SPConfig::setServiceProvider(ServiceProvider* serviceProvider)
135 {
136     delete m_serviceProvider;
137     m_serviceProvider = serviceProvider;
138 }
139
140 #ifndef SHIBSP_LITE
141 void SPConfig::setArtifactResolver(MessageDecoder::ArtifactResolver* artifactResolver)
142 {
143     delete m_artifactResolver;
144     m_artifactResolver = artifactResolver;
145 }
146
147 const MessageDecoder::ArtifactResolver* SPConfig::getArtifactResolver() const
148 {
149     return m_artifactResolver;
150 }
151 #endif
152
153 bool SPConfig::init(const char* catalog_path, const char* inst_prefix)
154 {
155 #ifdef _DEBUG
156     NDC ndc("init");
157 #endif
158     if (!inst_prefix)
159         inst_prefix = getenv("SHIBSP_PREFIX");
160     if (!inst_prefix)
161         inst_prefix = SHIBSP_PREFIX;
162     std::string inst_prefix2;
163     while (*inst_prefix) {
164         inst_prefix2.push_back((*inst_prefix=='\\') ? ('/') : (*inst_prefix));
165         ++inst_prefix;
166     }
167
168     const char* loglevel=getenv("SHIBSP_LOGGING");
169     if (!loglevel)
170         loglevel = SHIBSP_LOGGING;
171     std::string ll(loglevel);
172     PathResolver localpr;
173     localpr.setDefaultPrefix(inst_prefix2.c_str());
174     inst_prefix = getenv("SHIBSP_CFGDIR");
175     if (!inst_prefix)
176         inst_prefix = SHIBSP_CFGDIR;
177     localpr.setCfgDir(inst_prefix);
178     XMLToolingConfig::getConfig().log_config(localpr.resolve(ll, PathResolver::XMLTOOLING_CFG_FILE, PACKAGE_NAME).c_str());
179
180     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
181     log.debug("%s library initialization started", PACKAGE_STRING);
182
183     if (!catalog_path)
184         catalog_path = getenv("SHIBSP_SCHEMAS");
185     if (!catalog_path)
186         catalog_path = SHIBSP_SCHEMAS;
187     XMLToolingConfig::getConfig().catalog_path = catalog_path;
188
189 #ifndef SHIBSP_LITE
190     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
191         " OpenSAML/" + OPENSAML_FULLVERSIONDOT +
192         " XMLTooling/" + XMLTOOLING_FULLVERSIONDOT +
193         " XML-Security-C/" + XSEC_FULLVERSIONDOT +
194         " Xerces-C/" + XERCES_FULLVERSIONDOT;
195     if (!SAMLConfig::getConfig().init()) {
196         log.fatal("failed to initialize OpenSAML library");
197         return false;
198     }
199 #else
200     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
201         " XMLTooling/" + XMLTOOLING_FULLVERSIONDOT +
202         " Xerces-C/" + XERCES_FULLVERSIONDOT;
203     if (!XMLToolingConfig::getConfig().init()) {
204         log.fatal("failed to initialize XMLTooling library");
205         return false;
206     }
207 #endif
208     PathResolver* pr = XMLToolingConfig::getConfig().getPathResolver();
209     pr->setDefaultPackageName(PACKAGE_NAME);
210     pr->setDefaultPrefix(inst_prefix2.c_str());
211     pr->setCfgDir(inst_prefix);
212     inst_prefix = getenv("SHIBSP_LIBDIR");
213     if (!inst_prefix)
214         inst_prefix = SHIBSP_LIBDIR;
215     pr->setLibDir(inst_prefix);
216     inst_prefix = getenv("SHIBSP_LOGDIR");
217     if (!inst_prefix)
218         inst_prefix = SHIBSP_LOGDIR;
219     pr->setLogDir(inst_prefix);
220     inst_prefix = getenv("SHIBSP_RUNDIR");
221     if (!inst_prefix)
222         inst_prefix = SHIBSP_RUNDIR;
223     pr->setRunDir(inst_prefix);
224     inst_prefix = getenv("SHIBSP_XMLDIR");
225     if (!inst_prefix)
226         inst_prefix = SHIBSP_XMLDIR;
227     pr->setXMLDir(inst_prefix);
228
229     XMLToolingConfig::getConfig().setTemplateEngine(new TemplateEngine());
230     XMLToolingConfig::getConfig().getTemplateEngine()->setTagPrefix("shibmlp");
231
232     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
233     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
234     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
235     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
236     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
237     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
238
239 #ifdef SHIBSP_LITE
240     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
241     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
242     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
243     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
244     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
245     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
246 #endif
247
248 #ifndef SHIBSP_LITE
249     if (isEnabled(Metadata))
250         registerMetadataExtClasses();
251     if (isEnabled(Trust))
252         registerPKIXTrustEngine();
253 #endif
254
255     registerAttributeFactories();
256
257     if (isEnabled(Handlers)) {
258         registerHandlers();
259         registerLogoutInitiators();
260         registerSessionInitiators();
261         registerProtocolProviders();
262     }
263
264     registerServiceProviders();
265
266 #ifndef SHIBSP_LITE
267     if (isEnabled(AttributeResolution)) {
268         registerAttributeExtractors();
269         registerAttributeDecoders();
270         registerAttributeResolvers();
271         registerAttributeFilters();
272         registerMatchFunctors();
273     }
274     registerSecurityPolicyProviders();
275 #endif
276
277     if (isEnabled(Listener))
278         registerListenerServices();
279
280     if (isEnabled(RequestMapping)) {
281         registerAccessControls();
282         registerRequestMappers();
283     }
284
285     if (isEnabled(Caching))
286         registerSessionCaches();
287
288 #ifndef SHIBSP_LITE
289     if (isEnabled(OutOfProcess))
290         m_artifactResolver = new ArtifactResolver();
291 #endif
292     srand(static_cast<unsigned int>(std::time(nullptr)));
293
294     log.info("%s library initialization complete", PACKAGE_STRING);
295     return true;
296 }
297
298 void SPConfig::term()
299 {
300 #ifdef _DEBUG
301     NDC ndc("term");
302 #endif
303     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
304     log.info("%s library shutting down", PACKAGE_STRING);
305
306     setServiceProvider(nullptr);
307     if (m_configDoc)
308         m_configDoc->release();
309     m_configDoc = nullptr;
310 #ifndef SHIBSP_LITE
311     setArtifactResolver(nullptr);
312 #endif
313
314     if (isEnabled(Handlers)) {
315         ArtifactResolutionServiceManager.deregisterFactories();
316         AssertionConsumerServiceManager.deregisterFactories();
317         LogoutInitiatorManager.deregisterFactories();
318         ManageNameIDServiceManager.deregisterFactories();
319         SessionInitiatorManager.deregisterFactories();
320         SingleLogoutServiceManager.deregisterFactories();
321         HandlerManager.deregisterFactories();
322         ProtocolProviderManager.deregisterFactories();
323     }
324
325     ServiceProviderManager.deregisterFactories();
326     Attribute::deregisterFactories();
327
328 #ifndef SHIBSP_LITE
329     SecurityPolicyProviderManager.deregisterFactories();
330     if (isEnabled(AttributeResolution)) {
331         MatchFunctorManager.deregisterFactories();
332         AttributeFilterManager.deregisterFactories();
333         AttributeDecoderManager.deregisterFactories();
334         AttributeExtractorManager.deregisterFactories();
335         AttributeResolverManager.deregisterFactories();
336     }
337 #endif
338
339     if (isEnabled(Listener))
340         ListenerServiceManager.deregisterFactories();
341
342     if (isEnabled(RequestMapping)) {
343         AccessControlManager.deregisterFactories();
344         RequestMapperManager.deregisterFactories();
345     }
346
347     if (isEnabled(Caching))
348         SessionCacheManager.deregisterFactories();
349
350 #ifndef SHIBSP_LITE
351     SAMLConfig::getConfig().term();
352 #else
353     XMLToolingConfig::getConfig().term();
354 #endif
355     log.info("%s library shutdown complete", PACKAGE_STRING);
356 }
357
358 bool SPConfig::instantiate(const char* config, bool rethrow)
359 {
360 #ifdef _DEBUG
361     NDC ndc("instantiate");
362 #endif
363     if (!config)
364         config = getenv("SHIBSP_CONFIG");
365     if (!config)
366         config = SHIBSP_CONFIG;
367     try {
368         xercesc::DOMDocument* dummydoc;
369         if (*config == '"' || *config == '\'') {
370             throw ConfigurationException("The value of SHIBSP_CONFIG started with a quote.");
371         }
372         else if (*config != '<') {
373
374             // Mock up some XML.
375             string resolved(config);
376             stringstream snippet;
377             snippet
378                 << "<Dummy path='"
379                 << XMLToolingConfig::getConfig().getPathResolver()->resolve(resolved, PathResolver::XMLTOOLING_CFG_FILE)
380                 << "' validate='1'/>";
381             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
382             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
383             setServiceProvider(ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER, dummydoc->getDocumentElement()));
384             if (m_configDoc)
385                 m_configDoc->release();
386             m_configDoc = docjanitor.release();
387         }
388         else {
389             stringstream snippet(config);
390             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
391             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
392             static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
393             auto_ptr_char type(dummydoc->getDocumentElement()->getAttributeNS(nullptr,_type));
394             if (type.get() && *type.get())
395                 setServiceProvider(ServiceProviderManager.newPlugin(type.get(), dummydoc->getDocumentElement()));
396             else
397                 throw ConfigurationException("The supplied XML bootstrapping configuration did not include a type attribute.");
398             if (m_configDoc)
399                 m_configDoc->release();
400             m_configDoc = docjanitor.release();
401         }
402
403         getServiceProvider()->init();
404         return true;
405     }
406     catch (exception& ex) {
407         if (rethrow)
408             throw;
409         Category::getInstance(SHIBSP_LOGCAT".Config").fatal("caught exception while loading configuration: %s", ex.what());
410     }
411     return false;
412 }
413
414 TransactionLog::TransactionLog() : log(logging::Category::getInstance(SHIBSP_TX_LOGCAT)), m_lock(Mutex::create())
415 {
416 }
417
418 TransactionLog::~TransactionLog()
419 {
420     delete m_lock;
421 }
422
423 Lockable* TransactionLog::lock()
424 {
425     m_lock->lock();
426     return this;
427 }
428
429 void TransactionLog::unlock()
430 {
431     m_lock->unlock();
432 }