Cache directory was not initialized properly.
[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 "attribute/Attribute.h"
49 #include "binding/ProtocolProvider.h"
50 #include "handler/LogoutInitiator.h"
51 #include "handler/SessionInitiator.h"
52 #include "remoting/ListenerService.h"
53
54 #ifndef SHIBSP_LITE
55 # include "attribute/AttributeDecoder.h"
56 # include "attribute/filtering/AttributeFilter.h"
57 # include "attribute/filtering/MatchFunctor.h"
58 # include "attribute/resolver/AttributeExtractor.h"
59 # include "attribute/resolver/AttributeResolver.h"
60 # include "binding/ArtifactResolver.h"
61 # include "metadata/MetadataExt.h"
62 # include "security/PKIXTrustEngine.h"
63 # include "security/SecurityPolicyProvider.h"
64 # include <saml/version.h>
65 # include <saml/SAMLConfig.h>
66 #endif
67
68 #include <ctime>
69 #include <xercesc/util/XMLUniDefs.hpp>
70 #include <xmltooling/version.h>
71 #include <xmltooling/XMLToolingConfig.h>
72 #include <xmltooling/util/NDC.h>
73 #include <xmltooling/util/ParserPool.h>
74 #include <xmltooling/util/PathResolver.h>
75 #include <xmltooling/util/TemplateEngine.h>
76 #include <xmltooling/util/Threads.h>
77 #include <xmltooling/util/XMLHelper.h>
78
79 using namespace shibsp;
80 using namespace opensaml;
81 using namespace xmltooling;
82 using namespace boost;
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() : m_initCount(0), m_lock(Mutex::create()) {}
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         scoped_ptr<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 || !*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 #ifndef SHIBSP_LITE
202     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
203         " OpenSAML/" + gOpenSAMLDotVersionStr +
204         " XMLTooling/" + gXMLToolingDotVersionStr +
205         " XML-Security-C/" + XSEC_FULLVERSIONDOT +
206         " Xerces-C/" + XERCES_FULLVERSIONDOT +
207 #if defined(LOG4SHIB_VERSION)
208         " log4shib/" + LOG4SHIB_VERSION;
209 #elif defined(LOG4CPP_VERSION)
210         " log4cpp/" + LOG4CPP_VERSION;
211 #endif
212     if (!SAMLConfig::getConfig().init()) {
213         log.fatal("failed to initialize OpenSAML library");
214         return false;
215     }
216 #else
217     XMLToolingConfig::getConfig().user_agent = string(PACKAGE_NAME) + '/' + PACKAGE_VERSION +
218         " XMLTooling/" + gXMLToolingDotVersionStr +
219         " Xerces-C/" + XERCES_FULLVERSIONDOT +
220 #if defined(LOG4SHIB_VERSION)
221         " log4shib/" + LOG4SHIB_VERSION;
222 #elif defined(LOG4CPP_VERSION)
223         " log4cpp/" + LOG4CPP_VERSION;
224 #endif
225     if (!XMLToolingConfig::getConfig().init()) {
226         log.fatal("failed to initialize XMLTooling library");
227         return false;
228     }
229 #endif
230     if (!catalog_path)
231         catalog_path = getenv("SHIBSP_SCHEMAS");
232     if (!catalog_path)
233         catalog_path = SHIBSP_SCHEMAS;
234     if (!XMLToolingConfig::getConfig().getValidatingParser().loadCatalogs(catalog_path)) {
235         log.warn("failed to load schema catalogs into validating parser");
236     }
237
238     PathResolver* pr = XMLToolingConfig::getConfig().getPathResolver();
239     pr->setDefaultPackageName(PACKAGE_NAME);
240     pr->setDefaultPrefix(inst_prefix2.c_str());
241     pr->setCfgDir(inst_prefix);
242     inst_prefix = getenv("SHIBSP_LIBDIR");
243     if (!inst_prefix || !*inst_prefix)
244         inst_prefix = SHIBSP_LIBDIR;
245     pr->setLibDir(inst_prefix);
246     inst_prefix = getenv("SHIBSP_LOGDIR");
247     if (!inst_prefix || !*inst_prefix)
248         inst_prefix = SHIBSP_LOGDIR;
249     pr->setLogDir(inst_prefix);
250     inst_prefix = getenv("SHIBSP_RUNDIR");
251     if (!inst_prefix || !*inst_prefix)
252         inst_prefix = SHIBSP_RUNDIR;
253     pr->setRunDir(inst_prefix);
254     inst_prefix = getenv("SHIBSP_CACHEDIR");
255     if (!inst_prefix || !*inst_prefix)
256         inst_prefix = SHIBSP_CACHEDIR;
257     pr->setCacheDir(inst_prefix);
258     inst_prefix = getenv("SHIBSP_XMLDIR");
259     if (!inst_prefix || !*inst_prefix)
260         inst_prefix = SHIBSP_XMLDIR;
261     pr->setXMLDir(inst_prefix);
262
263     XMLToolingConfig::getConfig().setTemplateEngine(new TemplateEngine());
264     XMLToolingConfig::getConfig().getTemplateEngine()->setTagPrefix("shibmlp");
265
266     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
267     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
268     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
269     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
270     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
271     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
272
273 #ifdef SHIBSP_LITE
274     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
275     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
276     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
277     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
278     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
279     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
280 #endif
281
282 #ifndef SHIBSP_LITE
283     if (isEnabled(Metadata))
284         registerMetadataExtClasses();
285     if (isEnabled(Trust))
286         registerPKIXTrustEngine();
287 #endif
288
289     registerAttributeFactories();
290
291     if (isEnabled(Handlers)) {
292         registerHandlers();
293         registerLogoutInitiators();
294         registerSessionInitiators();
295         registerProtocolProviders();
296     }
297
298     registerServiceProviders();
299
300 #ifndef SHIBSP_LITE
301     if (isEnabled(AttributeResolution)) {
302         registerAttributeExtractors();
303         registerAttributeDecoders();
304         registerAttributeResolvers();
305         registerAttributeFilters();
306         registerMatchFunctors();
307     }
308     if (isEnabled(Logging)) {
309         registerEvents();
310     }
311     registerSecurityPolicyProviders();
312 #endif
313
314     if (isEnabled(Listener))
315         registerListenerServices();
316
317     if (isEnabled(RequestMapping)) {
318         registerAccessControls();
319         registerRequestMappers();
320     }
321
322     if (isEnabled(Caching))
323         registerSessionCaches();
324
325 #ifndef SHIBSP_LITE
326     if (isEnabled(OutOfProcess))
327         m_artifactResolver = new ArtifactResolver();
328 #endif
329     srand(static_cast<unsigned int>(std::time(nullptr)));
330
331     log.info("%s library initialization complete", PACKAGE_STRING);
332     return true;
333 }
334
335 void SPConfig::term()
336 {
337     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
338     log.info("%s library shutting down", PACKAGE_STRING);
339
340     setServiceProvider(nullptr);
341     if (m_configDoc)
342         m_configDoc->release();
343     m_configDoc = nullptr;
344 #ifndef SHIBSP_LITE
345     setArtifactResolver(nullptr);
346 #endif
347
348     if (isEnabled(Handlers)) {
349         ArtifactResolutionServiceManager.deregisterFactories();
350         AssertionConsumerServiceManager.deregisterFactories();
351         LogoutInitiatorManager.deregisterFactories();
352         ManageNameIDServiceManager.deregisterFactories();
353         SessionInitiatorManager.deregisterFactories();
354         SingleLogoutServiceManager.deregisterFactories();
355         HandlerManager.deregisterFactories();
356         ProtocolProviderManager.deregisterFactories();
357     }
358
359     ServiceProviderManager.deregisterFactories();
360     Attribute::deregisterFactories();
361
362 #ifndef SHIBSP_LITE
363     SecurityPolicyProviderManager.deregisterFactories();
364     if (isEnabled(Logging)) {
365         EventManager.deregisterFactories();
366     }
367     if (isEnabled(AttributeResolution)) {
368         MatchFunctorManager.deregisterFactories();
369         AttributeFilterManager.deregisterFactories();
370         AttributeDecoderManager.deregisterFactories();
371         AttributeExtractorManager.deregisterFactories();
372         AttributeResolverManager.deregisterFactories();
373     }
374 #endif
375
376     if (isEnabled(Listener))
377         ListenerServiceManager.deregisterFactories();
378
379     if (isEnabled(RequestMapping)) {
380         AccessControlManager.deregisterFactories();
381         RequestMapperManager.deregisterFactories();
382     }
383
384     if (isEnabled(Caching))
385         SessionCacheManager.deregisterFactories();
386
387 #ifndef SHIBSP_LITE
388     SAMLConfig::getConfig().term();
389 #else
390     XMLToolingConfig::getConfig().term();
391 #endif
392     log.info("%s library shutdown complete", PACKAGE_STRING);
393 }
394
395 bool SPConfig::instantiate(const char* config, bool rethrow)
396 {
397 #ifdef _DEBUG
398     NDC ndc("instantiate");
399 #endif
400     if (!config)
401         config = getenv("SHIBSP_CONFIG");
402     if (!config)
403         config = SHIBSP_CONFIG;
404     try {
405         xercesc::DOMDocument* dummydoc;
406         if (*config == '"' || *config == '\'') {
407             throw ConfigurationException("The value of SHIBSP_CONFIG started with a quote.");
408         }
409         else if (*config != '<') {
410
411             // Mock up some XML.
412             string resolved(config);
413             stringstream snippet;
414             snippet
415                 << "<Dummy path='"
416                 << XMLToolingConfig::getConfig().getPathResolver()->resolve(resolved, PathResolver::XMLTOOLING_CFG_FILE)
417                 << "' validate='1'/>";
418             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
419             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
420             setServiceProvider(ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER, dummydoc->getDocumentElement()));
421             if (m_configDoc)
422                 m_configDoc->release();
423             m_configDoc = docjanitor.release();
424         }
425         else {
426             stringstream snippet(config);
427             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
428             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
429             static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
430             auto_ptr_char type(dummydoc->getDocumentElement()->getAttributeNS(nullptr,_type));
431             if (type.get() && *type.get())
432                 setServiceProvider(ServiceProviderManager.newPlugin(type.get(), dummydoc->getDocumentElement()));
433             else
434                 throw ConfigurationException("The supplied XML bootstrapping configuration did not include a type attribute.");
435             if (m_configDoc)
436                 m_configDoc->release();
437             m_configDoc = docjanitor.release();
438         }
439
440         getServiceProvider()->init();
441         return true;
442     }
443     catch (exception& ex) {
444         if (rethrow)
445             throw;
446         Category::getInstance(SHIBSP_LOGCAT".Config").fatal("caught exception while loading configuration: %s", ex.what());
447     }
448     return false;
449 }
450
451 bool SPInternalConfig::init(const char* catalog_path, const char* inst_prefix)
452 {
453 #ifdef _DEBUG
454     xmltooling::NDC ndc("init");
455 #endif
456
457     Lock initLock(m_lock);
458
459     if (m_initCount == INT_MAX) {
460         Category::getInstance(SHIBSP_LOGCAT".Config").crit("library initialized too many times");
461         return false;
462     }
463
464     if (m_initCount >= 1) {
465         ++m_initCount;
466         return true;
467     }
468
469     if (!SPConfig::init(catalog_path, inst_prefix)) {
470         return false;
471     }
472
473     ++m_initCount;
474     return true;
475 }
476
477 void SPInternalConfig::term()
478 {
479 #ifdef _DEBUG
480     xmltooling::NDC ndc("term");
481 #endif
482     
483     Lock initLock(m_lock);
484     if (m_initCount == 0) {
485         Category::getInstance(SHIBSP_LOGCAT".Config").crit("term without corresponding init");
486         return;
487     }
488     else if (--m_initCount > 0) {
489         return;
490     }
491
492     SPConfig::term();
493 }