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"
26 #include "AccessControl.h"
27 #include "Application.h"
28 #include "RequestMapper.h"
29 #include "ServiceProvider.h"
30 #include "SessionCache.h"
32 #include "SPRequest.h"
33 #include "handler/SessionInitiator.h"
34 #include "remoting/ListenerService.h"
35 #include "util/DOMPropertySet.h"
36 #include "util/SPConstants.h"
38 #if defined(XMLTOOLING_LOG4SHIB)
39 # include <log4shib/PropertyConfigurator.hh>
40 #elif defined(XMLTOOLING_LOG4CPP)
41 # include <log4cpp/PropertyConfigurator.hh>
43 # error "Supported logging library not available."
45 #include <xercesc/util/XMLUniDefs.hpp>
46 #include <xmltooling/XMLToolingConfig.h>
47 #include <xmltooling/version.h>
48 #include <xmltooling/util/NDC.h>
49 #include <xmltooling/util/ReloadableXMLFile.h>
50 #include <xmltooling/util/XMLHelper.h>
53 # include "TransactionLog.h"
54 # include "attribute/filtering/AttributeFilter.h"
55 # include "attribute/resolver/AttributeExtractor.h"
56 # include "attribute/resolver/AttributeResolver.h"
57 # include "security/PKIXTrustEngine.h"
58 # include <saml/SAMLConfig.h>
59 # include <saml/version.h>
60 # include <saml/binding/ArtifactMap.h>
61 # include <saml/binding/SAMLArtifact.h>
62 # include <saml/saml1/core/Assertions.h>
63 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
64 # include <saml/saml2/metadata/ChainingMetadataProvider.h>
65 # include <xmltooling/security/ChainingTrustEngine.h>
66 # include <xmltooling/util/ReplayCache.h>
67 using namespace opensaml::saml2;
68 using namespace opensaml::saml2p;
69 using namespace opensaml::saml2md;
70 using namespace opensaml;
73 using namespace shibsp;
74 using namespace xmltooling;
78 # define min(a,b) (((a) < (b)) ? (a) : (b))
83 #if defined (_MSC_VER)
84 #pragma warning( push )
85 #pragma warning( disable : 4250 )
88 static vector<const Handler*> g_noHandlers;
90 // Application configuration wrapper
91 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
94 XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=NULL);
95 ~XMLApplication() { cleanup(); }
97 const char* getHash() const {return m_hash.c_str();}
100 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
101 throw ConfigurationException("No support for SAML 1.x artifact generation.");
103 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
104 pair<bool,int> index = make_pair(false,0);
105 const PropertySet* props = getRelyingParty(relyingParty);
106 index = props->getInt("artifactEndpointIndex");
108 index = getArtifactEndpointIndex();
109 return new SAML2ArtifactType0004(SAMLConfig::getConfig().hashSHA1(props->getString("entityID").second),index.first ? index.second : 1);
112 MetadataProvider* getMetadataProvider(bool required=true) const {
113 if (required && !m_base && !m_metadata)
114 throw ConfigurationException("No MetadataProvider available.");
115 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
117 TrustEngine* getTrustEngine(bool required=true) const {
118 if (required && !m_base && !m_trust)
119 throw ConfigurationException("No TrustEngine available.");
120 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
122 AttributeExtractor* getAttributeExtractor() const {
123 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
125 AttributeFilter* getAttributeFilter() const {
126 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
128 AttributeResolver* getAttributeResolver() const {
129 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
131 CredentialResolver* getCredentialResolver() const {
132 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
134 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
135 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
136 const vector<const XMLCh*>* getAudiences() const {
137 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
140 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
142 const vector<string>& getRemoteUserAttributeIds() const {
143 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
146 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
147 void setHeader(SPRequest& request, const char* name, const char* value) const;
148 string getSecureHeader(const SPRequest& request, const char* name) const;
150 const SessionInitiator* getDefaultSessionInitiator() const;
151 const SessionInitiator* getSessionInitiatorById(const char* id) const;
152 const Handler* getDefaultAssertionConsumerService() const;
153 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
154 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
155 const Handler* getHandler(const char* path) const;
156 void getHandlers(vector<const Handler*>& handlers) const;
158 void receive(DDF& in, ostream& out) {
159 // Only current function is to return the headers to clear.
161 DDF ret=DDF(NULL).list();
162 DDFJanitor jret(ret);
163 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
164 header = DDF(i->first.c_str()).string(i->second.c_str());
170 // Provides filter to exclude special config elements.
171 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
176 acceptNode(const DOMNode* node) const;
180 const XMLApplication* m_base;
182 std::pair<std::string,std::string> m_attributePrefix;
184 MetadataProvider* m_metadata;
185 TrustEngine* m_trust;
186 AttributeExtractor* m_attrExtractor;
187 AttributeFilter* m_attrFilter;
188 AttributeResolver* m_attrResolver;
189 CredentialResolver* m_credResolver;
190 vector<const XMLCh*> m_audiences;
192 // RelyingParty properties
194 map<xstring,PropertySet*> m_partyMap;
196 map<const XMLCh*,PropertySet*> m_partyMap;
199 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
201 // manage handler objects
202 vector<Handler*> m_handlers;
204 // maps location (path info) to applicable handlers
205 map<string,const Handler*> m_handlerMap;
207 // maps unique indexes to consumer services
208 map<unsigned int,const Handler*> m_acsIndexMap;
210 // pointer to default consumer service
211 const Handler* m_acsDefault;
213 // maps binding strings to supporting consumer service(s)
215 typedef map<xstring,vector<const Handler*> > ACSBindingMap;
217 typedef map<string,vector<const Handler*> > ACSBindingMap;
219 ACSBindingMap m_acsBindingMap;
221 // pointer to default session initiator
222 const SessionInitiator* m_sessionInitDefault;
224 // maps unique ID strings to session initiators
225 map<string,const SessionInitiator*> m_sessionInitMap;
227 // pointer to default artifact resolution service
228 const Handler* m_artifactResolutionDefault;
230 pair<bool,int> getArtifactEndpointIndex() const {
231 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
232 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
236 // Top-level configuration implementation
237 class SHIBSP_DLLLOCAL XMLConfig;
238 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
241 XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log);
244 RequestMapper* m_requestMapper;
245 map<string,Application*> m_appmap;
247 map< string,pair< PropertySet*,vector<const SecurityPolicyRule*> > > m_policyMap;
248 vector< pair< string, pair<string,string> > > m_transportOptions;
251 // Provides filter to exclude special config elements.
252 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
257 acceptNode(const DOMNode* node) const;
259 void setDocument(DOMDocument* doc) {
264 void doExtensions(const DOMElement* e, const char* label, Category& log);
267 const XMLConfig* m_outer;
268 DOMDocument* m_document;
271 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
277 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
278 m_impl(NULL), m_listener(NULL), m_sessionCache(NULL)
291 delete m_sessionCache;
295 SAMLConfig::getConfig().setArtifactMap(NULL);
296 XMLToolingConfig::getConfig().setReplayCache(NULL);
297 for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
302 const PropertySet* getParent() const { return m_impl->getParent(); }
303 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
304 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return m_impl->getBool(name,ns);}
305 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return m_impl->getString(name,ns);}
306 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return m_impl->getXMLString(name,ns);}
307 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return m_impl->getUnsignedInt(name,ns);}
308 pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return m_impl->getInt(name,ns);}
309 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
310 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
311 const DOMElement* getElement() const {return m_impl->getElement();}
316 void receive(DDF& in, ostream& out);
318 TransactionLog* getTransactionLog() const {
321 throw ConfigurationException("No TransactionLog available.");
324 StorageService* getStorageService(const char* id) const {
326 map<string,StorageService*>::const_iterator i=m_storage.find(id);
327 if (i!=m_storage.end())
334 ListenerService* getListenerService(bool required=true) const {
335 if (required && !m_listener)
336 throw ConfigurationException("No ListenerService available.");
340 SessionCache* getSessionCache(bool required=true) const {
341 if (required && !m_sessionCache)
342 throw ConfigurationException("No SessionCache available.");
343 return m_sessionCache;
346 RequestMapper* getRequestMapper(bool required=true) const {
347 if (required && !m_impl->m_requestMapper)
348 throw ConfigurationException("No RequestMapper available.");
349 return m_impl->m_requestMapper;
352 const Application* getApplication(const char* applicationId) const {
353 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
354 return (i!=m_impl->m_appmap.end()) ? i->second : NULL;
358 const PropertySet* getPolicySettings(const char* id) const {
359 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
360 if (i!=m_impl->m_policyMap.end())
361 return i->second.first;
362 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
365 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
366 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
367 if (i!=m_impl->m_policyMap.end())
368 return i->second.second;
369 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
372 bool setTransportOptions(SOAPTransport& transport) const {
374 vector< pair< string, pair<string,string> > >::const_iterator opt;
375 for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
376 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
377 m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
386 pair<bool,DOMElement*> load();
389 friend class XMLConfigImpl;
390 XMLConfigImpl* m_impl;
391 mutable ListenerService* m_listener;
392 mutable SessionCache* m_sessionCache;
394 mutable TransactionLog* m_tranLog;
395 mutable map<string,StorageService*> m_storage;
399 #if defined (_MSC_VER)
400 #pragma warning( pop )
403 static const XMLCh ApplicationOverride[] = UNICODE_LITERAL_19(A,p,p,l,i,c,a,t,i,o,n,O,v,e,r,r,i,d,e);
404 static const XMLCh ApplicationDefaults[] = UNICODE_LITERAL_19(A,p,p,l,i,c,a,t,i,o,n,D,e,f,a,u,l,t,s);
405 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
406 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);
407 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
408 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
409 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);
410 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);
411 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
412 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
413 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
414 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);
415 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
416 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
417 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
418 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
419 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
420 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
421 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
422 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
423 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
424 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
425 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);
426 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
427 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
428 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
429 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
430 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
431 static const XMLCh Policy[] = UNICODE_LITERAL_6(P,o,l,i,c,y);
432 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
433 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
434 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
435 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
436 static const XMLCh Rule[] = UNICODE_LITERAL_4(R,u,l,e);
437 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
438 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
439 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
440 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);
441 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
442 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
443 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
444 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
445 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
446 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
447 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
450 class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter
453 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
458 acceptNode(const DOMNode* node) const {
459 return FILTER_REJECT;
466 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
468 return new XMLConfig(e);
472 XMLApplication::XMLApplication(
473 const ServiceProvider* sp,
475 const XMLApplication* base
476 ) : Application(sp), m_base(base),
478 m_metadata(NULL), m_trust(NULL),
479 m_attrExtractor(NULL), m_attrFilter(NULL), m_attrResolver(NULL),
480 m_credResolver(NULL),
482 m_acsDefault(NULL), m_sessionInitDefault(NULL), m_artifactResolutionDefault(NULL)
485 xmltooling::NDC ndc("XMLApplication");
487 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
490 // First load any property sets.
495 SPConfig& conf=SPConfig::getConfig();
497 SAMLConfig& samlConf=SAMLConfig::getConfig();
498 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
501 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec.
502 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
503 string tohash=getId();
504 tohash+=getString("entityID").second;
505 for (const char* ch = tohash.c_str(); *ch; ++ch) {
506 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
507 m_hash += (DIGITS[0x0F & *ch]);
510 // Populate prefix pair.
511 m_attributePrefix.second = "HTTP_";
512 pair<bool,const char*> prefix = getString("attributePrefix");
514 m_attributePrefix.first = prefix.second;
515 const char* pch = prefix.second;
517 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
522 // Load attribute ID lists for REMOTE_USER and header clearing.
523 if (conf.isEnabled(SPConfig::InProcess)) {
524 pair<bool,const char*> attributes = getString("REMOTE_USER");
525 if (attributes.first) {
526 char* dup = strdup(attributes.second);
529 while (start && *start) {
530 while (*start && isspace(*start))
534 pos = strchr(start,' ');
537 m_remoteUsers.push_back(start);
538 start = pos ? pos+1 : NULL;
543 attributes = getString("unsetHeaders");
544 if (attributes.first) {
545 string transformedprefix(m_attributePrefix.second);
547 prefix = getString("metadataAttributePrefix");
551 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
555 char* dup = strdup(attributes.second);
558 while (start && *start) {
559 while (*start && isspace(*start))
563 pos = strchr(start,' ');
570 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
574 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
576 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
577 start = pos ? pos+1 : NULL;
580 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
584 Handler* handler=NULL;
585 const PropertySet* sessions = getPropertySet("Sessions");
587 // Process assertion export handler.
588 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
589 if (location.first) {
591 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS,_Handler);
592 exportElement->setAttributeNS(NULL,Location,sessions->getXMLString("exportLocation").second);
593 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
594 if (exportACL.first) {
595 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
596 exportElement->setAttributeNS(NULL,_acl,exportACL.second);
598 handler = conf.HandlerManager.newPlugin(
599 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
601 m_handlers.push_back(handler);
603 // Insert into location map. If it contains the handlerURL, we skip past that part.
604 const char* pch = strstr(location.second, sessions->getString("handlerURL").second);
606 location.second = pch + strlen(sessions->getString("handlerURL").second);
607 if (*location.second == '/')
608 m_handlerMap[location.second]=handler;
610 m_handlerMap[string("/") + location.second]=handler;
612 catch (exception& ex) {
613 log.error("caught exception installing assertion lookup handler: %s", ex.what());
617 // Process other handlers.
618 bool hardACS=false, hardSessionInit=false, hardArt=false;
619 const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : NULL;
622 // A handler is based on the Binding property in conjunction with the element name.
623 // If it's an ACS or SI, also handle index/id mappings and defaulting.
624 if (XMLString::equals(child->getLocalName(),_AssertionConsumerService)) {
625 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
626 if (!bindprop.get() || !*(bindprop.get())) {
627 log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
628 child = XMLHelper::getNextSiblingElement(child);
631 handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
632 // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
634 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
636 m_acsBindingMap[handler->getString("Binding").second].push_back(handler);
638 m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
641 pair<bool,bool> defprop=handler->getBool("isDefault");
643 if (defprop.second) {
645 m_acsDefault=handler;
648 else if (!m_acsDefault)
649 m_acsDefault=handler;
652 else if (XMLString::equals(child->getLocalName(),_SessionInitiator)) {
653 auto_ptr_char type(child->getAttributeNS(NULL,_type));
654 if (!type.get() || !*(type.get())) {
655 log.warn("SessionInitiator element has no type attribute, skipping it...");
656 child = XMLHelper::getNextSiblingElement(child);
659 SessionInitiator* sihandler=conf.SessionInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
661 pair<bool,const char*> si_id=handler->getString("id");
662 if (si_id.first && si_id.second)
663 m_sessionInitMap[si_id.second]=sihandler;
664 if (!hardSessionInit) {
665 pair<bool,bool> defprop=handler->getBool("isDefault");
667 if (defprop.second) {
668 hardSessionInit=true;
669 m_sessionInitDefault=sihandler;
672 else if (!m_sessionInitDefault)
673 m_sessionInitDefault=sihandler;
676 else if (XMLString::equals(child->getLocalName(),_LogoutInitiator)) {
677 auto_ptr_char type(child->getAttributeNS(NULL,_type));
678 if (!type.get() || !*(type.get())) {
679 log.warn("LogoutInitiator element has no type attribute, skipping it...");
680 child = XMLHelper::getNextSiblingElement(child);
683 handler=conf.LogoutInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
685 else if (XMLString::equals(child->getLocalName(),_ArtifactResolutionService)) {
686 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
687 if (!bindprop.get() || !*(bindprop.get())) {
688 log.warn("md:ArtifactResolutionService element has no Binding attribute, skipping it...");
689 child = XMLHelper::getNextSiblingElement(child);
692 handler=conf.ArtifactResolutionServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
695 pair<bool,bool> defprop=handler->getBool("isDefault");
697 if (defprop.second) {
699 m_artifactResolutionDefault=handler;
702 else if (!m_artifactResolutionDefault)
703 m_artifactResolutionDefault=handler;
706 else if (XMLString::equals(child->getLocalName(),_SingleLogoutService)) {
707 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
708 if (!bindprop.get() || !*(bindprop.get())) {
709 log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");
710 child = XMLHelper::getNextSiblingElement(child);
713 handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
715 else if (XMLString::equals(child->getLocalName(),_ManageNameIDService)) {
716 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
717 if (!bindprop.get() || !*(bindprop.get())) {
718 log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");
719 child = XMLHelper::getNextSiblingElement(child);
722 handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
725 auto_ptr_char type(child->getAttributeNS(NULL,_type));
726 if (!type.get() || !*(type.get())) {
727 log.warn("Handler element has no type attribute, skipping it...");
728 child = XMLHelper::getNextSiblingElement(child);
731 handler=conf.HandlerManager.newPlugin(type.get(),make_pair(child, getId()));
734 m_handlers.push_back(handler);
736 // Insert into location map.
737 location=handler->getString("Location");
738 if (location.first && *location.second == '/')
739 m_handlerMap[location.second]=handler;
740 else if (location.first)
741 m_handlerMap[string("/") + location.second]=handler;
744 catch (exception& ex) {
745 log.error("caught exception processing handler element: %s", ex.what());
748 child = XMLHelper::getNextSiblingElement(child);
752 DOMNodeList* nlist=e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS,Notify);
753 for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
754 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
755 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Channel);
756 auto_ptr_char loc(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Location));
757 if (loc.get() && *loc.get()) {
758 if (channel && *channel == chLatin_f)
759 m_frontLogout.push_back(loc.get());
761 m_backLogout.push_back(loc.get());
767 nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);
768 for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++)
769 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
770 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
772 if (conf.isEnabled(SPConfig::Metadata)) {
773 child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
775 auto_ptr_char type(child->getAttributeNS(NULL,_type));
776 log.info("building MetadataProvider of type %s...",type.get());
778 auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
780 m_metadata = mp.release();
782 catch (exception& ex) {
783 log.crit("error building/initializing MetadataProvider: %s", ex.what());
788 if (conf.isEnabled(SPConfig::Trust)) {
789 child = XMLHelper::getFirstChildElement(e,_TrustEngine);
791 auto_ptr_char type(child->getAttributeNS(NULL,_type));
792 log.info("building TrustEngine of type %s...",type.get());
794 m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);
796 catch (exception& ex) {
797 log.crit("error building TrustEngine: %s", ex.what());
802 if (conf.isEnabled(SPConfig::AttributeResolution)) {
803 child = XMLHelper::getFirstChildElement(e,_AttributeExtractor);
805 auto_ptr_char type(child->getAttributeNS(NULL,_type));
806 log.info("building AttributeExtractor of type %s...",type.get());
808 m_attrExtractor = conf.AttributeExtractorManager.newPlugin(type.get(),child);
810 catch (exception& ex) {
811 log.crit("error building AttributeExtractor: %s", ex.what());
815 child = XMLHelper::getFirstChildElement(e,_AttributeFilter);
817 auto_ptr_char type(child->getAttributeNS(NULL,_type));
818 log.info("building AttributeFilter of type %s...",type.get());
820 m_attrFilter = conf.AttributeFilterManager.newPlugin(type.get(),child);
822 catch (exception& ex) {
823 log.crit("error building AttributeFilter: %s", ex.what());
827 child = XMLHelper::getFirstChildElement(e,_AttributeResolver);
829 auto_ptr_char type(child->getAttributeNS(NULL,_type));
830 log.info("building AttributeResolver of type %s...",type.get());
832 m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);
834 catch (exception& ex) {
835 log.crit("error building AttributeResolver: %s", ex.what());
839 if (m_unsetHeaders.empty()) {
840 vector<string> unsetHeaders;
841 if (m_attrExtractor) {
842 Locker extlock(m_attrExtractor);
843 m_attrExtractor->getAttributeIds(unsetHeaders);
845 else if (m_base && m_base->m_attrExtractor) {
846 Locker extlock(m_base->m_attrExtractor);
847 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
849 if (m_attrResolver) {
850 Locker reslock(m_attrResolver);
851 m_attrResolver->getAttributeIds(unsetHeaders);
853 else if (m_base && m_base->m_attrResolver) {
854 Locker extlock(m_base->m_attrResolver);
855 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
857 if (!unsetHeaders.empty()) {
858 string transformedprefix(m_attributePrefix.second);
860 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
864 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
868 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
872 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
875 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
877 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
880 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
884 if (conf.isEnabled(SPConfig::Credentials)) {
885 child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
887 auto_ptr_char type(child->getAttributeNS(NULL,_type));
888 log.info("building CredentialResolver of type %s...",type.get());
890 m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
892 catch (exception& ex) {
893 log.crit("error building CredentialResolver: %s", ex.what());
898 // Finally, load relying parties.
899 child = XMLHelper::getFirstChildElement(e,RelyingParty);
901 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
902 rp->load(child,NULL,this);
904 m_partyMap[child->getAttributeNS(NULL,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
905 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
909 // Out of process only, we register a listener endpoint.
910 if (!conf.isEnabled(SPConfig::InProcess)) {
911 ListenerService* listener = sp->getListenerService(false);
913 string addr=string(getId()) + "::getHeaders::Application";
914 listener->regListener(addr.c_str(),this);
917 log.info("no ListenerService available, Application remoting disabled");
932 void XMLApplication::cleanup()
934 ListenerService* listener=getServiceProvider().getListenerService(false);
935 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
936 string addr=string(getId()) + "::getHeaders::Application";
937 listener->unregListener(addr.c_str(),this);
939 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
943 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
945 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<const XMLCh*,PropertySet>());
948 delete m_credResolver;
949 m_credResolver = NULL;
950 delete m_attrResolver;
951 m_attrResolver = NULL;
954 delete m_attrExtractor;
955 m_attrExtractor = NULL;
963 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
966 DOMNodeFilter::FilterAction
968 XMLApplication::acceptNode(const DOMNode* node) const
970 const XMLCh* name=node->getLocalName();
971 if (XMLString::equals(name,ApplicationOverride) ||
972 XMLString::equals(name,_Audience) ||
973 XMLString::equals(name,Notify) ||
974 XMLString::equals(name,_Handler) ||
975 XMLString::equals(name,_AssertionConsumerService) ||
976 XMLString::equals(name,_ArtifactResolutionService) ||
977 XMLString::equals(name,_LogoutInitiator) ||
978 XMLString::equals(name,_ManageNameIDService) ||
979 XMLString::equals(name,_SessionInitiator) ||
980 XMLString::equals(name,_SingleLogoutService) ||
981 XMLString::equals(name,RelyingParty) ||
982 XMLString::equals(name,_MetadataProvider) ||
983 XMLString::equals(name,_TrustEngine) ||
984 XMLString::equals(name,_CredentialResolver) ||
985 XMLString::equals(name,_AttributeFilter) ||
986 XMLString::equals(name,_AttributeExtractor) ||
987 XMLString::equals(name,_AttributeResolver))
988 return FILTER_REJECT;
990 return FILTER_ACCEPT;
995 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1000 #ifdef HAVE_GOOD_STL
1001 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1002 if (i!=m_partyMap.end())
1004 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1006 if (group->getName()) {
1007 i=m_partyMap.find(group->getName());
1008 if (i!=m_partyMap.end())
1011 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1014 map<const XMLCh*,PropertySet*>::const_iterator i=m_partyMap.begin();
1015 for (; i!=m_partyMap.end(); i++) {
1016 if (XMLString::equals(i->first,provider->getEntityID()))
1018 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1020 if (XMLString::equals(i->first,group->getName()))
1022 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1029 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1034 #ifdef HAVE_GOOD_STL
1035 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1036 if (i!=m_partyMap.end())
1039 map<const XMLCh*,PropertySet*>::const_iterator i=m_partyMap.begin();
1040 for (; i!=m_partyMap.end(); i++) {
1041 if (XMLString::equals(i->first,entityID))
1050 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1052 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1054 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1055 else if (index >= locs.size())
1058 #ifdef HAVE_STRCASECMP
1059 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1061 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1063 throw ConfigurationException("Request URL was not absolute.");
1065 const char* handler=locs[index].c_str();
1067 // Should never happen...
1068 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1069 throw ConfigurationException(
1070 "Invalid Location property ($1) in Notify element for Application ($2)",
1071 params(2, handler ? handler : "null", getId())
1074 // The "Location" property can be in one of three formats:
1076 // 1) a full URI: http://host/foo/bar
1077 // 2) a hostless URI: http:///foo/bar
1078 // 3) a relative path: /foo/bar
1080 // # Protocol Host Path
1081 // 1 handler handler handler
1082 // 2 handler resource handler
1083 // 3 resource resource handler
1085 const char* path = NULL;
1087 // Decide whether to use the handler or the resource for the "protocol"
1089 if (*handler != '/') {
1097 // break apart the "protocol" string into protocol, host, and "the rest"
1098 const char* colon=strchr(prot,':');
1100 const char* slash=strchr(colon,'/');
1104 // Compute the actual protocol and store.
1105 string notifyURL(prot, colon-prot);
1107 // create the "host" from either the colon/slash or from the target string
1108 // If prot == handler then we're in either #1 or #2, else #3.
1109 // If slash == colon then we're in #2.
1110 if (prot != handler || slash == colon) {
1111 colon = strchr(resource, ':');
1112 colon += 3; // Get past the ://
1113 slash = strchr(colon, '/');
1115 string host(colon, (slash ? slash-colon : strlen(colon)));
1118 notifyURL += host + path;
1122 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1124 if (!m_attributePrefix.first.empty()) {
1125 string temp = m_attributePrefix.first + rawname;
1126 string temp2 = m_attributePrefix.second + (cginame + 5);
1127 request.clearHeader(temp.c_str(), temp2.c_str());
1130 m_base->clearHeader(request, rawname, cginame);
1133 request.clearHeader(rawname, cginame);
1137 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1139 if (!m_attributePrefix.first.empty()) {
1140 string temp = m_attributePrefix.first + name;
1141 request.setHeader(temp.c_str(), value);
1144 m_base->setHeader(request, name, value);
1147 request.setHeader(name, value);
1151 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1153 if (!m_attributePrefix.first.empty()) {
1154 string temp = m_attributePrefix.first + name;
1155 return request.getSecureHeader(temp.c_str());
1158 return m_base->getSecureHeader(request,name);
1161 return request.getSecureHeader(name);
1165 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1167 if (m_sessionInitDefault) return m_sessionInitDefault;
1168 return m_base ? m_base->getDefaultSessionInitiator() : NULL;
1171 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1173 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1174 if (i!=m_sessionInitMap.end()) return i->second;
1175 return m_base ? m_base->getSessionInitiatorById(id) : NULL;
1178 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1180 if (m_acsDefault) return m_acsDefault;
1181 return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
1184 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1186 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1187 if (i!=m_acsIndexMap.end()) return i->second;
1188 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
1191 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1193 #ifdef HAVE_GOOD_STL
1194 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1196 auto_ptr_char temp(binding);
1197 ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
1199 if (i!=m_acsBindingMap.end())
1201 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1204 const Handler* XMLApplication::getHandler(const char* path) const
1207 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1208 if (i!=m_handlerMap.end())
1210 return m_base ? m_base->getHandler(path) : NULL;
1213 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1215 handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1217 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1218 if (m_handlerMap.count(h->first) == 0)
1219 handlers.push_back(h->second);
1224 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1227 DOMNodeFilter::FilterAction
1229 XMLConfigImpl::acceptNode(const DOMNode* node) const
1231 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1232 return FILTER_ACCEPT;
1233 const XMLCh* name=node->getLocalName();
1234 if (XMLString::equals(name,ApplicationDefaults) ||
1235 XMLString::equals(name,_ArtifactMap) ||
1236 XMLString::equals(name,_Extensions) ||
1237 XMLString::equals(name,Listener) ||
1238 XMLString::equals(name,_RequestMapper) ||
1239 XMLString::equals(name,_ReplayCache) ||
1240 XMLString::equals(name,SecurityPolicies) ||
1241 XMLString::equals(name,_SessionCache) ||
1242 XMLString::equals(name,Site) ||
1243 XMLString::equals(name,_StorageService) ||
1244 XMLString::equals(name,TCPListener) ||
1245 XMLString::equals(name,TransportOption) ||
1246 XMLString::equals(name,UnixListener))
1247 return FILTER_REJECT;
1249 return FILTER_ACCEPT;
1252 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1254 const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
1256 exts=XMLHelper::getFirstChildElement(exts,Library);
1258 auto_ptr_char path(exts->getAttributeNS(NULL,_path));
1261 if (!XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts))
1262 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1263 log.debug("loaded %s extension library (%s)", label, path.get());
1266 catch (exception& e) {
1267 const XMLCh* fatal=exts->getAttributeNS(NULL,_fatal);
1268 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
1269 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
1273 log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
1276 exts=XMLHelper::getNextSiblingElement(exts,Library);
1281 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1282 : m_requestMapper(NULL), m_outer(outer), m_document(NULL)
1285 xmltooling::NDC ndc("XMLConfigImpl");
1289 SPConfig& conf=SPConfig::getConfig();
1291 SAMLConfig& samlConf=SAMLConfig::getConfig();
1293 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1294 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
1295 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
1297 // Initialize log4cpp manually in order to redirect log messages as soon as possible.
1298 if (conf.isEnabled(SPConfig::Logging)) {
1299 const XMLCh* logconf=NULL;
1300 if (conf.isEnabled(SPConfig::OutOfProcess))
1301 logconf=SHAR->getAttributeNS(NULL,logger);
1302 else if (conf.isEnabled(SPConfig::InProcess))
1303 logconf=SHIRE->getAttributeNS(NULL,logger);
1304 if (!logconf || !*logconf)
1305 logconf=e->getAttributeNS(NULL,logger);
1306 if (logconf && *logconf) {
1307 auto_ptr_char logpath(logconf);
1308 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
1309 XMLToolingConfig::getConfig().log_config(logpath.get());
1314 m_outer->m_tranLog = new TransactionLog();
1318 // Re-log library versions now that logging is set up.
1321 "Library versions: Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1322 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1326 "Library versions: Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1327 XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1331 // First load any property sets.
1334 const DOMElement* child;
1337 // Much of the processing can only occur on the first instantiation.
1340 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1342 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1345 doExtensions(e, "global", log);
1346 if (conf.isEnabled(SPConfig::OutOfProcess))
1347 doExtensions(SHAR, "out of process", log);
1349 if (conf.isEnabled(SPConfig::InProcess))
1350 doExtensions(SHIRE, "in process", log);
1352 // Instantiate the ListenerService and SessionCache objects.
1353 if (conf.isEnabled(SPConfig::Listener)) {
1354 child=XMLHelper::getFirstChildElement(e,UnixListener);
1356 plugtype=UNIX_LISTENER_SERVICE;
1358 child=XMLHelper::getFirstChildElement(e,TCPListener);
1360 plugtype=TCP_LISTENER_SERVICE;
1362 child=XMLHelper::getFirstChildElement(e,Listener);
1364 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1366 plugtype=type.get();
1371 log.info("building ListenerService of type %s...", plugtype.c_str());
1372 m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1375 log.fatal("can't build ListenerService, missing conf:Listener element?");
1376 throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
1381 if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1382 m_outer->m_listener->regListener("set::RelayState", m_outer->m_listener);
1383 m_outer->m_listener->regListener("get::RelayState", m_outer->m_listener);
1387 if (conf.isEnabled(SPConfig::Caching)) {
1388 if (conf.isEnabled(SPConfig::OutOfProcess)) {
1390 // First build any StorageServices.
1391 child=XMLHelper::getFirstChildElement(e,_StorageService);
1393 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1394 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1396 log.info("building StorageService (%s) of type %s...", id.get(), type.get());
1397 m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
1399 catch (exception& ex) {
1400 log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
1402 child=XMLHelper::getNextSiblingElement(child,_StorageService);
1406 StorageService* replaySS=NULL;
1407 child=XMLHelper::getFirstChildElement(e,_ReplayCache);
1409 auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1410 if (ssid.get() && *ssid.get()) {
1411 if (m_outer->m_storage.count(ssid.get()))
1412 replaySS = m_outer->m_storage[ssid.get()];
1414 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
1416 log.warn("unable to locate StorageService (%s) for ReplayCache, using dedicated in-memory instance", ssid.get());
1418 xmlConf.setReplayCache(new ReplayCache(replaySS));
1421 log.warn("no ReplayCache built, missing conf:ReplayCache element?");
1425 child=XMLHelper::getFirstChildElement(e,_ArtifactMap);
1427 auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1428 if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {
1429 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());
1430 samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));
1433 if (samlConf.getArtifactMap()==NULL) {
1434 log.info("building in-memory ArtifactMap...");
1435 samlConf.setArtifactMap(new ArtifactMap(child));
1439 child=XMLHelper::getFirstChildElement(e,_SessionCache);
1441 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1442 log.info("building SessionCache of type %s...",type.get());
1443 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(), child);
1446 log.fatal("can't build SessionCache, missing conf:SessionCache element?");
1447 throw ConfigurationException("Can't build SessionCache, missing conf:SessionCache element?");
1450 } // end of first-time-only stuff
1452 // Back to the fully dynamic stuff...next up is the RequestMapper.
1453 if (conf.isEnabled(SPConfig::RequestMapping)) {
1454 child=XMLHelper::getFirstChildElement(e,_RequestMapper);
1456 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1457 log.info("building RequestMapper of type %s...",type.get());
1458 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1461 log.fatal("can't build RequestMapper, missing conf:RequestMapper element?");
1462 throw ConfigurationException("Can't build RequestMapper, missing conf:RequestMapper element?");
1467 // Load security policies.
1468 child = XMLHelper::getLastChildElement(e,SecurityPolicies);
1470 PolicyNodeFilter filter;
1471 child = XMLHelper::getFirstChildElement(child,Policy);
1473 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1474 pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];
1476 auto_ptr<DOMPropertySet> settings(new DOMPropertySet());
1477 settings->load(child, NULL, &filter);
1478 rules.first = settings.release();
1480 // Process Rule elements.
1481 const DOMElement* rule = XMLHelper::getFirstChildElement(child,Rule);
1483 auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1485 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1487 catch (exception& ex) {
1488 log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1490 rule = XMLHelper::getNextSiblingElement(rule,Rule);
1493 child = XMLHelper::getNextSiblingElement(child,Policy);
1497 // Process TransportOption elements.
1498 child = XMLHelper::getLastChildElement(e,TransportOption);
1500 if (child->hasChildNodes()) {
1501 auto_ptr_char provider(child->getAttributeNS(NULL,_provider));
1502 auto_ptr_char option(child->getAttributeNS(NULL,_option));
1503 auto_ptr_char value(child->getFirstChild()->getNodeValue());
1504 if (provider.get() && *provider.get() && option.get() && *option.get() && value.get() && *value.get()) {
1505 m_transportOptions.push_back(make_pair(string(provider.get()), make_pair(string(option.get()), string(value.get()))));
1508 child = XMLHelper::getPreviousSiblingElement(child,TransportOption);
1512 // Load the default application. This actually has a fixed ID of "default". ;-)
1513 child=XMLHelper::getLastChildElement(e,ApplicationDefaults);
1515 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
1516 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
1518 XMLApplication* defapp=new XMLApplication(m_outer,child);
1519 m_appmap[defapp->getId()]=defapp;
1521 // Load any overrides.
1522 child = XMLHelper::getFirstChildElement(child,ApplicationOverride);
1524 auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1525 if (m_appmap.count(iapp->getId()))
1526 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
1528 const char* iappid=iapp->getId();
1529 m_appmap[iappid]=iapp.release();
1532 child = XMLHelper::getNextSiblingElement(child,ApplicationOverride);
1535 catch (exception&) {
1541 XMLConfigImpl::~XMLConfigImpl()
1546 void XMLConfigImpl::cleanup()
1548 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
1551 for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {
1552 delete i->second.first;
1553 for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());
1555 m_policyMap.clear();
1557 delete m_requestMapper;
1558 m_requestMapper = NULL;
1560 m_document->release();
1565 void XMLConfig::receive(DDF& in, ostream& out)
1567 if (!strcmp(in.name(), "get::RelayState")) {
1568 const char* id = in["id"].string();
1569 const char* key = in["key"].string();
1571 throw ListenerException("Required parameters missing for RelayState recovery.");
1574 StorageService* storage = getStorageService(id);
1576 if (storage->readString("RelayState",key,&relayState)>0) {
1577 if (in["clear"].integer())
1578 storage->deleteString("RelayState",key);
1582 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1583 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1587 // Repack for return to caller.
1588 DDF ret=DDF(NULL).string(relayState.c_str());
1589 DDFJanitor jret(ret);
1592 else if (!strcmp(in.name(), "set::RelayState")) {
1593 const char* id = in["id"].string();
1594 const char* value = in["value"].string();
1596 throw ListenerException("Required parameters missing for RelayState creation.");
1599 StorageService* storage = getStorageService(id);
1601 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1602 rsKey = SAMLArtifact::toHex(rsKey);
1603 storage->createString("RelayState", rsKey.c_str(), value, time(NULL) + 600);
1606 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1607 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1611 // Repack for return to caller.
1612 DDF ret=DDF(NULL).string(rsKey.c_str());
1613 DDFJanitor jret(ret);
1619 pair<bool,DOMElement*> XMLConfig::load()
1621 // Load from source using base class.
1622 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1624 // If we own it, wrap it.
1625 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1627 XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this,m_log);
1629 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1630 impl->setDocument(docjanitor.release());
1635 return make_pair(false,(DOMElement*)NULL);