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