Correct MAX limit constant.
[shibboleth/cpp-sp.git] / shibsp / SPConfig.cpp
1 /*
2  * Licensed to UCAID under one or more contributor license agreements.
3  * See the NOTICE file distributed with this work for additional information
4  * regarding copyright ownership. The ASF licenses this file to you under
5  * the Apache License, Version 2.0 (the "License"); you may not use this
6  * file except in compliance with the License.  You may obtain a copy of the
7  * 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     class SHIBSP_DLLLOCAL SPInternalConfig : public SPConfig
100     {
101     public:
102         SPInternalConfig();
103         ~SPInternalConfig();
104
105         bool init(const char* catalog_path=nullptr, const char* inst_prefix=nullptr);
106         void term();
107
108     private:
109         int m_initCount;
110         Mutex* m_lock;
111     };
112     
113     SPInternalConfig g_config;
114 }
115
116 SPConfig& SPConfig::getConfig()
117 {
118     return g_config;
119 }
120
121 SPConfig::SPConfig() : attribute_value_delimeter(';'), m_serviceProvider(nullptr),
122 #ifndef SHIBSP_LITE
123     m_artifactResolver(nullptr),
124 #endif
125     m_features(0), m_configDoc(nullptr)
126 {
127 }
128
129 SPConfig::~SPConfig()
130 {
131 }
132
133 void SPConfig::setFeatures(unsigned long enabled)
134 {
135     m_features = enabled;
136 }
137
138 unsigned long SPConfig::getFeatures() const {
139     return m_features;
140 }
141
142 bool SPConfig::isEnabled(components_t feature) const
143 {
144     return (m_features & feature)>0;
145 }
146
147 ServiceProvider* SPConfig::getServiceProvider() const
148 {
149     return m_serviceProvider;
150 }
151
152 void SPConfig::setServiceProvider(ServiceProvider* serviceProvider)
153 {
154     delete m_serviceProvider;
155     m_serviceProvider = serviceProvider;
156 }
157
158 #ifndef SHIBSP_LITE
159 void SPConfig::setArtifactResolver(MessageDecoder::ArtifactResolver* artifactResolver)
160 {
161     delete m_artifactResolver;
162     m_artifactResolver = artifactResolver;
163 }
164
165 const MessageDecoder::ArtifactResolver* SPConfig::getArtifactResolver() const
166 {
167     return m_artifactResolver;
168 }
169 #endif
170
171 bool SPConfig::init(const char* catalog_path, const char* inst_prefix)
172 {
173     if (!inst_prefix)
174         inst_prefix = getenv("SHIBSP_PREFIX");
175     if (!inst_prefix)
176         inst_prefix = SHIBSP_PREFIX;
177     std::string inst_prefix2;
178     while (*inst_prefix) {
179         inst_prefix2.push_back((*inst_prefix=='\\') ? ('/') : (*inst_prefix));
180         ++inst_prefix;
181     }
182
183     const char* loglevel=getenv("SHIBSP_LOGGING");
184     if (!loglevel)
185         loglevel = SHIBSP_LOGGING;
186     std::string ll(loglevel);
187     PathResolver localpr;
188     localpr.setDefaultPrefix(inst_prefix2.c_str());
189     inst_prefix = getenv("SHIBSP_CFGDIR");
190     if (!inst_prefix)
191         inst_prefix = SHIBSP_CFGDIR;
192     localpr.setCfgDir(inst_prefix);
193     XMLToolingConfig::getConfig().log_config(localpr.resolve(ll, PathResolver::XMLTOOLING_CFG_FILE, PACKAGE_NAME).c_str());
194
195     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
196     log.debug("%s library initialization started", PACKAGE_STRING);
197
198     if (!catalog_path)
199         catalog_path = getenv("SHIBSP_SCHEMAS");
200     if (!catalog_path)
201         catalog_path = SHIBSP_SCHEMAS;
202     XMLToolingConfig::getConfig().catalog_path = catalog_path;
203
204 #ifndef SHIBSP_LITE
205     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
206         " OpenSAML/" + gOpenSAMLDotVersionStr +
207         " XMLTooling/" + gXMLToolingDotVersionStr +
208         " XML-Security-C/" + XSEC_FULLVERSIONDOT +
209         " Xerces-C/" + XERCES_FULLVERSIONDOT +
210 #if defined(LOG4SHIB_VERSION)
211         " log4shib/" + LOG4SHIB_VERSION;
212 #elif defined(LOG4CPP_VERSION)
213         " log4cpp/" + LOG4CPP_VERSION;
214 #endif
215     if (!SAMLConfig::getConfig().init()) {
216         log.fatal("failed to initialize OpenSAML library");
217         return false;
218     }
219 #else
220     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
221         " XMLTooling/" + gXMLToolingDotVersionStr +
222         " Xerces-C/" + XERCES_FULLVERSIONDOT +
223 #if defined(LOG4SHIB_VERSION)
224         " log4shib/" + LOG4SHIB_VERSION;
225 #elif defined(LOG4CPP_VERSION)
226         " log4cpp/" + LOG4CPP_VERSION;
227 #endif
228     if (!XMLToolingConfig::getConfig().init()) {
229         log.fatal("failed to initialize XMLTooling library");
230         return false;
231     }
232 #endif
233     PathResolver* pr = XMLToolingConfig::getConfig().getPathResolver();
234     pr->setDefaultPackageName(PACKAGE_NAME);
235     pr->setDefaultPrefix(inst_prefix2.c_str());
236     pr->setCfgDir(inst_prefix);
237     inst_prefix = getenv("SHIBSP_LIBDIR");
238     if (!inst_prefix)
239         inst_prefix = SHIBSP_LIBDIR;
240     pr->setLibDir(inst_prefix);
241     inst_prefix = getenv("SHIBSP_LOGDIR");
242     if (!inst_prefix)
243         inst_prefix = SHIBSP_LOGDIR;
244     pr->setLogDir(inst_prefix);
245     inst_prefix = getenv("SHIBSP_RUNDIR");
246     if (!inst_prefix)
247         inst_prefix = SHIBSP_RUNDIR;
248     pr->setRunDir(inst_prefix);
249     inst_prefix = getenv("SHIBSP_XMLDIR");
250     if (!inst_prefix)
251         inst_prefix = SHIBSP_XMLDIR;
252     pr->setXMLDir(inst_prefix);
253
254     XMLToolingConfig::getConfig().setTemplateEngine(new TemplateEngine());
255     XMLToolingConfig::getConfig().getTemplateEngine()->setTagPrefix("shibmlp");
256
257     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
258     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
259     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
260     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
261     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
262     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
263
264 #ifdef SHIBSP_LITE
265     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
266     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
267     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
268     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
269     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
270     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
271 #endif
272
273 #ifndef SHIBSP_LITE
274     if (isEnabled(Metadata))
275         registerMetadataExtClasses();
276     if (isEnabled(Trust))
277         registerPKIXTrustEngine();
278 #endif
279
280     registerAttributeFactories();
281
282     if (isEnabled(Handlers)) {
283         registerHandlers();
284         registerLogoutInitiators();
285         registerSessionInitiators();
286         registerProtocolProviders();
287     }
288
289     registerServiceProviders();
290
291 #ifndef SHIBSP_LITE
292     if (isEnabled(AttributeResolution)) {
293         registerAttributeExtractors();
294         registerAttributeDecoders();
295         registerAttributeResolvers();
296         registerAttributeFilters();
297         registerMatchFunctors();
298     }
299     registerSecurityPolicyProviders();
300 #endif
301
302     if (isEnabled(Listener))
303         registerListenerServices();
304
305     if (isEnabled(RequestMapping)) {
306         registerAccessControls();
307         registerRequestMappers();
308     }
309
310     if (isEnabled(Caching))
311         registerSessionCaches();
312
313 #ifndef SHIBSP_LITE
314     if (isEnabled(OutOfProcess))
315         m_artifactResolver = new ArtifactResolver();
316 #endif
317     srand(static_cast<unsigned int>(std::time(nullptr)));
318
319     log.info("%s library initialization complete", PACKAGE_STRING);
320     return true;
321 }
322
323 void SPConfig::term()
324 {
325     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
326     log.info("%s library shutting down", PACKAGE_STRING);
327
328     setServiceProvider(nullptr);
329     if (m_configDoc)
330         m_configDoc->release();
331     m_configDoc = nullptr;
332 #ifndef SHIBSP_LITE
333     setArtifactResolver(nullptr);
334 #endif
335
336     if (isEnabled(Handlers)) {
337         ArtifactResolutionServiceManager.deregisterFactories();
338         AssertionConsumerServiceManager.deregisterFactories();
339         LogoutInitiatorManager.deregisterFactories();
340         ManageNameIDServiceManager.deregisterFactories();
341         SessionInitiatorManager.deregisterFactories();
342         SingleLogoutServiceManager.deregisterFactories();
343         HandlerManager.deregisterFactories();
344         ProtocolProviderManager.deregisterFactories();
345     }
346
347     ServiceProviderManager.deregisterFactories();
348     Attribute::deregisterFactories();
349
350 #ifndef SHIBSP_LITE
351     SecurityPolicyProviderManager.deregisterFactories();
352     if (isEnabled(AttributeResolution)) {
353         MatchFunctorManager.deregisterFactories();
354         AttributeFilterManager.deregisterFactories();
355         AttributeDecoderManager.deregisterFactories();
356         AttributeExtractorManager.deregisterFactories();
357         AttributeResolverManager.deregisterFactories();
358     }
359 #endif
360
361     if (isEnabled(Listener))
362         ListenerServiceManager.deregisterFactories();
363
364     if (isEnabled(RequestMapping)) {
365         AccessControlManager.deregisterFactories();
366         RequestMapperManager.deregisterFactories();
367     }
368
369     if (isEnabled(Caching))
370         SessionCacheManager.deregisterFactories();
371
372 #ifndef SHIBSP_LITE
373     SAMLConfig::getConfig().term();
374 #else
375     XMLToolingConfig::getConfig().term();
376 #endif
377     log.info("%s library shutdown complete", PACKAGE_STRING);
378 }
379
380 bool SPConfig::instantiate(const char* config, bool rethrow)
381 {
382 #ifdef _DEBUG
383     NDC ndc("instantiate");
384 #endif
385     if (!config)
386         config = getenv("SHIBSP_CONFIG");
387     if (!config)
388         config = SHIBSP_CONFIG;
389     try {
390         xercesc::DOMDocument* dummydoc;
391         if (*config == '"' || *config == '\'') {
392             throw ConfigurationException("The value of SHIBSP_CONFIG started with a quote.");
393         }
394         else if (*config != '<') {
395
396             // Mock up some XML.
397             string resolved(config);
398             stringstream snippet;
399             snippet
400                 << "<Dummy path='"
401                 << XMLToolingConfig::getConfig().getPathResolver()->resolve(resolved, PathResolver::XMLTOOLING_CFG_FILE)
402                 << "' validate='1'/>";
403             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
404             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
405             setServiceProvider(ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER, dummydoc->getDocumentElement()));
406             if (m_configDoc)
407                 m_configDoc->release();
408             m_configDoc = docjanitor.release();
409         }
410         else {
411             stringstream snippet(config);
412             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
413             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
414             static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
415             auto_ptr_char type(dummydoc->getDocumentElement()->getAttributeNS(nullptr,_type));
416             if (type.get() && *type.get())
417                 setServiceProvider(ServiceProviderManager.newPlugin(type.get(), dummydoc->getDocumentElement()));
418             else
419                 throw ConfigurationException("The supplied XML bootstrapping configuration did not include a type attribute.");
420             if (m_configDoc)
421                 m_configDoc->release();
422             m_configDoc = docjanitor.release();
423         }
424
425         getServiceProvider()->init();
426         return true;
427     }
428     catch (exception& ex) {
429         if (rethrow)
430             throw;
431         Category::getInstance(SHIBSP_LOGCAT".Config").fatal("caught exception while loading configuration: %s", ex.what());
432     }
433     return false;
434 }
435
436 SPInternalConfig::SPInternalConfig() : m_initCount(0), m_lock(Mutex::create())
437 {
438 }
439
440 SPInternalConfig::~SPInternalConfig()
441 {
442     delete m_lock;
443 }
444
445 bool SPInternalConfig::init(const char* catalog_path, const char* inst_prefix)
446 {
447 #ifdef _DEBUG
448     xmltooling::NDC ndc("init");
449 #endif
450
451     Lock initLock(m_lock);
452
453     if (m_initCount == INT_MAX) {
454         Category::getInstance(SHIBSP_LOGCAT".Config").crit("library initialized too many times");
455         return false;
456     }
457
458     if (m_initCount >= 1) {
459         ++m_initCount;
460         return true;
461     }
462
463     if (!SPConfig::init(catalog_path, inst_prefix)) {
464         return false;
465     }
466
467     ++m_initCount;
468     return true;
469 }
470
471 void SPInternalConfig::term()
472 {
473 #ifdef _DEBUG
474     xmltooling::NDC ndc("term");
475 #endif
476     
477     Lock initLock(m_lock);
478     if (m_initCount == 0) {
479         Category::getInstance(SHIBSP_LOGCAT".Config").crit("term without corresponding init");
480         return;
481     }
482     else if (--m_initCount > 0) {
483         return;
484     }
485
486     SPConfig::term();
487 }
488
489
490 TransactionLog::TransactionLog() : log(logging::Category::getInstance(SHIBSP_TX_LOGCAT)), m_lock(Mutex::create())
491 {
492 }
493
494 TransactionLog::~TransactionLog()
495 {
496     delete m_lock;
497 }
498
499 Lockable* TransactionLog::lock()
500 {
501     m_lock->lock();
502     return this;
503 }
504
505 void TransactionLog::unlock()
506 {
507     m_lock->unlock();
508 }