2 * Copyright 2001-2007 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * XMLServiceProvider.cpp
20 * XML-based SP configuration and mgmt
24 #include "exceptions.h"
25 #include "AccessControl.h"
26 #include "Application.h"
27 #include "RequestMapper.h"
28 #include "ServiceProvider.h"
29 #include "SessionCache.h"
31 #include "SPRequest.h"
32 #include "handler/SessionInitiator.h"
33 #include "remoting/ListenerService.h"
34 #include "util/DOMPropertySet.h"
35 #include "util/SPConstants.h"
37 #include <log4cpp/Category.hh>
38 #include <log4cpp/PropertyConfigurator.hh>
39 #include <xercesc/util/XMLUniDefs.hpp>
40 #include <xmltooling/XMLToolingConfig.h>
41 #include <xmltooling/util/NDC.h>
42 #include <xmltooling/util/ReloadableXMLFile.h>
43 #include <xmltooling/util/XMLHelper.h>
46 # include "TransactionLog.h"
47 # include "attribute/filtering/AttributeFilter.h"
48 # include "attribute/resolver/AttributeExtractor.h"
49 # include "attribute/resolver/AttributeResolver.h"
50 # include "security/PKIXTrustEngine.h"
51 # include <saml/SAMLConfig.h>
52 # include <saml/binding/ArtifactMap.h>
53 # include <saml/binding/SAMLArtifact.h>
54 # include <saml/saml1/core/Assertions.h>
55 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
56 # include <saml/saml2/metadata/ChainingMetadataProvider.h>
57 # include <xmltooling/security/ChainingTrustEngine.h>
58 # include <xmltooling/util/ReplayCache.h>
59 using namespace opensaml::saml2;
60 using namespace opensaml::saml2p;
61 using namespace opensaml::saml2md;
62 using namespace opensaml;
65 using namespace shibsp;
66 using namespace xmltooling;
67 using namespace log4cpp;
72 #if defined (_MSC_VER)
73 #pragma warning( push )
74 #pragma warning( disable : 4250 )
77 static vector<const Handler*> g_noHandlers;
79 // Application configuration wrapper
80 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
83 XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=NULL);
84 ~XMLApplication() { cleanup(); }
87 const ServiceProvider& getServiceProvider() const {return *m_sp;}
88 const char* getId() const {return getString("id").second;}
89 const char* getHash() const {return m_hash.c_str();}
92 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
93 throw ConfigurationException("No support for SAML 1.x artifact generation.");
95 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
96 pair<bool,int> index = make_pair(false,0);
97 const PropertySet* props = getRelyingParty(relyingParty);
99 index = getInt("artifactEndpointIndex");
101 index = getArtifactEndpointIndex();
102 return new SAML2ArtifactType0004(SAMLConfig::getConfig().hashSHA1(getString("entityID").second),index.first ? index.second : 1);
105 MetadataProvider* getMetadataProvider(bool required=true) const {
106 if (required && !m_base && !m_metadata)
107 throw ConfigurationException("No MetadataProvider available.");
108 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
110 TrustEngine* getTrustEngine(bool required=true) const {
111 if (required && !m_base && !m_trust)
112 throw ConfigurationException("No TrustEngine available.");
113 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
115 AttributeExtractor* getAttributeExtractor() const {
116 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
118 AttributeFilter* getAttributeFilter() const {
119 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
121 AttributeResolver* getAttributeResolver() const {
122 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
124 CredentialResolver* getCredentialResolver() const {
125 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
127 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
128 const vector<const XMLCh*>& getAudiences() const {
129 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
132 string getNotificationURL(const HTTPRequest& request, bool front, unsigned int index) const;
134 const set<string>& getRemoteUserAttributeIds() const {
135 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
138 void clearAttributeHeaders(SPRequest& request) const;
139 const SessionInitiator* getDefaultSessionInitiator() const;
140 const SessionInitiator* getSessionInitiatorById(const char* id) const;
141 const Handler* getDefaultAssertionConsumerService() const;
142 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
143 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
144 const Handler* getHandler(const char* path) const;
146 void receive(DDF& in, ostream& out) {
147 // Only current function is to return the headers to clear.
149 DDF ret=DDF(NULL).list();
150 DDFJanitor jret(ret);
151 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
152 header = DDF(i->first.c_str()).string(i->second.c_str());
158 // Provides filter to exclude special config elements.
159 short acceptNode(const DOMNode* node) const;
163 const ServiceProvider* m_sp; // this is ok because its locking scope includes us
164 const XMLApplication* m_base;
167 MetadataProvider* m_metadata;
168 TrustEngine* m_trust;
169 AttributeExtractor* m_attrExtractor;
170 AttributeFilter* m_attrFilter;
171 AttributeResolver* m_attrResolver;
172 CredentialResolver* m_credResolver;
173 vector<const XMLCh*> m_audiences;
175 // RelyingParty properties
176 DOMPropertySet* m_partyDefault;
178 map<xstring,PropertySet*> m_partyMap;
180 map<const XMLCh*,PropertySet*> m_partyMap;
183 vector<string> m_frontLogout,m_backLogout;
184 set<string> m_remoteUsers;
185 mutable vector< pair<string,string> > m_unsetHeaders;
188 // manage handler objects
189 vector<Handler*> m_handlers;
191 // maps location (path info) to applicable handlers
192 map<string,const Handler*> m_handlerMap;
194 // maps unique indexes to consumer services
195 map<unsigned int,const Handler*> m_acsIndexMap;
197 // pointer to default consumer service
198 const Handler* m_acsDefault;
200 // maps binding strings to supporting consumer service(s)
202 typedef map<xstring,vector<const Handler*> > ACSBindingMap;
204 typedef map<string,vector<const Handler*> > ACSBindingMap;
206 ACSBindingMap m_acsBindingMap;
208 // pointer to default session initiator
209 const SessionInitiator* m_sessionInitDefault;
211 // maps unique ID strings to session initiators
212 map<string,const SessionInitiator*> m_sessionInitMap;
214 // pointer to default artifact resolution service
215 const Handler* m_artifactResolutionDefault;
217 pair<bool,int> getArtifactEndpointIndex() const {
218 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
219 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
223 // Top-level configuration implementation
224 class SHIBSP_DLLLOCAL XMLConfig;
225 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
228 XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log);
231 RequestMapper* m_requestMapper;
232 map<string,Application*> m_appmap;
234 map< string,pair< PropertySet*,vector<const SecurityPolicyRule*> > > m_policyMap;
237 // Provides filter to exclude special config elements.
238 short acceptNode(const DOMNode* node) const;
240 void setDocument(DOMDocument* doc) {
245 void doExtensions(const DOMElement* e, const char* label, Category& log);
248 const XMLConfig* m_outer;
249 DOMDocument* m_document;
252 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile, public Remoted
255 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
256 m_impl(NULL), m_listener(NULL), m_sessionCache(NULL)
269 delete m_sessionCache;
273 SAMLConfig::getConfig().setArtifactMap(NULL);
274 XMLToolingConfig::getConfig().setReplayCache(NULL);
275 for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
280 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
281 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return m_impl->getBool(name,ns);}
282 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return m_impl->getString(name,ns);}
283 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return m_impl->getXMLString(name,ns);}
284 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return m_impl->getUnsignedInt(name,ns);}
285 pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return m_impl->getInt(name,ns);}
286 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
287 const DOMElement* getElement() const {return m_impl->getElement();}
290 void receive(DDF& in, ostream& out);
294 TransactionLog* getTransactionLog() const {
297 throw ConfigurationException("No TransactionLog available.");
300 StorageService* getStorageService(const char* id) const {
302 map<string,StorageService*>::const_iterator i=m_storage.find(id);
303 if (i!=m_storage.end())
310 ListenerService* getListenerService(bool required=true) const {
311 if (required && !m_listener)
312 throw ConfigurationException("No ListenerService available.");
316 SessionCache* getSessionCache(bool required=true) const {
317 if (required && !m_sessionCache)
318 throw ConfigurationException("No SessionCache available.");
319 return m_sessionCache;
322 RequestMapper* getRequestMapper(bool required=true) const {
323 if (required && !m_impl->m_requestMapper)
324 throw ConfigurationException("No RequestMapper available.");
325 return m_impl->m_requestMapper;
328 const Application* getApplication(const char* applicationId) const {
329 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
330 return (i!=m_impl->m_appmap.end()) ? i->second : NULL;
334 const PropertySet* getPolicySettings(const char* id) const {
335 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
336 if (i!=m_impl->m_policyMap.end())
337 return i->second.first;
338 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
341 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
342 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
343 if (i!=m_impl->m_policyMap.end())
344 return i->second.second;
345 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
350 pair<bool,DOMElement*> load();
353 friend class XMLConfigImpl;
354 XMLConfigImpl* m_impl;
355 mutable ListenerService* m_listener;
356 mutable SessionCache* m_sessionCache;
358 mutable TransactionLog* m_tranLog;
359 mutable map<string,StorageService*> m_storage;
363 #if defined (_MSC_VER)
364 #pragma warning( pop )
367 static const XMLCh _Application[] = UNICODE_LITERAL_11(A,p,p,l,i,c,a,t,i,o,n);
368 static const XMLCh Applications[] = UNICODE_LITERAL_12(A,p,p,l,i,c,a,t,i,o,n,s);
369 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
370 static const XMLCh _AttributeExtractor[] = UNICODE_LITERAL_18(A,t,t,r,i,b,u,t,e,E,x,t,r,a,c,t,o,r);
371 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
372 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
373 static const XMLCh _AssertionConsumerService[] = UNICODE_LITERAL_24(A,s,s,e,r,t,i,o,n,C,o,n,s,u,m,e,r,S,e,r,v,i,c,e);
374 static const XMLCh _ArtifactResolutionService[] =UNICODE_LITERAL_25(A,r,t,i,f,a,c,t,R,e,s,o,l,u,t,i,o,n,S,e,r,v,i,c,e);
375 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
376 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
377 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
378 static const XMLCh _CredentialResolver[] = UNICODE_LITERAL_18(C,r,e,d,e,n,t,i,a,l,R,e,s,o,l,v,e,r);
379 static const XMLCh DefaultRelyingParty[] = UNICODE_LITERAL_19(D,e,f,a,u,l,t,R,e,l,y,i,n,g,P,a,r,t,y);
380 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
381 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
382 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
383 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
384 static const XMLCh Implementation[] = UNICODE_LITERAL_14(I,m,p,l,e,m,e,n,t,a,t,i,o,n);
385 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
386 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
387 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
388 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
389 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
390 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
391 static const XMLCh _ManageNameIDService[] = UNICODE_LITERAL_19(M,a,n,a,g,e,N,a,m,e,I,D,S,e,r,v,i,c,e);
392 static const XMLCh MemoryListener[] = UNICODE_LITERAL_14(M,e,m,o,r,y,L,i,s,t,e,n,e,r);
393 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
394 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
395 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
396 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
397 static const XMLCh Policy[] = UNICODE_LITERAL_6(P,o,l,i,c,y);
398 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
399 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
400 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
401 static const XMLCh Rule[] = UNICODE_LITERAL_4(R,u,l,e);
402 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
403 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
404 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
405 static const XMLCh _SingleLogoutService[] = UNICODE_LITERAL_19(S,i,n,g,l,e,L,o,g,o,u,t,S,e,r,v,i,c,e);
406 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
407 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
408 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
409 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
410 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
413 class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter
416 short acceptNode(const DOMNode* node) const {
417 if (XMLHelper::isNodeNamed(node,shibspconstants::SHIB2SPCONFIG_NS,Rule))
418 return FILTER_REJECT;
419 return FILTER_ACCEPT;
425 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
427 return new XMLConfig(e);
431 XMLApplication::XMLApplication(
432 const ServiceProvider* sp,
434 const XMLApplication* base
435 ) : m_sp(sp), m_base(base),
437 m_metadata(NULL), m_trust(NULL),
438 m_attrExtractor(NULL), m_attrFilter(NULL), m_attrResolver(NULL),
439 m_credResolver(NULL), m_partyDefault(NULL),
441 m_unsetLock(NULL), m_acsDefault(NULL), m_sessionInitDefault(NULL), m_artifactResolutionDefault(NULL)
444 xmltooling::NDC ndc("XMLApplication");
446 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
449 // First load any property sets.
454 SPConfig& conf=SPConfig::getConfig();
456 SAMLConfig& samlConf=SAMLConfig::getConfig();
457 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
460 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec.
461 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
462 string tohash=getId();
463 tohash+=getString("entityID").second;
464 for (const char* ch = tohash.c_str(); *ch; ++ch) {
465 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
466 m_hash += (DIGITS[0x0F & *ch]);
469 // Load attribute ID lists for REMOTE_USER and header clearing.
470 if (conf.isEnabled(SPConfig::InProcess)) {
471 pair<bool,const char*> attributes = getString("REMOTE_USER");
472 if (attributes.first) {
473 char* dup = strdup(attributes.second);
476 while (start && *start) {
477 while (*start && isspace(*start))
481 pos = strchr(start,' ');
484 m_remoteUsers.insert(start);
485 start = pos ? pos+1 : NULL;
490 attributes = getString("unsetHeaders");
491 if (attributes.first) {
492 char* dup = strdup(attributes.second);
495 while (start && *start) {
496 while (*start && isspace(*start))
500 pos = strchr(start,' ');
504 string transformed("HTTP_");
505 const char* pch = start;
507 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
510 m_unsetHeaders.push_back(pair<string,string>(start,transformed));
511 start = pos ? pos+1 : NULL;
514 m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
518 Handler* handler=NULL;
519 const PropertySet* sessions = getPropertySet("Sessions");
521 // Process assertion export handler.
522 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
523 if (location.first) {
525 handler = conf.HandlerManager.newPlugin(samlconstants::SAML20_BINDING_URI, make_pair(sessions->getElement(), getId()));
526 m_handlers.push_back(handler);
528 // Insert into location map.
529 if (*location.second == '/')
530 m_handlerMap[location.second]=handler;
532 m_handlerMap[string("/") + location.second]=handler;
534 catch (exception& ex) {
535 log.error("caught exception installing assertion lookup handler: %s", ex.what());
539 // Process other handlers.
540 bool hardACS=false, hardSessionInit=false, hardArt=false;
541 const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : NULL;
544 // A handler is based on the Binding property in conjunction with the element name.
545 // If it's an ACS or SI, also handle index/id mappings and defaulting.
546 if (XMLString::equals(child->getLocalName(),_AssertionConsumerService)) {
547 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
548 if (!bindprop.get() || !*(bindprop.get())) {
549 log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
550 child = XMLHelper::getNextSiblingElement(child);
553 handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
554 // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
556 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
558 m_acsBindingMap[handler->getString("Binding").second].push_back(handler);
560 m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
563 pair<bool,bool> defprop=handler->getBool("isDefault");
565 if (defprop.second) {
567 m_acsDefault=handler;
570 else if (!m_acsDefault)
571 m_acsDefault=handler;
574 else if (XMLString::equals(child->getLocalName(),_SessionInitiator)) {
575 auto_ptr_char type(child->getAttributeNS(NULL,_type));
576 if (!type.get() || !*(type.get())) {
577 log.warn("SessionInitiator element has no type attribute, skipping it...");
578 child = XMLHelper::getNextSiblingElement(child);
581 SessionInitiator* sihandler=conf.SessionInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
583 pair<bool,const char*> si_id=handler->getString("id");
584 if (si_id.first && si_id.second)
585 m_sessionInitMap[si_id.second]=sihandler;
586 if (!hardSessionInit) {
587 pair<bool,bool> defprop=handler->getBool("isDefault");
589 if (defprop.second) {
590 hardSessionInit=true;
591 m_sessionInitDefault=sihandler;
594 else if (!m_sessionInitDefault)
595 m_sessionInitDefault=sihandler;
598 else if (XMLString::equals(child->getLocalName(),_LogoutInitiator)) {
599 auto_ptr_char type(child->getAttributeNS(NULL,_type));
600 if (!type.get() || !*(type.get())) {
601 log.warn("LogoutInitiator element has no type attribute, skipping it...");
602 child = XMLHelper::getNextSiblingElement(child);
605 handler=conf.LogoutInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
607 else if (XMLString::equals(child->getLocalName(),_ArtifactResolutionService)) {
608 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
609 if (!bindprop.get() || !*(bindprop.get())) {
610 log.warn("md:ArtifactResolutionService element has no Binding attribute, skipping it...");
611 child = XMLHelper::getNextSiblingElement(child);
614 handler=conf.ArtifactResolutionServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
617 pair<bool,bool> defprop=handler->getBool("isDefault");
619 if (defprop.second) {
621 m_artifactResolutionDefault=handler;
624 else if (!m_artifactResolutionDefault)
625 m_artifactResolutionDefault=handler;
628 else if (XMLString::equals(child->getLocalName(),_SingleLogoutService)) {
629 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
630 if (!bindprop.get() || !*(bindprop.get())) {
631 log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");
632 child = XMLHelper::getNextSiblingElement(child);
635 handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
637 else if (XMLString::equals(child->getLocalName(),_ManageNameIDService)) {
638 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
639 if (!bindprop.get() || !*(bindprop.get())) {
640 log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");
641 child = XMLHelper::getNextSiblingElement(child);
644 handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
647 auto_ptr_char type(child->getAttributeNS(NULL,_type));
648 if (!type.get() || !*(type.get())) {
649 log.warn("Handler element has no type attribute, skipping it...");
650 child = XMLHelper::getNextSiblingElement(child);
653 handler=conf.HandlerManager.newPlugin(type.get(),make_pair(child, getId()));
656 m_handlers.push_back(handler);
658 // Insert into location map.
659 location=handler->getString("Location");
660 if (location.first && *location.second == '/')
661 m_handlerMap[location.second]=handler;
662 else if (location.first)
663 m_handlerMap[string("/") + location.second]=handler;
666 catch (exception& ex) {
667 log.error("caught exception processing handler element: %s", ex.what());
670 child = XMLHelper::getNextSiblingElement(child);
674 DOMNodeList* nlist=e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS,Notify);
675 for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
676 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
677 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Channel);
678 auto_ptr_char loc(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Location));
679 if (loc.get() && *loc.get()) {
680 if (channel && *channel == chLatin_f)
681 m_frontLogout.push_back(loc.get());
683 m_backLogout.push_back(loc.get());
689 nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);
690 for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++)
691 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
692 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
694 // Always include our own entityID as an audience.
695 m_audiences.push_back(getXMLString("entityID").second);
697 if (conf.isEnabled(SPConfig::Metadata)) {
698 child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
700 auto_ptr_char type(child->getAttributeNS(NULL,_type));
701 log.info("building MetadataProvider of type %s...",type.get());
703 auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
705 m_metadata = mp.release();
707 catch (exception& ex) {
708 log.crit("error building/initializing MetadataProvider: %s", ex.what());
713 if (conf.isEnabled(SPConfig::Trust)) {
714 child = XMLHelper::getFirstChildElement(e,_TrustEngine);
716 auto_ptr_char type(child->getAttributeNS(NULL,_type));
717 log.info("building TrustEngine of type %s...",type.get());
719 m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);
721 catch (exception& ex) {
722 log.crit("error building TrustEngine: %s", ex.what());
727 if (conf.isEnabled(SPConfig::AttributeResolution)) {
728 child = XMLHelper::getFirstChildElement(e,_AttributeExtractor);
730 auto_ptr_char type(child->getAttributeNS(NULL,_type));
731 log.info("building AttributeExtractor of type %s...",type.get());
733 m_attrExtractor = conf.AttributeExtractorManager.newPlugin(type.get(),child);
735 catch (exception& ex) {
736 log.crit("error building AttributeExtractor: %s", ex.what());
740 child = XMLHelper::getFirstChildElement(e,_AttributeFilter);
742 auto_ptr_char type(child->getAttributeNS(NULL,_type));
743 log.info("building AttributeFilter of type %s...",type.get());
745 m_attrFilter = conf.AttributeFilterManager.newPlugin(type.get(),child);
747 catch (exception& ex) {
748 log.crit("error building AttributeFilter: %s", ex.what());
752 child = XMLHelper::getFirstChildElement(e,_AttributeResolver);
754 auto_ptr_char type(child->getAttributeNS(NULL,_type));
755 log.info("building AttributeResolver of type %s...",type.get());
757 m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);
759 catch (exception& ex) {
760 log.crit("error building AttributeResolver: %s", ex.what());
764 if (m_unsetHeaders.empty()) {
765 vector<string> unsetHeaders;
766 if (m_attrExtractor) {
767 Locker extlock(m_attrExtractor);
768 m_attrExtractor->getAttributeIds(unsetHeaders);
770 if (m_attrResolver) {
771 Locker reslock(m_attrResolver);
772 m_attrResolver->getAttributeIds(unsetHeaders);
774 if (unsetHeaders.empty()) {
776 m_unsetHeaders.insert(m_unsetHeaders.end(), m_base->m_unsetHeaders.begin(), m_base->m_unsetHeaders.end());
778 m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
781 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
782 string transformed("HTTP_");
783 const char* pch = hdr->c_str();
785 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
788 m_unsetHeaders.push_back(pair<string,string>(*hdr,transformed));
790 m_unsetHeaders.push_back(pair<string,string>("Shib-Application-ID","HTTP_SHIB_APPLICATION_ID"));
795 if (conf.isEnabled(SPConfig::Credentials)) {
796 child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
798 auto_ptr_char type(child->getAttributeNS(NULL,_type));
799 log.info("building CredentialResolver of type %s...",type.get());
801 m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
803 catch (exception& ex) {
804 log.crit("error building CredentialResolver: %s", ex.what());
809 // Finally, load relying parties.
810 child = XMLHelper::getFirstChildElement(e,DefaultRelyingParty);
812 m_partyDefault=new DOMPropertySet();
813 m_partyDefault->load(child,log,this);
814 child = XMLHelper::getFirstChildElement(child,RelyingParty);
816 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
817 rp->load(child,log,this);
818 rp->setParent(m_partyDefault);
819 m_partyMap[child->getAttributeNS(NULL,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
820 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
825 // In process only, we need a shared lock around accessing the header clearing list.
826 if (!conf.isEnabled(SPConfig::OutOfProcess)) {
827 m_unsetLock = RWLock::create();
829 else if (!conf.isEnabled(SPConfig::InProcess)) {
830 ListenerService* listener = sp->getListenerService(false);
832 string addr=string(getId()) + "::getHeaders::Application";
833 listener->regListener(addr.c_str(),this);
836 log.info("no ListenerService available, Application remoting disabled");
851 void XMLApplication::cleanup()
853 ListenerService* listener=getServiceProvider().getListenerService(false);
854 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
855 string addr=string(getId()) + "::getHeaders::Application";
856 listener->unregListener(addr.c_str(),this);
860 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
863 delete m_partyDefault;
864 m_partyDefault = NULL;
866 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
868 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<const XMLCh*,PropertySet>());
871 delete m_credResolver;
872 m_credResolver = NULL;
873 delete m_attrResolver;
874 m_attrResolver = NULL;
877 delete m_attrExtractor;
878 m_attrExtractor = NULL;
886 short XMLApplication::acceptNode(const DOMNode* node) const
888 const XMLCh* name=node->getLocalName();
889 if (XMLString::equals(name,_Application) ||
890 XMLString::equals(name,_Audience) ||
891 XMLString::equals(name,Notify) ||
892 XMLString::equals(name,_AssertionConsumerService) ||
893 XMLString::equals(name,_ArtifactResolutionService) ||
894 XMLString::equals(name,_LogoutInitiator) ||
895 XMLString::equals(name,_ManageNameIDService) ||
896 XMLString::equals(name,_SessionInitiator) ||
897 XMLString::equals(name,_SingleLogoutService) ||
898 XMLString::equals(name,DefaultRelyingParty) ||
899 XMLString::equals(name,RelyingParty) ||
900 XMLString::equals(name,_MetadataProvider) ||
901 XMLString::equals(name,_TrustEngine) ||
902 XMLString::equals(name,_CredentialResolver) ||
903 XMLString::equals(name,_AttributeFilter) ||
904 XMLString::equals(name,_AttributeExtractor) ||
905 XMLString::equals(name,_AttributeResolver))
906 return FILTER_REJECT;
908 return FILTER_ACCEPT;
913 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
915 if (!m_partyDefault && m_base)
916 return m_base->getRelyingParty(provider);
918 return m_partyDefault;
921 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
922 if (i!=m_partyMap.end())
924 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
926 if (group->getName()) {
927 i=m_partyMap.find(group->getName());
928 if (i!=m_partyMap.end())
931 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
934 map<const XMLCh*,PropertySet*>::const_iterator i=m_partyMap.begin();
935 for (; i!=m_partyMap.end(); i++) {
936 if (XMLString::equals(i->first,provider->getId()))
938 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
940 if (XMLString::equals(i->first,group->getName()))
942 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
946 return m_partyDefault;
951 string XMLApplication::getNotificationURL(const HTTPRequest& request, bool front, unsigned int index) const
953 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
955 return m_base ? m_base->getNotificationURL(request, front, index) : string();
956 else if (index >= locs.size())
959 const char* resource = request.getRequestURL();
960 #ifdef HAVE_STRCASECMP
961 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
963 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
965 throw ConfigurationException("Request URL was not absolute.");
967 const char* handler=locs[index].c_str();
969 // Should never happen...
970 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
971 throw ConfigurationException(
972 "Invalid Location property ($1) in Notify element for Application ($2)",
973 params(2, handler ? handler : "null", getId())
976 // The "Location" property can be in one of three formats:
978 // 1) a full URI: http://host/foo/bar
979 // 2) a hostless URI: http:///foo/bar
980 // 3) a relative path: /foo/bar
982 // # Protocol Host Path
983 // 1 handler handler handler
984 // 2 handler resource handler
985 // 3 resource resource handler
987 const char* path = NULL;
989 // Decide whether to use the handler or the resource for the "protocol"
991 if (*handler != '/') {
999 // break apart the "protocol" string into protocol, host, and "the rest"
1000 const char* colon=strchr(prot,':');
1002 const char* slash=strchr(colon,'/');
1006 // Compute the actual protocol and store.
1007 string notifyURL(prot, colon-prot);
1009 // create the "host" from either the colon/slash or from the target string
1010 // If prot == handler then we're in either #1 or #2, else #3.
1011 // If slash == colon then we're in #2.
1012 if (prot != handler || slash == colon) {
1013 colon = strchr(resource, ':');
1014 colon += 3; // Get past the ://
1015 slash = strchr(colon, '/');
1017 string host(colon, (slash ? slash-colon : strlen(colon)));
1020 notifyURL += host + path;
1024 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1026 if (m_sessionInitDefault) return m_sessionInitDefault;
1027 return m_base ? m_base->getDefaultSessionInitiator() : NULL;
1030 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1032 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1033 if (i!=m_sessionInitMap.end()) return i->second;
1034 return m_base ? m_base->getSessionInitiatorById(id) : NULL;
1037 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1039 if (m_acsDefault) return m_acsDefault;
1040 return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
1043 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1045 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1046 if (i!=m_acsIndexMap.end()) return i->second;
1047 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
1050 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1052 #ifdef HAVE_GOOD_STL
1053 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1055 auto_ptr_char temp(binding);
1056 ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
1058 if (i!=m_acsBindingMap.end())
1060 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1063 const Handler* XMLApplication::getHandler(const char* path) const
1066 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1067 if (i!=m_handlerMap.end())
1069 return m_base ? m_base->getHandler(path) : NULL;
1072 void XMLApplication::clearAttributeHeaders(SPRequest& request) const
1074 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
1075 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i)
1076 request.clearHeader(i->first.c_str(), i->second.c_str());
1080 m_unsetLock->rdlock();
1081 if (m_unsetHeaders.empty()) {
1082 // No headers yet, so we have to request them from the remote half.
1083 m_unsetLock->unlock();
1084 m_unsetLock->wrlock();
1085 if (m_unsetHeaders.empty()) {
1086 SharedLock wrlock(m_unsetLock, false);
1087 string addr=string(getId()) + "::getHeaders::Application";
1088 DDF out,in = DDF(addr.c_str());
1089 DDFJanitor jin(in),jout(out);
1090 out = getServiceProvider().getListenerService()->send(in);
1092 DDF header = out.first();
1093 while (header.isstring()) {
1094 m_unsetHeaders.push_back(pair<string,string>(header.name(),header.string()));
1095 header = out.next();
1100 m_unsetLock->unlock();
1102 m_unsetLock->rdlock();
1105 // Now holding read lock.
1106 SharedLock unsetLock(m_unsetLock, false);
1107 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i)
1108 request.clearHeader(i->first.c_str(), i->second.c_str());
1111 short XMLConfigImpl::acceptNode(const DOMNode* node) const
1113 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1114 return FILTER_ACCEPT;
1115 const XMLCh* name=node->getLocalName();
1116 if (XMLString::equals(name,Applications) ||
1117 XMLString::equals(name,_ArtifactMap) ||
1118 XMLString::equals(name,_Extensions) ||
1119 XMLString::equals(name,Implementation) ||
1120 XMLString::equals(name,Listener) ||
1121 XMLString::equals(name,MemoryListener) ||
1122 XMLString::equals(name,Policy) ||
1123 XMLString::equals(name,_RequestMapper) ||
1124 XMLString::equals(name,_ReplayCache) ||
1125 XMLString::equals(name,_SessionCache) ||
1126 XMLString::equals(name,_StorageService) ||
1127 XMLString::equals(name,TCPListener) ||
1128 XMLString::equals(name,UnixListener))
1129 return FILTER_REJECT;
1131 return FILTER_ACCEPT;
1134 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1136 const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
1138 exts=XMLHelper::getFirstChildElement(exts,Library);
1140 auto_ptr_char path(exts->getAttributeNS(NULL,_path));
1143 XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts);
1144 log.debug("loaded %s extension library (%s)", label, path.get());
1147 catch (exception& e) {
1148 const XMLCh* fatal=exts->getAttributeNS(NULL,_fatal);
1149 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
1150 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
1154 log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
1157 exts=XMLHelper::getNextSiblingElement(exts,Library);
1162 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1163 : m_requestMapper(NULL), m_outer(outer), m_document(NULL)
1166 xmltooling::NDC ndc("XMLConfigImpl");
1170 SPConfig& conf=SPConfig::getConfig();
1172 SAMLConfig& samlConf=SAMLConfig::getConfig();
1174 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1175 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
1176 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
1178 // Initialize log4cpp manually in order to redirect log messages as soon as possible.
1179 if (conf.isEnabled(SPConfig::Logging)) {
1180 const XMLCh* logconf=NULL;
1181 if (conf.isEnabled(SPConfig::OutOfProcess))
1182 logconf=SHAR->getAttributeNS(NULL,logger);
1183 else if (conf.isEnabled(SPConfig::InProcess))
1184 logconf=SHIRE->getAttributeNS(NULL,logger);
1185 if (!logconf || !*logconf)
1186 logconf=e->getAttributeNS(NULL,logger);
1187 if (logconf && *logconf) {
1188 auto_ptr_char logpath(logconf);
1189 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
1190 XMLToolingConfig::getConfig().log_config(logpath.get());
1195 m_outer->m_tranLog = new TransactionLog();
1199 // First load any property sets.
1202 const DOMElement* child;
1205 // Much of the processing can only occur on the first instantiation.
1208 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1210 xmlConf.clock_skew_secs=skew.second;
1213 doExtensions(e, "global", log);
1214 if (conf.isEnabled(SPConfig::OutOfProcess))
1215 doExtensions(SHAR, "out of process", log);
1217 if (conf.isEnabled(SPConfig::InProcess))
1218 doExtensions(SHIRE, "in process", log);
1220 // Instantiate the ListenerService and SessionCache objects.
1221 if (conf.isEnabled(SPConfig::Listener)) {
1222 child=XMLHelper::getFirstChildElement(SHAR,UnixListener);
1224 plugtype=UNIX_LISTENER_SERVICE;
1226 child=XMLHelper::getFirstChildElement(SHAR,TCPListener);
1228 plugtype=TCP_LISTENER_SERVICE;
1230 child=XMLHelper::getFirstChildElement(SHAR,MemoryListener);
1232 plugtype=MEMORY_LISTENER_SERVICE;
1234 child=XMLHelper::getFirstChildElement(SHAR,Listener);
1236 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1238 plugtype=type.get();
1244 log.info("building ListenerService of type %s...", plugtype.c_str());
1245 m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(),child);
1248 log.fatal("can't build ListenerService, missing conf:Listener element?");
1249 throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
1253 if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1254 m_outer->m_listener->regListener("set::RelayState",m_outer->m_listener);
1255 m_outer->m_listener->regListener("get::RelayState",m_outer->m_listener);
1258 if (conf.isEnabled(SPConfig::Caching)) {
1259 if (conf.isEnabled(SPConfig::OutOfProcess)) {
1261 // First build any StorageServices.
1263 child=XMLHelper::getFirstChildElement(SHAR,_StorageService);
1265 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1266 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1268 log.info("building StorageService (%s) of type %s...", id.get(), type.get());
1269 m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
1270 if (!strcmp(type.get(),MEMORY_STORAGE_SERVICE))
1273 catch (exception& ex) {
1274 log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
1276 child=XMLHelper::getNextSiblingElement(child,_StorageService);
1279 child=XMLHelper::getFirstChildElement(SHAR,_SessionCache);
1281 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1282 log.info("building SessionCache of type %s...",type.get());
1283 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(),child);
1286 log.warn("SessionCache unspecified, building SessionCache of type %s...",STORAGESERVICE_SESSION_CACHE);
1287 if (inmemID.empty()) {
1289 log.info("no StorageServices configured, providing in-memory version for session cache");
1290 m_outer->m_storage[inmemID] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE,NULL);
1292 child = e->getOwnerDocument()->createElementNS(NULL,_SessionCache);
1293 auto_ptr_XMLCh ssid(inmemID.c_str());
1294 const_cast<DOMElement*>(child)->setAttributeNS(NULL,_StorageService,ssid.get());
1295 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(STORAGESERVICE_SESSION_CACHE,child);
1299 StorageService* replaySS=NULL;
1300 child=XMLHelper::getFirstChildElement(SHAR,_ReplayCache);
1302 auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1303 if (ssid.get() && *ssid.get()) {
1304 if (m_outer->m_storage.count(ssid.get()))
1305 replaySS = m_outer->m_storage[ssid.get()];
1307 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
1309 log.crit("unable to locate StorageService (%s) in configuration", ssid.get());
1313 log.info("building ReplayCache using in-memory StorageService...");
1314 if (inmemID.empty()) {
1316 log.info("no StorageServices configured, providing in-memory version for legacy config");
1317 m_outer->m_storage[inmemID] = xmlConf.StorageServiceManager.newPlugin(MEMORY_STORAGE_SERVICE,NULL);
1319 replaySS = m_outer->m_storage[inmemID];
1321 xmlConf.setReplayCache(new ReplayCache(replaySS));
1324 child=XMLHelper::getFirstChildElement(SHAR,_ArtifactMap);
1326 auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1327 if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {
1328 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());
1329 samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));
1332 if (samlConf.getArtifactMap()==NULL) {
1333 log.info("building in-memory ArtifactMap...");
1334 samlConf.setArtifactMap(new ArtifactMap(child));
1339 child=XMLHelper::getFirstChildElement(SHIRE,_SessionCache);
1341 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1342 log.info("building SessionCache of type %s...",type.get());
1343 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(),child);
1346 log.warn("SessionCache unspecified, building SessionCache of type %s...",REMOTED_SESSION_CACHE);
1347 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(REMOTED_SESSION_CACHE,child);
1351 } // end of first-time-only stuff
1353 // Back to the fully dynamic stuff...next up is the RequestMapper.
1354 if (conf.isEnabled(SPConfig::RequestMapping)) {
1355 child=XMLHelper::getFirstChildElement(SHIRE,_RequestMapper);
1357 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1358 log.info("building RequestMapper of type %s...",type.get());
1359 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1364 // Load security policies.
1365 child = XMLHelper::getLastChildElement(e,SecurityPolicies);
1367 PolicyNodeFilter filter;
1368 child = XMLHelper::getFirstChildElement(child,Policy);
1370 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1371 pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];
1373 auto_ptr<DOMPropertySet> settings(new DOMPropertySet());
1374 settings->load(child, log, &filter);
1375 rules.first = settings.release();
1376 const DOMElement* rule = XMLHelper::getFirstChildElement(child,Rule);
1378 auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1380 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1382 catch (exception& ex) {
1383 log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1385 rule = XMLHelper::getNextSiblingElement(rule,Rule);
1387 child = XMLHelper::getNextSiblingElement(child,Policy);
1392 // Load the default application. This actually has a fixed ID of "default". ;-)
1393 child=XMLHelper::getLastChildElement(e,Applications);
1395 log.fatal("can't build default Application object, missing conf:Applications element?");
1396 throw ConfigurationException("can't build default Application object, missing conf:Applications element?");
1398 XMLApplication* defapp=new XMLApplication(m_outer,child);
1399 m_appmap[defapp->getId()]=defapp;
1401 // Load any overrides.
1402 child = XMLHelper::getFirstChildElement(child,_Application);
1404 auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1405 if (m_appmap.count(iapp->getId()))
1406 log.crit("found conf:Application element with duplicate id attribute (%s), skipping it", iapp->getId());
1408 m_appmap[iapp->getId()]=iapp.release();
1410 child = XMLHelper::getNextSiblingElement(child,_Application);
1413 catch (exception&) {
1425 XMLConfigImpl::~XMLConfigImpl()
1430 void XMLConfigImpl::cleanup()
1432 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
1435 for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {
1436 delete i->second.first;
1437 for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());
1439 m_policyMap.clear();
1441 delete m_requestMapper;
1442 m_requestMapper = NULL;
1444 m_document->release();
1448 void XMLConfig::receive(DDF& in, ostream& out)
1451 if (!strcmp(in.name(), "get::RelayState")) {
1452 const char* id = in["id"].string();
1453 const char* key = in["key"].string();
1455 throw ListenerException("Required parameters missing for RelayState recovery.");
1458 StorageService* storage = getStorageService(id);
1460 if (storage->readString("RelayState",key,&relayState)>0) {
1461 if (in["clear"].integer())
1462 storage->deleteString("RelayState",key);
1466 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1467 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1471 // Repack for return to caller.
1472 DDF ret=DDF(NULL).string(relayState.c_str());
1473 DDFJanitor jret(ret);
1476 else if (!strcmp(in.name(), "set::RelayState")) {
1477 const char* id = in["id"].string();
1478 const char* value = in["value"].string();
1480 throw ListenerException("Required parameters missing for RelayState creation.");
1483 StorageService* storage = getStorageService(id);
1485 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1486 rsKey = SAMLArtifact::toHex(rsKey);
1487 storage->createString("RelayState", rsKey.c_str(), value, time(NULL) + 600);
1490 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1491 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1495 // Repack for return to caller.
1496 DDF ret=DDF(NULL).string(rsKey.c_str());
1497 DDFJanitor jret(ret);
1503 pair<bool,DOMElement*> XMLConfig::load()
1505 // Load from source using base class.
1506 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1508 // If we own it, wrap it.
1509 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1511 XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this,m_log);
1513 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1514 impl->setDocument(docjanitor.release());
1519 return make_pair(false,(DOMElement*)NULL);