2 * Copyright 2001-2009 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/TemplateEngine.h>
51 #include <xmltooling/util/XMLHelper.h>
54 # include "TransactionLog.h"
55 # include "attribute/filtering/AttributeFilter.h"
56 # include "attribute/resolver/AttributeExtractor.h"
57 # include "attribute/resolver/AttributeResolver.h"
58 # include "security/PKIXTrustEngine.h"
59 # include <saml/SAMLConfig.h>
60 # include <saml/version.h>
61 # include <saml/binding/ArtifactMap.h>
62 # include <saml/binding/SAMLArtifact.h>
63 # include <saml/saml1/core/Assertions.h>
64 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
65 # include <saml/saml2/metadata/ChainingMetadataProvider.h>
66 # include <xmltooling/security/ChainingTrustEngine.h>
67 # include <xmltooling/util/ReplayCache.h>
68 using namespace opensaml::saml2;
69 using namespace opensaml::saml2p;
70 using namespace opensaml::saml2md;
71 using namespace opensaml;
74 using namespace shibsp;
75 using namespace xmltooling;
79 # define min(a,b) (((a) < (b)) ? (a) : (b))
84 #if defined (_MSC_VER)
85 #pragma warning( push )
86 #pragma warning( disable : 4250 )
89 static vector<const Handler*> g_noHandlers;
91 // Application configuration wrapper
92 class SHIBSP_DLLLOCAL XMLApplication : public Application, public Remoted, public DOMPropertySet, public DOMNodeFilter
95 XMLApplication(const ServiceProvider*, const DOMElement* e, const XMLApplication* base=NULL);
96 ~XMLApplication() { cleanup(); }
98 const char* getHash() const {return m_hash.c_str();}
101 SAMLArtifact* generateSAML1Artifact(const EntityDescriptor* relyingParty) const {
102 throw ConfigurationException("No support for SAML 1.x artifact generation.");
104 SAML2Artifact* generateSAML2Artifact(const EntityDescriptor* relyingParty) const {
105 pair<bool,int> index = make_pair(false,0);
106 const PropertySet* props = getRelyingParty(relyingParty);
107 index = props->getInt("artifactEndpointIndex");
109 index = getArtifactEndpointIndex();
110 return new SAML2ArtifactType0004(SAMLConfig::getConfig().hashSHA1(props->getString("entityID").second),index.first ? index.second : 1);
113 MetadataProvider* getMetadataProvider(bool required=true) const {
114 if (required && !m_base && !m_metadata)
115 throw ConfigurationException("No MetadataProvider available.");
116 return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
118 TrustEngine* getTrustEngine(bool required=true) const {
119 if (required && !m_base && !m_trust)
120 throw ConfigurationException("No TrustEngine available.");
121 return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
123 AttributeExtractor* getAttributeExtractor() const {
124 return (!m_attrExtractor && m_base) ? m_base->getAttributeExtractor() : m_attrExtractor;
126 AttributeFilter* getAttributeFilter() const {
127 return (!m_attrFilter && m_base) ? m_base->getAttributeFilter() : m_attrFilter;
129 AttributeResolver* getAttributeResolver() const {
130 return (!m_attrResolver && m_base) ? m_base->getAttributeResolver() : m_attrResolver;
132 CredentialResolver* getCredentialResolver() const {
133 return (!m_credResolver && m_base) ? m_base->getCredentialResolver() : m_credResolver;
135 const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
136 const PropertySet* getRelyingParty(const XMLCh* entityID) const;
137 const vector<const XMLCh*>* getAudiences() const {
138 return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
141 string getNotificationURL(const char* resource, bool front, unsigned int index) const;
143 const vector<string>& getRemoteUserAttributeIds() const {
144 return (m_remoteUsers.empty() && m_base) ? m_base->getRemoteUserAttributeIds() : m_remoteUsers;
147 void clearHeader(SPRequest& request, const char* rawname, const char* cginame) const;
148 void setHeader(SPRequest& request, const char* name, const char* value) const;
149 string getSecureHeader(const SPRequest& request, const char* name) const;
151 const SessionInitiator* getDefaultSessionInitiator() const;
152 const SessionInitiator* getSessionInitiatorById(const char* id) const;
153 const Handler* getDefaultAssertionConsumerService() const;
154 const Handler* getAssertionConsumerServiceByIndex(unsigned short index) const;
155 const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
156 const Handler* getHandler(const char* path) const;
157 void getHandlers(vector<const Handler*>& handlers) const;
159 void receive(DDF& in, ostream& out) {
160 // Only current function is to return the headers to clear.
162 DDF ret=DDF(NULL).list();
163 DDFJanitor jret(ret);
164 for (vector< pair<string,string> >::const_iterator i = m_unsetHeaders.begin(); i!=m_unsetHeaders.end(); ++i) {
165 header = DDF(i->first.c_str()).string(i->second.c_str());
171 // Provides filter to exclude special config elements.
172 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
177 acceptNode(const DOMNode* node) const;
181 const XMLApplication* m_base;
183 std::pair<std::string,std::string> m_attributePrefix;
185 MetadataProvider* m_metadata;
186 TrustEngine* m_trust;
187 AttributeExtractor* m_attrExtractor;
188 AttributeFilter* m_attrFilter;
189 AttributeResolver* m_attrResolver;
190 CredentialResolver* m_credResolver;
191 vector<const XMLCh*> m_audiences;
193 // RelyingParty properties
195 map<xstring,PropertySet*> m_partyMap;
197 map<const XMLCh*,PropertySet*> m_partyMap;
200 vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
202 // manage handler objects
203 vector<Handler*> m_handlers;
205 // maps location (path info) to applicable handlers
206 map<string,const Handler*> m_handlerMap;
208 // maps unique indexes to consumer services
209 map<unsigned int,const Handler*> m_acsIndexMap;
211 // pointer to default consumer service
212 const Handler* m_acsDefault;
214 // maps binding strings to supporting consumer service(s)
216 typedef map<xstring,vector<const Handler*> > ACSBindingMap;
218 typedef map<string,vector<const Handler*> > ACSBindingMap;
220 ACSBindingMap m_acsBindingMap;
222 // pointer to default session initiator
223 const SessionInitiator* m_sessionInitDefault;
225 // maps unique ID strings to session initiators
226 map<string,const SessionInitiator*> m_sessionInitMap;
228 // pointer to default artifact resolution service
229 const Handler* m_artifactResolutionDefault;
231 pair<bool,int> getArtifactEndpointIndex() const {
232 if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
233 return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
237 // Top-level configuration implementation
238 class SHIBSP_DLLLOCAL XMLConfig;
239 class SHIBSP_DLLLOCAL XMLConfigImpl : public DOMPropertySet, public DOMNodeFilter
242 XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log);
245 RequestMapper* m_requestMapper;
246 map<string,Application*> m_appmap;
248 map< string,pair< PropertySet*,vector<const SecurityPolicyRule*> > > m_policyMap;
249 vector< pair< string, pair<string,string> > > m_transportOptions;
252 // Provides filter to exclude special config elements.
253 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
258 acceptNode(const DOMNode* node) const;
260 void setDocument(DOMDocument* doc) {
265 void doExtensions(const DOMElement* e, const char* label, Category& log);
268 const XMLConfig* m_outer;
269 DOMDocument* m_document;
272 class SHIBSP_DLLLOCAL XMLConfig : public ServiceProvider, public ReloadableXMLFile
278 XMLConfig(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".Config")),
279 m_impl(NULL), m_listener(NULL), m_sessionCache(NULL)
292 delete m_sessionCache;
296 SAMLConfig::getConfig().setArtifactMap(NULL);
297 XMLToolingConfig::getConfig().setReplayCache(NULL);
298 for_each(m_storage.begin(), m_storage.end(), cleanup_pair<string,StorageService>());
303 const PropertySet* getParent() const { return m_impl->getParent(); }
304 void setParent(const PropertySet* parent) {return m_impl->setParent(parent);}
305 pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return m_impl->getBool(name,ns);}
306 pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return m_impl->getString(name,ns);}
307 pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return m_impl->getXMLString(name,ns);}
308 pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return m_impl->getUnsignedInt(name,ns);}
309 pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return m_impl->getInt(name,ns);}
310 void getAll(map<string,const char*>& properties) const {return m_impl->getAll(properties);}
311 const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:2.0:native:sp:config") const {return m_impl->getPropertySet(name,ns);}
312 const DOMElement* getElement() const {return m_impl->getElement();}
317 void receive(DDF& in, ostream& out);
319 TransactionLog* getTransactionLog() const {
322 throw ConfigurationException("No TransactionLog available.");
325 StorageService* getStorageService(const char* id) const {
327 map<string,StorageService*>::const_iterator i=m_storage.find(id);
328 if (i!=m_storage.end())
335 ListenerService* getListenerService(bool required=true) const {
336 if (required && !m_listener)
337 throw ConfigurationException("No ListenerService available.");
341 SessionCache* getSessionCache(bool required=true) const {
342 if (required && !m_sessionCache)
343 throw ConfigurationException("No SessionCache available.");
344 return m_sessionCache;
347 RequestMapper* getRequestMapper(bool required=true) const {
348 if (required && !m_impl->m_requestMapper)
349 throw ConfigurationException("No RequestMapper available.");
350 return m_impl->m_requestMapper;
353 const Application* getApplication(const char* applicationId) const {
354 map<string,Application*>::const_iterator i=m_impl->m_appmap.find(applicationId);
355 return (i!=m_impl->m_appmap.end()) ? i->second : NULL;
359 const PropertySet* getPolicySettings(const char* id) const {
360 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
361 if (i!=m_impl->m_policyMap.end())
362 return i->second.first;
363 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
366 const vector<const SecurityPolicyRule*>& getPolicyRules(const char* id) const {
367 map<string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::const_iterator i = m_impl->m_policyMap.find(id);
368 if (i!=m_impl->m_policyMap.end())
369 return i->second.second;
370 throw ConfigurationException("Security Policy ($1) not found, check <SecurityPolicies> element.", params(1,id));
373 bool setTransportOptions(SOAPTransport& transport) const {
375 vector< pair< string, pair<string,string> > >::const_iterator opt;
376 for (opt = m_impl->m_transportOptions.begin(); opt != m_impl->m_transportOptions.end(); ++opt) {
377 if (!transport.setProviderOption(opt->first.c_str(), opt->second.first.c_str(), opt->second.second.c_str())) {
378 m_log.error("failed to set SOAPTransport option (%s)", opt->second.first.c_str());
387 pair<bool,DOMElement*> load();
390 friend class XMLConfigImpl;
391 XMLConfigImpl* m_impl;
392 mutable ListenerService* m_listener;
393 mutable SessionCache* m_sessionCache;
395 mutable TransactionLog* m_tranLog;
396 mutable map<string,StorageService*> m_storage;
400 #if defined (_MSC_VER)
401 #pragma warning( pop )
404 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);
405 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);
406 static const XMLCh _ArtifactMap[] = UNICODE_LITERAL_11(A,r,t,i,f,a,c,t,M,a,p);
407 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);
408 static const XMLCh _AttributeFilter[] = UNICODE_LITERAL_15(A,t,t,r,i,b,u,t,e,F,i,l,t,e,r);
409 static const XMLCh _AttributeResolver[] = UNICODE_LITERAL_17(A,t,t,r,i,b,u,t,e,R,e,s,o,l,v,e,r);
410 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);
411 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);
412 static const XMLCh _Audience[] = UNICODE_LITERAL_8(A,u,d,i,e,n,c,e);
413 static const XMLCh Binding[] = UNICODE_LITERAL_7(B,i,n,d,i,n,g);
414 static const XMLCh Channel[]= UNICODE_LITERAL_7(C,h,a,n,n,e,l);
415 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);
416 static const XMLCh _Extensions[] = UNICODE_LITERAL_10(E,x,t,e,n,s,i,o,n,s);
417 static const XMLCh _fatal[] = UNICODE_LITERAL_5(f,a,t,a,l);
418 static const XMLCh _Handler[] = UNICODE_LITERAL_7(H,a,n,d,l,e,r);
419 static const XMLCh _id[] = UNICODE_LITERAL_2(i,d);
420 static const XMLCh InProcess[] = UNICODE_LITERAL_9(I,n,P,r,o,c,e,s,s);
421 static const XMLCh Library[] = UNICODE_LITERAL_7(L,i,b,r,a,r,y);
422 static const XMLCh Listener[] = UNICODE_LITERAL_8(L,i,s,t,e,n,e,r);
423 static const XMLCh Location[] = UNICODE_LITERAL_8(L,o,c,a,t,i,o,n);
424 static const XMLCh logger[] = UNICODE_LITERAL_6(l,o,g,g,e,r);
425 static const XMLCh _LogoutInitiator[] = UNICODE_LITERAL_15(L,o,g,o,u,t,I,n,i,t,i,a,t,o,r);
426 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);
427 static const XMLCh _MetadataProvider[] = UNICODE_LITERAL_16(M,e,t,a,d,a,t,a,P,r,o,v,i,d,e,r);
428 static const XMLCh Notify[] = UNICODE_LITERAL_6(N,o,t,i,f,y);
429 static const XMLCh _option[] = UNICODE_LITERAL_6(o,p,t,i,o,n);
430 static const XMLCh OutOfProcess[] = UNICODE_LITERAL_12(O,u,t,O,f,P,r,o,c,e,s,s);
431 static const XMLCh _path[] = UNICODE_LITERAL_4(p,a,t,h);
432 static const XMLCh Policy[] = UNICODE_LITERAL_6(P,o,l,i,c,y);
433 static const XMLCh PolicyRule[] = UNICODE_LITERAL_10(P,o,l,i,c,y,R,u,l,e);
434 static const XMLCh _provider[] = UNICODE_LITERAL_8(p,r,o,v,i,d,e,r);
435 static const XMLCh RelyingParty[] = UNICODE_LITERAL_12(R,e,l,y,i,n,g,P,a,r,t,y);
436 static const XMLCh _ReplayCache[] = UNICODE_LITERAL_11(R,e,p,l,a,y,C,a,c,h,e);
437 static const XMLCh _RequestMapper[] = UNICODE_LITERAL_13(R,e,q,u,e,s,t,M,a,p,p,e,r);
438 static const XMLCh Rule[] = UNICODE_LITERAL_4(R,u,l,e);
439 static const XMLCh SecurityPolicies[] = UNICODE_LITERAL_16(S,e,c,u,r,i,t,y,P,o,l,i,c,i,e,s);
440 static const XMLCh _SessionCache[] = UNICODE_LITERAL_12(S,e,s,s,i,o,n,C,a,c,h,e);
441 static const XMLCh _SessionInitiator[] = UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
442 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);
443 static const XMLCh Site[] = UNICODE_LITERAL_4(S,i,t,e);
444 static const XMLCh _StorageService[] = UNICODE_LITERAL_14(S,t,o,r,a,g,e,S,e,r,v,i,c,e);
445 static const XMLCh TCPListener[] = UNICODE_LITERAL_11(T,C,P,L,i,s,t,e,n,e,r);
446 static const XMLCh TransportOption[] = UNICODE_LITERAL_15(T,r,a,n,s,p,o,r,t,O,p,t,i,o,n);
447 static const XMLCh _TrustEngine[] = UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
448 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
449 static const XMLCh UnixListener[] = UNICODE_LITERAL_12(U,n,i,x,L,i,s,t,e,n,e,r);
452 class SHIBSP_DLLLOCAL PolicyNodeFilter : public DOMNodeFilter
455 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
460 acceptNode(const DOMNode* node) const {
461 return FILTER_REJECT;
468 ServiceProvider* XMLServiceProviderFactory(const DOMElement* const & e)
470 return new XMLConfig(e);
474 XMLApplication::XMLApplication(
475 const ServiceProvider* sp,
477 const XMLApplication* base
478 ) : Application(sp), m_base(base),
480 m_metadata(NULL), m_trust(NULL),
481 m_attrExtractor(NULL), m_attrFilter(NULL), m_attrResolver(NULL),
482 m_credResolver(NULL),
484 m_acsDefault(NULL), m_sessionInitDefault(NULL), m_artifactResolutionDefault(NULL)
487 xmltooling::NDC ndc("XMLApplication");
489 Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
492 // First load any property sets.
497 SPConfig& conf=SPConfig::getConfig();
499 SAMLConfig& samlConf=SAMLConfig::getConfig();
500 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
503 // This used to be an actual hash, but now it's just a hex-encode to avoid xmlsec.
504 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
505 string tohash=getId();
506 tohash+=getString("entityID").second;
507 for (const char* ch = tohash.c_str(); *ch; ++ch) {
508 m_hash += (DIGITS[((unsigned char)(0xF0 & *ch)) >> 4 ]);
509 m_hash += (DIGITS[0x0F & *ch]);
512 // Populate prefix pair.
513 m_attributePrefix.second = "HTTP_";
514 pair<bool,const char*> prefix = getString("attributePrefix");
516 m_attributePrefix.first = prefix.second;
517 const char* pch = prefix.second;
519 m_attributePrefix.second += (isalnum(*pch) ? toupper(*pch) : '_');
524 // Load attribute ID lists for REMOTE_USER and header clearing.
525 if (conf.isEnabled(SPConfig::InProcess)) {
526 pair<bool,const char*> attributes = getString("REMOTE_USER");
527 if (attributes.first) {
528 char* dup = strdup(attributes.second);
531 while (start && *start) {
532 while (*start && isspace(*start))
536 pos = strchr(start,' ');
539 m_remoteUsers.push_back(start);
540 start = pos ? pos+1 : NULL;
545 attributes = getString("unsetHeaders");
546 if (attributes.first) {
547 string transformedprefix(m_attributePrefix.second);
549 prefix = getString("metadataAttributePrefix");
553 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
557 char* dup = strdup(attributes.second);
560 while (start && *start) {
561 while (*start && isspace(*start))
565 pos = strchr(start,' ');
572 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
576 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + start, m_attributePrefix.second + transformed));
578 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + start, transformedprefix + transformed));
579 start = pos ? pos+1 : NULL;
582 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
586 Handler* handler=NULL;
587 const PropertySet* sessions = getPropertySet("Sessions");
589 // Process assertion export handler.
590 pair<bool,const char*> location = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
591 if (location.first) {
593 DOMElement* exportElement = e->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS,_Handler);
594 exportElement->setAttributeNS(NULL,Location,sessions->getXMLString("exportLocation").second);
595 pair<bool,const XMLCh*> exportACL = sessions->getXMLString("exportACL");
596 if (exportACL.first) {
597 static const XMLCh _acl[] = UNICODE_LITERAL_9(e,x,p,o,r,t,A,C,L);
598 exportElement->setAttributeNS(NULL,_acl,exportACL.second);
600 handler = conf.HandlerManager.newPlugin(
601 samlconstants::SAML20_BINDING_URI, pair<const DOMElement*,const char*>(exportElement, getId())
603 m_handlers.push_back(handler);
605 // Insert into location map. If it contains the handlerURL, we skip past that part.
606 const char* pch = strstr(location.second, sessions->getString("handlerURL").second);
608 location.second = pch + strlen(sessions->getString("handlerURL").second);
609 if (*location.second == '/')
610 m_handlerMap[location.second]=handler;
612 m_handlerMap[string("/") + location.second]=handler;
614 catch (exception& ex) {
615 log.error("caught exception installing assertion lookup handler: %s", ex.what());
619 // Process other handlers.
620 bool hardACS=false, hardSessionInit=false, hardArt=false;
621 const DOMElement* child = sessions ? XMLHelper::getFirstChildElement(sessions->getElement()) : NULL;
624 // A handler is based on the Binding property in conjunction with the element name.
625 // If it's an ACS or SI, also handle index/id mappings and defaulting.
626 if (XMLString::equals(child->getLocalName(),_AssertionConsumerService)) {
627 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
628 if (!bindprop.get() || !*(bindprop.get())) {
629 log.warn("md:AssertionConsumerService element has no Binding attribute, skipping it...");
630 child = XMLHelper::getNextSiblingElement(child);
633 handler=conf.AssertionConsumerServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
634 // Map by binding (may be > 1 per binding, e.g. SAML 1.0 vs 1.1)
636 m_acsBindingMap[handler->getXMLString("Binding").second].push_back(handler);
638 m_acsBindingMap[handler->getString("Binding").second].push_back(handler);
640 m_acsIndexMap[handler->getUnsignedInt("index").second]=handler;
643 pair<bool,bool> defprop=handler->getBool("isDefault");
645 if (defprop.second) {
647 m_acsDefault=handler;
650 else if (!m_acsDefault)
651 m_acsDefault=handler;
654 else if (XMLString::equals(child->getLocalName(),_SessionInitiator)) {
655 auto_ptr_char type(child->getAttributeNS(NULL,_type));
656 if (!type.get() || !*(type.get())) {
657 log.warn("SessionInitiator element has no type attribute, skipping it...");
658 child = XMLHelper::getNextSiblingElement(child);
661 SessionInitiator* sihandler=conf.SessionInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
663 pair<bool,const char*> si_id=handler->getString("id");
664 if (si_id.first && si_id.second)
665 m_sessionInitMap[si_id.second]=sihandler;
666 if (!hardSessionInit) {
667 pair<bool,bool> defprop=handler->getBool("isDefault");
669 if (defprop.second) {
670 hardSessionInit=true;
671 m_sessionInitDefault=sihandler;
674 else if (!m_sessionInitDefault)
675 m_sessionInitDefault=sihandler;
678 else if (XMLString::equals(child->getLocalName(),_LogoutInitiator)) {
679 auto_ptr_char type(child->getAttributeNS(NULL,_type));
680 if (!type.get() || !*(type.get())) {
681 log.warn("LogoutInitiator element has no type attribute, skipping it...");
682 child = XMLHelper::getNextSiblingElement(child);
685 handler=conf.LogoutInitiatorManager.newPlugin(type.get(),make_pair(child, getId()));
687 else if (XMLString::equals(child->getLocalName(),_ArtifactResolutionService)) {
688 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
689 if (!bindprop.get() || !*(bindprop.get())) {
690 log.warn("md:ArtifactResolutionService element has no Binding attribute, skipping it...");
691 child = XMLHelper::getNextSiblingElement(child);
694 handler=conf.ArtifactResolutionServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
697 pair<bool,bool> defprop=handler->getBool("isDefault");
699 if (defprop.second) {
701 m_artifactResolutionDefault=handler;
704 else if (!m_artifactResolutionDefault)
705 m_artifactResolutionDefault=handler;
708 else if (XMLString::equals(child->getLocalName(),_SingleLogoutService)) {
709 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
710 if (!bindprop.get() || !*(bindprop.get())) {
711 log.warn("md:SingleLogoutService element has no Binding attribute, skipping it...");
712 child = XMLHelper::getNextSiblingElement(child);
715 handler=conf.SingleLogoutServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
717 else if (XMLString::equals(child->getLocalName(),_ManageNameIDService)) {
718 auto_ptr_char bindprop(child->getAttributeNS(NULL,Binding));
719 if (!bindprop.get() || !*(bindprop.get())) {
720 log.warn("md:ManageNameIDService element has no Binding attribute, skipping it...");
721 child = XMLHelper::getNextSiblingElement(child);
724 handler=conf.ManageNameIDServiceManager.newPlugin(bindprop.get(),make_pair(child, getId()));
727 auto_ptr_char type(child->getAttributeNS(NULL,_type));
728 if (!type.get() || !*(type.get())) {
729 log.warn("Handler element has no type attribute, skipping it...");
730 child = XMLHelper::getNextSiblingElement(child);
733 handler=conf.HandlerManager.newPlugin(type.get(),make_pair(child, getId()));
736 m_handlers.push_back(handler);
738 // Insert into location map.
739 location=handler->getString("Location");
740 if (location.first && *location.second == '/')
741 m_handlerMap[location.second]=handler;
742 else if (location.first)
743 m_handlerMap[string("/") + location.second]=handler;
746 catch (exception& ex) {
747 log.error("caught exception processing handler element: %s", ex.what());
750 child = XMLHelper::getNextSiblingElement(child);
754 DOMNodeList* nlist=e->getElementsByTagNameNS(shibspconstants::SHIB2SPCONFIG_NS,Notify);
755 for (XMLSize_t i=0; nlist && i<nlist->getLength(); i++) {
756 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
757 const XMLCh* channel = static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Channel);
758 auto_ptr_char loc(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,Location));
759 if (loc.get() && *loc.get()) {
760 if (channel && *channel == chLatin_f)
761 m_frontLogout.push_back(loc.get());
763 m_backLogout.push_back(loc.get());
769 nlist=e->getElementsByTagNameNS(samlconstants::SAML20_NS,Audience::LOCAL_NAME);
770 if (nlist && nlist->getLength()) {
771 log.warn("use of <saml:Audience> elements outside of a Security Policy Rule is deprecated");
772 for (XMLSize_t i=0; i<nlist->getLength(); i++)
773 if (nlist->item(i)->getParentNode()->isSameNode(e) && nlist->item(i)->hasChildNodes())
774 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
777 if (conf.isEnabled(SPConfig::Metadata)) {
778 child = XMLHelper::getFirstChildElement(e,_MetadataProvider);
780 auto_ptr_char type(child->getAttributeNS(NULL,_type));
781 log.info("building MetadataProvider of type %s...",type.get());
783 auto_ptr<MetadataProvider> mp(samlConf.MetadataProviderManager.newPlugin(type.get(),child));
785 m_metadata = mp.release();
787 catch (exception& ex) {
788 log.crit("error building/initializing MetadataProvider: %s", ex.what());
793 if (conf.isEnabled(SPConfig::Trust)) {
794 child = XMLHelper::getFirstChildElement(e,_TrustEngine);
796 auto_ptr_char type(child->getAttributeNS(NULL,_type));
797 log.info("building TrustEngine of type %s...",type.get());
799 m_trust = xmlConf.TrustEngineManager.newPlugin(type.get(),child);
801 catch (exception& ex) {
802 log.crit("error building TrustEngine: %s", ex.what());
807 if (conf.isEnabled(SPConfig::AttributeResolution)) {
808 child = XMLHelper::getFirstChildElement(e,_AttributeExtractor);
810 auto_ptr_char type(child->getAttributeNS(NULL,_type));
811 log.info("building AttributeExtractor of type %s...",type.get());
813 m_attrExtractor = conf.AttributeExtractorManager.newPlugin(type.get(),child);
815 catch (exception& ex) {
816 log.crit("error building AttributeExtractor: %s", ex.what());
820 child = XMLHelper::getFirstChildElement(e,_AttributeFilter);
822 auto_ptr_char type(child->getAttributeNS(NULL,_type));
823 log.info("building AttributeFilter of type %s...",type.get());
825 m_attrFilter = conf.AttributeFilterManager.newPlugin(type.get(),child);
827 catch (exception& ex) {
828 log.crit("error building AttributeFilter: %s", ex.what());
832 child = XMLHelper::getFirstChildElement(e,_AttributeResolver);
834 auto_ptr_char type(child->getAttributeNS(NULL,_type));
835 log.info("building AttributeResolver of type %s...",type.get());
837 m_attrResolver = conf.AttributeResolverManager.newPlugin(type.get(),child);
839 catch (exception& ex) {
840 log.crit("error building AttributeResolver: %s", ex.what());
844 if (m_unsetHeaders.empty()) {
845 vector<string> unsetHeaders;
846 if (m_attrExtractor) {
847 Locker extlock(m_attrExtractor);
848 m_attrExtractor->getAttributeIds(unsetHeaders);
850 else if (m_base && m_base->m_attrExtractor) {
851 Locker extlock(m_base->m_attrExtractor);
852 m_base->m_attrExtractor->getAttributeIds(unsetHeaders);
854 if (m_attrResolver) {
855 Locker reslock(m_attrResolver);
856 m_attrResolver->getAttributeIds(unsetHeaders);
858 else if (m_base && m_base->m_attrResolver) {
859 Locker extlock(m_base->m_attrResolver);
860 m_base->m_attrResolver->getAttributeIds(unsetHeaders);
862 if (!unsetHeaders.empty()) {
863 string transformedprefix(m_attributePrefix.second);
865 pair<bool,const char*> prefix = getString("metadataAttributePrefix");
869 transformedprefix += (isalnum(*pch) ? toupper(*pch) : '_');
873 for (vector<string>::const_iterator hdr = unsetHeaders.begin(); hdr!=unsetHeaders.end(); ++hdr) {
877 transformed += (isalnum(*pch) ? toupper(*pch) : '_');
880 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + *hdr, m_attributePrefix.second + transformed));
882 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + prefix.second + *hdr, transformedprefix + transformed));
885 m_unsetHeaders.push_back(pair<string,string>(m_attributePrefix.first + "Shib-Application-ID", m_attributePrefix.second + "SHIB_APPLICATION_ID"));
889 if (conf.isEnabled(SPConfig::Credentials)) {
890 child = XMLHelper::getFirstChildElement(e,_CredentialResolver);
892 auto_ptr_char type(child->getAttributeNS(NULL,_type));
893 log.info("building CredentialResolver of type %s...",type.get());
895 m_credResolver = xmlConf.CredentialResolverManager.newPlugin(type.get(),child);
897 catch (exception& ex) {
898 log.crit("error building CredentialResolver: %s", ex.what());
903 // Finally, load relying parties.
904 child = XMLHelper::getFirstChildElement(e,RelyingParty);
906 auto_ptr<DOMPropertySet> rp(new DOMPropertySet());
907 rp->load(child,NULL,this);
909 m_partyMap[child->getAttributeNS(NULL,saml2::Attribute::NAME_ATTRIB_NAME)]=rp.release();
910 child = XMLHelper::getNextSiblingElement(child,RelyingParty);
914 // Out of process only, we register a listener endpoint.
915 if (!conf.isEnabled(SPConfig::InProcess)) {
916 ListenerService* listener = sp->getListenerService(false);
918 string addr=string(getId()) + "::getHeaders::Application";
919 listener->regListener(addr.c_str(),this);
922 log.info("no ListenerService available, Application remoting disabled");
937 void XMLApplication::cleanup()
939 ListenerService* listener=getServiceProvider().getListenerService(false);
940 if (listener && SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess) && !SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
941 string addr=string(getId()) + "::getHeaders::Application";
942 listener->unregListener(addr.c_str(),this);
944 for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<Handler>());
948 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<xstring,PropertySet>());
950 for_each(m_partyMap.begin(),m_partyMap.end(),cleanup_pair<const XMLCh*,PropertySet>());
953 delete m_credResolver;
954 m_credResolver = NULL;
955 delete m_attrResolver;
956 m_attrResolver = NULL;
959 delete m_attrExtractor;
960 m_attrExtractor = NULL;
968 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
971 DOMNodeFilter::FilterAction
973 XMLApplication::acceptNode(const DOMNode* node) const
975 const XMLCh* name=node->getLocalName();
976 if (XMLString::equals(name,ApplicationOverride) ||
977 XMLString::equals(name,_Audience) ||
978 XMLString::equals(name,Notify) ||
979 XMLString::equals(name,_Handler) ||
980 XMLString::equals(name,_AssertionConsumerService) ||
981 XMLString::equals(name,_ArtifactResolutionService) ||
982 XMLString::equals(name,_LogoutInitiator) ||
983 XMLString::equals(name,_ManageNameIDService) ||
984 XMLString::equals(name,_SessionInitiator) ||
985 XMLString::equals(name,_SingleLogoutService) ||
986 XMLString::equals(name,RelyingParty) ||
987 XMLString::equals(name,_MetadataProvider) ||
988 XMLString::equals(name,_TrustEngine) ||
989 XMLString::equals(name,_CredentialResolver) ||
990 XMLString::equals(name,_AttributeFilter) ||
991 XMLString::equals(name,_AttributeExtractor) ||
992 XMLString::equals(name,_AttributeResolver))
993 return FILTER_REJECT;
995 return FILTER_ACCEPT;
1000 const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provider) const
1005 #ifdef HAVE_GOOD_STL
1006 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(provider->getEntityID());
1007 if (i!=m_partyMap.end())
1009 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1011 if (group->getName()) {
1012 i=m_partyMap.find(group->getName());
1013 if (i!=m_partyMap.end())
1016 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1019 map<const XMLCh*,PropertySet*>::const_iterator i=m_partyMap.begin();
1020 for (; i!=m_partyMap.end(); i++) {
1021 if (XMLString::equals(i->first,provider->getEntityID()))
1023 const EntitiesDescriptor* group=dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
1025 if (XMLString::equals(i->first,group->getName()))
1027 group=dynamic_cast<const EntitiesDescriptor*>(group->getParent());
1034 const PropertySet* XMLApplication::getRelyingParty(const XMLCh* entityID) const
1039 #ifdef HAVE_GOOD_STL
1040 map<xstring,PropertySet*>::const_iterator i=m_partyMap.find(entityID);
1041 if (i!=m_partyMap.end())
1044 map<const XMLCh*,PropertySet*>::const_iterator i=m_partyMap.begin();
1045 for (; i!=m_partyMap.end(); i++) {
1046 if (XMLString::equals(i->first,entityID))
1055 string XMLApplication::getNotificationURL(const char* resource, bool front, unsigned int index) const
1057 const vector<string>& locs = front ? m_frontLogout : m_backLogout;
1059 return m_base ? m_base->getNotificationURL(resource, front, index) : string();
1060 else if (index >= locs.size())
1063 #ifdef HAVE_STRCASECMP
1064 if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
1066 if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
1068 throw ConfigurationException("Request URL was not absolute.");
1070 const char* handler=locs[index].c_str();
1072 // Should never happen...
1073 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
1074 throw ConfigurationException(
1075 "Invalid Location property ($1) in Notify element for Application ($2)",
1076 params(2, handler ? handler : "null", getId())
1079 // The "Location" property can be in one of three formats:
1081 // 1) a full URI: http://host/foo/bar
1082 // 2) a hostless URI: http:///foo/bar
1083 // 3) a relative path: /foo/bar
1085 // # Protocol Host Path
1086 // 1 handler handler handler
1087 // 2 handler resource handler
1088 // 3 resource resource handler
1090 const char* path = NULL;
1092 // Decide whether to use the handler or the resource for the "protocol"
1094 if (*handler != '/') {
1102 // break apart the "protocol" string into protocol, host, and "the rest"
1103 const char* colon=strchr(prot,':');
1105 const char* slash=strchr(colon,'/');
1109 // Compute the actual protocol and store.
1110 string notifyURL(prot, colon-prot);
1112 // create the "host" from either the colon/slash or from the target string
1113 // If prot == handler then we're in either #1 or #2, else #3.
1114 // If slash == colon then we're in #2.
1115 if (prot != handler || slash == colon) {
1116 colon = strchr(resource, ':');
1117 colon += 3; // Get past the ://
1118 slash = strchr(colon, '/');
1120 string host(colon, (slash ? slash-colon : strlen(colon)));
1123 notifyURL += host + path;
1127 void XMLApplication::clearHeader(SPRequest& request, const char* rawname, const char* cginame) const
1129 if (!m_attributePrefix.first.empty()) {
1130 string temp = m_attributePrefix.first + rawname;
1131 string temp2 = m_attributePrefix.second + (cginame + 5);
1132 request.clearHeader(temp.c_str(), temp2.c_str());
1135 m_base->clearHeader(request, rawname, cginame);
1138 request.clearHeader(rawname, cginame);
1142 void XMLApplication::setHeader(SPRequest& request, const char* name, const char* value) const
1144 if (!m_attributePrefix.first.empty()) {
1145 string temp = m_attributePrefix.first + name;
1146 request.setHeader(temp.c_str(), value);
1149 m_base->setHeader(request, name, value);
1152 request.setHeader(name, value);
1156 string XMLApplication::getSecureHeader(const SPRequest& request, const char* name) const
1158 if (!m_attributePrefix.first.empty()) {
1159 string temp = m_attributePrefix.first + name;
1160 return request.getSecureHeader(temp.c_str());
1163 return m_base->getSecureHeader(request,name);
1166 return request.getSecureHeader(name);
1170 const SessionInitiator* XMLApplication::getDefaultSessionInitiator() const
1172 if (m_sessionInitDefault) return m_sessionInitDefault;
1173 return m_base ? m_base->getDefaultSessionInitiator() : NULL;
1176 const SessionInitiator* XMLApplication::getSessionInitiatorById(const char* id) const
1178 map<string,const SessionInitiator*>::const_iterator i=m_sessionInitMap.find(id);
1179 if (i!=m_sessionInitMap.end()) return i->second;
1180 return m_base ? m_base->getSessionInitiatorById(id) : NULL;
1183 const Handler* XMLApplication::getDefaultAssertionConsumerService() const
1185 if (m_acsDefault) return m_acsDefault;
1186 return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
1189 const Handler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
1191 map<unsigned int,const Handler*>::const_iterator i=m_acsIndexMap.find(index);
1192 if (i!=m_acsIndexMap.end()) return i->second;
1193 return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
1196 const vector<const Handler*>& XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
1198 #ifdef HAVE_GOOD_STL
1199 ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
1201 auto_ptr_char temp(binding);
1202 ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
1204 if (i!=m_acsBindingMap.end())
1206 return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : g_noHandlers;
1209 const Handler* XMLApplication::getHandler(const char* path) const
1212 map<string,const Handler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
1213 if (i!=m_handlerMap.end())
1215 return m_base ? m_base->getHandler(path) : NULL;
1218 void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
1220 handlers.insert(handlers.end(), m_handlers.begin(), m_handlers.end());
1222 for (map<string,const Handler*>::const_iterator h = m_base->m_handlerMap.begin(); h != m_base->m_handlerMap.end(); ++h) {
1223 if (m_handlerMap.count(h->first) == 0)
1224 handlers.push_back(h->second);
1229 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
1232 DOMNodeFilter::FilterAction
1234 XMLConfigImpl::acceptNode(const DOMNode* node) const
1236 if (!XMLString::equals(node->getNamespaceURI(),shibspconstants::SHIB2SPCONFIG_NS))
1237 return FILTER_ACCEPT;
1238 const XMLCh* name=node->getLocalName();
1239 if (XMLString::equals(name,ApplicationDefaults) ||
1240 XMLString::equals(name,_ArtifactMap) ||
1241 XMLString::equals(name,_Extensions) ||
1242 XMLString::equals(name,Listener) ||
1243 XMLString::equals(name,_RequestMapper) ||
1244 XMLString::equals(name,_ReplayCache) ||
1245 XMLString::equals(name,SecurityPolicies) ||
1246 XMLString::equals(name,_SessionCache) ||
1247 XMLString::equals(name,Site) ||
1248 XMLString::equals(name,_StorageService) ||
1249 XMLString::equals(name,TCPListener) ||
1250 XMLString::equals(name,TransportOption) ||
1251 XMLString::equals(name,UnixListener))
1252 return FILTER_REJECT;
1254 return FILTER_ACCEPT;
1257 void XMLConfigImpl::doExtensions(const DOMElement* e, const char* label, Category& log)
1259 const DOMElement* exts=XMLHelper::getFirstChildElement(e,_Extensions);
1261 exts=XMLHelper::getFirstChildElement(exts,Library);
1263 auto_ptr_char path(exts->getAttributeNS(NULL,_path));
1266 if (!XMLToolingConfig::getConfig().load_library(path.get(),(void*)exts))
1267 throw ConfigurationException("XMLToolingConfig::load_library failed.");
1268 log.debug("loaded %s extension library (%s)", label, path.get());
1271 catch (exception& e) {
1272 const XMLCh* fatal=exts->getAttributeNS(NULL,_fatal);
1273 if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
1274 log.fatal("unable to load mandatory %s extension library %s: %s", label, path.get(), e.what());
1278 log.crit("unable to load optional %s extension library %s: %s", label, path.get(), e.what());
1281 exts=XMLHelper::getNextSiblingElement(exts,Library);
1286 XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer, Category& log)
1287 : m_requestMapper(NULL), m_outer(outer), m_document(NULL)
1290 xmltooling::NDC ndc("XMLConfigImpl");
1294 SPConfig& conf=SPConfig::getConfig();
1296 SAMLConfig& samlConf=SAMLConfig::getConfig();
1298 XMLToolingConfig& xmlConf=XMLToolingConfig::getConfig();
1299 const DOMElement* SHAR=XMLHelper::getFirstChildElement(e,OutOfProcess);
1300 const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e,InProcess);
1302 // Initialize log4cpp manually in order to redirect log messages as soon as possible.
1303 if (conf.isEnabled(SPConfig::Logging)) {
1304 const XMLCh* logconf=NULL;
1305 if (conf.isEnabled(SPConfig::OutOfProcess))
1306 logconf=SHAR->getAttributeNS(NULL,logger);
1307 else if (conf.isEnabled(SPConfig::InProcess))
1308 logconf=SHIRE->getAttributeNS(NULL,logger);
1309 if (!logconf || !*logconf)
1310 logconf=e->getAttributeNS(NULL,logger);
1311 if (logconf && *logconf) {
1312 auto_ptr_char logpath(logconf);
1313 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
1314 XMLToolingConfig::getConfig().log_config(logpath.get());
1319 m_outer->m_tranLog = new TransactionLog();
1323 // Re-log library versions now that logging is set up.
1326 "Library versions: Xerces-C %s, XML-Security-C %s, XMLTooling-C %s, OpenSAML-C %s, Shibboleth %s",
1327 XERCES_FULLVERSIONDOT, XSEC_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, OPENSAML_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1331 "Library versions: Xerces-C %s, XMLTooling-C %s, Shibboleth %s",
1332 XERCES_FULLVERSIONDOT, XMLTOOLING_FULLVERSIONDOT, SHIBSP_FULLVERSIONDOT
1336 // First load any property sets.
1339 const DOMElement* child;
1342 // Much of the processing can only occur on the first instantiation.
1345 pair<bool,unsigned int> skew=getUnsignedInt("clockSkew");
1347 xmlConf.clock_skew_secs=min(skew.second,(60*60*24*7*28));
1349 pair<bool,const char*> unsafe = getString("unsafeChars");
1351 TemplateEngine::unsafe_chars = unsafe.second;
1354 doExtensions(e, "global", log);
1355 if (conf.isEnabled(SPConfig::OutOfProcess))
1356 doExtensions(SHAR, "out of process", log);
1358 if (conf.isEnabled(SPConfig::InProcess))
1359 doExtensions(SHIRE, "in process", log);
1361 // Instantiate the ListenerService and SessionCache objects.
1362 if (conf.isEnabled(SPConfig::Listener)) {
1363 child=XMLHelper::getFirstChildElement(e,UnixListener);
1365 plugtype=UNIX_LISTENER_SERVICE;
1367 child=XMLHelper::getFirstChildElement(e,TCPListener);
1369 plugtype=TCP_LISTENER_SERVICE;
1371 child=XMLHelper::getFirstChildElement(e,Listener);
1373 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1375 plugtype=type.get();
1380 log.info("building ListenerService of type %s...", plugtype.c_str());
1381 m_outer->m_listener = conf.ListenerServiceManager.newPlugin(plugtype.c_str(), child);
1384 log.fatal("can't build ListenerService, missing conf:Listener element?");
1385 throw ConfigurationException("Can't build ListenerService, missing conf:Listener element?");
1390 if (m_outer->m_listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
1391 m_outer->m_listener->regListener("set::RelayState", const_cast<XMLConfig*>(m_outer));
1392 m_outer->m_listener->regListener("get::RelayState", const_cast<XMLConfig*>(m_outer));
1393 m_outer->m_listener->regListener("set::PostData", const_cast<XMLConfig*>(m_outer));
1394 m_outer->m_listener->regListener("get::PostData", const_cast<XMLConfig*>(m_outer));
1398 if (conf.isEnabled(SPConfig::Caching)) {
1399 if (conf.isEnabled(SPConfig::OutOfProcess)) {
1401 // First build any StorageServices.
1402 child=XMLHelper::getFirstChildElement(e,_StorageService);
1404 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1405 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1407 log.info("building StorageService (%s) of type %s...", id.get(), type.get());
1408 m_outer->m_storage[id.get()] = xmlConf.StorageServiceManager.newPlugin(type.get(),child);
1410 catch (exception& ex) {
1411 log.crit("failed to instantiate StorageService (%s): %s", id.get(), ex.what());
1413 child=XMLHelper::getNextSiblingElement(child,_StorageService);
1417 StorageService* replaySS=NULL;
1418 child=XMLHelper::getFirstChildElement(e,_ReplayCache);
1420 auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1421 if (ssid.get() && *ssid.get()) {
1422 if (m_outer->m_storage.count(ssid.get()))
1423 replaySS = m_outer->m_storage[ssid.get()];
1425 log.info("building ReplayCache on top of StorageService (%s)...", ssid.get());
1427 log.warn("unable to locate StorageService (%s) for ReplayCache, using dedicated in-memory instance", ssid.get());
1429 xmlConf.setReplayCache(new ReplayCache(replaySS));
1432 log.warn("no ReplayCache built, missing conf:ReplayCache element?");
1436 child=XMLHelper::getFirstChildElement(e,_ArtifactMap);
1438 auto_ptr_char ssid(child->getAttributeNS(NULL,_StorageService));
1439 if (ssid.get() && *ssid.get() && m_outer->m_storage.count(ssid.get())) {
1440 log.info("building ArtifactMap on top of StorageService (%s)...", ssid.get());
1441 samlConf.setArtifactMap(new ArtifactMap(child, m_outer->m_storage[ssid.get()]));
1444 if (samlConf.getArtifactMap()==NULL) {
1445 log.info("building in-memory ArtifactMap...");
1446 samlConf.setArtifactMap(new ArtifactMap(child));
1450 child=XMLHelper::getFirstChildElement(e,_SessionCache);
1452 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1453 log.info("building SessionCache of type %s...",type.get());
1454 m_outer->m_sessionCache=conf.SessionCacheManager.newPlugin(type.get(), child);
1457 log.fatal("can't build SessionCache, missing conf:SessionCache element?");
1458 throw ConfigurationException("Can't build SessionCache, missing conf:SessionCache element?");
1461 } // end of first-time-only stuff
1463 // Back to the fully dynamic stuff...next up is the RequestMapper.
1464 if (conf.isEnabled(SPConfig::RequestMapping)) {
1465 child=XMLHelper::getFirstChildElement(e,_RequestMapper);
1467 auto_ptr_char type(child->getAttributeNS(NULL,_type));
1468 log.info("building RequestMapper of type %s...",type.get());
1469 m_requestMapper=conf.RequestMapperManager.newPlugin(type.get(),child);
1472 log.fatal("can't build RequestMapper, missing conf:RequestMapper element?");
1473 throw ConfigurationException("Can't build RequestMapper, missing conf:RequestMapper element?");
1478 // Load security policies.
1479 child = XMLHelper::getLastChildElement(e,SecurityPolicies);
1481 PolicyNodeFilter filter;
1482 child = XMLHelper::getFirstChildElement(child,Policy);
1484 auto_ptr_char id(child->getAttributeNS(NULL,_id));
1485 pair< PropertySet*,vector<const SecurityPolicyRule*> >& rules = m_policyMap[id.get()];
1487 auto_ptr<DOMPropertySet> settings(new DOMPropertySet());
1488 settings->load(child, NULL, &filter);
1489 rules.first = settings.release();
1491 // Process PolicyRule elements.
1492 const DOMElement* rule = XMLHelper::getFirstChildElement(child,PolicyRule);
1494 auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1496 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1498 catch (exception& ex) {
1499 log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1501 rule = XMLHelper::getNextSiblingElement(rule,PolicyRule);
1504 if (rules.second.size() == 0) {
1505 // Process Rule elements.
1506 log.warn("detected legacy Policy configuration, please convert to new PolicyRule syntax");
1507 rule = XMLHelper::getFirstChildElement(child,Rule);
1509 auto_ptr_char type(rule->getAttributeNS(NULL,_type));
1511 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(type.get(),rule));
1513 catch (exception& ex) {
1514 log.crit("error instantiating policy rule (%s) in policy (%s): %s", type.get(), id.get(), ex.what());
1516 rule = XMLHelper::getNextSiblingElement(rule,Rule);
1519 // Manually add a basic Conditions rule.
1520 log.info("installing a default Conditions rule in policy (%s) for compatibility with legacy configuration", id.get());
1521 rules.second.push_back(samlConf.SecurityPolicyRuleManager.newPlugin(CONDITIONS_POLICY_RULE, NULL));
1524 child = XMLHelper::getNextSiblingElement(child,Policy);
1528 // Process TransportOption elements.
1529 child = XMLHelper::getLastChildElement(e,TransportOption);
1531 if (child->hasChildNodes()) {
1532 auto_ptr_char provider(child->getAttributeNS(NULL,_provider));
1533 auto_ptr_char option(child->getAttributeNS(NULL,_option));
1534 auto_ptr_char value(child->getFirstChild()->getNodeValue());
1535 if (provider.get() && *provider.get() && option.get() && *option.get() && value.get() && *value.get()) {
1536 m_transportOptions.push_back(make_pair(string(provider.get()), make_pair(string(option.get()), string(value.get()))));
1539 child = XMLHelper::getPreviousSiblingElement(child,TransportOption);
1543 // Load the default application. This actually has a fixed ID of "default". ;-)
1544 child=XMLHelper::getLastChildElement(e,ApplicationDefaults);
1546 log.fatal("can't build default Application object, missing conf:ApplicationDefaults element?");
1547 throw ConfigurationException("can't build default Application object, missing conf:ApplicationDefaults element?");
1549 XMLApplication* defapp=new XMLApplication(m_outer,child);
1550 m_appmap[defapp->getId()]=defapp;
1552 // Load any overrides.
1553 child = XMLHelper::getFirstChildElement(child,ApplicationOverride);
1555 auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,child,defapp));
1556 if (m_appmap.count(iapp->getId()))
1557 log.crit("found conf:ApplicationOverride element with duplicate id attribute (%s), skipping it", iapp->getId());
1559 const char* iappid=iapp->getId();
1560 m_appmap[iappid]=iapp.release();
1563 child = XMLHelper::getNextSiblingElement(child,ApplicationOverride);
1566 catch (exception&) {
1572 XMLConfigImpl::~XMLConfigImpl()
1577 void XMLConfigImpl::cleanup()
1579 for_each(m_appmap.begin(),m_appmap.end(),cleanup_pair<string,Application>());
1582 for (map< string,pair<PropertySet*,vector<const SecurityPolicyRule*> > >::iterator i=m_policyMap.begin(); i!=m_policyMap.end(); ++i) {
1583 delete i->second.first;
1584 for_each(i->second.second.begin(), i->second.second.end(), xmltooling::cleanup<SecurityPolicyRule>());
1586 m_policyMap.clear();
1588 delete m_requestMapper;
1589 m_requestMapper = NULL;
1591 m_document->release();
1596 void XMLConfig::receive(DDF& in, ostream& out)
1598 if (!strcmp(in.name(), "get::RelayState")) {
1599 const char* id = in["id"].string();
1600 const char* key = in["key"].string();
1602 throw ListenerException("Required parameters missing for RelayState recovery.");
1605 StorageService* storage = getStorageService(id);
1607 if (storage->readString("RelayState",key,&relayState)>0) {
1608 if (in["clear"].integer())
1609 storage->deleteString("RelayState",key);
1613 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1614 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1618 // Repack for return to caller.
1619 DDF ret=DDF(NULL).string(relayState.c_str());
1620 DDFJanitor jret(ret);
1623 else if (!strcmp(in.name(), "set::RelayState")) {
1624 const char* id = in["id"].string();
1625 const char* value = in["value"].string();
1627 throw ListenerException("Required parameters missing for RelayState creation.");
1630 StorageService* storage = getStorageService(id);
1632 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1633 rsKey = SAMLArtifact::toHex(rsKey);
1634 storage->createString("RelayState", rsKey.c_str(), value, time(NULL) + 600);
1637 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1638 "Storage-backed RelayState with invalid StorageService ID (%s)", id
1642 // Repack for return to caller.
1643 DDF ret=DDF(NULL).string(rsKey.c_str());
1644 DDFJanitor jret(ret);
1647 else if (!strcmp(in.name(), "get::PostData")) {
1648 const char* id = in["id"].string();
1649 const char* key = in["key"].string();
1651 throw ListenerException("Required parameters missing for PostData recovery.");
1654 StorageService* storage = getStorageService(id);
1656 if (storage->readString("PostData",key,&postData) > 0) {
1657 storage->deleteString("PostData",key);
1661 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1662 "Storage-backed PostData with invalid StorageService ID (%s)", id
1665 // If the data's empty, we'll send nothing back.
1666 // If not, we don't need to round trip it, just send back the serialized DDF list.
1667 if (postData.empty()) {
1669 DDFJanitor jret(ret);
1676 else if (!strcmp(in.name(), "set::PostData")) {
1677 const char* id = in["id"].string();
1678 if (!id || !in["parameters"].islist())
1679 throw ListenerException("Required parameters missing for PostData creation.");
1682 StorageService* storage = getStorageService(id);
1684 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
1685 rsKey = SAMLArtifact::toHex(rsKey);
1686 ostringstream params;
1687 params << in["parameters"];
1688 storage->createString("PostData", rsKey.c_str(), params.str().c_str(), time(NULL) + 600);
1691 Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").error(
1692 "Storage-backed PostData with invalid StorageService ID (%s)", id
1696 // Repack for return to caller.
1697 DDF ret=DDF(NULL).string(rsKey.c_str());
1698 DDFJanitor jret(ret);
1704 pair<bool,DOMElement*> XMLConfig::load()
1706 // Load from source using base class.
1707 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
1709 // If we own it, wrap it.
1710 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
1712 XMLConfigImpl* impl = new XMLConfigImpl(raw.second,(m_impl==NULL),this,m_log);
1714 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
1715 impl->setDocument(docjanitor.release());
1720 return make_pair(false,(DOMElement*)NULL);