44240f20f0c8e79de39f0c2ce7d698c0c9191727
[shibboleth/cpp-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 "AccessControl.h"
39 #include "exceptions.h"
40 #include "RequestMapper.h"
41 #include "ServiceProvider.h"
42 #include "SessionCache.h"
43 #include "SPConfig.h"
44 #include "TransactionLog.h"
45 #include "attribute/Attribute.h"
46 #include "binding/ProtocolProvider.h"
47 #include "handler/LogoutInitiator.h"
48 #include "handler/SessionInitiator.h"
49 #include "remoting/ListenerService.h"
50
51 #ifndef SHIBSP_LITE
52 # include "attribute/AttributeDecoder.h"
53 # include "attribute/filtering/AttributeFilter.h"
54 # include "attribute/filtering/MatchFunctor.h"
55 # include "attribute/resolver/AttributeExtractor.h"
56 # include "attribute/resolver/AttributeResolver.h"
57 # include "binding/ArtifactResolver.h"
58 # include "metadata/MetadataExt.h"
59 # include "security/PKIXTrustEngine.h"
60 # include "security/SecurityPolicyProvider.h"
61 # include <saml/SAMLConfig.h>
62 #endif
63
64 #include <ctime>
65 #include <xercesc/util/XMLUniDefs.hpp>
66 #include <xmltooling/XMLToolingConfig.h>
67 #include <xmltooling/util/NDC.h>
68 #include <xmltooling/util/ParserPool.h>
69 #include <xmltooling/util/PathResolver.h>
70 #include <xmltooling/util/TemplateEngine.h>
71 #include <xmltooling/util/Threads.h>
72 #include <xmltooling/util/XMLHelper.h>
73
74 using namespace shibsp;
75 using namespace opensaml;
76 using namespace xmltooling;
77 using namespace std;
78
79 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
80 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
81 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
82 DECL_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
83 DECL_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
84 DECL_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
85
86 #ifdef SHIBSP_LITE
87 DECL_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
88 DECL_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
89 DECL_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
90 DECL_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
91 DECL_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
92 DECL_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
93 #endif
94
95 namespace shibsp {
96    SPConfig g_config;
97 }
98
99 SPConfig& SPConfig::getConfig()
100 {
101     return g_config;
102 }
103
104 SPConfig::SPConfig() : attribute_value_delimeter(';'), m_serviceProvider(nullptr),
105 #ifndef SHIBSP_LITE
106     m_artifactResolver(nullptr),
107 #endif
108     m_features(0), m_configDoc(nullptr)
109 {
110 }
111
112 SPConfig::~SPConfig()
113 {
114 }
115
116 void SPConfig::setFeatures(unsigned long enabled)
117 {
118     m_features = enabled;
119 }
120
121 bool SPConfig::isEnabled(components_t feature)
122 {
123     return (m_features & feature)>0;
124 }
125
126 ServiceProvider* SPConfig::getServiceProvider() const
127 {
128     return m_serviceProvider;
129 }
130
131 void SPConfig::setServiceProvider(ServiceProvider* serviceProvider)
132 {
133     delete m_serviceProvider;
134     m_serviceProvider = serviceProvider;
135 }
136
137 #ifndef SHIBSP_LITE
138 void SPConfig::setArtifactResolver(MessageDecoder::ArtifactResolver* artifactResolver)
139 {
140     delete m_artifactResolver;
141     m_artifactResolver = artifactResolver;
142 }
143
144 const MessageDecoder::ArtifactResolver* SPConfig::getArtifactResolver() const
145 {
146     return m_artifactResolver;
147 }
148 #endif
149
150 bool SPConfig::init(const char* catalog_path, const char* inst_prefix)
151 {
152 #ifdef _DEBUG
153     NDC ndc("init");
154 #endif
155     if (!inst_prefix)
156         inst_prefix = getenv("SHIBSP_PREFIX");
157     if (!inst_prefix)
158         inst_prefix = SHIBSP_PREFIX;
159     std::string inst_prefix2;
160     while (*inst_prefix) {
161         inst_prefix2.push_back((*inst_prefix=='\\') ? ('/') : (*inst_prefix));
162         ++inst_prefix;
163     }
164
165     const char* loglevel=getenv("SHIBSP_LOGGING");
166     if (!loglevel)
167         loglevel = SHIBSP_LOGGING;
168     std::string ll(loglevel);
169     PathResolver localpr;
170     localpr.setDefaultPrefix(inst_prefix2.c_str());
171     inst_prefix = getenv("SHIBSP_CFGDIR");
172     if (!inst_prefix)
173         inst_prefix = SHIBSP_CFGDIR;
174     localpr.setCfgDir(inst_prefix);
175     XMLToolingConfig::getConfig().log_config(localpr.resolve(ll, PathResolver::XMLTOOLING_CFG_FILE, PACKAGE_NAME).c_str());
176
177     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
178     log.debug("%s library initialization started", PACKAGE_STRING);
179
180     if (!catalog_path)
181         catalog_path = getenv("SHIBSP_SCHEMAS");
182     if (!catalog_path)
183         catalog_path = SHIBSP_SCHEMAS;
184     XMLToolingConfig::getConfig().catalog_path = catalog_path;
185
186 #ifndef SHIBSP_LITE
187     if (!SAMLConfig::getConfig().init()) {
188         log.fatal("failed to initialize OpenSAML library");
189         return false;
190     }
191 #else
192     if (!XMLToolingConfig::getConfig().init()) {
193         log.fatal("failed to initialize XMLTooling library");
194         return false;
195     }
196 #endif
197     PathResolver* pr = XMLToolingConfig::getConfig().getPathResolver();
198     pr->setDefaultPackageName(PACKAGE_NAME);
199     pr->setDefaultPrefix(inst_prefix2.c_str());
200     pr->setCfgDir(inst_prefix);
201     inst_prefix = getenv("SHIBSP_LIBDIR");
202     if (!inst_prefix)
203         inst_prefix = SHIBSP_LIBDIR;
204     pr->setLibDir(inst_prefix);
205     inst_prefix = getenv("SHIBSP_LOGDIR");
206     if (!inst_prefix)
207         inst_prefix = SHIBSP_LOGDIR;
208     pr->setLogDir(inst_prefix);
209     inst_prefix = getenv("SHIBSP_RUNDIR");
210     if (!inst_prefix)
211         inst_prefix = SHIBSP_RUNDIR;
212     pr->setRunDir(inst_prefix);
213     inst_prefix = getenv("SHIBSP_XMLDIR");
214     if (!inst_prefix)
215         inst_prefix = SHIBSP_XMLDIR;
216     pr->setXMLDir(inst_prefix);
217
218     XMLToolingConfig::getConfig().setTemplateEngine(new TemplateEngine());
219     XMLToolingConfig::getConfig().getTemplateEngine()->setTagPrefix("shibmlp");
220
221     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeException,shibsp);
222     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeExtractionException,shibsp);
223     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeFilteringException,shibsp);
224     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(AttributeResolutionException,shibsp);
225     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ConfigurationException,shibsp);
226     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ListenerException,shibsp);
227
228 #ifdef SHIBSP_LITE
229     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
230     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(SecurityPolicyException,opensaml);
231     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ProfileException,opensaml);
232     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(FatalProfileException,opensaml);
233     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(RetryableProfileException,opensaml);
234     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataException,opensaml::saml2md);
235 #endif
236
237 #ifndef SHIBSP_LITE
238     if (isEnabled(Metadata))
239         registerMetadataExtClasses();
240     if (isEnabled(Trust))
241         registerPKIXTrustEngine();
242 #endif
243
244     registerAttributeFactories();
245
246     if (isEnabled(Handlers)) {
247         registerHandlers();
248         registerLogoutInitiators();
249         registerSessionInitiators();
250         registerProtocolProviders();
251     }
252
253     registerServiceProviders();
254
255 #ifndef SHIBSP_LITE
256     if (isEnabled(AttributeResolution)) {
257         registerAttributeExtractors();
258         registerAttributeDecoders();
259         registerAttributeResolvers();
260         registerAttributeFilters();
261         registerMatchFunctors();
262     }
263     registerSecurityPolicyProviders();
264 #endif
265
266     if (isEnabled(Listener))
267         registerListenerServices();
268
269     if (isEnabled(RequestMapping)) {
270         registerAccessControls();
271         registerRequestMappers();
272     }
273
274     if (isEnabled(Caching))
275         registerSessionCaches();
276
277 #ifndef SHIBSP_LITE
278     if (isEnabled(OutOfProcess))
279         m_artifactResolver = new ArtifactResolver();
280 #endif
281     srand(static_cast<unsigned int>(std::time(nullptr)));
282
283     log.info("%s library initialization complete", PACKAGE_STRING);
284     return true;
285 }
286
287 void SPConfig::term()
288 {
289 #ifdef _DEBUG
290     NDC ndc("term");
291 #endif
292     Category& log=Category::getInstance(SHIBSP_LOGCAT".Config");
293     log.info("%s library shutting down", PACKAGE_STRING);
294
295     setServiceProvider(nullptr);
296     if (m_configDoc)
297         m_configDoc->release();
298     m_configDoc = nullptr;
299 #ifndef SHIBSP_LITE
300     setArtifactResolver(nullptr);
301 #endif
302
303     if (isEnabled(Handlers)) {
304         ArtifactResolutionServiceManager.deregisterFactories();
305         AssertionConsumerServiceManager.deregisterFactories();
306         LogoutInitiatorManager.deregisterFactories();
307         ManageNameIDServiceManager.deregisterFactories();
308         SessionInitiatorManager.deregisterFactories();
309         SingleLogoutServiceManager.deregisterFactories();
310         HandlerManager.deregisterFactories();
311         ProtocolProviderManager.deregisterFactories();
312     }
313
314     ServiceProviderManager.deregisterFactories();
315     Attribute::deregisterFactories();
316
317 #ifndef SHIBSP_LITE
318     SecurityPolicyProviderManager.deregisterFactories();
319     if (isEnabled(AttributeResolution)) {
320         MatchFunctorManager.deregisterFactories();
321         AttributeFilterManager.deregisterFactories();
322         AttributeDecoderManager.deregisterFactories();
323         AttributeExtractorManager.deregisterFactories();
324         AttributeResolverManager.deregisterFactories();
325     }
326 #endif
327
328     if (isEnabled(Listener))
329         ListenerServiceManager.deregisterFactories();
330
331     if (isEnabled(RequestMapping)) {
332         AccessControlManager.deregisterFactories();
333         RequestMapperManager.deregisterFactories();
334     }
335
336     if (isEnabled(Caching))
337         SessionCacheManager.deregisterFactories();
338
339 #ifndef SHIBSP_LITE
340     SAMLConfig::getConfig().term();
341 #else
342     XMLToolingConfig::getConfig().term();
343 #endif
344     log.info("%s library shutdown complete", PACKAGE_STRING);
345 }
346
347 bool SPConfig::instantiate(const char* config, bool rethrow)
348 {
349 #ifdef _DEBUG
350     NDC ndc("instantiate");
351 #endif
352     if (!config)
353         config = getenv("SHIBSP_CONFIG");
354     if (!config)
355         config = SHIBSP_CONFIG;
356     try {
357         xercesc::DOMDocument* dummydoc;
358         if (*config == '"' || *config == '\'') {
359             throw ConfigurationException("The value of SHIBSP_CONFIG started with a quote.");
360         }
361         else if (*config != '<') {
362
363             // Mock up some XML.
364             string resolved(config);
365             stringstream snippet;
366             snippet
367                 << "<Dummy path='"
368                 << XMLToolingConfig::getConfig().getPathResolver()->resolve(resolved, PathResolver::XMLTOOLING_CFG_FILE)
369                 << "' validate='1'/>";
370             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
371             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
372             setServiceProvider(ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER, dummydoc->getDocumentElement()));
373             if (m_configDoc)
374                 m_configDoc->release();
375             m_configDoc = docjanitor.release();
376         }
377         else {
378             stringstream snippet(config);
379             dummydoc = XMLToolingConfig::getConfig().getParser().parse(snippet);
380             XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
381             static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
382             auto_ptr_char type(dummydoc->getDocumentElement()->getAttributeNS(nullptr,_type));
383             if (type.get() && *type.get())
384                 setServiceProvider(ServiceProviderManager.newPlugin(type.get(), dummydoc->getDocumentElement()));
385             else
386                 throw ConfigurationException("The supplied XML bootstrapping configuration did not include a type attribute.");
387             if (m_configDoc)
388                 m_configDoc->release();
389             m_configDoc = docjanitor.release();
390         }
391
392         getServiceProvider()->init();
393         return true;
394     }
395     catch (exception& ex) {
396         if (rethrow)
397             throw;
398         Category::getInstance(SHIBSP_LOGCAT".Config").fatal("caught exception while loading configuration: %s", ex.what());
399     }
400     return false;
401 }
402
403 TransactionLog::TransactionLog() : log(logging::Category::getInstance(SHIBSP_TX_LOGCAT)), m_lock(Mutex::create())
404 {
405 }
406
407 TransactionLog::~TransactionLog()
408 {
409     delete m_lock;
410 }
411
412 Lockable* TransactionLog::lock()
413 {
414     m_lock->lock();
415     return this;
416 }
417
418 void TransactionLog::unlock()
419 {
420     m_lock->unlock();
421 }