SSPCPP-616 - clean up concatenated string literals
[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* logconf = getenv("SHIBSP_LOGGING");
187     if (!logconf || !*logconf) {
188         if (isEnabled(SPConfig::Logging) && isEnabled(SPConfig::OutOfProcess) && !isEnabled(SPConfig::InProcess))
189             logconf = SHIBSP_OUTOFPROC_LOGGING;
190         else if (isEnabled(SPConfig::Logging) && isEnabled(SPConfig::InProcess) && !isEnabled(SPConfig::OutOfProcess))
191             logconf = SHIBSP_INPROC_LOGGING;
192         else
193             logconf = SHIBSP_LOGGING;
194     }
195     PathResolver localpr;
196     localpr.setDefaultPrefix(inst_prefix2.c_str());
197     inst_prefix = getenv("SHIBSP_CFGDIR");
198     if (!inst_prefix || !*inst_prefix)
199         inst_prefix = SHIBSP_CFGDIR;
200     localpr.setCfgDir(inst_prefix);
201     std::string lc(logconf);
202     XMLToolingConfig::getConfig().log_config(localpr.resolve(lc, PathResolver::XMLTOOLING_CFG_FILE, PACKAGE_NAME).c_str());
203
204     Category& log=Category::getInstance(SHIBSP_LOGCAT ".Config");
205     log.debug("%s library initialization started", PACKAGE_STRING);
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
237     PathResolver* pr = XMLToolingConfig::getConfig().getPathResolver();
238     pr->setDefaultPackageName(PACKAGE_NAME);
239     pr->setDefaultPrefix(inst_prefix2.c_str());
240     pr->setCfgDir(inst_prefix);
241     inst_prefix = getenv("SHIBSP_LIBDIR");
242     if (!inst_prefix || !*inst_prefix)
243         inst_prefix = SHIBSP_LIBDIR;
244     pr->setLibDir(inst_prefix);
245     inst_prefix = getenv("SHIBSP_LOGDIR");
246     if (!inst_prefix || !*inst_prefix)
247         inst_prefix = SHIBSP_LOGDIR;
248     pr->setLogDir(inst_prefix);
249     inst_prefix = getenv("SHIBSP_RUNDIR");
250     if (!inst_prefix || !*inst_prefix)
251         inst_prefix = SHIBSP_RUNDIR;
252     pr->setRunDir(inst_prefix);
253     inst_prefix = getenv("SHIBSP_CACHEDIR");
254     if (!inst_prefix || !*inst_prefix)
255         inst_prefix = SHIBSP_CACHEDIR;
256     pr->setCacheDir(inst_prefix);
257     inst_prefix = getenv("SHIBSP_XMLDIR");
258     if (!inst_prefix || !*inst_prefix)
259         inst_prefix = SHIBSP_XMLDIR;
260     pr->setXMLDir(inst_prefix);
261
262     if (!catalog_path)
263         catalog_path = getenv("SHIBSP_SCHEMAS");
264     if (!catalog_path || !*catalog_path)
265         catalog_path = SHIBSP_SCHEMAS;
266     if (!XMLToolingConfig::getConfig().getValidatingParser().loadCatalogs(catalog_path)) {
267         log.warn("failed to load schema catalogs into validating parser");
268     }
269
270     XMLToolingConfig::getConfig().setTemplateEngine(new TemplateEngine());
271     XMLToolingConfig::getConfig().getTemplateEngine()->setTagPrefix("shibmlp");
272
273     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
274     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
275     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
276     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
277     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
278     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
279
280 #ifdef SHIBSP_LITE
281     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
282     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
283     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
284     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
285     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
286     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
287 #endif
288
289 #ifndef SHIBSP_LITE
290     if (isEnabled(Metadata))
291         registerMetadataExtClasses();
292     if (isEnabled(Trust))
293         registerPKIXTrustEngine();
294 #endif
295
296     registerAttributeFactories();
297
298     if (isEnabled(Handlers)) {
299         registerHandlers();
300         registerLogoutInitiators();
301         registerSessionInitiators();
302         registerProtocolProviders();
303     }
304
305     registerServiceProviders();
306
307 #ifndef SHIBSP_LITE
308     if (isEnabled(AttributeResolution)) {
309         registerAttributeExtractors();
310         registerAttributeDecoders();
311         registerAttributeResolvers();
312         registerAttributeFilters();
313         registerMatchFunctors();
314     }
315     if (isEnabled(Logging)) {
316         registerEvents();
317     }
318     registerSecurityPolicyProviders();
319 #endif
320
321     if (isEnabled(Listener))
322         registerListenerServices();
323
324     if (isEnabled(RequestMapping)) {
325         registerAccessControls();
326         registerRequestMappers();
327     }
328
329     if (isEnabled(Caching))
330         registerSessionCaches();
331
332 #ifndef SHIBSP_LITE
333     if (isEnabled(OutOfProcess))
334         m_artifactResolver = new ArtifactResolver();
335 #endif
336     srand(static_cast<unsigned int>(std::time(nullptr)));
337
338     log.info("%s library initialization complete", PACKAGE_STRING);
339     return true;
340 }
341
342 void SPConfig::term()
343 {
344     Category& log=Category::getInstance(SHIBSP_LOGCAT ".Config");
345     log.info("%s library shutting down", PACKAGE_STRING);
346
347     setServiceProvider(nullptr);
348     if (m_configDoc)
349         m_configDoc->release();
350     m_configDoc = nullptr;
351 #ifndef SHIBSP_LITE
352     setArtifactResolver(nullptr);
353 #endif
354
355     if (isEnabled(Handlers)) {
356         ArtifactResolutionServiceManager.deregisterFactories();
357         AssertionConsumerServiceManager.deregisterFactories();
358         LogoutInitiatorManager.deregisterFactories();
359         ManageNameIDServiceManager.deregisterFactories();
360         SessionInitiatorManager.deregisterFactories();
361         SingleLogoutServiceManager.deregisterFactories();
362         HandlerManager.deregisterFactories();
363         ProtocolProviderManager.deregisterFactories();
364     }
365
366     ServiceProviderManager.deregisterFactories();
367     Attribute::deregisterFactories();
368
369 #ifndef SHIBSP_LITE
370     SecurityPolicyProviderManager.deregisterFactories();
371     if (isEnabled(Logging)) {
372         EventManager.deregisterFactories();
373     }
374     if (isEnabled(AttributeResolution)) {
375         MatchFunctorManager.deregisterFactories();
376         AttributeFilterManager.deregisterFactories();
377         AttributeDecoderManager.deregisterFactories();
378         AttributeExtractorManager.deregisterFactories();
379         AttributeResolverManager.deregisterFactories();
380     }
381 #endif
382
383     if (isEnabled(Listener))
384         ListenerServiceManager.deregisterFactories();
385
386     if (isEnabled(RequestMapping)) {
387         AccessControlManager.deregisterFactories();
388         RequestMapperManager.deregisterFactories();
389     }
390
391     if (isEnabled(Caching))
392         SessionCacheManager.deregisterFactories();
393
394 #ifndef SHIBSP_LITE
395     SAMLConfig::getConfig().term();
396 #else
397     XMLToolingConfig::getConfig().term();
398 #endif
399     log.info("%s library shutdown complete", PACKAGE_STRING);
400 }
401
402 bool SPConfig::instantiate(const char* config, bool rethrow)
403 {
404 #ifdef _DEBUG
405     NDC ndc("instantiate");
406 #endif
407     if (!config)
408         config = getenv("SHIBSP_CONFIG");
409     if (!config)
410         config = SHIBSP_CONFIG;
411     try {
412         xercesc::DOMDocument* dummydoc;
413         if (*config == '"' || *config == '\'') {
414             throw ConfigurationException("The value of SHIBSP_CONFIG started with a quote.");
415         }
416         else if (*config != '<') {
417
418             // Mock up some XML.
419             string resolved(config);
420             stringstream snippet;
421             snippet
422                 << "<Dummy path='"
423                 << XMLToolingConfig::getConfig().getPathResolver()->resolve(resolved, PathResolver::XMLTOOLING_CFG_FILE)
424                 << "' validate='1'/>";
425             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
426             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
427             setServiceProvider(ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER, dummydoc->getDocumentElement()));
428             if (m_configDoc)
429                 m_configDoc->release();
430             m_configDoc = docjanitor.release();
431         }
432         else {
433             stringstream snippet(config);
434             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
435             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
436             static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
437             auto_ptr_char type(dummydoc->getDocumentElement()->getAttributeNS(nullptr,_type));
438             if (type.get() && *type.get())
439                 setServiceProvider(ServiceProviderManager.newPlugin(type.get(), dummydoc->getDocumentElement()));
440             else
441                 throw ConfigurationException("The supplied XML bootstrapping configuration did not include a type attribute.");
442             if (m_configDoc)
443                 m_configDoc->release();
444             m_configDoc = docjanitor.release();
445         }
446
447         getServiceProvider()->init();
448         return true;
449     }
450     catch (exception& ex) {
451         if (rethrow)
452             throw;
453         Category::getInstance(SHIBSP_LOGCAT ".Config").fatal("caught exception while loading configuration: %s", ex.what());
454     }
455     return false;
456 }
457
458 bool SPInternalConfig::init(const char* catalog_path, const char* inst_prefix)
459 {
460 #ifdef _DEBUG
461     xmltooling::NDC ndc("init");
462 #endif
463
464     Lock initLock(m_lock);
465
466     if (m_initCount == INT_MAX) {
467         Category::getInstance(SHIBSP_LOGCAT ".Config").crit("library initialized too many times");
468         return false;
469     }
470
471     if (m_initCount >= 1) {
472         ++m_initCount;
473         return true;
474     }
475
476     if (!SPConfig::init(catalog_path, inst_prefix)) {
477         return false;
478     }
479
480     ++m_initCount;
481     return true;
482 }
483
484 void SPInternalConfig::term()
485 {
486 #ifdef _DEBUG
487     xmltooling::NDC ndc("term");
488 #endif
489     
490     Lock initLock(m_lock);
491     if (m_initCount == 0) {
492         Category::getInstance(SHIBSP_LOGCAT ".Config").crit("term without corresponding init");
493         return;
494     }
495     else if (--m_initCount > 0) {
496         return;
497     }
498
499     SPConfig::term();
500 }