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